Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>package.json<|end_filename|> { "name": "express-opentracing", "version": "0.1.1", "description": "opentracing middleware for express-js", "main": "dist/index.js", "types": "index.d.ts", "publishConfig": { "registry": "https://registry.npmjs.org" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "./node_modules/.bin/babel src -d dist" }, "repository": { "type": "git", "url": "git+https://github.com/opentracing-contrib/javascript-express.git" }, "keywords": [ "tracing", "opentracing", "middleware" ], "author": "Clever", "license": "Apache-2.0", "bugs": { "url": "https://github.com/opentracing-contrib/javascript-express/issues" }, "homepage": "https://github.com/opentracing-contrib/javascript-express#readme", "dependencies": { "opentracing": "^0.14.0" }, "peerDependencies": { "opentracing": "^0.14.0" }, "devDependencies": { "babel-cli": "^6.18.0", "babel-preset-latest": "^6.16.0", "express": "4.x.x", "lightstep-tracer": "^0.20.3", "mocha": "^3.2.0", "request": "^2.79.0", "sinon": "^1.17.7", "underscore": "^1.8.3" } }
W3D3/javascript-express
<|start_filename|>src/components/LatestVideos/LatestVideos.module.css<|end_filename|> .latestVideos { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; justify-items: start; } @media (max-width: 700px) { .latestVideos { grid-template-columns: 1fr; } } .thumbnailContainer { overflow: visible !important; } .thumbnail { box-sizing: border-box; border-radius: 0.3rem; border: 3px solid var(--text); background-color: var(--text); box-shadow: 3px 3px 0 var(--text); } .thumbnail:hover { box-shadow: none; } <|start_filename|>src/components/PostMeta/PostMeta.module.css<|end_filename|> .postMeta > p { margin: 0rem; text-transform: lowercase; } .postMeta a { color: var(--text); } .postMeta a:hover { color: var(--primary); } <|start_filename|>src/components/Testimonials/Testimonials.module.css<|end_filename|> .testimonials { display: grid; row-gap: 4rem; } .testimonial { padding: 2rem; border-radius: 0.3rem; border: 3px solid var(--text); box-shadow: 3px 3px 0 var(--text); display: grid; color: var(--text); max-width: 32rem; } .testimonial:hover { color: var(--text); box-shadow: none; } .photoContainer { width: 4rem; margin: 0rem; border: 3px solid var(--text); background-color: var(--text); border-radius: 100%; } .photo { border-radius: 100%; } .name { margin: 0rem; font-family: "Montserrat", sans-serif; font-weight: 900; font-size: 1.5rem; letter-spacing: -0.075rem; color: var(--text); } .quote > p { margin: 2rem 0rem 0rem 0rem; } .header { display: grid; grid-auto-flow: column; justify-content: start; align-items: center; column-gap: 1rem; } <|start_filename|>src/test-utils/css.js<|end_filename|> // Modified identity-obj-proxy. // This works around the fact we use ES named exports for styles, e.g.: // import * as styles from './styles.scss'. // https://github.com/keyanzhang/identity-obj-proxy/issues/8 module.exports = new Proxy( {}, { get: function getter(target, key) { if (key === "__esModule") { // True instead of false to pretend we're an ES module. return true } return key }, }, ) <|start_filename|>src/styles/fancyLinks.css<|end_filename|> .fancyLinks a:not(.anchor, .gatsby-resp-image-link) { color: var(--text); box-shadow: inset 0 -2px var(--primary); } .fancyLinks a:not(.anchor, .gatsby-resp-image-link):hover { color: var(--text); box-shadow: inset 0 -25px 0 var(--primary); } <|start_filename|>src/components/Section/Section.module.css<|end_filename|> .title { font-size: clamp(3rem, 10vw, 4.5rem); font-weight: 900; letter-spacing: -0.2rem; margin: 0rem 0rem 1.75rem 0rem; } .link { display: inline-block; } .link:hover { text-shadow: 3px 3px var(--primary); } <|start_filename|>gatsby-config.js<|end_filename|> require("dotenv").config() const twitch = require("./src/transformers/twitch") const youtube = require("./src/transformers/youtube") const youtubeChannelId = "UCgbFhcZKt36Upo7oxWlLEig" const captivateRss = "https://feeds.captivate.fm/webdevweekly" const sentryUrl = "https://4d31bd282c17443b9ea608d763b71f79@o1037846.ingest.sentry.io/6005986" const config = { siteMetadata: { siteUrl: "https://bradgarropy.com", }, plugins: [ { resolve: "gatsby-plugin-react-helmet", }, { resolve: "gatsby-plugin-sitemap", }, { resolve: "gatsby-plugin-google-analytics", options: { trackingId: process.env.TRACKING_ID, head: true, anonymize: true, respectDNT: false, }, }, { resolve: "gatsby-plugin-web-font-loader", options: { google: { families: [ "Righteous:400", "Montserrat:400,500,600,700,800,900", "Open Sans:400,500,600,700,800,900", ], }, }, }, { resolve: "gatsby-source-filesystem", options: { name: "posts", path: "content/posts", }, }, { resolve: "gatsby-source-filesystem", options: { name: "pages", path: "content/pages", }, }, { resolve: "gatsby-source-filesystem", options: { name: "now", path: "content/now", }, }, { resolve: "gatsby-source-filesystem", options: { name: "testimonials", path: "content/testimonials", }, }, { resolve: "gatsby-source-filesystem", options: { name: "images", path: "static", }, }, { resolve: "gatsby-source-youtube-v3", options: { channelId: [youtubeChannelId], apiKey: process.env.YOUTUBE_API_KEY, }, }, { resolve: "gatsby-source-anchor", options: { rss: captivateRss, }, }, { resolve: "gatsby-source-github-api", options: { token: process.env.GITHUB_TOKEN, graphQLQuery: ` query { user(login: "bradgarropy") { pinnedItems(types: REPOSITORY, first: 6) { nodes { ... on Repository { url name description stargazerCount repositoryTopics(first: 20) { nodes { topic { name } } } } } } sponsorshipsAsMaintainer(first: 10) { nodes { sponsorEntity { ... on User { login url avatarUrl } } tier { name description isOneTime } } } } } `, }, }, { resolve: "gatsby-transformer-remark", options: { plugins: [ { resolve: "gatsby-remark-images", options: { maxWidth: 700, }, }, { resolve: "gatsby-remark-autolink-headers", options: { maintainCase: false, removeAccents: true, }, }, { resolve: "gatsby-remark-vscode", options: { theme: "Shades of Purple", extensions: ["shades-of-purple"], }, }, { resolve: "gatsby-remark-embedder", options: { customTransformers: [twitch, youtube], }, }, { resolve: "gatsby-remark-external-links", options: { rel: "noopener noreferrer", }, }, ], }, }, { resolve: "gatsby-plugin-twitter", }, { resolve: "gatsby-plugin-image", }, { resolve: "gatsby-plugin-sharp", }, { resolve: "gatsby-transformer-sharp", }, { resolve: "gatsby-plugin-catch-links", }, { resolve: "gatsby-plugin-react-svg", options: { rule: { include: /svg/, }, }, }, { resolve: "gatsby-plugin-layout", options: { component: require.resolve( "./src/components/Layout/Layout.tsx", ), }, }, { resolve: "@sentry/gatsby", options: { dsn: sentryUrl, sampleRate: 0.7, }, }, ], } module.exports = config
bradgarropy/bradgarropy.com
<|start_filename|>examples/echo/EchoClient.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <vector> #include "PollerBase.h" #include "PollEvent.h" class EchoClient : public IPollEvent { public: explicit EchoClient(PollerBase* poller); ~EchoClient(); void Start(const char* host, const char* port); private: void OnReadable(); void OnWritable(); void OnTimeout(); void Cleanup(); SOCKET Connect(const char* host, const char* port); void SendData(); private: std::string host_; std::string port_; SOCKET fd_; PollerBase* poller_; int sent_count_; std::vector<char> buf_; }; <|start_filename|>examples/pingpong/Server.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "Server.h" #include "Common/Logging.h" #include "Common/Error.h" #include "Common/StringUtil.h" #include "SocketOpts.h" #include "Session.h" #include "WsaExt.h" using namespace std::placeholders; Server::Server(IOServiceBase* service) : service_(service), ctx_(NULL), acceptor_(INVALID_SOCKET), counter_(2001) { } Server::~Server() { Cleanup(); } void Server::Cleanup() { if (acceptor_ != INVALID_SOCKET) { fprintf(stderr, "%d closed\n", (int)acceptor_); closesocket(acceptor_); acceptor_ = INVALID_SOCKET; } if (ctx_ != NULL) { delete ctx_->buf.buf; ctx_->buf.buf = NULL; ctx_->flags |= FLAG_LAZY_DELETE; service_->FreeOverlapCtx(ctx_); ctx_ = NULL; } } void Server::CloseSession(int sid) { auto iter = sessions_.find(sid); if (iter != sessions_.end()) { Session* session = iter->second; delete session; sessions_.erase(iter); } } void Server::Start(const char* host, const char* port) { SOCKET fd = CreateTCPAcceptor(host, port); CHECK(fd != INVALID_SOCKET) << LAST_ERROR_MSG; OverlapContext* ctx = service_->AllocOverlapCtx(fd, FLAG_ASSOCIATE); CHECK(ctx != NULL); acceptor_ = fd; ctx_ = ctx; StartAccept(); } void Server::StartAccept() { if (ctx_->buf.buf == NULL) { AcceptInfo* pinfo = new AcceptInfo(); ctx_->buf.buf = (char*)pinfo; ctx_->buf.len = sizeof(AcceptInfo); } else { memset(ctx_->buf.buf, 0, ctx_->buf.len); } ctx_->cb = std::bind(&Server::OnAccept, this, ctx_); service_->AsyncAccept(ctx_); } void Server::OnAccept(OverlapContext* ctx) { SOCKET newfd = (SOCKET)ctx->udata; ctx->udata = 0; if (ctx->GetStatusCode() != 0) { LOG(ERROR) << "accept failed: " << ctx->GetStatusCode(); closesocket(newfd); return; } OverlapContext* newctx = service_->AllocOverlapCtx(newfd, FLAG_ASSOCIATE); if (newctx == NULL) { closesocket(newfd); return; } int sid = counter_++; Session* session = new Session(sid, this, newctx); sessions_[sid] = session; session->StartRead(); AcceptInfo* info = (AcceptInfo*)ctx->buf.buf; struct sockaddr* remote_addr = NULL; struct sockaddr* local_addr = NULL; int local_len = 0; int remote_len = 0; WsaExt::GetAcceptExSockaddrs(info, 0, ACCEPTEX_ADDR_LEN, ACCEPTEX_ADDR_LEN, &local_addr, &local_len, &remote_addr, &remote_len); char buffer[40] = {}; inet_ntop(remote_addr->sa_family, remote_addr->sa_data, buffer, sizeof(buffer)); LOG(INFO) << StringPrintf("%d accepted from %s", newfd, buffer); StartAccept(); } <|start_filename|>src/AsyncEventPoller.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "AsyncEventPoller.h" #include <algorithm> #include "Common/Error.h" #include "Common/Logging.h" #include "Mask.h" #include <vector> AsyncEventPoller::AsyncEventPoller() : has_retired_(false) { events_.reserve(WSA_MAXIMUM_WAIT_EVENTS); fds_.reserve(WSA_MAXIMUM_WAIT_EVENTS); } AsyncEventPoller::~AsyncEventPoller() { CleanUp(); } void AsyncEventPoller::CleanUp() { for (size_t i = 0; i < fds_.size(); i++) { FdEntry* entry = &fds_[i]; WSAEventSelect(entry->fd, NULL, 0); WSACloseEvent(entry->hEvent); closesocket(entry->fd); entry->fd = INVALID_SOCKET; entry->hEvent = NULL; } fds_.clear(); events_.clear(); } int AsyncEventPoller::AddFd(SOCKET fd, IPollEvent* event) { if (fds_.size() >= WSA_MAXIMUM_WAIT_EVENTS) { return -1; } WSAEVENT hEvent = WSACreateEvent(); if (hEvent == WSA_INVALID_EVENT) { LOG(ERROR) << "WSACreateEvent: " << LAST_ERROR_MSG; return -1; } FdEntry entry = {}; entry.fd = fd; entry.hEvent = hEvent; entry.sink = event; fds_.push_back(entry); return 0; } void AsyncEventPoller::RemoveFd(SOCKET fd) { FdEntry* entry = FindEntry(fd); if (entry != NULL) { //clear the event record associated with socket WSACloseEvent(entry->hEvent); entry->hEvent = WSA_INVALID_EVENT; entry->fd = INVALID_SOCKET; // mark retired } has_retired_ = true; WSAEventSelect(fd, NULL, 0); } void AsyncEventPoller::SetPollIn(SOCKET fd) { FdEntry* entry = FindEntry(fd); if (entry != NULL) { long lEvent = FD_READ | FD_ACCEPT | FD_CLOSE; entry->lEvents |= lEvent; entry->mask |= MASK_READABLE; int r = WSAEventSelect(fd, entry->hEvent, entry->lEvents); if (r == SOCKET_ERROR) { LOG(ERROR) << "SetPollIn: WSAEventSelect, " << LAST_ERROR_MSG; return; } } } void AsyncEventPoller::ResetPollIn(SOCKET fd) { FdEntry* entry = FindEntry(fd); if (entry != NULL) { long lEvent = FD_READ | FD_ACCEPT | FD_CLOSE; entry->lEvents &= ~lEvent; entry->mask &= ~MASK_READABLE; int r = WSAEventSelect(fd, entry->hEvent, entry->lEvents); if (r == SOCKET_ERROR) { LOG(ERROR) << "ResetPollIn: WSAEventSelect, " << LAST_ERROR_MSG; return; } } } void AsyncEventPoller::SetPollOut(SOCKET fd) { FdEntry* entry = FindEntry(fd); if (entry != NULL) { long lEvent = FD_WRITE | FD_CONNECT | FD_CLOSE; entry->lEvents |= lEvent; entry->mask |= MASK_WRITABLE; int r = WSAEventSelect(fd, entry->hEvent, entry->lEvents); if (r == SOCKET_ERROR) { LOG(ERROR) << "SetPollOut: WSAEventSelect, " << LAST_ERROR_MSG; return; } } } void AsyncEventPoller::ResetPollOut(SOCKET fd) { FdEntry* entry = FindEntry(fd); if (entry != NULL) { long lEvent = FD_WRITE | FD_CONNECT | FD_CLOSE; entry->lEvents &= ~lEvent; entry->mask &= ~MASK_WRITABLE; int r = WSAEventSelect(fd, entry->hEvent, entry->lEvents); if (r == SOCKET_ERROR) { LOG(ERROR) << "ResetPollOut: WSAEventSelect, " << LAST_ERROR_MSG; return; } } } int AsyncEventPoller::Poll(int timeout) { int nready = 0; events_.clear(); for (size_t i = 0; i < fds_.size(); i++) { FdEntry* entry = &fds_[i]; if (entry->fd != INVALID_SOCKET && entry->hEvent != WSA_INVALID_EVENT) { events_.push_back(entry->hEvent); } } if (!events_.empty()) { nready = WSAWaitForMultipleEvents((DWORD)events_.size(), &events_[0], FALSE, timeout, FALSE); if (nready == WSA_WAIT_FAILED) { LOG(ERROR) << "Poll: WSAWaitForMultipleEvents, " << LAST_ERROR_MSG; nready = -1; } else if (nready == WSA_WAIT_TIMEOUT) { nready = -1; } } else { // nothing to do, sleep a while if (timeout > 0) { Sleep(timeout / 2); } } UpdateTimer(); if (nready >= 0 && !events_.empty()) { int index = nready - WSA_WAIT_EVENT_0; if (index >= WSA_MAXIMUM_WAIT_EVENTS) { LOG(ERROR) << "Poll: wait events index out of range: " << index; return 0; } WSAEVENT hEvent = events_[index]; FdEntry* entry = FindEntryByEvent(hEvent); if (entry == NULL) { LOG(ERROR) << "Poll: entry not found"; return 0; } WSANETWORKEVENTS events = {}; // This will reset the event object and adjust the status of // active FD events on the socket in an atomic fashion. int r = WSAEnumNetworkEvents(entry->fd, hEvent, &events); if (r == SOCKET_ERROR) { LOG(ERROR) << "Poll: WSAEnumNetworkEvents, " << LAST_ERROR_MSG; return 0; } HandleEvents(entry, &events); return 1; } RemoveRetired(); return 0; } void AsyncEventPoller::HandleEvents(FdEntry* entry, WSANETWORKEVENTS* events) { const int* errlist = events->iErrorCode; long event = events->lNetworkEvents; if (event & FD_READ) { int err = errlist[FD_READ_BIT]; last_err_ = err; if (entry->mask | MASK_READABLE) { entry->sink->OnReadable(); } } if (event & FD_CLOSE) { int err = errlist[FD_CLOSE_BIT]; last_err_ = err; if (entry->mask | MASK_READABLE) { entry->sink->OnReadable(); } } if (event & FD_ACCEPT) { int err = errlist[FD_ACCEPT_BIT]; last_err_ = err; if (entry->mask | MASK_READABLE) { entry->sink->OnReadable(); } } if (event & FD_WRITE) { int err = errlist[FD_WRITE_BIT]; last_err_ = err; if (entry->mask | MASK_READABLE) { entry->sink->OnWritable(); } } if (event & FD_CONNECT) { int err = errlist[FD_CONNECT_BIT]; last_err_ = err; if (entry->mask | MASK_READABLE) { entry->sink->OnWritable(); } } } AsyncEventPoller::FdEntry* AsyncEventPoller::FindEntry(SOCKET fd) { for (size_t i = 0; i < fds_.size(); i++) { if (fds_[i].fd == fd) { return &fds_[i]; } } return NULL; } AsyncEventPoller::FdEntry* AsyncEventPoller::FindEntryByEvent(WSAEVENT hEvent) { for (size_t i = 0; i < fds_.size(); i++) { if (fds_[i].hEvent == hEvent) { return &fds_[i]; } } return NULL; } void AsyncEventPoller::RemoveRetired() { if (has_retired_) { auto iter = std::remove_if(fds_.begin(), fds_.end(), [](const FdEntry& entry) { return entry.fd == INVALID_SOCKET; }); fds_.erase(iter, fds_.end()); has_retired_ = false; } } <|start_filename|>examples/echo/EchoConn.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <vector> #include "PollerBase.h" #include "PollEvent.h" class EchoServer; class EchoConn : public IPollEvent { public: explicit EchoConn(EchoServer* server, SOCKET fd); ~EchoConn(); void OnReadable(); void OnWritable(); void OnTimeout() {} void StartRead(); void Close(); private: EchoServer* server_; SOCKET fd_; std::vector<char> buf_; int recv_count_; }; <|start_filename|>examples/pingpong/main.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include <signal.h> #include <string> #include <iostream> #include <memory> #include "Common/WinsockInit.h" #include "IOServiceBase.h" #include "Server.h" #include "Client.h" using namespace std; IOServiceBase* service = nullptr; bool g_stop = false; void handleSignal(int sig) { g_stop = true; fprintf(stderr, "stop io service\n"); } int main(int argc, char* argv[]) { signal(SIGINT, handleSignal); if (argc != 5) { fprintf(stderr, "Usage: %s <server/client> <mode> <host> <port> <i/o model>\n", argv[0]); return 1; } string type = argv[1]; const char* host = argv[2]; const char* port = argv[3]; IOServiceType mode = (IOServiceType)atoi(argv[4]); WinsockAutoInit init; IOServiceBase* service = CreateIOService(mode); CHECK(service != nullptr); std::shared_ptr<Server> server = NULL; std::shared_ptr<Client> client = NULL; if (type == "server") { server.reset(new Server(service)); server->Start(host, port); fprintf(stdout, "server started at %s:%s\n", host, port); } else if (type == "client") { client.reset(new Client(service)); client->Start(host, port); fprintf(stdout, "client started at %s:%s\n", host, port); } else { fprintf(stderr, "invalid instance type: [%s]\n", type.c_str()); } while(!g_stop) { service->Run(50); } delete service; return 0; } <|start_filename|>examples/echo/EchoConn.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "EchoConn.h" #include "SocketOpts.h" #include "EchoServer.h" enum { MAX_CONN_RECVBUF = 1024, MAX_RECV_COUNT = 5, }; EchoConn::EchoConn(EchoServer* server, SOCKET fd) : server_(server), fd_(fd), recv_count_(0) { buf_.resize(MAX_CONN_RECVBUF); } EchoConn::~EchoConn() { } void EchoConn::Close() { if (fd_ != INVALID_SOCKET) { SOCKET fd = fd_; fd_ = INVALID_SOCKET; server_->CloseSession(fd); // delete this } } void EchoConn::StartRead() { int nbytes = ReadSome(fd_, &buf_[0], (int)buf_.size()); if (nbytes < 0) { Close(); // EOF or error; return; } else if (nbytes > 0) { recv_count_++; fprintf(stdout, "%d recv %d bytes, %d\n", (int)fd_, nbytes, recv_count_); if (recv_count_ < MAX_RECV_COUNT) { // echo back nbytes = WriteSome(fd_, &buf_[0], nbytes); if (nbytes < 0) { Close(); return; } fprintf(stdout, "%d send %d bytes, %d\n", (int)fd_, nbytes, recv_count_); } else { Close(); } } } void EchoConn::OnReadable() { StartRead(); } void EchoConn::OnWritable() { // writable } <|start_filename|>examples/pingpong/Session.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include "IOServiceBase.h" class Server; class Session { public: Session(int id, Server* server, OverlapContext* ctx); ~Session(); void StartRead(); void Close(); int Write(const void* data, int len); private: void OnRead(OverlapContext* ctx); void OnWritten(OverlapContext* ctx); private: IOServiceBase* service_; Server* server_; int id_; SOCKET fd_; OverlapContext* recv_ctx_; std::vector<char> recv_buf_; int recv_count_; }; <|start_filename|>src/PollEvent.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once struct ITimerEvent { virtual ~ITimerEvent() {} virtual void OnTimeout() = 0; }; struct IPollEvent : ITimerEvent { virtual ~IPollEvent(){} virtual void OnReadable() = 0; virtual void OnWritable() = 0; }; <|start_filename|>tests/echo/echo.go<|end_filename|> // Copyright (C) 2012-present All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. package main import ( "flag" "log" "net" "sync" "time" ) func main() { var mode, addr string var connCount, echoCount int flag.StringVar(&mode, "m", "server", "run server or client") flag.StringVar(&addr, "h", "127.0.0.1:8081", "host address") flag.IntVar(&connCount, "c", 32, "how many connections to make") flag.IntVar(&echoCount, "e", 5, "server response echo back count") flag.Parse() switch mode { case "client": startClient(addr, connCount, echoCount) case "server": startServer(addr, echoCount) default: log.Panicf("invalid mode: %s", mode) } } // 开始跑echo client func startClient(addr string, connCount, echoCount int) { log.Printf("starting %d clients to connect %s\n", connCount, addr) var wg sync.WaitGroup for i := 0; i < connCount; i++ { conn, err := net.Dial("tcp", addr) if err != nil { log.Fatalf("Dial: %v", err) } wg.Add(1) go handleClientConn(conn, echoCount, &wg) time.Sleep(10 * time.Millisecond) } wg.Wait() } //连续发送/接收`echoCount`条消息就close func handleClientConn(conn net.Conn, echoCount int, wg *sync.WaitGroup) { defer wg.Done() defer conn.Close() var msg = []byte("a quick brown fox jumps over the lazy dog") var buf = make([]byte, 1024) for i := 0; i < echoCount; i++ { nbytes, err := conn.Write(msg) if err != nil { log.Printf("%v Read: %v\n", conn.LocalAddr(), err) break } if nbytes == 0 { log.Printf("%v Recv 0 bytes, EOF\n", conn.LocalAddr()) break } log.Printf("%v Write %d bytes\n", conn.LocalAddr(), nbytes) nbytes, err = conn.Read(buf) if err != nil { log.Printf("Write: %v\n", err) break } log.Printf("%v Read %d bytes\n", conn.LocalAddr(), nbytes) time.Sleep(time.Second) } } // 开始跑echo server func startServer(addr string, echoCount int) { ln, err := net.Listen("tcp", addr) if err != nil { log.Fatalf("Listen: %v", err) } log.Printf("listen at %s\n", addr) for { conn, err := ln.Accept() if err != nil { log.Fatalf("Accept: %v", err) } log.Printf("accepted %v\n", conn.RemoteAddr()) go handleServerConn(conn, echoCount) } } //连续接收/发送`echoCount`条消息就close func handleServerConn(conn net.Conn, echoCount int) { defer conn.Close() defer log.Printf("connection %v closed\n", conn.RemoteAddr()) var buf = make([]byte, 1024) for i := 0; i < echoCount; i++ { conn.SetDeadline(time.Now().Add(300 * time.Second)) nbytes, err := conn.Read(buf) if err != nil { log.Printf("Read: %v\n", err) break } if nbytes == 0 { log.Printf("Recv 0 bytes, EOF\n") break } log.Printf("Recv %d bytes\n", nbytes) nbytes, err = conn.Write(buf[:nbytes]) if err != nil { log.Printf("Write: %v\n", err) break } log.Printf("Send %d bytes\n", nbytes) } } <|start_filename|>src/CompletionPortService.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "CompletionPortService.h" #include "Common/Logging.h" #include "Common/Error.h" #include "Common/StringUtil.h" #include "SocketOpts.h" #include "WsaExt.h" CompletionPortService::CompletionPortService() { HANDLE handle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); CHECK(handle != NULL) << LAST_ERROR_MSG; completion_port_ = handle; } CompletionPortService::~CompletionPortService() { if (completion_port_ != NULL) { CloseHandle(completion_port_); completion_port_ = NULL; } } OverlapContext* CompletionPortService::AllocOverlapCtx(SOCKET fd, int flags) { OverlapContext* ctx = new OverlapContext(); ctx->fd = fd; if (flags & FLAG_ASSOCIATE) { HANDLE handle = CreateIoCompletionPort((HANDLE)fd, completion_port_, (ULONG_PTR)fd, 0); if (handle != completion_port_) { LOG(ERROR) << "CreateIoCompletionPort: " << LAST_ERROR_MSG; FreeOverlapCtx(ctx); return NULL; } } return ctx; } void CompletionPortService::FreeOverlapCtx(OverlapContext* ctx) { if (ctx->flags & FLAG_CANCEL_IO) { CancelIoEx((HANDLE)ctx->fd, NULL); } ctx->fd = INVALID_SOCKET; if (!(ctx->flags & FLAG_LAZY_DELETE)) { delete ctx; } } int CompletionPortService::AsyncConnect(OverlapContext* ctx, const addrinfo* pinfo) { // ConnectEx need previously bound socket. int r = BindAnyAddr(ctx->fd, pinfo->ai_family); if (r != 0) { return r; } ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int fOK = WsaExt::ConnectEx(ctx->fd, (const struct sockaddr*)pinfo->ai_addr, (int)pinfo->ai_addrlen, nullptr, 0, nullptr, (WSAOVERLAPPED*)ctx); if (!fOK) { if (GetLastError() != WSA_IO_PENDING) { LOG(ERROR) << "ConnectEx: " << LAST_ERROR_MSG; return -1; } } else { UpdateConnectCtx(ctx->fd); } return 0; // succeed } int CompletionPortService::AsyncAccept(OverlapContext* ctx) { SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == INVALID_SOCKET) { LOG(ERROR) << StringPrintf("socket(): %s\n", LAST_ERROR_MSG); return -1; } ctx->udata = fd; ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int fOK = WsaExt::AcceptEx(ctx->fd, fd, ctx->buf.buf, 0, ACCEPTEX_ADDR_LEN, ACCEPTEX_ADDR_LEN, NULL, (WSAOVERLAPPED*)ctx); if (!fOK) { int r = WSAGetLastError(); if (r != WSA_IO_PENDING) { closesocket(fd); LOG(ERROR) << StringPrintf("AcceptEx(): %s\n", LAST_ERROR_MSG); return r; } } return 0; } int CompletionPortService::AsyncRead(OverlapContext* ctx) { DWORD dwFlags = 0; ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int r = WSARecv(ctx->fd, &ctx->buf, 1, NULL, &dwFlags, (WSAOVERLAPPED*)ctx, NULL); if (r == SOCKET_ERROR) { int r = WSAGetLastError(); if (r != WSA_IO_PENDING) { LOG(ERROR) << StringPrintf("WSARecv(): %s\n", LAST_ERROR_MSG); return r; } } return 0; } int CompletionPortService::AsyncWrite(OverlapContext* ctx) { ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int r = WSASend(ctx->fd, &ctx->buf, 1, NULL, 0, (WSAOVERLAPPED*)ctx, NULL); if (r == SOCKET_ERROR) { int r = WSAGetLastError(); if (r != WSA_IO_PENDING) { LOG(ERROR) << StringPrintf("WSASend(): %s\n", LAST_ERROR_MSG); return r; } } return 0; } int CompletionPortService::Run(int timeout) { DWORD dwBytes = 0; ULONG_PTR completionKey = 0; WSAOVERLAPPED* pOverlap = NULL; UpdateTimer(); int fOK = GetQueuedCompletionStatus(completion_port_, &dwBytes, (ULONG_PTR*)&completionKey, &pOverlap, timeout); if (!fOK) { DWORD dwErr = GetLastError(); if (pOverlap != NULL) { LOG(ERROR) << "GetQueuedCompletionStatus: " << LAST_ERROR_MSG; return -1; } else { if (dwErr != WAIT_TIMEOUT) { LOG(ERROR) << "GetQueuedCompletionStatus: " << LAST_ERROR_MSG; return -1; } } } OverlapContext* pContext = (OverlapContext*)pOverlap; if (pContext != NULL) { if (pContext->cb) { pContext->cb(); // dispatch event } if (pContext->flags & FLAG_LAZY_DELETE) { delete pContext; } } return 0; } <|start_filename|>src/Common/StringUtil.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <stdarg.h> #include <string> // Like printf, return a C++ string std::string StringPrintf(const char* format, ...); // Store result into a supplied string and return it const std::string& SStringPrintf(std::string* dst, const char* format, ...); // Lower-level routine that takes a va_list and appends to a specified // string. All other routines are just convenience wrappers around it. void StringAppendV(std::string* dst, const char* format, va_list ap); <|start_filename|>src/PollerBase.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include "TimerSched.h" #include <WinSock2.h> #include <vector> #include <map> enum PollerType { PollerSelect = 1, PollerAsyncSelect = 2, PollerAsyncEvent = 3, }; class PollerBase : public TimerSched { public: PollerBase(); virtual ~PollerBase(); virtual int AddFd(SOCKET fd, IPollEvent* event) = 0; virtual void RemoveFd(SOCKET fd) = 0; virtual void SetPollIn(SOCKET fd) = 0; virtual void ResetPollIn(SOCKET fd) = 0; virtual void SetPollOut(SOCKET fd) = 0; virtual void ResetPollOut(SOCKET fd) = 0; virtual int Poll(int timeout) = 0; int LastError() { return last_err_; } protected: int last_err_; }; PollerBase* CreatePoller(PollerType type); <|start_filename|>src/IOServiceBase.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <stdint.h> #include "TimerSched.h" #include "OverlapFd.h" enum IOServiceType { IOOverlapped = 1, IOAlertable = 2, IOCompletionPort = 3, }; // Async I/O service for TCP sockets class IOServiceBase : public TimerSched { public: IOServiceBase(); virtual ~IOServiceBase(); virtual int AsyncConnect(OverlapContext* ctx, const addrinfo* pinfo) = 0; virtual int AsyncAccept(OverlapContext* ctx) = 0; virtual int AsyncRead(OverlapContext* ctx) = 0; virtual int AsyncWrite(OverlapContext* ctx) = 0; virtual int Run(int timeout) = 0; virtual OverlapContext* AllocOverlapCtx(SOCKET fd, int flags) = 0; virtual void FreeOverlapCtx(OverlapContext* ctx) = 0; }; IOServiceBase* CreateIOService(IOServiceType type); <|start_filename|>src/Mask.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once enum { MASK_READABLE = 1, MASK_WRITABLE = 2, }; <|start_filename|>src/Common/Error.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "Error.h" #define THREAD_LOCAL __declspec(thread) const char* GetErrorMessage(DWORD dwErrorCode) { static THREAD_LOCAL char description[MAX_PATH]; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErrorCode, 0, description, MAX_PATH-1, NULL); return description; } <|start_filename|>src/IOServiceBase.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "IOServiceBase.h" #include "Common/Logging.h" #include "Common/Error.h" #include "OverlappedIOService.h" #include "CompletionPortService.h" IOServiceBase::IOServiceBase() { } IOServiceBase::~IOServiceBase() { } IOServiceBase* CreateIOService(IOServiceType type) { switch(type) { case IOOverlapped: return new OverlappedIOService; case IOCompletionPort: return new CompletionPortService; default: LOG(ERROR) << "unsupported service type"; return nullptr; } } <|start_filename|>examples/pingpong/Client.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <vector> #include "PollEvent.h" #include "IOServiceBase.h" class Client : public ITimerEvent { public: explicit Client(IOServiceBase* service); ~Client(); int Start(const char* host, const char* port); private: void StartRead(); void Cleanup(); int Connect(const char* host, const char* port); int Write(const void* data, int len); void OnConnect(OverlapContext* ctx); void OnRead(OverlapContext* ctx); void OnWritten(OverlapContext* ctx); void OnTimeout(); private: IOServiceBase* service_; OverlapContext* recv_ctx_; SOCKET fd_; int sent_count_; std::vector<char> recv_buf_; }; <|start_filename|>src/Common/WinsockInit.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <WinSock2.h> #include "Logging.h" #include "WsaExt.h" // Auto initialize winsock struct WinsockAutoInit { WinsockAutoInit() { WSADATA data; int r = WSAStartup(MAKEWORD(2, 2), &data); CHECK(r == 0); WsaExt init; // initialize winsock extension } ~WinsockAutoInit() { WSACleanup(); } }; <|start_filename|>src/Common/Logging.cpp<|end_filename|> // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Logging.h" #include <stdio.h> #include <stdarg.h> #include <algorithm> #include "Mutex.h" #include "StringUtil.h" static std::wstring Utf8ToWide(const std::string& strUtf8) { std::wstring strWide; int count = MultiByteToWideChar(CP_UTF8, 0, strUtf8.data(), (int)strUtf8.length(), NULL, 0); if (count > 0) { strWide.resize(count); MultiByteToWideChar(CP_UTF8, 0, strUtf8.data(), (int)strUtf8.length(), const_cast<wchar_t*>(strWide.data()), (int)strWide.length()); } return strWide; } const size_t MAX_OUTPUT_LEN = 4032; static void OutputStringToDebugger(const std::string& message) { const std::wstring& text = Utf8ToWide(message); if (text.size() < MAX_OUTPUT_LEN) //common case { OutputDebugStringW(text.c_str()); return; } size_t outputed = 0; while (outputed < text.size()) { // maximum length accepted // see http://www.unixwiz.net/techtips/outputdebugstring.html wchar_t buf[MAX_OUTPUT_LEN] = {}; size_t left = text.size() - outputed; wcsncpy_s(buf, text.c_str() + outputed, std::min(left, MAX_OUTPUT_LEN-1)); OutputDebugStringW(buf); if (left >= MAX_OUTPUT_LEN-1) { outputed += MAX_OUTPUT_LEN-1; } else { outputed += left; } } } namespace detail { void DefaultLogHandler(LogLevel level, const char* filename, int line, const std::string& message) { static const char* level_names[] = { "DEBUG","INFO", "WARNING", "ERROR", "FATAL" }; const char* sep = strrchr(filename, '\\'); if (sep) { filename = sep + 1; } auto msg = StringPrintf("[%s %s:%d] %s\n", level_names[level], filename, line, message.c_str()); #ifdef _DEBUG fprintf(stderr, "%s\n", msg.c_str()); #else OutputStringToDebugger(msg); #endif //_DEBUG } void NullLogHandler(LogLevel /* level */, const char* /* filename */, int /* line */, const std::string& /* message */) { // Nothing. } typedef void LogHandler(LogLevel level, const char* filename, int line, const std::string& message); static LogHandler* log_handler_ = &DefaultLogHandler; static int log_silencer_count_ = 0; static Mutex log_silencer_count_mutex_; void LogMessage::Finish() { bool suppress = false; if (level_ != LOGLEVEL_FATAL) { log_silencer_count_mutex_.Lock(); suppress = log_silencer_count_ > 0; log_silencer_count_mutex_.UnLock(); } if (!suppress) { log_handler_(level_, filename_, line_, strm_.str()); } if (level_ == LOGLEVEL_FATAL) { abort(); } } void LogFinisher::operator=(LogMessage& other) { other.Finish(); } LogHandler* GetDefaultLogHandler() { return log_handler_; } } // namespace detail <|start_filename|>src/SocketOpts.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "SocketOpts.h" #include <assert.h> #include <WS2tcpip.h> #include <MSWSock.h> #include "Common/Error.h" #include "Common/Logging.h" #include "Common/StringUtil.h" // set socket to non-blocking mode int SetNonblock(SOCKET fd, bool nonblock) { unsigned long val = nonblock ? 1 : 0; int r = ioctlsocket(fd, FIONBIO, &val); if (r == SOCKET_ERROR) { LOG(ERROR) << StringPrintf("ioctlsocket(): %s\n", LAST_ERROR_MSG); } return r; } int BindAnyAddr(SOCKET fd, int family) { sockaddr* paddr = nullptr; int addrlen = 0; sockaddr_in addr4 = {}; sockaddr_in6 addr6 = {}; switch (family) { case AF_INET: addr4.sin_family = family; addr4.sin_addr.S_un.S_addr = INADDR_ANY; paddr = (sockaddr*)&addr4; addrlen = sizeof(addr4); break; case AF_INET6: addr6.sin6_family = family; addr6.sin6_addr = in6addr_any; paddr = (sockaddr*)&addr6; addrlen = sizeof(addr6); break; default: CHECK(false) << "invalid net family"; return -1; } int r = bind(fd, paddr, addrlen); if (r == SOCKET_ERROR) { return r; } return 0; } int UpdateConnectCtx(SOCKET fd) { int r = setsockopt(fd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0); if (r == SOCKET_ERROR) { LOG(ERROR) << "UpdateConnectCtx: " << LAST_ERROR_MSG; } return r; } int ReadSome(SOCKET fd, void* buf, int size) { int nbytes = 0; while (true) { int r = recv(fd, (char*)buf + nbytes, size - nbytes, 0); if (r > 0) { nbytes += r; continue; } else if (r == 0) // EOF { return -1; } else if (r == SOCKET_ERROR) { int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK) { LOG(ERROR) << r << LAST_ERROR_MSG; return -1; } break; } break; } return nbytes; } int WriteSome(SOCKET fd, const void* buf, int size) { int nbytes = 0; while (nbytes < size) { int r = send(fd, (char*)buf + nbytes, size - nbytes, 0); if (r >= 0) { nbytes += r; continue; } else if (r == SOCKET_ERROR) { r = WSAGetLastError(); if (r != WSAEWOULDBLOCK) { LOG(ERROR) << r << LAST_ERROR_MSG; return -1; } break; } break; } return nbytes; } bool IsSelfConnection(SOCKET fd) { sockaddr_storage local_addr = {}; int local_len = sizeof(local_addr); int r = getsockname(fd, (sockaddr*)&local_addr, &local_len); if (r == SOCKET_ERROR) { LOG(ERROR) << StringPrintf("getsockname(): %s", LAST_ERROR_MSG); return false; } sockaddr_storage peer_addr = {}; int peer_len = sizeof(peer_addr); r = getpeername(fd, (sockaddr*)&peer_addr, &peer_len); if (r == SOCKET_ERROR) { LOG(ERROR) << StringPrintf("getpeername(): %s", LAST_ERROR_MSG); return false; } switch (local_addr.ss_family) { case AF_INET: { const sockaddr_in* locaddr = (const sockaddr_in*)&local_addr; const sockaddr_in* remoteaddr = (const sockaddr_in*)&peer_addr; if (locaddr->sin_port == remoteaddr->sin_port) { return locaddr->sin_addr.S_un.S_addr == remoteaddr->sin_addr.S_un.S_addr; } } break; case AF_INET6: { const sockaddr_in6* locaddr = (const sockaddr_in6*)&local_addr; const sockaddr_in6* remoteaddr = (const sockaddr_in6*)&peer_addr; if (locaddr->sin6_port == remoteaddr->sin6_port) { return memcmp(&locaddr->sin6_addr, &remoteaddr->sin6_addr, sizeof(in6_addr)) == 0; } } break; } return false; } SOCKET CreateTCPAcceptor(const char* host, const char* port, bool nonblock, bool ipv6) { struct addrinfo* aiList = NULL; struct addrinfo* pinfo = NULL; struct addrinfo hints = {}; hints.ai_family = ipv6 ? AF_INET6 : AF_INET; hints.ai_socktype = SOCK_STREAM; // TCP hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; int err = getaddrinfo(host, port, &hints, &aiList); if (err != 0) { LOG(ERROR) << StringPrintf("getaddrinfo(): %s:%s, %s.\n", host, port, gai_strerror(err)); return INVALID_SOCKET; } SOCKET fd = INVALID_SOCKET; for (pinfo = aiList; pinfo != NULL; pinfo = pinfo->ai_next) { fd = socket(pinfo->ai_family, pinfo->ai_socktype, pinfo->ai_protocol); if (fd == INVALID_SOCKET) { LOG(ERROR) << StringPrintf("socket(): %s\n", LAST_ERROR_MSG); continue; } int err = bind(fd, pinfo->ai_addr, (int)pinfo->ai_addrlen); if (err == SOCKET_ERROR) { LOG(ERROR) << StringPrintf("%s bind(): %s\n", pinfo->ai_addr, LAST_ERROR_MSG); closesocket(fd); fd = INVALID_SOCKET; continue; } // set to non-blocking mode if (nonblock) { if (SetNonblock(fd, true) == SOCKET_ERROR) { closesocket(fd); fd = INVALID_SOCKET; continue; } } err = listen(fd, SOMAXCONN); if (err == SOCKET_ERROR) { LOG(ERROR) << StringPrintf("listen(): %s\n", LAST_ERROR_MSG); closesocket(fd); fd = INVALID_SOCKET; continue; } break; // done } freeaddrinfo(aiList); return fd; } SOCKET CreateTcpConnector(const char* host, const char* port, bool nonblock, bool ipv6) { struct addrinfo* aiList = NULL; struct addrinfo* pinfo = NULL; struct addrinfo hints = {}; hints.ai_family = ipv6 ? AF_INET6 : AF_INET; hints.ai_socktype = SOCK_STREAM; // TCP hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; int err = getaddrinfo(host, port, &hints, &aiList); if (err != 0) { LOG(ERROR) << StringPrintf("getaddrinfo(): %s:%s, %s.\n", host, port, gai_strerror(err)); return INVALID_SOCKET; } SOCKET fd = INVALID_SOCKET; for (pinfo = aiList; pinfo != NULL; pinfo = pinfo->ai_next) { fd = socket(pinfo->ai_family, pinfo->ai_socktype, pinfo->ai_protocol); if (fd == INVALID_SOCKET) { LOG(ERROR) << StringPrintf("socket(): %s\n", LAST_ERROR_MSG); continue; } // set to non-blocking mode if (nonblock) { if (SetNonblock(fd, true) == SOCKET_ERROR) { closesocket(fd); fd = INVALID_SOCKET; continue; } } int err = connect(fd, pinfo->ai_addr, (int)pinfo->ai_addrlen); if (err == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { LOG(ERROR) << StringPrintf("connect(): %s\n", LAST_ERROR_MSG); closesocket(fd); fd = INVALID_SOCKET; return false; } } break; } freeaddrinfo(aiList); return fd; } <|start_filename|>examples/echo/EchoServer.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <vector> #include <unordered_map> #include "PollerBase.h" #include "PollEvent.h" #include "EchoConn.h" class EchoServer : public IPollEvent { public: explicit EchoServer(PollerBase* poller); ~EchoServer(); void Start(const char* host, const char* port); void CloseSession(SOCKET fd); PollerBase* Poller() { return poller_; } private: void Cleanup(); void OnReadable(); void OnWritable(); void OnTimeout(){} private: PollerBase* poller_; SOCKET acceptor_; std::unordered_map<SOCKET, EchoConn*> connections_; }; <|start_filename|>examples/pingpong/Client.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "Client.h" #include <WS2tcpip.h> #include <functional> #include "Common/Logging.h" #include "Common/StringUtil.h" #include "Common/Error.h" enum { MAX_SEND_COUNT = 5, }; using namespace std::placeholders; Client::Client(IOServiceBase* service) : recv_ctx_(NULL), service_(service), fd_(INVALID_SOCKET), sent_count_(0) { } Client::~Client() { Cleanup(); } void Client::Cleanup() { if (fd_ != INVALID_SOCKET) { fprintf(stderr, "%d closed\n", (int)fd_); closesocket(fd_); fd_ = INVALID_SOCKET; } if (recv_ctx_ != NULL) { recv_ctx_->flags |= FLAG_LAZY_DELETE; service_->FreeOverlapCtx(recv_ctx_); recv_ctx_ = NULL; } } int Client::Start(const char* host, const char* port) { return Connect(host, port); } int Client::Connect(const char* host, const char* port) { struct addrinfo* aiList = NULL; struct addrinfo* pinfo = NULL; struct addrinfo hints = {}; hints.ai_family = AF_INET; // IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; int err = getaddrinfo(host, port, &hints, &aiList); if (err != 0) { LOG(ERROR) << StringPrintf("getaddrinfo(): %s:%s, %s.\n", host, port, gai_strerror(err)); return -1; } for (pinfo = aiList; pinfo != NULL; pinfo = pinfo->ai_next) { SOCKET fd = socket(pinfo->ai_family, pinfo->ai_socktype, pinfo->ai_protocol); if (fd == INVALID_SOCKET) { continue; } OverlapContext* ctx = service_->AllocOverlapCtx(fd, FLAG_ASSOCIATE); if (ctx == NULL) { continue; } fd_ = fd; ctx->cb = std::bind(&Client::OnConnect, this, ctx); int r = service_->AsyncConnect(ctx, pinfo); if (r < 0) { service_->FreeOverlapCtx(ctx); continue; } recv_ctx_ = ctx; break; } freeaddrinfo(aiList); return 0; } void Client::OnConnect(OverlapContext* ctx) { if (ctx->GetStatusCode() != 0) { LOG(ERROR) << "Conenct error: " << ctx->GetStatusCode(); service_->FreeOverlapCtx(ctx); return; } StartRead(); service_->AddTimer(1000, this); } void Client::StartRead() { recv_buf_.resize(1024); recv_ctx_->SetBuffer(&recv_buf_[0], (int)recv_buf_.size()); recv_ctx_->cb = std::bind(&Client::OnRead, this, recv_ctx_); service_->AsyncRead(recv_ctx_); } void Client::OnRead(OverlapContext* ctx) { DWORD dwErr = ctx->GetStatusCode(); if (dwErr != 0) { if (dwErr != ERROR_IO_PENDING) { LOG(ERROR) << StringPrintf("recv error %d: %s", dwErr, GetErrorMessage(dwErr)); Cleanup(); } return; } int nbytes = ctx->GetTransferredBytes(); if (nbytes > 0) { fprintf(stdout, "%d recv %d bytes, %d\n", (int)fd_, nbytes, sent_count_); recv_buf_.resize(nbytes); } // read again StartRead(); } int Client::Write(const void* data, int len) { DCHECK(data != NULL && len > 0); OverlapContext* ctx = service_->AllocOverlapCtx(fd_, 0); if (ctx == NULL) { return -1; } ctx->buf.buf = new char[len]; memcpy(ctx->buf.buf, data, len); ctx->buf.len = len; ctx->cb = std::bind(&Client::OnWritten, this, ctx); service_->AsyncWrite(ctx); return 0; } void Client::OnWritten(OverlapContext* ctx) { DWORD dwErr = ctx->GetStatusCode(); if (dwErr == 0) { int nbytes = ctx->GetTransferredBytes(); if (nbytes > 0) { fprintf(stdout, "%d send %d bytes, %d\n", (int)fd_, nbytes, sent_count_); sent_count_++; } } else { LOG(WARNING) << StringPrintf("Send error: %d, %s", dwErr, GetErrorMessage(dwErr)); } delete ctx->buf.buf; ctx->buf.buf = NULL; ctx->buf.len = 0; ctx->flags |= FLAG_LAZY_DELETE; service_->FreeOverlapCtx(ctx); } void Client::OnTimeout() { if (sent_count_ < MAX_SEND_COUNT) // write again { if (!recv_buf_.empty()) { Write(&recv_buf_[0], (int)recv_buf_.size()); } } else { Cleanup(); } service_->AddTimer(1000, this); } <|start_filename|>examples/pingpong/Session.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "Session.h" #include "Server.h" #include "Common/Logging.h" #include "Common/Error.h" #include "Common/StringUtil.h" #include <functional> using namespace std::placeholders; Session::Session(int id, Server* server, OverlapContext* ctx) : server_(server), service_(server->GetIOService()), recv_ctx_(ctx), id_(id), fd_(ctx->fd), recv_count_(0) { } Session::~Session() { Close(); } void Session::Close() { if (id_ > 0) { fprintf(stderr, "%d closed\n", (int)fd_); closesocket(fd_); fd_ = INVALID_SOCKET; int sid = id_; id_ = 0; recv_ctx_->flags |= FLAG_LAZY_DELETE; service_->FreeOverlapCtx(recv_ctx_); server_->CloseSession(sid); // will delete me } } int Session::Write(const void* data, int len) { DCHECK(data != NULL && len > 0); OverlapContext* ctx = service_->AllocOverlapCtx(fd_, 0); if (ctx == NULL) { return -1; } ctx->buf.buf = new char[len]; memcpy(ctx->buf.buf, data, len); ctx->buf.len = len; ctx->cb = std::bind(&Session::OnWritten, this, ctx); service_->AsyncWrite(ctx); return 0; } void Session::StartRead() { recv_buf_.resize(1024); recv_ctx_->SetBuffer(&recv_buf_[0], (int)recv_buf_.size()); recv_ctx_->cb = std::bind(&Session::OnRead, this, recv_ctx_); service_->AsyncRead(recv_ctx_); } void Session::OnRead(OverlapContext* ctx) { DWORD dwErr = ctx->GetStatusCode(); if (dwErr != 0) { if (dwErr != ERROR_IO_PENDING) { LOG(ERROR) << StringPrintf("recv error %d: %s", dwErr, GetErrorMessage(dwErr)); Close(); } return; } int nbytes = ctx->GetTransferredBytes(); if (nbytes > 0) { fprintf(stdout, "%d recv %d bytes, %d\n", (int)fd_, nbytes, recv_count_); recv_buf_.resize(nbytes); recv_count_++; Write(&recv_buf_[0], nbytes); StartRead(); } else // EOF { Close(); } } void Session::OnWritten(OverlapContext* ctx) { if (ctx->GetStatusCode() != 0) { LOG(WARNING) << "Send error: " << ctx->GetStatusCode(); } int nbytes = ctx->GetTransferredBytes(); if (nbytes > 0) { fprintf(stdout, "%d send %d bytes, %d\n", (int)fd_, nbytes, recv_count_); } delete ctx->buf.buf; ctx->buf.buf = NULL; ctx->buf.len = 0; ctx->flags |= FLAG_LAZY_DELETE; service_->FreeOverlapCtx(ctx); } <|start_filename|>src/SelectPoller.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "SelectPoller.h" #include <assert.h> #include "Common/Error.h" #include "Common/Logging.h" #include <algorithm> SelectPoller::SelectPoller() { fds_.reserve(64); has_retired_ = false; memset(&readfds_, 0, sizeof(fd_set)); memset(&writefds_, 0, sizeof(fd_set)); memset(&exceptfds_, 0, sizeof(fd_set)); } SelectPoller::~SelectPoller() { } int SelectPoller::AddFd(SOCKET fd, IPollEvent* event) { assert(event != nullptr); if (fds_.size() >= FD_SETSIZE) { return -1; } FdEntry entry = {}; entry.fd = fd; entry.sink = event; fds_.push_back(entry); // start polling on errors. FD_SET(fd, &exceptfds_); return 0; } void SelectPoller::RemoveFd(SOCKET fd) { MarkRetired(fd); // stop polling on the descriptor FD_CLR(fd, &readfds_); FD_CLR(fd, &writefds_); FD_CLR(fd, &exceptfds_); } void SelectPoller::SetPollIn(SOCKET fd) { FD_SET(fd, &readfds_); } void SelectPoller::ResetPollIn(SOCKET fd) { FD_CLR(fd, &readfds_); } void SelectPoller::SetPollOut(SOCKET fd) { FD_SET(fd, &writefds_); } void SelectPoller::ResetPollOut(SOCKET fd) { FD_CLR(fd, &writefds_); } // timeout in milliseconds int SelectPoller::Poll(int timeout) { int r = 0; fd_set rdset, wrset, exptset; // select() returns WSAEINVAL if all 3 fd_sets empty if (!fds_.empty()) { memcpy(&rdset, &readfds_, sizeof(fd_set)); memcpy(&wrset, &writefds_, sizeof(fd_set)); memcpy(&exptset, &exceptfds_, sizeof(fd_set)); timeval tvp = {}; tvp.tv_usec = timeout * 1000; r = select(0, &rdset, &wrset, &exptset, &tvp); if (r == SOCKET_ERROR) { LOG(ERROR) << GetLastError() << ": " << LAST_ERROR_MSG; return 0; } } else { // nothing to do, sleep a while if (timeout > 0) { Sleep(timeout / 2); } } int count = 0; for (size_t i = 0; r > 0 && i < fds_.size(); i++) { SOCKET fd = fds_[i].fd; if (fd == INVALID_SOCKET) continue; if (FD_ISSET(fd, &exptset)) { fds_[i].sink->OnReadable(); count++; } if (fd == INVALID_SOCKET) continue; if (FD_ISSET(fd, &wrset)) { fds_[i].sink->OnWritable(); count++; } if (fd == INVALID_SOCKET) continue; if (FD_ISSET(fd, &rdset)) { fds_[i].sink->OnReadable(); count++; } } // execute time out callbacks UpdateTimer(); RemoveRetired(); return count; } void SelectPoller::MarkRetired(SOCKET fd) { for (size_t i = 0; i < fds_.size(); i++) { if (fds_[i].fd == fd) { fds_[i].fd = INVALID_SOCKET; fds_[i].sink = NULL; break; } } has_retired_ = true; } void SelectPoller::RemoveRetired() { if (has_retired_) { auto iter = std::remove_if(fds_.begin(), fds_.end(), [](const FdEntry& entry) { return entry.fd == INVALID_SOCKET; }); fds_.erase(iter, fds_.end()); has_retired_ = false; } } <|start_filename|>src/SocketOpts.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <WinSock2.h> // set socket to non-blocking mode int SetNonblock(SOCKET fd, bool nonblock); int BindAnyAddr(SOCKET fd, int family); // enable previously set properties or options after ConnectEx int UpdateConnectCtx(SOCKET fd); // make sure 'size' is read before to return (unless error is encountered) int ReadSome(SOCKET fd, void* buf, int size); // make sure 'size' is written before to return (unless error is encountered) int WriteSome(SOCKET fd, const void* buf, int size); bool IsSelfConnection(SOCKET fd); SOCKET CreateTCPAcceptor(const char* host, const char* port, bool nonblock = true, bool ipv6 = false); SOCKET CreateTcpConnector(const char* host, const char* port, bool nonblock = true, bool ipv6 = false); <|start_filename|>src/Common/Mutex.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <Windows.h> class Mutex { public: Mutex() { InitializeCriticalSection(&cs_); } ~Mutex() { DeleteCriticalSection(&cs_); } void Lock() { EnterCriticalSection(&cs_); } bool TryLock() { return TryEnterCriticalSection(&cs_) > 0; } void UnLock() { LeaveCriticalSection(&cs_); } private: CRITICAL_SECTION cs_; }; <|start_filename|>examples/pingpong/Server.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include "IOServiceBase.h" #include <unordered_map> class Session; class Server { public: explicit Server(IOServiceBase* service); ~Server(); void Start(const char* host, const char* port); void CloseSession(int sid); IOServiceBase* GetIOService() { return service_; } private: void Cleanup(); void StartAccept(); void OnAccept(OverlapContext* ctx); private: IOServiceBase* service_; OverlapContext* ctx_; SOCKET acceptor_; int counter_; std::unordered_map<int, Session*> sessions_; }; <|start_filename|>src/OverlappedIOService.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include "IOServiceBase.h" #include <vector> #include <unordered_map> class OverlappedIOService : public IOServiceBase { public: OverlappedIOService(); ~OverlappedIOService(); int AsyncConnect(OverlapContext* ctx, const addrinfo* pinfo); int AsyncAccept(OverlapContext* ctx); int AsyncRead(OverlapContext* ctx); int AsyncWrite(OverlapContext* ctx); OverlapContext* AllocOverlapCtx(SOCKET fd, int flags); void FreeOverlapCtx(OverlapContext* ctx); int Run(int timeout); private: void CleanUp(); private: std::vector<WSAEVENT> events_; std::unordered_map<WSAEVENT, OverlapContext*> fds_; }; <|start_filename|>src/PollerBase.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "PollerBase.h" #include <stdint.h> #include <Windows.h> #include "SelectPoller.h" #include "AsyncSelectPoller.h" #include "AsyncEventPoller.h" PollerBase::PollerBase() : last_err_(0) { } PollerBase::~PollerBase() { } PollerBase* CreatePoller(PollerType type) { switch(type) { case PollerSelect: return new SelectPoller; case PollerAsyncSelect: return new AsyncSelectPoller; case PollerAsyncEvent: return new AsyncEventPoller; default: return nullptr; } } <|start_filename|>examples/echo/EchoServer.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "EchoServer.h" #include <functional> #include <WS2tcpip.h> #include "Common/Error.h" #include "Common/Logging.h" #include "Common/StringUtil.h" #include "SocketOpts.h" ////////////////////////////////////////////////////// EchoServer::EchoServer(PollerBase* poller) : acceptor_(INVALID_SOCKET) { poller_ = poller; } EchoServer::~EchoServer() { Cleanup(); } void EchoServer::Start(const char* host, const char* port) { SOCKET fd = CreateTCPAcceptor(host, port); CHECK(fd != INVALID_SOCKET) << LAST_ERROR_MSG; acceptor_ = fd; poller_->AddFd(acceptor_, this); poller_->SetPollIn(fd); } void EchoServer::Cleanup() { if (acceptor_ != INVALID_SOCKET) { poller_->RemoveFd(acceptor_); closesocket(acceptor_); acceptor_ = INVALID_SOCKET; } for (auto iter = connections_.begin(); iter != connections_.end(); ++iter) { EchoConn* conn = iter->second; conn->Close(); delete conn; } connections_.clear(); } void EchoServer::CloseSession(SOCKET fd) { LOG(INFO) << StringPrintf("sock %d closed.", fd); auto iter = connections_.find(fd); if (iter != connections_.end()) { poller_->RemoveFd(fd); closesocket(fd); EchoConn* conn = iter->second; delete conn; connections_.erase(iter); } } void EchoServer::OnReadable() { SOCKET newfd = accept(acceptor_, NULL, NULL); if (newfd == INVALID_SOCKET ) { LOG(ERROR) << "accept " << LAST_ERROR_MSG; return; } LOG(INFO) << StringPrintf("sock %d accepted.", newfd); EchoConn* conn = new EchoConn(this, newfd); if (poller_->AddFd(newfd, conn) < 0) { conn->Close(); delete conn; return; } poller_->SetPollIn(newfd); poller_->SetPollOut(newfd); conn->StartRead(); connections_[newfd] = conn; // keep in memory } void EchoServer::OnWritable() { // do nothing here } <|start_filename|>examples/echo/main.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include <stdio.h> #include <signal.h> #include <string> #include <memory> #include "Common/WinsockInit.h" #include "EchoServer.h" #include "EchoClient.h" using namespace std; bool g_stop = false; void HandleSignal(int sig) { g_stop = true; fprintf(stderr, "stop poller\n"); } int main(int argc, const char* argv[]) { signal(SIGINT, HandleSignal); if (argc != 5) { fprintf(stderr, "Usage: %s <server/client> {host} {port} {mode}\n", argv[0]); return 1; } string type = argv[1]; const char* host = argv[2]; const char* port = argv[3]; PollerType mode = (PollerType)atoi(argv[4]); WinsockAutoInit init; PollerBase* poller = CreatePoller(mode); CHECK(poller != NULL); std::shared_ptr<EchoServer> server = NULL; std::shared_ptr<EchoClient> client = NULL; std::shared_ptr<IPollEvent> sink = NULL; if (type == "server") { server.reset(new EchoServer(poller)); server->Start(host, port); sink = server; fprintf(stdout, "server started at %s:%s\n", host, port); } else if (type == "client") { client.reset(new EchoClient(poller)); client->Start(host, port); sink = client; fprintf(stdout, "client started at %s:%s\n", host, port); } else { fprintf(stderr, "invalid instance type: [%s]\n", type.c_str()); } while (!g_stop) { poller->Poll(50); } delete poller; return 0; } <|start_filename|>src/AsyncEventPoller.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <Windows.h> #include <vector> #include "PollerBase.h" class AsyncEventPoller : public PollerBase { public: AsyncEventPoller(); ~AsyncEventPoller(); int AddFd(SOCKET fd, IPollEvent* event); void RemoveFd(SOCKET fd); void SetPollIn(SOCKET fd); void ResetPollIn(SOCKET fd); void SetPollOut(SOCKET fd); void ResetPollOut(SOCKET fd); int Poll(int timeout); private: struct FdEntry { SOCKET fd; WSAEVENT hEvent; LONG lEvents; int mask; IPollEvent* sink; }; void CleanUp(); void HandleEvents(FdEntry* entry, WSANETWORKEVENTS* events); FdEntry* FindEntry(SOCKET fd); FdEntry* FindEntryByEvent(WSAEVENT hEvent); void RemoveRetired(); private: std::vector<WSAEVENT> events_; std::vector<FdEntry> fds_; bool has_retired_; }; <|start_filename|>src/Common/StringUtil.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "StringUtil.h" #include <stdarg.h> #ifndef va_copy // This is a hack, assuming va_list is simply a // pointer into the stack and is safe to copy. #define va_copy(dest, src) ((dest) = (src)) #endif void StringAppendV(std::string* dst, const char* format, va_list ap) { // First try with a small fixed size buffer static const int kSpaceLength = 1024; char space[kSpaceLength]; // It's possible for methods that use a va_list to invalidate // the data in it upon use. The fix is to make a copy // of the structure before using it and use that copy instead. va_list backup_ap; va_copy(backup_ap, ap); int result = vsprintf_s(space, kSpaceLength, format, backup_ap); va_end(backup_ap); if (result < kSpaceLength) { if (result >= 0) // Normal case -- everything fit. { dst->append(space, result); return; } va_copy(backup_ap, ap); result = vsprintf_s(NULL, 0, format, backup_ap); va_end(backup_ap); if (result < 0) // Just an error. { return; } } // Increase the buffer size to the size requested by vsnprintf, // plus one for the closing \0. int length = result + 1; char* buf = new char[length]; // Restore the va_list before we use it again va_copy(backup_ap, ap); result = vsprintf_s(buf, length, format, backup_ap); va_end(backup_ap); if (result >= 0 && result < length) // It fit { dst->append(buf, result); } delete[] buf; } std::string StringPrintf(const char* format, ...) { va_list ap; va_start(ap, format); std::string result; StringAppendV(&result, format, ap); va_end(ap); return result; } const std::string& SStringPrintf(std::string* dst, const char* format, ...) { va_list ap; va_start(ap, format); dst->clear(); StringAppendV(dst, format, ap); va_end(ap); return *dst; } <|start_filename|>src/TimerSched.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <vector> #include <unordered_map> #include "PollEvent.h" class TimerSched { public: TimerSched(); virtual ~TimerSched(); int AddTimer(int millsec, ITimerEvent* event); void CancelTimer(int id); void UpdateTimer(); private: void clear(); bool siftdown(int x, int n); void siftup(int j); struct TimerEntry; private: int next_id_; // next timer id std::vector<TimerEntry*> heap_; // min-heap timer std::unordered_map<int, TimerEntry*> ref_; // reference }; <|start_filename|>examples/echo/EchoClient.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "EchoClient.h" #include <WS2tcpip.h> #include <WinSock2.h> #include <functional> #include "Common/Error.h" #include "Common/Logging.h" #include "Common/StringUtil.h" #include "SocketOpts.h" using namespace std::placeholders; enum { MAX_SEND_COUNT = 5, }; EchoClient::EchoClient(PollerBase* poller) :fd_(INVALID_SOCKET) { poller_ = poller; buf_.reserve(1024); sent_count_ = 0; } EchoClient::~EchoClient() { } void EchoClient::Cleanup() { fprintf(stderr, "%d closed\n", (int)fd_); poller_->RemoveFd(fd_); closesocket(fd_); fd_ = INVALID_SOCKET; } void EchoClient::Start(const char* host, const char* port) { host_ = host; port_ = port; SOCKET fd = CreateTcpConnector(host, port); CHECK(fd != INVALID_SOCKET); fd_ = fd; poller_->AddFd(fd, this); poller_->SetPollIn(fd); poller_->SetPollOut(fd); } void EchoClient::OnReadable() { char buf[1024] = {}; int nbytes = ReadSome(fd_, buf, 1024); if (nbytes < 0) { Cleanup(); } else if(nbytes > 0) { fprintf(stdout, "%d recv %d bytes, %d\n", (int)fd_, nbytes, sent_count_); buf_.resize(nbytes); memcpy(&buf_[0], buf, nbytes); } } void EchoClient::OnWritable() { // connected if (IsSelfConnection(fd_)) { Cleanup(); Start(host_.c_str(), port_.c_str()); return; } poller_->AddTimer(1000, this); poller_->ResetPollOut(fd_); } void EchoClient::OnTimeout() { if (fd_ != INVALID_SOCKET) { SendData(); } if (sent_count_ < MAX_SEND_COUNT) { poller_->AddTimer(1000, this); } } void EchoClient::SendData() { const char* msg = "a quick brown fox jumps over the lazy dog"; int len = (int)strlen(msg); if (sent_count_ > 0 && !buf_.empty()) { msg = &buf_[0]; len = (int)buf_.size(); } sent_count_++; int nbytes = WriteSome(fd_, msg, len); if (nbytes < 0) { Cleanup(); } else { fprintf(stdout, "%d send %d bytes, %d\n", (int)fd_, nbytes, sent_count_); buf_.clear(); } } <|start_filename|>src/WsaExt.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <WinSock2.h> #include <Mswsock.h> #include <ws2tcpip.h> class WsaExt { public: WsaExt(); static void Init(SOCKET sock); static LPFN_CONNECTEX ConnectEx; static LPFN_ACCEPTEX AcceptEx; static LPFN_ACCEPTEX DisconnectEx; static LPFN_GETACCEPTEXSOCKADDRS GetAcceptExSockaddrs; private: static bool intialized_; }; <|start_filename|>src/Common/Logging.h<|end_filename|> // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <stdint.h> #include <string> #include <sstream> #include <type_traits> // =================================================================== // emulates google3/base/logging.h enum LogLevel { LOGLEVEL_DEBUG, LOGLEVEL_INFO, // Informational. LOGLEVEL_WARNING, // Warns about issues that, although not technically a // problem now, could cause problems in the future. For // example, a // warning will be printed when parsing a // message that is near the message size limit. LOGLEVEL_ERROR, // An error occurred which should never happen during // normal use. LOGLEVEL_FATAL, // An error occurred from which the library cannot // recover. This usually indicates a programming error // in the code which calls the library, especially when // compiled in debug mode. LOGLEVEL_DFATAL = LOGLEVEL_FATAL }; namespace detail { class LogFinisher; class LogMessage { public: LogMessage(LogLevel level, const char* filename, int line) : level_(level), filename_(filename), line_(line) { } ~LogMessage() { } template <typename T> LogMessage& operator<<(const T& value) { strm_ << value; return *this; } private: friend class LogFinisher; void Finish(); LogLevel level_; const char* filename_; int line_; std::ostringstream strm_; }; // Used to make the entire "LOG(BLAH) << etc." expression have a void return // type and print a newline after each message. class LogFinisher { public: void operator=(LogMessage& other); }; } // namespace detail // Undef everything in case we're being mixed with some other Google library // which already defined them itself. Presumably all Google libraries will // support the same syntax for these so it should not be a big deal if they // end up using our definitions instead. #undef LOG #undef LOG_IF #undef CHECK #undef CHECK_OK #undef CHECK_EQ #undef CHECK_NE #undef CHECK_LT #undef CHECK_LE #undef CHECK_GT #undef CHECK_GE #undef CHECK_NOTNULL #undef DLOG #undef DCHECK #undef DCHECK_EQ #undef DCHECK_NE #undef DCHECK_LT #undef DCHECK_LE #undef DCHECK_GT #undef DCHECK_GE #define LOG(LEVEL) \ ::detail::LogFinisher() = \ ::detail::LogMessage(::LOGLEVEL_##LEVEL, __FILE__, __LINE__) #define LOG_IF(LEVEL, CONDITION) \ !(CONDITION) ? (void)0 : LOG(LEVEL) #define CHECK(EXPRESSION) \ LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": " #define CHECK_OK(A) CHECK(A) #define CHECK_EQ(A, B) CHECK((A) == (B)) #define CHECK_NE(A, B) CHECK((A) != (B)) #define CHECK_LT(A, B) CHECK((A) < (B)) #define CHECK_LE(A, B) CHECK((A) <= (B)) #define CHECK_GT(A, B) CHECK((A) > (B)) #define CHECK_GE(A, B) CHECK((A) >= (B)) namespace internal { template<typename T> T* CheckNotNull(const char* /* file */, int /* line */, const char* name, T* val) { if (val == NULL) { LOG(FATAL) << name; } return val; } } // namespace internal #define CHECK_NOTNULL(A) \ ::internal::CheckNotNull(__FILE__, __LINE__, "'" #A "' must not be NULL", (A)) #ifdef NDEBUG #define DLOG LOG_IF(INFO, false) #define DCHECK(EXPRESSION) while(false) CHECK(EXPRESSION) #define DCHECK_EQ(A, B) DCHECK((A) == (B)) #define DCHECK_NE(A, B) DCHECK((A) != (B)) #define DCHECK_LT(A, B) DCHECK((A) < (B)) #define DCHECK_LE(A, B) DCHECK((A) <= (B)) #define DCHECK_GT(A, B) DCHECK((A) > (B)) #define DCHECK_GE(A, B) DCHECK((A) >= (B)) #define DCHECK_NOTNULL CHECK_NOTNULL #else // NDEBUG #define DLOG LOG #define DCHECK CHECK #define DCHECK_EQ CHECK_EQ #define DCHECK_NE CHECK_NE #define DCHECK_LT CHECK_LT #define DCHECK_LE CHECK_LE #define DCHECK_GT CHECK_GT #define DCHECK_GE CHECK_GE #define DCHECK_NOTNULL CHECK_NOTNULL #endif // !NDEBUG <|start_filename|>src/SelectPoller.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include "PollerBase.h" #include <vector> class SelectPoller : public PollerBase { public: SelectPoller(); ~SelectPoller(); int AddFd(SOCKET fd, IPollEvent* event); void RemoveFd(SOCKET fd); void SetPollIn(SOCKET fd); void ResetPollIn(SOCKET fd); void SetPollOut(SOCKET fd); void ResetPollOut(SOCKET fd); int Poll(int timeout); private: void MarkRetired(SOCKET fd); void RemoveRetired(); struct FdEntry { SOCKET fd; IPollEvent* sink; }; private: std::vector<FdEntry> fds_; bool has_retired_; fd_set readfds_; fd_set writefds_; fd_set exceptfds_; }; <|start_filename|>src/Common/Error.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <Windows.h> /// description of specified error id const char* GetErrorMessage(DWORD dwError); // last error description of current thread #define LAST_ERROR_MSG GetErrorMessage(GetLastError()) <|start_filename|>src/AsyncSelectPoller.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <Windows.h> #include <map> #include "PollerBase.h" // This API may be altered or unavailable in subsequent Windows versions. class AsyncSelectPoller : public PollerBase { public: AsyncSelectPoller(); ~AsyncSelectPoller(); int AddFd(SOCKET fd, IPollEvent* event); void RemoveFd(SOCKET fd); void SetPollIn(SOCKET fd); void ResetPollIn(SOCKET fd); void SetPollOut(SOCKET fd); void ResetPollOut(SOCKET fd); int Poll(int timeout); void Cleanup(); private: struct FdEntry { SOCKET fd; LONG lEvents; int mask; IPollEvent* sink; }; void CreateHidenWindow(); void HandleEvent(SOCKET fd, int ev, int ec); FdEntry* FindEntry(SOCKET fd); void RemoveRetired(); private: HWND hwnd_; std::vector<FdEntry> fds_; bool has_retired_; }; <|start_filename|>src/WsaExt.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "WsaExt.h" #include "Common/Error.h" #include "Common/Logging.h" bool WsaExt::intialized_ = false; LPFN_CONNECTEX WsaExt::ConnectEx = NULL; LPFN_ACCEPTEX WsaExt::AcceptEx = NULL; LPFN_ACCEPTEX WsaExt::DisconnectEx = NULL; LPFN_GETACCEPTEXSOCKADDRS WsaExt::GetAcceptExSockaddrs = NULL; WsaExt::WsaExt() { Init(INVALID_SOCKET); } void WsaExt::Init(SOCKET fd) { if (intialized_) return; bool should_close = false; if (fd == INVALID_SOCKET) { fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // IPv4 should_close = true; } GUID guid_connectex = WSAID_CONNECTEX; GUID guid_acceptex = WSAID_ACCEPTEX; GUID guid_disconnectex = WSAID_DISCONNECTEX; GUID guid_getacceptexaddr = WSAID_GETACCEPTEXSOCKADDRS; int err = 0; DWORD bytes = 0; // ConnectEx err = WSAIoctl(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid_connectex, sizeof(guid_connectex), &ConnectEx, sizeof(ConnectEx), &bytes, NULL, NULL); CHECK(err != SOCKET_ERROR) << "WSAIoctl: ConnectEx, " << LAST_ERROR_MSG; // AcceptEx err = WSAIoctl(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid_acceptex, sizeof(guid_acceptex), &AcceptEx, sizeof(AcceptEx), &bytes, NULL, NULL); CHECK(err != SOCKET_ERROR) << "WSAIoctl: AcceptEx, " << LAST_ERROR_MSG; // DisconnectEx err = WSAIoctl(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid_disconnectex, sizeof(guid_disconnectex), &DisconnectEx, sizeof(DisconnectEx), &bytes, NULL, NULL); CHECK(err != SOCKET_ERROR) << "WSAIoctl: DisconnectEx, " << LAST_ERROR_MSG; // GetAcceptExSockaddrs err = WSAIoctl(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid_getacceptexaddr, sizeof(guid_getacceptexaddr), &GetAcceptExSockaddrs, sizeof(GetAcceptExSockaddrs), &bytes, NULL, NULL); CHECK(err != SOCKET_ERROR) << "WSAIoctl: GetAcceptExSockaddrs, " << LAST_ERROR_MSG; if (should_close) { closesocket(fd); } intialized_ = true; } <|start_filename|>src/CompletionPortService.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include "IOServiceBase.h" // I/O Completion Port class CompletionPortService : public IOServiceBase { public: CompletionPortService(); ~CompletionPortService(); int AsyncConnect(OverlapContext* ctx, const addrinfo* pinfo); int AsyncAccept(OverlapContext* ctx); int AsyncRead(OverlapContext* ctx); int AsyncWrite(OverlapContext* ctx); OverlapContext* AllocOverlapCtx(SOCKET fd, int flags); void FreeOverlapCtx(OverlapContext* ctx); int Run(int timeout); private: HANDLE completion_port_; }; <|start_filename|>src/OverlapFd.h<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #pragma once #include <WinSock2.h> #include <stdint.h> #include <functional> enum { FLAG_ASSOCIATE = 1, FLAG_CANCEL_IO = 2, FLAG_LAZY_DELETE = 3, }; struct OverlapContext { WSAOVERLAPPED overlap; // overlapped structure, must be the first field WSABUF buf; // buffer SOCKET fd; // socket descriptor int flags; // int64_t udata; // user data std::function<void()> cb; // callback DWORD GetStatusCode() { return (DWORD)overlap.Internal; } DWORD GetTransferredBytes() { return (DWORD)overlap.InternalHigh; } void SetBuffer(void* buffer, int len) { buf.buf = (char*)buffer; buf.len = len; } }; struct AcceptInfo { struct sockaddr_storage local_addr; char reserved1[16]; struct sockaddr_storage remote_addr; char reserved2[16]; }; enum { ACCEPTEX_ADDR_LEN = sizeof(sockaddr_storage) + 16, }; <|start_filename|>src/TimerSched.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "TimerSched.h" #include <stdint.h> #include <Windows.h> // GetTickCount64 struct TimerSched::TimerEntry { int index; // heap index of this item int id; // unique timer id int64_t expire; // expire time ITimerEvent* sink; // event sink TimerEntry() { index = 0; id = 0; expire = 0; sink = nullptr; } }; TimerSched::TimerSched() : next_id_(100) // time flies { ref_.rehash(64); } TimerSched::~TimerSched() { clear(); } void TimerSched::clear() { for (size_t i = 0; i < heap_.size(); i++) { delete heap_[i]; } heap_.clear(); } #define HEAP_ITEM_LESS(i, j) (heap_[(i)]->expire < heap_[(j)]->expire) bool TimerSched::siftdown(int x, int n) { int i = x; for (;;) { int j1 = 2 * i + 1; if ((j1 >= n) || (j1 < 0)) // j1 < 0 after int overflow { break; } int j = j1; // left child int j2 = j1 + 1; if (j2 < n && !HEAP_ITEM_LESS(j1, j2)) { j = j2; // right child } if (!HEAP_ITEM_LESS(j, i)) { break; } std::swap(heap_[i], heap_[j]); heap_[i]->index = i; heap_[j]->index = j; i = j; } return i > x; } void TimerSched::siftup(int j) { for (;;) { int i = (j - 1) / 2; // parent node if (i == j || !HEAP_ITEM_LESS(j, i)) { break; } std::swap(heap_[i], heap_[j]); heap_[i]->index = i; heap_[j]->index = j; j = i; } } #undef HEAP_ITEM_LESS int TimerSched::AddTimer(int millsec, ITimerEvent* event) { TimerEntry* entry = new TimerEntry; entry->id = next_id_++; entry->expire = GetTickCount64() + millsec; entry->sink = event; entry->index = (int)heap_.size(); ref_[entry->id] = entry; heap_.push_back(entry); siftup((int)heap_.size() - 1); return entry->id; } void TimerSched::UpdateTimer() { int64_t now = GetTickCount64(); int last_id = next_id_; while (!heap_.empty()) { TimerEntry* entry = heap_[0]; if (now < entry->expire) { break; } // we don't process timers created by time events in this iteration if (entry->id > last_id) { continue; } int n = (int)heap_.size() - 1; std::swap(heap_[0], heap_[n]); heap_[0]->index = 0; siftdown(0, n); heap_.pop_back(); ref_.erase(entry->id); if (entry->sink) { entry->sink->OnTimeout(); } delete entry; } } void TimerSched::CancelTimer(int id) { auto iter = ref_.find(id); if (iter == ref_.end()) { return; } TimerEntry* entry = iter->second; if (entry == nullptr) { return; } int n = (int)heap_.size() - 1; int i = entry->index; if (i != n) { std::swap(heap_[i], heap_[n]); heap_[i]->index = i; if (!siftdown(i, n)) { siftup(i); } } heap_.pop_back(); delete entry; } <|start_filename|>src/OverlappedIOService.cpp<|end_filename|> // Copyright (C) 2012-present <EMAIL> All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include "OverlappedIOService.h" #include <WS2tcpip.h> #include "Common/Error.h" #include "Common/Logging.h" #include "Common/StringUtil.h" #include "SocketOpts.h" #include "WsaExt.h" using namespace std::placeholders; OverlappedIOService::OverlappedIOService() { events_.reserve(WSA_MAXIMUM_WAIT_EVENTS); fds_.reserve(WSA_MAXIMUM_WAIT_EVENTS); } OverlappedIOService::~OverlappedIOService() { CleanUp(); } void OverlappedIOService::CleanUp() { fds_.clear(); events_.clear(); } OverlapContext* OverlappedIOService::AllocOverlapCtx(SOCKET fd, int flags) { if (fds_.size() >= WSA_MAXIMUM_WAIT_EVENTS) { LOG(ERROR) << "WSA_MAXIMUM_WAIT_EVENTS limit"; return NULL; } WSAEVENT hEvent = WSACreateEvent(); if (hEvent == WSA_INVALID_EVENT) { LOG(ERROR) << "AllocOverlapContext: WSACreateEvent " << LAST_ERROR_MSG; return NULL; } OverlapContext* ctx = new OverlapContext(); ctx->fd = fd; ctx->overlap.hEvent = hEvent; fds_[hEvent] = ctx; return ctx; } void OverlappedIOService::FreeOverlapCtx(OverlapContext* ctx) { WSAEVENT hEvent = ctx->overlap.hEvent; WSACloseEvent(hEvent); ctx->fd = INVALID_SOCKET; ctx->overlap.hEvent = WSA_INVALID_EVENT; fds_.erase(hEvent); delete ctx; } int OverlappedIOService::AsyncConnect(OverlapContext* ctx, const addrinfo* pinfo) { // ConnectEx need previously bound socket. int r = BindAnyAddr(ctx->fd, pinfo->ai_family); if (r != 0) { return r; } ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int fOK = WsaExt::ConnectEx(ctx->fd, (const struct sockaddr*)pinfo->ai_addr, (int)pinfo->ai_addrlen, nullptr, 0, nullptr, &ctx->overlap); if (!fOK) { if (GetLastError() != WSA_IO_PENDING) { LOG(ERROR) << "ConnectEx: " << LAST_ERROR_MSG; return -1; } } else { UpdateConnectCtx(ctx->fd); } return 0; // succeed } int OverlappedIOService::AsyncAccept(OverlapContext* ctx) { SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == INVALID_SOCKET) { LOG(ERROR) << StringPrintf("socket(): %s\n", LAST_ERROR_MSG); return -1; } ctx->udata = fd; ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int fOK = WsaExt::AcceptEx(ctx->fd, fd, ctx->buf.buf, 0, ACCEPTEX_ADDR_LEN, ACCEPTEX_ADDR_LEN, NULL, &ctx->overlap); if (!fOK) { int r = WSAGetLastError(); if (r != WSA_IO_PENDING) { closesocket(fd); LOG(ERROR) << StringPrintf("AcceptEx(): %s\n", LAST_ERROR_MSG); return r; } } return 0; } int OverlappedIOService::AsyncRead(OverlapContext* ctx) { DWORD dwFlags = 0; ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int r = WSARecv(ctx->fd, &ctx->buf, 1, NULL, &dwFlags, &ctx->overlap, NULL); if (r == SOCKET_ERROR) { int r = WSAGetLastError(); if (r != WSA_IO_PENDING) { LOG(ERROR) << StringPrintf("WSARecv(): %s\n", LAST_ERROR_MSG); return r; } } return 0; } int OverlappedIOService::AsyncWrite(OverlapContext* ctx) { ctx->overlap.Internal = 0; ctx->overlap.InternalHigh = 0; int r = WSASend(ctx->fd, &ctx->buf, 1, NULL, 0, &ctx->overlap, NULL); if (r == SOCKET_ERROR) { int r = WSAGetLastError(); if (r != WSA_IO_PENDING) { LOG(ERROR) << StringPrintf("WSASend(): %s\n", LAST_ERROR_MSG); return r; } } return 0; } int OverlappedIOService::Run(int timeout) { int nready = 0; events_.clear(); for (auto iter = fds_.begin(); iter != fds_.end(); ++iter) { events_.push_back(iter->first); } if (!events_.empty()) { nready = WSAWaitForMultipleEvents((DWORD)events_.size(), &events_[0], FALSE, timeout, FALSE); if (nready == WSA_WAIT_FAILED) { LOG(ERROR) << "Poll: WSAWaitForMultipleEvents, " << LAST_ERROR_MSG; nready = -1; } else if (nready == WSA_WAIT_TIMEOUT) { nready = -1; } } else { // nothing to do, sleep a while if (timeout > 0) { Sleep(timeout / 2); } } UpdateTimer(); if (nready >= 0 && !events_.empty()) { int index = nready - WSA_WAIT_EVENT_0; if (index >= WSA_MAXIMUM_WAIT_EVENTS) { LOG(ERROR) << "Poll: wait events index out of range: " << index; return -1; } WSAEVENT hEvent = events_[index]; auto iter = fds_.find(hEvent); if (iter == fds_.end()) { //LOG(ERROR) << "Run: overlap context not found"; return -1; } OverlapContext* pContext = iter->second; DWORD dwBytes = 0; DWORD dwFlags = 0; if (!WSAGetOverlappedResult(pContext->fd, &pContext->overlap, &dwBytes, 1, &dwFlags)) { LOG(ERROR) << "WSAGetOverlappedResult: " << LAST_ERROR_MSG; } if (pContext && pContext->cb) { pContext->cb(); // dispatch event } } return 0; }
ichenq/WinsockTut
<|start_filename|>example/src/App.js<|end_filename|> import React from 'react' import { Router, Switch, Route, Link } from 'react-router-dom' import { createBrowserHistory } from 'history' import qhistory from 'qhistory' import { parse, stringify } from 'qs' const products = [ { id: 0, name: 'Chair' }, { id: 1, name: 'Stool' }, { id: 2, name: 'Recliner' }, { id: 3, name: 'Adirondack' }, { id: 4, name: 'Terrace' }, ] const Product = ({ location }) => { const product = products[parseInt(location.query.id, 10)] return ( <div> You are viewing product: {product.name} <p> <Link to='/'>Home</Link> </p> <p> <Link to={{ pathname: '/product', query: { id: Math.floor(Math.random()*products.length) } }}> Random Product </Link> </p> </div> ) } const Showcase = () => ( <div> <h1>Products:</h1> <ul> { products.map(p => ( <li key={p.id}> <Link to={{ pathname: '/product', query: { id: p.id }}}>{p.name}</Link> </li> )) } </ul> <p> Or view a <Link to={{ pathname: '/product', query: { id: Math.floor(Math.random()*products.length) } }}> Random Product </Link> </p> </div> ) const queryHistory = qhistory( createBrowserHistory(), stringify, parse ) const App = () => ( <Router history={queryHistory}> <Switch> <Route exact path='/' component={Showcase} /> <Route path='/product' component={Product} /> </Switch> </Router> ) export default App <|start_filename|>src/index.js<|end_filename|> import invariant from 'invariant' const qhistory = (history, stringify, parse) => { invariant( typeof stringify === 'function', 'A stringify function is required in order to transform ' + 'query objects into search strings.' ) invariant( typeof parse === 'function', 'A parse function is required in order to transform ' + 'search strings into query objects.' ) const addSearch = (location) => { if (typeof location === 'object') { let search = location.search || '' if (location.query) { search = stringify(location.query) // Ensure leading "?" for non-empty search if (search.length > 0 && search.charAt(0) !== '?') { search = `?${search}` } } return {...location, search} } return location } const addQuery = (location) => { const { search } = location return { ...location, query: search ? parse(search.charAt(0) === '?' ? search.substring(1) : search) : {} } } const updateProperties = (history) => { const properties = ['length', 'entries', 'index', 'action'] properties.forEach(prop => { if (history.hasOwnProperty(prop)) { queryHistory[prop] = history[prop] } }) } // This relies on being the first listener called by // the actual history instance. If you register a // listener on the history instance before modifying // it with qhistory, the location object will not have // the query property set on it when that listener // is called. history.listen((location) => { updateProperties(history) }) const queryHistory = { ...history, listen: (listener) => history.listen((location, action) => { const isV5 = location.location != null if (isV5) { action = location.action location = location.location } const queryLocation = addQuery(location) isV5 ? listener({location: queryLocation, action}) : listener(queryLocation, action) }), push: (location, state) => history.push(addSearch(location), state), replace: (location, state) => history.replace(addSearch(location), state), createHref: (location) => history.createHref(addSearch(location)) } Object.defineProperty(queryHistory, 'location', { get: () => addQuery(history.location), }) return queryHistory } export default qhistory <|start_filename|>package.json<|end_filename|> { "name": "qhistory", "version": "1.1.0", "description": "Wrap history with query support", "main": "lib/index.js", "module": "es/index.js", "files": [ "lib", "umd", "es", "LICENSE", "*.md", "index.d.ts" ], "scripts": { "prebuild": "rimraf lib umd es", "build": "npm run build:lib && npm run build:umd && npm run build:min && npm run build:es", "build:es": "cross-env BABEL_ENV=es babel ./src -d es", "build:lib": "cross-env BABEL_ENV=cjs babel ./src -d lib", "build:umd": "webpack --define process.env.NODE_ENV=\"'production'\" --output-filename=umd/qhistory.js", "build:min": "webpack -p --optimize-minimize --output-filename=umd/qhistory.min.js", "prepublish": "npm run build", "test": "jest" }, "repository": { "type": "git", "url": "git://github.com/pshrmn/qhistory.git" }, "keywords": [ "history", "query", "search" ], "author": "<NAME>", "license": "MIT", "bugs": { "url": "https://github.com/pshrmn/qhistory/issues" }, "homepage": "https://github.com/pshrmn/qhistory#readme", "peerDependencies": { "history": ">=4.0.0" }, "dependencies": { "invariant": "^2.2.2" }, "devDependencies": { "babel-cli": "^6.22.2", "babel-core": "^6.22.1", "babel-jest": "^18.0.0", "babel-loader": "^6.2.10", "babel-plugin-transform-export-extensions": "^6.22.0", "babel-plugin-transform-object-rest-spread": "^6.22.0", "babel-preset-es2015": "^6.22.0", "cross-env": "^3.1.4", "history": "^5.0.0", "jest": "^18.1.0", "qs": "^6.3.0", "rimraf": "^2.5.4", "webpack": "^2.2.1" } } <|start_filename|>webpack.config.js<|end_filename|> const webpack = require('webpack') const path = require('path') module.exports = { context: path.join(__dirname, 'src'), entry: './index.js', output: { library: 'qhistory', libraryTarget: 'umd' }, externals: { history: { global: 'history', commonjs2: 'history', commonjs: 'history', amd: 'history' } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] } } <|start_filename|>tests/qhistory.spec.js<|end_filename|> import qhistory from '../src/index' import { createMemoryHistory } from 'history' import { stringify, parse } from 'qs' describe('qhistory', () => { describe('stringify & parse', () => { it('throws error if stringify is not a function', () => { const history = createMemoryHistory() expect(() => { const q = qhistory(history, undefined, parse) }).toThrow() }) it('throws error if parse is not a function', () => { const history = createMemoryHistory() expect(() => { const q = qhistory(history, stringify, undefined) }).toThrow() }) }) describe('query', () => { it('will be present on initial location', () => { const history = createMemoryHistory({ initialEntries: [{ pathname: '/first', search: '?second=third'}] }) const q = qhistory(history, stringify, parse) expect(q.location.query).toBeDefined() }) it('will be present after navigating', () => { const history = createMemoryHistory() const q = qhistory(history, stringify, parse) q.listen(({location}) => { expect(location.query).toEqual({ tooGoodToBe: 'true' }) expect(q.location.query).toEqual({ tooGoodToBe: 'true' }) expect(location.search).toBe('?tooGoodToBe=true') expect(q.location.search).toBe('?tooGoodToBe=true') }) q.push('/test?tooGoodToBe=true') }) it('will be an empty query object when there is no query/search', () => { const history = createMemoryHistory() const q = qhistory(history, stringify, parse) q.listen(({location}) => { expect(location.query).toBeInstanceOf(Object) expect(Object.keys(location.query).length).toBe(0) }) q.push('/test') }) }) describe('search', () => { it('will prefer query object over search string', () => { const history = createMemoryHistory() history.push = jest.fn(); const q = qhistory(history, stringify, parse) q.push({ pathname: '/somewhere', search: '?overRainbow=false', query: { overRainbow: true } }) expect(history.push).toHaveBeenCalledWith(expect.objectContaining({search: '?overRainbow=true'}), undefined) }) it('uses search if no query provided', () => { const history = createMemoryHistory() history.push = jest.fn(); const q = qhistory(history, stringify, parse) q.push({ pathname: '/somewhere', search: '?overRainbow=false' }) expect(history.push).toHaveBeenCalledWith(expect.objectContaining({search: '?overRainbow=false'}), undefined) }) it('sets search to empty string if no query/search', () => { const history = createMemoryHistory() history.push = jest.fn(); const q = qhistory(history, stringify, parse) q.push({ pathname: '/somewhere' }) expect(history.push).toHaveBeenCalledWith(expect.objectContaining({search: ''}), undefined) }) }) describe('push', () => { it('will set search string for location passed to actual history', () => { const history = createMemoryHistory() history.push = jest.fn(); const q = qhistory(history, stringify, parse) q.push({ pathname: '/somewhere', query: { overRainbow: true }}) expect(history.push).toHaveBeenCalledWith(expect.objectContaining({search: '?overRainbow=true'}), undefined) }) it('will call the history instance\'s push method', () => { const history = createMemoryHistory() const q = qhistory(history, stringify, parse) q.push({ pathname: '/somewhere', query: { overRainbow: true }}) expect(q.action).toBe('PUSH') }) }) describe('replace', () => { it('will set search string for location passed to actual history', () => { const history = createMemoryHistory() history.replace = jest.fn(); const q = qhistory(history, stringify, parse) q.replace({ pathname: '/somewhere', query: { overRainbow: true }}) expect(history.replace).toHaveBeenCalledWith(expect.objectContaining({search: '?overRainbow=true'}), undefined) }) it('will call the history instance\'s replace method', () => { const history = createMemoryHistory() history.replace = jest.fn(); const q = qhistory(history, stringify, parse) q.replace({ pathname: '/somewhere', query: { overRainbow: true }}) expect(history.replace).toHaveBeenCalled() }) }) describe('createHref', () => { it('uses the query object when creating a path from location', () => { const history = createMemoryHistory() const q = qhistory(history, stringify, parse) const location = { pathname: '/neighborhood', query: { beautifulDay: true } } expect(q.createHref(location)).toBe('/neighborhood?beautifulDay=true') }) }) })
pshrmn/qhistory
<|start_filename|>converter/locale-converter.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Locale to action sdk data converter class. */ const fs = require('fs'); const path = require('path'); const util = require('./util.js'); class LocaleConverter { /** * @param {!Object} options - Constructor options. * @param {string} options.locale - Sheet locale. * @param {string} options.dataDir - Webhook data dir. * @param {string} options.sdkDir - Action SDK root dir. */ constructor({locale, dataDir, sdkDir}) { this.locale = locale; this.dataDir = dataDir; this.sdkDir = sdkDir; } /** * Parse locale data and convert to appropriate sdk resource files. */ convert() { const filePath = path.join(__dirname, `./locales/${this.locale}.json`); if (!fs.existsSync(filePath)) { throw new Error(`${this.locale} data does not exists`); } const {actions, intents, types, settings} = util.readJsonFile(filePath); this.updateActions(actions); this.updateIntents(intents); this.updateTypes(types); this.updateSettings(settings); } /** * Update actions file in sdk. * @param {Object} actions - Actions data; */ updateActions(actions) { const filePath = path.join(__dirname, this.sdkDir, `actions/${this.locale}/actions.yaml`); util.writeYamlFile(filePath, actions); } /** * Update intents files in sdk. * @param {Array<Object>} intents - Intents data. */ updateIntents(intents) { for (const [intent, data] of Object.entries(intents)) { const filePath = path.join( __dirname, this.sdkDir, `custom/intents/${this.locale}/${intent}.yaml` ); util.writeYamlFile(filePath, data); } } /** * Update types files in sdk * @param {Array<Object>} types - Types data. */ updateTypes(types) { for (const [type, data] of Object.entries(types)) { const filePath = path.join( __dirname, this.sdkDir, `custom/types/${this.locale}/${type}.yaml` ); util.writeYamlFile(filePath, data); } } /** * Update settings file in sdk * @param {Object} settings - Settings data. */ updateSettings(settings) { const filePath = path.join(__dirname, this.sdkDir, `settings/${this.locale}/settings.yaml`); util.writeYamlFile(filePath, settings); } } module.exports = LocaleConverter; <|start_filename|>canvas/src/App.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'gsap'; import React, {Component, Fragment} from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import './App.css'; import ProgressBar from './component/progressbar'; import Basic from './component/basic'; import Typeface from './component/typeface'; import Option from './component/option'; import Transition from './component/transition'; import AssistantHost from './container/assistantHost'; import {setFrozen} from './action'; import {Template} from './constant'; const displayableTemplates = new Set([Template.INTRO, Template.QUESTION, Template.OUTCOME]); /** * @fileoverview Main PersonalityQuiz canvas entry-point. Expects input via the * assistant API to add and configure new slides. */ /** * @constructor */ class App extends Component { static propTypes = { slides: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number.isRequired, fields: PropTypes.shape({ template: PropTypes.string, data: PropTypes.shape({ header: PropTypes.string, body: PropTypes.string, small: PropTypes.string, background: PropTypes.shape({ portrait: PropTypes.string, landscape: PropTypes.string, }), image: PropTypes.shape({ portrait: PropTypes.string, landscape: PropTypes.string, }), }), suggestions: PropTypes.arrayOf( PropTypes.shape({ image: PropTypes.string, text: PropTypes.string, speech: PropTypes.string, }) ), }), }) ), progress: PropTypes.number, config: PropTypes.object, transition: PropTypes.any, }; static defaultProps = { slides: [], }; /** * Answer the current question. Sends the answer directly to the assistantHost * and stores the x/y position where a user clicked (used for the transition) * @param {string} answer * @param {x:number; y:number;} offset * @return {Promise} - Promise that resolves to sendTextQuery state. * @private */ answer(answer, offset) { if (offset && offset.hasOwnProperty('x')) { this.props.transition.offset = offset; } this.props.dispatch(setFrozen(true)); return window.interactiveCanvas .sendTextQuery(answer) .then((state) => { console.log({answer, state}); return state; }) .catch(console.error); } /** * Render the application */ render() { const {config, slides, progress, frozen} = this.props; return ( <Fragment> <AssistantHost /> <Typeface src={config.font} /> {slides && slides .filter((slide) => displayableTemplates.has(slide.fields.template)) .slice(-2) .map((slide) => { const {data = {}, template, suggestions} = slide.fields; const {header, body, small, image, background} = data; return ( <Basic key={slide.id} {...{template, header, body, small, image, background, frozen}} > {suggestions && suggestions.map((option, index) => ( <Option key={index} {...{index}} isRestart={template === Template.OUTCOME} value={option.speech} onClick={(answer, data) => this.answer(answer, data)} > <Fragment> {option.image && <img src={option.image} alt={option.text} />} {option.text} </Fragment> </Option> ))} </Basic> ); })} <Transition /> <ProgressBar progress={progress} /> </Fragment> ); } } export default connect((state) => ({ slides: state.slides, config: state.config, progress: state.progress, transition: state.transition, frozen: state.frozen, }))(App); <|start_filename|>canvas/config/webpackDevServer.config.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware'); const ignoredFiles = require('react-dev-utils/ignoredFiles'); const config = require('./webpack.config.dev'); const paths = require('./paths'); const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; const host = process.env.HOST || '0.0.0.0'; module.exports = (proxy, allowedHost) => { return { disableHostCheck: !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true', compress: true, clientLogLevel: 'none', contentBase: paths.appPublic, watchContentBase: true, hot: true, publicPath: config.output.publicPath, quiet: true, watchOptions: { ignored: ignoredFiles(paths.appSrc), }, https: protocol === 'https', host: host, overlay: false, historyApiFallback: { disableDotRule: true, }, public: allowedHost, proxy, before(app) { app.use(errorOverlayMiddleware()); }, }; }; <|start_filename|>canvas/src/component/transition/Transition.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React, {Component} from 'react'; import {setTransition} from '../../action'; import connect from 'react-redux/es/connect/connect'; import style from './Transition.css'; import fitRect from 'fit-rect'; import TweenLite from 'gsap/TweenLite'; import Easing from '../../util/easingPreset'; /** * @fileoverview The transition class; renders a Canvas element, and will draw * an animated masked circle on it. */ class Transition extends Component { state = {}; /** * @description options for initializing the animation */ options = { image: null, offset: null, }; /** * @description Size of the window */ size = {}; /** * description visibility of the canvas * @type {boolean} */ visible = false; /** * description contains the scale/x/y offset for fitting the image as cover. */ imageProps = null; radius = 0; /** * @description Progress of the transition * @type {number} */ progress = 0; /** * description alpha applied on circle on top of image. * @type {number} */ alpha = 0.5; /** * @description default options for initializing the animation */ static Defaults = { options: { offset: { x: window.innerWidth / 2, y: window.innerHeight / 2, }, }, }; componentDidMount() { this.props.dispatch(setTransition(this)); this.ctx = this.canvas.getContext('2d'); this.hide(); this.reset(); } /** * Reset the offset, and re-calculate the canvas size for good measure. Needed * at least once. */ reset() { this.resize(); this.offset = {...Transition.Defaults.options.offset}; } /** * Recalculate the canvas size based on the current window dimensions. */ resize() { this.size = { w: window.innerWidth * window.devicePixelRatio, h: window.innerHeight * window.devicePixelRatio, }; this.canvas.width = this.size.w; this.canvas.height = this.size.h; } /** * Show the canvas */ show() { this.canvas.style.opacity = 1; this.visible = true; } /** * Hide the canvas */ hide() { this.canvas.style.opacity = 0; this.visible = false; } /** * Start playing the transition animation * @returns TweenLite */ start() { this.resize(); this.transition = TweenLite.to(this, 0.8, { progress: 1, onStart: () => { this.show(); }, onUpdate: () => { this.draw(); }, ease: Easing.standard, }); return this.transition; } /** * Called when the animation is done and ready to be hidden. */ end() { this.hide(); this.progress = 0; } /** * The "requestAnimationFrame" type drawing; draws data to the canvas using * the current tween progress. */ draw() { if (!this.ctx || !this.options.image || !this.imageProps) return; this.ctx.clearRect(0, 0, this.size.w, this.size.h); this.ctx.save(); // Draw Image this.ctx.drawImage( this.options.image, this.imageProps[0], this.imageProps[1], this.imageProps[2], this.imageProps[3] ); // Paint alpha this.ctx.fillStyle = `rgba(255, 255, 255, ${this.alpha - this.progress * this.alpha})`; this.ctx.fillRect(0, 0, this.size.w, this.size.h); this.ctx.fill(); this.ctx.globalCompositeOperation = 'destination-in'; // Reset alpha this.ctx.fillStyle = `rgba(255, 255, 255, 1)`; // Draw Circle for clipping this.ctx.arc( this.options.offset.x, this.options.offset.y, this.radius * this.progress, 0, Math.PI * 2, false ); this.ctx.fill(); this.ctx.restore(); } /** * Set an image URL * @param {string} url */ set image(url) { this.options.image = url; /** * Calculate the x/y/w/h of how the image should be placed, to replicate the * browser-native "cover" background-sizing. */ const rect = [0, 0, this.options.image.naturalWidth, this.options.image.naturalHeight]; const target = [0, 0, this.size.w, this.size.h]; this.imageProps = fitRect(rect, target, 'cover'); } /** * Sets the start-point of the animation * @param {number} x * @param {number} y */ set offset({x, y}) { this.options.offset = { x: x * window.devicePixelRatio, y: y * window.devicePixelRatio, }; this.resize(); // Calculate the total radius we should animate out to const maxX = Math.max( Math.abs(0 - this.options.offset.x), Math.abs(this.size.w - this.options.offset.x) ); const maxY = Math.max( Math.abs(0 - this.options.offset.y), Math.abs(this.size.h - this.options.offset.y) ); this.radius = Math.sqrt(maxX ** 2 + maxY ** 2); } render() { return <canvas className={style.root} ref={(el) => (this.canvas = el)} />; } } export default connect()(Transition); <|start_filename|>canvas/src/component/basic/Basic.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React, {Component, Fragment} from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {TimelineLite} from 'gsap'; import style from './Basic.css'; import preloadImage from '../../util/preloadImage'; import orientation from '../../util/orientation'; import Background from '../background'; import {validateBackground} from '../../util/backgroundOptions'; import {setFrozen} from '../../action'; import {Template} from '../../constant'; /** * @fileoverview A relatively generic "slide" for the presenter. It can house * any components by injecting them as children, and will animate once it has * loaded all required assets. */ class Basic extends Component { static propTypes = { template: PropTypes.string, header: PropTypes.string, body: PropTypes.string, small: PropTypes.string, background: PropTypes.shape({ landscape: PropTypes.string, portrait: PropTypes.string, }), image: PropTypes.shape({ landscape: PropTypes.string, portrait: PropTypes.string, }), config: PropTypes.object, transition: PropTypes.any, children: PropTypes.arrayOf(PropTypes.node), frozen: PropTypes.bool, }; state = {autoScroll: true}; async componentDidMount() { const tl = this.setupTimeline(); const backgroundUrl = await validateBackground(this.props.background); this.setState({background: backgroundUrl}); this.props.transition.image = await preloadImage(backgroundUrl); tl.play(); this.startAutoScroll(); } componentWillUnmount() { this.stopAutoScroll(); } startAutoScroll() { if (this.smallContainer && this.state.autoScroll) { setTimeout(this.stepAutoScroll.bind(this), 10000); } } stopAutoScroll() { this.setState({autoScroll: false}); } stepAutoScroll() { if (this.smallContainer && this.state.autoScroll) { const {offsetHeight, scrollTop, scrollHeight} = this.smallContainer; if (offsetHeight + scrollTop >= scrollHeight) { this.stopAutoScroll(); } else { requestAnimationFrame(() => { this.smallContainer.scrollBy(0, 1); const delay = orientation() === 'portrait' ? 100 : 55; setTimeout(this.stepAutoScroll.bind(this), delay); }); } } } /** * Generate all the "in" animations. * @return {TimelineLite} */ setupTimeline() { const {transition} = this.props; const tl = new TimelineLite({paused: true}); // Start the circle-masking animation tl.add(transition.start()); // Toggle visibility of this element tl.from(this.root, 0.01, {opacity: 0}); // Hide the circle-masking animation tl.add(() => transition.end()); tl.add('text', '+=0.0'); tl.add('buttons', '+=0.4'); tl.add(() => this.props.dispatch(setFrozen(false))); return tl; } render() { const {template, config, header, body, small, image, children, frozen} = this.props; const {background} = this.state; const isIntroSlide = template === Template.INTRO; const isOutcomeSlide = template === Template.OUTCOME; const isQuestionSlide = template === Template.QUESTION; const headerColor = isIntroSlide ? config.introTitleColor : config.textColor; const bodyColor = isIntroSlide ? config.introSubtitleColor : config.textColor; const smallColor = isIntroSlide ? config.introSubtitleColor : config.textColor; return ( <div className={[style.root, frozen ? style.frozen : null].join(' ')} ref={(el) => (this.root = el)} onTouchStart={this.stopAutoScroll.bind(this)} onClick={this.stopAutoScroll.bind(this)} onWheel={this.stopAutoScroll.bind(this)} > <Background src={background} /> <div className={[ style.container, isOutcomeSlide ? style.outcomeContainer : null, isQuestionSlide ? style.questionContainer : null, ].join(' ')} > {image && image[orientation()] && ( <div className={style.imageContainer}> <picture> <img src={image[orientation()]} alt={header} /> </picture> </div> )} <div className={[ style.textContainer, isIntroSlide ? style.introTextContainer : null, isOutcomeSlide ? style.outcomeTextContainer : null, ].join(' ')} > {header && ( <h1 className={style.header} ref={(el) => (this.header = el)} style={{color: headerColor}} > {header.split('\n').map((item, index) => ( <Fragment key={index}> {item} <br /> </Fragment> ))} </h1> )} {body && ( <h2 className={[style.body, isOutcomeSlide ? style.outcomeBody : null].join(' ')} ref={(el) => (this.body = el)} style={{color: bodyColor}} > {body.split('\n').map((item, index) => ( <Fragment key={index}> {item} <br /> </Fragment> ))} </h2> )} {isOutcomeSlide && ( <div className={style.smallContainer} ref={(el) => (this.smallContainer = el)}> <p className={style.small} ref={(el) => (this.small = el)} style={{color: smallColor}} > {small && small.split('\n').map((item, index) => ( <Fragment key={index}> {item} <br /> </Fragment> ))} </p> {children && isOutcomeSlide && ( <div className={[ style.childrenContainer, isOutcomeSlide ? style.outcomeChildrenContainer : null, ].join(' ')} ref={(el) => (this.childrenContainer = el)} > {children} </div> )} </div> )} </div> {children && !isOutcomeSlide && ( <div className={[ style.childrenContainer, isQuestionSlide ? style.questionChildrenContainer : null, ].join(' ')} ref={(el) => (this.childrenContainer = el)} > {children} </div> )} </div> </div> ); } } export default connect((state) => ({ config: state.config, transition: state.transition, frozen: state.frozen, }))(Basic); <|start_filename|>functions/data/en/quiz_intro.json<|end_filename|> [ { "displayed_introduction": "I love you, a whole lot. In fact, I’d say that we’re a pretty dynamic duo. But I can’t quite decide which one...Want to answer a few questions to help me pick which Dreamteam we most resemble?" }, { "displayed_introduction": "I love you, a whole lot.Together, we’re as winning as one of the world’s all-time great teams. \nWant to answer a few quick questions, so I can tell you exactly which one?" }, { "displayed_introduction": "I love you, a whole lot. But let's get more specific. Want to answer a\nfew quick questions so we can figure out our special kind of bond?" }, { "displayed_introduction": "I love you, a whole lot. You’re so dreamy, I’m surprised that it doesn’t put me into sleep mode. Can I ask you a few questions to help me figure out which dreamteam we’re most like?" } ] <|start_filename|>functions/app.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const {conversation} = require('@assistant/conversation'); const config = require('./config.js'); const {Action, Alias, Prompt} = require('./constant.js'); const util = require('./util'); const debug = require('./analytics/debug.js'); const logger = require('./analytics/logger.js'); const CanvasBuilder = require('./canvas-builder.js'); const ConvHelper = require('./conv-helper.js'); const Fulfillment = require('./fulfillment.js'); /** * @module app * @desc ConversationV3 App Setup and Routing */ /** * Init data constructor, output will be set to conv.session.params.data on initial request. * @return {Object<string, any>} - Init data. */ const initDataCtor = () => ({ quizSettings: { [Alias.QUIZ_SETTINGS.PLAY_INTRO_CONFIRMATION]: config.PLAY_INTRO_CONFIRMATION_DEFAULT, [Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ]: config.QUESTIONS_PER_QUIZ_DEFAULT, [Alias.QUIZ_SETTINGS.INTRO_TITLE]: config.INTRO_TITLE_DEFAULT, [Alias.QUIZ_SETTINGS.INTRO_SUBTITLE]: config.INTRO_SUBTITLE_DEFAULT, [Alias.QUIZ_SETTINGS.INTRO_TITLE_COLOR]: config.INTRO_TITLE_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.INTRO_SUBTITLE_COLOR]: config.INTRO_SUBTITLE_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.START_BUTTON_TEXT]: config.START_BUTTON_TEXT_DEFAULT, [Alias.QUIZ_SETTINGS.RESTART_BUTTON_TEXT]: config.RESTART_BUTTON_TEXT_DEFAULT, [Alias.QUIZ_SETTINGS.TEXT_COLOR]: config.TEXT_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.FONT]: config.FONT_DEFAULT, [Alias.QUIZ_SETTINGS.BUTTON_NORMAL_TEXT_COLOR]: config.BUTTON_NORMAL_TEXT_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.BUTTON_NORMAL_BACKGROUND_COLOR]: config.BUTTON_NORMAL_BACKGROUND_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.BUTTON_SELECTED_TEXT_COLOR]: config.BUTTON_SELECTED_TEXT_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.BUTTON_SELECTED_BACKGROUND_COLOR]: config.BUTTON_SELECTED_BACKGROUND_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.PROGRESS_BAR_BACKGROUND_COLOR]: config.PROGRESS_BAR_BACKGROUND_COLOR_DEFAULT, [Alias.QUIZ_SETTINGS.PROGRESS_BAR_FILL_COLOR]: config.PROGRESS_BAR_FILL_COLOR_DEFAULT, }, count: 0, limit: config.MAX_QUESTIONS_PER_QUIZ, questions: [], traitToWeight: {}, }); /** * Device capabilities to conv field lookup. */ const capabilityLookup = { RICH_RESPONSE: 'hasScreen', SPEECH: 'hasAudio', LONG_FORM_AUDIO: 'hasLongFormAudio', WEB_LINK: 'hasWebBrowser', INTERACTIVE_CANVAS: 'hasInteractiveCanvas', }; /** * ConversationV3 app middleware handler. * @param {ConversationV3} conv - ConversationV3 instance. */ const middleware = (conv) => { // Set capability helper props on conv. util.object.forOwn(capabilityLookup, (prop, capability) => { conv[prop] = conv.device.capabilities.includes(capability); }); // Add init data to conv.session.params.data on initial request. if (conv.session.params.data == null) { conv.session.params.data = Object.assign({}, initDataCtor()); } // Attach a ConvHelper instance to conv.$helper conv.$helper = ConvHelper.create(conv); // Attach a CanvasBuilder instance to conv.$immersive conv.$immersive = CanvasBuilder.create(conv.hasInteractiveCanvas, { url: conv.$helper.isNewConversation() ? config.IMMERSIVE_URL : null, }); }; /** * ConversationV3 app error handler. * @param {ConversationV3} conv - ConversationV3 instance. * @param {Error} error - Error object. * @return {?Promise} - Promise that resolve to error handler response. */ const errorHandler = async (conv, error) => { debug.setDebugInfo(conv, error); logger.error(`An error has occurred handling [${conv.handler.name}]: `, { labels: {execution_id: conv.headers['function-execution-id']}, stack: error.stack, conv: util.object.stringify(conv), }); // Reset canvas response builder to default initial state. conv.$immersive = CanvasBuilder.create(conv.hasInteractiveCanvas, { url: conv.$helper.isNewConversation() ? config.IMMERSIVE_URL : null, }); try { await conv.$helper.closeWithPrompt(Prompt.GENERIC_MAX_NO_MATCH); } catch (err) { err.labels = {execution_id: conv.headers['function-execution-id']}; logger.error(`Failed to follow up with a fallback error response: `, err); conv.scene.next = {name: 'actions.scene.END_CONVERSATION'}; conv.add('An unknown error occurred.'); } }; // Instantiates the ConversationV3 app. const app = conversation({debug: false}); // App Middleware. app.middleware(middleware); // Map fulfillment handlers with actions const fulfillment = Fulfillment.create(); for (const action of Object.values(Action)) { if (typeof fulfillment[action] !== 'function') continue; app.handle(action, async (conv, ...args) => { await fulfillment[action](conv, ...args); debug.setDebugInfo(conv); }); } // Handles uncaught errors. app.catch(errorHandler); module.exports = app; <|start_filename|>functions/__tests__/index.test.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const chai = require('chai'); const {expect} = chai; const functionHandler = require('../index.js'); const {FUNCTION_NAME, FUNCTION_VERSION} = require('../config.js'); describe('index', function() { it('exports function name with current version from config', function() { expect(functionHandler).to.have.ownProperty(`${FUNCTION_NAME}_${FUNCTION_VERSION}`); }); }); <|start_filename|>functions/util/__tests__/ssml.test.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const chai = require('chai'); const {expect} = chai; const ssml = require('../ssml.js'); const config = require('../../config.js'); const {TtsMark} = require('../../constant.js'); describe('util - ssml', function() { describe('sanitize', function() { it('returns a string', function() { const output = ssml.sanitize``; expect(output).to.be.a('string'); }); it('replaces & symbol with &amp;', function() { const output = ssml.sanitize`${'&'}`; expect(output).to.eql('&amp;'); }); it('replaces < symbol with &lt;', function() { const output = ssml.sanitize`${'<'}`; expect(output).to.eql('&lt;'); }); it('replaces > symbol with &gt;', function() { const output = ssml.sanitize`${'>'}`; expect(output).to.eql('&gt;'); }); it('replaces " symbol with &quot;', function() { const output = ssml.sanitize`${'"'}`; expect(output).to.eql('&quot;'); }); it('trims whitespace around <speak> tags', function() { const output = ssml.sanitize` <speak></speak> `; expect(output).to.eql('<speak></speak>'); }); it('removes leading whitespace before <speak> tag per line', function() { const output = ssml.sanitize` <speak> ${'input'} </speak> `; expect(output).to.eql('<speak>\n input\n</speak>'); }); it('inserts multiple expressions into template literal output', function() { const output = ssml.sanitize`<speak>${'Hello'} ${'World'}</speak>`; expect(output).to.eql('<speak>Hello World</speak>'); }); }); describe('merge', function() { const parts = ['<speak>a</speak>', '<speak>b</speak>']; const breakTime = 0; it('returns a string', function() { const output = ssml.merge(parts, breakTime); expect(output).to.be.a('string'); }); it('surrounds by <speak> tag', function() { const output = ssml.merge(['a', 'b'], breakTime); expect(output).to.eql('<speak>a b</speak>'); }); it('trims whitespace for input strings', function() { const output = ssml.merge([' test '], breakTime); expect(output).to.eql('<speak>test</speak>'); }); it('filters trimmed empty parts', function() { const output = ssml.merge([' ', ' ', 'test', ' '], breakTime); expect(output).to.eql('<speak>test</speak>'); }); it('separate input strings by a whitespace', function() { const output = ssml.merge(['a', 'b'], breakTime); expect(output).to.eql('<speak>a b</speak>'); }); it('removes inner <speak> tags from input strings', function() { const output = ssml.merge(parts, breakTime); expect(output).to.eql('<speak>a b</speak>'); }); it('Add break tag if specify breakTime argument greater than 0', function() { const output = ssml.merge(parts, 5); expect(output).to.eql('<speak>a <break time="5ms"/>b</speak>'); }); it('Use default break time from config if second argument is not specified', function() { const output = ssml.merge(parts); expect(output).to.eql(`<speak>a <break time="${config.SSML_BREAK_TIME}ms"/>b</speak>`); }); }); describe('mergeWithMark', function() { const parts = ['<speak>a</speak>', '<speak>b</speak>']; const markName = 'SWITCH'; const breakTime = 500; it('returns a string', function() { const output = ssml.mergeWithMark(parts, markName, breakTime); expect(output).to.be.a('string'); }); it('surrounds by <speak> tag', function() { const output = ssml.mergeWithMark(['a', 'b'], markName, breakTime); expect(output).to.eql( `<speak>a<break time="${breakTime}ms"/><mark name="${markName}_1"/> b</speak>` ); }); it('trims whitespace for input strings', function() { const output = ssml.mergeWithMark([' a ', ' b '], markName, breakTime); expect(output).to.eql( `<speak>a<break time="${breakTime}ms"/><mark name="${markName}_1"/> b</speak>` ); }); it('filters trimmed empty parts', function() { const output = ssml.mergeWithMark([' ', ' ', ' a ', ''], markName, breakTime); expect(output).to.eql(`<speak>a</speak>`); }); it('removes inner <speak> tags from input strings', function() { const output = ssml.mergeWithMark( ['<speak>a</speak>', '<speak>b</speak>'], markName, breakTime ); expect(output).to.eql( `<speak>a<break time="${breakTime}ms"/><mark name="${markName}_1"/> b</speak>` ); }); it('increment custom mark name for each additional interval', function() { const output = ssml.mergeWithMark(['a', 'b', 'c'], markName, breakTime); expect(output).to.eql( `<speak>a<break time="${breakTime}ms"/><mark name="${markName}_1"/> b` + `<break time="${breakTime}ms"/><mark name="${markName}_2"/> c</speak>` ); }); it('Use default markName and breakTime if not provided', function() { const output = ssml.mergeWithMark(['a', 'b']); expect(output).to.eql( `<speak>a<break time="${config.SSML_BREAK_TIME}ms"/><mark name="${ TtsMark.FLIP }_1"/> b</speak>` ); }); }); describe('clean', function() { it('returns a string', function() { const output = ssml.clean(''); expect(output).to.be.a('string'); }); it('removes whitespace around < and > symbol', function() { const output = ssml.clean(' < speak > a < /speak > '); expect(output).to.eql('<speak>a</speak>'); }); it('removes extra whitespace symbol', function() { const output = ssml.clean(' < speak > a b < /speak > '); expect(output).to.eql('<speak>a b</speak>'); }); it('removes emoji symbols', function() { const output = ssml.clean(' < speak> \u{1f9ff} abc \u{1f300} < /speak> '); expect(output).to.eql('<speak>abc</speak>'); }); it('escapes special characters if input is not surrounded by <speak> tag', function() { const output = ssml.clean('"1 + 1 > 1"'); expect(output).to.eql('<speak>&quot;1 + 1 &gt; 1&quot;</speak>'); }); it('returns empty string if no content inside ssml speak tag', function() { const output = ssml.clean(' < speak > \u{1f9ff} < /speak > '); expect(output).to.eql(''); }); it('returns empty string if no content as raw string', function() { const output = ssml.clean(' \u{1f9ff} '); expect(output).to.eql(''); }); }); describe('escape', function() { it('returns a string', function() { const output = ssml.escape(''); expect(output).to.be.a('string'); }); it('escapes special ssml characters', function() { const output = ssml.escape('\'a\' > "b" < &'); expect(output).to.eql('&apos;a&apos; &gt; &quot;b&quot; &lt; &amp;'); }); }); }); <|start_filename|>canvas/src/component/option/Option.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import Easing from '../../util/easingPreset'; import {TweenLite} from 'gsap'; import style from './Option.css'; import {setOptionActive} from '../../action'; /** * @fileoverview A Button class. Includes the "ripple" selected-state. * @example * ```js * <Option value="Yes" onClick={(value, data) => this.answer(value, data)}> * { "Yes" } * </Option> * ``` * * Note that the "data" argument sent in the onClick handler, returns an object * of shape: { x: number; y: number; }, to indicate where the user has clicked * relative to the window. */ class Option extends Component { static propTypes = { onClick: PropTypes.func.isRequired, children: PropTypes.node, value: PropTypes.string, index: PropTypes.number, option: PropTypes.number, isRestart: PropTypes.bool, }; state = { active: false, }; componentDidUpdate() { if (this.state.active === false && this.props.index === this.props.option) { this.activate(); } else if (this.state.active === true && this.props.option === null) { this.deactivate(); } } /** * Activate the "down" state. Triggers the ripple-effect. * @param {SyntheticEvent} [e] * @param {boolean} bubble - True to indicate user clicked event. */ activate( e = { nativeEvent: { offsetX: this.root.clientWidth * 0.5, offsetY: this.root.clientHeight * 0.5, clientX: this.root.getBoundingClientRect().x + this.root.clientWidth * 0.5, clientY: this.root.getBoundingClientRect().y + this.root.clientHeight * 0.5, }, }, bubble = false ) { this.setState({active: true}); this.props.dispatch(setOptionActive(this.props.index)); const {offsetX, offsetY, clientX, clientY} = e.nativeEvent; const {clientWidth, clientHeight} = this.root; // Calculate max radius the ripple needs to be const x = Math.round((offsetX / clientWidth) * 100); const y = Math.round((offsetY / clientHeight) * 100); const radius = Math.sqrt( Math.max(offsetX, Math.abs(clientWidth - offsetX)) ** 2 + Math.max(offsetY, Math.abs(clientHeight - offsetY)) ** 2 ); // Animate the ripple TweenLite.fromTo( this.ripple, 0.64, { webkitClipPath: `circle(20px at ${x}% ${y}%)`, clipPath: `circle(20px at ${x}% ${y}%)`, }, { webkitClipPath: `circle(${radius}px at ${x}% ${y}%)`, clipPath: `circle(${radius}px at ${x}% ${y}%)`, ease: Easing.decelerate, } ); TweenLite.to(this.root, 0.2, { color: this.props.config.buttonSelectedTextColor, }); /** * The onClick callback. The value is the string set in the Option.value * parameter. The second object is of shape {x:number; y:number;}, and * indicated where on-screen a user has clicked. */ if (bubble === true) { this.props.onClick(this.props.value, { x: clientX, y: clientY, }); } } /** * Undo the "down"-state. */ deactivate() { this.setState({active: false}); /* TweenLite.to(this.ripple, 0.2, {opacity: 0}); TweenLite.to(this.root, 0.2, { color: this.props.config.buttonNormalTextColor, });*/ } /** * Render the element * @returns {*} */ render() { const {config, children, isRestart} = this.props; return ( <button className={[style.root, isRestart ? style.restartRoot : null].join(' ')} ref={(el) => (this.root = el)} style={{ color: config.buttonNormalTextColor, backgroundColor: config.buttonNormalBackgroundColor, }} onClick={(e) => { if (!this.state.active && !this.props.frozen) { this.activate(e, true); } }} > <div className={style.ripple} ref={(el) => (this.ripple = el)} style={{backgroundColor: config.buttonSelectedBackgroundColor}} /> <div className={style.text}>{children}</div> </button> ); } } export default connect((state) => ({ config: state.config, option: state.option, frozen: state.frozen, }))(Option); <|start_filename|>functions/constant.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; /** * @module constant * @desc Common enumeration constants. */ /** * Action names from ConversationV3 handlers. * @readonly */ const Action = { LOAD_SETTINGS: 'LOAD_SETTINGS', SETUP_QUIZ: 'SETUP_QUIZ', START_SKIP_CONFIRMATION: 'START_SKIP_CONFIRMATION', START_CONFIRMATION: 'START_CONFIRMATION', START_YES: 'START_YES', START_NO: 'START_NO', START_HELP: 'START_HELP', START_REPEAT: 'START_REPEAT', START_NO_MATCH_1: 'START_NO_MATCH_1', START_NO_MATCH_2: 'START_NO_MATCH_2', START_NO_INPUT_1: 'START_NO_INPUT_1', START_NO_INPUT_2: 'START_NO_INPUT_2', QUESTION_REPEAT: 'QUESTION_REPEAT', ANSWER: 'ANSWER', ANSWER_ORDINAL: 'ANSWER_ORDINAL', ANSWER_BOTH_OR_NONE: 'ANSWER_BOTH_OR_NONE', ANSWER_HELP: 'ANSWER_HELP', ANSWER_SKIP: 'ANSWER_SKIP', ANSWER_NO_MATCH_1: 'ANSWER_NO_MATCH_1', ANSWER_NO_MATCH_2: 'ANSWER_NO_MATCH_2', ANSWER_MAX_NO_MATCH: 'ANSWER_MAX_NO_MATCH', ANSWER_NO_INPUT_1: 'ANSWER_NO_INPUT_1', ANSWER_NO_INPUT_2: 'ANSWER_NO_INPUT_2', ANSWER_MAX_NO_INPUT: 'ANSWER_MAX_NO_INPUT', RESTART_CONFIRMATION: 'RESTART_CONFIRMATION', RESTART_YES: 'RESTART_YES', RESTART_NO: 'RESTART_NO', RESTART_REPEAT: 'RESTART_REPEAT', PLAY_AGAIN_YES: 'PLAY_AGAIN_YES', PLAY_AGAIN_NO: 'PLAY_AGAIN_NO', PLAY_AGAIN_REPEAT: 'PLAY_AGAIN_REPEAT', QUIT_CONFIRMATION: 'QUIT_CONFIRMATION', QUIT_YES: 'QUIT_YES', QUIT_NO: 'QUIT_NO', QUIT_REPEAT: 'QUIT_REPEAT', GENERIC_NO_MATCH: 'GENERIC_NO_MATCH', GENERIC_MAX_NO_MATCH: 'GENERIC_MAX_NO_MATCH', GENERIC_NO_INPUT: 'GENERIC_NO_INPUT', GENERIC_MAX_NO_INPUT: 'GENERIC_MAX_NO_INPUT', }; /** * ConversationV3 intents. * @readonly */ const Intent = { MAIN: 'actions.intent.MAIN', PLAY_GAME: 'actions.intent.PLAY_GAME', NO_MATCH: 'actions.intent.NO_MATCH', NO_INPUT: 'actions.intent.NO_INPUT', CANCEL: 'actions.intent.CANCEL', HELP: 'Help', YES: 'Yes', NO: 'No', ORDINAL_CHOICE: 'OrdinalChoice', BOTH_OR_NONE: 'BothOrNone', QUIT: 'Quit', REPEAT: 'Repeat', RESTART: 'Restart', SKIP: 'Skip', START: 'Start', }; /** * ConversationV3 types. * @readonly */ const Type = { ANSWER: 'answer', COUNT: 'count', }; /** * Enumerators used for answer type. * @readonly */ const Answer = { POSITIVE: 'positive', NEGATIVE: 'negative', FIRST: 'first', SECOND: 'second', }; /** * Interactive Canvas response template slide types. * @readonly */ const Template = { /** Question and answer slide */ QUESTION: 'template.question', /** Intro slide */ INTRO: 'template.intro', /** Outcome slide */ OUTCOME: 'template.outcome', /** Only say the ssml, no displayed slide */ SAY: 'template.say', /** Tell the ssml, and close the session */ TELL: 'template.tell', }; /** * Interactive Canvas response template render actions. * @readonly */ const TemplateAction = { /** Reset the UI state */ RESET: 'template.action.reset', /** Freeze UI controls */ FREEZE: 'template.action.freeze', /** Set positive choice button to active */ ACTIVE_0: 'template.action.positive', /** Set negative choice button to active */ ACTIVE_1: 'template.action.negative', }; /** * SSML TTS status marks from Interactive Canvas API. * @readonly */ const TtsMark = { START: 'START', END: 'END', ERROR: 'ERROR', FLIP: 'FLIP', }; /** * Conversation environments * @readonly */ const ConvEnv = { PREVIEW: 'preview', PRODUCTION: 'production', }; /** * Spreadsheet tab Types * Array: each row is an independent doc * Dictionary: rows are grouped together by a key column * @readonly */ const TabType = { ARRAY: 'ARRAY', DICTIONARY: 'DICTIONARY', }; /** * Type override mode * @readonly */ const TypeOverrideMode = { TYPE_MERGE: 'TYPE_MERGE', TYPE_REPLACE: 'TYPE_REPLACE', TYPE_UNSPECIFIED: 'TYPE_UNSPECIFIED', }; /** * Validation schema types * @readonly */ const SchemaType = { CUSTOM: 'CUSTOM', BOOLEAN: 'BOOLEAN', INTEGER: 'INTEGER', FLOAT: 'FLOAT', SSML: 'SSML', STRING: 'STRING', STRING_LIST: 'STRING_LIST', IMAGE: 'IMAGE', URL: 'URL', GOOGLE_FONT: 'GOOGLE_FONT', COLOR_HEX: 'COLOR_HEX', DATE: 'DATE', }; /** * Alias keys for Firestore documents. Fulfillment will refer fetched doc by alias keys. * @readonly */ const Alias = { QUIZ_INTRO: { DISPLAYED_INTRO: 'text', SPOKEN_INTRO: 'speech', BACKGROUND_LANDSCAPE_IMAGE: 'backgroundLandscape', BACKGROUND_PORTRAIT_IMAGE: 'backgroundPortrait', }, QUIZ_Q_A: { PERSONALITY_TRAIT: 'trait', DISPLAYED_QUESTION: 'questionText', SPOKEN_QUESTION: 'questionSpeech', POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS: 'positiveAnswers', NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS: 'negativeAnswers', POSITIVE_RESPONSE_SPOKEN_FOLLOWUP: 'positiveFollowupSpeech', POSITIVE_RESPONSE_DISPLAYED_FOLLOWUP: 'positiveFollowupText', NEGATIVE_RESPONSE_SPOKEN_FOLLOWUP: 'negativeFollowupSpeech', NEGATIVE_RESPONSE_DISPLAYED_FOLLOWUP: 'negativeFollowupText', BACKGROUND_LANDSCAPE_IMAGE: 'backgroundLandscape', BACKGROUND_PORTRAIT_IMAGE: 'backgroundPortrait', POSITIVE_ANSWER_IMAGE: 'positiveAnswerImage', NEGATIVE_ANSWER_IMAGE: 'negativeAnswerImage', }, QUIZ_OUTCOMES: { DISPLAYED_OUTCOME: 'text', SPOKEN_OUTCOME: 'speech', POSITIVE_OUTCOME_TRAITS: 'positiveTraits', NEGATIVE_OUTCOME_TRAITS: 'negativeTraits', TITLE: 'title', HORIZONTAL_IMAGE: 'imageLandscape', VERTICAL_IMAGE: 'imagePortrait', BACKGROUND_LANDSCAPE_IMAGE: 'backgroundLandscape', BACKGROUND_PORTRAIT_IMAGE: 'backgroundPortrait', }, QUIZ_SETTINGS: { PLAY_INTRO_CONFIRMATION: 'playIntroConfirmation', QUESTIONS_PER_QUIZ: 'questionsPerQuiz', INTRO_TITLE: 'introTitle', INTRO_SUBTITLE: 'introSubtitle', INTRO_TITLE_COLOR: 'introTitleColor', INTRO_SUBTITLE_COLOR: 'introSubtitleColor', START_BUTTON_TEXT: 'startButtonText', RESTART_BUTTON_TEXT: 'restartButtonText', TEXT_COLOR: 'textColor', FONT: 'font', BUTTON_NORMAL_TEXT_COLOR: 'buttonNormalTextColor', BUTTON_NORMAL_BACKGROUND_COLOR: 'buttonNormalBackgroundColor', BUTTON_SELECTED_TEXT_COLOR: 'buttonSelectedTextColor', BUTTON_SELECTED_BACKGROUND_COLOR: 'buttonSelectedBackgroundColor', PROGRESS_BAR_BACKGROUND_COLOR: 'progressBarBackgroundColor', PROGRESS_BAR_FILL_COLOR: 'progressBarFillColor', }, GENERAL_PROMPTS: { DISPLAYED_FLOW: 'text', SPOKEN_FLOW: 'speech', }, }; /** * General prompts choices. * @readonly */ const Prompt = { INTRO_CONFIRMATION: 'INTRO_CONFIRMATION', INTRO_CONFIRMATION_POSITIVE: 'INTRO_CONFIRMATION_POSITIVE', INTRO_CONFIRMATION_NEGATIVE: 'INTRO_CONFIRMATION_NEGATIVE', INTRO_POSITIVE_RESPONSE: 'INTRO_POSITIVE_RESPONSE', INTRO_NEGATIVE_RESPONSE: 'INTRO_NEGATIVE_RESPONSE', INTRO_NO_MATCH_1: 'INTRO_NO_MATCH_1', INTRO_NO_MATCH_2: 'INTRO_NO_MATCH_2', INTRO_NO_INPUT_1: 'INTRO_NO_INPUT_1', INTRO_NO_INPUT_2: 'INTRO_NO_INPUT_2', START_REPEAT: 'START_REPEAT', START_HELP: 'START_HELP', TRANSITIONS_REGULAR: 'TRANSITIONS_REGULAR', TRANSITIONS_FINAL: 'TRANSITIONS_FINAL', QUESTION_REPEAT: 'QUESTION_REPEAT', ANSWER_HELP: 'ANSWER_HELP', ANSWER_NO_MATCH_1: 'ANSWER_NO_MATCH_1', ANSWER_NO_MATCH_2: 'ANSWER_NO_MATCH_2', ANSWER_MAX_NO_MATCH: 'ANSWER_MAX_NO_MATCH', ANSWER_NO_INPUT_1: 'ANSWER_NO_INPUT_1', ANSWER_NO_INPUT_2: 'ANSWER_NO_INPUT_2', ANSWER_MAX_NO_INPUT: 'ANSWER_MAX_NO_INPUT', OUTCOME_INTRO: 'OUTCOME_INTRO', END_OF_GAME: 'END_OF_GAME', END_OF_GAME_PLAY_AGAIN_YES: 'END_OF_GAME_PLAY_AGAIN_YES', END_OF_GAME_PLAY_AGAIN_NO: 'END_OF_GAME_PLAY_AGAIN_NO', RESTART_CONFIRMATION: 'RESTART_CONFIRMATION', RESTART_YES_RESPONSE: 'RESTART_YES_RESPONSE', RESTART_NO_RESPONSE: 'RESTART_NO_RESPONSE', SKIP: 'SKIP', QUIT_CONFIRMATION: 'QUIT_CONFIRMATION', CONTINUE_TO_PLAY: 'CONTINUE_TO_PLAY', ACKNOWLEDGE_QUIT: 'ACKNOWLEDGE_QUIT', GENERIC_NO_MATCH: 'GENERIC_NO_MATCH', GENERIC_MAX_NO_MATCH: 'GENERIC_MAX_NO_MATCH', GENERIC_NO_INPUT: 'GENERIC_NO_INPUT', GENERIC_MAX_NO_INPUT: 'GENERIC_MAX_NO_INPUT', QUESTION_OR: 'QUESTION_OR', GENERIC_YES: 'GENERIC_YES', GENERIC_NO: 'GENERIC_NO', GENERIC_NO_MATCH_NONANSWER: 'GENERIC_NO_MATCH_NONANSWER', }; module.exports = { Action, Intent, Type, Answer, Template, TemplateAction, TtsMark, ConvEnv, TabType, TypeOverrideMode, SchemaType, Alias, Prompt, }; <|start_filename|>canvas/config/env.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const fs = require('fs'); const path = require('path'); const paths = require('./paths'); delete require.cache[require.resolve('./paths')]; const NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV) { throw new Error('The NODE_ENV environment variable is required but was not specified.'); } let dotenvFiles = [ `${paths.dotenv}.${NODE_ENV}.local`, `${paths.dotenv}.${NODE_ENV}`, NODE_ENV !== 'test' && `${paths.dotenv}.local`, paths.dotenv, ].filter(Boolean); dotenvFiles.forEach((dotenvFile) => { if (fs.existsSync(dotenvFile)) { require('dotenv-expand')( require('dotenv').config({ path: dotenvFile, }) ); } }); const appDirectory = fs.realpathSync(process.cwd()); process.env.NODE_PATH = (process.env.NODE_PATH || '') .split(path.delimiter) .filter((folder) => folder && !path.isAbsolute(folder)) .map((folder) => path.resolve(appDirectory, folder)) .join(path.delimiter); const REACT_APP = /^REACT_APP_/i; function getClientEnvironment(publicUrl) { const raw = Object.keys(process.env) .filter((key) => REACT_APP.test(key)) .reduce( (env, key) => { env[key] = process.env[key]; return env; }, { NODE_ENV: process.env.NODE_ENV || 'development', PUBLIC_URL: publicUrl, } ); const stringified = { 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}), }; return {raw, stringified}; } module.exports = getClientEnvironment; <|start_filename|>functions/canvas-builder.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const {Canvas} = require('@assistant/conversation'); const util = require('./util'); /** * @typedef CanvasState * @property {string} [url] - Host url of web app. * @property {boolean} [suppressMic] - True to close mic. * @property {string} [action] - Canvas response action. * @property {string} [template] - Canvas response template. * @property {string} [speech] - Output TTS to be spoken by device. * @property {Object<string, any>} [config] - Configuration options for web app. * @property {Object<string, any>} [data] - Displayable data for web app. * @property {Array<Object|string>} [suggestions] - Suggestion chips. * @property {CanvasBuilder} [next] - Next Canvas response. */ /** * Utility class to construct Canvas Response object. */ class CanvasBuilder { /** * Constructs a new CanvasBuilder object. * @param {CanvasState} initialState - Initial state. */ constructor(initialState = {}) { this.url = initialState.url || ''; this.suppressMic = initialState.suppressMic || false; this.action = initialState.action || ''; this.template = initialState.template || ''; this.speech = initialState.speech || ''; this.config = initialState.config || {}; this.data = initialState.data || {}; this.suggestions = initialState.suggestions || []; this.next = initialState.next || null; } /** * Sets canvas states by state object. * @param {CanvasState} newState - New state object. * @return {CanvasBuilder} - This instance. */ setState(newState = {}) { util.object.forOwn(newState, (val, prop) => { switch (prop) { case 'url': case 'suppressMic': case 'action': case 'template': case 'speech': case 'next': this.set(prop, val); break; case 'config': case 'data': case 'suggestions': this.add(prop, val); break; default: break; } }); return this; } /** * Sets new value for prop. * @param {string} prop - Property name. * @param {*} value - New value. * @return {CanvasBuilder} - This instance. */ set(prop, value) { if (this.hasOwnProperty(prop)) { this[prop] = value; } return this; } /** * Adds new values for existing prop with array/object value type. * @param {string} prop - Property name. * @param {!Object|Array} values - New values. * @return {CanvasBuilder} - This instance. */ add(prop, values) { if (this.hasOwnProperty(prop)) { if (Array.isArray(this[prop])) { this[prop] = this[prop].concat(values); } else if (typeof this[prop] === 'object') { this[prop] = Object.assign(this[prop], values); } else { this.set(prop, values); } } return this; } /** * Builds state object. * @return {Object} - Constructed state object. */ buildState() { return CanvasBuilder.clean({ action: this.action, template: this.template, speech: this.speech, config: this.config, data: this.data, suggestions: this.suggestions, next: this.next, }); } /** * Builds Canvas Response for ConversationV3. * @param {string} url - URL for canvas init. * @return {Canvas} - Canvas response. */ build(url) { if (typeof url === 'string' && url) { this.url = url; } const slides = [this.buildState()]; while (slides[slides.length - 1].next) { const last = slides[slides.length - 1]; slides.push(last.next); delete last.next; } return new Canvas({ url: this.url, suppressMic: this.suppressMic, data: slides, }); } /** * Cleans the SSML fields, and remove all empty properties. * @param {Object} state - Canvas response state. * @return {Object} - Cleaned canvas response state. */ static clean(state) { if (state.speech) { state.speech = util.ssml.clean(state.speech).trim(); } const cleanedNext = state.next instanceof CanvasBuilder ? state.next.buildState() : null; state.next = null; // deep clean on next is already done above const cleanedState = util.object.deepClean(state); if (!util.object.isEmpty(cleanedNext)) { cleanedState.next = cleanedNext; } return cleanedState; } /** * Creates either an CanvasBuilder instance or one with Proxy wrapper. * If using Proxy object: * - Routes all method invocation to do nothing. * - Routes all property lookup to return undefined. * - Skips redundant work when immersive response is not needed. * @param {boolean} hasCanvas - False to create a Proxy wrapper object. * @param {...any} args - Args to pass to CanvasBuilder constructor. * @return {CanvasBuilder|Proxy} - CanvasBuilder or Proxy wrapper. */ static create(hasCanvas, ...args) { // Wrap instance with Proxy object const wrap = function(obj) { const handler = { get(target, prop, receiver) { if (target[prop] instanceof Function) { return () => (prop.startsWith('build') ? undefined : receiver); } }, }; return new Proxy(obj, handler); }; const instance = new CanvasBuilder(...args); return hasCanvas ? instance : wrap(instance); } } module.exports = CanvasBuilder; <|start_filename|>canvas/src/util/backgroundOptions.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import orientation from './orientation'; import preloadImage from './preloadImage'; /** * @fileoverview Returns a random background of the default set of backgrounds. * Returns a shape of { portrait:string; landscape:string; }, so it can * accommodate either orientation when implemented. */ const backgrounds = [ { portrait: '/image/defaults/quiz_portrait_1@2x.png', landscape: '/image/defaults/quiz_landscape_1@2x.png', }, { portrait: '/image/defaults/quiz_portrait_2@2x.png', landscape: '/image/defaults/quiz_landscape_2@2x.png', }, { portrait: '/image/defaults/quiz_portrait_3@2x.png', landscape: '/image/defaults/quiz_landscape_3@2x.png', }, { portrait: '/image/defaults/quiz_portrait_4@2x.png', landscape: '/image/defaults/quiz_landscape_4@2x.png', }, ]; const randomBackground = () => { return backgrounds[Math.floor(Math.random() * backgrounds.length)]; }; const validateBackground = async (background) => { let url; try { url = background[orientation()]; await preloadImage(url); } catch (e) { url = randomBackground()[orientation()]; } return url; }; export {randomBackground, backgrounds, validateBackground}; <|start_filename|>canvas/src/util/preloadImage.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utility functions which will preload an image. */ export default (url) => { return new Promise((resolve, reject) => { let image = new Image(); image.onload = () => { resolve(image); }; image.onerror = () => { reject(); }; image.src = url; }); }; <|start_filename|>converter/sheet-converter.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Data sheet to local data converter class. */ const path = require('path'); const {Tab, TabType, OutputType} = require('./schema.js'); const util = require('./util.js'); class SheetConverter { /** * @param {!Object} options - Constructor options. * @param {sheets_v4.Sheets} options.sheets - Google sheet client. * @param {string} options.sheetId - Sheet id. * @param {string} options.locale - Sheet locale. * @param {string} options.dataDir - Webhook data dir. * @param {string} options.sdkDir - Action SDK root dir. */ constructor({sheets, sheetId, locale, dataDir, sdkDir}) { this.sheets = sheets; this.sheetId = sheetId; this.locale = locale; this.dataDir = dataDir; this.sdkDir = sdkDir; } /** * Parse data sheet and convert to appropriate local files. */ async convert() { const parsed = {}; for (const [key, tab] of Object.entries(Tab)) { parsed[key] = await this.parseTab(tab); } for (const [key, tab] of Object.entries(Tab)) { const dirPath = tab.outputType === OutputType.JSON ? this.dataDir : this.sdkDir; const filePath = this._getOutputFilePath(tab.outputType, dirPath, tab.name); this.writeTab(tab.outputType, filePath, parsed[key]); } } /** * Parse sheet tab based on tab's type. * @param {Object} tab - Sheet tab name. * @return {Object} - Parsed data. */ async parseTab(tab) { tab = JSON.parse(JSON.stringify(tab)); // ensure original tab is not modified if (tab.type === TabType.ARRAY) return this.parseArrayTab(tab); if (tab.type === TabType.DICTIONARY) return this.parseDictTab(tab); throw new Error(`Tab type:${tab.type} is neither ARRAY or DICTIONARY.`); } /** * Parse tab as array of objects by rows using header row as keys and respective column as value. * @param {Object} tab - Sheet tab name. * @return {Array<Object>} - Parsed data. */ async parseArrayTab(tab) { const res = await this.sheets.spreadsheets.values.get({ spreadsheetId: this.sheetId, range: tab.displayName, majorDimension: 'ROWS', }); const rows = res.data.values; const excludeRows = new Set(tab.excludeRows.map((r) => r - 1)); const headerRowIdx = this._getHeaderRowIdx(tab, rows); const idxToColDef = {}; for (const colDef of tab.columns) { const colIdx = rows[headerRowIdx].findIndex( (val) => val.toLowerCase() === colDef.displayName.toLowerCase() ); if (colIdx === -1 && colDef.isRequired) { throw new Error( `Tab:${tab.displayName} Header:${colDef.displayName} is required but not found.` ); } idxToColDef[colIdx] = colDef; } const output = []; for (let r = headerRowIdx + 1; r < rows.length; ++r) { if (excludeRows.has(r)) continue; const row = rows[r]; const doc = {}; for (let c = 0; c < row.length; ++c) { if (!idxToColDef[c]) continue; const colDef = idxToColDef[c]; let value = row[c].trim(); if (colDef.isRequired && !value) { throw new Error( `Tab:${tab.displayName} Row:${r + 1} Column:${ colDef.displayName } is required but empty.` ); } if (colDef.isRepeated) { value = this._parseRepeatedValue(value); if (colDef.isRequired && value.length === 0) { throw new Error( `Tab:${tab.displayName} Row:${r + 1} Column:${ colDef.displayName } is required but empty.` ); } } doc[colDef.name] = value; } output.push(doc); } return output; } /** * Parse tab as dictionary by using specified key column as keys and value object specified by * other columns as key/val pairs. * @param {Object} tab - Sheet tab name. * @return {Object} - Parsed data. */ async parseDictTab(tab) { const res = await this.sheets.spreadsheets.values.get({ spreadsheetId: this.sheetId, range: tab.displayName, majorDimension: 'ROWS', }); const rows = res.data.values; const excludeRows = new Set(tab.excludeRows.map((r) => r - 1)); const headerRowIdx = this._getHeaderRowIdx(tab, rows); let keyColIdx = 0; const idxToColDef = {}; for (const colDef of tab.columns) { const colIdx = rows[headerRowIdx].findIndex( (val) => val.toLowerCase() === colDef.displayName.toLowerCase() ); if (colIdx === -1 && colDef.isKey) { throw new Error( `Tab:${tab.displayName} Header:${colDef.displayName} is required but not found.` ); } if (colDef.isKey) { keyColIdx = colIdx; } else { idxToColDef[colIdx] = colDef; } } const output = {}; for (let r = headerRowIdx + 1; r < rows.length; ++r) { if (excludeRows.has(r)) continue; const row = rows[r]; const doc = {}; let key = ''; for (let c = 0; c < row.length; ++c) { if (c !== keyColIdx && !idxToColDef[c]) continue; if (c === keyColIdx) { const keyDef = tab.keys.find( (def) => def.displayName.toLowerCase() === row[c].toLowerCase() ); if (!keyDef) continue; key = keyDef.name; } else { const colDef = idxToColDef[c]; doc[colDef.name] = row[c].trim(); } } if (!key) continue; output[key] = doc; } return output; } /** * Get header row index by filtering out excluding rows. * @param {Object} tab - Sheet tab name. * @param {Array<Array<string>>} rows - Spreadsheet rows. * @return {number} - Header row index. */ _getHeaderRowIdx(tab, rows) { const excludeRows = new Set(tab.excludeRows.map((r) => r - 1)); let headerRowIdx = 0; for (let r = 0; r < rows.length; ++r) { if (!excludeRows.has(r)) { headerRowIdx = r; break; } } return headerRowIdx; } /** * Parsed repeated values by splitting with pipe(|) symbol. * @param {string} val - Raw value * @return {Array<string>} - Parsed values */ _parseRepeatedValue(val) { return val .split('|') .map((str) => str.trim()) .filter(Boolean); } /** * Write data to local file based on file type. * @param {string} type - Output file type. * @param {string} filePath - Output file path. * @param {string} data - Data to write. */ writeTab(type, filePath, data) { switch (type) { case OutputType.JSON: util.writeJsonFile(filePath, data); break; case OutputType.YAML: util.writeYamlFile(filePath, data); break; default: throw new Error(`Invalid output type:${type}`); } } /** * Gets full file path based on output type and locale. * @param {string} type - Output file type. * @param {string} dirPath - Dir path. * @param {string} name - File name. * @return {string} - Full output file path. */ _getOutputFilePath(type, dirPath, name) { return path.join(__dirname, dirPath, `${this.locale}/${name}.${type}`); } } module.exports = SheetConverter; <|start_filename|>canvas/src/util/CubicBezier.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview CubicBezier class */ export default class CubicBezier { constructor(p1x = 0, p1y = 0, p2x = 1, p2y = 1) { this.p1x = p1x; this.p1y = p1y; this.p2x = p2x; this.p2y = p2y; this.cx = 3.0 * this.p1x; this.cy = 3.0 * this.p1y; this.bx = 3.0 * (this.p2x - this.p1x) - this.cx; this.by = 3.0 * (this.p2y - this.p1y) - this.cy; this.ax = 1.0 - this.cx - this.bx; this.ay = 1.0 - this.cy - this.by; this.ease = this.ease.bind(this); } static config(p1x = 0, p1y = 0, p2x = 1, p2y = 1) { return new CubicBezier(p1x, p1y, p2x, p2y).ease; } ease(time, start, change, duration) { return this.solve(time, this.getEpsilon(duration)); } getEpsilon(duration = 400) { return 1 / (200 * duration); } solve(x, epsilon) { return this.sampleCurveY(this.solveCurveX(x, epsilon)); } solveCurveX(x, epsilon) { for (let i = 0, t2 = x; i < 8; i++) { const x2 = this.sampleCurveX(t2) - x; if (Math.abs(x2) < epsilon) return t2; const d2 = this.sampleDerivX(t2); if (Math.abs(d2) < epsilon) break; t2 = t2 - x2 / d2; } let t0 = 0.0; let t1 = 1.0; let t2 = x; if (t2 < t0) return t0; if (t2 > t1) return t1; while (t0 < t1) { const x2 = this.sampleCurveX(t2); if (Math.abs(x2 - x) < epsilon) return t2; if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) * 0.5 + t0; } return t2; } sampleCurveX(t) { return ((this.ax * t + this.bx) * t + this.cx) * t; } sampleCurveY(t) { return ((this.ay * t + this.by) * t + this.cy) * t; } sampleDerivX(t) { return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; } } <|start_filename|>functions/types/global.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; /** * Format arguments as replacement strings for prompts. * @typedef {Object} FormatArgs * @property {Array<string|Object>} textArgs - Replacement args for text property. * @property {Array<string|Object>} speechArgs - Replacement args for speech property. */ /** * @typedef {Object} ValidatorSchema * @property {string} type - One of supported SchemaType. * @property {Function} process - Preprocessor function before apply Joi validation. * @property {Joi} validate - Joi schema validation object. * @property {*} [default] - Default value to use if validation failed. * @property {Boolean} [optional] - True to not validate if value is an empty string. * @property {string} [alias] - Alias key to replace the original field key. */ /** * @typedef {Object} RichBasicCard * @property {string} display - Image display options, one of DEFAULT, WHITE, CROPPED. * @property {string} [text] - Body text. * @property {string} [title] - Title text. * @property {Image} [image] - Card image. */ /** * @typedef {Object} TransitionResponse * @property {string} simple - Voice only simple response. * @property {Array<Object>} rich - Chat UI rich responses. * @property {!ImmersiveResponse} immersive - Immersive canvas response. */ /** * @typedef {Object} QuizSessionState * @property {number} count - Index position of current question. * @property {number} limit - Number of questions per session. * @property {!Object<string, number>} traitToWeight - Trait to weight/score. * @property {Array<Question>} questions - Shuffled questions for new session. */ /** * @typedef {Object} QuizSettings * @property {boolean} playIntroConfirmation - True to ask intro confirmation before quiz starts. * @property {number} questionsPerQuiz - Number of questions per quiz. * @property {string} introTitle - Intro title text. * @property {string} introSubtitle - Intro subtitle text. * @property {string} introTitleColor - Intro title text color in HEX. * @property {string} introSubtitleColor - Intro subtitle text color in HEX. * @property {string} startButtonText - Intro slide start button display text. * @property {string} restartButtonText - Outcome slide restart button display text. * @property {string} textColor - Main body text color in HEX. * @property {string} font - Google hosted font in full URL. * @property {string} buttonNormalTextColor - Button normal text color in HEX. * @property {string} buttonNormalBackgroundColor - Button normal background color in HEX. * @property {string} buttonSelectedTextColor - Button selected text color in HEX. * @property {string} buttonSelectedBackgroundColor - Button selected background color in HEX. * @property {string} progressBarBackgroundColor - Progress bar background color in HEX. * @property {string} progressBarFillColor - Progress bar filled color in HEX. */ /** * @typedef {Object} QuizIntro * @property {string} text - Intro displayed text. * @property {string} [speech] - Intro spoken ssml text. * @property {string} [backgroundLandscape] - Intro landscape background image URL. * @property {string} [backgroundPortrait] - Intro portrait background image URL. */ /** * @typedef {Object} Question * @property {string} trait - Matching trait for the question. * @property {string} questionText - Question displayed text. * @property {string} [questionSpeech] - Question spoken ssml text. * @property {Array<string>} positiveAnswers - Positive acceptable answers. * @property {Array<string>} negativeAnswers - Negative acceptable answers. * @property {string} [positiveFollowupSpeech] - Positive followup spoken ssml text. * @property {string} [positiveFollowupText] - Positive followup displayed text. * @property {string} [negativeFollowupSpeech] - Negative followup spoken ssml text. * @property {string} [negativeFollowupText] - Negative followup displayed text. * @property {string} [backgroundLandscape] - Landscape background image URL. * @property {string} [backgroundPortrait] - Portrait background image URL. * @property {string} [positiveAnswerImage] - Positive answer suggestion image URL. * @property {string} [negativeAnswerImage] - Negative answer suggestion image URL. */ /** * @typedef {Object} QuizOutcome * @property {string} text - Outcome displayed text. * @property {string} [speech] - Outcome spoken ssml text. * @property {string} [positiveTraits] - Positive traits split by & symbol. * @property {string} [negativeTraits] - Negative traits split by & symbol. * @property {string} [title] - Outcome title. * @property {string} [imageLandscape] - Landscape outcome image URL. * @property {string} [imagePortrait] - Portrait outcome image URL. * @property {string} [backgroundLandscape] - Landscape outcome background imag URL. * @property {string} [backgroundPortrait] - Portrait outcome background imag URL. */ <|start_filename|>canvas/src/component/basic/Basic.css<|end_filename|> /** * Copyright 2020 Google LLC * * 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. */ :local(.root) { height: 100vh; width: 100vw; top: 0; left: 0; position: absolute; display: flex; } :local(.frozen) { pointer-events: none; } :local(.container) { position: relative; text-align: center; padding: 0 8vw; margin: auto; color: white; display: flex; flex-direction: column; width: 100%; } :local(.imageContainer) { border-radius: 0.5em; } :local(.imageContainer img) { object-fit: contain; width: 100%; height: 100%; } :local(.textContainer) { display: flex; flex-direction: column; justify-content: center; text-align: center; max-height: 100%; width: 100%; overflow: hidden; } :local(.header) { font-weight: 700; max-height: 100%; line-height: 1; margin: 0; } :local(.body) { font-weight: 700; max-height: 100%; line-height: 1.25; margin: 0; padding: 0.5em 0; letter-spacing: 0.012em; } :local(.smallContainer) { display: flex; flex-direction: column; justify-content: flex-start; flex: 1 1 auto; margin: 0.5em 0; overflow-y: auto; } :local(.smallContainer::-webkit-scrollbar) { display: none; } :local(.small) { font-weight: 400; line-height: 1.5; margin: 0.5em 0; flex: 1 1 auto; } :local(.childrenContainer) { display: flex; align-items: center; justify-content: center; width: 100%; flex: 0 0 auto; } @media (orientation: portrait) { :local(.container) { justify-content: flex-start; height: 70%; } :local(.outcomeContainer) { height: 92%; padding-top: 6vh; } :local(.imageContainer) { flex: 0 0 auto; max-height: 32%; padding-bottom: 5%; } :local(.textContainer) { flex-grow: 1; } :local(.introTextContainer) { justify-content: space-around; } :local(.header) { font-size: 13.5vw; } :local(.body) { font-size: 7vw; } :local(.small) { font-size: 4.5vw; } :local(.childrenContainer) { flex-direction: column; } } @media (orientation: landscape) { :local(.container) { justify-content: center; height: 66%; } :local(.questionContainer) { padding: 0 14vw; } :local(.outcomeContainer) { flex-direction: row; height: 92%; padding-top: 12.5vh; } :local(.imageContainer) { margin: 0 4vw 0 0; flex: 1 0 38%; max-height: 100%; } :local(.introTextContainer) { flex-grow: 1; justify-content: space-around; } :local(.outcomeTextContainer) { flex: auto; justify-content: flex-start; height: 100%; text-align: left; } :local(.header) { font-size: 15vh; } :local(.body) { font-size: 7.5vh; } :local(.outcomeBody) { padding-top: 0; } :local(.small) { font-size: 4.0vh; } :local(.questionChildrenContainer) { justify-content: space-between; } :local(.outcomeChildrenContainer) { justify-content: left; } } <|start_filename|>functions/__tests__/app.test.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const rewire = require('rewire'); const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); const {expect} = chai; chai.use(sinonChai); const app = rewire('../app.js'); const {Prompt} = require('../constant.js'); const logger = require('../analytics/logger.js'); const ConvHelper = require('../conv-helper.js'); const CanvasBuilder = require('../canvas-builder.js'); describe('app', function() { const initDataCtor = app.__get__('initDataCtor'); const middleware = app.__get__('middleware'); const errorHandler = app.__get__('errorHandler'); before(function() { logger.transports.forEach((t) => (t.silent = true)); }); beforeEach(function() { sinon.stub(console, 'log'); sinon.stub(console, 'error'); }); afterEach(function() { sinon.restore(); }); describe('exports', function() { it('exports a ConversationV3 app', function() { expect(app).to.be.a('function'); expect(app.middleware).to.be.a('function'); expect(app.catch).to.be.a('function'); }); }); describe('initDataCtor', function() { it('is an function', function() { expect(initDataCtor).to.be.a('function'); }); it('returns an object for initial conv data', function() { const initData = initDataCtor(); expect(initData).to.be.an('object'); expect(initData.quizSettings).to.be.an('object'); }); }); describe('middleware', function() { let fakeConv; beforeEach(function() { fakeConv = { request: {}, headers: { ['function-execution-id']: 'xyz123', }, handler: { name: 'LOAD_SETTINGS', }, intent: { name: 'actions.intent.MAIN', params: {}, query: 'Talk to test app', }, scene: { name: 'Welcome', slotFillingStatus: 'UNSPECIFIED', slots: {}, }, session: { id: 'abc123', params: {}, typeOverrides: [], languageCode: '', }, user: { locale: 'en-US', params: {}, accountLinkingStatus: 'ACCOUNT_LINKING_STATUS_UNSPECIFIED', verificationStatus: 'VERIFIED', packageEntitlements: [], lastSeenTime: '2020-08-07T23:11:04Z', }, home: { params: {}, }, device: { capabilities: [ 'SPEECH', 'RICH_RESPONSE', 'WEB_LINK', 'LONG_FORM_AUDIO', 'INTERACTIVE_CANVAS', ], }, expected: { speech: [], }, context: {}, add: () => {}, append: () => {}, json: () => {}, response: () => {}, serialize: () => {}, }; }); it('sets capability shortcut properties to true', function() { fakeConv.device.capabilities = [ 'SPEECH', 'RICH_RESPONSE', 'WEB_LINK', 'LONG_FORM_AUDIO', 'INTERACTIVE_CANVAS', ]; middleware(fakeConv); expect(fakeConv.hasScreen).to.be.true; expect(fakeConv.hasAudio).to.be.true; expect(fakeConv.hasLongFormAudio).to.be.true; expect(fakeConv.hasWebBrowser).to.be.true; expect(fakeConv.hasInteractiveCanvas).to.be.true; }); it('sets capability shortcut properties to false', function() { fakeConv.device.capabilities = [,]; middleware(fakeConv); expect(fakeConv.hasScreen).to.be.false; expect(fakeConv.hasAudio).to.be.false; expect(fakeConv.hasLongFormAudio).to.be.false; expect(fakeConv.hasWebBrowser).to.be.false; expect(fakeConv.hasInteractiveCanvas).to.be.false; }); it('assigns a init data to conv.session.params.data if does not exist', function() { fakeConv.session.params = {}; middleware(fakeConv); expect(fakeConv.session.params.data).to.be.a('object'); }); it('not assigns a init data to conv.session.params.data if already exists', function() { fakeConv.session.params.data = {a: 1}; middleware(fakeConv); expect(fakeConv.session.params.data).to.eql({a: 1}); }); it('instantiate a $helper prop on conv', function() { middleware(fakeConv); expect(fakeConv.$helper).to.be.instanceOf(ConvHelper); }); it('instantiate a $immersive prop on conv', function() { middleware(fakeConv); expect(fakeConv.$immersive).to.be.instanceOf(CanvasBuilder); }); it('instantiate $immersive prop with url if is a new conversation', function() { fakeConv.intent.name = 'actions.intent.MAIN'; middleware(fakeConv); expect(fakeConv.$immersive.url).to.be.ok; }); it('instantiate $immersive prop with empty url if is not a new conversation', function() { fakeConv.intent.name = 'YES'; middleware(fakeConv); expect(fakeConv.$immersive.url).to.not.be.ok; }); }); describe('errorHandler', function() { const originalImmersive = CanvasBuilder.create(true); let fakeConv; beforeEach(function() { fakeConv = { request: {}, headers: { ['function-execution-id']: 'xyz123', }, handler: { name: 'LOAD_SETTINGS', }, intent: { name: 'actions.intent.MAIN', params: {}, query: 'Talk to test app', }, scene: { name: 'Welcome', slotFillingStatus: 'UNSPECIFIED', slots: {}, }, session: { id: 'abc123', params: {}, typeOverrides: [], languageCode: '', }, user: { locale: 'en-US', params: {}, accountLinkingStatus: 'ACCOUNT_LINKING_STATUS_UNSPECIFIED', verificationStatus: 'VERIFIED', packageEntitlements: [], lastSeenTime: '2020-08-07T23:11:04Z', }, home: { params: {}, }, device: { capabilities: [ 'SPEECH', 'RICH_RESPONSE', 'WEB_LINK', 'LONG_FORM_AUDIO', 'INTERACTIVE_CANVAS', ], }, expected: { speech: [], }, context: {}, add: () => {}, append: () => {}, json: () => {}, response: () => {}, serialize: () => {}, $immersive: originalImmersive, }; fakeConv.$helper = ConvHelper.create(fakeConv); sinon.spy(logger, 'error'); }); it('logs error message by logger', async function() { await errorHandler(fakeConv, new Error('failed')); expect(logger.error).to.have.been.called; }); it('resets conv.$immersive to a new instance', async function() { fakeConv.intent.name = 'YES'; await errorHandler(fakeConv, new Error('failed')); expect(fakeConv.$immersive).to.not.equal(originalImmersive); }); it('invokes conv.$helper.closeWithPrompt with GENERIC_MAX_NO_MATCH prompt', async function() { sinon.stub(fakeConv.$helper, 'closeWithPrompt').resolves({}); await errorHandler(fakeConv, new Error('failed')); expect(fakeConv.$helper.closeWithPrompt).to.have.been.calledWith(Prompt.GENERIC_MAX_NO_MATCH); }); it('catches error if conv.$helper.closeWithPrompt fails', async function() { sinon.spy(fakeConv, 'add'); sinon.stub(fakeConv.$helper, 'closeWithPrompt').rejects(new Error('failed again')); await errorHandler(fakeConv, new Error('failed')); expect(fakeConv.$helper.closeWithPrompt).to.have.been.calledWith(Prompt.GENERIC_MAX_NO_MATCH); expect(fakeConv.scene.next).to.eql({name: 'actions.scene.END_CONVERSATION'}); expect(fakeConv.add).to.have.been.called; }); }); }); <|start_filename|>canvas/src/reducer/index.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {combineReducers} from 'redux'; import config from './config'; import frozen from './freeze'; import option from './option'; import progress from './progress'; import slides from './slides'; import ssml from './ssml'; import transition from './transition'; /** * @fileoverview Combines all the reducers into one */ export default combineReducers({ config, frozen, option, progress, slides, ssml, transition, }); <|start_filename|>functions/__tests__/canvas-builder.test.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const chai = require('chai'); const {expect} = chai; const {Canvas} = require('@assistant/conversation'); const CanvasBuilder = require('../canvas-builder.js'); describe('CanvasBuilder', function() { describe('constructor', function() { it('is a function', function() { expect(CanvasBuilder).to.be.a('function'); }); it('has static create function', function() { expect(CanvasBuilder.create).to.be.a('function'); }); it('has static clean function', function() { expect(CanvasBuilder.clean).to.be.a('function'); }); it('is a class constructor', function() { expect(new CanvasBuilder()).to.be.instanceOf(CanvasBuilder); }); it('returns an object with defined methods', function() { const output = new CanvasBuilder(); expect(output.setState).to.be.a('function'); expect(output.set).to.be.a('function'); expect(output.add).to.be.a('function'); expect(output.buildState).to.be.a('function'); expect(output.build).to.be.a('function'); }); it('returns an object with defined props', function() { const output = new CanvasBuilder(); expect(output).to.have.property('url'); expect(output).to.have.property('suppressMic'); expect(output).to.have.property('action'); expect(output).to.have.property('template'); expect(output).to.have.property('speech'); expect(output).to.have.property('config'); expect(output).to.have.property('data'); expect(output).to.have.property('suggestions'); expect(output).to.have.property('next'); }); }); describe('static create', function() { it('returns CanvasBuilder instance if hasCanvas is true', function() { const hasCanvas = true; const output = CanvasBuilder.create(hasCanvas); expect(output).to.be.instanceOf(CanvasBuilder); expect(output).to.not.be.instanceOf(Proxy); }); it('returns Proxy instance if hasCanvas is false', function() { const hasCanvas = false; const output = CanvasBuilder.create(hasCanvas); expect(output.action).to.be.undefined; expect(output.build()).to.be.undefined; }); it('passes rest args to CanvasBuilder constructor', function() { const hasCanvas = true; const action = 'testAction'; const output = CanvasBuilder.create(hasCanvas, {action}); expect(output.action).to.equal(action); }); }); describe('static clean', function() { it('returns an object', function() { const output = CanvasBuilder.clean({}); expect(output).to.be.a('object'); }); it('invoke ssml.clean if has speech property', function() { const testState = {speech: '<speak > a </speak>'}; const output = CanvasBuilder.clean(testState); expect(output.speech).to.equal('<speak>a</speak>'); }); it('deep cleans on input state', function() { const testState = {action: 'a', config: {data: {}}}; const output = CanvasBuilder.clean(testState); expect(output).to.eql({action: 'a'}); }); it('cleans state.next if it is CanvasBuilder instance', function() { const testState = {action: 'a', config: {}, data: {}}; testState.next = new CanvasBuilder({action: 'b', data: {}}); const output = CanvasBuilder.clean(testState); expect(output).to.eql({action: 'a', next: {action: 'b'}}); }); }); describe('setState', function() { let instance; beforeEach(function() { instance = new CanvasBuilder(); }); it('returns CanvasBuilder instance', function() { const output = instance.setState({}); expect(output).to.equal(instance); }); it('sets internal props with new values', function() { const testState = { url: 'a', suppressMic: true, action: 'b', speech: 'd', next: 'e', template: 'f', }; instance.setState(testState); expect(instance.url).to.equal(testState.url); expect(instance.suppressMic).to.equal(testState.suppressMic); expect(instance.action).to.equal(testState.action); expect(instance.micState).to.equal(testState.micState); expect(instance.speech).to.equal(testState.speech); expect(instance.next).to.equal(testState.next); expect(instance.template).to.equal(testState.template); }); it('adds internal props with new values', function() { const testState1 = { config: {a: 1}, data: {b: 1}, suggestions: [1, 2, 3], }; const testState2 = { config: {b: 1}, data: {a: 1}, suggestions: [1, 2, 3], }; instance.setState(testState1); instance.setState(testState2); expect(instance.config).to.eql({a: 1, b: 1}); expect(instance.data).to.eql({a: 1, b: 1}); expect(instance.suggestions).to.eql([1, 2, 3, 1, 2, 3]); }); it('not set prop that are not defined in constructor', function() { const testState = { abc: 1, xyz: [1, 2], }; instance.setState(testState); expect(instance.abc).to.be.undefined; expect(instance.xyz).to.be.undefined; }); }); describe('set', function() { const testValue = 'testValue'; let instance; beforeEach(function() { instance = new CanvasBuilder(); }); it('returns CanvasBuilder instance', function() { const output = instance.set('action', 'newAction'); expect(output).to.equal(instance); }); it('sets internal props with new value', function() { instance.set('action', testValue); expect(instance.action).to.equal(testValue); }); it('not set prop that are not defined in constructor', function() { instance.set('abc', testValue); expect(instance.abc).to.be.undefined; }); }); describe('add', function() { let instance; beforeEach(function() { instance = new CanvasBuilder(); }); it('returns CanvasBuilder instance', function() { const output = instance.add('config', {}); expect(output).to.equal(instance); }); it('concat array props with new values', function() { const testValue = [1, 2, 3]; instance.add('suggestions', testValue); instance.add('suggestions', testValue); expect(instance.suggestions).to.eql([1, 2, 3, 1, 2, 3]); }); it('add/update objects props with new values', function() { const testValue1 = {a: 1, b: 2}; instance.add('config', testValue1); expect(instance.config).to.eql(testValue1); const testValue2 = {b: 3, c: 4}; instance.add('config', testValue2); expect(instance.config).to.eql({a: 1, b: 3, c: 4}); }); it('replaces prop with primitive type value', function() { const testValue = 'FOO_BAR'; instance.add('action', testValue); expect(instance.action).to.eql(testValue); }); it('not set prop that are not defined in constructor', function() { const testValue = {a: 1, b: 2}; instance.add('abc', testValue); expect(instance.abc).to.be.undefined; }); }); describe('buildState', function() { let instance; beforeEach(function() { instance = new CanvasBuilder(); }); it('returns an object', function() { const output = instance.buildState(); expect(output).to.be.a('object'); }); it('returns a cleaned state', function() { instance.setState({ action: 'a', data: {}, config: {}, }); const output = instance.buildState(); expect(output).to.eql({action: 'a'}); }); }); describe('build', function() { let instance; beforeEach(function() { instance = new CanvasBuilder({ suppressMic: false, }); }); it('returns an object', function() { const output = instance.build(); expect(output).to.be.a('object'); }); it('updates valid immersive url from input', function() { instance.url = ''; const testUrl = 'myCustomUrl'; const output = instance.build(testUrl); expect(output.url).to.equal(testUrl); }); it('returns Canvas instance from @assistant/conversation library', function() { const state = { url: 'abc', suppressMic: true, action: 'action1', template: 'template1', config: {a: 1}, data: {b: 1}, suggestions: ['a', 'b', 'c'], }; instance.setState(state); const output = instance.build(); expect(output).to.be.instanceOf(Canvas); expect(output.url).to.eql(state.url); expect(output.suppressMic).to.eql(state.suppressMic); expect(output.data).to.be.a('array'); expect(output.data[0].action).to.eql(state.action); expect(output.data[0].template).to.eql(state.template); expect(output.data[0].config).to.eql(state.config); expect(output.data[0].data).to.eql(state.data); expect(output.data[0].suggestions).to.eql(state.suggestions); }); it('returns built states as multiple elements of data array', function() { const state1 = {action: 'action1', template: 'template1'}; const state2 = {action: 'action2', template: 'template2'}; instance.setState(state1); instance.set('next', new CanvasBuilder()); instance.next.setState(state2); const output = instance.build(); expect(output).to.be.instanceOf(Canvas); expect(output.data).to.be.a('array'); expect(output.data[0]).to.eql(state1); expect(output.data[1]).to.eql(state2); }); }); }); <|start_filename|>canvas/src/component/option/Option.css<|end_filename|> /** * Copyright 2020 Google LLC * * 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. */ :local(.root) { -webkit-tap-highlight-color: transparent; appearance: none; display: block; box-sizing: border-box; overflow: hidden; position: relative; flex: 1 0 auto; width: 100%; transform: translate3d(0, 0, 0); border: 0; border-radius: .5em; background: white; color: black; outline: none; font-family: var(--google-sans); font-weight: 600; line-height: 1.25; text-decoration: none; cursor: pointer; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, .2), 0 2px 2px 0 rgba(0, 0, 0, .14), 0 1px 5px 0 rgba(0, 0, 0, .12); } @media (orientation: portrait) { :local(.root) { font-size: 7vw; margin: 5vh 0; padding: 0; height: 11vh; } :local(.restartRoot) { margin: 2.25vh 0; max-width: 85%; height: 10vh; } } @media (orientation: landscape) { :local(.root) { font-size: 3.25vw; margin: 0; padding: 0; max-width: 45%; height: 18vh; } :local(.restartRoot) { margin: 2.5vh 0; max-width: 40vw; height: 16vh; } } :local(.text) { position: relative; height: 100%; display: flex; align-items: center; justify-content: center; text-align: center; } :local(.ripple) { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; border-radius: .5em; clip-path: circle(0% at 50% 50%); transform: translate3d(0, 0, 0); } <|start_filename|>functions/data/en/quiz_settings.json<|end_filename|> { "play_intro_confirmation": { "value": "Yes" }, "number_of_questions_per_quiz": { "value": "3" }, "intro_title": {}, "intro_subtitle": {}, "intro_title_text_color": {}, "intro_subtitle_text_color": {}, "start_button_text": { "value": "Start" }, "restart_button_text": { "value": "Play Again" }, "text_color": {}, "font": {}, "button_text_color": {}, "button_background_color": {}, "selected_button_text_color": {}, "selected_button_background_color": {}, "progress_bar_background_color": {}, "progress_bar_fill_color": {} } <|start_filename|>functions/conv-helper.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const {Simple, Image, Suggestion} = require('@assistant/conversation'); const util = require('./util'); const metric = require('./analytics/metric.js'); const {Collection, Key, Schema, PromptVariant, Tab} = require('./sheet.js'); const {Intent, Type, Alias, Template, TemplateAction, TypeOverrideMode} = require('./constant.js'); const sheetData = require('./sheet-data.js'); /** * @typedef {Object} ConvHelperResponses * @property {string|Object} simple - Voice only simple response. * @property {Array} rich - Array of rich responses. * @property {Array} immersive - Array of Immersive responses. */ /** * Helper methods for AoG Conversation conv object. */ class ConvHelper { /** * @param {ConversationV3} conv - ConversationV3 instance. */ constructor(conv) { this.conv = conv; } /** * Creates a ConvHelper instance. * @param {ConversationV3} conv - ConversationV3 instance. * @return {ConvHelper} - ConvHelperV3 instance. */ static create(conv) { return new ConvHelper(conv); } /** * Get locale from request info * @return {string} - Conv locale */ getLocale() { return this.conv.user.locale; } /** * Check whether current conv is a new conversation. * @return {boolean} - True if current conv is a new conversation. */ isNewConversation() { const intent = this.conv.intent.name; return intent === Intent.MAIN || intent === Intent.PLAY_GAME; } /** * Loads quiz config settings and validates through FieldSchema. * @return {Promise<QuizSettings>} - Promise that resolves to validated quiz config settings. */ getQuizSettings() { const collection = Collection.QUIZ_SETTINGS; const valueKey = Tab.QUIZ_SETTINGS.valueKey; const options = Object.values(Tab.QUIZ_SETTINGS.key); const settings = Object.assign( {}, Tab.QUIZ_SETTINGS.default, this.loadCompatibleSettings(collection, valueKey, options) ); return Promise.resolve(util.schema.validateObject(settings, Tab.QUIZ_SETTINGS.schema)); } /** * Loads a random validated quiz intro doc. * @return {Promise<QuizIntro>} - Promise that resolves to validated quiz intro doc. */ getRandomQuizIntro() { return Promise.resolve(this.getRandomValidatedDoc(Collection.QUIZ_INTRO, Schema.QUIZ_INTRO)); } /** * Loads all validated quiz question docs. * @return {Promise<Array<Question>>} - Promise that resolves to validated quiz questions docs. */ getAllQuizQuestions() { return Promise.resolve(this.getAllValidatedDocs(Collection.QUIZ_Q_A, Schema.QUIZ_Q_A)); } /** * Loads all validated quiz outcome docs. * @return {Promise<Array<QuizOutcome>>} - Promise that resolves to validated quiz outcome docs. */ getAllQuizOutcomes() { return Promise.resolve( this.getAllValidatedDocs(Collection.QUIZ_OUTCOMES, Schema.QUIZ_OUTCOMES) ); } /** * Fetches a random prompt and optionally fill the placeholder strings. * @param {string} name - Prompt name to fetch. * @param {FormatArgs} [formatArgs] - Replacement strings for prompt. * @return {Promise<Simple>} - Promise that resolves to a formatted prompt. */ getRandomFormattedPrompt(name, formatArgs) { return this.getRandomPrompt(name).then((prompt) => util.response.formatSimple(prompt, formatArgs) ); } /** * Fetches a random prompt from Firestore for all variants, then validates by field schema, * then converts to SimpleResponse shape, which simplifies ssml merge and concatenation. * @param {string} name - Prompt name. * @return {Promise<Simple>} - Promise that resolves to random validated prompt. */ getRandomPrompt(name) { if (!PromptVariant[name]) { throw new Error(`Invalid prompt name provided: ${name}`); } const {key, variant} = PromptVariant[name]; let keys = [key]; if (variant > 0) { const {variantSuffix} = Tab.GENERAL_PROMPTS; keys = Array.from({length: variant}, (_, i) => `${key}${variantSuffix}${i + 1}`); } const prompts = keys.map((key) => { const prompt = sheetData.byLocale(this.getLocale())[Collection.GENERAL_PROMPTS][key]; const validated = util.schema.validateObject(prompt, Schema.GENERAL_PROMPTS); return util.response.toSimple( validated, Key.GENERAL_PROMPTS.DISPLAYED_FLOW, Key.GENERAL_PROMPTS.SPOKEN_FLOW ); }); return Promise.resolve(util.array.randomPick(prompts.filter((prompt) => prompt.text))); } /** * Load a random document from a collection and validates with schema validator. * @param {string} collection - Collection name. * @param {Object} [schema={}] - Validation schema. * @return {Object} - Random validated collection doc. */ getRandomValidatedDoc(collection, schema = {}) { return util.array.randomPick(this.getAllValidatedDocs(collection, schema)); } /** * Load all documents from a collection and validates with schema validator. * @param {string} collection - Collection name. * @param {Object} [schema={}] - Validation schema. * @return {Array<Object>} - Validated collection docs. */ getAllValidatedDocs(collection, schema = {}) { const docs = sheetData.byLocale(this.getLocale())[collection]; return util.schema.validateCollection(docs, schema); } /** * Loads parameter settings, then filter by matching setting options. * @param {string} collection - Collection name. * @param {string} valueKey - Database value object key that maps to actual value. * @param {Array<string>} options - Compatible settings options. * @return {Object} - Compatible settings object. */ loadCompatibleSettings(collection, valueKey, options) { const lowerCaseOptions = new Set(options.map((s) => s.toLowerCase())); const hasMatchKey = (_, key) => lowerCaseOptions.has(key.toLowerCase()); const settings = this.loadSettings(collection, valueKey); return util.object.pickBy(settings, hasMatchKey); } /** * Loads parameter settings, then map values to valueKey property of value object. * @param {string} collection - Collection name. * @param {string} valueKey - Database value object key that maps to actual value. * @return {Object} - Settings object. */ loadSettings(collection, valueKey) { const getValueCol = (target) => { target = Array.isArray(target) ? target[0] : target; return util.object.isObject(target) ? target[valueKey] : target; }; const settings = sheetData.byLocale(this.getLocale())[collection]; return util.object.mapValues(settings, getValueCol); } /** * Updates conv.session.params.data.quizSettings values with sheet settings for existing keys * (case-insensitive) only. New values will be converted to same type as existing values. * @param {!Object} sheetSettings - Sheet settings to update conv.session.params.data.quizSettings */ updateConvDataQuizSettings(sheetSettings) { const {quizSettings} = this.conv.session.params.data; const lookup = new Map(); Object.keys(quizSettings).forEach((prop) => lookup.set(prop.toLowerCase(), prop)); util.object.forOwn(sheetSettings, (val, key) => { const lowerCaseKey = key.toLowerCase(); if (lookup.has(lowerCaseKey)) { const prop = lookup.get(lowerCaseKey); quizSettings[prop] = util.string.convertType(val, typeof quizSettings[prop]); } }); } /** * Checks whether input is a valid transition object. * transition = {simple: '', rich: [], immersive: {}} * @param {?TransitionResponse} target - Input to check. * @return {boolean} - True for valid transition. */ isValidTransition(target) { return ( util.object.isObject(target) && typeof target.simple === 'string' && Array.isArray(target.rich) && util.object.isObject(target.immersive) ); } /** * Builds session type and speech biasing for answer type. */ setupSessionTypeAndSpeechBiasing() { const clean = (synonyms) => [...new Set(synonyms.map((s) => util.string.stripEmoji(s).trim()))]; const question = this.getCurrentQuestion(); const positiveAnswers = clean(question[Alias.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS]); const negativeAnswers = clean(question[Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS]); this.conv.expected.speech = [...positiveAnswers, ...negativeAnswers]; this.addSessionType(Type.ANSWER, positiveAnswers, negativeAnswers); } /** * Add entry to session type. * @param {string} typeName - Session type name. * @param {Array<Array<string>>} synonymsEntries - List of synonyms for session type. */ addSessionType(typeName, ...synonymsEntries) { const entries = synonymsEntries.map((synonyms) => { synonyms = synonyms.map((tokens) => tokens.toLowerCase().trim()).filter(Boolean); return {name: synonyms[0], synonyms: [...new Set(synonyms)]}; }); const sessionType = { name: typeName, mode: TypeOverrideMode.TYPE_REPLACE, synonym: {entries}, }; const index = this.conv.session.typeOverrides.findIndex((ele) => ele.name === sessionType.name); if (index === -1) { this.conv.session.typeOverrides.push(sessionType); } else { this.conv.session.typeOverrides[index] = sessionType; } } /** * Returns rich response suggestion chip texts for current question. * @return {Array<string>} - Rich response suggestion chip texts for current question. */ getQuestionRichSuggestions() { const question = this.getCurrentQuestion(); return [ this.cleanRichSuggestion(question[Alias.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS][0]), this.cleanRichSuggestion(question[Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS][0]), ]; } /** * Get UserAnswer and clear it in session params. * @return {string} - Captured value of 'answer' type. */ getAndClearUserAnswer() { const userAnswer = this.conv.session.params.UserAnswer; this.conv.session.params.UserAnswer = null; return userAnswer; } /** * Returns the current quiz question. * @return {Question} - Current question. */ getCurrentQuestion() { return this.conv.session.params.data.questions[this.conv.session.params.data.count]; } /** * Fetches suggestion prompts and build cleaned rich response suggestion chips. * @param {Array<string>} prompts - Suggestion chip prompts. * @return {Promise<Array<string>>} - Promise that resolves to cleans suggestion chip texts. */ buildPromptRichSuggestions(prompts) { return Promise.all(prompts.map(this.getRandomPrompt.bind(this))).then((chips) => chips.map(this.cleanRichSuggestion.bind(this)) ); } /** * Clean text for Rich response suggestion chip. * @param {string[]|Simple[]} chip - Suggestion chip text or prompt object. * @return {Array<string>} - Cleaned suggestion chip text. */ cleanRichSuggestion(chip) { return util.string.stripEmoji(typeof chip === 'string' ? chip : chip.text).trim(); } /** * Build rich response basic card for an outcome. * @param {QuizOutcome} outcome - Outcome doc. * @return {?RichBasicCard} - BasicCard shape object or null. */ buildOutcomeBasicCard(outcome) { const bodyText = outcome[Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]; const imageUrl = outcome[Alias.QUIZ_OUTCOMES.HORIZONTAL_IMAGE]; const title = outcome[Alias.QUIZ_OUTCOMES.TITLE]; if (!bodyText && !imageUrl) return null; const card = {imageFill: 'WHITE'}; if (title) card.title = title; if (bodyText) card.text = bodyText; if (imageUrl) card.image = new Image({url: imageUrl, alt: title || 'outcome image'}); return card; } /** * Continue the conv by asking a randomly fetched prompt. * @param {string} name - Prompt name. * @param {string[]} [suggestions] - An array of suggestions used for Rich Response. * @return {Promise} - Promise that resolves to continue the conv with a prompt. */ askWithPrompt(name, suggestions) { return this.getRandomPrompt(name).then((prompt) => this.ask({ simple: prompt.speech, rich: [ new Simple(prompt), ...(Array.isArray(suggestions) ? suggestions.map((str) => new Suggestion({title: util.string.stripEmoji(str)})) : [null]), ].filter(Boolean), immersive: [ new Simple(prompt.speech), this.conv.$immersive .set('template', Template.SAY) .set('action', TemplateAction.RESET) .set('speech', prompt.speech) .build(), ], }) ); } /** * Closes the conv with a randomly fetched prompt. * @param {string} name - Prompt name. * @return {Promise} - Promise that resolves to close the conv with a prompt. */ closeWithPrompt(name) { return this.getRandomPrompt(name).then((prompt) => this.close({ simple: prompt.speech, rich: [new Simple(prompt)], immersive: [ new Simple(prompt.speech), this.conv.$immersive .set('suppressMic', true) .set('template', Template.TELL) .set('speech', prompt.speech) .build(), ], }) ); } /** * Continue conversation with constructed responses. * @param {ConvHelperResponses} responses - Simple, rich and immersive responses. */ ask(responses) { this.respond('ask', responses); } /** * Closes conversation with constructed responses. * @param {ConvHelperResponses} responses - Simple, rich and immersive responses. */ close(responses) { this.respond('close', responses); } /** * Responds to user by response type based on device capability. * @param {string} type - Response type ('ask', 'close') * @param {ConvHelperResponses} responses - Simple, rich and immersive responses. */ respond(type, {simple, rich = [], immersive = []} = {}) { metric.jsonSize('conv.session.params', this.conv.session.params); if (this.conv.hasInteractiveCanvas && immersive.filter(Boolean).length > 0) { this.conv.add(...immersive); } else if (this.conv.hasScreen && rich.filter(Boolean).length > 0) { this.conv.add(...rich); } else { this.conv.add(simple); } if (type === 'close') { this.conv.scene.next = {name: 'actions.scene.END_CONVERSATION'}; } } } module.exports = ConvHelper; <|start_filename|>functions/sheet.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const util = require('./util'); const {Alias, Prompt, TabType, SchemaType} = require('./constant.js'); const config = require('./config.js'); /** * Collection names. * @readonly */ const Collection = { QUIZ_INTRO: 'quiz_intro', QUIZ_Q_A: 'quiz_q_a', QUIZ_OUTCOMES: 'quiz_outcomes', QUIZ_SETTINGS: 'quiz_settings', GENERAL_PROMPTS: 'general_prompts', }; /** * Document keys. * @readonly */ const Key = { QUIZ_INTRO: { DISPLAYED_INTRO: 'displayed_introduction', SPOKEN_INTRO: 'spoken_introduction', BACKGROUND_LANDSCAPE_IMAGE: 'quiz_intro_background_landscape_image', BACKGROUND_PORTRAIT_IMAGE: 'quiz_intro_background_portrait_image', }, QUIZ_Q_A: { PERSONALITY_TRAIT: 'personality_trait', DISPLAYED_QUESTION: 'displayed_question', SPOKEN_QUESTION: 'spoken_question', POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS: 'positive_response_answers', NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS: 'negative_response_answers', POSITIVE_RESPONSE_SPOKEN_FOLLOWUP: 'positive_response_spoken_followup', POSITIVE_RESPONSE_DISPLAYED_FOLLOWUP: 'positive_response_displayed_followup', NEGATIVE_RESPONSE_SPOKEN_FOLLOWUP: 'negative_response_spoken_followup', NEGATIVE_RESPONSE_DISPLAYED_FOLLOWUP: 'negative_response_displayed_followup', BACKGROUND_LANDSCAPE_IMAGE: 'quiz_question_background_landscape_image', BACKGROUND_PORTRAIT_IMAGE: 'quiz_question_background_portrait_image', POSITIVE_ANSWER_IMAGE: 'positive_suggested_answer_image', NEGATIVE_ANSWER_IMAGE: 'negative_suggested_answer_image', }, QUIZ_OUTCOMES: { DISPLAYED_OUTCOME: 'displayed_quiz_outcome', SPOKEN_OUTCOME: 'spoken_quiz_outcome', POSITIVE_OUTCOME_TRAITS: 'positive_outcome_matching_traits', NEGATIVE_OUTCOME_TRAITS: 'negative_outcome_matching_traits', TITLE: 'outcome_title', HORIZONTAL_IMAGE: 'horizontal_outcome_image', VERTICAL_IMAGE: 'vertical_outcome_image', BACKGROUND_LANDSCAPE_IMAGE: 'outcome_background_landscape_image', BACKGROUND_PORTRAIT_IMAGE: 'outcome_background_portrait_image', }, QUIZ_SETTINGS: { PLAY_INTRO_CONFIRMATION: 'play_intro_confirmation', QUESTIONS_PER_QUIZ: 'number_of_questions_per_quiz', INTRO_TITLE: 'intro_title', INTRO_SUBTITLE: 'intro_subtitle', INTRO_TITLE_COLOR: 'intro_title_text_color', INTRO_SUBTITLE_COLOR: 'intro_subtitle_text_color', START_BUTTON_TEXT: 'start_button_text', RESTART_BUTTON_TEXT: 'restart_button_text', TEXT_COLOR: 'text_color', FONT: 'font', BUTTON_NORMAL_TEXT_COLOR: 'button_text_color', BUTTON_NORMAL_BACKGROUND_COLOR: 'button_background_color', BUTTON_SELECTED_TEXT_COLOR: 'selected_button_text_color', BUTTON_SELECTED_BACKGROUND_COLOR: 'selected_button_background_color', PROGRESS_BAR_BACKGROUND_COLOR: 'progress_bar_background_color', PROGRESS_BAR_FILL_COLOR: 'progress_bar_fill_color', }, GENERAL_PROMPTS: { DISPLAYED_FLOW: 'displayed_flow', SPOKEN_FLOW: 'spoken_flow', }, }; /** * Field schema for transformation and validation of raw docs. * @readonly */ const Schema = { QUIZ_INTRO: { [Key.QUIZ_INTRO.DISPLAYED_INTRO]: { alias: Alias.QUIZ_INTRO.DISPLAYED_INTRO, type: SchemaType.STRING, }, [Key.QUIZ_INTRO.SPOKEN_INTRO]: { alias: Alias.QUIZ_INTRO.SPOKEN_INTRO, type: SchemaType.SSML, optional: true, }, [Key.QUIZ_INTRO.BACKGROUND_LANDSCAPE_IMAGE]: { alias: Alias.QUIZ_INTRO.BACKGROUND_LANDSCAPE_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_INTRO.BACKGROUND_PORTRAIT_IMAGE]: { alias: Alias.QUIZ_INTRO.BACKGROUND_PORTRAIT_IMAGE, type: SchemaType.IMAGE, optional: true, }, }, QUIZ_Q_A: { [Key.QUIZ_Q_A.PERSONALITY_TRAIT]: { alias: Alias.QUIZ_Q_A.PERSONALITY_TRAIT, type: SchemaType.STRING, }, [Key.QUIZ_Q_A.DISPLAYED_QUESTION]: { alias: Alias.QUIZ_Q_A.DISPLAYED_QUESTION, type: SchemaType.STRING, }, [Key.QUIZ_Q_A.SPOKEN_QUESTION]: { alias: Alias.QUIZ_Q_A.SPOKEN_QUESTION, type: SchemaType.SSML, optional: true, }, [Key.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS]: { alias: Alias.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS, type: SchemaType.STRING_LIST, }, [Key.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS]: { alias: Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS, type: SchemaType.STRING_LIST, }, [Key.QUIZ_Q_A.POSITIVE_RESPONSE_SPOKEN_FOLLOWUP]: { alias: Alias.QUIZ_Q_A.POSITIVE_RESPONSE_SPOKEN_FOLLOWUP, type: SchemaType.SSML, optional: true, }, [Key.QUIZ_Q_A.POSITIVE_RESPONSE_DISPLAYED_FOLLOWUP]: { alias: Alias.QUIZ_Q_A.POSITIVE_RESPONSE_DISPLAYED_FOLLOWUP, type: SchemaType.STRING, optional: true, }, [Key.QUIZ_Q_A.NEGATIVE_RESPONSE_SPOKEN_FOLLOWUP]: { alias: Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_SPOKEN_FOLLOWUP, type: SchemaType.SSML, optional: true, }, [Key.QUIZ_Q_A.NEGATIVE_RESPONSE_DISPLAYED_FOLLOWUP]: { alias: Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_DISPLAYED_FOLLOWUP, type: SchemaType.STRING, optional: true, }, [Key.QUIZ_Q_A.BACKGROUND_LANDSCAPE_IMAGE]: { alias: Alias.QUIZ_Q_A.BACKGROUND_LANDSCAPE_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_Q_A.BACKGROUND_PORTRAIT_IMAGE]: { alias: Alias.QUIZ_Q_A.BACKGROUND_PORTRAIT_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_Q_A.POSITIVE_ANSWER_IMAGE]: { alias: Alias.QUIZ_Q_A.POSITIVE_ANSWER_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_Q_A.NEGATIVE_ANSWER_IMAGE]: { alias: Alias.QUIZ_Q_A.NEGATIVE_ANSWER_IMAGE, type: SchemaType.IMAGE, optional: true, }, }, QUIZ_OUTCOMES: { [Key.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: { alias: Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME, type: SchemaType.STRING, }, [Key.QUIZ_OUTCOMES.SPOKEN_OUTCOME]: { alias: Alias.QUIZ_OUTCOMES.SPOKEN_OUTCOME, type: SchemaType.SSML, optional: true, }, [Key.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: { alias: Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS, type: SchemaType.STRING, optional: true, }, [Key.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: { alias: Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS, type: SchemaType.STRING, optional: true, }, [Key.QUIZ_OUTCOMES.TITLE]: { alias: Alias.QUIZ_OUTCOMES.TITLE, type: SchemaType.STRING, optional: true, }, [Key.QUIZ_OUTCOMES.HORIZONTAL_IMAGE]: { alias: Alias.QUIZ_OUTCOMES.HORIZONTAL_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_OUTCOMES.VERTICAL_IMAGE]: { alias: Alias.QUIZ_OUTCOMES.VERTICAL_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_OUTCOMES.BACKGROUND_LANDSCAPE_IMAGE]: { alias: Alias.QUIZ_OUTCOMES.BACKGROUND_LANDSCAPE_IMAGE, type: SchemaType.IMAGE, optional: true, }, [Key.QUIZ_OUTCOMES.BACKGROUND_PORTRAIT_IMAGE]: { alias: Alias.QUIZ_OUTCOMES.BACKGROUND_PORTRAIT_IMAGE, type: SchemaType.IMAGE, optional: true, }, }, QUIZ_SETTINGS: { [Key.QUIZ_SETTINGS.PLAY_INTRO_CONFIRMATION]: { alias: Alias.QUIZ_SETTINGS.PLAY_INTRO_CONFIRMATION, type: SchemaType.BOOLEAN, default: config.PLAY_INTRO_CONFIRMATION_DEFAULT, }, [Key.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ]: { alias: Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ, type: SchemaType.INTEGER, default: config.QUESTIONS_PER_QUIZ_DEFAULT, }, [Key.QUIZ_SETTINGS.INTRO_TITLE]: { alias: Alias.QUIZ_SETTINGS.INTRO_TITLE, type: SchemaType.STRING, default: config.INTRO_TITLE_DEFAULT, }, [Key.QUIZ_SETTINGS.INTRO_SUBTITLE]: { alias: Alias.QUIZ_SETTINGS.INTRO_SUBTITLE, type: SchemaType.STRING, default: config.INTRO_SUBTITLE_DEFAULT, }, [Key.QUIZ_SETTINGS.INTRO_TITLE_COLOR]: { alias: Alias.QUIZ_SETTINGS.INTRO_TITLE_COLOR, type: SchemaType.COLOR_HEX, default: config.INTRO_TITLE_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.INTRO_SUBTITLE_COLOR]: { alias: Alias.QUIZ_SETTINGS.INTRO_SUBTITLE_COLOR, type: SchemaType.COLOR_HEX, default: config.INTRO_SUBTITLE_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.START_BUTTON_TEXT]: { alias: Alias.QUIZ_SETTINGS.START_BUTTON_TEXT, type: SchemaType.STRING, default: config.START_BUTTON_TEXT_DEFAULT, }, [Key.QUIZ_SETTINGS.RESTART_BUTTON_TEXT]: { alias: Alias.QUIZ_SETTINGS.RESTART_BUTTON_TEXT, type: SchemaType.STRING, default: config.RESTART_BUTTON_TEXT_DEFAULT, }, [Key.QUIZ_SETTINGS.TEXT_COLOR]: { alias: Alias.QUIZ_SETTINGS.TEXT_COLOR, type: SchemaType.COLOR_HEX, default: config.TEXT_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.FONT]: { alias: Alias.QUIZ_SETTINGS.FONT, type: SchemaType.GOOGLE_FONT, default: config.FONT_DEFAULT, }, [Key.QUIZ_SETTINGS.BUTTON_NORMAL_TEXT_COLOR]: { alias: Alias.QUIZ_SETTINGS.BUTTON_NORMAL_TEXT_COLOR, type: SchemaType.COLOR_HEX, default: config.BUTTON_NORMAL_TEXT_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.BUTTON_NORMAL_BACKGROUND_COLOR]: { alias: Alias.QUIZ_SETTINGS.BUTTON_NORMAL_BACKGROUND_COLOR, type: SchemaType.COLOR_HEX, default: config.BUTTON_NORMAL_BACKGROUND_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.BUTTON_SELECTED_TEXT_COLOR]: { alias: Alias.QUIZ_SETTINGS.BUTTON_SELECTED_TEXT_COLOR, type: SchemaType.COLOR_HEX, default: config.BUTTON_SELECTED_TEXT_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.BUTTON_SELECTED_BACKGROUND_COLOR]: { alias: Alias.QUIZ_SETTINGS.BUTTON_SELECTED_BACKGROUND_COLOR, type: SchemaType.COLOR_HEX, default: config.BUTTON_SELECTED_BACKGROUND_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.PROGRESS_BAR_BACKGROUND_COLOR]: { alias: Alias.QUIZ_SETTINGS.PROGRESS_BAR_BACKGROUND_COLOR, type: SchemaType.COLOR_HEX, default: config.PROGRESS_BAR_BACKGROUND_COLOR_DEFAULT, }, [Key.QUIZ_SETTINGS.PROGRESS_BAR_FILL_COLOR]: { alias: Alias.QUIZ_SETTINGS.PROGRESS_BAR_FILL_COLOR, type: SchemaType.COLOR_HEX, default: config.PROGRESS_BAR_FILL_COLOR_DEFAULT, }, }, GENERAL_PROMPTS: { [Key.GENERAL_PROMPTS.DISPLAYED_FLOW]: { type: SchemaType.STRING, }, [Key.GENERAL_PROMPTS.SPOKEN_FLOW]: { type: SchemaType.SSML, optional: true, }, }, }; /** * Prompt variant configuration in structured-type schema. * Prompts with multiple entries have separate keys, we will append variant suffixes during * database fetch. * @readonly */ const PromptVariant = { [Prompt.INTRO_CONFIRMATION]: { key: 'intro_confirmation_question', variant: 3, }, [Prompt.INTRO_CONFIRMATION_POSITIVE]: { key: 'intro_confirmation_positive', variant: 0, }, [Prompt.INTRO_CONFIRMATION_NEGATIVE]: { key: 'intro_confirmation_negative', variant: 0, }, [Prompt.INTRO_POSITIVE_RESPONSE]: { key: 'intro_positive_response', variant: 3, }, [Prompt.INTRO_NEGATIVE_RESPONSE]: { key: 'intro_negative_response', variant: 3, }, [Prompt.INTRO_NO_MATCH_1]: { key: 'intro_no_match_first', variant: 3, }, [Prompt.INTRO_NO_MATCH_2]: { key: 'intro_no_match_second', variant: 3, }, [Prompt.INTRO_NO_INPUT_1]: { key: 'intro_no_input_first', variant: 3, }, [Prompt.INTRO_NO_INPUT_2]: { key: 'intro_no_input_second', variant: 3, }, [Prompt.START_REPEAT]: { key: 'start_repeat', variant: 3, }, [Prompt.START_HELP]: { key: 'start_help', variant: 0, }, [Prompt.TRANSITIONS_REGULAR]: { key: 'transitions_regular', variant: 3, }, [Prompt.TRANSITIONS_FINAL]: { key: 'transitions_final', variant: 3, }, [Prompt.QUESTION_REPEAT]: { key: 'question_repeat', variant: 3, }, [Prompt.ANSWER_HELP]: { key: 'answer_help', variant: 0, }, [Prompt.ANSWER_NO_MATCH_1]: { key: 'answer_no_match_first', variant: 3, }, [Prompt.ANSWER_NO_MATCH_2]: { key: 'answer_no_match_second', variant: 3, }, [Prompt.ANSWER_MAX_NO_MATCH]: { key: 'answer_max_no_match', variant: 3, }, [Prompt.ANSWER_NO_INPUT_1]: { key: 'answer_no_input_first', variant: 3, }, [Prompt.ANSWER_NO_INPUT_2]: { key: 'answer_no_input_second', variant: 3, }, [Prompt.ANSWER_MAX_NO_INPUT]: { key: 'answer_max_no_input', variant: 3, }, [Prompt.OUTCOME_INTRO]: { key: 'outcome_intro', variant: 3, }, [Prompt.END_OF_GAME]: { key: 'end_of_game', variant: 3, }, [Prompt.END_OF_GAME_PLAY_AGAIN_YES]: { key: 'end_of_game_play_again_yes', variant: 0, }, [Prompt.END_OF_GAME_PLAY_AGAIN_NO]: { key: 'end_of_game_play_again_no', variant: 0, }, [Prompt.RESTART_CONFIRMATION]: { key: 'restart_confirmation', variant: 3, }, [Prompt.RESTART_YES_RESPONSE]: { key: 'restart_yes_response', variant: 3, }, [Prompt.RESTART_NO_RESPONSE]: { key: 'restart_no_response', variant: 3, }, [Prompt.SKIP]: { key: 'skip', variant: 3, }, [Prompt.QUIT_CONFIRMATION]: { key: 'quit_confirmation', variant: 3, }, [Prompt.CONTINUE_TO_PLAY]: { key: 'continue_to_play', variant: 3, }, [Prompt.ACKNOWLEDGE_QUIT]: { key: 'acknowledge_quit', variant: 3, }, [Prompt.GENERIC_NO_MATCH]: { key: 'generic_no_match', variant: 3, }, [Prompt.GENERIC_MAX_NO_MATCH]: { key: 'generic_max_no_match', variant: 3, }, [Prompt.GENERIC_NO_INPUT]: { key: 'generic_no_input', variant: 3, }, [Prompt.GENERIC_MAX_NO_INPUT]: { key: 'generic_max_no_input', variant: 3, }, [Prompt.QUESTION_OR]: { key: 'question_or', variant: 0, }, [Prompt.GENERIC_YES]: { key: 'generic_yes', variant: 0, }, [Prompt.GENERIC_NO]: { key: 'generic_no', variant: 0, }, [Prompt.GENERIC_NO_MATCH_NONANSWER]: { key: 'generic_no_match_nonanswer', variant: 3, }, }; /** * Configuration and aliases for each sheet tab. * @readonly */ const Tab = { QUIZ_INTRO: { type: TabType.ARRAY, key: Key.QUIZ_INTRO, schema: Schema.QUIZ_INTRO, }, QUIZ_Q_A: { type: TabType.ARRAY, key: Key.QUIZ_Q_A, schema: Schema.QUIZ_Q_A, }, QUIZ_OUTCOMES: { type: TabType.ARRAY, key: Key.QUIZ_OUTCOMES, schema: Schema.QUIZ_OUTCOMES, }, QUIZ_SETTINGS: { type: TabType.DICTIONARY, key: Key.QUIZ_SETTINGS, valueKey: 'value', schema: Schema.QUIZ_SETTINGS, default: util.object.mapValues(Schema.QUIZ_SETTINGS, (val) => val.default), }, GENERAL_PROMPTS: { type: TabType.DICTIONARY, key: Key.GENERAL_PROMPTS, schema: Schema.GENERAL_PROMPTS, config: PromptVariant, structuredType: true, variantSuffix: '_variant_', }, }; module.exports = { Collection, Key, Schema, PromptVariant, Tab, }; <|start_filename|>canvas/src/constant.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Interactive Canvas response template slide types. * @readonly */ const Template = { /** Question and answer slide */ QUESTION: 'template.question', /** Intro slide */ INTRO: 'template.intro', /** Outcome slide */ OUTCOME: 'template.outcome', /** Only say the ssml, no displayed slide */ SAY: 'template.say', /** Tell the ssml, and close the session */ TELL: 'template.tell', }; /** * Interactive Canvas response template render actions. * @readonly */ const TemplateAction = { /** Reset the UI state */ RESET: 'template.action.reset', /** Freeze UI controls */ FREEZE: 'template.action.freeze', /** Set button 1 to active */ ACTIVE_0: 'template.action.positive', /** Set button 2 to active */ ACTIVE_1: 'template.action.negative', }; /** * SSML TTS status marks from Interactive Canvas API. * @readonly */ const TtsMark = { START: 'START', END: 'END', ERROR: 'ERROR', FLIP: 'FLIP', }; export {Template, TemplateAction, TtsMark}; <|start_filename|>canvas/src/util/easingPreset.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Easing functions which approximate Google's Material Design * guideline easing functions. */ import CubicBezier from './CubicBezier'; export default { standard: CubicBezier.config(0.4, 0.0, 0.2, 1), decelerate: CubicBezier.config(0.0, 0.0, 0.2, 1), accelerate: CubicBezier.config(0.4, 0.0, 1, 1), sharp: CubicBezier.config(0.4, 0.0, 0.6, 1), }; <|start_filename|>functions/quiz.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const util = require('./util'); const config = require('./config.js'); const {Answer, Alias} = require('./constant.js'); /** * @module quiz * @desc Quiz setup and outcome scoring logics */ /** * Initializes quiz game state for new session. * @param {Array<Question>} questions - Quiz questions. * @param {number} questionsPerQuiz - Number of questions per quiz from Quiz Settings. * @return {QuizSessionState} - Initialized quiz session state. * @static */ const initSessionState = (questions, questionsPerQuiz) => { const traitKey = Alias.QUIZ_Q_A.PERSONALITY_TRAIT; questions.forEach((question) => (question[traitKey] = question[traitKey].toLowerCase())); const numberOfQuestions = Math.min( questionsPerQuiz, questions.length, config.MAX_QUESTIONS_PER_QUIZ ); return { count: 0, limit: numberOfQuestions, questions: shuffleByTraits(questions).slice(0, numberOfQuestions), traitToWeight: Object.assign(...getUniqueTraits(questions).map((trait) => ({[trait]: 0}))), }; }; /** * Get all unique traits from a pool of quiz questions. * @param {Array<Question>} questions - Quiz questions. * @return {Array<string>} - Unique traits in questions. * @static */ const getUniqueTraits = (questions) => { const traitKey = Alias.QUIZ_Q_A.PERSONALITY_TRAIT; return [...new Set(questions.map((question) => question[traitKey].toLowerCase()))]; }; /** * Shuffle questions grouped by unique sets of traits. This ensures questions with unique traits * are asked first before cycling to next set of questions with remaining unique traits. * For example, for a question pool with 3xA, 3xB, 2xC, 1xD traits => [A, A, A, B, B, B, C, C, D] * The shuffling logic will ensure the first group to be randomly ordered [ABCD] questions, followed * by a second group of randomly ordered [ABC] unused questions, followed by a final group of * randomly ordered [AB] unused questions. * @param {Array<Question>} questions - Quiz questions. * @return {Array<Question>} - Shuffled questions * @static */ const shuffleByTraits = (questions) => { const traitToQuestions = new Map(); questions.forEach((question) => { const trait = question[Alias.QUIZ_Q_A.PERSONALITY_TRAIT].toLowerCase(); if (!traitToQuestions.has(trait)) { traitToQuestions.set(trait, []); } traitToQuestions.get(trait).push(question); }); const shuffledQuestions = []; while (traitToQuestions.size > 0 && shuffledQuestions.length < questions.length) { const randomUniqueTraits = util.array.shuffle([...traitToQuestions.keys()]); randomUniqueTraits.forEach((trait) => { shuffledQuestions.push(util.array.randomPop(traitToQuestions.get(trait))); if (traitToQuestions.get(trait).length === 0) { traitToQuestions.delete(trait); } }); } return shuffledQuestions; }; /** * Matches user response with positive or negative answers. * A positive answer will grant +1 to question trait, and a negative answer will grant -1. * @param {Question} question - Quiz question. * @param {string} [answer=''] - The raw answer a user has entered. * @return {[string, number]} - [trait, weight] * @static */ const matchAnswer = (question, answer = '') => { const clean = (ans) => util.string.stripEmoji(ans.toLowerCase().replace(/\s/g, '')); const trait = question[Alias.QUIZ_Q_A.PERSONALITY_TRAIT].toLowerCase(); answer = clean(answer); const positiveAnswers = question[Alias.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS].map(clean); const negativeAnswers = question[Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS].map(clean); if (answer === Answer.POSITIVE || positiveAnswers.includes(answer)) { return [trait, 1]; } if (answer === Answer.NEGATIVE || negativeAnswers.includes(answer)) { return [trait, -1]; } return [null, null]; }; /** * Matches an outcome with highest overall weight score, calculated by its associated positive and * negative traits with weight scores accumulated from user choices to session questions. * If there is a tie in highest overall weight, then we pick a random outcome with highest weight. * @param {Array<QuizOutcome>} outcomes - Quiz outcomes. * @param {Object<string, number>} traitToWeight - Trait to weight. * @return {QuizOutcome} - Matched outcome with highest weight score. * @static */ const matchOutcome = (outcomes, traitToWeight) => { const parseTraits = (val) => typeof val === 'string' ? val.split('&').map((trait) => trait.trim().toLowerCase()) : []; outcomes.forEach((outcome) => { outcome._positive = new Set(parseTraits(outcome[Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS])); outcome._negative = new Set(parseTraits(outcome[Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS])); outcome._score = 0; }); Object.entries(traitToWeight).forEach(([trait, weight]) => { trait = trait.toLowerCase(); outcomes.forEach((outcome) => { if (outcome._positive.has(trait)) { outcome._score += weight; } if (outcome._negative.has(trait)) { outcome._score -= weight; } }); }); const maxScore = Math.max(...outcomes.map((outcome) => outcome._score)); return util.array.randomPick(outcomes.filter((outcome) => outcome._score === maxScore)); }; module.exports = { initSessionState, getUniqueTraits, shuffleByTraits, matchAnswer, matchOutcome, }; <|start_filename|>canvas/src/component/progressbar/ProgressBar.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import style from './ProgressBar.css'; /** * @fileoverview Renders a progress-bar, with a dynamic width. */ const ProgressBar = ({progress, config}) => { const total = parseInt(config.questionsPerQuiz, 10); return ( <div className={[style.container, progress >= 0 && progress < total ? style.show : null].join(' ')} style={{backgroundColor: config.progressBarBackgroundColor}} > <div className={style.bar} style={{ width: `${(progress / total) * 100}%`, backgroundColor: config.progressBarFillColor, }} /> </div> ); }; ProgressBar.propTypes = { progress: PropTypes.number, }; ProgressBar.defaultProps = { progress: -1, }; export default connect((state) => ({ config: state.config, }))(ProgressBar); <|start_filename|>functions/config.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; /** * Project configuration settings */ const config = { // Webhook config FUNCTION_NAME: 'personalityQuiz', FUNCTION_VERSION: 'v1', FUNCTION_MEMORY: '1GB', FUNCTION_REGION: 'us-central1', FUNCTION_TIMEOUT: 60, // seconds IMMERSIVE_URL: `https://${process.env.GCLOUD_PROJECT}.web.app/`, ENABLE_DEBUG: true, DEBUG_KEY: 'DedicatedDebugInfo', SSML_BREAK_TIME: 750, // milliseconds MAX_QUESTIONS_PER_QUIZ: 10, // Default values for Quiz settings in the data sheet PLAY_INTRO_CONFIRMATION_DEFAULT: false, QUESTIONS_PER_QUIZ_DEFAULT: 3, INTRO_TITLE_DEFAULT: '', INTRO_SUBTITLE_DEFAULT: '', INTRO_TITLE_COLOR_DEFAULT: '#fff', INTRO_SUBTITLE_COLOR_DEFAULT: '#fff', START_BUTTON_TEXT_DEFAULT: 'Start', RESTART_BUTTON_TEXT_DEFAULT: 'Play Again', TEXT_COLOR_DEFAULT: '#fff', FONT_DEFAULT: '', BUTTON_NORMAL_TEXT_COLOR_DEFAULT: '#202124', BUTTON_NORMAL_BACKGROUND_COLOR_DEFAULT: '#fff', BUTTON_SELECTED_TEXT_COLOR_DEFAULT: '#fff', BUTTON_SELECTED_BACKGROUND_COLOR_DEFAULT: '#4285f4', PROGRESS_BAR_BACKGROUND_COLOR_DEFAULT: '#fff', PROGRESS_BAR_FILL_COLOR_DEFAULT: '#f24738', }; module.exports = config; <|start_filename|>canvas/src/index.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React from 'react'; import ReactDOM from 'react-dom'; import {createStore} from 'redux'; import {Provider} from 'react-redux'; import './index.css'; import App from './App'; import reducer from './reducer'; /** * @fileoverview The bootstrap file. Creates a Redux store, starts the main * Application. */ const store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); <|start_filename|>functions/__tests__/quiz.test.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const chai = require('chai'); const {expect} = chai; const Quiz = require('../quiz.js'); const config = require('../config.js'); const {Alias, Answer} = require('../constant.js'); describe('Quiz', function() { const positiveAnswers = ['p1', 'p2', 'p3']; const negativeAnswers = ['n1', 'n2', 'n3']; const createQuestions = (traitGroups) => { const questions = []; traitGroups.forEach(([trait, count]) => { for (let i = 0; i < count; ++i) { questions.push({ [Alias.QUIZ_Q_A.PERSONALITY_TRAIT]: trait, [Alias.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS]: positiveAnswers, [Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS]: negativeAnswers, }); } }); return questions; }; const createOutcomes = (traits) => { const outcomes = []; const count = 1 << traits.length; // 2^n power set for (let i = 0; i < count; ++i) { const positive = []; const negatives = []; for (let j = 0; j < traits.length; j++) { if (i & (1 << j)) { // bitwise translation to element position positive.push(traits[j]); } else { negatives.push(traits[j]); } } const displayedKey = traits .map((trait) => (negatives.includes(trait) ? '!' : '') + trait) .join(','); outcomes.push({ [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: displayedKey, [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: positive.join(' & '), [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: negatives.join(' & '), }); } return outcomes; }; describe('initSessionState', function() { it('returns a QuizSessionState object', function() { const questions = createQuestions([['A', 4]]); const output = Quiz.initSessionState(questions, 3); expect(output.count).to.be.a('number'); expect(output.limit).to.be.a('number'); expect(output.questions).to.be.an('array'); expect(output.traitToWeight).to.be.an('object'); }); it('converts trait prop of questions to lowercase', function() { const questions = createQuestions([['A', 4]]); const output = Quiz.initSessionState(questions, 4); output.questions.forEach((question) => { expect(question[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]).to.equal('a'); }); }); it('has prop count initialized to 0', function() { const questions = createQuestions([['A', 4]]); const output = Quiz.initSessionState(questions, 3); expect(output.count).to.equal(0); }); it('has prop limit set by questionsPerQuiz input', function() { const questions = createQuestions([['A', 10], ['B', 10], ['C', 10], ['D', 10]]); const output = Quiz.initSessionState(questions, 3); expect(output.limit).to.equal(3); }); it('has prop limit not exceeding total questions size', function() { const questions = createQuestions([['A', 1], ['B', 1]]); const output = Quiz.initSessionState(questions, 3); expect(output.limit).to.equal(2); }); it('has prop limit not exceeding config.MAX_QUESTIONS_PER_QUIZ', function() { const questions = createQuestions([['A', 10], ['B', 10], ['C', 10], ['D', 10]]); const output = Quiz.initSessionState(questions, 20); expect(output.limit).to.equal(config.MAX_QUESTIONS_PER_QUIZ); }); it('has prop questions size set by questionsPerQuiz input', function() { const questions = createQuestions([['A', 10], ['B', 10], ['C', 10], ['D', 10]]); const output = Quiz.initSessionState(questions, 3); expect(output.questions).to.have.lengthOf(3); }); it('has prop questions size not exceeding total questions size', function() { const questions = createQuestions([['A', 1], ['B', 1]]); const output = Quiz.initSessionState(questions, 3); expect(output.questions).to.have.lengthOf(2); }); it('has prop questions size not exceeding config.MAX_QUESTIONS_PER_QUIZ', function() { const questions = createQuestions([['A', 10], ['B', 10], ['C', 10], ['D', 10]]); const output = Quiz.initSessionState(questions, 20); expect(output.questions).to.have.lengthOf(config.MAX_QUESTIONS_PER_QUIZ); }); it('has prop questions shuffled by traits', function() { const questions = createQuestions([['A', 3], ['B', 3], ['C', 2], ['D', 1]]); const output = Quiz.initSessionState(questions, 9); const group1 = output.questions.slice(0, 4).map((q) => q[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]); expect(group1).to.have.members(['a', 'b', 'c', 'd']); const group2 = output.questions.slice(4, 7).map((q) => q[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]); expect(group2).to.have.members(['a', 'b', 'c']); const group3 = output.questions.slice(7, 9).map((q) => q[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]); expect(group3).to.have.members(['a', 'b']); }); it('has prop traitToWeight with unique traits of value initialized to 0', function() { const questions = createQuestions([['A', 4], ['B', 3], ['C', 2], ['D', 1]]); const output = Quiz.initSessionState(questions, 10); expect(output.traitToWeight).to.eql({a: 0, b: 0, c: 0, d: 0}); }); }); describe('getUniqueTraits', function() { it('returns an array of string', function() { const questions = createQuestions([['A', 4]]); const output = Quiz.getUniqueTraits(questions); expect(output).to.be.a('array'); output.forEach((trait) => { expect(trait).to.be.a('string'); }); }); it('returns an array of lowercased unique traits', function() { const questions = createQuestions([['A', 3], ['B', 3], ['C', 2], ['D', 1]]); const output = Quiz.getUniqueTraits(questions); expect(output).to.have.lengthOf(4); expect(output).to.have.members(['a', 'b', 'c', 'd']); }); }); describe('shuffleByTraits', function() { it('returns an array of shuffled question by trait groups', function() { const questions = createQuestions([['A', 3], ['B', 3], ['C', 2], ['D', 1]]); const output = Quiz.shuffleByTraits(questions); const group1 = output.slice(0, 4).map((q) => q[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]); expect(group1).to.have.members(['A', 'B', 'C', 'D']); const group2 = output.slice(4, 7).map((q) => q[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]); expect(group2).to.have.members(['A', 'B', 'C']); const group3 = output.slice(7, 9).map((q) => q[Alias.QUIZ_Q_A.PERSONALITY_TRAIT]); expect(group3).to.have.members(['A', 'B']); }); it('does not mutate input questions', function() { const questions = createQuestions([['A', 3], ['B', 3], ['C', 2], ['D', 1]]); const questionsCopy = [...questions]; Quiz.shuffleByTraits(questions); expect(questions).to.eql(questionsCopy); }); }); describe('matchAnswer', function() { it('returns a tuple of [trait, weight]', function() { const question = createQuestions([['A', 1]])[0]; const output = Quiz.matchAnswer(question, 'p1'); expect(output) .to.be.an('array') .of.lengthOf(2); expect(output[0]).to.be.an('string'); expect(output[1]).to.be.an('number'); }); it('returns a positive weight for positive matched answer', function() { const question = createQuestions([['A', 1]])[0]; const output = Quiz.matchAnswer(question, 'p1'); expect(output[0]).to.equal('a'); expect(output[1]).to.equal(1); }); it('returns a negative weight for negative matched answer', function() { const question = createQuestions([['B', 1]])[0]; const output = Quiz.matchAnswer(question, 'n1'); expect(output[0]).to.equal('b'); expect(output[1]).to.equal(-1); }); it('returns a positive weight for matched Answer.POSITIVE constant', function() { const question = createQuestions([['C', 1]])[0]; const output = Quiz.matchAnswer(question, Answer.POSITIVE); expect(output[0]).to.equal('c'); expect(output[1]).to.equal(1); }); it('returns a negative weight for matched Answer.NEGATIVE constant', function() { const question = createQuestions([['D', 1]])[0]; const output = Quiz.matchAnswer(question, Answer.NEGATIVE); expect(output[0]).to.equal('d'); expect(output[1]).to.equal(-1); }); it('returns [null, null] for unmatched answer', function() { const question = createQuestions([['D', 1]])[0]; const output = Quiz.matchAnswer(question, 'abc'); expect(output[0]).to.be.null; expect(output[1]).to.be.null; }); }); describe('matchOutcome', function() { it('returns an outcome object', function() { const outcomes = createOutcomes(['A', 'B', 'C', 'D']); const output = Quiz.matchOutcome(outcomes, {A: 1, B: 1}); expect(output).to.be.an('object'); expect(output).to.have.ownProperty(Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME); expect(output).to.have.ownProperty(Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS); expect(output).to.have.ownProperty(Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS); }); it('returns with highest overall weight', function() { const outcomes = createOutcomes(['A', 'B', 'C', 'D']); const output = Quiz.matchOutcome(outcomes, {A: 1, B: -1, C: 1, D: -1}); expect(output[Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]).to.equal('A,!B,C,!D'); }); it('returns with a random outcome for tied outcome weights', function() { const outcomes = [ { [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: 'A,B', [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: ['A', 'B'].join(' & '), [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: null, }, { [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: '!C,!D', [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: null, [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: ['C', 'D'].join(' & '), }, { [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: '!B,C', [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: 'C', [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: 'B', }, { [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: '!A,D', [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: 'D', [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: 'A', }, ]; const outcomeTexts = new Set(); for (let i = 0; i < 50; ++i) { outcomeTexts.add( Quiz.matchOutcome(outcomes, {A: 1, C: -1})[Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME] ); } expect(outcomeTexts.size).to.equal(2); }); it('works with optional positive/negative outcome traits', function() { const outcomes = [ { [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: 'A,B', [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: ['A', 'B'].join(' & '), [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: null, }, { [Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]: '!C,!D', [Alias.QUIZ_OUTCOMES.POSITIVE_OUTCOME_TRAITS]: null, [Alias.QUIZ_OUTCOMES.NEGATIVE_OUTCOME_TRAITS]: ['C', 'D'].join(' & '), }, ]; const output = Quiz.matchOutcome(outcomes, {A: 1, B: 1}); expect(output[Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME]).to.equal('A,B'); }); }); }); <|start_filename|>converter/schema.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Schema constants for Personality Quiz 2.0 data sheet. */ /** * Spreadsheet tab Types * ARRAY: each row is an independent doc * DICTIONARY: rows are grouped together by a key column */ const TabType = { ARRAY: 'ARRAY', DICTIONARY: 'DICTIONARY', }; /** * Converted output type */ const OutputType = { JSON: 'json', YAML: 'yaml', }; /** * Spreadsheet tab definitions */ const Tab = { QUIZ_INTRO: { name: 'quiz_intro', displayName: 'Quiz Intro', type: TabType.ARRAY, outputType: OutputType.JSON, excludeRows: [1, 3], columns: [ { name: 'displayed_introduction', displayName: 'Displayed Introduction', isRequired: true, }, { name: 'spoken_introduction', displayName: 'Spoken Introduction', }, { name: 'quiz_intro_background_landscape_image', displayName: 'Quiz Intro Background Landscape Image', }, { name: 'quiz_intro_background_portrait_image', displayName: 'Quiz Intro Background Portrait Image', }, ], }, QUIZ_Q_A: { name: 'quiz_q_a', displayName: 'Quiz Q&A', type: TabType.ARRAY, outputType: OutputType.JSON, excludeRows: [1, 3], columns: [ { name: 'personality_trait', displayName: 'Personality Trait', isRequired: true, }, { name: 'displayed_question', displayName: 'Displayed Question', isRequired: true, }, { name: 'positive_response_answers', displayName: 'Positive Response Answers', isRequired: true, isRepeated: true, }, { name: 'negative_response_answers', displayName: 'Negative Response Answers', isRequired: true, isRepeated: true, }, { name: 'spoken_question', displayName: 'Spoken Question', }, { name: 'positive_response_spoken_followup', displayName: 'Positive Response Spoken Followup', }, { name: 'positive_response_displayed_followup', displayName: 'Positive Response Displayed Followup', }, { name: 'negative_response_spoken_followup', displayName: 'Negative Response Spoken Followup', }, { name: 'negative_response_displayed_followup', displayName: 'Negative Response Displayed Followup', }, { name: 'quiz_question_background_landscape_image', displayName: 'Quiz Question Background Landscape Image', }, { name: 'quiz_question_background_portrait_image', displayName: 'Quiz Question Background Portrait Image', }, { name: 'positive_suggested_answer_image', displayName: 'Positive Suggested Answer Image', }, { name: 'negative_suggested_answer_image', displayName: 'Negative Suggested Answer Image', }, ], }, QUIZ_OUTCOMES: { name: 'quiz_outcomes', displayName: 'Quiz Outcomes', type: TabType.ARRAY, outputType: OutputType.JSON, excludeRows: [1, 3], columns: [ { name: 'displayed_quiz_outcome', displayName: 'Displayed Quiz Outcome', isRequired: true, }, { name: 'positive_outcome_matching_traits', displayName: 'Positive Outcome Matching Traits', }, { name: 'negative_outcome_matching_traits', displayName: 'Negative Outcome Matching Traits', }, { name: 'spoken_quiz_outcome', displayName: 'Spoken Quiz Outcome', }, { name: 'horizontal_outcome_image', displayName: 'Horizontal Outcome Image', }, { name: 'vertical_outcome_image', displayName: 'Vertical Outcome Image', }, { name: 'outcome_background_landscape_image', displayName: 'Outcome Background Landscape Image', }, { name: 'outcome_background_portrait_image', displayName: 'Outcome Background Portrait Image', }, { name: 'outcome_title', displayName: 'Outcome Title', }, ], }, QUIZ_SETTINGS: { name: 'quiz_settings', displayName: 'Quiz Settings', type: TabType.DICTIONARY, outputType: OutputType.JSON, excludeRows: [1, 3], columns: [ { name: 'parameter_name', displayName: 'Parameter Name', isKey: true, }, { name: 'value', displayName: 'Value', }, ], keys: [ { name: 'play_intro_confirmation', displayName: 'Play Intro Confirmation', }, { name: 'number_of_questions_per_quiz', displayName: 'Number of Questions Per Quiz', }, { name: 'intro_title', displayName: 'Intro Title', }, { name: 'intro_subtitle', displayName: 'Intro Subtitle', }, { name: 'intro_title_text_color', displayName: 'Intro Title Text Color', }, { name: 'intro_subtitle_text_color', displayName: 'Intro Subtitle Text Color', }, { name: 'start_button_text', displayName: 'Start Button Text', }, { name: 'restart_button_text', displayName: 'Restart Button Text', }, { name: 'text_color', displayName: 'Text Color', }, { name: 'font', displayName: 'Font', }, { name: 'button_text_color', displayName: 'Button Text Color', }, { name: 'button_background_color', displayName: 'Button Background Color', }, { name: 'selected_button_text_color', displayName: 'Selected Button Text Color', }, { name: 'selected_button_background_color', displayName: 'Selected Button Background Color', }, { name: 'progress_bar_background_color', displayName: 'Progress Bar Background Color', }, { name: 'progress_bar_fill_color', displayName: 'Progress Bar Fill Color', }, ], }, GENERAL_PROMPTS: { name: 'general_prompts', displayName: 'General Prompts', type: TabType.DICTIONARY, outputType: OutputType.JSON, excludeRows: [1, 3], columns: [ { name: 'prompt_section', displayName: 'Prompt Section', isKey: true, }, { name: 'displayed_flow', displayName: 'Displayed Flow', }, { name: 'spoken_flow', displayName: 'Spoken Flow', }, ], keys: [ { name: 'intro_confirmation_question_variant_1', displayName: 'INTRO-CONFIRMATION-QUESTION-VARIANT-1', }, { name: 'intro_confirmation_question_variant_2', displayName: 'INTRO-CONFIRMATION-QUESTION-VARIANT-2', }, { name: 'intro_confirmation_question_variant_3', displayName: 'INTRO-CONFIRMATION-QUESTION-VARIANT-3', }, { name: 'intro_confirmation_positive', displayName: 'INTRO-CONFIRMATION-POSITIVE', }, { name: 'intro_confirmation_negative', displayName: 'INTRO-CONFIRMATION-NEGATIVE', }, { name: 'intro_positive_response_variant_1', displayName: 'INTRO-POSITIVE-RESPONSE-VARIANT-1', }, { name: 'intro_positive_response_variant_2', displayName: 'INTRO-POSITIVE-RESPONSE-VARIANT-2', }, { name: 'intro_positive_response_variant_3', displayName: 'INTRO-POSITIVE-RESPONSE-VARIANT-3', }, { name: 'intro_negative_response_variant_1', displayName: 'INTRO-NEGATIVE-RESPONSE-VARIANT-1', }, { name: 'intro_negative_response_variant_2', displayName: 'INTRO-NEGATIVE-RESPONSE-VARIANT-2', }, { name: 'intro_negative_response_variant_3', displayName: 'INTRO-NEGATIVE-RESPONSE-VARIANT-3', }, { name: 'intro_no_match_first_variant_1', displayName: 'INTRO-NO-MATCH-FIRST-VARIANT-1', }, { name: 'intro_no_match_first_variant_2', displayName: 'INTRO-NO-MATCH-FIRST-VARIANT-2', }, { name: 'intro_no_match_first_variant_3', displayName: 'INTRO-NO-MATCH-FIRST-VARIANT-3', }, { name: 'intro_no_match_second_variant_1', displayName: 'INTRO-NO-MATCH-SECOND-VARIANT-1', }, { name: 'intro_no_match_second_variant_2', displayName: 'INTRO-NO-MATCH-SECOND-VARIANT-2', }, { name: 'intro_no_match_second_variant_3', displayName: 'INTRO-NO-MATCH-SECOND-VARIANT-3', }, { name: 'transitions_regular_variant_1', displayName: 'TRANSITIONS-REGULAR-VARIANT-1', }, { name: 'transitions_regular_variant_2', displayName: 'TRANSITIONS-REGULAR-VARIANT-2', }, { name: 'transitions_regular_variant_3', displayName: 'TRANSITIONS-REGULAR-VARIANT-3', }, { name: 'transitions_final_variant_1', displayName: 'TRANSITIONS-FINAL-VARIANT-1', }, { name: 'transitions_final_variant_2', displayName: 'TRANSITIONS-FINAL-VARIANT-2', }, { name: 'transitions_final_variant_3', displayName: 'TRANSITIONS-FINAL-VARIANT-3', }, { name: 'intro_no_input_first_variant_1', displayName: 'INTRO-NO-INPUT-FIRST-VARIANT-1', }, { name: 'intro_no_input_first_variant_2', displayName: 'INTRO-NO-INPUT-FIRST-VARIANT-2', }, { name: 'intro_no_input_first_variant_3', displayName: 'INTRO-NO-INPUT-FIRST-VARIANT-3', }, { name: 'intro_no_input_second_variant_1', displayName: 'INTRO-NO-INPUT-SECOND-VARIANT-1', }, { name: 'intro_no_input_second_variant_2', displayName: 'INTRO-NO-INPUT-SECOND-VARIANT-2', }, { name: 'intro_no_input_second_variant_3', displayName: 'INTRO-NO-INPUT-SECOND-VARIANT-3', }, { name: 'answer_no_match_first_variant_1', displayName: 'ANSWER-NO-MATCH-FIRST-VARIANT-1', }, { name: 'answer_no_match_first_variant_2', displayName: 'ANSWER-NO-MATCH-FIRST-VARIANT-2', }, { name: 'answer_no_match_first_variant_3', displayName: 'ANSWER-NO-MATCH-FIRST-VARIANT-3', }, { name: 'answer_no_match_second_variant_1', displayName: 'ANSWER-NO-MATCH-SECOND-VARIANT-1', }, { name: 'answer_no_match_second_variant_2', displayName: 'ANSWER-NO-MATCH-SECOND-VARIANT-2', }, { name: 'answer_no_match_second_variant_3', displayName: 'ANSWER-NO-MATCH-SECOND-VARIANT-3', }, { name: 'answer_max_no_match_variant_1', displayName: 'ANSWER-MAX-NO-MATCH-VARIANT-1', }, { name: 'answer_max_no_match_variant_2', displayName: 'ANSWER-MAX-NO-MATCH-VARIANT-2', }, { name: 'answer_max_no_match_variant_3', displayName: 'ANSWER-MAX-NO-MATCH-VARIANT-3', }, { name: 'answer_no_input_first_variant_1', displayName: 'ANSWER-NO-INPUT-FIRST-VARIANT-1', }, { name: 'answer_no_input_first_variant_2', displayName: 'ANSWER-NO-INPUT-FIRST-VARIANT-2', }, { name: 'answer_no_input_first_variant_3', displayName: 'ANSWER-NO-INPUT-FIRST-VARIANT-3', }, { name: 'answer_no_input_second_variant_1', displayName: 'ANSWER-NO-INPUT-SECOND-VARIANT-1', }, { name: 'answer_no_input_second_variant_2', displayName: 'ANSWER-NO-INPUT-SECOND-VARIANT-2', }, { name: 'answer_no_input_second_variant_3', displayName: 'ANSWER-NO-INPUT-SECOND-VARIANT-3', }, { name: 'answer_max_no_input_variant_1', displayName: 'ANSWER-MAX-NO-INPUT-VARIANT-1', }, { name: 'answer_max_no_input_variant_2', displayName: 'ANSWER-MAX-NO-INPUT-VARIANT-2', }, { name: 'answer_max_no_input_variant_3', displayName: 'ANSWER-MAX-NO-INPUT-VARIANT-3', }, { name: 'outcome_intro_variant_1', displayName: 'OUTCOME-INTRO-VARIANT-1', }, { name: 'outcome_intro_variant_2', displayName: 'OUTCOME-INTRO-VARIANT-2', }, { name: 'outcome_intro_variant_3', displayName: 'OUTCOME-INTRO-VARIANT-3', }, { name: 'end_of_game_variant_1', displayName: 'END-OF-GAME-VARIANT-1', }, { name: 'end_of_game_variant_2', displayName: 'END-OF-GAME-VARIANT-2', }, { name: 'end_of_game_variant_3', displayName: 'END-OF-GAME-VARIANT-3', }, { name: 'end_of_game_play_again_yes', displayName: 'END-OF-GAME-PLAY-AGAIN-YES', }, { name: 'end_of_game_play_again_no', displayName: 'END-OF-GAME-PLAY-AGAIN-NO', }, { name: 'restart_no_response_variant_1', displayName: 'RESTART-NO-RESPONSE-VARIANT-1', }, { name: 'restart_no_response_variant_2', displayName: 'RESTART-NO-RESPONSE-VARIANT-2', }, { name: 'restart_no_response_variant_3', displayName: 'RESTART-NO-RESPONSE-VARIANT-3', }, { name: 'start_repeat_variant_1', displayName: 'START-REPEAT-VARIANT-1', }, { name: 'start_repeat_variant_2', displayName: 'START-REPEAT-VARIANT-2', }, { name: 'start_repeat_variant_3', displayName: 'START-REPEAT-VARIANT-3', }, { name: 'skip_variant_1', displayName: 'SKIP-VARIANT-1', }, { name: 'skip_variant_2', displayName: 'SKIP-VARIANT-2', }, { name: 'skip_variant_3', displayName: 'SKIP-VARIANT-3', }, { name: 'start_help', displayName: 'START-HELP', }, { name: 'question_repeat_variant_1', displayName: 'QUESTION-REPEAT-VARIANT-1', }, { name: 'question_repeat_variant_2', displayName: 'QUESTION-REPEAT-VARIANT-2', }, { name: 'question_repeat_variant_3', displayName: 'QUESTION-REPEAT-VARIANT-3', }, { name: 'answer_help', displayName: 'ANSWER-HELP', }, { name: 'quit_confirmation_variant_1', displayName: 'QUIT-CONFIRMATION-VARIANT-1', }, { name: 'quit_confirmation_variant_2', displayName: 'QUIT-CONFIRMATION-VARIANT-2', }, { name: 'quit_confirmation_variant_3', displayName: 'QUIT-CONFIRMATION-VARIANT-3', }, { name: 'continue_to_play_variant_1', displayName: 'CONTINUE-TO-PLAY-VARIANT-1', }, { name: 'continue_to_play_variant_2', displayName: 'CONTINUE-TO-PLAY-VARIANT-2', }, { name: 'continue_to_play_variant_3', displayName: 'CONTINUE-TO-PLAY-VARIANT-3', }, { name: 'acknowledge_quit_variant_1', displayName: 'ACKNOWLEDGE-QUIT-VARIANT-1', }, { name: 'acknowledge_quit_variant_2', displayName: 'ACKNOWLEDGE-QUIT-VARIANT-2', }, { name: 'acknowledge_quit_variant_3', displayName: 'ACKNOWLEDGE-QUIT-VARIANT-3', }, { name: 'restart_confirmation_variant_1', displayName: 'RESTART-CONFIRMATION-VARIANT-1', }, { name: 'restart_confirmation_variant_2', displayName: 'RESTART-CONFIRMATION-VARIANT-2', }, { name: 'restart_confirmation_variant_3', displayName: 'RESTART-CONFIRMATION-VARIANT-3', }, { name: 'restart_yes_response_variant_1', displayName: 'RESTART-YES-RESPONSE-VARIANT-1', }, { name: 'restart_yes_response_variant_2', displayName: 'RESTART-YES-RESPONSE-VARIANT-2', }, { name: 'restart_yes_response_variant_3', displayName: 'RESTART-YES-RESPONSE-VARIANT-3', }, { name: 'generic_no_match_variant_1', displayName: 'GENERIC-NO-MATCH-VARIANT-1', }, { name: 'generic_no_match_variant_2', displayName: 'GENERIC-NO-MATCH-VARIANT-2', }, { name: 'generic_no_match_variant_3', displayName: 'GENERIC-NO-MATCH-VARIANT-3', }, { name: 'generic_max_no_match_variant_1', displayName: 'GENERIC-MAX-NO-MATCH-VARIANT-1', }, { name: 'generic_max_no_match_variant_2', displayName: 'GENERIC-MAX-NO-MATCH-VARIANT-2', }, { name: 'generic_max_no_match_variant_3', displayName: 'GENERIC-MAX-NO-MATCH-VARIANT-3', }, { name: 'generic_no_input_variant_1', displayName: 'GENERIC-NO-INPUT-VARIANT-1', }, { name: 'generic_no_input_variant_2', displayName: 'GENERIC-NO-INPUT-VARIANT-2', }, { name: 'generic_no_input_variant_3', displayName: 'GENERIC-NO-INPUT-VARIANT-3', }, { name: 'generic_max_no_input_variant_1', displayName: 'GENERIC-MAX-NO-INPUT-VARIANT-1', }, { name: 'generic_max_no_input_variant_2', displayName: 'GENERIC-MAX-NO-INPUT-VARIANT-2', }, { name: 'generic_max_no_input_variant_3', displayName: 'GENERIC-MAX-NO-INPUT-VARIANT-3', }, { name: 'question_or', displayName: 'QUESTION-OR', }, { name: 'generic_yes', displayName: 'GENERIC-YES', }, { name: 'generic_no', displayName: 'GENERIC-NO', }, { name: 'generic_no_match_nonanswer_variant_1', displayName: 'GENERIC-NO-MATCH-NONANSWER-VARIANT-1', }, { name: 'generic_no_match_nonanswer_variant_2', displayName: 'GENERIC-NO-MATCH-NONANSWER-VARIANT-2', }, { name: 'generic_no_match_nonanswer_variant_3', displayName: 'GENERIC-NO-MATCH-NONANSWER-VARIANT-3', }, ], }, }; module.exports = { TabType, OutputType, Tab, }; <|start_filename|>functions/fulfillment.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const {Card, Simple, Suggestion} = require('@assistant/conversation'); const util = require('./util'); const config = require('./config.js'); const {Action, Answer, Template, TemplateAction, Alias, Prompt, Type} = require('./constant.js'); const CanvasBuilder = require('./canvas-builder.js'); const Quiz = require('./quiz.js'); /** * Fulfillment class to handle supported ConversationV3 actions. */ class Fulfillment { /** * @return {Fulfillment} */ static create() { return new Fulfillment(); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.LOAD_SETTINGS](conv) { const quizSettings = await conv.$helper.getQuizSettings(); conv.$helper.updateConvDataQuizSettings(quizSettings); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.SETUP_QUIZ](conv) { const quizQuestions = await conv.$helper.getAllQuizQuestions(); const initQuizState = Quiz.initSessionState( quizQuestions, conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ] ); conv.session.params.data = {...conv.session.params.data, ...initQuizState}; conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ] = conv.session.params.data.limit; } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_SKIP_CONFIRMATION](conv) { const quizIntro = await conv.$helper.getRandomQuizIntro(); const introSimple = util.response.toSimple( quizIntro, Alias.QUIZ_INTRO.DISPLAYED_INTRO, Alias.QUIZ_INTRO.SPOKEN_INTRO ); const transition = { simple: introSimple.speech, rich: [new Simple(introSimple)], immersive: CanvasBuilder.create(conv.hasInteractiveCanvas, { url: config.IMMERSIVE_URL, template: Template.INTRO, action: TemplateAction.RESET, speech: introSimple.speech, data: { header: conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.INTRO_TITLE], body: conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.INTRO_SUBTITLE], progress: -1, background: { landscape: quizIntro[Alias.QUIZ_INTRO.BACKGROUND_LANDSCAPE_IMAGE], portrait: quizIntro[Alias.QUIZ_INTRO.BACKGROUND_PORTRAIT_IMAGE], }, }, config: {...conv.session.params.data.quizSettings}, }), }; return this.question(conv, transition); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_CONFIRMATION](conv) { const [ quizIntro, introConfirmationPrompt, {text: introConfirmationPositiveChip}, {text: introConfirmationNegativeChip}, ] = await Promise.all([ conv.$helper.getRandomQuizIntro(), conv.$helper.getRandomPrompt(Prompt.INTRO_CONFIRMATION), conv.$helper.getRandomPrompt(Prompt.INTRO_CONFIRMATION_POSITIVE), conv.$helper.getRandomPrompt(Prompt.INTRO_CONFIRMATION_NEGATIVE), ]); const introSimple = util.response.toSimple( quizIntro, Alias.QUIZ_INTRO.DISPLAYED_INTRO, Alias.QUIZ_INTRO.SPOKEN_INTRO ); const ssml = util.ssml.merge([introSimple.speech, introConfirmationPrompt.speech]); conv.$immersive = CanvasBuilder.create(conv.hasInteractiveCanvas, { url: config.IMMERSIVE_URL, template: Template.INTRO, action: TemplateAction.RESET, speech: ssml, data: { header: conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.INTRO_TITLE], body: conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.INTRO_SUBTITLE], progress: -1, background: { landscape: quizIntro[Alias.QUIZ_INTRO.BACKGROUND_LANDSCAPE_IMAGE], portrait: quizIntro[Alias.QUIZ_INTRO.BACKGROUND_PORTRAIT_IMAGE], }, }, suggestions: [ { text: conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.START_BUTTON_TEXT], speech: introConfirmationPositiveChip, }, ], config: {...conv.session.params.data.quizSettings}, }); return conv.$helper.ask({ simple: ssml, rich: [ new Simple(introSimple), new Simple(introConfirmationPrompt), new Suggestion({title: conv.$helper.cleanRichSuggestion(introConfirmationPositiveChip)}), new Suggestion({title: conv.$helper.cleanRichSuggestion(introConfirmationNegativeChip)}), ], immersive: [new Simple(ssml), conv.$immersive.build()], }); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_YES](conv) { const introPositivePrompt = await conv.$helper.getRandomPrompt(Prompt.INTRO_POSITIVE_RESPONSE); const transition = { simple: introPositivePrompt.speech, rich: [new Simple(introPositivePrompt)], immersive: CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.SAY, action: TemplateAction.ACTIVE_0, speech: introPositivePrompt.speech, data: {progress: -1}, config: {[Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ]: conv.session.params.data.limit}, }), }; return this.question(conv, transition); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_NO](conv) { return conv.$helper.closeWithPrompt(Prompt.INTRO_NEGATIVE_RESPONSE); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_HELP](conv) { const suggestions = await conv.$helper.buildPromptRichSuggestions([ Prompt.INTRO_CONFIRMATION_POSITIVE, Prompt.INTRO_CONFIRMATION_NEGATIVE, ]); return conv.$helper.askWithPrompt(Prompt.START_HELP, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_REPEAT](conv) { const suggestions = await conv.$helper.buildPromptRichSuggestions([ Prompt.INTRO_CONFIRMATION_POSITIVE, Prompt.INTRO_CONFIRMATION_NEGATIVE, ]); return conv.$helper.askWithPrompt(Prompt.START_REPEAT, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_NO_MATCH_1](conv) { const suggestions = await conv.$helper.buildPromptRichSuggestions([ Prompt.INTRO_CONFIRMATION_POSITIVE, Prompt.INTRO_CONFIRMATION_NEGATIVE, ]); return conv.$helper.askWithPrompt(Prompt.INTRO_NO_MATCH_1, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_NO_MATCH_2](conv) { const suggestions = await conv.$helper.buildPromptRichSuggestions([ Prompt.INTRO_CONFIRMATION_POSITIVE, Prompt.INTRO_CONFIRMATION_NEGATIVE, ]); return conv.$helper.askWithPrompt(Prompt.INTRO_NO_MATCH_2, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_NO_INPUT_1](conv) { return conv.$helper.askWithPrompt(Prompt.INTRO_NO_INPUT_1); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.START_NO_INPUT_2](conv) { return conv.$helper.askWithPrompt(Prompt.INTRO_NO_INPUT_2); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.QUESTION_REPEAT](conv) { const repeatPrompt = await conv.$helper.getRandomPrompt(Prompt.QUESTION_REPEAT); conv.$helper.setupSessionTypeAndSpeechBiasing(); const question = conv.$helper.getCurrentQuestion(); const questionSimple = util.response.toSimple( question, Alias.QUIZ_Q_A.DISPLAYED_QUESTION, Alias.QUIZ_Q_A.SPOKEN_QUESTION ); const ssml = util.ssml.merge([repeatPrompt.speech, questionSimple.speech]); return conv.$helper.ask({ simple: ssml, rich: [ new Simple(repeatPrompt), new Simple(questionSimple), ...conv.$helper.getQuestionRichSuggestions().map((chip) => new Suggestion({title: chip})), ], immersive: [ new Simple(ssml), conv.$immersive .set('template', Template.SAY) .set('speech', ssml) .build(), ], }); } /** * @param {ConversationV3} conv * @param {string} [answer] * @return {Promise} */ async [Action.ANSWER](conv, answer) { answer = answer || conv.$helper.getAndClearUserAnswer(); const question = conv.$helper.getCurrentQuestion(); const [trait, weight] = Quiz.matchAnswer(question, answer); conv.session.params.data.traitToWeight[trait] += weight; const followupSimple = util.response.toSimple( question, ...(weight > 0 ? [ Alias.QUIZ_Q_A.POSITIVE_RESPONSE_DISPLAYED_FOLLOWUP, Alias.QUIZ_Q_A.POSITIVE_RESPONSE_SPOKEN_FOLLOWUP, ] : [ Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_DISPLAYED_FOLLOWUP, Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_SPOKEN_FOLLOWUP, ]) ); let transition; if (followupSimple.speech) { transition = { simple: followupSimple.speech, rich: [], immersive: CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.SAY, action: weight > 0 ? TemplateAction.ACTIVE_0 : TemplateAction.ACTIVE_1, speech: followupSimple.speech, }), }; if (followupSimple.text) { transition.rich.push(new Simple(followupSimple)); } } return ++conv.session.params.data.count >= conv.session.params.data.limit ? this.outcome(conv, transition) : this.question(conv, transition); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_ORDINAL](conv) { if (!conv.intent.params[Type.COUNT] || !conv.intent.params[Type.COUNT].resolved) { return this[Action.ANSWER_NO_MATCH_1](conv); } return this[Action.ANSWER]( conv, conv.intent.params[Type.COUNT].resolved === Answer.FIRST ? Answer.POSITIVE : Answer.NEGATIVE ); } /** * Asks the user a question, in the order of questions for this session. * @param {ConversationV3} conv * @param {TransitionResponse} [transition] * @return {Promise} */ async question(conv, transition) { let transitionPrompt = {speech: '', text: ''}; // Default (first question) - no transition if (conv.session.params.data.count > 0) { transitionPrompt = await conv.$helper.getRandomPrompt( conv.session.params.data.count < conv.session.params.data.limit - 1 ? Prompt.TRANSITIONS_REGULAR // Second to before last question : Prompt.TRANSITIONS_FINAL // Last question ); } conv.$helper.setupSessionTypeAndSpeechBiasing(); const question = conv.$helper.getCurrentQuestion(); const questionSimple = util.response.toSimple( question, Alias.QUIZ_Q_A.DISPLAYED_QUESTION, Alias.QUIZ_Q_A.SPOKEN_QUESTION ); const speeches = [transitionPrompt.speech, questionSimple.speech]; const positiveSuggestionText = question[Alias.QUIZ_Q_A.POSITIVE_RESPONSE_ACCEPTABLE_ANSWERS][0]; const negativeSuggestionText = question[Alias.QUIZ_Q_A.NEGATIVE_RESPONSE_ACCEPTABLE_ANSWERS][0]; const canvasSpeeches = [util.ssml.merge([transitionPrompt.speech, questionSimple.speech])]; const immersiveQuestion = CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.QUESTION, action: TemplateAction.RESET, speech: util.ssml.merge([transitionPrompt.speech, questionSimple.speech]), data: { body: questionSimple.text, progress: conv.session.params.data.count, background: { landscape: question[Alias.QUIZ_Q_A.BACKGROUND_LANDSCAPE_IMAGE], portrait: question[Alias.QUIZ_Q_A.BACKGROUND_PORTRAIT_IMAGE], }, }, suggestions: [ { image: question[Alias.QUIZ_Q_A.POSITIVE_ANSWER_IMAGE], text: positiveSuggestionText, speech: util.string.stripEmoji(positiveSuggestionText), }, { image: question[Alias.QUIZ_Q_A.NEGATIVE_ANSWER_IMAGE], text: negativeSuggestionText, speech: util.string.stripEmoji(negativeSuggestionText), }, ], }); conv.$immersive = immersiveQuestion; const hasValidTransition = conv.$helper.isValidTransition(transition); if (hasValidTransition) { conv.$immersive = transition.immersive; conv.$immersive.set('next', immersiveQuestion); speeches.unshift(transition.simple); canvasSpeeches.unshift(transition.simple); } return conv.$helper.ask({ simple: util.ssml.merge(speeches), rich: [ ...(hasValidTransition ? transition.rich : []), new Simple(util.response.mergeSimple(transitionPrompt, questionSimple)), new Suggestion({title: conv.$helper.cleanRichSuggestion(positiveSuggestionText)}), new Suggestion({title: conv.$helper.cleanRichSuggestion(negativeSuggestionText)}), ], immersive: [new Simple(util.ssml.mergeWithMark(canvasSpeeches)), conv.$immersive.build()], }); } /** * Get the outcome of the quiz; sums the trait weights and match to closest outcome. * @param {ConversationV3} conv * @param {TransitionResponse} [transition] * @return {Promise} */ async outcome(conv, transition) { const [ quizOutcomes, outcomeIntroPrompt, endOfGamePrompt, {text: endOfGamePlayAgainYesChip}, {text: endOfGamePlayAgainNoChip}, ] = await Promise.all([ conv.$helper.getAllQuizOutcomes(), conv.$helper.getRandomPrompt(Prompt.OUTCOME_INTRO), conv.$helper.getRandomPrompt(Prompt.END_OF_GAME), conv.$helper.getRandomPrompt(Prompt.END_OF_GAME_PLAY_AGAIN_YES), conv.$helper.getRandomPrompt(Prompt.END_OF_GAME_PLAY_AGAIN_NO), ]); const quizOutcome = Quiz.matchOutcome(quizOutcomes, conv.session.params.data.traitToWeight); const outcomeSimple = util.response.toSimple( quizOutcome, Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME, Alias.QUIZ_OUTCOMES.SPOKEN_OUTCOME ); // "Ok, you are a {outcome}... Do you want to play again?" const outcomeSlide = CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.OUTCOME, action: TemplateAction.RESET, speech: util.ssml.merge([outcomeSimple.speech, endOfGamePrompt.speech]), data: { body: quizOutcome[Alias.QUIZ_OUTCOMES.TITLE], small: quizOutcome[Alias.QUIZ_OUTCOMES.DISPLAYED_OUTCOME], image: { landscape: quizOutcome[Alias.QUIZ_OUTCOMES.VERTICAL_IMAGE], portrait: quizOutcome[Alias.QUIZ_OUTCOMES.HORIZONTAL_IMAGE], }, background: { landscape: quizOutcome[Alias.QUIZ_OUTCOMES.BACKGROUND_LANDSCAPE_IMAGE], portrait: quizOutcome[Alias.QUIZ_OUTCOMES.BACKGROUND_PORTRAIT_IMAGE], }, }, suggestions: [ { text: conv.session.params.data.quizSettings[Alias.QUIZ_SETTINGS.RESTART_BUTTON_TEXT], speech: endOfGamePlayAgainYesChip, }, ], }); // "Let me think about that... I have it!" const outcomeIntroSlide = CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.SAY, speech: outcomeIntroPrompt.speech, data: {}, next: outcomeSlide, }); const isValidOutcomeIntro = outcomeIntroPrompt.speech.length > '<speak></speak>'.length; const startSlide = isValidOutcomeIntro ? outcomeIntroSlide : outcomeSlide; startSlide.add('data', {progress: conv.session.params.data.limit}); conv.$immersive = startSlide; const outcomeBasicCard = conv.$helper.buildOutcomeBasicCard(quizOutcome); // Show outcome title in SimpleResponse chat bubble if no BasicCard. const outcomeText = outcomeBasicCard ? '' : quizOutcome[Alias.QUIZ_OUTCOMES.TITLE] || ''; let combinedSimple = { speech: util.ssml.merge([outcomeIntroPrompt.speech, outcomeSimple.speech]), text: [outcomeIntroPrompt.text, outcomeText].join(' \n\n').trim(), }; const speeches = [outcomeIntroPrompt.speech, outcomeSimple.speech, endOfGamePrompt.speech]; const canvasSpeeches = [ outcomeIntroPrompt.speech, util.ssml.merge([outcomeSimple.speech, endOfGamePrompt.speech]), ]; // Check for previous transition slide from argument. if (conv.$helper.isValidTransition(transition)) { conv.$immersive = transition.immersive; conv.$immersive.set('next', startSlide); speeches.unshift(transition.simple); canvasSpeeches.unshift(transition.simple); if (transition.rich[0] instanceof Simple) { const transitionSimple = { text: transition.rich[0].text, speech: transition.rich[0].speech, }; combinedSimple = util.response.mergeSimple(transitionSimple, combinedSimple); } } return conv.$helper.ask({ simple: util.ssml.merge(speeches), rich: [ new Simple(combinedSimple), ...(outcomeBasicCard ? [new Card(outcomeBasicCard)] : []), new Simple(endOfGamePrompt), new Suggestion({title: conv.$helper.cleanRichSuggestion(endOfGamePlayAgainYesChip)}), new Suggestion({title: conv.$helper.cleanRichSuggestion(endOfGamePlayAgainNoChip)}), ], immersive: [new Simple(util.ssml.mergeWithMark(canvasSpeeches)), conv.$immersive.build()], }); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_BOTH_OR_NONE](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); const suggestions = conv.$helper.getQuestionRichSuggestions(); return conv.$helper.askWithPrompt(Prompt.GENERIC_NO_MATCH_NONANSWER, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_HELP](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); const suggestions = conv.$helper.getQuestionRichSuggestions(); return conv.$helper.askWithPrompt(Prompt.ANSWER_HELP, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_SKIP](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); const suggestions = conv.$helper.getQuestionRichSuggestions(); return conv.$helper.askWithPrompt(Prompt.SKIP, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_NO_MATCH_1](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); const suggestions = conv.$helper.getQuestionRichSuggestions(); return conv.$helper.askWithPrompt(Prompt.ANSWER_NO_MATCH_1, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_NO_MATCH_2](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); const suggestions = conv.$helper.getQuestionRichSuggestions(); return conv.$helper.askWithPrompt(Prompt.ANSWER_NO_MATCH_2, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_MAX_NO_MATCH](conv) { return conv.$helper.closeWithPrompt(Prompt.ANSWER_MAX_NO_MATCH); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_NO_INPUT_1](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); return conv.$helper.askWithPrompt(Prompt.ANSWER_NO_INPUT_1); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_NO_INPUT_2](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); return conv.$helper.askWithPrompt(Prompt.ANSWER_NO_INPUT_2); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.ANSWER_MAX_NO_INPUT](conv) { return conv.$helper.closeWithPrompt(Prompt.ANSWER_MAX_NO_INPUT); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.RESTART_CONFIRMATION](conv) { const suggestions = await conv.$helper.buildPromptRichSuggestions([ Prompt.END_OF_GAME_PLAY_AGAIN_YES, Prompt.END_OF_GAME_PLAY_AGAIN_NO, ]); return conv.$helper.askWithPrompt(Prompt.RESTART_CONFIRMATION, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.RESTART_YES](conv) { const [restartYesPrompt] = await Promise.all([ conv.$helper.getRandomPrompt(Prompt.RESTART_YES_RESPONSE), this[Action.SETUP_QUIZ](conv), ]); const transition = { simple: restartYesPrompt.speech, rich: [new Simple(restartYesPrompt)], immersive: CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.SAY, action: TemplateAction.RESET, speech: restartYesPrompt.speech, data: {progress: -1}, config: {[Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ]: conv.session.params.data.limit}, }), }; return this.question(conv, transition); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.RESTART_NO](conv) { return this[Action.QUIT_NO](conv); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.RESTART_REPEAT](conv) { return this[Action.RESTART_CONFIRMATION](conv); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.PLAY_AGAIN_YES](conv) { const [restartYesPrompt] = await Promise.all([ conv.$helper.getRandomPrompt(Prompt.RESTART_YES_RESPONSE), this[Action.SETUP_QUIZ](conv), ]); const transition = { simple: restartYesPrompt.speech, rich: [new Simple(restartYesPrompt)], immersive: CanvasBuilder.create(conv.hasInteractiveCanvas, { template: Template.SAY, action: TemplateAction.ACTIVE_0, speech: restartYesPrompt.speech, data: {progress: -1}, config: {[Alias.QUIZ_SETTINGS.QUESTIONS_PER_QUIZ]: conv.session.params.data.limit}, }), }; return this.question(conv, transition); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.PLAY_AGAIN_NO](conv) { return conv.$helper.closeWithPrompt(Prompt.RESTART_NO_RESPONSE); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.PLAY_AGAIN_REPEAT](conv) { return this[Action.RESTART_CONFIRMATION](conv); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.QUIT_CONFIRMATION](conv) { const suggestions = await conv.$helper.buildPromptRichSuggestions([ Prompt.GENERIC_YES, Prompt.GENERIC_NO, ]); return conv.$helper.askWithPrompt(Prompt.QUIT_CONFIRMATION, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.QUIT_YES](conv) { return conv.$helper.closeWithPrompt(Prompt.ACKNOWLEDGE_QUIT); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.QUIT_NO](conv) { conv.$helper.setupSessionTypeAndSpeechBiasing(); const suggestions = conv.$helper.getQuestionRichSuggestions(); return conv.$helper.askWithPrompt(Prompt.CONTINUE_TO_PLAY, suggestions); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.QUIT_REPEAT](conv) { return this[Action.QUIT_CONFIRMATION](conv); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.GENERIC_NO_MATCH](conv) { return conv.$helper.askWithPrompt(Prompt.GENERIC_NO_MATCH); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.GENERIC_MAX_NO_MATCH](conv) { return conv.$helper.closeWithPrompt(Prompt.GENERIC_MAX_NO_MATCH); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.GENERIC_NO_INPUT](conv) { return conv.$helper.askWithPrompt(Prompt.GENERIC_NO_INPUT); } /** * @param {ConversationV3} conv * @return {Promise} */ async [Action.GENERIC_MAX_NO_INPUT](conv) { return conv.$helper.closeWithPrompt(Prompt.GENERIC_MAX_NO_INPUT); } } module.exports = Fulfillment; <|start_filename|>canvas/src/index.css<|end_filename|> /** * Copyright 2020 Google LLC * * 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. */ /* cyrillic */ @font-face { font-family: 'Google Sans'; font-style: normal; font-weight: 400; src: local('Google Sans Regular'), local('GoogleSans-Regular'), url(https://fonts.gstatic.com/s/googlesans/v5/4UaGrENHsxJlGDuGo1OIlL3Kwp5eKQtGBlc.woff2) format('woff2'); unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; } /* greek */ @font-face { font-family: 'Google Sans'; font-style: normal; font-weight: 400; src: local('Google Sans Regular'), local('GoogleSans-Regular'), url(https://fonts.gstatic.com/s/googlesans/v5/4UaGrENHsxJlGDuGo1OIlL3Nwp5eKQtGBlc.woff2) format('woff2'); unicode-range: U+0370-03FF; } /* latin-ext */ @font-face { font-family: 'Google Sans'; font-style: normal; font-weight: 400; src: local('Google Sans Regular'), local('GoogleSans-Regular'), url(https://fonts.gstatic.com/s/googlesans/v5/4UaGrENHsxJlGDuGo1OIlL3Awp5eKQtGBlc.woff2) format('woff2'); unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Google Sans'; font-style: normal; font-weight: 400; src: local('Google Sans Regular'), local('GoogleSans-Regular'), url(https://fonts.gstatic.com/s/googlesans/v5/4UaGrENHsxJlGDuGo1OIlL3Owp5eKQtG.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } :root { --google-sans: 'Google Sans', Helvetica, sans-serif; --easing-standard: cubic-bezier(0.4, 0.0, 0.2, 1); --easing-deceleration: cubic-bezier(0.0, 0.0, 0.2, 1); --easing-acceleration: cubic-bezier(0.4, 0.0, 1, 1); --easing-sharp: cubic-bezier(0.4, 0.0, 0.6, 1); } html { box-sizing: border-box; font-size: 62.5%; } *, *:before, *:after { box-sizing: inherit; } body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-family: var(--google-sans); font-weight: 400; font-size: 1.6rem; line-height: 2.6rem; margin: 0; padding: 0; position: relative; background-color: #fff; } .view { transform: rotate(180deg); } :global(#root) { position: relative; width: 100%; height: 100%; } <|start_filename|>canvas/src/container/assistantHost.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {Component} from 'react'; import {connect} from 'react-redux'; import { addSlide, setConfig, setProgress, setFrozen, setOptionDeactive, setOptionActive, } from '../action'; import {TemplateAction, TtsMark} from '../constant'; /** * @fileoverview React-redux wrapper for the AssistantHost. Relies on reducers * to manage state. * @example * const App = () => { * return( * <div> * <Header /> * <AssistantHost/> * <Footer /> * </div> * ); * } */ class AssistantHost extends Component { constructor(props) { super(props); this.canvas = window.interactiveCanvas; this.slides = []; this.index = 0; } componentDidMount() { this.setCallbacks(); } setCallbacks() { const assistantCanvasCallbacks = {}; assistantCanvasCallbacks.onUpdate = (slides) => { // Make slide addition async to allow previous slides to flip to reach the end. setTimeout(() => { this.slides = slides; this.index = 0; const slide = this.slides[this.index]; if (slide.action) { switch (slide.action) { case TemplateAction.RESET: this.props.dispatch(setFrozen(false)); this.props.dispatch(setOptionDeactive()); break; case TemplateAction.FREEZE: this.props.dispatch(setFrozen(true)); break; case TemplateAction.ACTIVE_0: this.props.dispatch(setFrozen(true)); this.props.dispatch(setOptionActive(0)); break; case TemplateAction.ACTIVE_1: this.props.dispatch(setFrozen(true)); this.props.dispatch(setOptionActive(1)); break; default: console.error('Unknown template action:', slide.action); } } if (slide.config) { this.props.dispatch(setConfig(slide.config)); } if (slide.template) { this.props.dispatch(addSlide(slide)); } if (slide.data && slide.data.progress) { this.props.dispatch(setProgress(slide.data.progress)); } }, 0); }; assistantCanvasCallbacks.onTtsMark = (markName) => { console.log({ markName, slide: this.props.slides.length > 0 ? this.props.slides[this.props.slides.length - 1].fields : null, }); if (markName.slice(0, 4) === TtsMark.FLIP) { assistantCanvasCallbacks._flipSlide(); } else if (markName === TtsMark.END || markName === TtsMark.ERROR) { while (this.index < this.slides.length - 1) { assistantCanvasCallbacks._flipSlide(); } } }; assistantCanvasCallbacks._flipSlide = () => { if (this.index >= this.slides.length - 1) return; const slide = this.slides[++this.index]; if (slide && slide.template) { if (slide.action === TemplateAction.RESET) { this.props.dispatch(setOptionDeactive()); } this.props.dispatch(setFrozen(true)); this.props.dispatch(addSlide(slide)); if (slide.data && slide.data.progress) { this.props.dispatch(setProgress(slide.data.progress)); } } }; // Called by the Interactive Canvas web app once it has loaded to register callbacks. this.canvas.ready(assistantCanvasCallbacks); } render() { return null; } } export default connect((state) => ({ slides: state.slides, ssml: state.ssml, }))(AssistantHost); <|start_filename|>canvas/src/action/index.js<|end_filename|> // Copyright 2020, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export const Slide = { ADD: 'SLIDE_ADD', }; export const Config = { SET: 'CONFIG_SET', }; export const SSML = { SET: 'SSML_SET', UNSET: 'SSML_UNSET', }; export const Progress = { SET: 'PROGRESS_SET', }; export const Transition = { SET: 'TRANSITION_SET', }; export const Frozen = { SET: 'FREEZE_SET', }; export const Option = { ACTIVATE: 'OPTION_ACTIVATE', DEACTIVATE: 'OPTION_DEACTIVATE', }; let slideKey = 0; export const addSlide = (fields) => ({ type: Slide.ADD, id: ++slideKey, fields, }); export const setConfig = (fields) => ({ type: Config.SET, fields, }); export const setSSML = (id) => ({ type: SSML.SET, id, }); export const unsetSSML = () => ({ type: SSML.UNSET, id: null, }); export const setProgress = (id) => ({ type: Progress.SET, id, }); export const setTransition = (component) => ({ type: Transition.SET, component, }); export const setFrozen = (frozen) => ({ type: Frozen.SET, frozen, }); export const setOptionActive = (option) => ({ type: Option.ACTIVATE, option, }); export const setOptionDeactive = (option) => ({ type: Option.DEACTIVATE, option, });
jelonmusk/actions-on-google-pq2-template-sdk
<|start_filename|>css/tit-fontello.css<|end_filename|> @font-face { font-family: 'tit-fontello'; src: url('../font/tit-fontello.eot?26419932'); src: url('../font/tit-fontello.eot?26419932#iefix') format('embedded-opentype'), url('../font/tit-fontello.woff2?26419932') format('woff2'), url('../font/tit-fontello.woff?26419932') format('woff'), url('../font/tit-fontello.ttf?26419932') format('truetype'), url('../font/tit-fontello.svg?26419932#tit-fontello') format('svg'); font-weight: normal; font-style: normal; } /* Chrome hack: SVG is rendered more smooth in Windozze. 100% magic, uncomment if you need it. */ /* Note, that will break hinting! In other OS-es font will be not as sharp as it could be */ /* @media screen and (-webkit-min-device-pixel-ratio:0) { @font-face { font-family: 'tit-fontello'; src: url('../font/tit-fontello.svg?26419932#tit-fontello') format('svg'); } } */ [class^="tit-icon-"]:before, [class*=" tit-icon-"]:before { font-family: "tit-fontello"; font-style: normal; font-weight: normal; speak: none; display: inline-block; text-decoration: inherit; width: 1em; margin-right: .2em; text-align: center; /* opacity: .8; */ /* For safety - reset parent styles, that can break glyph codes*/ font-variant: normal; text-transform: none; /* fix buttons height, for twitter bootstrap */ line-height: 1em; /* Animation center compensation - margins should be symmetric */ /* remove if not needed */ margin-left: .2em; /* you can be more comfortable with increased icons size */ /* font-size: 120%; */ /* Font smoothing. That was taken from TWBS */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; /* Uncomment for 3D effect */ /* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */ } .tit-icon-floppy:before { content: '\e800'; } /* '' */ .tit-icon-upload:before { content: '\e801'; } /* '' */ .tit-icon-download-alt:before { content: '\e802'; } /* '' */ .tit-icon-download-2:before { content: '\e803'; } /* '' */ .tit-icon-arrows-cw:before { content: '\e804'; } /* '' */ .tit-icon-arrows-cw-1:before { content: '\e805'; } /* '' */ .tit-icon-eye:before { content: '\e806'; } /* '' */ .tit-icon-eye-1:before { content: '\e807'; } /* '' */ .tit-icon-eye-off:before { content: '\e808'; } /* '' */ .tit-icon-lock:before { content: '\e809'; } /* '' */ .tit-icon-lock-open:before { content: '\e80a'; } /* '' */ .tit-icon-block:before { content: '\e80b'; } /* '' */ .tit-icon-monitor:before { content: '\e80c'; } /* '' */ .tit-icon-mobile-1:before { content: '\e80d'; } /* '' */ .tit-icon-reply:before { content: '\e80e'; } /* '' */ .tit-icon-forward:before { content: '\e80f'; } /* '' */ .tit-icon-desktop-1:before { content: '\e810'; } /* '' */ .tit-icon-mobile-2:before { content: '\e811'; } /* '' */ .tit-icon-help:before { content: '\e812'; } /* '' */ .tit-icon-code:before { content: '\e913'; } /* '' */ .tit-icon-trash:before { content: '\e921'; } /* '' */ .tit-icon-download:before { content: '\e923'; } /* '' */ .tit-icon-cog:before { content: '\e925'; } /* '' */ .tit-icon-file-code:before { content: '\e933'; } /* '' */ .tit-icon-download-1:before { content: '\f02e'; } /* '' */ .tit-icon-upload-1:before { content: '\f02f'; } /* '' */ .tit-icon-menu:before { content: '\f0c9'; } /* '' */ .tit-icon-desktop:before { content: '\f108'; } /* '' */ .tit-icon-mobile:before { content: '\f10b'; } /* '' */ .tit-icon-info:before { content: '\f129'; } /* '' */ .tit-icon-lock-open-alt:before { content: '\f13e'; } /* '' */ .tit-icon-sliders:before { content: '\f1de'; } /* '' */
Nisarga-Developer/Try-It-Editor-Offline
<|start_filename|>opencl_caffe_viewer/src/opencl_caffe_viewer.cpp<|end_filename|> /* * Copyright (c) 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <cv_bridge/cv_bridge.h> #include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include <ros/ros.h> #include <object_msgs/ObjectsInBoxes.h> void cbTimeSync(const sensor_msgs::ImageConstPtr& img, const object_msgs::ObjectsInBoxes::ConstPtr& objs) { try { cv::Mat cv_image = cv_bridge::toCvShare(img, "bgr8")->image; for (auto obj : objs->objects_vector) { std::stringstream ss; ss << obj.object.object_name << ':' << obj.object.probability; cv::rectangle(cv_image, cvPoint(obj.roi.x_offset, obj.roi.y_offset), cvPoint(obj.roi.x_offset + obj.roi.width, obj.roi.y_offset + obj.roi.height), cv::Scalar(255, 242, 35)); cv::putText(cv_image, ss.str(), cvPoint(obj.roi.x_offset, obj.roi.y_offset + 20), cv::FONT_HERSHEY_PLAIN, 1.0f, cv::Scalar(0, 255, 255)); } cv::imshow("opencl_caffe_viewer", cv_image); cv::waitKey(5); } catch (cv_bridge::Exception& e) { ROS_ERROR("Could not convert from '%s' to 'bgr8'.", img->encoding.c_str()); } } int main(int argc, char** argv) { ros::init(argc, argv, "opencl_caffe_viewer"); ros::NodeHandle n; message_filters::Subscriber<sensor_msgs::Image> cam_sub(n, "/usb_cam/image_raw", 1); message_filters::Subscriber<object_msgs::ObjectsInBoxes> objs_sub(n, "opencl_caffe/inference", 1); message_filters::TimeSynchronizer<sensor_msgs::Image, object_msgs::ObjectsInBoxes> ts(cam_sub, objs_sub, 60); ts.registerCallback(boost::bind(&cbTimeSync, _1, _2)); ros::spin(); return 0; } <|start_filename|>opencl_caffe/tests/unittest_detector.cpp<|end_filename|> /* * Copyright (c) 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string> #include <utility> #include <vector> #include <fstream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <gtest/gtest.h> #include <cv_bridge/cv_bridge.h> #include <ros/package.h> #include "opencl_caffe/detector_gpu.h" TEST(UnitTestDetector, testDetectorGPU) { opencl_caffe::DetectorGpu detector; ros::NodeHandle n("~"); std::string net_config_path, weights_path, labels_path; if (!n.getParam("net_config_path", net_config_path)) { ROS_WARN("param net_cfg_path not set, use default"); } if (!n.getParam("weights_path", weights_path)) { ROS_WARN("param weights_path not set, use default"); } if (!n.getParam("labels_path", labels_path)) { ROS_WARN("param labels_path not set, use default"); } // use ASSERT instead of EXPECT ASSERT_TRUE(boost::filesystem::exists(net_config_path)); ASSERT_TRUE(boost::filesystem::exists(weights_path)); ASSERT_TRUE(boost::filesystem::exists(labels_path)); ASSERT_TRUE(detector.loadResources(net_config_path, weights_path, labels_path)); cv::Mat image = cv::imread(ros::package::getPath("opencl_caffe") + "/resources/cat.jpg"); sensor_msgs::ImagePtr image_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg(); object_msgs::ObjectsInBoxes obejcts; ASSERT_TRUE(detector.runInference(image_msg, obejcts)); ASSERT_GE(obejcts.objects_vector.size(), 1); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "ropencl_caffe_test"); return RUN_ALL_TESTS(); }
gachiemchiep/ros_opencl_caffe
<|start_filename|>index.js<|end_filename|> module.exports = require("./lib/knex-backend.js");
jacy2013/node_acl_knex_mysql
<|start_filename|>src/com/wotbrew/relic/impl/util.cljc<|end_filename|> (ns com.wotbrew.relic.impl.util "Generic utility functions, for use everywhere. Depends on nothing." (:require [clojure.string :as str])) (defn dissoc-in "Recursive dissoc, like assoc-in. Removes intermediates. Not safe on records or vectors. Map only." [m ks] (if-let [[k & ks] (seq ks)] (if (seq ks) (let [v (dissoc-in (get m k) ks)] (if (empty? v) (dissoc m k) (assoc m k v))) (dissoc m k)) m)) (defn disjoc "Convenience for remove the element x of the set at (m k) returning a new map. If the resulting set is empty, drop k from the map." [m k x] (let [ns (disj (get m k) x)] (if (empty? ns) (dissoc m k) (assoc m k ns)))) (defn disjoc-in "Recursive disjoc for a set nested in a map given a path, see disjoc. Removes intermediates. Not safe on records or vectors. Map only." [m ks x] (let [[k & ks] ks] (if ks (let [nm (disjoc-in (get m k) ks x)] (if (empty? nm) (dissoc m k) (assoc m k nm))) (let [ns (disj (get m k) x)] (if (empty? ns) (dissoc m k) (assoc m k ns)))))) (defn update-in2 "Like clojure.core/update-in but lets you specify the type of empty-map to use, e.g for nesting (sorted-map)." ([m empty ks f & args] (let [up (fn up [m ks f args] (let [[k & ks] ks] (if ks (assoc m k (up (get m k empty) ks f args)) (assoc m k (apply f (get m k) args)))))] (up m ks f args)))) (def set-conj (fnil conj #{})) (defn raise "Throws an ex-info." ([msg] (throw (ex-info msg {}))) ([msg map] (throw (ex-info msg map))) ([msg map cause] (throw (ex-info msg map cause)))) (defn realise-coll "If coll is an eduction, yields a vector." [maybe-eduction] (cond (nil? maybe-eduction) nil (coll? maybe-eduction) maybe-eduction :else (vec maybe-eduction))) ;; cross platform mutable set (defn mutable-set [] (volatile! (transient #{}))) (defn add-to-mutable-set [mset v] (vswap! mset conj! v) mset) (defn del-from-mutable-set [mset v] (vswap! mset disj! v) mset) (defn iterable-mut-set [mset] (when mset (persistent! @mset))) ;; cross platform mutable list (defn mutable-list [] (volatile! (transient []))) (defn add-to-mutable-list [mlist v] (vswap! mlist conj! v) mlist) (defn iterable-mut-list [mlist] (when mlist (persistent! @mlist))) (defn best-effort-fn-name [expr] (let [expr-str (str #?(:clj expr :cljs (.-name expr))) split-expr (str/split expr-str #"\$") ns (str/join "." (butlast split-expr)) f (last split-expr) show-ns (if (= #?(:clj "clojure.core" :cljs "cljs.core") ns) false true) [f] (str/split (str f) #"\@")] #?(:clj (clojure.lang.Compiler/demunge (if show-ns (str ns "/" f) f)) :cljs (if (empty? f) "fn" (demunge (if show-ns (str ns "/" f) f)))))) (defn vector-if-any-non-nil ([a] (when (some? a) [a])) ([a b] (when (or (some? a) (some? b)) [a b])) ([a b c] (when (or (some? a) (some? b) (some? c)) [a b c])) ([a b c & more] (when (or (some? a) (some? b) (some? c) (some some? more)) (into [a b c] more))))
The-Alchemist/relic
<|start_filename|>ein_reduce.h<|end_filename|> // Copyright 2019 Google LLC // // 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 // // https://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 ein_reduce.h * \brief Optional helper for computing Einstein reductions on arrays. */ #ifndef NDARRAY_EIN_REDUCE_H #define NDARRAY_EIN_REDUCE_H #include "array.h" namespace nda { namespace internal { // TODO: Find a way to enable operations with non-op types? e.g. scalars. template <class T> using enable_if_ein_op = std::enable_if_t<std::is_same<typename T::is_ein_op, std::true_type>::value>; template <class T> using enable_if_ein_assign = std::enable_if_t<std::is_same<typename T::is_assign, std::true_type>::value>; // Briefly, the high level goal of the next few classes is to enable construction of // expressions describing Einstein summations or other reductions. This is done using // a small expression template system. Normally, expression templates are troublesome // due to overwhemling the compiler's ability to do CSE and other optimziations. In // the case of Einstein reductions, the expressions will usually be very small... template <class Derived> struct ein_op_base { using is_ein_op = std::true_type; using is_assign = std::false_type; // We need to be able to get the derived type when creating binary operations using // this operation as an operand. const Derived& derived() const { return *static_cast<const Derived*>(this); } auto operator-() const { return make_ein_op_negate(derived()); } template <class T, class = enable_if_ein_op<T>> auto operator+(const T& r) const { return make_ein_op_add(derived(), r); } template <class T, class = enable_if_ein_op<T>> auto operator-(const T& r) const { return make_ein_op_sub(derived(), r); } template <class T, class = enable_if_ein_op<T>> auto operator*(const T& r) const { return make_ein_op_mul(derived(), r); } template <class T, class = enable_if_ein_op<T>> auto operator/(const T& r) const { return make_ein_op_div(derived(), r); } }; // A leaf operand of an Einstein reduction expression. The Is... indicate the // dimension of the reduction to use to address this operand. template <class Op, size_t... Is> struct ein_op : public ein_op_base<ein_op<Op, Is...>> { Op op; ein_op(Op op) : op(std::move(op)) {} // The largest dimension used by this operand. static constexpr index_t MaxIndex = sizeof...(Is) == 0 ? -1 : variadic_max(Is...); // auto doesn't work here because it doesn't include the reference type of operator() when we // need it, but it writing it includes it when we can't, e.g. if op(...) doesn't return a // reference. template <class Idx> NDARRAY_INLINE decltype(op(Is...)) operator()(const Idx& i) const { return op(std::get<Is>(i)...); } // Only ein_op has assignment operators. template <class T, class = enable_if_ein_op<T>> auto operator=(const T& r) const { return make_ein_op_assign(*this, r); } template <class T, class = enable_if_ein_op<T>> auto operator+=(const T& r) const { return make_ein_op_add_assign(*this, r); } template <class T, class = enable_if_ein_op<T>> auto operator-=(const T& r) const { return make_ein_op_sub_assign(*this, r); } template <class T, class = enable_if_ein_op<T>> auto operator*=(const T& r) const { return make_ein_op_mul_assign(*this, r); } }; // A unary operation on an Einstein operand. template <class Op, class Derived> struct ein_unary_op : public ein_op_base<Derived> { Op op; ein_unary_op(const Op& op) : op(op) {} static constexpr index_t MaxIndex = Op::MaxIndex; }; // Unary negate. template <class Op> struct ein_negate_op : public ein_unary_op<Op, ein_negate_op<Op>> { using base = ein_unary_op<Op, ein_negate_op<Op>>; ein_negate_op(const Op& op) : base(op) {} template <class Idx> NDARRAY_INLINE auto operator()(const Idx& i) const { return -base::op(i); } }; template <class Op> auto make_ein_op_negate(const Op& op) { return ein_negate_op<Op>(op); } // Cast to a different type. template <class Type, class Op> struct ein_cast_op : public ein_unary_op<Op, ein_cast_op<Type, Op>> { using base = ein_unary_op<Op, ein_cast_op<Type, Op>>; ein_cast_op(const Op& op) : base(op) {} template <class Idx> NDARRAY_INLINE auto operator()(const Idx& i) const { return static_cast<Type>(base::op(i)); } }; // A binary operation of two operands. template <class OpA, class OpB, class Derived> struct ein_binary_op : public ein_op_base<Derived> { OpA op_a; OpB op_b; ein_binary_op(const OpA& a, const OpB& b) : op_a(a), op_b(b) {} static constexpr index_t MaxIndex = std::max(OpA::MaxIndex, OpB::MaxIndex); }; #define NDARRAY_MAKE_EIN_BINARY_HELPERS(name, op) \ template <class OpA, class OpB> \ auto make_##name(const OpA& a, const OpB& b) { \ return name<OpA, OpB>(a, b); \ } #define NDARRAY_MAKE_EIN_BINARY_OP(name, op, is_assign_) \ template <class OpA, class OpB> \ struct name : public ein_binary_op<OpA, OpB, name<OpA, OpB>> { \ using base = ein_binary_op<OpA, OpB, name>; \ name(const OpA& a, const OpB& b) : base(a, b) {} \ using is_assign = is_assign_; \ template <class Idx> \ NDARRAY_INLINE auto operator()(const Idx& i) const { \ return base::op_a(i) op base::op_b(i); \ } \ }; \ NDARRAY_MAKE_EIN_BINARY_HELPERS(name, op) #define NDARRAY_MAKE_EIN_BINARY_FN(name, fn) \ template <class OpA, class OpB> \ struct name : public ein_binary_op<OpA, OpB, name<OpA, OpB>> { \ using base = ein_binary_op<OpA, OpB, name>; \ name(const OpA& a, const OpB& b) : base(a, b) {} \ template <class Idx> \ NDARRAY_INLINE auto operator()(const Idx& i) const { \ using std::min; \ using std::max; \ return fn(base::op_a(i), base::op_b(i)); \ } \ }; \ NDARRAY_MAKE_EIN_BINARY_HELPERS(name, op) // Define the expression types for the operations we support. NDARRAY_MAKE_EIN_BINARY_OP(ein_op_add, +, std::false_type); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_sub, -, std::false_type); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_mul, *, std::false_type); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_div, /, std::false_type); NDARRAY_MAKE_EIN_BINARY_FN(ein_op_min, min); NDARRAY_MAKE_EIN_BINARY_FN(ein_op_max, max); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_assign, =, std::true_type); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_add_assign, +=, std::true_type); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_sub_assign, -=, std::true_type); NDARRAY_MAKE_EIN_BINARY_OP(ein_op_mul_assign, *=, std::true_type); #undef NDARRAY_MAKE_EIN_BINARY_FN #undef NDARRAY_MAKE_EIN_BINARY_OP #undef NDARRAY_MAKE_EIN_BINARY_HELPERS } // namespace internal /** Cast an Einstein summation operand to a different type `Type`. * The cast is performed using `static_cast<Type>`. */ template <class Type, class Op> auto cast(const internal::ein_op_base<Op>& op) { return internal::ein_cast_op<Type, Op>(op.derived()); } /** The min or max of two Einstein summation operands. */ template <class OpA, class OpB> auto min(const internal::ein_op_base<OpA>& a, const internal::ein_op_base<OpB>& b) { return internal::make_ein_op_min(a.derived(), b.derived()); } template <class OpA, class OpB> auto max(const internal::ein_op_base<OpA>& a, const internal::ein_op_base<OpB>& b) { return internal::make_ein_op_max(a.derived(), b.derived()); } namespace internal { // Let these be found via ADL too. using nda::cast; using nda::max; using nda::min; // If multiple operands provide the same dim, we need to reconcile them // to one dim. If you follow a compiler or runtime error here, your // Einstein expression tries to address two dimensions that have different // bounds with the same loop variable. // TODO: It would be nice if this error would appear when constructing the // Einstein expression when possible, but that's really hard to do. template <class Dim0, class... Dims, class = std::enable_if_t<!any(not_equal(Dim0::Min, Dims::Min)...)>, class = std::enable_if_t<!any(not_equal(Dim0::Extent, Dims::Extent)...)>> NDARRAY_INLINE const Dim0& reconcile_dim(const Dim0& dim0, const Dims&... dims) { if (dim0.stride() != 0) { // If the first dim is an output dimension, just require the other dims // to be in-bounds. This is a slightly relaxed requirement compared to the // compile-time constraints. assert(all(dims.is_in_range(dim0)...)); } else { // If this is a reduction dimension, all of the dims must match. For // example, this is the constraint that checks that the inner dimensions of // a matrix multiplication are compatible. assert(all(dim0.min() == dims.min()...)); assert(all(dim0.extent() == dims.extent()...)); } return dim0; } // If we have zero dims, the user skipped a dim index, so we need a dummy // loop. NDARRAY_INLINE dim<0, 1, 0> reconcile_dim() { return {}; } template <class... Dims, size_t... Is> NDARRAY_INLINE auto reconcile_dim(const std::tuple<Dims...>& dims, index_sequence<Is...>) { return reconcile_dim(std::get<Is>(dims)...); } template <class... Dims> NDARRAY_INLINE auto reconcile_dim(const std::tuple<Dims...>& dims) { return reconcile_dim(dims, make_index_sequence<sizeof...(Dims)>()); } // Get the shape of an ein_reduce operand, or an empty shape if not an array. template <class T, class Shape> NDARRAY_INLINE const auto& dims_of(const array_ref<T, Shape>& op) { return op.shape().dims(); } template <class T> NDARRAY_INLINE std::tuple<> dims_of(const T& op) { return std::tuple<>(); } // Helper to reinterpret a dim with a new stride. template <index_t NewStride, index_t Min, index_t Extent, index_t Stride> NDARRAY_INLINE auto with_stride(const dim<Min, Extent, Stride>& d) { return dim<Min, Extent, NewStride>(d.min(), d.extent()); } template <index_t NewStride, class Dim> NDARRAY_INLINE auto with_stride(const std::tuple<Dim>& maybe_dim) { return std::make_tuple(with_stride<NewStride>(std::get<0>(maybe_dim))); } template <index_t NewStride> NDARRAY_INLINE std::tuple<> with_stride(std::tuple<> maybe_dim) { return maybe_dim; } // These types are flags that let us overload behavior based on these 3 options. class is_inferred_shape {}; class is_result_shape {}; class is_operand_shape {}; // Get a dim from an operand, depending on the intended use of the shape. template <size_t Dim, class Dims, size_t... Is> NDARRAY_INLINE auto gather_dims(is_result_shape, const ein_op<Dims, Is...>& op) { // If this is part of the result, we want to keep its strides. return get_or_empty<index_of<Dim, Is...>()>(dims_of(op.op)); } template <size_t Dim, class Dims, size_t... Is> NDARRAY_INLINE auto gather_dims(is_inferred_shape, const ein_op<Dims, Is...>& op) { // For inferred shapes, we want shapes without any constexpr strides, so it can be reshaped. return with_stride<dynamic>(get_or_empty<index_of<Dim, Is...>()>(dims_of(op.op))); } template <size_t Dim, class Dims, size_t... Is> NDARRAY_INLINE auto gather_dims(is_operand_shape, const ein_op<Dims, Is...>& op) { // If this is an operand shape, we want all of its dimensions to be stride 0. return with_stride<0>(get_or_empty<index_of<Dim, Is...>()>(dims_of(op.op))); } template <size_t Dim, class Kind, class Op, class X> NDARRAY_INLINE auto gather_dims(Kind kind, const ein_unary_op<Op, X>& op) { return gather_dims<Dim>(kind, op.op); } template <size_t Dim, class Kind, class OpA, class OpB, class X> NDARRAY_INLINE auto gather_dims(Kind kind, const ein_binary_op<OpA, OpB, X>& op) { return std::tuple_cat(gather_dims<Dim>(kind, op.op_a), gather_dims<Dim>(kind, op.op_b)); } template <size_t Dim, class Kind0, class Op0, class Kind1, class Op1> NDARRAY_INLINE auto gather_dims(Kind0 kind0, const Op0& op0, Kind1 kind1, const Op1& op1) { return std::tuple_cat(gather_dims<Dim>(kind0, op0), gather_dims<Dim>(kind1, op1)); } template <size_t... Is, class... KindAndOps> NDARRAY_UNIQUE auto make_ein_reduce_shape( index_sequence<Is...>, const KindAndOps&... kind_and_ops) { return make_shape(reconcile_dim(gather_dims<Is>(kind_and_ops...))...); } } // namespace internal /** Operand for an Einstein summation, which is an array or other * callable object, along with a set of dimension indices. * `ein<i, j, ...>(a)` means the dimensions `i, j, ...` of the * summation index are used to address `a` during Einstein * summation. The number of dimensions must match the number of * arguments of `a`. See `ein_reduce()` for more details. */ template <size_t... Is, class Op, class = internal::enable_if_callable<Op, decltype(Is)...>> auto ein(Op op) { return internal::ein_op<Op, Is...>(std::move(op)); } template <size_t... Is, class T, class Shape, class Alloc, class = std::enable_if_t<sizeof...(Is) == Shape::rank()>> auto ein(array<T, Shape, Alloc>& op) { return ein<Is...>(op.ref()); } template <size_t... Is, class T, class Shape, class Alloc, class = std::enable_if_t<sizeof...(Is) == Shape::rank()>> auto ein(const array<T, Shape, Alloc>& op) { return ein<Is...>(op.ref()); } /** Define an Einstein summation operand for a scalar. The scalar * is broadcasted as needed during the summation. Because this * operand does not provide a shape, the dimensions of the sum * must be inferred from other operands. See `ein_reduce()` for more * details. */ template <class T> auto ein(T& scalar) { return ein<>(array_ref<T, shape<>>(&scalar, {})); } /** Define an Einstein summation operand for a pointer and size. */ template <size_t I0, class T> auto ein(T* x, size_t N) { return ein<I0>(make_array_ref(&x[0], shape<dim<0, dynamic, 1>>(static_cast<index_t>(N)))); } /** Define an Einstein summation operand for a C array. */ template <size_t I0, class T, size_t N> auto ein(T (&x)[N]) { return ein<I0>(make_array_ref(&x[0], shape<dim<0, N, 1>>())); } /** Compute an Einstein reduction. This function allows one to specify * many kinds of array transformations and reductions using * <a href="https://en.wikipedia.org/wiki/Einstein_notation">Einstein notation</a>. * * This function accepts an expression `expr` constructed using operators * on `ein<i, j, ...>(op)` operands. These operands describe which * dimensions of the reduction index should be used to address that * operand. The rank of the reduction operation is inferred from the * number of dimensions used in the expression. The reduction operation * is executed in the order of the indices, with the lowest numbered * dimension executed as the innermost loop. * * If `expr` is a reduction operator, the result must be initialized to * some useful value, typically the identity value for the reduction * operator, e.g. `0` for `+=`. Not initializing the result allows * successive `ein_reduce` operations to be applied to the same result. * * This function does not optimize the associative order in which the * operations are performed. It evaluates the expression for each element * of the final result reduction. This can be efficient for expansion * operations, but it may be inefficient for contractions. Contractions * may need to be reassociated manually for efficient computation. * * This function does not optimize the loop ordering within each operation. * The goal of this function is to provide a low-overhead and expressive * reduction that can be composed with other explicit loop transformations * to achieve good performance. Various optimization strategies can be * implemented by splitting loops appropriately and by controlling the * order of the loops with the reduction indices. * * Examples: * - `ein_reduce(ein<>(tr_A) += ein<i, i>(A))`, the trace of `A`. * - `ein_reduce(ein<>(dot) += (ein<i>(x) + ein<i>(y)) * ein<i>(z))`, * the dot product `(x + y)*z`. * - `ein_reduce(ein<i, j>(AB) += ein<i, k>(A) * ein<k, j>(B))`, the matrix product `A*B` * - `ein_reduce(ein<i>(Ax) += ein<i, j>(A) * ein<j>(x))`, the matrix-vector product `A*x` * - `ein_reduce(ein<i>(diag_A) = ein<i, i>(A))`, the diagonal of `A`. * * where: * - `A`, `B`, `AB` are matrices (rank 2 arrays) * - `x`, `y`, `z`, `Ax` are vectors (rank 1 arrays) * - `tr_A`, `dot` are scalar (rank 0 arrays) * - `i`, `j`, `k` are unique constexpr integers. */ template <class Expr, class = internal::enable_if_ein_assign<Expr>> NDARRAY_UNIQUE auto ein_reduce(const Expr& expr) { constexpr index_t LoopRank = Expr::MaxIndex + 1; // Gather the dimensions identified by the indices. gather_dims keeps the // first dimension it finds, so we want that to be the result dimension if it // is present. If not, this selects one of the operand dimensions, which are // given stride 0. auto reduction_shape = internal::make_ein_reduce_shape(internal::make_index_sequence<LoopRank>(), internal::is_result_shape(), expr.op_a, internal::is_operand_shape(), expr.op_b); // TODO: Try to compile-time optimize reduction_shape? :) // This is maybe actually somewhat doable, simply moving the for_each_index // call below into a function that could be overloaded based on the type of // the shape would enable different optimizations. This function could be a // member of a template parameter/parameter of this function, enabling the // caller to customize the optimization. However, it's still very difficult // to make useful optimizations without making some assumptions about the // dimensions of the shape. // Perform the reduction. for_each_index_in_order(reduction_shape, expr); // Assume the expr is an assignment, and return the left-hand side. return expr.op_a.op; } /** Infer the shape of the result of `make_ein_reduce`. */ template <size_t... ResultIs, class Expr, class = internal::enable_if_ein_op<Expr>> auto make_ein_reduce_shape(const Expr& expr) { auto result_shape = internal::make_ein_reduce_shape( internal::index_sequence<ResultIs...>(), internal::is_inferred_shape(), expr); return make_compact(result_shape); } /** Compute an Einstein summation using `ein_reduce` and return the result. The * `value_type` of the result will be `T`, and the result shape will be inferred * from the shape of the operands. The result is initialized to `init` prior to * computing the summation. The Einstein summation indices for the result operand * are `ResultIs...`. * * Examples: * - `trace_A = make_ein_sum<T>(ein<i, i>(A))` * - `dot = make_ein_sum<T>((ein<i>(x) + ein<i>(y)) * ein<i>(z))` * - `AB = make_ein_sum<T, i, j>(ein<i, k>(A) * ein<k, j>(B))` * - `Ax = make_ein_sum<T, i>(ein<i, j>(A) * ein<1>(x))` * * where: * - `A`, `B` are matrices (rank 2 arrays) * - `x`, `y`, `z` are vectors (rank 1 arrays) * - `i`, `j`, `k` are unique constexpr integers. * * See `ein_reduce()` for more details. **/ // TODO: It would be nice to be able to express reductions other than sums. // TODO: Add an overload with a default ResultIs... = 0, 1, 2, ... This requires // also inferring the rank of the result. template <class T, size_t... ResultIs, class Expr, class Alloc = std::allocator<T>, class = internal::enable_if_ein_op<Expr>> NDARRAY_UNIQUE auto make_ein_sum( const Expr& expr, const T& init = T(), const Alloc& alloc = Alloc()) { auto result_shape = make_ein_reduce_shape<ResultIs...>(expr); auto result = make_array<T>(result_shape, init, alloc); ein_reduce(ein<ResultIs...>(result) += expr); return result; } } // namespace nda #endif // NDARRAY_EIN_REDUCE_H
dsharlet/array
<|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/gtests/test_memory.cpp<|end_filename|> /******************************************************************************* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <memory> #include <cstring> #include "gtest/gtest.h" #include "mkldnn_test_common.hpp" #include "mkldnn.hpp" namespace mkldnn { typedef float data_t; struct memory_test_params { memory::dims dims; memory::format_tag fmt_tag; bool expect_to_fail; mkldnn_status_t expected_status; }; class memory_test: public ::testing::TestWithParam<memory_test_params> { protected: virtual void SetUp() { memory_test_params p = ::testing::TestWithParam<decltype(p)>::GetParam(); catch_expected_failures([=](){Test();}, p.expect_to_fail, p.expected_status); } void Test() { memory_test_params p = ::testing::TestWithParam<decltype(p)>::GetParam(); auto e = engine(get_test_engine_kind(), 0); mkldnn::memory mem0({p.dims, memory::data_type::f32, p.fmt_tag}, e); auto mem0_ptr = map_memory<data_t>(mem0); memory::dim phys_size = mem0.get_desc().get_size() / sizeof(data_t); fill_data<data_t>(phys_size, mem0_ptr); std::vector<data_t> mem1_vec(phys_size); mem1_vec.assign((data_t *)mem0_ptr, (data_t *)mem0_ptr + phys_size); mkldnn::memory mem1({p.dims, memory::data_type::f32, p.fmt_tag}, e, mem1_vec.data()); check_zero_tail<data_t>(0, mem1); check_zero_tail<data_t>(1, mem0); for (memory::dim i = 0; i < phys_size; ++i) ASSERT_NEAR(mem0_ptr[i], mem1_vec[i], 1e-7) << i; } }; using fmt = memory::format_tag; TEST_P(memory_test, TestsMemory) { } CPU_INSTANTIATE_TEST_SUITE_P(TestMemory, memory_test, ::testing::Values( memory_test_params{{2, 0, 1, 1}, fmt::nChw16c}, memory_test_params{{2, 15, 3, 2}, fmt::nChw16c}, memory_test_params{{2, 15, 3, 2, 4}, fmt::nCdhw8c}, memory_test_params{{2, 9, 3, 2}, fmt::OIhw8o8i}, memory_test_params{{2, 9, 3, 2}, fmt::OIhw8i16o2i}, memory_test_params{{2, 9, 3, 2}, fmt::OIhw8o16i2o}, memory_test_params{{2, 9, 3, 2}, fmt::OIhw16o16i}, memory_test_params{{2, 9, 3, 2}, fmt::OIhw16i16o}, memory_test_params{{2, 9, 3, 2}, fmt::OIhw4i16o4i}, memory_test_params{{2, 9, 4, 3, 2}, fmt::gOihw16o}, memory_test_params{{1, 2, 9, 3, 2}, fmt::gOIhw8o8i}, memory_test_params{{1, 2, 9, 3, 2}, fmt::gOIhw4o4i}, memory_test_params{{1, 2, 9, 3, 2}, fmt::gOIhw8i8o}, memory_test_params{{2, 17, 9, 3, 2}, fmt::gOIhw4i16o4i}, memory_test_params{{2, 17, 9, 3, 2}, fmt::gOIhw2i8o4i}, memory_test_params{{15, 16, 16, 3, 3}, fmt::Goihw8g} ) ); } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/platform/utils_windows.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 <cstring> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" namespace minigo { bool FdSupportsAnsiColors(int fd) { return false; } int GetNumLogicalCpus() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; } ProcessId GetProcessId() { return ::GetCurrentProcessId(); } std::string GetHostname() { // Windows guarantees that a 256B buffer is large enough to hold the hostname, // so we don't need to worry about whether a truncated hostname is // null-terminated. char hostname[256]; return gethostname(hostname, sizeof(hostname)) == 0 ? hostname : "hostname"; } } // namespace minigo <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-16/lingvo/core/ops/ascii_tokenizer.cc<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "third_party/tensorflow_models/mlperf/models/rough/transformer_lingvo/lingvo/core/ops/ascii_tokenizer.h" #include <algorithm> #include <string> #include <unordered_map> #include "third_party/tensorflow/core/lib/strings/str_util.h" #include "third_party/tensorflow/core/platform/logging.h" namespace tensorflow { namespace babelfish { namespace { const string& FindOrDie(const std::unordered_map<int32, string>& m, int32 k) { const auto it = m.find(k); CHECK(it != m.end()); return it->second; } const int32 kUnkId = 0; const int32 kSOSId = 1; const int32 kEOSId = 2; const int32 kEOWId = 3; const int32 kNoiseId = 4; const int32 kEpsilonId = 73; const int32 kTextOnlyId = 74; const int32 kSORWId = 75; // indicator for start of rare word const int32 kMaxTokenId = 75; struct CharTokenizer { std::unordered_map<string, int32> token_to_id; std::unordered_map<int32, string> id_to_token; string epsilon_token; string unk_token; string noise_token; string eos_token; string sos_token; string text_only_token; string sorw_token; string IdToToken(int32 id) const { const auto it = id_to_token.find(id); if (it != id_to_token.end()) return it->second; return unk_token; } int32 TokenToId(const string& tok) const { const auto it = token_to_id.find(tok); if (it != token_to_id.end()) return it->second; return kUnkId; } }; const CharTokenizer* CreateTokenizer() { CharTokenizer* ct = new CharTokenizer(); ct->id_to_token = {{0, "<unk>"}, {1, "<s>"}, {2, "</s>"}, {3, " "}, {4, "<noise>"}, {5, "a"}, {6, "b"}, {7, "c"}, {8, "d"}, {9, "e"}, {10, "f"}, {11, "g"}, {12, "h"}, {13, "i"}, {14, "j"}, {15, "k"}, {16, "l"}, {17, "m"}, {18, "n"}, {19, "o"}, {20, "p"}, {21, "q"}, {22, "r"}, {23, "s"}, {24, "t"}, {25, "u"}, {26, "v"}, {27, "w"}, {28, "x"}, {29, "y"}, {30, "z"}, {31, "."}, {32, "\'"}, {33, "-"}, {34, ":"}, {35, "!"}, {36, "~"}, {37, "`"}, {38, ";"}, {39, "0"}, {40, "1"}, {41, "2"}, {42, "3"}, {43, "4"}, {44, "5"}, {45, "6"}, {46, "7"}, {47, "8"}, {48, "9"}, {49, "\""}, {50, "#"}, {51, "$"}, {52, "%"}, {53, "&"}, {54, "("}, {55, ")"}, {56, "*"}, {57, "+"}, {58, ","}, {59, "/"}, {60, "<"}, {61, "="}, {62, ">"}, {63, "?"}, {64, "@"}, {65, "["}, {66, "\\"}, {67, "]"}, {68, "^"}, {69, "_"}, {70, "{"}, {71, "|"}, {72, "}"}, {73, "<epsilon>"}, {74, "<text_only>"}, {75, "<sorw>"}}; // kEpsilonWord: end-of-block for neural transducer. for (const std::pair<const int32, string>& p : ct->id_to_token) { CHECK_LE(p.first, kMaxTokenId); CHECK(ct->token_to_id.insert({p.second, p.first}).second); } ct->unk_token = FindOrDie(ct->id_to_token, kUnkId); ct->noise_token = FindOrDie(ct->id_to_token, kNoiseId); ct->epsilon_token = FindOrDie(ct->id_to_token, kEpsilonId); ct->sos_token = FindOrDie(ct->id_to_token, kSOSId); ct->eos_token = FindOrDie(ct->id_to_token, kEOSId); ct->sorw_token = FindOrDie(ct->id_to_token, kSORWId); ct->text_only_token = FindOrDie(ct->id_to_token, kTextOnlyId); return ct; } const CharTokenizer* GetTokenizer() { static const CharTokenizer* tokenizer = CreateTokenizer(); return tokenizer; } } // namespace string AsciiTokenizer::ConvertString(const string& transcript) { string result = transcript; std::transform(result.begin(), result.end(), result.begin(), ::tolower); return result; } int32 AsciiTokenizer::NumTokens() { return kMaxTokenId + 1; } std::vector<int32> AsciiTokenizer::StringToIds(const string& label) { const CharTokenizer* tokenizer = GetTokenizer(); const string converted = ConvertString(label); const StringPiece converted_view(converted); std::vector<int32> ids; const std::vector<std::pair<string, const int32>> special_token_ids{ {tokenizer->unk_token, kUnkId}, {tokenizer->noise_token, kNoiseId}, {tokenizer->sos_token, kSOSId}, {tokenizer->eos_token, kEOSId}, {tokenizer->epsilon_token, kEpsilonId}, {tokenizer->text_only_token, kTextOnlyId}, {tokenizer->sorw_token, kSORWId}, }; for (int i = 0; i < converted.size(); ++i) { bool is_special_token = false; for (const auto& token_id : special_token_ids) { if (str_util::StartsWith(converted_view.substr(i), token_id.first)) { ids.push_back(token_id.second); i += token_id.first.size() - 1; is_special_token = true; break; } } if (!is_special_token) { ids.push_back(tokenizer->TokenToId(string(1, converted[i]))); } } return ids; } std::vector<string> AsciiTokenizer::IdToStrings(const std::vector<int32>& ids) { const CharTokenizer* tokenizer = GetTokenizer(); std::vector<string> out_strings(ids.size()); for (int i = 0; i < ids.size(); ++i) { out_strings[i] = tokenizer->IdToToken(ids[i]); } return out_strings; } string AsciiTokenizer::JoinLabels(const std::vector<string>& labels) { return str_util::Join(labels, ""); } } // namespace babelfish } // namespace tensorflow <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/weighted_mix_record_yielder.h<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef LINGVO_CORE_OPS_WEIGHTED_MIX_RECORD_YIELDER_H_ #define LINGVO_CORE_OPS_WEIGHTED_MIX_RECORD_YIELDER_H_ #include "REDACTEDsubmissions/training/v0_7/models/prod/transformer_lingvo/lingvo/core/ops/record_yielder.h" namespace tensorflow { namespace babelfish { // WeightedMixRecordYielder is a special RecordYielder that mixes examples from // yielders in a random order maintaining the mix ratio specified by // input_source_weights. // // Usage example: // BasicRecordYielder::Options opts1; // opts1.file_pattern = <file_pattern>; // opts1.seed = 301; // opts1.bufsize = 1000000; // A randomized buffer with 1M records. // opts1.parallelism = 8; // Use 8 iterators. // RecordYielder* yielder1 = BasicRecordYielder::New(opts1); // BasicRecordYielder::Options opts2; // opts2.file_pattern = <file_pattern>; // opts2.seed = 301; // opts2.bufsize = 1000000; // A randomized buffer with 1M records. // opts2.parallelism = 8; // Use 8 iterators. // RecordYielder* yielder2 = BasicRecordYielder::New(opts2); // // Use records from yielder1 for 70% of the yields. // WeightedMixRecordYielder* yielder = WeightedMixRecordYielder::New( // opts1.seed, {yielder1, yielder2}, {0.7, 0.3}); // Record record; // while (true) { // yielder->Yield(&record); // // process record. // } // yielder->Close(); // // WeightedMixRecordYielder can be accessed by multiple threads concurrently. class WeightedMixRecordYielder : public RecordYielder { public: ~WeightedMixRecordYielder() override; void Close() override; Status Yield(Record* record) override; // Creates new WeightedMixRecordYielder and takes ownership over yielders // provided. Those yielders should be properly initialized already and will be // closed once WeightedMixRecordYielder is closed. Caller is responsible // closing the WeightedMixRecordYielder returned by this function. Caller // should not delete the yielder as it will be handled internally. static WeightedMixRecordYielder* New( const int64 seed, const std::vector<RecordYielder*>& yielders, const std::vector<float>& input_source_weights); protected: WeightedMixRecordYielder(const int64 seed, const std::vector<RecordYielder*>& yielders, const std::vector<float>& input_source_weights); private: mutable absl::Mutex mu_; // PRG used for randomization. std::mt19937_64 rnd_ ABSL_GUARDED_BY(mu_); std::discrete_distribution<size_t> sample_distribution_; // A list of child yielders used as an input to the mixer. std::vector<RecordYielder*> yielders_; }; } // namespace babelfish } // namespace tensorflow #endif // LINGVO_CORE_OPS_WEIGHTED_MIX_RECORD_YIELDER_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ocl_rnn_pd.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_RNN_PD_HPP #define OCL_RNN_PD_HPP #include "common/c_types_map.hpp" #include "common/nstl.hpp" #include "common/rnn_pd.hpp" #include "common/type_helpers.hpp" #include "common/utils.hpp" #include "ocl/ocl_engine.hpp" namespace mkldnn { namespace impl { namespace ocl { struct ocl_rnn_fwd_pd_t : public rnn_fwd_pd_t { using rnn_fwd_pd_t::rnn_fwd_pd_t; virtual status_t set_default_params() { using namespace format_tag; if (src_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(src_layer_md_, tnc)); if (weights_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(weights_layer_md_, ldigo)); if (weights_iter_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(weights_iter_md_, ldigo)); if (dst_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(dst_layer_md_, tnc)); // Optional parameters if ((!types::is_zero_md(&src_iter_md_)) && (src_iter_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(src_iter_md_, ldnc)); if ((!types::is_zero_md(&src_iter_c_md_)) && (src_iter_c_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(src_iter_c_md_, ldnc)); if ((!types::is_zero_md(&bias_md_)) && (bias_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(bias_md_, ldgo)); if ((!types::is_zero_md(&dst_iter_md_)) && (dst_iter_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(dst_iter_md_, ldnc)); if ((!types::is_zero_md(&dst_iter_c_md_)) && (dst_iter_c_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(dst_iter_c_md_, ldnc)); return status::success; } }; struct ocl_rnn_bwd_pd_t : public rnn_bwd_pd_t { using rnn_bwd_pd_t::rnn_bwd_pd_t; protected: virtual status_t set_default_params() { using namespace format_tag; if (src_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(src_layer_md_, tnc)); if (weights_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(weights_layer_md_, ldgoi)); if (dst_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(dst_layer_md_, tnc)); if (weights_iter_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(weights_iter_md_, ldgoi)); if (diff_src_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(diff_src_layer_md_, tnc)); if (diff_weights_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(diff_weights_layer_md_, ldigo)); if (diff_weights_iter_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(diff_weights_iter_md_, ldigo)); if (diff_dst_layer_md_.format_kind == format_kind::any) CHECK(memory_desc_init_by_tag(diff_dst_layer_md_, tnc)); // Optional parameters if ((!types::is_zero_md(&src_iter_md_)) && (src_iter_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(src_iter_md_, ldnc)); if ((!types::is_zero_md(&src_iter_c_md_)) && (src_iter_c_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(src_iter_c_md_, ldnc)); if ((!types::is_zero_md(&bias_md_)) && (bias_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(bias_md_, ldgo)); if ((!types::is_zero_md(&dst_iter_md_)) && (dst_iter_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(dst_iter_md_, ldnc)); if ((!types::is_zero_md(&dst_iter_c_md_)) && (dst_iter_c_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(dst_iter_c_md_, ldnc)); if ((!types::is_zero_md(&diff_src_iter_md_)) && (diff_src_iter_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(diff_src_iter_md_, ldnc)); if ((!types::is_zero_md(&diff_src_iter_c_md_)) && (diff_src_iter_c_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(diff_src_iter_c_md_, ldnc)); if ((!types::is_zero_md(&diff_bias_md_)) && (diff_bias_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(diff_bias_md_, ldgo)); if ((!types::is_zero_md(&diff_dst_iter_md_)) && (diff_dst_iter_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(diff_dst_iter_md_, ldnc)); if ((!types::is_zero_md(&diff_dst_iter_c_md_)) && (diff_dst_iter_c_md_.format_kind == format_kind::any)) CHECK(memory_desc_init_by_tag(diff_dst_iter_c_md_, ldnc)); return status::success; } }; } } } #endif <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/position.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_POSITION_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_POSITION_H_ #include <array> #include <cstdint> #include <memory> #include <string> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/color.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/coord.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/group.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/inline_vector.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/padded_array.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/stone.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/zobrist.h" namespace minigo { // Array of neighbor points for each point on the board. extern const std::array<inline_vector<Coord, 4>, kN * kN> kNeighborCoords; // A fixed-capacity stack of Coords used when traversing connected points on // the board. class CoordStack : private inline_vector<Coord, kN * kN> { using Impl = inline_vector<Coord, kN * kN>; public: using Impl::empty; void push(Coord c) { Impl::push_back(c); } Coord pop() { auto result = Impl::back(); Impl::pop_back(); return result; } }; // BoardVisitor visits points on the board only once. // A simple example that visits all points on the board only once: // BoardVisitor bv; // bv.Begin() // bv.Visit(0); // while (!bv.Done()) { // Coord coord = bv.Next(); // std::cout << "Visiting " << coord << "\n"; // for (auto neighbor_coord : GetNeighbors(coord)) { // bv.Visit(neighbor_coord); // } // } // // Points are visited in the order that they are passed to Visit for the first // time. class BoardVisitor { public: BoardVisitor() = default; // Starts a new visit around the board. void Begin() { MG_DCHECK(Done()); if (++epoch_ == 0) { memset(visited_.data(), 0, sizeof(visited_)); epoch_ = 1; } } // Returns true when there are no more points to visit. bool Done() const { return stack_.empty(); } // Returns the coordinates of the next point in the stack to visit. Coord Next() { return stack_.pop(); } // If this is the first time Visit has been passed coordinate c since the // most recent call to Begin, Visit pushes the coordinate onto its stack of // points to visit and returns true. Otherwise, Visit returns false. bool Visit(Coord c) { if (visited_[c] != epoch_) { visited_[c] = epoch_; stack_.push(c); return true; } return false; } private: CoordStack stack_; std::array<uint8_t, kN * kN> visited_; // Initializing to 0xff means the visited_ array will get initialized on the // first call to Begin(). uint8_t epoch_ = 0xff; }; // GroupVisitor simply keeps track of which groups have been visited since the // most recent call to Begin. Unlike BoardVisitor, it does not keep a pending // stack of groups to visit. class GroupVisitor { public: GroupVisitor() = default; void Begin() { if (++epoch_ == 0) { memset(visited_.data(), 0, sizeof(visited_)); epoch_ = 1; } } bool Visit(GroupId id) { if (visited_[id] != epoch_) { visited_[id] = epoch_; return true; } return false; } private: std::array<uint8_t, Group::kMaxNumGroups> visited_; // Initializing to 0xff means the visited_ array will get initialized on the // first call to Begin(). uint8_t epoch_ = 0xff; }; // Position represents a single board position. // It tracks the stones on the board and their groups, and contains the logic // for removing groups with no remaining liberties and merging neighboring // groups of the same color. // // Since the MCTS code makes a copy of the board position for each expanded // node in the tree, we aim to keep the data structures as compact as possible. // This is in tension with our other aim of avoiding heap allocations where // possible, which means we have to preallocate some pools of memory. In // particular, the BoardVisitor and GroupVisitor classes that Position uses to // update its internal state are relatively large compared to the board size // (even though we're only talking a couple of kB in total. Consequently, the // caller of the Position code must pass pointers to previously allocated // instances of BoardVisitor and GroupVisitor. These can then be reused by all // instances of the Position class. class Position { public: using Stones = std::array<Stone, kN * kN>; // State required to undo a call to PlayMove. struct UndoState { UndoState(Coord c, Color to_play, Coord ko) : c(c), to_play(to_play), ko(ko) {} Coord c; Color to_play; Coord ko; inline_vector<Coord, 4> captures; }; // Calculates the Zobrist hash for an array of stones. Prefer using // Position::stone_hash() if possible. static zobrist::Hash CalculateStoneHash(const Stones& stones); // Interface used to enforce positional superko based on the Zobrist hash of // a position. class ZobristHistory { public: virtual ~ZobristHistory() = default; virtual bool HasPositionBeenPlayedBefore( zobrist::Hash stone_hash) const = 0; }; // Initializes an empty board. // All moves are considered legal. explicit Position(Color to_play); Position(const Position&) = default; Position& operator=(const Position&) = default; // Plays the given move and updates which moves are legal. // If zobrist_history is non-null, move legality considers positional superko. // If zobrist_history is null, positional superko is not considered when // updating the legal moves, only ko. // Returns an UndoState object that allows the move to be undone. UndoState PlayMove(Coord c, Color color = Color::kEmpty, ZobristHistory* zobrist_history = nullptr); // Undoes the move recent call to PlayMove. void UndoMove(const UndoState& undo, ZobristHistory* zobrist_history = nullptr); // TODO(tommadams): Do we really need to store this on the position? Return // the number of captured stones from AddStoneToBoard and track the number of // captures in the player. const std::array<int, 2>& num_captures() const { return num_captures_; } // Calculates the score from B perspective. If W is winning, score is // negative. float CalculateScore(float komi) const; // Calculates all pass-alive region that are enclosed by groups of `color` // stones. // Elements in the returned array are set to `Color::kBlack` or // `Color::kWhite` if they belong to a pass-alive region or `Color::kEmpty` // otherwise. Only intersections inside the enclosed region are set, // intersections that are part of an enclosing group are set to // `Color::kEmpty`. Concretely, given the following position: // X . X . O X . // X X X X X X . // . . . . . . . // The returned array will be set to: // . X . X X . . // . . . . . . . std::array<Color, kN * kN> CalculatePassAliveRegions() const; // Returns true if the whole board is pass-alive. bool CalculateWholeBoardPassAlive() const; // Returns true if playing this move is legal. // Does not check positional superko. // legal_move(c) can be used to check for positional superko. enum class MoveType { // The position is illegal: // - a stone is already at that position. // - the move is ko. // - the move is suicidal. kIllegal, // The move will not capture an opponent's group. // The move is not necessarily legal because of superko. kNoCapture, // The move will capture an opponent's group. // The move is not necessarily legal because of superko. kCapture, }; MoveType ClassifyMoveIgnoringSuperko(Coord c) const; std::string ToSimpleString() const; std::string ToPrettyString(bool use_ansi_colors = true) const; Color to_play() const { return to_play_; } const Stones& stones() const { return stones_; } int n() const { return n_; } Coord ko() const { return ko_; } zobrist::Hash stone_hash() const { return stone_hash_; } uint8_t legal_move(Coord c) const { MG_DCHECK(c < kNumMoves); return legal_moves_[c]; } const PaddedArray<uint8_t, kNumMoves>& legal_moves() const { return legal_moves_; } // Returns the number of liberties the chain at c has. int num_chain_liberties(Coord c) const { MG_DCHECK(c <= kN * kN); auto s = stones_[c]; return s.empty() ? 0 : groups_[s.group_id()].num_liberties; } int chain_size(Coord c) const { MG_DCHECK(c <= kN * kN); auto s = stones_[c]; return s.empty() ? 0 : groups_[s.group_id()].size; } // The following methods are protected to enable direct testing by unit tests. protected: // Returns the Group of the stone at the given coordinate. Used for testing. Group GroupAt(Coord c) const { auto s = stones_[c]; return s.empty() ? Group() : groups_[s.group_id()]; } // Returns color C if the position at idx is empty and surrounded on all // sides by stones of color C. // Returns Color::kEmpty otherwise. Color IsKoish(Coord c) const; // Adds the stone to the board. // Removes newly surrounded opponent groups. // DOES NOT update legal_moves_: callers of AddStoneToBoard must explicitly // call UpdateLegalMoves afterwards (this is because UpdateLegalMoves uses // AddStoneToBoard internally). // Updates liberty counts of remaining groups. // Updates num_captures_. // If the move captures a single stone, sets ko_ to the coordinate of that // stone. Sets ko_ to kInvalid otherwise. // Returns a list of the neighbors of c that belonged to groups that were // captured by this move. inline_vector<Coord, 4> AddStoneToBoard(Coord c, Color color); // Updates legal_moves_. // If zobrist_history is non-null, this takes into account positional superko. void UpdateLegalMoves(ZobristHistory* zobrist_history); private: // Sets the pass alive regions for the given color in result. // The caller is responsible for initializing all elements in `result` to // `Color::kEmpty` before calling. void CalculatePassAliveRegionsForColor( Color color, BoardVisitor* board_visitor, GroupVisitor* group_visitor, std::array<Color, kN * kN>* result) const; // Removes the group with a stone at the given coordinate from the board, // updating the liberty counts of neighboring groups. void RemoveGroup(Coord c); // Merge neighboring groups of the same color as the stone at coordinate c // into that stone's group. Called when a stone is placed on the board that // has two or more distinct neighboring groups of the same color. void MergeGroup(Coord c); // Called as part of UndoMove for the given color at point capture_c. // Replaces the previously captured stones at point group_c. GroupId UncaptureGroup(Color color, Coord capture_c, Coord group_c); // Called as part of UndoMove. // Create a new group for the chain of stones at c. void AssignNewGroup(Coord c, BoardVisitor* board_visitor); // Returns true if the point at coordinate c neighbors the given group. bool HasNeighboringGroup(Coord c, GroupId group_id) const; Stones stones_; GroupPool groups_; Color to_play_; Coord ko_ = Coord::kInvalid; // Number of captures for (B, W). // TODO(tommadams): remove this from the Position class and track it in the // game instead. std::array<int, 2> num_captures_{{0, 0}}; int n_ = 0; // MctsNode::CalculateChildActionScoreSse requires that `legal_moves_` is // padded to a multiple of 16 bytes. PaddedArray<uint8_t, kNumMoves> legal_moves_; // Zobrist hash of the stones. It can be used for positional superko. // This has does not include number of consecutive passes or ko, so should not // be used for caching inferences. zobrist::Hash stone_hash_ = 0; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_POSITION_H_ <|start_filename|>NVIDIA/benchmarks/gnmt/implementations/pytorch/seq2seq/csrc/attn_score_cuda_kernel.cu<|end_filename|> #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <ATen/AccumulateType.h> #include <THC/THC.h> #define ASSERT_INT4_ALIGNED(PTR) \ AT_ASSERTM(is_aligned<int4>(PTR), "Tensor is not int4 aligned") template<class T> bool is_aligned(const void * ptr) noexcept { auto iptr = reinterpret_cast<std::uintptr_t>(ptr); return !(iptr % alignof(T)); } /** Each block process TILE_Q*TILE_K*hidden volumn. */ template <int TILE, typename scalar_t, typename accscalar_t, typename outscalar_t> __global__ void cunn_AttnScoreForward( outscalar_t *output, const scalar_t* __restrict__ attn_query, const scalar_t* __restrict__ attn_keys, const scalar_t* __restrict__ bias, const scalar_t* __restrict__ linear_attn, int t_q, int t_k, int hidden) { extern __shared__ unsigned char smem[]; auto tmp_q = reinterpret_cast<scalar_t*>(smem); auto tmp_k = tmp_q + TILE * blockDim.x; auto tmp_b = tmp_k + TILE * blockDim.x; auto tmp_l = tmp_b + blockDim.x; auto tmp_o = reinterpret_cast<accscalar_t*>(tmp_l + blockDim.x); int batch_id = blockIdx.x; int q_start = blockIdx.y * TILE; int k_start = blockIdx.z * TILE; attn_query += batch_id*t_q*hidden + q_start*hidden; attn_keys += batch_id*t_k*hidden + k_start*hidden; output += batch_id*t_q*t_k; // initialize intermediate result #pragma unroll for (int i = 0; i < TILE; i++) #pragma unroll for (int j = 0; j < TILE; j++) tmp_o[i*TILE*blockDim.x+j*blockDim.x+threadIdx.x] = 0; // ilpReduce int offset = threadIdx.x; int last = hidden % blockDim.x; // ilpReduce on regular data for (; offset < hidden - last; offset += blockDim.x) { // prolog: load query slices to shared memory for (int i = 0; i < t_q - q_start && i < TILE; i++) tmp_q[i*blockDim.x+threadIdx.x] = attn_query[i*hidden+offset]; // prolog: load key slices to shared memory for (int i = 0; i < t_k - k_start && i < TILE; i++) tmp_k[i*blockDim.x+threadIdx.x] = attn_keys[i*hidden+offset]; // prolog: load bias and linear_attn slices to shared memory tmp_b[threadIdx.x] = bias[offset]; tmp_l[threadIdx.x] = linear_attn[offset]; // main loop for (int i = 0; i < t_q - q_start && i < TILE; i++) { for (int j = 0; j < t_k - k_start && j < TILE; j++) { accscalar_t s = static_cast<accscalar_t>( tmp_q[i*blockDim.x+threadIdx.x] + tmp_k[j*blockDim.x+threadIdx.x] + tmp_b[threadIdx.x]); tmp_o[i*TILE*blockDim.x+j*blockDim.x+threadIdx.x] += tanhf(s) * tmp_l[threadIdx.x]; } } } // ilpReduce on boundary for (; offset < hidden; offset += blockDim.x) { // prolog: load query slices to shared memory for (int i = 0; i < t_q - q_start && i < TILE; i++) tmp_q[i*blockDim.x+threadIdx.x] = attn_query[i*hidden+offset]; // prolog: load key slices to shared memory for (int i = 0; i < t_k - k_start && i < TILE; i++) tmp_k[i*blockDim.x+threadIdx.x] = attn_keys[i*hidden+offset]; // prolog: load bias and linear_attn slices to shared memory tmp_b[threadIdx.x] = bias[offset]; tmp_l[threadIdx.x] = linear_attn[offset]; // main loop for (int i = 0; i < t_q - q_start && i < TILE; i++) { for (int j = 0; j < t_k - k_start && j < TILE; j++) { accscalar_t s = static_cast<accscalar_t>( tmp_q[i*blockDim.x+threadIdx.x] + tmp_k[j*blockDim.x+threadIdx.x] + tmp_b[threadIdx.x]); tmp_o[i*TILE*blockDim.x+j*blockDim.x+threadIdx.x] += tanhf(s) * tmp_l[threadIdx.x]; } } } // blockReduce __syncthreads(); // First warp will perform per-warp reductions for the remaining warps uint32_t mask = (((uint64_t)1) << (blockDim.x / 32)) - 1; if (threadIdx.x < 32) { int lane = threadIdx.x % 32; if (lane < blockDim.x / 32) { for (int i = 0; i < t_q - q_start && i < TILE; i++) { for (int j = 0; j < t_k - k_start && j < TILE; j++) { accscalar_t warpVal = static_cast<accscalar_t>(0); #pragma unroll for (int k = 0; k < 32; ++k) { warpVal += tmp_o[i*TILE*blockDim.x+j*blockDim.x+lane*32+k]; } __syncwarp(mask); tmp_o[i*TILE*blockDim.x+j*blockDim.x+lane] = warpVal; } } } } __syncthreads(); // First thread will perform a reduction of the above per-warp reductions if (threadIdx.x == 0) { for (int i = 0; i < t_q - q_start && i < TILE; i++) { for (int j = 0; j < t_k - k_start && j < TILE; j++) { accscalar_t blockVal = static_cast<accscalar_t>(0); for (int k = 0; k < blockDim.x / 32; ++k) { blockVal += tmp_o[i*TILE*blockDim.x+j*blockDim.x+k]; } output[(i+q_start)*t_k+(j+k_start)] = static_cast<outscalar_t>(blockVal); } } } // Sync and broadcast __syncthreads(); } at::Tensor attn_score_forward_cuda( const at::Tensor &attn_query, const at::Tensor &attn_keys, const at::Tensor &bias, const at::Tensor &linear_attn) { int batch_sz = attn_query.size(0); int t_q = attn_query.size(1); int t_k = attn_keys.size(1); int hidden = attn_query.size(2); at::Tensor output = at::empty({batch_sz, t_q, t_k}, attn_query.options()); const int TILE = 4; int grid_x = batch_sz; int grid_y = (t_q + TILE - 1) / TILE; int grid_z = (t_k + TILE - 1) / TILE; // Each block process TILE_Q*TILE_K*hidden volumn. dim3 block(128); dim3 grid(grid_x, grid_y, grid_z); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); // Each block load (TILE_Q+TILE_K)*block.x volumn each time // Each block load block.x volumn bias and linear_attn // Each thread reserve its local results for intra block reduction AT_DISPATCH_FLOATING_TYPES_AND_HALF(attn_query.scalar_type(), "attn_score_fprop", [&] { using accscalar_t = at::acc_type<scalar_t, true>; cunn_AttnScoreForward<TILE, scalar_t, accscalar_t, scalar_t> <<<grid, block, (2*TILE+2)*block.x * sizeof(scalar_t)+ block.x * TILE * TILE * sizeof(accscalar_t), stream>>>( output.data_ptr<scalar_t>(), attn_query.data_ptr<scalar_t>(), attn_keys.data_ptr<scalar_t>(), bias.data_ptr<scalar_t>(), linear_attn.data_ptr<scalar_t>(), t_q, t_k, hidden ); }); THCudaCheck(cudaGetLastError()); return output; } // Extends cuda/include/vector_types.h struct __builtin_align__(16) float8 { float x0, x1, x2, x3, x4, x5, x6, x7; }; typedef struct float8 float8; // Extends torch/include/ATen/AccumulateType.h template <typename T, typename U> struct VectorType {}; #if defined(__CUDACC__) || defined(__HIPCC__) template <> struct VectorType<half, float> { using type = float8; }; #endif template <> struct VectorType<at::Half, float> { using type = float8; }; template <> struct VectorType<float, float> { using type = float4; }; template <> struct VectorType<double, double> { using type = double2; }; template<typename T, typename U> using vec_type = typename VectorType<T, U>::type; // Convert int4 data to corresponding to vector type void __device__ __inline__ int4ToVector(float8 *dst, int4 *src) { at::Half *src_t = reinterpret_cast<at::Half *>(src); dst->x0 = static_cast<float>(src_t[0]); dst->x1 = static_cast<float>(src_t[1]); dst->x2 = static_cast<float>(src_t[2]); dst->x3 = static_cast<float>(src_t[3]); dst->x4 = static_cast<float>(src_t[4]); dst->x5 = static_cast<float>(src_t[5]); dst->x6 = static_cast<float>(src_t[6]); dst->x7 = static_cast<float>(src_t[7]); } void __device__ __inline__ int4ToVector(float4 *dst, int4 *src) { float4 *src_t = reinterpret_cast<float4 *>(src); *dst = *src_t; } void __device__ __inline__ int4ToVector(double2 *dst, int4 *src) { double2 *src_t = reinterpret_cast<double2 *>(src); *dst = *src_t; } // Convert vector type to int4 void __device__ __inline__ vectorToInt4(int4 *dst, float8 *src) { at::Half *dst_t = reinterpret_cast<at::Half *>(dst); dst_t[0] = static_cast<at::Half>(src->x0); dst_t[1] = static_cast<at::Half>(src->x1); dst_t[2] = static_cast<at::Half>(src->x2); dst_t[3] = static_cast<at::Half>(src->x3); dst_t[4] = static_cast<at::Half>(src->x4); dst_t[5] = static_cast<at::Half>(src->x5); dst_t[6] = static_cast<at::Half>(src->x6); dst_t[7] = static_cast<at::Half>(src->x7); } void __device__ __inline__ vectorToInt4(int4 *dst, float4 *src) { int4 *src_t = reinterpret_cast<int4 *>(src); *dst = *src_t; } void __device__ __inline__ vectorToInt4(int4 *dst, double2 *src) { int4 *src_t = reinterpret_cast<int4 *>(src); *dst = *src_t; } /** * Each block process BZ*t_q*t_k*LEN volumn. */ template <int THREADS, int ILP, int LEN, int TILE, int BZ, typename scalar_t, typename accscalar_t, typename vector_t, typename outscalar_t> __global__ void cunn_AttnScoreBackward( outscalar_t *grad_query, outscalar_t *grad_key, outscalar_t *grad_biases, outscalar_t *grad_lins, const scalar_t* __restrict__ grad_output, const scalar_t* __restrict__ attn_query, const scalar_t* __restrict__ attn_key, const scalar_t* __restrict__ bias, const scalar_t* __restrict__ linear_attn, int batch_sz, int t_q, int t_k, int hidden) { // common parameter check static_assert((LEN > 1) & !(LEN & (LEN - 1)), "LEN should be power of 2 for faster mod."); static_assert((TILE > 1) & !(TILE & (TILE - 1)), "TILE should be power of 2 for faster round down."); static_assert((LEN/ILP > 1) & !(LEN/ILP & (LEN/ILP - 1)), "LEN/ILP should be power of 2 for faster mod."); static_assert(TILE*TILE*LEN/ILP%THREADS == 0, "Tailing of tile is not expected."); static_assert(TILE*LEN == ILP*THREADS, "Expect threads process a 2D slice of one TILE each time for better performance."); static_assert(TILE % ILP == 0, "Expect gradients w.r.t. output can use int4."); // calculate rounded up/down bounday int t_kd = t_k & ~(TILE - 1); int t_qu = (t_q + TILE - 1) / TILE * TILE; int t_ku = (t_k + TILE - 1) / TILE * TILE; // assign shared memory address // keep input key as scalar_t to reduce shared memory usage extern __shared__ unsigned char smem[]; auto tmp_qk = reinterpret_cast<accscalar_t*>(smem); auto tmp_gk = tmp_qk + TILE * LEN; auto tmp_k = reinterpret_cast<scalar_t*>(tmp_gk + t_ku * LEN); // calculate hidden start and batch start int tid = threadIdx.x; int h_start = blockIdx.x % (hidden / LEN) * LEN; int n_start = blockIdx.x / (hidden / LEN) * BZ; int h_offset = (tid & (LEN / ILP - 1)) * ILP; // update pointers with offset grad_output += n_start * t_q * t_k; attn_query += h_start + n_start * t_q * hidden; attn_key += h_start + n_start * t_k * hidden; bias += h_start; linear_attn += h_start; grad_query += h_start + n_start * t_q * hidden; grad_key += h_start + n_start * t_k * hidden; grad_biases += blockIdx.x * LEN; grad_lins += blockIdx.x * LEN; // load bias and linear_attn volume to registers // assume one thread process the same hidden id static_assert(THREADS % (LEN / ILP) == 0, "Expect one thread process the same hidden index."); vector_t tmp_b, tmp_l; int4ToVector(&tmp_b, (int4*)(&bias[h_offset])); int4ToVector(&tmp_l, (int4*)(&linear_attn[h_offset])); // initialize bias and linear_attn gradients to zero vector_t tmp_gb = {0}, tmp_gl = {0}; for (int n=0; n<BZ && n<(batch_sz-n_start); n++) { // initialize gradients of key to zero // load batch specific key to shared memory for (int i=tid*ILP; i<t_kd*LEN; i+=THREADS*ILP) { *(int4*)&tmp_k[i] = *(int4*)&attn_key[i/LEN*hidden + (i&(LEN-1))]; *(vector_t*)&tmp_gk[i] = {0}; } for (int i=t_kd*LEN+tid*ILP; i<t_ku*LEN; i+=THREADS*ILP) { if (i/LEN >= t_k) *(int4*)&tmp_k[i] = {0}; else *(int4*)&tmp_k[i] = *(int4*)&attn_key[i/LEN*hidden + (i&(LEN-1))]; *(vector_t*)&tmp_gk[i] = {0}; } __syncthreads(); // loop each tile along query dimension for (int tile_q=0; tile_q<t_qu; tile_q+=TILE) { // load per thread query of shape ILP to registers // initialize gradients of query to zero int q_id = tile_q + tid / (LEN / ILP); vector_t tmp_q = {0}, tmp_gq = {0}; if (q_id < t_q) int4ToVector(&tmp_q, (int4*)&attn_query[q_id*hidden + h_offset]); // loop each tile along key dimension for (int tile_k=0; tile_k<t_ku; tile_k+=TILE) { // load per thread g_o of shape TILE to registers accscalar_t tmp_go[TILE] = {0}; if (q_id < t_q) { const scalar_t *grad_o = grad_output + q_id * t_k + tile_k; if (tile_k < t_kd) { #pragma unroll for (int i=0; i<TILE/ILP; i++) { int4ToVector(&((vector_t *)tmp_go)[i], (int4*)&grad_o[i*ILP]); } } else { for (int i=0; i<t_k-t_kd; i++) { tmp_go[i] = static_cast<accscalar_t>(grad_o[i]); } } } __syncthreads(); // loop each TILE_Q * LEN slice along key dimension for (int k=tile_k; k<tile_k+TILE; k++) { // load per thread k and g_k to registers vector_t tmp_k_r; int idx = k * LEN + h_offset; int4ToVector(&tmp_k_r, (int4*)&tmp_k[idx]); accscalar_t t; vector_t g_qk = {0}; #pragma unroll for (int i=0; i<ILP; i++) { t = *((accscalar_t *)(&tmp_q)+i) + *((accscalar_t *)(&tmp_k_r)+i) + *((accscalar_t *)(&tmp_b)+i); t = tanhf(t); *((accscalar_t *)(&tmp_gl)+i) += t * tmp_go[k - tile_k]; t = *((accscalar_t *)(&tmp_l)+i) * tmp_go[k - tile_k] * (1.f - t * t); *((accscalar_t *)(&tmp_gq)+i) += t; *((accscalar_t *)(&g_qk)+i) = t; } ((vector_t*)tmp_qk)[tid] = g_qk; __syncthreads(); // reduce gradients of key, TILE*LEN == THREADS*ILP t = 0; #pragma unroll for (int i=0; i<ILP; i++) { t += tmp_qk[tid + THREADS*i]; } tmp_qk[tid] = t; __syncthreads(); if (LEN <= 512 && THREADS >= 1024 && tid < 512) tmp_qk[tid] += tmp_qk[tid + 512]; __syncthreads(); if (LEN <= 256 && THREADS >= 512 && tid < 256) tmp_qk[tid] += tmp_qk[tid + 256]; __syncthreads(); if (LEN <= 128 && THREADS >= 256 && tid < 128) tmp_qk[tid] += tmp_qk[tid + 128]; __syncthreads(); if (LEN <= 64 && THREADS >= 128 && tid < 64) tmp_qk[tid] += tmp_qk[tid + 64]; __syncthreads(); if (LEN <= 32 && tid < 32) { accscalar_t t; #pragma unroll for (int m=32; m>=LEN; m>>=1) { t = tmp_qk[tid] + tmp_qk[tid + m]; __syncwarp(); tmp_qk[tid] = t; } } __syncthreads(); if (tid < LEN) { tmp_gk[k * LEN + tid] += tmp_qk[tid]; } __syncthreads(); } } // store g_q to global memory // accumulate partial g_b using g_q if (q_id < t_q) { vectorToInt4((int4*)&grad_query[q_id*hidden + h_offset], &tmp_gq); #pragma unroll for (int i=0; i<ILP; i++) { *((accscalar_t *)(&tmp_gb)+i) += *((accscalar_t *)(&tmp_gq)+i); } } } // store g_k to global memory for (int i=tid*ILP; i<t_k*LEN; i+=THREADS*ILP) { vectorToInt4((int4*)&grad_key[i/LEN*hidden + (i&(LEN-1))], (vector_t*)&tmp_gk[i]); } // update pointer for next batch grad_output += t_q * t_k; grad_query += t_q * hidden; grad_key += t_k * hidden; attn_query += t_q * hidden; attn_key += t_k * hidden; } // reduce partial g_b, g_l auto smem_gb = reinterpret_cast<accscalar_t*>(smem); auto smem_gl = smem_gb + THREADS * ILP; *(vector_t*)&smem_gb[tid * ILP] = tmp_gb; *(vector_t*)&smem_gl[tid * ILP] = tmp_gl; __syncthreads(); accscalar_t s = 0, t = 0; #pragma unroll for (int i=0; i<ILP; i++) { s += smem_gb[tid + THREADS*i]; t += smem_gl[tid + THREADS*i]; } smem_gb[tid] = s; smem_gl[tid] = t; __syncthreads(); if (LEN <= 512 && THREADS >= 1024 && tid < 512) { smem_gb[tid] += smem_gb[tid + 512]; smem_gl[tid] += smem_gl[tid + 512]; } __syncthreads(); if (LEN <= 256 && THREADS >= 512 && tid < 256) { smem_gb[tid] += smem_gb[tid + 256]; smem_gl[tid] += smem_gl[tid + 256]; } __syncthreads(); if (LEN <= 128 && THREADS >= 256 && tid < 128) { smem_gb[tid] += smem_gb[tid + 128]; smem_gl[tid] += smem_gl[tid + 128]; } __syncthreads(); if (LEN <= 64 && THREADS >= 128 && tid < 64) { smem_gb[tid] += smem_gb[tid + 64]; smem_gl[tid] += smem_gl[tid + 64]; } __syncthreads(); if (LEN <= 32 && tid < 32) { #pragma unroll for (int m=32; m>=LEN; m>>=1) { t = smem_gb[tid] + smem_gb[tid + m]; s = smem_gl[tid] + smem_gl[tid + m]; __syncwarp(); smem_gb[tid] = t; smem_gl[tid] = s; } } __syncthreads(); // store per CTA g_b, g_l to global memory if (tid < LEN / ILP) { vectorToInt4((int4*)&grad_biases[h_offset], (vector_t*)&smem_gb[h_offset]); vectorToInt4((int4*)&grad_lins[h_offset], (vector_t*)&smem_gl[h_offset]); } __syncthreads(); } std::vector<at::Tensor> attn_score_backward_cuda( const at::Tensor &grad_output, const at::Tensor &attn_query, const at::Tensor &attn_keys, const at::Tensor &bias, const at::Tensor &linear_attn) { int batch_sz = attn_query.size(0); int t_q = attn_query.size(1); int t_k = attn_keys.size(1); int hidden = attn_query.size(2); at::Tensor grad_query = at::empty_like(attn_query); at::Tensor grad_keys = at::empty_like(attn_keys); const int BZ = 2; const int THREADS = 128; const int ILP = sizeof(int4) / attn_query.element_size(); const int len = (t_k <= 80) ? 8 * ILP : 4 * ILP; assert(hidden % len == 0); // Each CTA process BZ*t_q*t_k*len volume // Each thread process 1*1*1*int4 a time dim3 block(THREADS); dim3 grid(((batch_sz+BZ-1)/BZ) * (hidden/len)); // Allocate per-CTA buffer for future reduction on bias and linear_attn at::Tensor grad_biases = at::empty({grid.x, len}, bias.options()); at::Tensor grad_lins = at::empty({grid.x, len}, linear_attn.options()); // Check alignment ASSERT_INT4_ALIGNED(grad_query.data_ptr()); ASSERT_INT4_ALIGNED(grad_keys.data_ptr()); ASSERT_INT4_ALIGNED(grad_biases.data_ptr()); ASSERT_INT4_ALIGNED(grad_lins.data_ptr()); ASSERT_INT4_ALIGNED(grad_output.data_ptr()); ASSERT_INT4_ALIGNED(attn_query.data_ptr()); ASSERT_INT4_ALIGNED(attn_keys.data_ptr()); ASSERT_INT4_ALIGNED(bias.data_ptr()); ASSERT_INT4_ALIGNED(linear_attn.data_ptr()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (t_k <= 80) { const int TILE = 16; const int THREADS_PER_LEN = 8; const int LEN = THREADS_PER_LEN * ILP; AT_DISPATCH_FLOATING_TYPES_AND_HALF(attn_query.scalar_type(), "attn_score_bprop", [&] { using accscalar_t = at::acc_type<scalar_t, true>; using vector_t = vec_type<scalar_t, accscalar_t>; cunn_AttnScoreBackward<THREADS, sizeof(int4) / sizeof(scalar_t), THREADS_PER_LEN * sizeof(int4) / sizeof(scalar_t), TILE, BZ, scalar_t, accscalar_t, vector_t, scalar_t> <<<grid, block, (TILE + (t_k + TILE - 1) / TILE * TILE) * LEN * sizeof(accscalar_t) + (t_k + TILE - 1) / TILE * TILE * LEN * sizeof(scalar_t), stream>>>( grad_query.data_ptr<scalar_t>(), grad_keys.data_ptr<scalar_t>(), grad_biases.data_ptr<scalar_t>(), grad_lins.data_ptr<scalar_t>(), grad_output.data_ptr<scalar_t>(), attn_query.data_ptr<scalar_t>(), attn_keys.data_ptr<scalar_t>(), bias.data_ptr<scalar_t>(), linear_attn.data_ptr<scalar_t>(), batch_sz, t_q, t_k, hidden ); }); } else { const int TILE = 32; const int THREADS_PER_LEN = 4; const int LEN = THREADS_PER_LEN * ILP; AT_DISPATCH_FLOATING_TYPES_AND_HALF(attn_query.scalar_type(), "attn_score_bprop", [&] { using accscalar_t = at::acc_type<scalar_t, true>; using vector_t = vec_type<scalar_t, accscalar_t>; cunn_AttnScoreBackward<THREADS, sizeof(int4) / sizeof(scalar_t), THREADS_PER_LEN * sizeof(int4) / sizeof(scalar_t), TILE, BZ, scalar_t, accscalar_t, vector_t, scalar_t> <<<grid, block, (TILE + (t_k + TILE - 1) / TILE * TILE) * LEN * sizeof(accscalar_t) + (t_k + TILE - 1) / TILE * TILE * LEN * sizeof(scalar_t), stream>>>( grad_query.data_ptr<scalar_t>(), grad_keys.data_ptr<scalar_t>(), grad_biases.data_ptr<scalar_t>(), grad_lins.data_ptr<scalar_t>(), grad_output.data_ptr<scalar_t>(), attn_query.data_ptr<scalar_t>(), attn_keys.data_ptr<scalar_t>(), bias.data_ptr<scalar_t>(), linear_attn.data_ptr<scalar_t>(), batch_sz, t_q, t_k, hidden ); }); } // Reduce bias and linear_attn gradients at::Tensor grad_bias = at::sum(grad_biases.view({-1, hidden}), 0); at::Tensor grad_lin = at::sum(grad_lins.view({-1, hidden}), 0); THCudaCheck(cudaGetLastError()); std::vector<at::Tensor> ret = {grad_query, grad_keys, grad_bias, grad_lin}; return ret; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/tensor/ordering_op-inl.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2016 by Contributors * \file ordering_op-inl.h * \brief Function definition of ordering operators */ #ifndef MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #define MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #include <mxnet/operator_util.h> #include <dmlc/optional.h> #include <mshadow/tensor.h> #include <algorithm> #include <vector> #include <type_traits> #include "./indexing_op.h" namespace mshadow { template<typename xpu, int src_dim, typename DType, int dst_dim> inline Tensor<xpu, dst_dim, DType> inplace_reshape(const Tensor<xpu, src_dim, DType> &src, const Shape<dst_dim> &target_shape) { CHECK_EQ(src.CheckContiguous(), true); return Tensor<xpu, dst_dim, DType>(src.dptr_, target_shape, src.stream_); } }; namespace mxnet { namespace op { // These enums are only visible within this header namespace topk_enum { enum TopKReturnType {kReturnValue, kReturnIndices, kReturnMask, kReturnBoth}; } // topk_enum struct TopKParam : public dmlc::Parameter<TopKParam> { dmlc::optional<int> axis; int k; int ret_typ; bool is_ascend; int dtype; DMLC_DECLARE_PARAMETER(TopKParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose the top k indices." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(k).set_default(1) .describe("Number of top elements to select," " should be always smaller than or equal to the element number in the given axis." " A global sort is performed if set k < 1."); DMLC_DECLARE_FIELD(ret_typ).set_default(topk_enum::kReturnIndices) .add_enum("value", topk_enum::kReturnValue) .add_enum("indices", topk_enum::kReturnIndices) .add_enum("mask", topk_enum::kReturnMask) .add_enum("both", topk_enum::kReturnBoth) .describe("The return type.\n" " \"value\" means to return the top k values," " \"indices\" means to return the indices of the top k values," " \"mask\" means to return a mask array containing 0 and 1. 1 means the top k values." " \"both\" means to return a list of both values and indices of top k elements."); DMLC_DECLARE_FIELD(is_ascend).set_default(false) .describe("Whether to choose k largest or k smallest elements." " Top K largest elements will be chosen if set to false."); DMLC_DECLARE_FIELD(dtype) // TODO(srivrohi): remove support for real data type in mxnet-2.0 .add_enum("uint8", mshadow::kUint8) .add_enum("int32", mshadow::kInt32) .add_enum("int64", mshadow::kInt64) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(mshadow::kFloat32) .describe("DType of the output indices when ret_typ is \"indices\" or \"both\". " "An error will be raised if the selected data type cannot precisely represent the " "indices."); } }; struct SortParam : public dmlc::Parameter<SortParam> { dmlc::optional<int> axis; bool is_ascend; DMLC_DECLARE_PARAMETER(SortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); } }; struct ArgSortParam : public dmlc::Parameter<ArgSortParam> { dmlc::optional<int> axis; bool is_ascend; int dtype; DMLC_DECLARE_PARAMETER(ArgSortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); DMLC_DECLARE_FIELD(dtype) // TODO(srivrohi): remove support for real data type in mxnet-2.0 .add_enum("uint8", mshadow::kUint8) .add_enum("int32", mshadow::kInt32) .add_enum("int64", mshadow::kInt64) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(mshadow::kFloat32) .describe("DType of the output indices. It is only valid when ret_typ is \"indices\" or" " \"both\". An error will be raised if the selected data type cannot precisely " "represent the indices."); } }; inline void ParseTopKParam(const TShape& src_shape, const TopKParam& param, TShape *target_shape, size_t *batch_size, index_t *element_num, int *axis, index_t *k, bool *do_transpose, bool *is_ascend) { *do_transpose = false; *k = param.k; *is_ascend = param.is_ascend; // get batch_size, axis and element_num if (!static_cast<bool>(param.axis)) { // No axis given *axis = 0; *batch_size = 1; *element_num = src_shape.Size(); } else { *axis = param.axis.value(); if (*axis < 0) { *axis += src_shape.ndim(); } CHECK(*axis >= 0 && *axis < static_cast<int>(src_shape.ndim())) << "Invalid axis! axis should be between 0 and " << src_shape.ndim() << ", found axis=" << *axis; *batch_size = src_shape.Size() / src_shape[*axis]; *element_num = src_shape[*axis]; if (*axis != src_shape.ndim() - 1) { *do_transpose = true; } } // get k if (param.k <= 0) { *k = *element_num; } // get target_shape if (!static_cast<bool>(param.axis)) { if (param.ret_typ != topk_enum::kReturnMask) { *target_shape = mshadow::Shape1(*k); } else { *target_shape = src_shape; } } else { *target_shape = src_shape; if (param.ret_typ != topk_enum::kReturnMask) { (*target_shape)[*axis] = *k; } } CHECK(*k >= 1 && *k <= *element_num) << "k must be smaller than " << *element_num << ", get k = " << *k; } using namespace mshadow; struct fill_ind_to_one { template<typename DType> MSHADOW_XINLINE static void Map(int i, const index_t* indices, DType* out) { out[indices[i]] = static_cast<DType>(1); } }; struct fill_ind { template<typename DType> MSHADOW_XINLINE static void Map(int i, const index_t* indices, const DType* val, int req, DType* out) { KERNEL_ASSIGN(out[indices[i]], req, val[i]); } }; template<typename DType> MSHADOW_FORCE_INLINE void TopKSort(const Tensor<cpu, 1, DType>& dat, const Tensor<cpu, 1, index_t>& ind, const Tensor<cpu, 1, char>& work, index_t K, index_t N, bool is_ascend, Stream<cpu> *s) { // Use full sort when K is relatively large. const bool full_sort(K*8 > N); // Batch size. const index_t M(work.size(0)/(sizeof(DType)*N)); const int omp_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < M; ++i) { // Tensor `work` stores the flattened source data, while `dat` stores the sorted result. DType *vals = reinterpret_cast<DType*>(work.dptr_); DType *sorted_vals = dat.dptr_+i*N; index_t *indices = ind.dptr_+i*N; if (is_ascend) { if (full_sort) { std::sort(indices, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] < vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] < vals[i2]; }); } } else { if (full_sort) { std::sort(indices, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] > vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] > vals[i2]; }); } } for (index_t j = 0; j < K; ++j) { sorted_vals[j] = vals[indices[j]]; } } } #ifdef __CUDACC__ template<typename DType> MSHADOW_XINLINE bool TopKCompare(DType val1, index_t ind1, DType val2, index_t ind2, bool is_ascend) { // Negative indices denote undefined values which are considered arbitrary small resp. large. return (ind2 < 0) || (ind1 >= 0 && ((is_ascend && val1 < val2) || (!is_ascend && val1 > val2))); } template<typename DType> MSHADOW_XINLINE void MergeTopK(index_t K, DType *val1, index_t *ind1, DType *val2, index_t *ind2, bool is_ascend) { // In-place merge of two sorted top-K lists into val1/ind1. First determine the intervals // [0,..,i1], [0,..i2] of the two lists that will be part of the merged list. index_t i1(K-1), i2(K-1); for (index_t i = 0; i < K; ++i) { if (TopKCompare(val1[i1], ind1[i1], val2[i2], ind2[i2], is_ascend)) { --i2; } else { --i1; } } // Now merge the lists from back to front. for (index_t i = K; i--;) { if (i2 < 0 || i1 >= 0 && TopKCompare(val2[i2], ind2[i2], val1[i1], ind1[i1], is_ascend)) { val1[i] = val1[i1]; ind1[i] = ind1[i1]; --i1; } else { val1[i] = val2[i2]; ind1[i] = ind2[i2]; --i2; } } } template<typename DType> __global__ void PartialSortSmallK(index_t K, index_t N, DType *val, index_t *ind, bool is_ascend) { // Buffer for pairwise reduction. extern __shared__ index_t buff[]; // Start of buffer sections associated with this thread. const index_t offset(threadIdx.x*K); index_t *ind_buff = &buff[offset]; DType *val_buff = reinterpret_cast<DType*>(&buff[blockDim.x*K])+offset; // Initialize top-K values for this thread. for (index_t i = 0; i < K; ++i) { ind_buff[i] = -1; } // Range of values this thread cares about. Each thread block processes // a different batch item (i.e. a different set of ind/val where we // have to select the top-K elements). All threads within the same // block work on the same batch item. const index_t first(blockIdx.x*N+threadIdx.x), last((blockIdx.x+1)*N); // Select top-K from this range and store it sorted in the buffer. // We assume a small K, so linear insertion is o.k. for (index_t i = first; i < last; i += blockDim.x) { DType cur_val(val[i]); index_t cur_ind(ind[i]); for (index_t j = K; j-- && TopKCompare(cur_val, cur_ind, val_buff[j], ind_buff[j], is_ascend); ) { if (j+1 < K) { val_buff[j+1] = val_buff[j]; ind_buff[j+1] = ind_buff[j]; } val_buff[j] = cur_val; ind_buff[j] = cur_ind; } } // Recursive merge of sorted lists for this thread block. Note that blockDim.x is not // necessary a power of two, therefore the additional checks for last_s. for (index_t s = (blockDim.x+1)/2, last_s = blockDim.x; last_s > 1; last_s = s, s = (s+1)/2) { __syncthreads(); if (threadIdx.x < s && threadIdx.x+s < last_s) { MergeTopK(K, val_buff, ind_buff, val_buff+s*K, ind_buff+s*K, is_ascend); } } // Final updates on master thread. if (threadIdx.x == 0) { for (index_t i = 0; i < K; ++i) { ind[blockIdx.x*N+i] = ind_buff[i]; val[blockIdx.x*N+i] = val_buff[i]; } } } template<typename DType> MSHADOW_FORCE_INLINE void TopKSort(const Tensor<gpu, 1, DType>& dat, const Tensor<gpu, 1, index_t>& ind, const Tensor<gpu, 1, char>& work, index_t K, index_t N, bool is_ascend, Stream<gpu> *s) { // Use full sort for all but very small K for which we // can do a partial sort entirely within shared memory. const bool full_sort(K > 5); // Batch size. const index_t M(dat.size(0)/N); if (full_sort) { // Divide workspace into two parts. The first one is needed to store batch ids. const size_t alignment = std::max(sizeof(DType), sizeof(index_t)); const size_t id_size = PadBytes(sizeof(index_t) * ind.size(0), alignment); Tensor<gpu, 1, index_t> batch_id(reinterpret_cast<index_t*>(work.dptr_), Shape1(ind.size(0)), s); Tensor<gpu, 1, char> sort_work(work.dptr_+id_size, Shape1(work.size(0)-id_size), s); mxnet::op::SortByKey(dat, ind, is_ascend, &sort_work); if (M > 1) { // Back to back sorting. Note that mxnet::op::SortByKey is a stable sort. batch_id = ind / N; mxnet::op::SortByKey(batch_id, dat, true, &sort_work); batch_id = ind / N; mxnet::op::SortByKey(batch_id, ind, true, &sort_work); } } else { const int nthreads(mshadow::cuda::kBaseThreadNum); PartialSortSmallK<<<M, nthreads, nthreads*K*(sizeof(int)+sizeof(DType)), mshadow::Stream<gpu>::GetStream(s)>>> (K, N, dat.dptr_, ind.dptr_, is_ascend); } } #endif template<typename xpu, typename DType> size_t GetMemorySize(const TBlob& src) { const auto srcSize = src.Size(); const auto alignment = std::max(sizeof(DType), sizeof(int)); size_t temp_size = 0; // Temp space needed by the gpu-based full sorts. temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<int, int, xpu>(srcSize)); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<int, DType, xpu>(srcSize)); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<DType, int, xpu>(srcSize)); // Additional temp space for gpu full sorts for batch ids. temp_size += PadBytes(sizeof(index_t) * srcSize, alignment); // Temp space for cpu sorts. return std::max(temp_size, static_cast<size_t>(sizeof(DType) * srcSize)); } typedef void (*topK_func)(const RunContext &ctx, const Resource &resource, const std::vector<OpReqType>& req, const TBlob& src, const size_t temp_size, const std::vector<TBlob>& ret, const TopKParam& param); /*! * \brief Implementation of the TopK operation * * * \param ctx the running context * \param resource temporary resource handler * \param src the Source blob * \param ret the destination blobs * \param k the K elements to keep * \param param the topk parameters * \tparam xpu the device type. * \tparam DType type of the output value/mask. * \tparam IDType type of the output indices. */ template<typename xpu, typename DType, typename IDType> void TopKImpl(const RunContext &ctx, const Resource &resource, const std::vector<OpReqType>& req, const TBlob& src, const size_t temp_size, const std::vector<TBlob>& ret, const TopKParam& param) { using namespace mshadow; using namespace mshadow::expr; // 1. Parse and initialize information Stream<xpu> *s = ctx.get_stream<xpu>(); size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<index_t>()) << "'index_t' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<index_t>() << " elements"; Tensor<xpu, 3, DType> dat = src.FlatTo3D<xpu, DType>(axis, axis, s); const auto srcSize = src.Size(); const auto total_size = batch_size * k; const auto retMask = param.ret_typ == topk_enum::kReturnMask; const size_t alignment = std::max(sizeof(DType), sizeof(index_t)); const auto size_1 = PadBytes(sizeof(DType) * srcSize, alignment); const auto size_2 = PadBytes(sizeof(index_t) * srcSize, alignment); const auto size_3 = retMask ? PadBytes(sizeof(index_t) * total_size, alignment) : 0; const size_t workspace_size = temp_size + size_1 + size_2 + size_3; const Tensor<xpu, 1, char> workspace = resource.get_space_typed<xpu, 1, char> (Shape1(workspace_size), s); char* workspace_curr_ptr = workspace.dptr_; Tensor<xpu, 1, DType>sorted_dat(reinterpret_cast<DType*>(workspace_curr_ptr), Shape1(srcSize), s); // contain sorted dat workspace_curr_ptr += size_1; Tensor<xpu, 1, index_t> indices(reinterpret_cast<index_t*>(workspace_curr_ptr), Shape1(srcSize), s); // indices in the original matrix workspace_curr_ptr += size_2; Tensor<xpu, 1, index_t> sel_indices; if (retMask) { sel_indices = Tensor<xpu, 1, index_t>(reinterpret_cast<index_t*>(workspace_curr_ptr), Shape1(total_size), s); workspace_curr_ptr += size_3; CHECK_EQ(sel_indices.CheckContiguous(), true); } Tensor<xpu, 1, char> temp_workspace; if (std::is_same<xpu, cpu>::value) { Tensor<xpu, 1, DType> flattened_data; if (do_transpose) { flattened_data = Tensor<xpu, 1, DType>(reinterpret_cast<DType*>(workspace_curr_ptr), Shape1(srcSize), s); flattened_data = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(srcSize)); CHECK_EQ(flattened_data.CheckContiguous(), true); } else { flattened_data = src.FlatTo1D<xpu, DType>(s); } // `temp_workspace` stores the flattened data temp_workspace = Tensor<xpu, 1, char>(reinterpret_cast<char*>(flattened_data.dptr_), Shape1(sizeof(DType)*srcSize), s); CHECK_EQ(temp_workspace.CheckContiguous(), true); } else { if (do_transpose) { sorted_dat = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(srcSize)); } else { sorted_dat = reshape(dat, Shape1(srcSize)); } CHECK_EQ(sorted_dat.CheckContiguous(), true); temp_workspace = Tensor<xpu, 1, char>(workspace_curr_ptr, Shape1(temp_size), s); // temp space } mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size * element_num, 1, index_t{0}, index_t{1}, kWriteTo, indices.dptr_); CHECK_EQ(indices.CheckContiguous(), true); // 2. Perform inplace batch sort. // After sorting, each batch in `sorted_dat` will be sorted in the corresponding order // up to the k-th element and the `indices` will contain the corresponding index in `sorted_dat` // `temp_workspace` is used to store the flattened source data for CPU device, and it's used as // a temporal buffer for GPU device. TopKSort(sorted_dat, indices, temp_workspace, k, element_num, is_ascend, s); // 3. Assign results to the ret blob // When returning indices, only update(modulo) required elements instead of full elements // to avoid redundant calculation. // Cast `ret_indices` from int to real_t could introduce conversion error when the element_num // is large enough. if (retMask) { Tensor<xpu, 1, DType> ret_mask = ret[0].FlatTo1D<xpu, DType>(s); ret_mask = scalar<DType>(0); sel_indices = reshape(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), Shape1(total_size)); if (do_transpose) { mxnet::TShape src_shape = src.shape_.FlatTo3D(axis); CHECK_EQ(sel_indices.CheckContiguous(), true); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } if (req[0] == kNullOp) { return; } else if (req[0] == kWriteTo) { mxnet_op::Kernel<fill_ind_to_one, xpu>::Launch(s, total_size, sel_indices.dptr_, ret_mask.dptr_); } else { LOG(FATAL) << "req=" << req[0] << " is not supported yet."; } } else if (param.ret_typ == topk_enum::kReturnIndices) { if (do_transpose) { Tensor<xpu, 3, IDType> ret_indices = ret[0].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, IDType> ret_indices = ret[0].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } else { if (do_transpose) { Tensor<xpu, 3, DType> ret_value = ret[0].FlatTo3D<xpu, DType>(axis, axis, s); Tensor<xpu, 3, IDType> ret_indices = ret[1].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_value, req[0], transpose( slice<2>(inplace_reshape(sorted_dat, Shape3(ret_value.shape_[0], ret_value.shape_[2], element_num)), 0, k), Shape3(0, 2, 1))); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, DType> ret_value = ret[0].get_with_shape<xpu, 2, DType>(Shape2(batch_size, k), s); Tensor<xpu, 2, IDType> ret_indices = ret[1].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_value, req[0], slice<1>(inplace_reshape(sorted_dat, Shape2(batch_size, element_num)), 0, k)); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } } template<typename xpu> void TopK_Operation(const TopKParam& param, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const bool flag = param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnBoth; topK_func F; size_t size; MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { size = GetMemorySize<xpu, DType>(inputs[0]); if (flag) { MSHADOW_TYPE_SWITCH(param.dtype, IDType, F = TopKImpl<xpu, DType, IDType>;) } else { F = TopKImpl<xpu, DType, index_t>; } }); (*F)(ctx.run_ctx, ctx.requested[0], req, inputs[0], size, outputs, param); } template<typename xpu> void TopK(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { TopK_Operation<xpu>(nnvm::get<TopKParam>(attrs.parsed), ctx, inputs, req, outputs); } template<typename xpu> void Sort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; TopK_Operation<xpu>(topk_param, ctx, inputs, req, outputs); } template<typename xpu> void ArgSort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.dtype = param.dtype; topk_param.ret_typ = topk_enum::kReturnIndices; TopK_Operation<xpu>(topk_param, ctx, inputs, req, outputs); } template<typename xpu, typename DType, typename IDType> void TopKBackwardImpl(const OpContext &ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const TopKParam& param) { CHECK_NE(req[0], kWriteInplace); using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.run_ctx.get_stream<xpu>(); CHECK(param.ret_typ == topk_enum::kReturnValue || param.ret_typ == topk_enum::kReturnBoth); size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(outputs[0].shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<IDType>()) << "'IDType' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<IDType>() << " elements"; const auto total_size = batch_size * k; Tensor<xpu, 1, index_t> workspace = ctx.requested[0].get_space_typed<xpu, 1, index_t>(Shape1(total_size + batch_size), s); Tensor<xpu, 1, index_t> sel_indices(workspace.dptr_, Shape1(total_size), s); Tensor<xpu, 1, index_t> batch_shift(workspace.dptr_ + total_size, Shape1(batch_size), s); Tensor<xpu, 2, DType> out_grad = inputs[0].get_with_shape<xpu, 2, DType>(Shape2(inputs[0].shape_.Size(), 1), s); Tensor<xpu, 2, DType> in_grad = outputs[0].get_with_shape<xpu, 2, DType>(Shape2(outputs[0].shape_.Size(), 1), s); mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size, 1, index_t{0}, element_num, kWriteTo, batch_shift.dptr_); if (do_transpose) { Tensor<xpu, 1, IDType> indices = inputs[2].FlatTo1D<xpu, IDType>(s); mxnet::TShape src_shape = outputs[0].shape_.FlatTo3D(axis); sel_indices = reshape(transpose( broadcast_to(inplace_reshape(batch_shift, Shape3(src_shape[0], src_shape[2], 1)), mxnet::TShape(Shape3(src_shape[0], src_shape[2], k))), Shape3(0, 2, 1)), Shape1(total_size)); sel_indices += tcast<index_t>(indices); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } else { Tensor<xpu, 2, IDType> indices = inputs[2].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); sel_indices = reshape(tcast<index_t>(indices) + broadcast_to(inplace_reshape(batch_shift, Shape2(batch_size, 1)), mxnet::TShape(Shape2(batch_size, k))), Shape1(total_size)); } CHECK_EQ(sel_indices.CheckContiguous(), true); if (kWriteTo == req[0] || kAddTo == req[0]) { if (kWriteTo == req[0]) { in_grad = scalar<DType>(0); } mxnet_op::Kernel<fill_ind, xpu>::Launch(s, total_size, sel_indices.dptr_, out_grad.dptr_, req[0], in_grad.dptr_); } else { LOG(FATAL) << "Not Implemented!"; } } typedef void (*topKBackward_func)(const OpContext &ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const TopKParam& param); template<typename xpu> void TopKBackward_(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); const bool flag = param.ret_typ == topk_enum::kReturnBoth; if (flag || param.ret_typ == topk_enum::kReturnValue) { topKBackward_func F; MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { if (flag) { MSHADOW_TYPE_SWITCH(param.dtype, IDType, F = TopKBackwardImpl<xpu, DType, IDType>;) } else { F = TopKBackwardImpl<xpu, DType, index_t>; } }); (*F)(ctx, inputs, req, outputs, param); } else { LOG(FATAL) << "Not Implemented"; } } inline uint32_t TopKNumOutputs(const NodeAttrs& attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { return static_cast<uint32_t>(1); } else { return static_cast<uint32_t>(2); } } inline uint32_t TopKNumVisibleOutputs(const NodeAttrs& attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnBoth) { return static_cast<uint32_t>(2); } else { return static_cast<uint32_t>(1); } } inline bool AssignTypes(std::vector<int> *in_attrs, std::vector<int> *out_attrs) { int data_type = -1; CHECK(type_assign(&data_type, (*in_attrs)[0])) << "Incompatible dtype of input, in_attrs[0]=" << (*in_attrs)[0]; CHECK(type_assign(&data_type, (*out_attrs)[0])) << "Incompatible dtype of output, out_attrs[0]=" << (*out_attrs)[0]; CHECK(type_assign(&(*in_attrs)[0], data_type)) << "Incompatible dtype of input, in_attrs[0]=" << (*in_attrs)[0]; CHECK(type_assign(&(*out_attrs)[0], data_type)) << "Incompatible dtype of output, out_attrs[0]=" << (*out_attrs)[0]; return data_type != -1; } inline bool TopKType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); const size_t in_size = in_attrs->size(); const size_t out_size = out_attrs->size(); CHECK_EQ(in_size, 1); CHECK(out_size == 1 || out_size == 2); // out_attr[0] -> stores value // out_attr[1] -> stores indices if (out_size > 1) { if (param.ret_typ == topk_enum::kReturnValue) { #if MXNET_USE_INT64_TENSOR_SIZE == 1 CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt64)) #else CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt32)) #endif << "Failed to set the type of ret_indices."; } else { CHECK(type_assign(&(*out_attrs)[1], param.dtype)) << "Failed to set the type of ret_indices."; } } if (param.ret_typ == topk_enum::kReturnIndices) { CHECK(type_assign(&(*out_attrs)[0], param.dtype)) << "Failed to set the type of ret_indices."; return true; } return AssignTypes(in_attrs, out_attrs); } inline bool TopKShapeImpl(const TopKParam& param, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); const auto flag = param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask; CHECK_EQ(out_attrs->size(), (flag? 1U : 2U)); mxnet::TShape& in_shape = (*in_attrs)[0]; size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(in_shape, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); SHAPE_ASSIGN_CHECK(*out_attrs, 0, target_shape); if (!flag) { SHAPE_ASSIGN_CHECK(*out_attrs, 1, target_shape); } return true; } inline bool TopKShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); return TopKShapeImpl(param, in_attrs, out_attrs); } inline bool SortType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 1); CHECK_EQ(out_attrs->size(), 2); CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt32)) << "Failed to set the type of ret_indices."; return AssignTypes(in_attrs, out_attrs); } inline bool SortShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } inline bool ArgSortType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); CHECK(type_assign(&(*out_attrs)[0], param.dtype)) << "Failed to set the type of ret_indices"; return true; } inline bool ArgSortShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnIndices; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/common_f32.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef COMMON_F32_HPP #define COMMON_F32_HPP #include "jit_generator.hpp" #define F32_COPY_KERNEL_CODE_SIZE (4096L * 5) #define F32_COMPUTE_KERNEL_CODE_SIZE (4096L * 32) namespace mkldnn { namespace impl { namespace cpu { class jit_avx512_core_f32_copy_an_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx512_core_f32_copy_an_kern); public: jit_avx512_core_f32_copy_an_kern(); }; class jit_avx512_core_f32_copy_at_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx512_core_f32_copy_at_kern); public: jit_avx512_core_f32_copy_at_kern(); }; class jit_avx512_core_f32_copy_bn_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx512_core_f32_copy_bn_kern); public: jit_avx512_core_f32_copy_bn_kern(); }; class jit_avx512_core_f32_copy_bt_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx512_core_f32_copy_bt_kern); public: jit_avx512_core_f32_copy_bt_kern(); }; class jit_avx2_f32_copy_an_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx2_f32_copy_an_kern); public: jit_avx2_f32_copy_an_kern(); }; class jit_avx2_f32_copy_at_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx2_f32_copy_at_kern); public: jit_avx2_f32_copy_at_kern(); }; class jit_avx2_f32_copy_bn_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx2_f32_copy_bn_kern); public: jit_avx2_f32_copy_bn_kern(); }; class jit_avx2_f32_copy_bt_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx2_f32_copy_bt_kern); public: jit_avx2_f32_copy_bt_kern(); }; class jit_avx_f32_copy_an_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx_f32_copy_an_kern); public: jit_avx_f32_copy_an_kern(); }; class jit_avx_f32_copy_at_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx_f32_copy_at_kern); public: jit_avx_f32_copy_at_kern(); }; class jit_avx_f32_copy_bn_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx_f32_copy_bn_kern); public: jit_avx_f32_copy_bn_kern(); }; class jit_avx_f32_copy_bt_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx_f32_copy_bt_kern); public: jit_avx_f32_copy_bt_kern(); }; class jit_avx_kernel_b0_sgemm_kern: public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx_kernel_b0_sgemm_kern); public: jit_avx_kernel_b0_sgemm_kern(); }; class jit_avx_kernel_sgemm_kern: public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_avx_kernel_sgemm_kern); public: jit_avx_kernel_sgemm_kern(); }; class jit_sse41_f32_copy_an_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_sse41_f32_copy_an_kern); public: jit_sse41_f32_copy_an_kern(); }; class jit_sse41_f32_copy_at_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_sse41_f32_copy_at_kern); public: jit_sse41_f32_copy_at_kern(); }; class jit_sse41_f32_copy_bn_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_sse41_f32_copy_bn_kern); public: jit_sse41_f32_copy_bn_kern(); }; class jit_sse41_f32_copy_bt_kern : public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_sse41_f32_copy_bt_kern); public: jit_sse41_f32_copy_bt_kern(); }; class jit_sse41_kernel_b0_sgemm_kern: public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_sse41_kernel_b0_sgemm_kern); public: jit_sse41_kernel_b0_sgemm_kern(); }; class jit_sse41_kernel_sgemm_kern: public jit_generator { DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_sse41_kernel_sgemm_kern); public: jit_sse41_kernel_sgemm_kern(); }; } } } #endif // COMMON_F32_HPP <|start_filename|>DellEMC/benchmarks/ssd/implementation/mxnet/Dockerfile<|end_filename|> # Copyright (c) 2018-2020, NVIDIA CORPORATION. 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. ARG FROM_IMAGE_NAME=nvcr.io/nvidian/mxnet:20.06-py3 FROM ${FROM_IMAGE_NAME} # Install dependencies for system configuration logger RUN apt-get update \ && apt-get install -y --no-install-recommends \ infiniband-diags \ pciutils \ && rm -rf /var/lib/apt/lists/* # Update container's pycocotools to optimized version RUN pip uninstall -y pycocotools ENV COCOAPI_VERSION=2.0+nv0.4.0 RUN export COCOAPI_TAG=$(echo ${COCOAPI_VERSION} | sed 's/^.*+n//') \ && pip install --no-cache-dir pybind11 \ && pip install --no-cache-dir git+https://github.com/NVIDIA/cocoapi.git@${COCOAPI_TAG}#subdirectory=PythonAPI WORKDIR /workspace/ssd # Install python dependencies COPY requirements.txt . RUN pip install --no-cache-dir cython \ && pip install --no-cache-dir https://github.com/mlperf/logging/archive/9ea0afa.zip \ && pip install --no-cache-dir -r requirements.txt # Copy SSD code COPY . . # Compile Horovod MPI test RUN cd /workspace/ssd/tests && mpicxx --std=c++11 horovod_mpi_test.cpp -o horovod_mpi_test && cd /workspace/ssd ENV HOROVOD_CYCLE_TIME=0.1 \ HOROVOD_BATCH_D2D_MEMCOPIES=1 \ HOROVOD_NUM_NCCL_STREAMS=1 \ MXNET_CUDNN_AUTOTUNE_DEFAULT=0 \ MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_FWD=999 \ MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_BWD=999 \ MXNET_GPU_WORKER_NTHREADS=1 \ MXNET_CPU_PRIORITY_NTHREADS=1 \ MXNET_EXPERIMENTAL_ENABLE_CUDA_GRAPH=1 \ OMP_NUM_THREADS=1 \ OMPI_MCA_btl=^openib \ OPENCV_FOR_THREADS_NUM=1 # HOROVOD_STALL_CHECK_DISABLE=1 <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/include/mxnet/c_api_cac.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2015 by Contributors * \file c_api.h * \brief C API of mxnet */ #ifndef MXNET_C_API_CAC_H_ #define MXNET_C_API_CAC_H_ /*! \brief Inhibit C++ name-mangling for MXNet functions. */ #ifdef __cplusplus extern "C" { #endif // __cplusplus #include <mxnet/c_api.h> struct GradientSkipInfo { char *key; int skip_term; int layer_num; }; /*! * \brief Excecutor run backward * * \param handle execute handle * \param len lenth * \param head_grads NDArray handle for heads' gradient * \param is_train int value to indicate whether the backward pass is for evaluation * * \return 0 when success, -1 when failure happens */ MXNET_DLL int MXExecutorBackwardExWithGradientSkip(ExecutorHandle handle, mx_uint len, NDArrayHandle *head_grads, int is_train, GradientSkipInfo *gs_info = nullptr, mx_uint gs_info_len = 0, int gs_stop_layer_num = -1, int gs_non_stop_layer_num = -1, int *gs_stop_layer_num_update = nullptr); #ifdef __cplusplus } #endif // __cplusplus #endif // MXNET_C_API_CAC_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/subgraph/tensorrt/tensorrt-inl.h<|end_filename|> #ifndef MXNET_OPERATOR_SUBGRAPH_TENSORRT_TENSORRT_INL_H_ #define MXNET_OPERATOR_SUBGRAPH_TENSORRT_TENSORRT_INL_H_ /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file tensorrt-inl.h * \brief TensorRT operation registration * \author <NAME>, <NAME> */ #if MXNET_USE_TENSORRT #include <onnx-tensorrt/NvOnnxParser.h> #include <utility> #include <string> #include <vector> #include "../../nn/activation-inl.h" #include "../../nn/batch_norm-inl.h" #include "../../nn/concat-inl.h" #include "../../nn/convolution-inl.h" #include "../../nn/deconvolution-inl.h" #include "../../nn/dropout-inl.h" #include "../../nn/fully_connected-inl.h" #include "../../nn/pooling-inl.h" #include "../../tensor/matrix_op-inl.h" #include "../common.h" #include "../subgraph_property.h" #include "nnvm_to_onnx-inl.h" #include "./onnx_to_tensorrt.h" namespace mxnet { namespace op { using int64 = ::google::protobuf::int64; struct TRTParam { std::unordered_map<std::string, uint32_t> inputs_to_idx; std::unordered_map<std::string, uint32_t> outputs_to_idx; std::unordered_map<std::string, NDArray> params_map; }; struct TRTEngineParam { TRTEngineParam(onnx_to_tensorrt::unique_ptr<nvinfer1::ICudaEngine> _trt_engine, onnx_to_tensorrt::unique_ptr<nvonnxparser::IParser> _trt_parser, std::unique_ptr<onnx_to_tensorrt::TRT_Logger> _trt_logger, const std::unordered_map<std::string, uint32_t>& input_map, const std::unordered_map<std::string, uint32_t>& output_map) { trt_engine = std::move(_trt_engine); trt_logger = std::move(_trt_logger); trt_parser = std::move(_trt_parser); binding_order = std::make_shared<std::vector<std::pair<uint32_t, bool> > >(); bindings = std::make_shared<std::vector<void*> >(); binding_order->reserve(trt_engine->getNbBindings()); bindings->resize(trt_engine->getNbBindings()); for (int b = 0; b < trt_engine->getNbBindings(); ++b) { const std::string& binding_name = trt_engine->getBindingName(b); if (trt_engine->bindingIsInput(b)) { binding_order->emplace_back(input_map.at(binding_name), true); } else { binding_order->emplace_back(output_map.at(binding_name), false); } } trt_executor = onnx_to_tensorrt::InferObject(trt_engine->createExecutionContext()); } onnx_to_tensorrt::unique_ptr<nvinfer1::ICudaEngine> trt_engine; onnx_to_tensorrt::unique_ptr<nvinfer1::IExecutionContext> trt_executor; onnx_to_tensorrt::unique_ptr<nvonnxparser::IParser> trt_parser; std::unique_ptr<onnx_to_tensorrt::TRT_Logger> trt_logger; std::shared_ptr<std::vector<std::pair<uint32_t, bool> > > binding_order; std::shared_ptr<std::vector<void*> > bindings; }; class TensorrtSelector : public SubgraphSelector { public: const std::unordered_set<std::string> unconditionalTRTops = { "_copy", "clip", "elemwise_add", "elemwise_sub", "elemwise_mul", "Flatten", // "mean", TODO(cfujitsang): add "Pad", "relu", "rsqrt", "SoftmaxOutput" }; const std::unordered_set<std::string> withWeightsOps = { "BatchNorm", "Convolution", "Deconvolution", "FullyConnected" }; bool isTRTCompatible(const nnvm::Node &n) { const std::string op_name = n.op()->name; if (op_name == "FullyConnected") { const auto& param = nnvm::get<FullyConnectedParam>(n.attrs.parsed); return !param.no_bias; } // TODO(cfujitsang): Check about limit on stride / pad / kernel if (op_name == "Pooling") { const auto& param = nnvm::get<PoolingParam>(n.attrs.parsed); if (param.layout.has_value()) { if (param.layout.value() == mshadow::kNHWC) { LOG(INFO) << "Warning: NHWC layout (node: " << n.attrs.name << ") is not supported by TensorRT"; return false; } else if (param.layout.value() == mshadow::kNDHWC) { LOG(INFO) << "Warning: NDHWC layout (node: " << n.attrs.name << ") is not supported by TensorRT"; return false; } } if (param.pooling_convention != pool_enum::kValid && !param.global_pool) return false; if (param.pool_type == pool_enum::kAvgPooling) { if ((!param.global_pool) && (!param.count_include_pad.has_value() || param.count_include_pad.value())) return false; return true; } else if (param.pool_type == pool_enum::kMaxPooling) { return true; } else { return false; } } if (op_name == "Convolution") { const auto& param = nnvm::get<ConvolutionParam>(n.attrs.parsed); if (!param.layout.has_value()) return true; switch (param.layout.value()) { case mshadow::kNCHW: case mshadow::kNCW: case mshadow::kNCDHW: return true; case mshadow::kNHWC: LOG(INFO) << "Warning: NHWC layout (node: " << n.attrs.name << ") is not supported by TensorRT"; return false; case mshadow::kNDHWC: LOG(INFO) << "Warning: NDHWC layout (node: " << n.attrs.name << ") is not supported by TensorRT"; return false; default: LOG(INFO) << "Warning: Layout (node: " << n.attrs.name << ") is unknown (so unsupported by TensorRT)"; return false; } } if (op_name == "Deconvolution") { const auto& param = nnvm::get<DeconvolutionParam>(n.attrs.parsed); if (!param.layout.has_value()) return true; switch (param.layout.value()) { case mshadow::kNCHW: case mshadow::kNCW: case mshadow::kNCDHW: return true; case mshadow::kNHWC: LOG(INFO) << "Warning: NHWC layout (node: " << n.attrs.name << ") is no tsupported by TensorRT"; return false; case mshadow::kNDHWC: LOG(INFO) << "Warning: NDHWC layout (node: " << n.attrs.name << ") is not supported by TensorRT"; return false; default: LOG(INFO) << "Warning: Layout (node: " << n.attrs.name << ") is unknown (so unsupported by TensorRT)"; return false; } } if (op_name == "Concat") { const auto& param = nnvm::get<ConcatParam>(n.attrs.parsed); return (param.dim != 0); } if (op_name == "Dropout") { const auto& param = nnvm::get<DropoutParam>(n.attrs.parsed); return param.mode == dropout::kTraining && param.axes.ndim() == 0; } if (op_name == "Activation") { const auto& param = nnvm::get<ActivationParam>(n.attrs.parsed); return param.act_type == activation::kReLU || param.act_type == activation::kTanh || param.act_type == activation::kSigmoid; } if (op_name == "BatchNorm") { const auto& param = nnvm::get<BatchNormParam>(n.attrs.parsed); if (param.axis != 1) { LOG(INFO) << "Warning: Only Layout NC(D)(H)W are supported by TensorRT " << "(node " << n.attrs.name << ")"; return false; } return true; } if (op_name == "slice") { const auto& param = nnvm::get<SliceParam>(n.attrs.parsed); if (param.begin[0].has_value() && param.begin[0].value() != 0) return false; if (param.end[0].has_value()) return false; for (auto a : param.step) { if (a.has_value() && a.value() != 1) return false; } return true; } if (unconditionalTRTops.count(op_name)) { return true; } return false; } bool Select(const nnvm::Node &n) override { return !n.is_variable() && isTRTCompatible(n); } bool SelectInput(const nnvm::Node &n, const nnvm::Node &new_node) override { if (new_node.is_variable()) { if (withWeightsOps.count(n.op()->name)) { return n.inputs[0].node->attrs.name != new_node.attrs.name; } else { return false; } } return isTRTCompatible(new_node); } bool SelectOutput(const nnvm::Node &n, const nnvm::Node &new_node) override { return isTRTCompatible(new_node); } std::vector<nnvm::Node*> Filter(const std::vector<nnvm::Node*>& candidates) override { bool found_one = false; // TensorRT is interesting with at least 2 operations for (auto& n : candidates) { if (!n->is_variable()) { if (found_one) { return candidates; } else { found_one = true; } } } return std::vector<nnvm::Node*>(); } }; class TensorrtProperty : public SubgraphProperty { public: static SubgraphPropertyPtr Create() { auto sgprop = std::make_shared<TensorrtProperty>(); sgprop->SetAttr<std::string>("property_name", "TensorRT"); return sgprop; } nnvm::NodePtr CreateSubgraphNode(const nnvm::Symbol &sym, const int subgraph_id) const override { nnvm::NodePtr n = nnvm::Node::Create(); nnvm::Symbol new_sym; std::unique_copy(sym.outputs.begin(), sym.outputs.end(), std::back_inserter(new_sym.outputs), []( nnvm::NodeEntry lhs, nnvm::NodeEntry rhs) { return lhs.index == rhs.index && lhs.node.get() == rhs.node.get(); }); n->attrs.name = "TensorRT" + std::to_string(subgraph_id); n->attrs.op = Op::Get("_TensorRT"); CHECK(n->attrs.op); DFSVisit(new_sym.outputs, [&n](const nnvm::NodePtr& node) { if (node->op() == Op::Get("BatchNorm")) { const auto& param = nnvm::get<BatchNormParam>(node->attrs.parsed); if (param.fix_gamma) { n->attrs.dict.insert({"subgraph_forced_val_" + node->inputs[batchnorm::kGamma].node->attrs.name, "1."}); } } }); n->attrs.subgraphs.emplace_back(std::make_shared<nnvm::Symbol>(new_sym)); std::ostringstream params_oss; for (auto &e : new_sym.ListInputNames(nnvm::Symbol::kAll)) { params_oss << e << ";"; } auto tensorrt_params_names = params_oss.str(); tensorrt_params_names.pop_back(); n->attrs.dict["subgraph_params_names"] = tensorrt_params_names; TRTParam param; n->attrs.parsed = param; n->op()->attr_parser(&(n->attrs)); return n; } SubgraphSelectorPtr CreateSubgraphSelector() const override { return std::make_shared<TensorrtSelector>(); } void ConnectSubgraphOutputs(const nnvm::NodePtr subgraph_node, \ std::vector<nnvm::NodeEntry*>* output_entries) const override { std::vector<nnvm::NodeEntry>& outputs = subgraph_node->attrs.subgraphs[0]->outputs; TRTParam& _params = nnvm::get<TRTParam>(subgraph_node->attrs.parsed); for (size_t i = 0; i < outputs.size(); i++) { auto& o = outputs[i]; for (auto& e : *output_entries) { if (o.index == e->index && o.node.get() == e->node.get()) { e->index = i; e->node = subgraph_node; // TODO(cfujitsang): For future support this would fail // if the node have multiple outputs _params.outputs_to_idx[o.node->attrs.name] = i; } } } subgraph_node->attrs.parsed = std::move(_params); } void ConnectSubgraphInputs(const nnvm::NodePtr subgraph_node, std::vector<nnvm::NodeEntry*>* input_entries, std::vector<nnvm::NodeEntry>* orig_input_entries) const override { TRTParam& _params = nnvm::get<TRTParam>(subgraph_node->attrs.parsed); subgraph_node->inputs.clear(); subgraph_node->inputs.resize(orig_input_entries->size()); for (size_t i = 0; i < orig_input_entries->size(); ++i) { subgraph_node->inputs[i] = orig_input_entries->at(i); _params.inputs_to_idx[input_entries->at(i)->node->attrs.name] = i; } subgraph_node->attrs.parsed = std::move(_params); } }; } // namespace op } // namespace mxnet #endif // MXNET_USE_TENSORRT #endif // MXNET_OPERATOR_SUBGRAPH_TENSORRT_TENSORRT_INL_H_ <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/rope.h<|end_filename|> // absl::Cord is not yet open sourced. Introduce a Rope adapter class that's // absl::Cord internally and std::string externally. #ifndef LINGVO_CORE_OPS_ROPE_H_ #define LINGVO_CORE_OPS_ROPE_H_ #include "REDACTEDstrings/cord.h" namespace tensorflow { namespace babelfish { typedef absl::Cord Rope; } // namespace babelfish } // namespace tensorflow #endif // LINGVO_CORE_OPS_ROPE_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/bn_stats_finalize.cu<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file bn_stats_finalize.cu * \brief Batch Normalization Stats Finalize code * \author <NAME> */ #include <cuda_runtime_api.h> #include <algorithm> #include "batch_norm-inl.h" #include "bn_stats_finalize-inl.h" #if MXNET_USE_CUDNN == 1 #include "./cudnn/cudnn_bn_stats_finalize-inl.h" #endif #include "../../common/cuda_utils.h" #include "../../../include/mxnet/tensor_blob.h" using namespace mxnet; /*! \brief inverse standard deviation <-> variance */ #define VARIANCE_TO_INVSTD(__var$, __eps$) (1.0/sqrt((__var$) + DType(__eps$))) #define INVSTD_TO_VARIANCE(__invstd$, __eps$) ((1.0 / ((__invstd$) * (__invstd$))) - (__eps$)) namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 template<typename DType> static CuDNNBNStatsFinalizeOp<DType>& GetCuDNNBNStatsFinalizeOp( const BNStatsFinalizeParam& param, const TShape& shape, const OpContext& ctx) { #if DMLC_CXX11_THREAD_LOCAL static thread_local std::unordered_map<BNStatsFinalizeSignature, std::shared_ptr<CuDNNBNStatsFinalizeOp<DType> >, OpHash> ops; #else static MX_THREAD_LOCAL std::unordered_map<BNStatsFinalizeSignature, std::shared_ptr<CuDNNBNStatsFinalizeOp<DType> >, OpHash> ops; #endif BNStatsFinalizeSignature key(param); key.Reserve(shape.ndim()); key.AddSign(shape); auto it = ops.find(key); if (it == ops.end()) { std::shared_ptr<CuDNNBNStatsFinalizeOp<DType>> op( new CuDNNBNStatsFinalizeOp<DType>()); auto ins_ret = ops.insert(std::pair<BNStatsFinalizeSignature, std::shared_ptr<CuDNNBNStatsFinalizeOp<DType>>>(key, op)); CHECK(ins_ret.second); it = ins_ret.first; it->second->Init(param, shape, ctx); } return *it->second; } #endif template<> void BNStatsFinalizeCompute<gpu>(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), static_cast<size_t>(bn_stats_finalize::kNumInputs)); std::vector<TBlob> in_data(inputs.begin(), inputs.begin() + bn_stats_finalize::kNumNonAuxInputs); std::vector<TBlob> aux_states(inputs.begin() + bn_stats_finalize::kNumNonAuxInputs, inputs.end()); // Note that the equiv_scale and equiv_bias outputs are float16, with the other i/o's float32 int dtype = outputs[0].type_flag_; TShape shape = outputs[0].shape_; #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 BNStatsFinalizeParam param = nnvm::get<BNStatsFinalizeParam>(attrs.parsed); // We enable the discrete NHWC cuda kernels by the same 'cudnn_off' flag. MSHADOW_REAL_TYPE_SWITCH_EX(dtype, DType, AccReal, { if (CuDNNBNStatsFinalizeOp<DType>::Supports(param, dtype, shape)) GetCuDNNBNStatsFinalizeOp<DType>(param, shape, ctx).Forward(ctx, in_data, req, outputs, aux_states); else LOG(FATAL) << "No fallback impl for unsupported BNStatsFinalize configuration."; }); #else LOG(FATAL) << "Only cudnn-based BNStatsFinalize supported."; #endif } template<> void BNStatsFinalizeGradCompute<gpu>(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { // Only incoming gradients (== number of fwd outputs) are inputs of the backward node. CHECK_EQ(inputs.size(), static_cast<size_t>(bn_stats_finalize::kNumOutputs)); // Learn of the dtype of the backward node from an otherwise-ignored d_equiv_scale int dtype = inputs[0].type_flag_; TShape shape = inputs[0].shape_; #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 BNStatsFinalizeParam param = nnvm::get<BNStatsFinalizeParam>(attrs.parsed); // We enable the discrete NHWC cuda kernels by the same 'cudnn_off' flag. MSHADOW_REAL_TYPE_SWITCH_EX(dtype, DType, AccReal, { if (CuDNNBNStatsFinalizeOp<DType>::Supports(param, dtype, shape)) GetCuDNNBNStatsFinalizeOp<DType>(param, shape, ctx).Backward(ctx, inputs, req, outputs); else LOG(FATAL) << "No fallback impl for unsupported BNStatsFinalize configuration."; }); #else LOG(FATAL) << "Only cudnn-based BNStatsFinalize supported."; #endif } NNVM_REGISTER_OP(BNStatsFinalize) .set_attr<FCompute>("FCompute<gpu>", BNStatsFinalizeCompute<gpu>); NNVM_REGISTER_OP(_backward_BNStatsFinalize) .set_attr<FCompute>("FCompute<gpu>", BNStatsFinalizeGradCompute<gpu>); } // namespace op } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/bn_add_relu_fuse_pass.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file bn_add_relu_fuse_pass.cc * \brief optimization pass which fuse add_relu into BatchNorm * \author <NAME> */ #include <mxnet/base.h> #include <mxnet/operator.h> #include "./exec_pass.h" #include "../operator/nn/batch_norm-inl.h" #include "../operator/nn/batch_norm_add_relu-inl.h" #include "../common/cuda_utils.h" namespace mxnet { namespace exec { using namespace mxnet::op; namespace { inline bool IsCompatibleReLU(const nnvm::NodePtr& node) { using namespace mxnet::common::cuda; if (node->op() == Op::Get("Activation")) { const auto& param = nnvm::get<ActivationParam>(node->attrs.parsed); return param.act_type == activation::kReLU; } return node->op() == Op::Get("relu"); } void FuseBNAddReluNode(const nnvm::NodePtr bn, const nnvm::NodePtr add, const nnvm::NodePtr relu, const nnvm::NodeEntry other) { static const Op* bn_add_relu_op = Op::Get("BatchNormAddRelu"); relu->attrs.op = bn_add_relu_op; relu->attrs.name = bn->attrs.name + "_add_relu"; relu->attrs.dict = bn->attrs.dict; relu->attrs.dict.erase("act_type"); // BatchNormAddRelu does not have "act_type" parameter relu->inputs.resize(6); relu->inputs[0] = bn->inputs[0]; // data relu->inputs[1] = bn->inputs[1]; // gamma relu->inputs[2] = bn->inputs[2]; // beta relu->inputs[3] = other; // addend relu->inputs[4] = bn->inputs[3]; // moving_mean relu->inputs[5] = bn->inputs[4]; // moving_var bn_add_relu_op->attr_parser(&(relu->attrs)); } } // namespace Graph FuseBNAddRelu(Graph&& g) { const auto& shape_vec = g.GetAttr<mxnet::ShapeVector>("shape"); const auto& dtype_vec = g.GetAttr<nnvm::DTypeVector>("dtype"); const auto& context_vec = g.GetAttr<ContextVector>("context"); const auto& idx = g.indexed_graph(); const auto ne_counter = GetNodeEntryCount(g); std::unordered_set<nnvm::NodePtr> to_delete; DFSVisit(g.outputs, [&ne_counter, &idx, &shape_vec, &dtype_vec, &context_vec, &to_delete](const nnvm::NodePtr& n) { if (IsCompatibleReLU(n) && ne_counter.at(n->inputs[0]) == 1) { const nnvm::NodePtr& relu = n; // TODO(cfujitsang): Should add_n be separated in multiple elemwise_add to allow this fusion ? if (n->inputs[0].node->op() == Op::Get("elemwise_add")) { const nnvm::NodePtr& add = n->inputs[0].node; auto eid = idx.entry_id(add->inputs[0]); auto nid = idx.node_id(add.get()); if (batchnormaddrelu::IsCompatibleBatchNorm( add->inputs[0].node, dtype_vec[eid], shape_vec[eid], context_vec[nid]) && add->inputs[0].index == 0 && ne_counter.at(add->inputs[0]) == 1) { const nnvm::NodePtr& bn = add->inputs[0].node; to_delete.insert(add); to_delete.insert(bn); FuseBNAddReluNode(bn, add, relu, add->inputs[1]); } // TODO(cfujitsang): because of topology modification // right now we can't merge if the BN is on the inputs[1]. } } }); return g; } } // namespace exec } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/cmake/Threading.cmake<|end_filename|> #=============================================================================== # Copyright 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #=============================================================================== # Utils for managing threading-related configuration #=============================================================================== if(Threading_cmake_included) return() endif() set(Threading_cmake_included true) # Always require pthreads even for sequential threading (required for e.g. # std::call_once that relies on mutexes) find_package(Threads REQUIRED) list(APPEND EXTRA_SHARED_LIBS "${CMAKE_THREAD_LIBS_INIT}") # While MKL-DNN defaults to OpenMP (if _OPENMP is defined) without CMake, here # we default to sequential threading and let OpenMP.cmake and TBB.cmake to # figure things out. This is especially important because OpenMP is used both # for threading and vectorization via #pragma omp simd set(MKLDNN_CPU_RUNTIME_CURRENT "SEQ") <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/conv_bn_fuse_pass.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file convbn_fuse_pass.cc * \brief detect whether fused conv + bn is possible * \author <NAME> */ #include <mxnet/base.h> #include <mxnet/operator.h> #include <mxnet/op_attr_types.h> #include <nnvm/graph_attr_types.h> #include "./exec_pass.h" #include "../operator/nn/activation-inl.h" #include "../operator/nn/batch_norm-inl.h" #include "../operator/nn/convolution-inl.h" #include "../operator/nn/norm_convolution-inl.h" #include "../operator/tensor/broadcast_reduce_op.h" namespace mxnet { namespace exec { using namespace mxnet::op; namespace { #if DEBUG void PrintGraph(const Graph& g) { LOG(INFO) << "######## GRAPH IS ########"; const auto ne_counter = GetNodeEntryCount(g); DFSVisit(g.outputs, [&ne_counter](const nnvm::NodePtr& n) { if (n->op() == nullptr) { LOG(INFO) << n->attrs.name << ":"; } else { LOG(INFO) << n->attrs.name << ": " << n->op()->name; } if (n->op() != nullptr) { if (n->op() == Op::Get("NormalizedConvolution") || n->op() == Op::Get("Convolution") || n->op() == Op::Get("BatchNorm")) { for (const auto& p : n->attrs.dict) { LOG(INFO) << " - " << p.first << ": " << p.second; } } LOG(INFO) << " INPUTS:"; for (const auto& e : n->inputs) { LOG(INFO) << " - " << e.node->attrs.name << " | " << e.index << " | " << ne_counter.at(e); } } }); } #endif bool IsCompatibleBN(const nnvm::NodePtr& node, const TShape& shape) { if (node->op() != Op::Get("BatchNorm")) return false; auto param = nnvm::get<BatchNormParam>(node->attrs.parsed); return (shape.ndim() - 1 == param.axis || param.axis == -1); } void ConvToNormConv(const nnvm::NodePtr& node) { static const Op* norm_conv_op = Op::Get("NormConvolution"); nnvm::NodeAttrs attrs; attrs.name = node->attrs.name + "_normalized"; std::vector<std::string> transferable_conv_dict_params = {"kernel", "stride", "dilate", "pad", "num_filter", "num_group", "layout"}; for (auto& s : transferable_conv_dict_params) { const auto& it = node->attrs.dict.find(s); if (it != node->attrs.dict.end()) attrs.dict.insert({s, it->second}); } attrs.dict.insert({"no_norm", "True"}); attrs.op = norm_conv_op; norm_conv_op->attr_parser(&attrs); node->attrs = attrs; } void NormConvToConv(const nnvm::NodePtr& node) { static const Op* conv_op = Op::Get("Convolution"); node->attrs.name.erase(node->attrs.name.end() - 11, node->attrs.name.end()); node->attrs.op = conv_op; node->attrs.dict.erase("no_norm"); node->attrs.dict.insert({"no_bias", "True"}); conv_op->attr_parser(&(node->attrs)); } void FuseBatchNorm(const nnvm::NodePtr prev_conv, const nnvm::NodePtr bn, const nnvm::NodePtr next_conv, nnvm::NodeEntryMap<nnvm::NodeEntry>* entry_map) { next_conv->attrs.dict["no_norm"] = "False"; std::vector<std::string> transferable_bn_dict_params = {"act_type", "eps", "momentum", "fix_gamma", "use_global_stats", "output_mean_var"}; for (auto& s : transferable_bn_dict_params) { const auto& it = bn->attrs.dict.find(s); if (it != bn->attrs.dict.end()) next_conv->attrs.dict.insert({s, it->second}); } next_conv->inputs.resize(8); next_conv->inputs[norm_conv::kData] = nnvm::NodeEntry{prev_conv, norm_conv::kOut, 0}; next_conv->inputs[norm_conv::kWeight] = next_conv->inputs[norm_conv::kWeightNoNorm]; next_conv->inputs[norm_conv::kInSum] = nnvm::NodeEntry{prev_conv, norm_conv::kOutSum, 0}; next_conv->inputs[norm_conv::kInSumOfSquares] = nnvm::NodeEntry{prev_conv, norm_conv::kOutSumOfSquares, 0}; next_conv->inputs[norm_conv::kGamma] = bn->inputs[batchnorm::kGamma]; next_conv->inputs[norm_conv::kBeta] = bn->inputs[batchnorm::kBeta]; next_conv->inputs[norm_conv::kMovingMean] = bn->inputs[batchnorm::kInMovingMean]; next_conv->inputs[norm_conv::kMovingVar] = bn->inputs[batchnorm::kInMovingVar]; next_conv->op()->attr_parser(&(next_conv->attrs)); entry_map->insert({nnvm::NodeEntry{bn, batchnorm::kMean, 0}, nnvm::NodeEntry{next_conv, norm_conv::kSavedMean, 0}}); entry_map->insert({nnvm::NodeEntry{bn, batchnorm::kVar, 0}, nnvm::NodeEntry{next_conv, norm_conv::kSavedInvStdDev, 0}}); } } // namespace Graph FuseConvBN(Graph&& g) { // shapes, dtypes and context are necessary for checking compatibility with NormConvolution const auto& shape_vec = g.GetAttr<mxnet::ShapeVector>("shape"); const auto& dtype_vec = g.GetAttr<nnvm::DTypeVector>("dtype"); const auto& context_vec = g.GetAttr<ContextVector>("context"); auto& idx = g.indexed_graph(); // NormConvolution can have the same behavior than Convolution // So we convert compatible Convolution regardless of BN presence // We can always convert back to Convolution after DFSVisit(g.outputs, [&idx, &shape_vec, &dtype_vec, &context_vec](const nnvm::NodePtr node) { if (node->op() == Op::Get("Convolution")) { auto eid = idx.entry_id(node->inputs[0]); auto nid = idx.node_id(node.get()); if (norm_conv::IsCompatibleConvolution(node, dtype_vec[eid], shape_vec[eid], context_vec[nid])) ConvToNormConv(node); } }); // Fuse NormConv + BN + NormConv => NormConv + NormConv auto ne_counter = GetNodeEntryCount(g); nnvm::NodeEntryMap<nnvm::NodeEntry> entry_map; DFSVisit(g.outputs, [&idx, &shape_vec, &ne_counter, &entry_map](const nnvm::NodePtr& next) { if (next->op() == Op::Get("NormConvolution")) { auto node = next->inputs[0].node; auto eid = idx.entry_id(idx.node_id(node.get()), 0); if (IsCompatibleBN(node, shape_vec[eid]) && next->inputs[0].index == 0 && ne_counter[next->inputs[0]] == 1) { auto prev = node->inputs[0].node; if (prev->op() == Op::Get("NormConvolution") && ne_counter[node->inputs[0]] == 1) { FuseBatchNorm(prev, node, next, &entry_map); } } } }); g = ReplaceNodeEntries(std::move(g), entry_map); // Transform NormalizedConvolution without any ApplyStats or GenStats to Convolution ne_counter = GetNodeEntryCount(g); DFSVisit(g.outputs, [&ne_counter](const nnvm::NodePtr& n) { if (n->op() == Op::Get("NormConvolution")) { auto const& param = nnvm::get<NormConvolutionParam>(n->attrs.parsed); if (param.no_norm && ne_counter[nnvm::NodeEntry{n, 1, 0}] == 0 && ne_counter[nnvm::NodeEntry{n, 2, 0}] == 0) { NormConvToConv(n); } } }); return g; } } // namespace exec } // namespace mxnet <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/mass_op.cc<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <numeric> #include <random> #include "third_party/tensorflow/core/framework/op_kernel.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/tensor_shape.h" #include "third_party/tensorflow/core/lib/core/errors.h" namespace tensorflow { namespace babelfish { namespace { static const int kBOS = 1; static const int kEOS = 2; class MassOp : public OpKernel { public: explicit MassOp(OpKernelConstruction* ctx); void Compute(OpKernelContext* ctx) override; private: float mask_ratio_; int mask_minlen_; int mask_id_; int span_len_; float random_start_prob_; float keep_prob_; float rand_prob_; float mask_prob_; bool mask_target_; int vocab_size_; int first_unreserved_id_; std::mt19937 rng_; // Populates a vector of length seq_len with 1's in positions where // the corresponding token will be masked, and 0's elsewhere. void GenerateMask(std::vector<int>* mask); void ValidateInput(OpKernelContext* ctx, const Tensor& ids, const Tensor& weights, const Tensor& actual_seq_len); template <typename T> void CopyTensorToMutableOutput(const TensorShape& shape, const string& name, const Tensor& source, OpKernelContext* ctx, Tensor** out) { OP_REQUIRES_OK(ctx, ctx->allocate_output(name, shape, out)); (*out)->flat<T>() = source.flat<T>(); } }; MassOp::MassOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("mask_ratio", &mask_ratio_)); CHECK_GT(mask_ratio_, 0); CHECK_LT(mask_ratio_, 1); OP_REQUIRES_OK(ctx, ctx->GetAttr("mask_minlen", &mask_minlen_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("mask_id", &mask_id_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("span_len", &span_len_)); CHECK_GT(span_len_, 0); OP_REQUIRES_OK(ctx, ctx->GetAttr("random_start_prob", &random_start_prob_)); CHECK_GE(random_start_prob_, 0); CHECK_LE(random_start_prob_, 1); OP_REQUIRES_OK(ctx, ctx->GetAttr("keep_prob", &keep_prob_)); CHECK_GE(keep_prob_, 0); CHECK_LE(keep_prob_, 1); OP_REQUIRES_OK(ctx, ctx->GetAttr("rand_prob", &rand_prob_)); CHECK_GE(rand_prob_, 0); CHECK_LE(rand_prob_, 1); OP_REQUIRES_OK(ctx, ctx->GetAttr("mask_prob", &mask_prob_)); CHECK_GE(mask_prob_, 0); CHECK_LE(mask_prob_, 1); CHECK_EQ(keep_prob_ + rand_prob_ + mask_prob_, 1); OP_REQUIRES_OK(ctx, ctx->GetAttr("mask_target", &mask_target_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("vocab_size", &vocab_size_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("first_unreserved_id", &first_unreserved_id_)); rng_.seed(7743); // seed the random generator } void MassOp::ValidateInput(OpKernelContext* ctx, const Tensor& ids, const Tensor& weights, const Tensor& actual_seq_len) { // Verify shapes and sizes OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(ids.shape()), errors::InvalidArgument("ids must be matrix, but got ", ids.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(weights.shape()), errors::InvalidArgument("weights must be matrix, but got ", weights.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(actual_seq_len.shape()), errors::InvalidArgument("actual_seq_len must be vector, but got ", actual_seq_len.shape().DebugString())); OP_REQUIRES(ctx, ids.dim_size(0) > 0, errors::InvalidArgument("batch size must be > 0")); OP_REQUIRES(ctx, ids.dim_size(1) > 0, errors::InvalidArgument("max seq length must be > 0")); OP_REQUIRES(ctx, ids.dim_size(0) == weights.dim_size(0), errors::InvalidArgument("inconsistent batch size")); OP_REQUIRES(ctx, ids.dim_size(0) == actual_seq_len.dim_size(0), errors::InvalidArgument("inconsistent batch size")); OP_REQUIRES(ctx, ids.dim_size(1) == weights.dim_size(1), errors::InvalidArgument("inconsistent seq length")); } void MassOp::GenerateMask(std::vector<int>* mask) { int seq_len = mask->size(); int mask_len = seq_len * mask_ratio_; // skip short sentences if (mask_len < mask_minlen_) return; int num_segments = std::ceil(static_cast<float>(mask_len) / span_len_); int non_mask_len = seq_len - mask_len; // segments = [span_len, span_len, ..., span_len] std::vector<int> segments(num_segments + non_mask_len, span_len_); // if there is a remainder, last segment will be a different length if (mask_len % span_len_ > 0) { // now segments are [span_len, span_len, ..., remaining_mask_len] segments.back() = mask_len % span_len_; } // non-masked segments of length 1 are represented by 0 // now segments are [0, 0, ..., span_len, span_len, ... remaining_mask_len] std::fill(segments.begin(), segments.begin() + non_mask_len, 0); std::uniform_real_distribution<> realdistr(0.0, 1.0); float px = realdistr(rng_); float fixed_start_prob = 1 - random_start_prob_; if (px >= random_start_prob_ + fixed_start_prob / 2) { // place a segment at position 0, shuffle the rest std::swap(segments.front(), segments.back()); if (num_segments > 1) { std::shuffle(segments.begin() + 1, segments.end(), rng_); } } else if (px >= random_start_prob_) { // keep a segment at final position, shuffle the rest if (num_segments > 1) { std::shuffle(segments.begin(), segments.end() - 1, rng_); } } else { // shuffle all segments std::shuffle(segments.begin(), segments.end(), rng_); } int idx = 0; for (int n : segments) { if (n == 0) { // Each 0 in segments represents a non-masked token; i.e. mask will be 0 (*mask)[idx++] = 0; } else { // Each n in segments represents a masked segment of length n tokens for (int i = 0; i < n; i++) { (*mask)[idx++] = 1; } } } } void MassOp::Compute(OpKernelContext* ctx) { // get inputs const Tensor& ids = ctx->input(0); const Tensor& weights = ctx->input(1); const Tensor& actual_seq_len = ctx->input(2); auto Tactual_seq_len = actual_seq_len.vec<int32>(); ValidateInput(ctx, ids, weights, actual_seq_len); OP_REQUIRES_OK(ctx, ctx->status()); int batch_size = ids.dim_size(0); int max_seq_len = ids.dim_size(1); // create outputs Tensor* src_ids; Tensor* tgt_ids; Tensor* tgt_weights; Tensor* tgt_labels; CopyTensorToMutableOutput<int32>(TensorShape({batch_size, max_seq_len}), "src_ids", ids, ctx, &src_ids); CopyTensorToMutableOutput<int32>(TensorShape({batch_size, max_seq_len}), "tgt_ids", ids, ctx, &tgt_ids); CopyTensorToMutableOutput<float>(TensorShape({batch_size, max_seq_len}), "tgt_weights", weights, ctx, &tgt_weights); CopyTensorToMutableOutput<int32>(TensorShape({batch_size, max_seq_len}), "tgt_labels", ids, ctx, &tgt_labels); auto Tsrc_ids = src_ids->matrix<int32>(); auto Ttgt_ids = tgt_ids->matrix<int32>(); auto Ttgt_weights = tgt_weights->matrix<float>(); // for each example, mask the source and target to implement MASS. for (int i = 0; i < batch_size; i++) { int seq_len = Tactual_seq_len(i); if (seq_len <= 0) { LOG(WARNING) << "Skipping zero-length sequence"; continue; } if (seq_len > max_seq_len) seq_len = max_seq_len; std::vector<int> mask(seq_len, 0); GenerateMask(&mask); // Right shift tgt and drop EOS for (int j = max_seq_len - 1; j > 0; j--) { if (Ttgt_ids(i, j - 1) == kEOS) { Ttgt_ids(i, j) = 0; Ttgt_weights(i, j) = 0.0; } else { Ttgt_ids(i, j) = Ttgt_ids(i, j - 1); Ttgt_weights(i, j) = Ttgt_weights(i, j - 1); } } Ttgt_ids(i, 0) = kBOS; Ttgt_weights(i, 0) = 1.0; std::uniform_int_distribution<> vocabdistr(first_unreserved_id_, vocab_size_); // mask source and target tokens. if (std::accumulate(mask.begin(), mask.end(), 0) > 0) { for (int j = 0; j < mask.size(); j++) { if (mask[j] == 1) { std::uniform_real_distribution<> realdistr(0.0, 1.0); float tx = realdistr(rng_); if (tx >= mask_prob_ + rand_prob_) { // Keep token } else if (tx >= mask_prob_) { Tsrc_ids(i, j) = vocabdistr(rng_); // replace with random token } else { Tsrc_ids(i, j) = mask_id_; // replace with mask id } } else if (mask_target_) { // either source is masked or target is masked. Ttgt_ids(i, j) = mask_id_; // where target is masked, target weights are zero Ttgt_weights(i, j) = 0; } } } } } REGISTER_KERNEL_BUILDER(Name("Mass").Device(DEVICE_CPU), MassOp); } // namespace } // namespace babelfish } // namespace tensorflow <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/cl_stream.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CL_STREAM_HPP #define CL_STREAM_HPP #include <memory> #include "common/stream.hpp" #include "ocl/cl_executor.hpp" namespace mkldnn { namespace impl { namespace ocl { // Abstract stream class providing access to cl_executor. // Intended to use as a base class for OpenCL-like stream classes. struct cl_stream_t : public stream_t { cl_stream_t(engine_t *engine, unsigned flags) : stream_t(engine, flags) {} virtual ~cl_stream_t() override = default; virtual cl_executor_t *cl_executor() const { return cl_executor_.get(); } protected: void set_cl_executor(cl_executor_t *cl_executor) { cl_executor_.reset(cl_executor); } private: std::unique_ptr<cl_executor_t> cl_executor_; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/async/sharded_executor.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_SHARDED_EXECUTOR_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_SHARDED_EXECUTOR_H_ #include <functional> #include <memory> #include <vector> #include "REDACTEDmemory/memory.h" #include "REDACTEDsynchronization/blocking_counter.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread_safe_queue.h" namespace minigo { // Helper class for running a function over an array in parallel shards. // A simple example for setting all elements of an array to 1: // // constexpr int kSize = 10000; // constexpr int kNumShards = 4; // // ShardedExecutor executor(kNumShards); // std::array<int, kSize> a; // executor.Execute([&a](int shard, int num_shards) { // auto range = ShardedExecutor::GetShardRange(shard, num_shards, a.size()); // for (int i = range.begin; i < range.end; ++i) { // a[i] = 1; // } // }); // // `ShardedExecutor` is thread-safe. class ShardedExecutor { public: struct Range { int begin; int end; }; // Helper function for mapping from a shard to a sub-range of elements. static Range GetShardRange(int shard_idx, int num_shards, int num_elements) { auto begin = shard_idx * num_elements / num_shards; auto end = (shard_idx + 1) * num_elements / num_shards; return {begin, end}; } explicit ShardedExecutor(int num_shards); ~ShardedExecutor(); // Invoke `fn` `num_shards` times. // The first argument to `fn` is the shard ID in the range [0, `num_shards`). // The second argument to `fn` is `num_shards`. // One invocation of `fn` happens on the calling thread; if `num_shards > 0`, // the remaining invocations happen in parallel on threads owned by the // `ShardedExecutor`. // Blocks until all shards of work are complete. void Execute(const std::function<void(int, int)>& fn); private: struct WorkerThread : public Thread { WorkerThread(int shard, int num_shards); void Execute(const std::function<void(int, int)>* fn, absl::BlockingCounter* counter); void Join() override; private: struct Work { const std::function<void(int, int)>* fn; absl::BlockingCounter* counter; }; void Run() override; const int shard_; const int num_shards_; ThreadSafeQueue<Work> work_queue_; }; std::vector<std::unique_ptr<WorkerThread>> threads_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_SHARDED_EXECUTOR_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/kvstore/comm_tree.h<|end_filename|> /* * 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. */ /** * Copyright (c) 2018 by Contributors */ #ifndef MXNET_KVSTORE_COMM_TREE_H_ #define MXNET_KVSTORE_COMM_TREE_H_ #include <dmlc/omp.h> #include <string> #include <algorithm> #include <utility> #include <limits> #include <vector> #include <tuple> #include <thread> #include <map> #include "mxnet/ndarray.h" #include "gradient_compression.h" #include "../ndarray/ndarray_function.h" #include "../operator/tensor/sparse_retain-inl.h" #include "./kvstore_utils.h" #include "./gpu_topology.h" namespace mxnet { namespace kvstore { /** * \brief an implementation of Comm that performs reduction on device * directly using tree. * * It is faster if the total device-to-device bandwidths is larger than * device-to-cpu, which is often true for 4 or 8 GPUs. But it uses more device * memory. */ class CommDeviceTree : public CommDevice { public: CommDeviceTree() { inited_ = false; gpuarray_bound_ = dmlc::GetEnv("MXNET_KVSTORE_TREE_ARRAY_BOUND", 10000000); backtrack_ = dmlc::GetEnv("MXNET_KVSTORE_TREE_BACKTRACK", 0); link_usage_penalty_ = dmlc::GetEnv("MXNET_KVSTORE_TREE_LINK_USAGE_PENALTY", 0.7); } virtual ~CommDeviceTree() { } void Init(int key, const NDArrayStorageType stype, const mxnet::TShape& shape, int dtype = mshadow::kFloat32) override { tree_sorted_key_attrs_.emplace_back(key, shape, dtype); sorted_key_attrs_.emplace_back(key, shape, dtype); } void InitBuffersAndComm(const std::vector<NDArray>& src) { if (!inited_) { for (const auto& a : src) { devs_.push_back(a.ctx()); } QueryTopology(); // Note: delayed allocation set to true, because we do not want to allocate // both in TreeBufferEntry and BufferEntry, so we use a size_t to keep // track of each key's shape within BufferEntry // -this information is required for inherited Reduce- and // BroadcastRowSparse InitMergeBuffer(devs_); InitMergeBufferTree(); } } /** * \brief Reduce src to tree_merge_buf_ * \param key is the id of the gradient we are doing Reduce on * \param src is the array of values located on different GPUs * \param root is the id of the GPU we want to send result of reduce to * \param merged_row is the id of the slice we are taking * \param priority the priority of the operation */ const NDArray& ReduceInner(int key, const std::vector<NDArray>& src, int root, int merged_row, int priority) { std::vector<std::vector<NDArray>> reduce(devs_.size()); TreeBufferEntry& random_buf = tree_merge_buf_[0][key]; const NDArrayStorageType stype = random_buf.merged[0].storage_type(); std::vector<size_t>& topology = topology_[root]; NDArray buf_slice; if (stype == kDefaultStorage) { // Copy everything into buf.merged for each gpu for (const auto& src_gpu_value : src) { int start = scan_[root][depth_]; int end = scan_[root][depth_+1]; for (int j = start; j < end; ++j) { int topo_id = topology[j]; TreeBufferEntry& buf = tree_merge_buf_[topo_id][key]; if (devs_[topo_id] == src_gpu_value.ctx()) { CopyFromTo(src_gpu_value, &(buf.merged[merged_row]), priority); } } } for (int level = depth_; level > 0; --level) { int start = scan_[root][level ]; int end = scan_[root][level+1]; unsigned is_dest = 0; int dest_id = 0; for (int j = start; j < end; ++j) { int topo_id = topology[j]; dest_id = (is_dest == 0) ? topo_id : dest_id; TreeBufferEntry& buf_dest = tree_merge_buf_[dest_id][key]; TreeBufferEntry& buf_from = tree_merge_buf_[topo_id][key]; if (!is_dest) { if (reduce[dest_id].size() == 0) { reduce[dest_id].push_back(buf_dest.merged[merged_row]); } } else { if (dest_id != topo_id) { CopyFromTo(buf_from.merged[merged_row], &(buf_dest.copy_buf[merged_row][is_dest-1]), priority); reduce[dest_id].push_back( buf_dest.copy_buf[merged_row][is_dest-1]); } } is_dest = (is_dest == static_cast<unsigned>(kBranch)-1) ? 0 : is_dest+1; } start = scan_[root][level-1]; end = scan_[root][level]; int source = end; for (int i = start; i < end; ++i) { int gpu_id = topology[i]; // source keeps track of 2 leaf nodes, while start keeps track of parent int dest_id = topology[source]; int from_id = topology[source+1]; source += 2; // conditional to detect whether operation must be done if (reduce[gpu_id].size() > 1 && dest_id != from_id) { TreeBufferEntry& buf = tree_merge_buf_[gpu_id][key]; ElementwiseSum(reduce[gpu_id], &(buf.merged[merged_row]), priority); } } // reset for (unsigned i = 0; i < devs_.size(); ++i) { reduce[i].clear(); } } } else { LOG(FATAL) << "Only dense input supported for now"; } int topo_id = topology[0]; TreeBufferEntry& buf = tree_merge_buf_[topo_id][key]; return buf.merged[merged_row]; } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { // when this reduce is called from kvstore_dist, gc is not set // we don't do compression twice in dist_sync_device if ((gc_ != nullptr) && (gc_->get_type() != CompressionType::kNone)) { return ReduceCompressed(key, src, priority); } // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { return src[0]; } InitBuffersAndComm(src); std::vector<std::vector<NDArray>> slice(devs_.size()); std::vector<std::vector<NDArray*>> broadcast_slice(devs_.size()); std::vector<int> slice_scan(devs_.size()+1); int total_size = src[0].shape().Size(); unsigned first_size = src[0].shape()[0]; const NDArrayStorageType stype = src[0].storage_type(); // normal dense reduce if (stype == kDefaultStorage) { if (total_size > gpuarray_bound_ && first_size >= 2*devs_.size()) { // Find slice bounds slice_scan[0] = 0; int slice_size = first_size/devs_.size(); for (unsigned i = 1; i < devs_.size(); ++i) { slice_scan[i] = slice_scan[i-1] + slice_size; } slice_scan[devs_.size()] = src[0].shape()[0]; // row: which slice // col: which gpu for (unsigned row = 0; row < devs_.size(); ++row) { for (unsigned col = 0; col < devs_.size(); ++col) { TreeBufferEntry& buf = tree_merge_buf_[col][key]; NDArray curr_slice = src[col].Slice(slice_scan[row], slice_scan[row+1]); slice[row].push_back(curr_slice); broadcast_slice[row].push_back(&(buf.merged[row])); } } // Do reduce-scatter (multiroot reduce) // input: slice (src) // output: buf.merge_buf for (unsigned i = 0; i < devs_.size(); ++i) { ReduceInner(key, slice[i], i, i, priority); } for (unsigned i = 0; i < devs_.size(); ++i) { BroadcastInner(key, *(broadcast_slice[i][i]), broadcast_slice[i], i, i, priority); } } else { int root = 0; ReduceInner(key, src, root, 0, priority); TreeBufferEntry& buf = tree_merge_buf_[root][key]; return buf.merged[0]; } // Copy from list of small NDArrays to one big NDArray, which is returned int gpu_id = 0; return src[gpu_id]; } else { // sparse reduce return ReduceRowSparse(key, src, priority); } } void BroadcastInner(int key, const NDArray& src, const std::vector<NDArray*>& dst, int root, int merged_row, int priority) { // copy to root of tree std::vector<size_t>& topology = topology_[root]; std::vector<NDArray> temp(devs_.size()); int gpu_id = topology[0]; if (merged_row == -1) CopyFromTo(src, dst[gpu_id], priority); temp[gpu_id] = *dst[gpu_id]; for (int level = 1; level <= depth_; ++level) { int start = scan_[root][level]; int end = scan_[root][level+1]; unsigned is_src = 0; int src_id = 0; for (int j = start; j < end; ++j) { int topo_id = topology[j]; src_id = (is_src == 0) ? topo_id : src_id; if (is_src && src_id != topo_id) { CopyFromTo(temp[src_id], dst[topo_id], priority); temp[topo_id] = *dst[topo_id]; } is_src = (is_src == static_cast<unsigned>(kBranch)-1) ? 0 : is_src+1; } } } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { if (!inited_) { // copy to a random device first int dev_id = key % dst.size(); CopyFromTo(src, dst[dev_id], priority); for (size_t i = 0; i < dst.size(); ++i) { if (i != static_cast<size_t>(dev_id)) { CopyFromTo(*dst[dev_id], dst[i], priority); } } } else { int total_size = src.shape().Size(); unsigned first_size = src.shape()[0]; const NDArrayStorageType stype = src.storage_type(); // normal dense reduce if (stype == kDefaultStorage) { if (total_size > gpuarray_bound_ && first_size >= 2*devs_.size()) { std::vector<int> slice_scan(devs_.size()+1); slice_scan[0] = 0; int slice_size = (dst[0]->shape()[0])/devs_.size(); for (unsigned i = 1; i < devs_.size(); ++i) { slice_scan[i] = slice_scan[i-1] + slice_size; } slice_scan[devs_.size()] = dst[0]->shape()[0]; for (unsigned gpu_id = 0; gpu_id < dst.size(); ++gpu_id) { TreeBufferEntry& buf = tree_merge_buf_[gpu_id][key]; for (unsigned i = 0; i < devs_.size(); ++i) { if (devs_[gpu_id] == dst[gpu_id]->ctx()) { NDArray curr_slice = dst[gpu_id]->Slice(slice_scan[i], slice_scan[i+1]); CopyFromTo(buf.merged[i], &curr_slice, priority); } } } } else { int root = 0; BroadcastInner(key, src, dst, root, -1, priority); }} else { LOG(FATAL) << "Only dense input supported for now"; } } } private: void EnableP2P(std::vector<int>* p2p) { #if MXNET_USE_CUDA std::vector<int> gpus; for (const auto& d : devs_) { if (d.dev_mask() == gpu::kDevMask) { gpus.push_back(d.dev_id); } } int n = static_cast<int>(gpus.size()); int enabled = 0; p2p->clear(); p2p->resize(n*n, 0); for (int i = 0; i < n; ++i) { mxnet::common::cuda::DeviceStore device_store(gpus[i]); for (int j = 0; j < n; j++) { int access; cudaDeviceCanAccessPeer(&access, gpus[i], gpus[j]); if (access) { cudaDeviceEnablePeerAccess(gpus[j], 0); cudaError_t e = cudaGetLastError(); if (e == cudaSuccess || e == cudaErrorPeerAccessAlreadyEnabled || e == cudaErrorCudartUnloading) { ++enabled; (*p2p)[i*n+j] = 1; } else { LOG(FATAL) << cudaGetErrorString(e); } } } } if (enabled != n*(n-1)) { // print warning info if not fully enabled LOG(WARNING) << "only " << enabled << " out of " << n*(n-1) << " GPU pairs are enabled direct access. " << "It may affect the performance. " << "You can set MXNET_ENABLE_GPU_P2P=0 to turn it off"; std::string access(n, '.'); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { access[j] = (*p2p)[i*n+j] ? 'v' : '.'; } LOG(WARNING) << access; } } #endif } void QueryTopology() { #if MXNET_USE_CUDA std::vector<float> link_matrix(devs_.size()*devs_.size()); std::vector<int> p2p_matrix(devs_.size()*devs_.size()); EnableP2P(&p2p_matrix); GetP2PWeight(devs_, p2p_matrix, &link_matrix); if (backtrack_) LOG(INFO) << "Using Backtracking to generate trees"; else LOG(INFO) << "Using Kernighan-Lin to generate trees"; ComputeTrees(link_matrix, devs_.size(), link_usage_penalty_, backtrack_, &topology_, &scan_); depth_ = ComputeDepth(devs_.size()); #endif } using KeyAttrs = std::tuple<int, mxnet::TShape, int>; // try to allocate buff on device evenly void InitMergeBufferTree() { LOG(INFO) << "Using Tree"; // same as all-reduce, except: // 1) Allocate copy_buf here instead of in Reduce() // 2) Force copy_buf to be of kRecvBufferSize // 3) Do not use greedy assignment; all keys are assigned to each GPU for (unsigned i = 0; i < devs_.size(); ++i) tree_merge_buf_.emplace_back(); bool delay_alloc = true; std::map<int, int> key_dist; for (auto& tree_sorted_key_attr : tree_sorted_key_attrs_) { const int key = std::get<0>(tree_sorted_key_attr); const mxnet::TShape& shape = std::get<1>(tree_sorted_key_attr); const int type = std::get<2>(tree_sorted_key_attr); if (key_dist.find(shape.Size()) == key_dist.end()) key_dist[shape.Size()] = 1; else key_dist[shape.Size()]++; int start = scan_[0][depth_]; int end = scan_[0][depth_+1]; // In order to generalize to any number of GPUs in arbitrary order, we use // strategy of having found the mapping from 0, 1, ..., n_gpus to dev_id. // For example, if the user wants to use --gpus 4,2,3,1,7,5,0, they can do // so: // // idx: 0 1 2 3 4 5 6 // dev_id: 4 2 3 1 7 5 0 // // From this, we: // 1) generate a link topology matrix with dimensions n_gpus x n_gpus // (link_matrix) // // 2) the reduction trees are saved as indices from 0, 1, ..., n_gpus // in a vector of vectors (topology_): // // index | topology_[index] // ------------------------- // 0 | [Tree 0] // 1 | [Tree 1] // . // . // . // n_gpus | [Tree n_gpus] // // 3) We use the mapping (devs_) to retrieve dev_id and device context for (int j = start; j < end; ++j) { int topo_id = topology_[0][j]; auto& buf = tree_merge_buf_[topo_id][key]; Context ctx = devs_[topo_id]; // buf.merged enforces that we only visit each GPU once if (buf.merged.empty()) { mxnet::TShape shape_copy = shape; int total_size = shape.Size(); unsigned first_size = shape[0]; if (total_size > gpuarray_bound_ && first_size >= 2*devs_.size()) { // Find slice bounds int slice_size = first_size/devs_.size(); int last_slice = first_size-(devs_.size()-1)*slice_size; shape_copy[0] = slice_size; buf.merged.resize(devs_.size()); for (unsigned row = 0; row < devs_.size(); ++row) { if (row == devs_.size()-1) shape_copy[0] = last_slice; buf.merged[row] = NDArray(shape_copy, ctx, delay_alloc, type); buf.copy_buf.emplace_back(); if (buf.copy_buf[row].empty()) { buf.copy_buf[row].resize(kBranch-1); for (size_t col = 0; col < buf.copy_buf[0].size(); ++col) { buf.copy_buf[row][col] = NDArray(buf.merged[row].shape(), buf.merged[row].ctx(), delay_alloc, buf.merged[row].dtype()); } } } } else { buf.merged.emplace_back(shape, ctx, false, type); if (buf.copy_buf.empty()) { buf.copy_buf.emplace_back(); buf.copy_buf[0].resize(kBranch-1); for (size_t col = 0; col < buf.copy_buf[0].size(); ++col) { buf.copy_buf[0][col] = NDArray(buf.merged[0].shape(), buf.merged[0].ctx(), delay_alloc, buf.merged[0].dtype()); } } } } } } for (auto& kv : key_dist) { LOG(INFO) << "Size " << kv.first << " occurs " << kv.second << " times"; } inited_ = true; } std::vector<KeyAttrs> tree_sorted_key_attrs_; /// \brief temporal space for pushing and pulling struct TreeBufferEntry { /// \brief the dense merged value for reduce and broadcast operations std::vector<NDArray> merged; /// \brief the gpu buffer for copy during reduce operation std::vector<std::vector<NDArray>> copy_buf; /// \brief the residual buffer for gradient compression std::vector<NDArray> residual; /// \brief the small buffer for compressed data in sender std::vector<NDArray> compressed_send_buf; /// \brief the small buffer for compressed data in receiver std::vector<NDArray> compressed_recv_buf; private: /// \brief the sparse merged value for reduce and rowsparse broadcast operations NDArray sparse_merged; }; /// \brief intent of tree_merge_buf_ in old comm.h: store key->gpu mapping /// new intent: for every gpu: store key->memory mapping std::vector<std::unordered_map<int, TreeBufferEntry>> tree_merge_buf_; /// \brief NVLink-connected topology in full binary tree format std::vector<std::vector<size_t>> topology_; std::vector<std::vector<size_t>> scan_; std::vector<Context> devs_; int depth_; int gpuarray_bound_; bool backtrack_; float link_usage_penalty_; /// \brief constant for maximum size of recv buffer per GPU /// 2: only receive from 1 other GPU const int kBranch = 2; }; } // namespace kvstore } // namespace mxnet #endif // MXNET_KVSTORE_COMM_TREE_H_ <|start_filename|>Intel/benchmarks/minigo/8-nodes-32s-cpx-tensorflow/cc/eval.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 <stdio.h> #include <atomic> #include <cmath> #include <functional> #include <iostream> #include <memory> #include <string> #include <thread> #include <utility> #include <vector> #include <fstream> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_split.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "cc/constants.h" #include "cc/file/path.h" #include "cc/file/utils.h" #include "cc/game.h" #include "cc/game_utils.h" #include "cc/init.h" #include "cc/logging.h" #include "cc/mcts_player.h" #include "cc/model/batching_model.h" #include "cc/model/loader.h" #include "cc/model/model.h" #include "cc/random.h" #include "cc/tf_utils.h" #include "cc/zobrist.h" #include "gflags/gflags.h" // Game options flags. DEFINE_bool(resign_enabled, true, "Whether resign is enabled."); DEFINE_double(resign_threshold, -0.999, "Resign threshold."); DEFINE_uint64(seed, 0, "Random seed. Use default value of 0 to use a time-based seed."); // Tree search flags. DEFINE_int32(virtual_losses, 8, "Number of virtual losses when running tree search."); DEFINE_double(value_init_penalty, 2.0, "New children value initialization penalty.\n" "Child value = parent's value - penalty * color, clamped to" " [-1, 1]. Penalty should be in [0.0, 2.0].\n" "0 is init-to-parent, 2.0 is init-to-loss [default].\n" "This behaves similiarly to Leela's FPU \"First Play Urgency\"."); // Inference flags. DEFINE_string(eval_model, "", "Path to a minigo model to evaluate against a target."); DEFINE_string(eval_device, "", "Optional ID of the device to the run inference on for the eval " "model. For TPUs, pass the gRPC address."); DEFINE_int32(num_eval_readouts, 100, "Number of readouts to make during tree search for the eval " "model.)"); DEFINE_string(target_model, "", "Path to a target minigo model that eval_model is evaluated " "against."); DEFINE_string(target_device, "", "Optional ID of the device to the run inference on for the " "target model. For TPUs, pass the gRPC address."); DEFINE_int32(num_target_readouts, 100, "Number of readouts to make during tree search for the eval " "model.)"); DEFINE_int32(parallel_games, 32, "Number of games to play in parallel."); // Output flags. DEFINE_string(output_bigtable, "", "Output Bigtable specification, of the form: " "project,instance,table. " "If empty, no examples are written to Bigtable."); DEFINE_string(sgf_dir, "", "SGF directory for selfplay and puzzles. If empty in selfplay " "mode, no SGF is written."); DEFINE_string(bigtable_tag, "", "Used in Bigtable metadata."); DEFINE_bool(verbose, true, "Enable verbose logging."); namespace minigo { namespace { class Evaluator { class EvaluatedModel { public: EvaluatedModel(BatchingModelFactory* batcher, const std::string& path, const MctsPlayer::Options& player_options) : batcher_(batcher), path_(path), player_options_(player_options) {} std::string name() { absl::MutexLock lock(&mutex_); if (name_.empty()) { // The model's name is lazily initialized the first time we create a // instance. Make sure it's valid. NewModelImpl(); } return name_; } WinStats GetWinStats() const { absl::MutexLock lock(&mutex_); return win_stats_; } void UpdateWinStats(const Game& game) { absl::MutexLock lock(&mutex_); win_stats_.Update(game); } std::unique_ptr<Model> NewModel() { absl::MutexLock lock(&mutex_); return NewModelImpl(); } const MctsPlayer::Options& player_options() const { return player_options_; } private: std::unique_ptr<Model> NewModelImpl() EXCLUSIVE_LOCKS_REQUIRED(&mutex_) { auto model = batcher_->NewModel(path_); if (name_.empty()) { name_ = model->name(); } return model; } mutable absl::Mutex mutex_; BatchingModelFactory* batcher_ GUARDED_BY(&mutex_); const std::string path_; std::string name_ GUARDED_BY(&mutex_); WinStats win_stats_ GUARDED_BY(&mutex_); MctsPlayer::Options player_options_; }; public: Evaluator() { // Create a batcher for the eval model. batchers_.push_back( absl::make_unique<BatchingModelFactory>(FLAGS_eval_device, 2)); // If the target model requires a different device, create one & a second // batcher too. if (FLAGS_target_device != FLAGS_eval_device) { batchers_.push_back( absl::make_unique<BatchingModelFactory>(FLAGS_target_device, 2)); } } void Run() { auto start_time = absl::Now(); game_options_.resign_enabled = FLAGS_resign_enabled; game_options_.resign_threshold = -std::abs(FLAGS_resign_threshold); std::ofstream outfile; outfile.open("train.log", std::ios_base::app); std::time_t t = std::time(0); outfile << ":::MLLOG {\"namespace\": \"worker1\", \"time_ms\": " << t << ", \"event_type\": \"POINT_IN_TIME\", \"key\": \"resign_threshold\", \"value\": " << game_options_.resign_threshold << ", \"metadata\": {\"file\": \"eval.cc\", \"lineno\": 177}}" << "\n"; outfile.close(); MctsPlayer::Options player_options; player_options.virtual_losses = FLAGS_virtual_losses; player_options.inject_noise = false; player_options.random_seed = FLAGS_seed; player_options.tree.value_init_penalty = FLAGS_value_init_penalty; player_options.tree.soft_pick_enabled = false; player_options.num_readouts = FLAGS_num_eval_readouts; EvaluatedModel eval_model(batchers_.front().get(), FLAGS_eval_model, player_options); player_options.num_readouts = FLAGS_num_target_readouts; EvaluatedModel target_model(batchers_.back().get(), FLAGS_target_model, player_options); int num_games = FLAGS_parallel_games; for (int thread_id = 0; thread_id < num_games; ++thread_id) { bool swap_models = (thread_id & 1) != 0; threads_.emplace_back( std::bind(&Evaluator::ThreadRun, this, thread_id, swap_models ? &target_model : &eval_model, swap_models ? &eval_model : &target_model)); } for (auto& t : threads_) { t.join(); } MG_LOG(INFO) << "Evaluated " << num_games << " games, total time " << (absl::Now() - start_time); MG_LOG(INFO) << FormatWinStatsTable( {{eval_model.name(), eval_model.GetWinStats()}, {target_model.name(), target_model.GetWinStats()}}); } private: void ThreadRun(int thread_id, EvaluatedModel* black_model, EvaluatedModel* white_model) { // Only print the board using ANSI colors if stderr is sent to the // terminal. const bool use_ansi_colors = FdSupportsAnsiColors(fileno(stderr)); // The player and other_player reference this pointer. std::unique_ptr<Model> model; std::vector<std::string> bigtable_spec = absl::StrSplit(FLAGS_output_bigtable, ','); bool use_bigtable = bigtable_spec.size() == 3; if (!FLAGS_output_bigtable.empty() && !use_bigtable) { MG_LOG(FATAL) << "Bigtable output must be of the form: project,instance,table"; return; } Game game(black_model->name(), white_model->name(), game_options_); const bool verbose = FLAGS_verbose && (thread_id == 0); auto black = absl::make_unique<MctsPlayer>( black_model->NewModel(), nullptr, &game, black_model->player_options()); auto white = absl::make_unique<MctsPlayer>( white_model->NewModel(), nullptr, &game, white_model->player_options()); BatchingModelFactory::StartGame(black->model(), white->model()); auto* curr_player = black.get(); auto* next_player = white.get(); while (!game.game_over()) { if (curr_player->root()->position.n() >= kMinPassAliveMoves && curr_player->root()->position.CalculateWholeBoardPassAlive()) { // Play pass moves to end the game. while (!game.game_over()) { MG_CHECK(curr_player->PlayMove(Coord::kPass)); next_player->PlayOpponentsMove(Coord::kPass); std::swap(curr_player, next_player); } break; } auto move = curr_player->SuggestMove(curr_player->options().num_readouts); if (verbose) { std::cerr << curr_player->tree().Describe() << "\n"; } MG_CHECK(curr_player->PlayMove(move)); if (move != Coord::kResign) { next_player->PlayOpponentsMove(move); } if (verbose) { MG_LOG(INFO) << absl::StreamFormat( "%d: %s by %s\nQ: %0.4f", curr_player->root()->position.n(), move.ToGtp(), curr_player->name(), curr_player->root()->Q()); MG_LOG(INFO) << curr_player->root()->position.ToPrettyString( use_ansi_colors); } std::swap(curr_player, next_player); } BatchingModelFactory::EndGame(black->model(), white->model()); if (game.result() > 0) { black_model->UpdateWinStats(game); } else { white_model->UpdateWinStats(game); } if (verbose) { MG_LOG(INFO) << game.result_string(); MG_LOG(INFO) << "Black was: " << game.black_name(); } // Write SGF. std::string output_name = "NO_SGF_SAVED"; if (!FLAGS_sgf_dir.empty()) { output_name = absl::StrCat(GetOutputName(game_id_++), "-", black->name(), "-", white->name()); game.AddComment( absl::StrCat("B inferences: ", black->GetModelsUsedForInference())); game.AddComment( absl::StrCat("W inferences: ", white->GetModelsUsedForInference())); WriteSgf(FLAGS_sgf_dir, output_name, game, true); } if (use_bigtable) { const auto& gcp_project_name = bigtable_spec[0]; const auto& instance_name = bigtable_spec[1]; const auto& table_name = bigtable_spec[2]; tf_utils::WriteEvalRecord(gcp_project_name, instance_name, table_name, game, output_name, FLAGS_bigtable_tag); } MG_LOG(INFO) << "Thread " << thread_id << " stopping"; } Game::Options game_options_; std::vector<std::thread> threads_; std::atomic<size_t> game_id_{0}; std::vector<std::unique_ptr<BatchingModelFactory>> batchers_; }; } // namespace } // namespace minigo int main(int argc, char* argv[]) { minigo::Init(&argc, &argv); minigo::zobrist::Init(FLAGS_seed); minigo::Evaluator evaluator; evaluator.Run(); return 0; } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/file/utils_windows.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 <cstdio> #include <string> #include "REDACTEDstrings/match.h" #include "REDACTEDstrings/string_view.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> // NOLINT namespace minigo { namespace file { namespace { bool MaybeCreateDir(const std::string& path) { if (CreateDirectory(path.c_str(), nullptr)) { return true; } if (GetLastError() != ERROR_ALREADY_EXISTS) { return false; } auto attribs = GetFileAttributes(path.c_str()); if (attribs == INVALID_FILE_ATTRIBUTES) { return false; } return (attribs & FILE_ATTRIBUTE_DIRECTORY) != 0; } bool RecursivelyCreateDirNormalized(const std::string& path) { if (MaybeCreateDir(path)) { return true; } if (!RecursivelyCreateDirNormalized(std::string(Dirname(path)))) { return false; } // Creates the directory knowing the parent already exists. return MaybeCreateDir(path); } } // namespace bool RecursivelyCreateDir(std::string path) { return RecursivelyCreateDirNormalized(NormalizeSlashes(path)); } bool WriteFile(std::string path, absl::string_view contents) { path = NormalizeSlashes(path); FILE* f = fopen(path.c_str(), "wb"); if (f == nullptr) { MG_LOG(ERROR) << "error opening " << path << " for write"; return false; } bool ok = true; if (!contents.empty()) { ok = fwrite(contents.data(), contents.size(), 1, f) == 1; if (!ok) { MG_LOG(ERROR) << "error writing " << path; } } fclose(f); return ok; } bool ReadFile(std::string path, std::string* contents) { path = NormalizeSlashes(path); FILE* f = fopen(path.c_str(), "rb"); if (f == nullptr) { MG_LOG(ERROR) << "error opening " << path << " for read"; return false; } fseek(f, 0, SEEK_END); contents->resize(ftell(f)); fseek(f, 0, SEEK_SET); bool ok = fread(&(*contents)[0], contents->size(), 1, f) == 1; if (!ok) { MG_LOG(ERROR) << "error reading " << path; } fclose(f); return ok; } bool GetModTime(std::string path, uint64_t* mtime_usec) { path = NormalizeSlashes(path); auto h = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (h == INVALID_HANDLE_VALUE) { return false; } FILETIME t; bool success = GetFileTime(h, nullptr, nullptr, &t); CloseHandle(h); if (success) { // FILETIME represents time in 100-nanosecond intervals. Convert to // microseconds. auto lo = static_cast<uint64_t>(t.dwLowDateTime); auto hi = static_cast<uint64_t>(t.dwHighDateTime) << 32; auto usec = (lo + hi) / 10; // Also, the Windows & Unix epochs are different. *mtime_usec = usec - 11644473600000000ull; } return success; } bool ListDir(std::string directory, std::vector<std::string>* files) { directory = JoinPath(NormalizeSlashes(directory), "*"); WIN32_FIND_DATA ffd; auto h = FindFirstFile(directory.c_str(), &ffd); if (h == INVALID_HANDLE_VALUE) { return false; } files->clear(); do { absl::string_view p(ffd.cFileName); if (p == "." || p == "..") { continue; } files->push_back(ffd.cFileName); } while (FindNextFile(h, &ffd)); FindClose(h); return true; } bool FileExists(std::string path) { path = NormalizeSlashes(path); auto dwAttrib = GetFileAttributes(path.c_str()); return dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY); } } // namespace file } // namespace minigo <|start_filename|>NVIDIA/benchmarks/dlrm/implementations/hugectr/Dockerfile<|end_filename|> # Copyright (c) 2020, NVIDIA CORPORATION. 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. # NOTE: This implementation of DLRM uses the HugeCTR framework. The benchmark # leverages the NGC PyTorch image solely for the GPU-enabled build environment # it provides, not for the PyTorch framework itself (HugeCTR as a framework is # independent of PyTorch). Other NGC DL Frameworks images such as # nvcr.io/nvidia/tensorflow:20.06-tf1-py3 or nvcr.io/nvidia/mxnet:20.06-py3 # could have been used similarly as a base for this benchmark. ARG FROM_IMAGE_NAME=nvcr.io/nvidia/pytorch:20.06-py3 FROM ${FROM_IMAGE_NAME} # Install HugeCTR framework WORKDIR /opt RUN git clone --recursive -b v2.1_a100_update https://github.com/NVIDIA/hugectr.git \ && cd hugectr \ && mkdir -p build \ && cd build \ && cmake -DCMAKE_BUILD_TYPE=Release -DSM="70;80" .. \ && make -j$(nproc) \ && cp bin/* /usr/local/bin \ && cd .. \ && git submodule deinit json \ && rm -rf build .git/modules/json # Install Python dependencies RUN pip install --no-cache-dir https://github.com/mlperf/logging/archive/9ea0afa.zip \ && pip install --no-cache-dir numpy pandas sklearn ortools # Install DLRM benchmark code WORKDIR /workspace/dlrm COPY . . <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/examples/cpu_cnn_training_f32.c<|end_filename|> /******************************************************************************* * Copyright 2016-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /// @example cpu_cnn_training_f32.c /// @copybrief cpu_cnn_training_f32_c /// @page cpu_cnn_training_f32_c CNN f32 training example /// This C API example demonstrates how to build an AlexNet model training. /// The example implements a few layers from AlexNet model. /// /// @include cpu_cnn_training_f32.c // Required for posix_memalign #define _POSIX_C_SOURCE 200112L #include "mkldnn.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BATCH 32 #define IC 3 #define OC 96 #define CONV_IH 227 #define CONV_IW 227 #define CONV_OH 55 #define CONV_OW 55 #define CONV_STRIDE 4 #define CONV_PAD 0 #define POOL_OH 27 #define POOL_OW 27 #define POOL_STRIDE 2 #define POOL_PAD 0 #define CHECK(f) \ do { \ mkldnn_status_t s = f; \ if (s != mkldnn_success) { \ printf("[%s:%d] error: %s returns %d\n", __FILE__, __LINE__, #f, \ s); \ exit(2); \ } \ } while (0) #define CHECK_TRUE(expr) \ do { \ int e_ = expr; \ if (!e_) { \ printf("[%s:%d] %s failed\n", __FILE__, __LINE__, #expr); \ exit(2); \ } \ } while (0) static size_t product(mkldnn_dim_t *arr, size_t size) { size_t prod = 1; for (size_t i = 0; i < size; ++i) prod *= arr[i]; return prod; } static void init_net_data(float *data, uint32_t dim, const mkldnn_dim_t *dims) { if (dim == 1) { for (mkldnn_dim_t i = 0; i < dims[0]; ++i) { data[i] = (float)(i % 1637); } } else if (dim == 4) { for (mkldnn_dim_t in = 0; in < dims[0]; ++in) for (mkldnn_dim_t ic = 0; ic < dims[1]; ++ic) for (mkldnn_dim_t ih = 0; ih < dims[2]; ++ih) for (mkldnn_dim_t iw = 0; iw < dims[3]; ++iw) { mkldnn_dim_t indx = in * dims[1] * dims[2] * dims[3] + ic * dims[2] * dims[3] + ih * dims[3] + iw; data[indx] = (float)(indx % 1637); } } } typedef struct { int nargs; mkldnn_exec_arg_t *args; } args_t; static void prepare_arg_node(args_t *node, int nargs) { node->args = (mkldnn_exec_arg_t *)malloc(sizeof(mkldnn_exec_arg_t) * nargs); node->nargs = nargs; } static void free_arg_node(args_t *node) { free(node->args); } static void set_arg( mkldnn_exec_arg_t *arg, int arg_idx, mkldnn_memory_t memory) { arg->arg = arg_idx; arg->memory = memory; } static void init_data_memory(uint32_t dim, const mkldnn_dim_t *dims, mkldnn_format_tag_t user_fmt, mkldnn_data_type_t data_type, mkldnn_engine_t engine, float *data, mkldnn_memory_t *memory) { mkldnn_memory_desc_t user_md; CHECK(mkldnn_memory_desc_init_by_tag( &user_md, dim, dims, mkldnn_f32, user_fmt)); CHECK(mkldnn_memory_create(memory, &user_md, engine, data)); } mkldnn_status_t prepare_reorder(mkldnn_memory_t *user_memory, /// in const mkldnn_memory_desc_t *prim_memory_md, /// in mkldnn_engine_t prim_engine, /// in: primitive's engine int dir_is_user_to_prim, /// in: user -> prim or prim -> user mkldnn_memory_t *prim_memory, /// out: primitive's memory created mkldnn_primitive_t *reorder, /// out: reorder primitive created uint32_t * net_index, /// primitive index in net (inc if reorder created) mkldnn_primitive_t *net, args_t *net_args) { const mkldnn_memory_desc_t *user_memory_md; mkldnn_memory_get_memory_desc(*user_memory, &user_memory_md); mkldnn_engine_t user_mem_engine; mkldnn_memory_get_engine(*user_memory, &user_mem_engine); if (!mkldnn_memory_desc_equal(user_memory_md, prim_memory_md)) { CHECK(mkldnn_memory_create(prim_memory, prim_memory_md, prim_engine, MKLDNN_MEMORY_ALLOCATE)); mkldnn_primitive_desc_t reorder_pd; if (dir_is_user_to_prim) { CHECK(mkldnn_reorder_primitive_desc_create(&reorder_pd, user_memory_md, user_mem_engine, prim_memory_md, prim_engine, NULL)); } else { CHECK(mkldnn_reorder_primitive_desc_create(&reorder_pd, prim_memory_md, prim_engine, user_memory_md, user_mem_engine, NULL)); } CHECK(mkldnn_primitive_create(reorder, reorder_pd)); CHECK(mkldnn_primitive_desc_destroy(reorder_pd)); net[*net_index] = *reorder; prepare_arg_node(&net_args[*net_index], 2); set_arg(&net_args[*net_index].args[0], MKLDNN_ARG_FROM, dir_is_user_to_prim ? *user_memory : *prim_memory); set_arg(&net_args[*net_index].args[1], MKLDNN_ARG_TO, dir_is_user_to_prim ? *prim_memory : *user_memory); (*net_index)++; } else { *prim_memory = NULL; *reorder = NULL; } return mkldnn_success; } mkldnn_status_t simple_net() { mkldnn_engine_t engine; CHECK(mkldnn_engine_create(&engine, mkldnn_cpu, 0)); // idx // build a simple net uint32_t n_fwd = 0, n_bwd = 0; mkldnn_primitive_t net_fwd[10], net_bwd[10]; args_t net_fwd_args[10], net_bwd_args[10]; mkldnn_dim_t net_src_sizes[4] = { BATCH, IC, CONV_IH, CONV_IW }; mkldnn_dim_t net_dst_sizes[4] = { BATCH, OC, POOL_OH, POOL_OW }; float *net_src = (float *)malloc(product(net_src_sizes, 4) * sizeof(float)); float *net_dst = (float *)malloc(product(net_dst_sizes, 4) * sizeof(float)); init_net_data(net_src, 4, net_src_sizes); memset(net_dst, 0, product(net_dst_sizes, 4) * sizeof(float)); //---------------------------------------------------------------------- //----------------- Forward Stream ------------------------------------- // AlexNet: conv // {BATCH, IC, CONV_IH, CONV_IW} (x) {OC, IC, 11, 11} -> // {BATCH, OC, CONV_OH, CONV_OW} // strides: {CONV_STRIDE, CONV_STRIDE} mkldnn_dim_t *conv_user_src_sizes = net_src_sizes; mkldnn_dim_t conv_user_weights_sizes[4] = { OC, IC, 11, 11 }; mkldnn_dim_t conv_bias_sizes[4] = { OC }; mkldnn_dim_t conv_user_dst_sizes[4] = { BATCH, OC, CONV_OH, CONV_OW }; mkldnn_dim_t conv_strides[2] = { CONV_STRIDE, CONV_STRIDE }; mkldnn_dim_t conv_padding[2] = { CONV_PAD, CONV_PAD }; float *conv_src = net_src; float *conv_weights = (float *)malloc( product(conv_user_weights_sizes, 4) * sizeof(float)); float *conv_bias = (float *)malloc(product(conv_bias_sizes, 1) * sizeof(float)); init_net_data(conv_weights, 4, conv_user_weights_sizes); init_net_data(conv_bias, 1, conv_bias_sizes); // create memory for user data mkldnn_memory_t conv_user_src_memory, conv_user_weights_memory, conv_user_bias_memory; init_data_memory(4, conv_user_src_sizes, mkldnn_nchw, mkldnn_f32, engine, conv_src, &conv_user_src_memory); init_data_memory(4, conv_user_weights_sizes, mkldnn_oihw, mkldnn_f32, engine, conv_weights, &conv_user_weights_memory); init_data_memory(1, conv_bias_sizes, mkldnn_x, mkldnn_f32, engine, conv_bias, &conv_user_bias_memory); // create a convolution mkldnn_primitive_desc_t conv_pd; { // create data descriptors for convolution w/ no specified format mkldnn_memory_desc_t conv_src_md, conv_weights_md, conv_bias_md, conv_dst_md; CHECK(mkldnn_memory_desc_init_by_tag(&conv_src_md, 4, conv_user_src_sizes, mkldnn_f32, mkldnn_format_tag_any)); CHECK(mkldnn_memory_desc_init_by_tag(&conv_weights_md, 4, conv_user_weights_sizes, mkldnn_f32, mkldnn_format_tag_any)); CHECK(mkldnn_memory_desc_init_by_tag( &conv_bias_md, 1, conv_bias_sizes, mkldnn_f32, mkldnn_x)); CHECK(mkldnn_memory_desc_init_by_tag(&conv_dst_md, 4, conv_user_dst_sizes, mkldnn_f32, mkldnn_format_tag_any)); mkldnn_convolution_desc_t conv_any_desc; CHECK(mkldnn_convolution_forward_desc_init(&conv_any_desc, mkldnn_forward, mkldnn_convolution_direct, &conv_src_md, &conv_weights_md, &conv_bias_md, &conv_dst_md, conv_strides, conv_padding, conv_padding)); CHECK(mkldnn_primitive_desc_create( &conv_pd, &conv_any_desc, NULL, engine, NULL)); } mkldnn_memory_t conv_internal_src_memory, conv_internal_weights_memory, conv_internal_dst_memory; // create memory for dst data, we don't need to reorder it to user data const mkldnn_memory_desc_t *conv_dst_md = mkldnn_primitive_desc_query_md(conv_pd, mkldnn_query_dst_md, 0); CHECK(mkldnn_memory_create(&conv_internal_dst_memory, conv_dst_md, engine, MKLDNN_MEMORY_ALLOCATE)); // create reorder primitives between user data and convolution srcs // if required mkldnn_primitive_t conv_reorder_src, conv_reorder_weights; const mkldnn_memory_desc_t *conv_src_md = mkldnn_primitive_desc_query_md(conv_pd, mkldnn_query_src_md, 0); CHECK(prepare_reorder(&conv_user_src_memory, conv_src_md, engine, 1, &conv_internal_src_memory, &conv_reorder_src, &n_fwd, net_fwd, net_fwd_args)); const mkldnn_memory_desc_t *conv_weights_md = mkldnn_primitive_desc_query_md( conv_pd, mkldnn_query_weights_md, 0); CHECK(prepare_reorder(&conv_user_weights_memory, conv_weights_md, engine, 1, &conv_internal_weights_memory, &conv_reorder_weights, &n_fwd, net_fwd, net_fwd_args)); mkldnn_memory_t conv_src_memory = conv_internal_src_memory ? conv_internal_src_memory : conv_user_src_memory; mkldnn_memory_t conv_weights_memory = conv_internal_weights_memory ? conv_internal_weights_memory : conv_user_weights_memory; // finally create a convolution primitive mkldnn_primitive_t conv; CHECK(mkldnn_primitive_create(&conv, conv_pd)); net_fwd[n_fwd] = conv; prepare_arg_node(&net_fwd_args[n_fwd], 4); set_arg(&net_fwd_args[n_fwd].args[0], MKLDNN_ARG_SRC, conv_src_memory); set_arg(&net_fwd_args[n_fwd].args[1], MKLDNN_ARG_WEIGHTS, conv_weights_memory); set_arg(&net_fwd_args[n_fwd].args[2], MKLDNN_ARG_BIAS, conv_user_bias_memory); set_arg(&net_fwd_args[n_fwd].args[3], MKLDNN_ARG_DST, conv_internal_dst_memory); n_fwd++; // AlexNet: relu // {BATCH, OC, CONV_OH, CONV_OW} -> {BATCH, OC, CONV_OH, CONV_OW} float negative_slope = 1.0f; // keep memory format of source same as the format of convolution // output in order to avoid reorder const mkldnn_memory_desc_t *relu_src_md = conv_dst_md; // create a relu primitive descriptor mkldnn_eltwise_desc_t relu_desc; CHECK(mkldnn_eltwise_forward_desc_init(&relu_desc, mkldnn_forward, mkldnn_eltwise_relu, relu_src_md, negative_slope, 0)); mkldnn_primitive_desc_t relu_pd; CHECK(mkldnn_primitive_desc_create( &relu_pd, &relu_desc, NULL, engine, NULL)); // create relu dst memory mkldnn_memory_t relu_dst_memory; const mkldnn_memory_desc_t *relu_dst_md = mkldnn_primitive_desc_query_md(relu_pd, mkldnn_query_dst_md, 0); CHECK(mkldnn_memory_create(&relu_dst_memory, relu_dst_md, engine, MKLDNN_MEMORY_ALLOCATE)); // finally create a relu primitive mkldnn_primitive_t relu; CHECK(mkldnn_primitive_create(&relu, relu_pd)); net_fwd[n_fwd] = relu; prepare_arg_node(&net_fwd_args[n_fwd], 2); set_arg(&net_fwd_args[n_fwd].args[0], MKLDNN_ARG_SRC, conv_internal_dst_memory); set_arg(&net_fwd_args[n_fwd].args[1], MKLDNN_ARG_DST, relu_dst_memory); n_fwd++; // AlexNet: lrn // {BATCH, OC, CONV_OH, CONV_OW} -> {BATCH, OC, CONV_OH, CONV_OW} // local size: 5 // alpha: 0.0001 // beta: 0.75 // k: 1.0 uint32_t local_size = 5; float alpha = 0.0001f; float beta = 0.75f; float k = 1.0f; // create lrn src memory descriptor using dst memory descriptor // from previous primitive const mkldnn_memory_desc_t *lrn_src_md = relu_dst_md; // create a lrn primitive descriptor mkldnn_lrn_desc_t lrn_desc; CHECK(mkldnn_lrn_forward_desc_init(&lrn_desc, mkldnn_forward, mkldnn_lrn_across_channels, lrn_src_md, local_size, alpha, beta, k)); mkldnn_primitive_desc_t lrn_pd; CHECK(mkldnn_primitive_desc_create(&lrn_pd, &lrn_desc, NULL, engine, NULL)); // create primitives for lrn dst and workspace memory mkldnn_memory_t lrn_dst_memory, lrn_ws_memory; const mkldnn_memory_desc_t *lrn_dst_md = mkldnn_primitive_desc_query_md(lrn_pd, mkldnn_query_dst_md, 0); CHECK(mkldnn_memory_create(&lrn_dst_memory, lrn_dst_md, engine, MKLDNN_MEMORY_ALLOCATE)); // create workspace only in training and only for forward primitive // query lrn_pd for workspace, this memory will be shared with forward lrn const mkldnn_memory_desc_t *lrn_ws_md = mkldnn_primitive_desc_query_md( lrn_pd, mkldnn_query_workspace_md, 0); CHECK(mkldnn_memory_create( &lrn_ws_memory, lrn_ws_md, engine, MKLDNN_MEMORY_ALLOCATE)); // finally create a lrn primitive mkldnn_primitive_t lrn; CHECK(mkldnn_primitive_create(&lrn, lrn_pd)); net_fwd[n_fwd] = lrn; prepare_arg_node(&net_fwd_args[n_fwd], 3); set_arg(&net_fwd_args[n_fwd].args[0], MKLDNN_ARG_SRC, relu_dst_memory); set_arg(&net_fwd_args[n_fwd].args[1], MKLDNN_ARG_DST, lrn_dst_memory); set_arg(&net_fwd_args[n_fwd].args[2], MKLDNN_ARG_WORKSPACE, lrn_ws_memory); n_fwd++; // AlexNet: pool // {BATCH, OC, CONV_OH, CONV_OW} -> {BATCH, OC, POOL_OH, POOL_OW} // kernel: {3, 3} // strides: {POOL_STRIDE, POOL_STRIDE} mkldnn_dim_t *pool_dst_sizes = net_dst_sizes; mkldnn_dim_t pool_kernel[2] = { 3, 3 }; mkldnn_dim_t pool_strides[2] = { POOL_STRIDE, POOL_STRIDE }; mkldnn_dim_t pool_padding[2] = { POOL_PAD, POOL_PAD }; // create memory for user dst data mkldnn_memory_t pool_user_dst_memory; init_data_memory(4, pool_dst_sizes, mkldnn_nchw, mkldnn_f32, engine, net_dst, &pool_user_dst_memory); // create a pooling primitive descriptor mkldnn_primitive_desc_t pool_pd; { // create pooling src memory descriptor using dst descriptor // from previous primitive const mkldnn_memory_desc_t *pool_src_md = lrn_dst_md; // create descriptors for dst pooling data mkldnn_memory_desc_t pool_dst_md; CHECK(mkldnn_memory_desc_init_by_tag(&pool_dst_md, 4, pool_dst_sizes, mkldnn_f32, mkldnn_format_tag_any)); mkldnn_pooling_desc_t pool_desc; CHECK(mkldnn_pooling_forward_desc_init(&pool_desc, mkldnn_forward, mkldnn_pooling_max, pool_src_md, &pool_dst_md, pool_strides, pool_kernel, pool_padding, pool_padding)); CHECK(mkldnn_primitive_desc_create( &pool_pd, &pool_desc, NULL, engine, NULL)); } // create memory for workspace mkldnn_memory_t pool_ws_memory; const mkldnn_memory_desc_t *pool_ws_md = mkldnn_primitive_desc_query_md( pool_pd, mkldnn_query_workspace_md, 0); CHECK(mkldnn_memory_create(&pool_ws_memory, pool_ws_md, engine, MKLDNN_MEMORY_ALLOCATE)); // create reorder primitives between pooling dsts and user format dst // if required mkldnn_primitive_t pool_reorder_dst; mkldnn_memory_t pool_internal_dst_memory; const mkldnn_memory_desc_t *pool_dst_md = mkldnn_primitive_desc_query_md(pool_pd, mkldnn_query_dst_md, 0); n_fwd += 1; // tentative workaround: preserve space for pooling that should // happen before the reorder CHECK(prepare_reorder(&pool_user_dst_memory, pool_dst_md, engine, 0, &pool_internal_dst_memory, &pool_reorder_dst, &n_fwd, net_fwd, net_fwd_args)); n_fwd -= pool_reorder_dst ? 2 : 1; mkldnn_memory_t pool_dst_memory = pool_internal_dst_memory ? pool_internal_dst_memory : pool_user_dst_memory; // finally create a pooling primitive mkldnn_primitive_t pool; CHECK(mkldnn_primitive_create(&pool, pool_pd)); net_fwd[n_fwd] = pool; prepare_arg_node(&net_fwd_args[n_fwd], 3); set_arg(&net_fwd_args[n_fwd].args[0], MKLDNN_ARG_SRC, lrn_dst_memory); set_arg(&net_fwd_args[n_fwd].args[1], MKLDNN_ARG_DST, pool_dst_memory); set_arg(&net_fwd_args[n_fwd].args[2], MKLDNN_ARG_WORKSPACE, pool_ws_memory); n_fwd++; if (pool_reorder_dst) n_fwd += 1; //----------------------------------------------------------------------- //----------------- Backward Stream ------------------------------------- //----------------------------------------------------------------------- // ... user diff_data ... float *net_diff_dst = (float *)malloc(product(pool_dst_sizes, 4) * sizeof(float)); init_net_data(net_diff_dst, 4, pool_dst_sizes); // create memory for user diff dst data mkldnn_memory_t pool_user_diff_dst_memory; init_data_memory(4, pool_dst_sizes, mkldnn_nchw, mkldnn_f32, engine, net_diff_dst, &pool_user_diff_dst_memory); // Pooling Backward // pooling diff src memory descriptor const mkldnn_memory_desc_t *pool_diff_src_md = lrn_dst_md; // pooling diff dst memory descriptor const mkldnn_memory_desc_t *pool_diff_dst_md = pool_dst_md; // create backward pooling descriptor mkldnn_pooling_desc_t pool_bwd_desc; CHECK(mkldnn_pooling_backward_desc_init(&pool_bwd_desc, mkldnn_pooling_max, pool_diff_src_md, pool_diff_dst_md, pool_strides, pool_kernel, pool_padding, pool_padding)); // backward primitive descriptor needs to hint forward descriptor mkldnn_primitive_desc_t pool_bwd_pd; CHECK(mkldnn_primitive_desc_create( &pool_bwd_pd, &pool_bwd_desc, NULL, engine, pool_pd)); // create reorder primitive between user diff dst and pool diff dst // if required mkldnn_memory_t pool_diff_dst_memory, pool_internal_diff_dst_memory; mkldnn_primitive_t pool_reorder_diff_dst; CHECK(prepare_reorder(&pool_user_diff_dst_memory, pool_diff_dst_md, engine, 1, &pool_internal_diff_dst_memory, &pool_reorder_diff_dst, &n_bwd, net_bwd, net_bwd_args)); pool_diff_dst_memory = pool_internal_diff_dst_memory ? pool_internal_diff_dst_memory : pool_user_diff_dst_memory; // create memory for pool diff src data mkldnn_memory_t pool_diff_src_memory; CHECK(mkldnn_memory_create(&pool_diff_src_memory, pool_diff_src_md, engine, MKLDNN_MEMORY_ALLOCATE)); // finally create backward pooling primitive mkldnn_primitive_t pool_bwd; CHECK(mkldnn_primitive_create(&pool_bwd, pool_bwd_pd)); net_bwd[n_bwd] = pool_bwd; prepare_arg_node(&net_bwd_args[n_bwd], 3); set_arg(&net_bwd_args[n_bwd].args[0], MKLDNN_ARG_DIFF_DST, pool_diff_dst_memory); set_arg(&net_bwd_args[n_bwd].args[1], MKLDNN_ARG_WORKSPACE, pool_ws_memory); set_arg(&net_bwd_args[n_bwd].args[2], MKLDNN_ARG_DIFF_SRC, pool_diff_src_memory); n_bwd++; // Backward lrn const mkldnn_memory_desc_t *lrn_diff_dst_md = pool_diff_src_md; // create backward lrn descriptor mkldnn_lrn_desc_t lrn_bwd_desc; CHECK(mkldnn_lrn_backward_desc_init(&lrn_bwd_desc, mkldnn_lrn_across_channels, lrn_src_md, lrn_diff_dst_md, local_size, alpha, beta, k)); mkldnn_primitive_desc_t lrn_bwd_pd; CHECK(mkldnn_primitive_desc_create( &lrn_bwd_pd, &lrn_bwd_desc, NULL, engine, lrn_pd)); // create memory for lrn diff src mkldnn_memory_t lrn_diff_src_memory; const mkldnn_memory_desc_t *lrn_diff_src_md = mkldnn_primitive_desc_query_md( lrn_bwd_pd, mkldnn_query_diff_src_md, 0); CHECK(mkldnn_memory_create(&lrn_diff_src_memory, lrn_diff_src_md, engine, MKLDNN_MEMORY_ALLOCATE)); // finally create backward lrn primitive mkldnn_primitive_t lrn_bwd; CHECK(mkldnn_primitive_create(&lrn_bwd, lrn_bwd_pd)); net_bwd[n_bwd] = lrn_bwd; prepare_arg_node(&net_bwd_args[n_bwd], 4); set_arg(&net_bwd_args[n_bwd].args[0], MKLDNN_ARG_SRC, relu_dst_memory); set_arg(&net_bwd_args[n_bwd].args[1], MKLDNN_ARG_DIFF_DST, pool_diff_src_memory); set_arg(&net_bwd_args[n_bwd].args[2], MKLDNN_ARG_WORKSPACE, lrn_ws_memory); set_arg(&net_bwd_args[n_bwd].args[3], MKLDNN_ARG_DIFF_SRC, lrn_diff_src_memory); n_bwd++; // Backward relu const mkldnn_memory_desc_t *relu_diff_dst_md = lrn_diff_src_md; // create backward relu descriptor mkldnn_eltwise_desc_t relu_bwd_desc; CHECK(mkldnn_eltwise_backward_desc_init(&relu_bwd_desc, mkldnn_eltwise_relu, relu_diff_dst_md, relu_src_md, negative_slope, 0)); mkldnn_primitive_desc_t relu_bwd_pd; CHECK(mkldnn_primitive_desc_create( &relu_bwd_pd, &relu_bwd_desc, NULL, engine, relu_pd)); // create memory for relu diff src mkldnn_memory_t relu_diff_src_memory; const mkldnn_memory_desc_t *relu_diff_src_md = mkldnn_primitive_desc_query_md( relu_bwd_pd, mkldnn_query_diff_src_md, 0); CHECK(mkldnn_memory_create(&relu_diff_src_memory, relu_diff_src_md, engine, MKLDNN_MEMORY_ALLOCATE)); // finally create backward relu primitive mkldnn_primitive_t relu_bwd; CHECK(mkldnn_primitive_create(&relu_bwd, relu_bwd_pd)); net_bwd[n_bwd] = relu_bwd; prepare_arg_node(&net_bwd_args[n_bwd], 3); set_arg(&net_bwd_args[n_bwd].args[0], MKLDNN_ARG_SRC, conv_internal_dst_memory); set_arg(&net_bwd_args[n_bwd].args[1], MKLDNN_ARG_DIFF_DST, lrn_diff_src_memory); set_arg(&net_bwd_args[n_bwd].args[2], MKLDNN_ARG_DIFF_SRC, relu_diff_src_memory); n_bwd++; // Backward convolution with respect to weights float *conv_diff_bias_buffer = (float *)malloc(product(conv_bias_sizes, 1) * sizeof(float)); float *conv_user_diff_weights_buffer = (float *)malloc( product(conv_user_weights_sizes, 4) * sizeof(float)); // initialize memory for diff weights in user format mkldnn_memory_t conv_user_diff_weights_memory; init_data_memory(4, conv_user_weights_sizes, mkldnn_oihw, mkldnn_f32, engine, conv_user_diff_weights_buffer, &conv_user_diff_weights_memory); // create backward convolution primitive descriptor mkldnn_primitive_desc_t conv_bwd_weights_pd; { // memory descriptors should be in format `any` to allow backward // convolution for // weights to chose the format it prefers for best performance mkldnn_memory_desc_t conv_diff_src_md, conv_diff_weights_md, conv_diff_bias_md, conv_diff_dst_md; CHECK(mkldnn_memory_desc_init_by_tag(&conv_diff_src_md, 4, conv_user_src_sizes, mkldnn_f32, mkldnn_format_tag_any)); CHECK(mkldnn_memory_desc_init_by_tag(&conv_diff_weights_md, 4, conv_user_weights_sizes, mkldnn_f32, mkldnn_format_tag_any)); CHECK(mkldnn_memory_desc_init_by_tag( &conv_diff_bias_md, 1, conv_bias_sizes, mkldnn_f32, mkldnn_x)); CHECK(mkldnn_memory_desc_init_by_tag(&conv_diff_dst_md, 4, conv_user_dst_sizes, mkldnn_f32, mkldnn_format_tag_any)); // create backward convolution descriptor mkldnn_convolution_desc_t conv_bwd_weights_desc; CHECK(mkldnn_convolution_backward_weights_desc_init( &conv_bwd_weights_desc, mkldnn_convolution_direct, &conv_diff_src_md, &conv_diff_weights_md, &conv_diff_bias_md, &conv_diff_dst_md, conv_strides, conv_padding, conv_padding)); CHECK(mkldnn_primitive_desc_create(&conv_bwd_weights_pd, &conv_bwd_weights_desc, NULL, engine, conv_pd)); } // for best performance convolution backward might chose // different memory format for src and diff_dst // than the memory formats preferred by forward convolution // for src and dst respectively // create reorder primitives for src from forward convolution to the // format chosen by backward convolution mkldnn_primitive_t conv_bwd_reorder_src; mkldnn_memory_t conv_bwd_internal_src_memory; const mkldnn_memory_desc_t *conv_diff_src_md = mkldnn_primitive_desc_query_md( conv_bwd_weights_pd, mkldnn_query_src_md, 0); CHECK(prepare_reorder(&conv_src_memory, conv_diff_src_md, engine, 1, &conv_bwd_internal_src_memory, &conv_bwd_reorder_src, &n_bwd, net_bwd, net_bwd_args)); mkldnn_memory_t conv_bwd_weights_src_memory = conv_bwd_internal_src_memory ? conv_bwd_internal_src_memory : conv_src_memory; // create reorder primitives for diff_dst between diff_src from relu_bwd // and format preferred by conv_diff_weights mkldnn_primitive_t conv_reorder_diff_dst; mkldnn_memory_t conv_internal_diff_dst_memory; const mkldnn_memory_desc_t *conv_diff_dst_md = mkldnn_primitive_desc_query_md( conv_bwd_weights_pd, mkldnn_query_diff_dst_md, 0); CHECK(prepare_reorder(&relu_diff_src_memory, conv_diff_dst_md, engine, 1, &conv_internal_diff_dst_memory, &conv_reorder_diff_dst, &n_bwd, net_bwd, net_bwd_args)); mkldnn_memory_t conv_diff_dst_memory = conv_internal_diff_dst_memory ? conv_internal_diff_dst_memory : relu_diff_src_memory; // create reorder primitives for conv diff weights memory mkldnn_primitive_t conv_reorder_diff_weights; mkldnn_memory_t conv_internal_diff_weights_memory; const mkldnn_memory_desc_t *conv_diff_weights_md = mkldnn_primitive_desc_query_md( conv_bwd_weights_pd, mkldnn_query_diff_weights_md, 0); n_bwd += 1; // tentative workaround: preserve space for conv_bwd_weights // that should happen before the reorder CHECK(prepare_reorder(&conv_user_diff_weights_memory, conv_diff_weights_md, engine, 0, &conv_internal_diff_weights_memory, &conv_reorder_diff_weights, &n_bwd, net_bwd, net_bwd_args)); n_bwd -= conv_reorder_diff_weights ? 2 : 1; mkldnn_memory_t conv_diff_weights_memory = conv_internal_diff_weights_memory ? conv_internal_diff_weights_memory : conv_user_diff_weights_memory; // create memory for diff bias memory mkldnn_memory_t conv_diff_bias_memory; const mkldnn_memory_desc_t *conv_diff_bias_md = mkldnn_primitive_desc_query_md( conv_bwd_weights_pd, mkldnn_query_diff_weights_md, 1); CHECK(mkldnn_memory_create( &conv_diff_bias_memory, conv_diff_bias_md, engine, NULL)); CHECK(mkldnn_memory_set_data_handle( conv_diff_bias_memory, conv_diff_bias_buffer)); // finally created backward convolution weights primitive mkldnn_primitive_t conv_bwd_weights; CHECK(mkldnn_primitive_create(&conv_bwd_weights, conv_bwd_weights_pd)); net_bwd[n_bwd] = conv_bwd_weights; prepare_arg_node(&net_bwd_args[n_bwd], 4); set_arg(&net_bwd_args[n_bwd].args[0], MKLDNN_ARG_SRC, conv_bwd_weights_src_memory); set_arg(&net_bwd_args[n_bwd].args[1], MKLDNN_ARG_DIFF_DST, conv_diff_dst_memory); set_arg(&net_bwd_args[n_bwd].args[2], MKLDNN_ARG_DIFF_WEIGHTS, conv_diff_weights_memory); set_arg(&net_bwd_args[n_bwd].args[3], MKLDNN_ARG_DIFF_BIAS, conv_diff_bias_memory); n_bwd++; if (conv_reorder_diff_weights) n_bwd += 1; // output from backward stream void *net_diff_weights = NULL; void *net_diff_bias = NULL; int n_iter = 10; // number of iterations for training. mkldnn_stream_t stream; CHECK(mkldnn_stream_create(&stream, engine, mkldnn_stream_default_flags)); // Execute the net for (int i = 0; i < n_iter; i++) { for (uint32_t i = 0; i < n_fwd; ++i) CHECK(mkldnn_primitive_execute(net_fwd[i], stream, net_fwd_args[i].nargs, net_fwd_args[i].args)); // Update net_diff_dst void *net_output = NULL; // output from forward stream: CHECK(mkldnn_memory_get_data_handle(pool_user_dst_memory, &net_output)); // ...user updates net_diff_dst using net_output... // some user defined func update_diff_dst(net_diff_dst, net_output) // Backward pass for (uint32_t i = 0; i < n_bwd; ++i) CHECK(mkldnn_primitive_execute(net_bwd[i], stream, net_bwd_args[i].nargs, net_bwd_args[i].args)); // ... update weights ... CHECK(mkldnn_memory_get_data_handle( conv_user_diff_weights_memory, &net_diff_weights)); CHECK(mkldnn_memory_get_data_handle( conv_diff_bias_memory, &net_diff_bias)); // ...user updates weights and bias using diff weights and bias... // some user defined func update_weights(conv_user_weights_memory, // conv_bias_memory, // net_diff_weights, net_diff_bias); } CHECK(mkldnn_stream_wait(stream)); mkldnn_stream_destroy(stream); // clean up nets for (uint32_t i = 0; i < n_fwd; ++i) free_arg_node(&net_fwd_args[i]); for (uint32_t i = 0; i < n_bwd; ++i) free_arg_node(&net_bwd_args[i]); // Cleanup forward CHECK(mkldnn_primitive_desc_destroy(pool_pd)); CHECK(mkldnn_primitive_desc_destroy(lrn_pd)); CHECK(mkldnn_primitive_desc_destroy(relu_pd)); CHECK(mkldnn_primitive_desc_destroy(conv_pd)); free(net_src); free(net_dst); mkldnn_memory_destroy(conv_user_src_memory); mkldnn_memory_destroy(conv_user_weights_memory); mkldnn_memory_destroy(conv_user_bias_memory); mkldnn_memory_destroy(conv_internal_src_memory); mkldnn_memory_destroy(conv_internal_weights_memory); mkldnn_memory_destroy(conv_internal_dst_memory); mkldnn_primitive_destroy(conv_reorder_src); mkldnn_primitive_destroy(conv_reorder_weights); mkldnn_primitive_destroy(conv); free(conv_weights); free(conv_bias); mkldnn_memory_destroy(relu_dst_memory); mkldnn_primitive_destroy(relu); mkldnn_memory_destroy(lrn_ws_memory); mkldnn_memory_destroy(lrn_dst_memory); mkldnn_primitive_destroy(lrn); mkldnn_memory_destroy(pool_user_dst_memory); mkldnn_memory_destroy(pool_internal_dst_memory); mkldnn_memory_destroy(pool_ws_memory); mkldnn_primitive_destroy(pool_reorder_dst); mkldnn_primitive_destroy(pool); // Cleanup backward CHECK(mkldnn_primitive_desc_destroy(pool_bwd_pd)); CHECK(mkldnn_primitive_desc_destroy(lrn_bwd_pd)); CHECK(mkldnn_primitive_desc_destroy(relu_bwd_pd)); CHECK(mkldnn_primitive_desc_destroy(conv_bwd_weights_pd)); mkldnn_memory_destroy(pool_user_diff_dst_memory); mkldnn_memory_destroy(pool_diff_src_memory); mkldnn_memory_destroy(pool_internal_diff_dst_memory); mkldnn_primitive_destroy(pool_reorder_diff_dst); mkldnn_primitive_destroy(pool_bwd); free(net_diff_dst); mkldnn_memory_destroy(lrn_diff_src_memory); mkldnn_primitive_destroy(lrn_bwd); mkldnn_memory_destroy(relu_diff_src_memory); mkldnn_primitive_destroy(relu_bwd); mkldnn_memory_destroy(conv_user_diff_weights_memory); mkldnn_memory_destroy(conv_diff_bias_memory); mkldnn_memory_destroy(conv_bwd_internal_src_memory); mkldnn_primitive_destroy(conv_bwd_reorder_src); mkldnn_memory_destroy(conv_internal_diff_dst_memory); mkldnn_primitive_destroy(conv_reorder_diff_dst); mkldnn_memory_destroy(conv_internal_diff_weights_memory); mkldnn_primitive_destroy(conv_reorder_diff_weights); mkldnn_primitive_destroy(conv_bwd_weights); free(conv_diff_bias_buffer); free(conv_user_diff_weights_buffer); mkldnn_engine_destroy(engine); return mkldnn_success; } int main(int argc, char **argv) { mkldnn_status_t result = simple_net(); printf("%s\n", (result == mkldnn_success) ? "passed" : "failed"); return result; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/examples/cpu_performance_profiling.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /// @example cpu_performance_profiling.cpp /// This example demonstrates the best practices for application performance /// optimizations with Intel MKL-DNN. /// /// > Annotated version: @ref cpu_performance_profiling_cpp #include <iostream> #include <string> #include <chrono> #include <stdio.h> /// @page cpu_performance_profiling_cpp Performance Profiling Example /// > Example code: @ref cpu_performance_profiling.cpp /// /// This example uses [MKLDNN_VERBOSE](@ref dev_guide_verbose) trace output /// to tune Intel MKL-DNN code to align /// with the [best practices](@ref dev_guide_inference). /// /// It will assume knowledge of memory formats and their usage in /// Intel MKL-DNN. You can read more about this topic /// [here](@ref cpu_memory_format_propagation_cpp). /// /// The example has three different implementations of the mathematical /// operation: /// 1. *Naive implementation* executes 2D convolution followed by /// ReLU on the data in **NCHW** format. This implementation /// does not align with Intel MKL-DNN best practices and results in /// suboptimal performance. /// 2. *Blocked format implementation* executes the same operations /// sequence on the **blocked format** optimized for convolution /// performance. This implementation uses `format_tag=ANY` to create a /// convolution memory descriptor to determine the data format optimal /// for the convolution implementation. It then **propagates the blocked /// format** to the non-intensive ReLU. This implementation results /// in better overall performance than the naive implementation. /// 3. *Fused implementation* executes convolution fused with ReLU on /// blocked data format. This implementation uses /// `format_tag=ANY` to create a convolution memory descriptor, and then /// adds ReLU as a **post-op** to the convolution primitive. This version /// implements all of the best practices for inference resulting in the /// best overall performance. /// /// @section cpu_performance_profiling_cpp_walkthrough Walkthrough /// /// The program in \ref cpu_performance_profiling.cpp includes all three /// implementations introduced above. You can select the specific implementation /// using command line options. /// /// After compilation, you can execute each implementation with: /// ~~~sh /// ./program.exe implementation /// ~~~ /// /// Before you run the program, set your `MKLDNN_VERBOSE` environment /// variable to 1: /// ~~~sh /// export MKLDNN_VERBOSE=1 /// ~~~ /// /// The program starts by creating Intel MKL-DNN memory objects in **NCHW** /// format. These are called `user_` because they are meant to represent the /// user's source data entering Intel MKL-DNN with the NCHW format. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Set dimensions /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create memory objects /// @page cpu_performance_profiling_cpp /// @note You can change the batch size to easily increase/decrease the workload. /// /// The following descriptions of each implementation will reference each other, /// and are meant to be read in order. /// // [Prologue] #include "mkldnn.hpp" using namespace mkldnn; // Set Strides and Padding const memory::dims strides = {4, 4}; const memory::dims padding = {0, 0}; // Initialize engine engine cpu(engine::kind::cpu, 0); // Initialize stream stream s(cpu); // [Prologue] // function to init data void init_data(memory &m, float v) { auto data = (float *)m.get_data_handle(); auto size = m.get_desc().get_size() / sizeof(*data); for (size_t i = 0; i < size; ++i) data[i] = v; } // function to execute non-fused relu void create_and_execute_relu(memory data) { // relu operates on whatever data format is given to it // create a primitive auto relu_d = eltwise_forward::desc( prop_kind::forward_inference, algorithm::eltwise_relu, data.get_desc(), 0.f, 0.f); auto relu_pd = eltwise_forward::primitive_desc(relu_d, cpu); auto relu = eltwise_forward(relu_pd); // execute it (in-place) relu.execute(s, { {MKLDNN_ARG_SRC, data}, {MKLDNN_ARG_DST, data}}); } // [Create post_op attr with relu] // function to create post-op attribute for fused relu primitive_attr create_attr_with_relu_post_op() { // create a post-op with relu post_ops ops; ops.append_eltwise(1.f, algorithm::eltwise_relu, 0.f, 0.f); // create an attribute and set the corresponding post op primitive_attr attr; attr.set_post_ops(ops); return attr; } // [Create post_op attr with relu] // Implementation for naive convolution on nchw (data) and oihw (weights), // followed by execution of non-fused relu void conv_relu_naive(memory user_src, memory user_wei, memory user_dst) { /// @section cpu_performance_profiling_cpp_implementation1 Naive Implementation /// This implementation is launched with the following shell code: /// ~~~sh /// ./program.exe naive /// ~~~ /// The program will call the implementation defined in the function /// `conv_relu_naive()`. /// /// First it sets the dimensions and format for convolution memory /// descriptors (`_md`) to match `user_` values--one `md` each for source, /// destination, and weight data. Then it uses those `md` to create the /// convolution descriptor `conv_d`, which tells Intel MKL-DNN to use /// plain format (NCHW) for the convolution. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create mem_desc // [Create mem_desc] // copy the dimensions and format from user's memory auto conv_src_md = memory::desc(user_src.get_desc()); auto conv_wei_md = memory::desc(user_wei.get_desc()); auto conv_dst_md = memory::desc(user_dst.get_desc()); // [Create mem_desc] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_desc // [Create conv_desc] // create a convolution descriptor auto conv_d = convolution_forward::desc( prop_kind::forward_inference, algorithm::convolution_direct, conv_src_md, conv_wei_md, conv_dst_md, strides, padding, padding); // [Create conv_desc] /// Next the program creates a convolution primitive descriptor `conv_pd` /// and convolution primitive `conv`. These structs will inherit /// NCHW format from `md` by way of the `conv_d`. Finally it creates /// the convolution primitive `conv` and adds it to the stream `s`, and then /// executes the `create_and_execute_relu(user_dst)` function. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_prim_desc // [Create conv_prim_desc] // create a convolution primitive descriptor auto conv_pd = convolution_forward::primitive_desc(conv_d, cpu); // [Create conv_prim_desc] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_primitive // [Create conv_primitive] // create convolution primitive auto conv = convolution_forward(conv_pd); // [Create conv_primitive] // @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Add to stream // [Add to stream] // execute convolution by adding it to the stream s conv.execute(s, { {MKLDNN_ARG_SRC, user_src}, {MKLDNN_ARG_WEIGHTS, user_wei}, {MKLDNN_ARG_DST, user_dst}}); // [Add to stream] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create and execute relu // [Create and execute relu] // execute relu (on convolution's destination format, whatever it is) create_and_execute_relu(user_dst); // [Create and execute relu] /// @page cpu_performance_profiling_cpp /// @note The function for creation and execution of ReLU primitive is /// defined elsewhere to keep this example clean. It is an non-intensive /// operation, so the `create_and_execute_relu()` function uses whatever /// the input data format is at the time it is called. /// /// Using NCHW data format may result in suboptimal performance for compute /// intensives primitives, as shown in the following MKLDNN_VERBOSE output /// by the convolution and relu execution /// times of 235.9 and 100.3 milliseconds, respectively. /// /// *MKLDNN_VERBOSE output (see configuration notice\*):* /// ~~~sh /// mkldnn_verbose,exec,convolution,gemm:jit,forward_inference,src_f32:: /// blocked:abcd:f0 wei_f32::blocked:abcd:f0 dst_f32:: /// blocked:abcd:f0,alg:convolution_direct, /// mb1000_ic3oc96_ih227oh55kh11sh4dh0ph0_iw227ow55kw11sw4dw0pw0,235.86 /// mkldnn_verbose,exec,eltwise,jit:avx512_common,forward_inference, /// data_f32::blocked:abcd:f0,alg:eltwise_relu,1000x96x55x55,100.264 /// ~~~ /// In *Blocked format implementation*, we will incorporate the best /// practice of letting Intel MKL-DNN determine the optimal format /// for convolution primitive. } // Implementation for convolution on blocked format for data and // weights, followed by execution of non-fused relu void conv_relu_blocked(memory user_src, memory user_wei, memory user_dst) { /// @page cpu_performance_profiling_cpp /// @section cpu_performance_profiling_cpp_implementation2 Blocked format implementation /// This implementation is launched with the following shell code: /// ~~~sh /// ./program.exe blocked /// ~~~ /// The program will call the implementation defined in the function /// `conv_relu_blocked()`. /// /// First it creates the md as in **naive implementation**. Next it changes /// the mkldnn::memory::format_tag for each md to `ANY`. Then it uses those /// md to create the convolution descriptor conv_d, which tells Intel /// MKL-DNN to use whatever format it recommends for the convolution. /// Intel MKL-DNN will choose the CPU-friendly blocked format. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create mem_desc with tag=any // [Create mem_desc with tag=any] // copy the dimensions and format from user's memory auto conv_src_md = memory::desc(user_src.get_desc()); auto conv_wei_md = memory::desc(user_wei.get_desc()); auto conv_dst_md = memory::desc(user_dst.get_desc()); // reset format to "any" to allow convolution to pick the best implementation conv_src_md.data.format_kind = mkldnn_format_kind_any; conv_wei_md.data.format_kind = mkldnn_format_kind_any; conv_dst_md.data.format_kind = mkldnn_format_kind_any; // [Create mem_desc with tag=any] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_desc implementation2 // [Create conv_desc implementation2] // create a convolution descriptor auto conv_d = convolution_forward::desc( prop_kind::forward_inference, algorithm::convolution_direct, conv_src_md, conv_wei_md, conv_dst_md, strides, padding, padding); // [Create conv_desc implementation2] /// Next the program creates a convolution primitive descriptor conv_pd and /// convolution primitive conv as in naive implementation. /// However, in this implementation the structs will inherit blocked format /// from md by way of the conv_d. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_prim_desc implementation2 // [Create conv_prim_desc implementation2] // create a convolution primitive descriptor and primitive auto conv_pd = convolution_forward::primitive_desc(conv_d, cpu); // [Create conv_prim_desc implementation2] /// Since the resulting convolution primitive will expect /// blocked source data, conditional reorders are inserted to convert /// input data to blocked format if required. /// The input data user_src is NCHW, so this conditional will be triggered: /// /// @note The reoders are applied using Intel MKL-DNN `reorder` primitive. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Conditionally create and execute reorder prims // [Conditionally create and execute reorder prims] // prepare convolution source memory conv_src = user_src; if (conv_pd.src_desc() != user_src.get_desc()) { conv_src = memory(conv_pd.src_desc(), cpu); auto r_pd = reorder::primitive_desc(user_src, conv_src); reorder(r_pd).execute(s, user_src, conv_src); } // prepare convolution weights memory conv_wei = user_wei; if (conv_pd.weights_desc() != user_wei.get_desc()) { conv_wei = memory(conv_pd.weights_desc(), cpu); auto r_pd = reorder::primitive_desc(user_wei, conv_wei); reorder(r_pd).execute(s, user_wei, conv_wei); } // prepare convolution destination memory conv_dst = user_dst; if (conv_pd.dst_desc() != user_dst.get_desc()) conv_dst = memory(conv_pd.dst_desc(), cpu); // [Conditionally create and execute reorder prims] /// Finally it creates the convolution primitive `conv` and adds it to the /// stream `s` with the reordered data (`conv_src`, `conv_wei`, `conv_dst1`) /// as inputs and then executes the /// `create_and_execute_relu(conv_dst)` function. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_primitive implementation2 // [Create conv_primitive implementation2] // create convolution primitive auto conv = convolution_forward(conv_pd); // [Create conv_primitive implementation2] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Add to stream implementation2 // [Add to stream implementation2] // execute convolution by adding it to the stream s conv.execute(s, { {MKLDNN_ARG_SRC, conv_src}, {MKLDNN_ARG_WEIGHTS, conv_wei}, {MKLDNN_ARG_DST, conv_dst}}); // [Add to stream implementation2] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create and execute relu implementation2 // [Create and execute relu implementation2] // execute relu (on convolution's destination format, whatever it is) create_and_execute_relu(conv_dst); // [Create and execute relu implementation2] if (conv_pd.dst_desc() != user_dst.get_desc()) { auto r_pd = reorder::primitive_desc(conv_dst, user_dst); reorder(r_pd).execute(s, conv_dst, user_dst); } /// @page cpu_performance_profiling_cpp /// Blocked memory format is recommended for Intel MKL-DNN primitive /// execution and provides better performance, as shown in the /// MKLDNN_VERBOSE output by the convolution and relu execution times of /// 119.6 and 34.4 milliseconds (down from 235.9 and 100.3 in /// *naive implementation*), respectively. /// In this implementation, there is an additional reorder operation that /// executes before and after the the conv + relu. This small cost is worth /// the gain from executing in blocked format. If fact, it becomes /// negligible when chaining together multiple Intel Mkl-DNN operations in /// succession. In these situations, you can do one reorder at the beginning /// and one at the end of the chain, and only pay the reorder penalty at /// those points in the execution. /// /// *MKLDNN_VERBOSE output (see configuration notice\*):* /// ~~~sh /// mkldnn_verbose,exec,reorder,jit:uni,undef,src_f32::blocked:abcd:f0 /// dst_f32::blocked:Acdb16a:f0,num:1,96x3x11x11,3.71387 /// mkldnn_verbose,exec,convolution,jit:avx512_common,forward_inference, /// src_f32::blocked:abcd:f0 wei_f32::blocked:Acdb16a:f0 /// dst_f32::blocked:aBcd16b:f0,alg:convolution_direct, /// mb1000_ic3oc96_ih227oh55kh11sh4dh0ph0_iw227ow55kw11sw4dw0pw0,119.649 /// mkldnn_verbose,exec,eltwise,jit:avx512_common,forward_inference, /// data_f32::blocked:aBcd16b:f0,alg:eltwise_relu,1000x96x55x55,34.417 /// mkldnn_verbose,exec,reorder,jit:uni,undef,src_f32::blocked:aBcd16b:f0 /// dst_f32::blocked:abcd:f0,num:1,1000x96x55x55,97.3352 /// ~~~ /// This inference implementation is closer to best practices than /// *naive implementation* because it uses Intel MKL-DNN recommended memory /// format. *fused implementation* will futher optimize the performance by /// using a fused version of the conv + ReLU primitive emplying the Intel /// MKL-DNN [post-ops attribute](@ref dev_guide_attributes_post_ops) // reorder data to the user's format if needed. } // Implementation for convolution on blocked format for data and // weights and the relu operation fused via a post-op attribute added to the // convolution prim_descriptor void conv_relu_fused(memory user_src, memory user_wei, memory user_dst) { /// @section cpu_performance_profiling_cpp_implementation3 Fused Implementation /// This implementation is launched with the following shell code: /// ~~~sh /// ./program.exe fused /// ~~~ /// The program will call the implementation defined in the function /// `conv_relu_fused()`. /// @page cpu_performance_profiling_cpp /// /// First the memory descriptors and convolution descriptor are created as /// in *naive implementation*. // copy the dimensions and format from user's memory auto conv_src_md = memory::desc(user_src.get_desc()); auto conv_wei_md = memory::desc(user_wei.get_desc()); auto conv_dst_md = memory::desc(user_dst.get_desc()); // reset format to any to allow convolution to pick the best implementation conv_src_md.data.format_kind = mkldnn_format_kind_any; conv_wei_md.data.format_kind = mkldnn_format_kind_any; conv_dst_md.data.format_kind = mkldnn_format_kind_any; // create a convolution descriptor auto conv_d = convolution_forward::desc( prop_kind::forward_inference, algorithm::convolution_direct, conv_src_md, conv_wei_md, conv_dst_md, strides, padding, padding); /// Then in preparation for the convolution prim desctiptor, a ReLU post-op /// is built and added to the primitive attribute `attr`: /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create post_op attr with relu // Next the convolution prim descriptor is created, which inherits the ReLU /// post-op by way of the attributes `attr`: /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create prim_desc with attr // [Create prim_desc with attr] // create an attribute for fused relu auto attr = create_attr_with_relu_post_op(); // create a convolution primitive descriptor auto conv_pd = convolution_forward::primitive_desc(conv_d, attr, cpu); // [Create prim_desc with attr] /// Then conditional reorders are applied as in *blocked format /// implementation* to convert `user_` format NCHW to blocked. Finally, it /// creates the convolution primitive `conv` and adds it to the stream `s` /// with the reordered data (`conv_src`, `conv_wei`, `conv_dst1`). // prepare convolution source memory conv_src = user_src; if (conv_pd.src_desc() != user_src.get_desc()) { conv_src = memory(conv_pd.src_desc(), cpu); auto r_pd = reorder::primitive_desc(user_src, conv_src); reorder(r_pd).execute(s, user_src, conv_src); } // prepare convolution weights memory conv_wei = user_wei; if (conv_pd.weights_desc() != user_wei.get_desc()) { conv_wei = memory(conv_pd.weights_desc(), cpu); auto r_pd = reorder::primitive_desc(user_wei, conv_wei); reorder(r_pd).execute(s, user_wei, conv_wei); } // prepare convolution destination memory conv_dst = user_dst; if (conv_pd.dst_desc() != user_dst.get_desc()) conv_dst = memory(conv_pd.dst_desc(), cpu); /// @page cpu_performance_profiling_cpp /// @note There is no separate addition to the stream for the ReLU /// operation because it has been added as a post-op to the `conv` primitive. /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Create conv_primitive implementation3 // [Create conv_primitive implementation3] // create convolution primitive auto conv = convolution_forward(conv_pd); // [Create conv_primitive implementation3] /// @page cpu_performance_profiling_cpp /// @snippet cpu_performance_profiling.cpp Add to stream implementation3 // [Add to stream implementation3] // execute convolution by adding it to the stream s conv.execute(s, { {MKLDNN_ARG_SRC, conv_src}, {MKLDNN_ARG_WEIGHTS, conv_wei}, {MKLDNN_ARG_DST, conv_dst}}); // [Add to stream implementation3] // reorder data to user's format if needed if (conv_pd.dst_desc() != user_dst.get_desc()) { auto r_pd = reorder::primitive_desc(conv_dst, user_dst); reorder(r_pd).execute(s, conv_dst, user_dst); } /// @page cpu_performance_profiling_cpp /// This implementation complies with best practices for f32 inference by /// using the Intel MKL-DNN recommended blocked format for convolution and /// adding ReLU as a post-op to execute a fused version of conv + ReLU. /// The consequence to following best practices can be seen in the execution /// time of the fused primitive of 103.9 milliseconds. /// /// *MKLDNN_VERBOSE output (see configuration notice\*):* /// ~~~sh /// mkldnn_verbose,exec,convolution,jit:avx512_common,forward_inference, /// src_f32::blocked:abcd:f0 wei_f32::blocked:Acdb16a:f0 /// dst_f32::blocked:aBcd16b:f0,alg:convolution_direct, /// mb1000_ic3oc96_ih227oh55kh11sh4dh0ph0_iw227ow55kw11sw4dw0pw0,103.916 /// ~~~ } /// @page cpu_performance_profiling_cpp /// @section cpu_performance_profiling_cpp_roundup Performance summary /// /// | Implmentation | Time, ms | Cumulative speedup | /// | :-- | --: | --: | /// | Naive | 336.1 | 1.0 | /// | Blocked format | 154.0 | 2.2 | /// | Fused | 103.9 | 3.2 | /// /// ** ** /// @page cpu_performance_profiling_cpp /// @section cpu_performance_profiling_cpp_config Configuration Notice /// @note This example is meant to demonstrate Intel MKL-DNN best practices. /// @note It is not meant for benchmarking purposes. The platform is not fully /// @note optimized, so the primitive execution times are only relevant in /// @note relation to the other times in this example. /// /// Runtime Settings: /// * OMP_NUM_THREADS=14 /// * KMP_AFFINITY=granularity=fine,compact,1,0 /// /// Platform: /// * CPU: Intel(R) Xeon(R) Platinum 8180M CPU @ 2.50GHz /// * Thread(s) per core: 2 /// * Core(s) per socket: 28 /// * Socket(s): 2 /// * NUMA node(s): 2 /// * RAM (DDR4): 1.45 TB int main(int argc, char *argv[]) { // [Set dimensions] // set dimensions for synthetic data and weights const memory::dim BATCH = 1000; const memory::dim IC = 3, OC = 96; const memory::dim IH = 227, KH = 11, OH = 55; const memory::dim IW = 227, KW = 11, OW = 55; // [Set dimensions] // [Create memory objects] // create MKL-DNN memory objects for user's tensors (in nchw and oihw formats) // @note here the library allocates memory auto user_src = memory({{BATCH, IC, IH, IW}, memory::data_type::f32, memory::format_tag::nchw}, cpu); auto user_wei = memory({{OC, IC, KH, KW}, memory::data_type::f32, memory::format_tag::oihw}, cpu); auto user_dst = memory({{BATCH, OC, OH, OW}, memory::data_type::f32, memory::format_tag::nchw}, cpu); // [Create memory objects] // fill source, destination, and weights with synthetic data init_data(user_src, 1); init_data(user_dst, -1); init_data(user_wei, .5); // set implementation ("naive"||"blocked"||"fused") setting implementation // to "validation" will run all implementations std::string implementation; if (argc == 1) implementation = "validation"; else if (argc == 2) implementation = argv[1]; if (!(implementation == "validation" || implementation == "naive" || implementation == "blocked" || implementation == "fused")) { std::cout << "\nUsage: " << argv[0] << " [implementation]\n\n"; std::cout << "The implementation can be one of:\n"; std::cout << " - naive: NCHW format without fusion\n"; std::cout << " - blocked: format propagation without fusion\n"; std::cout << " - fused: format propagation with fusion\n"; std::cout << " - validation: runs all implementations\n\n"; std::cout << "Validation will be run if no parameters are specified\n\n"; return -1; } if (implementation == "naive" || implementation == "validation") { std::cout << "implementation: naive\n"; // run conv + relu w/o fusing conv_relu_naive(user_src, user_wei, user_dst); std::cout << "conv + relu w/ nchw format completed\n"; } if (implementation == "blocked" || implementation == "validation") { std::cout << "implementation: blocked\n"; // run conv + relu w/o fusing conv_relu_blocked(user_src, user_wei, user_dst); std::cout << "conv + relu w/ blocked format completed\n"; } if (implementation == "fused" || implementation == "validation") { std::cout << "implementation: fused\n"; // run conv + relu w/ fusing conv_relu_fused(user_src, user_wei, user_dst); std::cout << "conv + relu w/ fusing completed\n"; } return 0; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/examples/cpu_cnn_inference_int8.cpp<|end_filename|> /******************************************************************************* * Copyright 2018-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /// @example cpu_cnn_inference_int8.cpp /// @copybrief cpu_cnn_inference_int8_cpp /// > Annotated version: @ref cpu_cnn_inference_int8_cpp /// @page cpu_cnn_inference_int8_cpp CNN int8 inference example /// This C++ API example demonstrates how to run AlexNet's conv3 and relu3 /// with int8 data type. /// /// > Example code: @ref cpu_cnn_inference_int8.cpp #include "mkldnn.hpp" #include <iostream> #include <numeric> #include <string> using namespace mkldnn; memory::dim product(const memory::dims &dims) { return std::accumulate(dims.begin(), dims.end(), (memory::dim)1, std::multiplies<memory::dim>()); } void simple_net_int8() { using tag = memory::format_tag; using dt = memory::data_type; auto cpu_engine = engine(engine::kind::cpu, 0); stream s(cpu_engine); const int batch = 8; /// Configure tensor shapes /// @snippet cpu_cnn_inference_int8.cpp Configure tensor shapes //[Configure tensor shapes] // AlexNet: conv3 // {batch, 256, 13, 13} (x) {384, 256, 3, 3}; -> {batch, 384, 13, 13} // strides: {1, 1} memory::dims conv_src_tz = { batch, 256, 13, 13 }; memory::dims conv_weights_tz = { 384, 256, 3, 3 }; memory::dims conv_bias_tz = { 384 }; memory::dims conv_dst_tz = { batch, 384, 13, 13 }; memory::dims conv_strides = { 1, 1 }; memory::dims conv_padding = { 1, 1 }; //[Configure tensor shapes] /// Next, the example configures the scales used to quantize f32 data /// into int8. For this example, the scaling value is chosen as an /// arbitrary number, although in a realistic scenario, it should be /// calculated from a set of precomputed values as previously mentioned. /// @snippet cpu_cnn_inference_int8.cpp Choose scaling factors //[Choose scaling factors] // Choose scaling factors for input, weight, output and bias quantization const std::vector<float> src_scales = { 1.8f }; const std::vector<float> weight_scales = { 2.0f }; const std::vector<float> bias_scales = { 1.0f }; const std::vector<float> dst_scales = { 0.55f }; // Choose channel-wise scaling factors for convolution std::vector<float> conv_scales(384); const int scales_half = 384 / 2; std::fill(conv_scales.begin(), conv_scales.begin() + scales_half, 0.3f); std::fill(conv_scales.begin() + scales_half + 1, conv_scales.end(), 0.8f); //[Choose scaling factors] /// The *source, weights, bias* and *destination* datasets use the single-scale /// format with mask set to '0', while the *output* from the convolution /// (conv_scales) will use the array format where mask = 2 corresponding /// to the output dimension. /// @snippet cpu_cnn_inference_int8.cpp Set scaling mask //[Set scaling mask] const int src_mask = 0; const int weight_mask = 0; const int bias_mask = 0; const int dst_mask = 0; const int conv_mask = 2; // 1 << output_channel_dim //[Set scaling mask] // Allocate input and output buffers for user data std::vector<float> user_src(batch * 256 * 13 * 13); std::vector<float> user_dst(batch * 384 * 13 * 13); // Allocate and fill buffers for weights and bias std::vector<float> conv_weights(product(conv_weights_tz)); std::vector<float> conv_bias(product(conv_bias_tz)); /// Create the memory primitives for user data (source, weights, and bias). /// The user data will be in its original 32-bit floating point format. /// @snippet cpu_cnn_inference_int8.cpp Allocate buffers //[Allocate buffers] auto user_src_memory = memory({ { conv_src_tz }, dt::f32, tag::nchw }, cpu_engine, user_src.data()); auto user_weights_memory = memory({ { conv_weights_tz }, dt::f32, tag::oihw }, cpu_engine, conv_weights.data()); auto user_bias_memory = memory({ { conv_bias_tz }, dt::f32, tag::x }, cpu_engine, conv_bias.data()); //[Allocate buffers] /// Create a memory descriptor for each convolution parameter. /// The convolution data uses 8-bit integer values, so the memory /// descriptors are configured as: /// /// * 8-bit unsigned (u8) for source and destination. /// * 8-bit signed (s8) for bias and weights. /// /// > **Note** /// > The destination type is chosen as *unsigned* because the /// > convolution applies a ReLU operation where data results \f$\geq 0\f$. /// @snippet cpu_cnn_inference_int8.cpp Create convolution memory descriptors //[Create convolution memory descriptors] auto conv_src_md = memory::desc({ conv_src_tz }, dt::u8, tag::any); auto conv_bias_md = memory::desc({ conv_bias_tz }, dt::s8, tag::any); auto conv_weights_md = memory::desc({ conv_weights_tz }, dt::s8, tag::any); auto conv_dst_md = memory::desc({ conv_dst_tz }, dt::u8, tag::any); //[Create convolution memory descriptors] /// Create a convolution descriptor passing the int8 memory /// descriptors as parameters. /// @snippet cpu_cnn_inference_int8.cpp Create convolution descriptor //[Create convolution descriptor] auto conv_desc = convolution_forward::desc(prop_kind::forward, algorithm::convolution_direct, conv_src_md, conv_weights_md, conv_bias_md, conv_dst_md, conv_strides, conv_padding, conv_padding); //[Create convolution descriptor] /// Configuring int8-specific parameters in an int8 primitive is done /// via the Attributes Primitive. Create an attributes object for the /// convolution and configure it accordingly. /// @snippet cpu_cnn_inference_int8.cpp Configure scaling //[Configure scaling] primitive_attr conv_attr; conv_attr.set_output_scales(conv_mask, conv_scales); //[Configure scaling] /// The ReLU layer from Alexnet is executed through the PostOps feature. Create /// a PostOps object and configure it to execute an _eltwise relu_ operation. /// @snippet cpu_cnn_inference_int8.cpp Configure post-ops //[Configure post-ops] const float ops_scale = 1.f; const float ops_alpha = 0.f; // relu negative slope const float ops_beta = 0.f; post_ops ops; ops.append_eltwise(ops_scale, algorithm::eltwise_relu, ops_alpha, ops_beta); conv_attr.set_post_ops(ops); //[Configure post-ops] // check if int8 convolution is supported try { auto conv_prim_desc = convolution_forward::primitive_desc( conv_desc, conv_attr, cpu_engine); } catch (error &e) { if (e.status == mkldnn_unimplemented) { std::cerr << "Intel MKL-DNN does not have int8 convolution " "implementation that supports this system. Please refer to " "the developer guide for details." << std::endl; } throw; } /// Create a primitive descriptor using the convolution descriptor /// and passing along the int8 attributes in the constructor. The primitive /// descriptor for the convolution will contain the specific memory /// formats for the computation. /// @snippet cpu_cnn_inference_int8.cpp Create convolution primitive descriptor //[Create convolution primitive descriptor] auto conv_prim_desc = convolution_forward::primitive_desc( conv_desc, conv_attr, cpu_engine); //[Create convolution primitive descriptor] /// Create a memory for each of the convolution's data input /// parameters (source, bias, weights, and destination). Using the convolution /// primitive descriptor as the creation parameter enables Intel MKL-DNN /// to configure the memory formats for the convolution. /// /// Scaling parameters are passed to the reorder primitive via the attributes /// primitive. /// /// User memory must be transformed into convolution-friendly memory /// (for int8 and memory format). A reorder layer performs the data /// transformation from f32 (the original user data) into int8 format /// (the data used for the convolution). In addition, the reorder /// transforms the user data into the required memory format (as explained /// in the simple_net example). /// /// @snippet cpu_cnn_inference_int8.cpp Quantize data and weights //[Quantize data and weights] auto conv_src_memory = memory(conv_prim_desc.src_desc(), cpu_engine); primitive_attr src_attr; src_attr.set_output_scales(src_mask, src_scales); auto src_reorder_pd = reorder::primitive_desc(cpu_engine, user_src_memory.get_desc(), cpu_engine, conv_src_memory.get_desc(), src_attr); auto src_reorder = reorder(src_reorder_pd); src_reorder.execute(s, user_src_memory, conv_src_memory); auto conv_weights_memory = memory(conv_prim_desc.weights_desc(), cpu_engine); primitive_attr weight_attr; weight_attr.set_output_scales(weight_mask, weight_scales); auto weight_reorder_pd = reorder::primitive_desc(cpu_engine, user_weights_memory.get_desc(), cpu_engine, conv_weights_memory.get_desc(), weight_attr); auto weight_reorder = reorder(weight_reorder_pd); weight_reorder.execute(s, user_weights_memory, conv_weights_memory); auto conv_bias_memory = memory(conv_prim_desc.bias_desc(), cpu_engine); primitive_attr bias_attr; bias_attr.set_output_scales(bias_mask, bias_scales); auto bias_reorder_pd = reorder::primitive_desc(cpu_engine, user_bias_memory.get_desc(), cpu_engine, conv_bias_memory.get_desc(), bias_attr); auto bias_reorder = reorder(bias_reorder_pd); bias_reorder.execute(s, user_bias_memory, conv_bias_memory); //[Quantize data and weights] auto conv_dst_memory = memory(conv_prim_desc.dst_desc(), cpu_engine); /// Create the convolution primitive and add it to the net. The int8 example /// computes the same Convolution +ReLU layers from AlexNet simple-net.cpp /// using the int8 and PostOps approach. Although performance is not /// measured here, in practice it would require less computation time to achieve /// similar results. /// @snippet cpu_cnn_inference_int8.cpp Create convolution primitive //[Create convolution primitive] auto conv = convolution_forward(conv_prim_desc); conv.execute(s, { { MKLDNN_ARG_SRC, conv_src_memory }, { MKLDNN_ARG_WEIGHTS, conv_weights_memory }, { MKLDNN_ARG_BIAS, conv_bias_memory }, { MKLDNN_ARG_DST, conv_dst_memory } }); //[Create convolution primitive] /// @page cpu_cnn_inference_int8_cpp /// Finally, *dst memory* may be dequantized from int8 into the original /// f32 format. Create a memory primitive for the user data in the original /// 32-bit floating point format and then apply a reorder to transform the /// computation output data. /// @snippet cpu_cnn_inference_int8.cpp Dequantize the result //[Dequantize the result] auto user_dst_memory = memory({ { conv_dst_tz }, dt::f32, tag::nchw }, cpu_engine, user_dst.data()); primitive_attr dst_attr; dst_attr.set_output_scales(dst_mask, dst_scales); auto dst_reorder_pd = reorder::primitive_desc(cpu_engine, conv_dst_memory.get_desc(), cpu_engine, user_dst_memory.get_desc(), dst_attr); auto dst_reorder = reorder(dst_reorder_pd); dst_reorder.execute(s, conv_dst_memory, user_dst_memory); //[Dequantize the result] s.wait(); } int main(int argc, char **argv) { try { simple_net_int8(); std::cout << "Simple-net-int8 example passed!" << std::endl; } catch (error &e) { std::cerr << "status: " << e.status << std::endl; std::cerr << "message: " << e.message << std::endl; } return 0; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/common/sum_pd.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef SUM_PD_HPP #define SUM_PD_HPP #include <assert.h> #include "mkldnn.h" #include "c_types_map.hpp" #include "nstl.hpp" #include "primitive_desc.hpp" #include "type_helpers.hpp" #include "utils.hpp" namespace mkldnn { namespace impl { struct sum_pd_t: public primitive_desc_t { sum_pd_t(engine_t *engine, const primitive_attr_t *attr, const memory_desc_t *dst_md, int n, const float *scales, const memory_desc_t *src_mds) : primitive_desc_t(engine, attr, primitive_kind::sum) , n_(n), dst_md_(*dst_md) { scales_.reserve(n_); for (int i = 0; i < n_; ++i) scales_.push_back(scales[i]); src_mds_.reserve(n_); for (int i = 0; i < n_; ++i) src_mds_.push_back(src_mds[i]); } virtual void init_info() override { impl::init_info(this, this->info_); } virtual arg_usage_t arg_usage(int arg) const override { if (arg >= MKLDNN_ARG_MULTIPLE_SRC && arg < MKLDNN_ARG_MULTIPLE_SRC + n_inputs()) return arg_usage_t::input; if (arg == MKLDNN_ARG_DST) return arg_usage_t::output; return primitive_desc_t::arg_usage(arg); } virtual const memory_desc_t *src_md(int index = 0) const override { return index < n_inputs() ? &src_mds_[index] : &glob_zero_md; } virtual const memory_desc_t *dst_md(int index = 0) const override { return index == 0 ? &dst_md_ : &glob_zero_md; } const memory_desc_t *dst_acc_md() const { return need_output_reorder() ? &dst_acc_md_ : &dst_md_; } virtual int n_inputs() const override { return n_; } virtual int n_outputs() const override { return 1; } const float *scales() const { return &scales_[0]; } bool need_output_reorder() const { return dst_md()->data_type != mkldnn_f32; } protected: int n_; nstl::vector<float> scales_; memory_desc_t dst_md_, dst_acc_md_; nstl::vector<memory_desc_t> src_mds_; protected: /* inits dst_md_ in simple cases. The call may fail. */ status_t init() { for (int i = 0; i < n_; ++i) { const memory_desc_wrapper src_d(&src_mds_[i]); if (!src_d.is_blocking_desc() || src_d.is_additional_buffer()) return status::unimplemented; } bool ok = true && set_default_params() == status::success && attr()->has_default_values(); if (!ok) return status::unimplemented; // use f32 accumulator to handle float scales w/o accuracy loss if (need_output_reorder()) { dst_acc_md_ = dst_md_; dst_acc_md_.data_type = mkldnn_f32; } return status::success; } status_t set_default_params() { if (dst_md_.format_kind != format_kind::any) return status::success; /* The stupidest ever heuristics (but not the same as we had before): * - Pick the first non-plain format; * - If all formats are plain, pick the format of the first input */ for (int i = 0; i < n_; ++i) { const memory_desc_wrapper src_d(src_mds_[i]); if (!src_d.is_plain() && src_d.is_blocking_desc()) { return memory_desc_init_by_blocking_desc(dst_md_, src_d.blocking_desc()); } } if (src_mds_[0].format_kind != format_kind::blocked) return status::unimplemented; data_type_t dst_dt = dst_md_.data_type; dst_md_ = src_mds_[0]; dst_md_.data_type = dst_dt; return status::success; } }; #define DECLARE_SUM_PD_t(impl_name, ...) \ static status_t create(sum_pd_t **sum_pd, \ engine_t *engine, const primitive_attr_t *attr, \ const memory_desc_t *dst_md, int n, const float *scales, \ const memory_desc_t *src_mds) { \ using namespace status; \ auto _pd = new pd_t(engine, attr, dst_md, n, scales, src_mds); \ if (_pd == nullptr) return out_of_memory; \ if (_pd->init() != success) { delete _pd; return unimplemented; } \ return safe_ptr_assign<sum_pd_t>(*sum_pd, _pd); \ } \ virtual status_t create_primitive(primitive_t **p) const override { \ double ms = get_msec(); \ auto ret = safe_ptr_assign<primitive_t>(*p, new (__VA_ARGS__)(this)); \ status_t status = (*p)->init(); \ if (status != status::success) return status; \ ms = get_msec() - ms; \ if (mkldnn_verbose()->level >= 2) { \ printf("mkldnn_verbose,create,%s,%g\n", this->info(), ms); \ fflush(0); \ } \ return ret; \ } \ virtual pd_t *clone() const override { return new pd_t(*this); } \ virtual const char *name() const override { return impl_name; } \ #define DECLARE_SUM_PD_T(impl_name, ...) \ DECLARE_SUM_PD_t(impl_name, __VA_ARGS__) } } #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ref_softmax.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "ocl/ref_softmax.hpp" namespace mkldnn { namespace impl { namespace ocl { template <impl::data_type_t data_type> status_t ref_softmax_fwd_t<data_type>::execute_generic( const exec_ctx_t &ctx) const { auto &src = CTX_IN_STORAGE(MKLDNN_ARG_SRC); auto &dst = CTX_OUT_STORAGE(MKLDNN_ARG_DST); kernel_.set_arg(0, src); kernel_.set_arg(1, dst); auto nd_range = cl_nd_range_t(pd()->gws.size(), pd()->gws.data()); auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); status_t status = executor.parallel_for(nd_range, kernel_); return status; } template <impl::data_type_t data_type> status_t ref_softmax_bwd_t<data_type>::execute_generic( const exec_ctx_t &ctx) const { auto &dst = CTX_IN_STORAGE(MKLDNN_ARG_DST); auto &diff_dst = CTX_IN_STORAGE(MKLDNN_ARG_DIFF_DST); auto &diff_src = CTX_OUT_STORAGE(MKLDNN_ARG_DIFF_SRC); kernel_.set_arg(0, dst); kernel_.set_arg(1, diff_src); kernel_.set_arg(2, diff_dst); auto nd_range = cl_nd_range_t(pd()->gws.size(), pd()->gws.data()); auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); status_t status = executor.parallel_for(nd_range, kernel_); return status; } template struct ref_softmax_fwd_t<data_type::f16>; template struct ref_softmax_fwd_t<data_type::f32>; template struct ref_softmax_bwd_t<data_type::f32>; } // namespace ocl } // namespace impl } // namespace mkldnn // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/group.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_GROUP_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_GROUP_H_ #include <cstdint> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/inline_vector.h" namespace minigo { // GroupId is a unique identifier for a group (string) of stones. using GroupId = uint16_t; // Group represents a group (string) of stones. // A group only keeps track of the count of its current liberties, not their // location. struct Group { Group() = default; Group(uint16_t size, uint16_t num_liberties) : size(size), num_liberties(num_liberties) {} // Maximum number of potential groups on the board. // Used in various places to pre-allocate buffers. // TODO(tommadams): We can probably reduce the space reserved for potential // groups a bit: https://senseis.xmp.net/?MaximumNumberOfLiveGroups static constexpr int kMaxNumGroups = kN * kN; uint16_t size = 0; uint16_t num_liberties = 0; }; // GroupPool is a simple memory pool for Group objects. class GroupPool { public: // Allocates a new Group with the given size and number of liberties, and // returns the group's ID. GroupId alloc(uint16_t size, uint16_t num_liberties) { GroupId id; if (!free_ids_.empty()) { // We have at least one previously acclocated then freed group, return it. id = free_ids_.back(); free_ids_.pop_back(); groups_[id] = {size, num_liberties}; } else { // Allocate a new group from the pool. id = static_cast<GroupId>(groups_.size()); groups_.emplace_back(size, num_liberties); } return id; } // Free the group, returning it the pool. void free(GroupId id) { free_ids_.push_back(id); } // Access the Group object by ID. Group& operator[](GroupId id) { return groups_[id]; } const Group& operator[](GroupId id) const { return groups_[id]; } private: inline_vector<Group, Group::kMaxNumGroups> groups_; inline_vector<GroupId, Group::kMaxNumGroups> free_ids_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_GROUP_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_avx_f32_copy_bn_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_f32.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx_f32_copy_bn_kern::jit_avx_f32_copy_bn_kern() : jit_generator(nullptr, F32_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rsi #define B rdi #define I rax #define A1 r10 #define A2 rsi #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l118; Xbyak::Label l15c; Xbyak::Label l16c; Xbyak::Label l18c; Xbyak::Label l1cc; Xbyak::Label l200; Xbyak::Label l230; Xbyak::Label l234; Xbyak::Label l254; Xbyak::Label l294; Xbyak::Label l2c4; Xbyak::Label l2e8; Xbyak::Label l2ec; Xbyak::Label l2f4; Xbyak::Label l310; Xbyak::Label l328; Xbyak::Label l398; Xbyak::Label l3ec; Xbyak::Label l434; Xbyak::Label l444; Xbyak::Label l464; Xbyak::Label l4ac; Xbyak::Label l4e4; Xbyak::Label l518; Xbyak::Label l51c; Xbyak::Label l53c; Xbyak::Label l54; Xbyak::Label l580; Xbyak::Label l5b4; Xbyak::Label l5dc; Xbyak::Label l5e0; Xbyak::Label l5e8; Xbyak::Label l5f4; Xbyak::Label l60c; Xbyak::Label l67c; Xbyak::Label l6c; Xbyak::Label l6d0; Xbyak::Label l718; Xbyak::Label l728; Xbyak::Label l748; Xbyak::Label l790; Xbyak::Label l7c8; Xbyak::Label l7fc; Xbyak::Label l800; Xbyak::Label l820; Xbyak::Label l864; Xbyak::Label l898; Xbyak::Label l8c0; Xbyak::Label l8c4; Xbyak::Label lcc; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); sub(A, 0x0); sub(B, -128); shl(LDA, 0x2); lea(LDA3, ptr[LDA+LDA*2]); vbroadcastss(ymm6, dword[ALPHA]); vpcmpeqb(xmm3, xmm3, xmm3); vpsrld(xmm3, xmm3, 0x17); vpslld(xmm3, xmm3, 0x19); vpsrld(xmm3, xmm3, 0x2); vpcmpeqb(xmm4, xmm4, xmm4); vpslld(xmm4, xmm4, 0x1f); vperm2f128(ymm4, ymm4, ymm4, 0x20); vucomiss(xmm6, xmm3); jne(l2f4, T_NEAR); cmp(N, 0x4); jl(l16c, T_NEAR); align(4); L(l54); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(lcc, T_NEAR); align(4); L(l6c); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1+LDA*1]); vmovups(xmm2, xword[A1+LDA*2]); vmovups(xmm3, xword[A1+LDA3*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm5, xmm0, xmm1); vunpcklps(xmm1, xmm2, xmm3); vunpckhps(xmm3, xmm2, xmm3); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vunpcklpd(xmm2, xmm5, xmm3); vunpckhpd(xmm3, xmm5, xmm3); vmovups(xword[B-0x80], xmm0); vmovups(xword[B-0x70], xmm1); vmovups(xword[B-0x60], xmm2); vmovups(xword[B-0x50], xmm3); lea(A2, ptr[A1+LDA*4]); sub(A1, -16); sub(B, -64); dec(I); jg(l6c, T_NEAR); align(4); L(lcc); test(M, 0x2); jle(l118, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1+LDA*1]); vmovhps(xmm0, xmm0, qword[A1+LDA*2]); vmovhps(xmm1, xmm1, qword[A1+LDA3*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vmovups(xword[B-0x80], xmm0); vmovups(xword[B-0x70], xmm1); lea(A2, ptr[A1+LDA*4]); sub(A1, -8); sub(B, -32); align(4); L(l118); test(M, 0x1); jle(l15c, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmovss(xmm2, dword[A1+LDA*2]); vmovss(xmm3, dword[A1+LDA3*1]); vunpcklps(xmm2, xmm2, xmm3); vunpcklpd(xmm0, xmm0, xmm2); vmovups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); sub(A1, -4); sub(B, -16); align(4); L(l15c); sub(N, 0x4); cmp(N, 0x4); jge(l54, T_NEAR); align(4); L(l16c); cmp(N, 0x2); jl(l234, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l1cc, T_NEAR); align(4); L(l18c); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1+LDA*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vmovaps(xmm0, xmm4); vmovlps(qword[B-0x80], xmm0); vmovhps(qword[B-0x78], xmm0); vmovlps(qword[B-0x70], xmm1); vmovhps(qword[B-0x68], xmm1); lea(A2, ptr[A1+LDA*2]); sub(A1, -16); sub(B, -32); dec(I); jg(l18c, T_NEAR); align(4); L(l1cc); test(M, 0x2); jle(l200, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmovlps(qword[B-0x80], xmm0); vmovhps(qword[B-0x78], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -8); sub(B, -16); align(4); L(l200); test(M, 0x1); jle(l230, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmovlps(qword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -4); sub(B, -8); align(4); L(l230); sub(N, 0x2); align(4); L(l234); cmp(N, 0x1); jl(l2ec, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l294, T_NEAR); align(4); L(l254); vmovups(xmm0, xword[A1]); vpshufd(xmm1, xmm0, 0x55); vpshufd(xmm2, xmm0, 0xaa); vpshufd(xmm3, xmm0, 0xff); vmovss(dword[B-0x80], xmm0); vmovss(dword[B-0x7c], xmm1); vmovss(dword[B-0x78], xmm2); vmovss(dword[B-0x74], xmm3); lea(A2, ptr[A1+LDA*1]); sub(A1, -16); sub(B, -16); dec(I); jg(l254, T_NEAR); align(4); L(l294); test(M, 0x2); jle(l2c4, T_NEAR); vmovsd(xmm0, qword[A1]); vpshufd(xmm1, xmm0, 0x55); vmovss(dword[B-0x80], xmm0); vmovss(dword[B-0x7c], xmm1); lea(A2, ptr[A1+LDA*1]); sub(A1, -8); sub(B, -8); align(4); L(l2c4); test(M, 0x1); jle(l2e8, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(dword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*1]); sub(A1, -4); sub(B, -4); align(4); L(l2e8); sub(N, 0x1); align(4); L(l2ec); jmp(l8c4, T_NEAR); align(4); L(l2f4); vxorps(xmm3, xmm3, xmm4); vucomiss(xmm6, xmm3); jne(l5e8, T_NEAR); vmovaps(ymm6, ymm4); cmp(N, 0x4); jl(l444, T_NEAR); align(4); L(l310); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(l398, T_NEAR); align(4); L(l328); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1+LDA*1]); vmovups(xmm2, xword[A1+LDA*2]); vmovups(xmm3, xword[A1+LDA3*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm5, xmm0, xmm1); vunpcklps(xmm1, xmm2, xmm3); vunpckhps(xmm3, xmm2, xmm3); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vunpcklpd(xmm2, xmm5, xmm3); vunpckhpd(xmm3, xmm5, xmm3); vxorps(xmm0, xmm6, xmm0); vxorps(xmm1, xmm6, xmm1); vxorps(xmm2, xmm6, xmm2); vxorps(xmm3, xmm6, xmm3); vmovups(xword[B-0x80], xmm0); vmovups(xword[B-0x70], xmm1); vmovups(xword[B-0x60], xmm2); vmovups(xword[B-0x50], xmm3); lea(A2, ptr[A1+LDA*4]); sub(A1, -16); sub(B, -64); dec(I); jg(l328, T_NEAR); align(4); L(l398); test(M, 0x2); jle(l3ec, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1+LDA*1]); vmovhps(xmm0, xmm0, qword[A1+LDA*2]); vmovhps(xmm1, xmm1, qword[A1+LDA3*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vxorps(xmm0, xmm6, xmm0); vxorps(xmm1, xmm6, xmm1); vmovups(xword[B-0x80], xmm0); vmovups(xword[B-0x70], xmm1); lea(A2, ptr[A1+LDA*4]); sub(A1, -8); sub(B, -32); align(4); L(l3ec); test(M, 0x1); jle(l434, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmovss(xmm2, dword[A1+LDA*2]); vmovss(xmm3, dword[A1+LDA3*1]); vunpcklps(xmm2, xmm2, xmm3); vunpcklpd(xmm0, xmm0, xmm2); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); sub(A1, -4); sub(B, -16); align(4); L(l434); sub(N, 0x4); cmp(N, 0x4); jge(l310, T_NEAR); align(4); L(l444); cmp(N, 0x2); jl(l51c, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l4ac, T_NEAR); align(4); L(l464); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1+LDA*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vmovaps(xmm0, xmm4); vxorps(xmm0, xmm6, xmm0); vxorps(xmm1, xmm6, xmm1); vmovlps(qword[B-0x80], xmm0); vmovhps(qword[B-0x78], xmm0); vmovlps(qword[B-0x70], xmm1); vmovhps(qword[B-0x68], xmm1); lea(A2, ptr[A1+LDA*2]); sub(A1, -16); sub(B, -32); dec(I); jg(l464, T_NEAR); align(4); L(l4ac); test(M, 0x2); jle(l4e4, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovhps(qword[B-0x78], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -8); sub(B, -16); align(4); L(l4e4); test(M, 0x1); jle(l518, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -4); sub(B, -8); align(4); L(l518); sub(N, 0x2); align(4); L(l51c); cmp(N, 0x1); jl(l5e0, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l580, T_NEAR); align(4); L(l53c); vmovups(xmm0, xword[A1]); vxorps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vpshufd(xmm2, xmm0, 0xaa); vpshufd(xmm3, xmm0, 0xff); vmovss(dword[B-0x80], xmm0); vmovss(dword[B-0x7c], xmm1); vmovss(dword[B-0x78], xmm2); vmovss(dword[B-0x74], xmm3); lea(A2, ptr[A1+LDA*1]); sub(A1, -16); sub(B, -16); dec(I); jg(l53c, T_NEAR); align(4); L(l580); test(M, 0x2); jle(l5b4, T_NEAR); vmovsd(xmm0, qword[A1]); vxorps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vmovss(dword[B-0x80], xmm0); vmovss(dword[B-0x7c], xmm1); lea(A2, ptr[A1+LDA*1]); sub(A1, -8); sub(B, -8); align(4); L(l5b4); test(M, 0x1); jle(l5dc, T_NEAR); vmovss(xmm0, dword[A1]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*1]); sub(A1, -4); sub(B, -4); align(4); L(l5dc); sub(N, 0x1); align(4); L(l5e0); jmp(l8c4, T_NEAR); align(4); L(l5e8); cmp(N, 0x4); jl(l728, T_NEAR); align(4); L(l5f4); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(l67c, T_NEAR); align(4); L(l60c); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1+LDA*1]); vmovups(xmm2, xword[A1+LDA*2]); vmovups(xmm3, xword[A1+LDA3*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm5, xmm0, xmm1); vunpcklps(xmm1, xmm2, xmm3); vunpckhps(xmm3, xmm2, xmm3); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vunpcklpd(xmm2, xmm5, xmm3); vunpckhpd(xmm3, xmm5, xmm3); vmulps(xmm0, xmm6, xmm0); vmulps(xmm1, xmm6, xmm1); vmulps(xmm2, xmm6, xmm2); vmulps(xmm3, xmm6, xmm3); vmovups(xword[B-0x80], xmm0); vmovups(xword[B-0x70], xmm1); vmovups(xword[B-0x60], xmm2); vmovups(xword[B-0x50], xmm3); lea(A2, ptr[A1+LDA*4]); sub(A1, -16); sub(B, -64); dec(I); jg(l60c, T_NEAR); align(4); L(l67c); test(M, 0x2); jle(l6d0, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1+LDA*1]); vmovhps(xmm0, xmm0, qword[A1+LDA*2]); vmovhps(xmm1, xmm1, qword[A1+LDA3*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vmulps(xmm0, xmm6, xmm0); vmulps(xmm1, xmm6, xmm1); vmovups(xword[B-0x80], xmm0); vmovups(xword[B-0x70], xmm1); lea(A2, ptr[A1+LDA*4]); sub(A1, -8); sub(B, -32); align(4); L(l6d0); test(M, 0x1); jle(l718, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmovss(xmm2, dword[A1+LDA*2]); vmovss(xmm3, dword[A1+LDA3*1]); vunpcklps(xmm2, xmm2, xmm3); vunpcklpd(xmm0, xmm0, xmm2); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); sub(A1, -4); sub(B, -16); align(4); L(l718); sub(N, 0x4); cmp(N, 0x4); jge(l5f4, T_NEAR); align(4); L(l728); cmp(N, 0x2); jl(l800, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l790, T_NEAR); align(4); L(l748); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1+LDA*1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vmovaps(xmm0, xmm4); vmulps(xmm0, xmm6, xmm0); vmulps(xmm1, xmm6, xmm1); vmovlps(qword[B-0x80], xmm0); vmovhps(qword[B-0x78], xmm0); vmovlps(qword[B-0x70], xmm1); vmovhps(qword[B-0x68], xmm1); lea(A2, ptr[A1+LDA*2]); sub(A1, -16); sub(B, -32); dec(I); jg(l748, T_NEAR); align(4); L(l790); test(M, 0x2); jle(l7c8, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovhps(qword[B-0x78], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -8); sub(B, -16); align(4); L(l7c8); test(M, 0x1); jle(l7fc, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1+LDA*1]); vunpcklps(xmm0, xmm0, xmm1); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -4); sub(B, -8); align(4); L(l7fc); sub(N, 0x2); align(4); L(l800); cmp(N, 0x1); jl(l8c4, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l864, T_NEAR); align(4); L(l820); vmovups(xmm0, xword[A1]); vmulps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vpshufd(xmm2, xmm0, 0xaa); vpshufd(xmm3, xmm0, 0xff); vmovss(dword[B-0x80], xmm0); vmovss(dword[B-0x7c], xmm1); vmovss(dword[B-0x78], xmm2); vmovss(dword[B-0x74], xmm3); lea(A2, ptr[A1+LDA*1]); sub(A1, -16); sub(B, -16); dec(I); jg(l820, T_NEAR); align(4); L(l864); test(M, 0x2); jle(l898, T_NEAR); vmovsd(xmm0, qword[A1]); vmulps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vmovss(dword[B-0x80], xmm0); vmovss(dword[B-0x7c], xmm1); lea(A2, ptr[A1+LDA*1]); sub(A1, -8); sub(B, -8); align(4); L(l898); test(M, 0x1); jle(l8c0, T_NEAR); vmovss(xmm0, dword[A1]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*1]); sub(A1, -4); sub(B, -4); align(4); L(l8c0); sub(N, 0x1); align(4); L(l8c4); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ref_shuffle.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_REF_SHUFFLE_HPP #define OCL_REF_SHUFFLE_HPP #include "common/c_types_map.hpp" #include "ocl/jit_ref_shuffle_kernel.hpp" #include "ocl/ocl_engine.hpp" #include "ocl/ocl_shuffle_pd.hpp" #include "ocl/ocl_stream.hpp" #include "ocl/ocl_utils.hpp" extern const char *ref_shuffle_kernel; namespace mkldnn { namespace impl { namespace ocl { template<int data_type_size> struct ref_shuffle_t : public primitive_t { using shuffle_class = ref_shuffle_t<data_type_size>; struct pd_t : public ocl_shuffle_pd_t { using ocl_shuffle_pd_t::ocl_shuffle_pd_t; DECLARE_COMMON_PD_T("ocl:ref:any", shuffle_class); status_t init() { using namespace format_tag; auto *cl_engine = utils::downcast<cl_engine_t *>(engine()); bool ok = true && data_type_size == types::data_type_size(data_md()->data_type) && IMPLICATION( desc()->data_desc.data_type == data_type::f16, cl_engine->mayiuse(cl_device_ext_t::khr_fp16)) && desc()->data_desc.data_type != data_type::bf16; if (!ok) return status::unimplemented; dat_tag_ = any; return jit_ref_shuffle_kernel::init_conf(this, jshfl_, jit_off_, src_md(), dst_md(), diff_src_md(), diff_dst_md()); } jit_shuffle_conf_t jshfl_; jit_offsets jit_off_; format_tag_t dat_tag_; }; ref_shuffle_t(const pd_t *apd) : primitive_t(apd) {} virtual status_t init() override { auto jit = ocl_jit_t(ref_shuffle_kernel); status_t status = jit_ref_shuffle_kernel::init_const_def(jit, pd()->jshfl_, pd()->jit_off_); if (status != status::success) return status; status = jit.build(engine()); if (status != status::success) return status; kernel_ = jit.get_kernel("ref_shuffle"); if (!kernel_) return status::runtime_error; return status::success; } ~ref_shuffle_t() {} virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_<format_tag::any>(ctx); } private: template<format_tag_t tag> status_t execute_(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } ocl_kernel_t kernel_; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/sample_records.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/sample_records.h" #include <cstddef> DEFINE_double(sample_frac, 0, "Fraction of records to read. Exactly one of sample_frac or " "num_records must be non-zero."); DEFINE_uint64(num_records, 0, "Exact number of records to sample. Exactly one of sample_frac " "or num_records must be non-zero."); DEFINE_int32(num_read_threads, 1, "Number of threads to use when reading source files."); DEFINE_int32(num_write_threads, 1, "Number of threads to use when writing destination files. If " "num_write threads is > 1, the destination file will be sharded " "with one shard per write thread. Shards will be named " "<basename>-NNNNN-of-NNNNN.tfrecord.zz"); DEFINE_int32(compression, 1, "Compression level between 0 (disabled) and 9. Default is 1."); DEFINE_int32(files_per_pattern, 0, "If > 0, randomly select exactly files_per_pattern input files " "to sample records from, failing if fewer are found."); DEFINE_uint64(seed, 0, "Random seed."); DEFINE_bool(shuffle, false, "Whether to shuffle the sampled records."); DEFINE_string(dst, "", "Destination path. If path has a .zz suffix, the file will be " "automatically compressed."); namespace minigo { void ReadThread::Run() { namespace tf_io = ::tensorflow::io; tf_io::RecordReaderOptions options; for (const auto& path : paths_) { std::unique_ptr<tensorflow::RandomAccessFile> file; TF_CHECK_OK(tensorflow::Env::Default()->NewRandomAccessFile(path, &file)); if (absl::EndsWith(path, ".zz")) { options.compression_type = tf_io::RecordReaderOptions::ZLIB_COMPRESSION; } else { options.compression_type = tf_io::RecordReaderOptions::NONE; } tensorflow::io::SequentialRecordReader reader(file.get(), options); tensorflow::tstring record; for (;;) { auto status = reader.ReadRecord(&record); if (status.code() == tensorflow::error::OUT_OF_RANGE) { // Reached the end of the file. break; } else if (!status.ok()) { // Some other error. MG_LOG(WARNING) << "Error reading record from \"" << path << "\": " << status; continue; } if (options_.sample_frac == 1 || rnd_() < options_.sample_frac) { sampled_records_.push_back(std::move(record)); } } } } WriteThread::WriteThread(std::vector<tensorflow::tstring> records, const std::string& path, const Options& options) : records_(std::move(records)), options_(options) { if (options_.num_shards == 1) { path_ = path; } else { absl::string_view expected_ext = options_.compression == 0 ? ".tfrecord" : ".tfrecord.zz"; absl::string_view stem = path; MG_CHECK(absl::ConsumeSuffix(&stem, expected_ext)) << "expected path to have extension '" << expected_ext << "', got '" << stem << "'"; path_ = absl::StrFormat("%s-%05d-of-%05d.tfrecord.zz", stem, options_.shard, options_.num_shards); } } void WriteThread::Run() { std::unique_ptr<tensorflow::WritableFile> file; TF_CHECK_OK(tensorflow::Env::Default()->NewWritableFile(path_, &file)); tensorflow::io::RecordWriterOptions options; if (options_.compression > 0) { MG_CHECK(options_.compression <= 9); options.compression_type = tensorflow::io::RecordWriterOptions::ZLIB_COMPRESSION; options.zlib_options.compression_level = options_.compression; } else { options.compression_type = tensorflow::io::RecordWriterOptions::NONE; } tensorflow::io::RecordWriter writer(file.get(), options); for (const auto& record : records_) { TF_CHECK_OK(writer.WriteRecord(record)); } TF_CHECK_OK(writer.Close()); TF_CHECK_OK(file->Close()); } std::vector<tensorflow::tstring> Read(std::vector<std::string> paths) { int num_paths = static_cast<int>(paths.size()); int num_read_threads = std::min<int>(FLAGS_num_read_threads, num_paths); MG_LOG(INFO) << "reading " << num_paths << " files on " << num_read_threads << " threads"; ReadThread::Options read_options; // If --sample_frac wasn't set, default to reading all records: we need to // read all records from all files in order to fairly read exaclty // --num_records records. read_options.sample_frac = FLAGS_sample_frac == 0 ? 1 : FLAGS_sample_frac; std::vector<std::unique_ptr<ReadThread>> threads; for (int i = 0; i < num_read_threads; ++i) { // Get the record paths that this thread should run on. int begin = i * num_paths / num_read_threads; int end = (i + 1) * num_paths / num_read_threads; std::vector<std::string> thread_paths; for (int j = begin; j < end; ++j) { thread_paths.push_back(std::move(paths[j])); } threads.push_back( absl::make_unique<ReadThread>(std::move(thread_paths), read_options)); } for (auto& t : threads) { t->Start(); } for (auto& t : threads) { t->Join(); } // Concatenate sampled records. size_t num_sampled = 0; for (const auto& t : threads) { num_sampled += t->sampled_records().size(); } MG_LOG(INFO) << "sampled " << num_sampled << " records"; MG_LOG(INFO) << "concatenating"; std::vector<tensorflow::tstring> records; records.reserve(num_sampled); for (const auto& t : threads) { MoveAppend(&t->sampled_records(), &records); } return records; } void Shuffle(std::vector<tensorflow::tstring>* records) { Random rnd(FLAGS_seed, Random::kUniqueStream); MG_LOG(INFO) << "shuffling"; rnd.Shuffle(records); } size_t Write(const std::vector<tensorflow::tstring>& records, const std::string& path) { MG_LOG(INFO) << "writing to " << path; WriteThread::Options write_options; write_options.num_shards = FLAGS_num_write_threads; write_options.compression = FLAGS_compression; size_t num_records; if (FLAGS_num_records != 0) { MG_CHECK(FLAGS_num_records <= records.size()) << "--num_records=" << FLAGS_num_records << " but there are only " << records.size() << " available"; num_records = FLAGS_num_records; } else { num_records = static_cast<size_t>(records.size()); } size_t total_dst = 0; std::vector<std::unique_ptr<WriteThread>> threads; for (int shard = 0; shard < FLAGS_num_write_threads; ++shard) { write_options.shard = shard; // Calculate the range of source records for this shard. size_t begin_src = shard * records.size() / FLAGS_num_write_threads; size_t end_src = (shard + 1) * records.size() / FLAGS_num_write_threads; size_t num_src = end_src - begin_src; // Calculate the number of destination records for this shard. size_t begin_dst = shard * num_records / FLAGS_num_write_threads; size_t end_dst = (shard + 1) * num_records / FLAGS_num_write_threads; size_t num_dst = end_dst - begin_dst; total_dst += num_dst; // Sample the records for this shard. std::vector<tensorflow::tstring> shard_records; shard_records.reserve(num_dst); for (size_t i = 0; i < num_dst; ++i) { size_t j = begin_src + i * num_src / num_dst; shard_records.push_back(std::move(records[j])); } threads.push_back(absl::make_unique<WriteThread>(std::move(shard_records), path, write_options)); } MG_CHECK(total_dst == num_records); MG_LOG(INFO) << "writing " << num_records << " records to " << path; for (auto& t : threads) { t->Start(); } for (auto& t : threads) { t->Join(); } return num_records; } size_t Run(const std::vector<std::string>& src_paths, const std::string& dst_path) { MG_CHECK((FLAGS_sample_frac != 0) != (FLAGS_num_records != 0)) << "expected exactly one of --sample_frac and --num_records to be " "non-zero"; MG_CHECK(!src_paths.empty()); MG_CHECK(!dst_path.empty()); auto records = Read(std::move(src_paths)); if (FLAGS_shuffle) { Shuffle(&records); } size_t num_records = Write(records, dst_path); MG_LOG(INFO) << "Done writing"; return num_records; } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/common/engine.hpp<|end_filename|> /******************************************************************************* * Copyright 2016-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef ENGINE_HPP #define ENGINE_HPP #include "mkldnn.h" #include "c_types_map.hpp" #include "primitive.hpp" #include "utils.hpp" /** \brief An abstraction of an execution unit with shared resources * * Responsibilities: * - Provide engine specific memory allocation * - Provide engine specific primitive_desc_t creators */ struct mkldnn_engine: public mkldnn::impl::c_compatible { mkldnn_engine(mkldnn::impl::engine_kind_t kind, mkldnn::impl::backend_kind_t backend_kind) : kind_(kind), backend_kind_(backend_kind) {} virtual ~mkldnn_engine() {} /** get kind of the current engine */ mkldnn::impl::engine_kind_t kind() const { return kind_; } /** get the backend kind of the current engine */ mkldnn::impl::backend_kind_t backend_kind() const { return backend_kind_; } /** create memory storage */ virtual mkldnn::impl::status_t create_memory_storage( mkldnn::impl::memory_storage_t **storage, unsigned flags, size_t size, void *handle) = 0; mkldnn::impl::status_t create_memory_storage( mkldnn::impl::memory_storage_t **storage, size_t size) { return create_memory_storage( storage, mkldnn::impl::memory_flags_t::alloc, size, nullptr); } /** create stream */ virtual mkldnn::impl::status_t create_stream( mkldnn::impl::stream_t **stream, unsigned flags) = 0; /** implementation section (typedefs) */ // TODO: remove engine? typedef mkldnn::impl::status_t (*reorder_primitive_desc_create_f)( mkldnn::impl::reorder_pd_t **reorder_pd, mkldnn::impl::engine_t *engine, const mkldnn::impl::primitive_attr_t *attr, mkldnn::impl::engine_t *src_engine, const mkldnn::impl::memory_desc_t *src_md, mkldnn::impl::engine_t *dst_engine, const mkldnn::impl::memory_desc_t *dst_md); typedef mkldnn::impl::status_t (*concat_primitive_desc_create_f)( mkldnn::impl::concat_pd_t **concat_pd, mkldnn::impl::engine_t *engine, const mkldnn::impl::primitive_attr_t *attr, const mkldnn::impl::memory_desc_t *dst_md, int n, int concat_dim, const mkldnn::impl::memory_desc_t *src_mds); typedef mkldnn::impl::status_t (*sum_primitive_desc_create_f)( mkldnn::impl::sum_pd_t **sum_pd, mkldnn::impl::engine_t *engine, const mkldnn::impl::primitive_attr_t *attr, const mkldnn::impl::memory_desc_t *dst_md, int n, const float *scales, const mkldnn::impl::memory_desc_t *src_mds); typedef mkldnn::impl::status_t (*primitive_desc_create_f)( mkldnn::impl::primitive_desc_t **, const mkldnn::impl::op_desc_t *, const mkldnn::impl::primitive_attr_t *attr, mkldnn::impl::engine_t *, const mkldnn::impl::primitive_desc_t *); /* implementation section */ /** return the list of reorder implementations. engine guarantees to return * a NULL-terminated list */ virtual const reorder_primitive_desc_create_f* get_reorder_implementation_list() const = 0; /** return the list of concat implementations. engine guarantees to return * a NULL-terminated list */ virtual const concat_primitive_desc_create_f* get_concat_implementation_list() const = 0; /** return the list of sum implementations. engine guarantees to return * a NULL-terminated list */ virtual const sum_primitive_desc_create_f* get_sum_implementation_list() const = 0; /** return the list of implementations. engine guarantees to return a * NULL-terminated list */ virtual const primitive_desc_create_f* get_implementation_list() const = 0; protected: mkldnn::impl::engine_kind_t kind_; mkldnn::impl::backend_kind_t backend_kind_; }; namespace mkldnn { namespace impl { struct engine_factory_t: public c_compatible { virtual size_t count() const = 0; virtual status_t engine_create(engine_t **engine, size_t index) const = 0; virtual ~engine_factory_t() = default; }; } } #endif // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/common/gemm_types.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef GEMM_TYPES_HPP #define GEMM_TYPES_HPP #include "mkldnn_types.h" namespace mkldnn { namespace impl { enum transpose_t { mkldnn_notrans, mkldnn_trans }; namespace transpose { const transpose_t notrans = mkldnn_notrans; const transpose_t trans = mkldnn_trans; } /** A descriptor for a matrix multiplication (gemm) operation */ typedef struct { /** The kind of primitive. Used for self identifying the primitive * descriptor. Must be #mkldnn_gemm. */ mkldnn_primitive_kind_t primitive_kind; /** Flag for transposing matrix A. */ transpose_t transa; /** Flag for transposing matrix B. */ transpose_t transb; /** Number of rows of C. */ mkldnn_dim_t m; /** Number of columns of C. */ mkldnn_dim_t n; /** Size of inner dimension shared between A and B. */ mkldnn_dim_t k; /** Leading dimension of A. */ mkldnn_dim_t lda; /** Leading dimension of B. */ mkldnn_dim_t ldb; /** Leading dimension of C. */ mkldnn_dim_t ldc; /** Scaling factor for A*B. */ float alpha; /** Scaling factor for C. */ float beta; /** Type of matrix A. */ mkldnn_data_type_t a_type; /** Type of matrix B. */ mkldnn_data_type_t b_type; /** Type of matrix C. */ mkldnn_data_type_t c_type; } mkldnn_gemm_desc_t; } // namespace impl } // namespace mkldnn #endif // GEMM_TYPES_HPP <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/cudnn/cudnn_bn_stats_finalize-inl.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file cudnn_bn_stats_finalize-inl.h * \brief * \author <NAME> */ #ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_BN_STATS_FINALIZE_INL_H_ #define MXNET_OPERATOR_NN_CUDNN_CUDNN_BN_STATS_FINALIZE_INL_H_ #include <vector> #include <map> #include <string> #include <utility> #include "../bn_stats_finalize-inl.h" #include "cudnn_common_op.h" namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 #if defined(__CUDACC__) template<typename DType> class CuDNNBNStatsFinalizeOp { public: CuDNNBNStatsFinalizeOp() #if CUDNN_VERSION >= 7600 : train_op_(CUDNN_FUSED_BN_FINALIZE_STATISTICS_TRAINING), inference_op_(CUDNN_FUSED_BN_FINALIZE_STATISTICS_INFERENCE) #endif { using namespace mshadow; dtype_ = DataType<DType>::kCudnnFlag; // For float16 input type beta, gamma, mean, and average are stored in float32. // For other input types, these parameters have the same type as input dtype_param_ = (dtype_ == CUDNN_DATA_HALF) ? kFloat32 : DataType<DType>::kFlag; CUDNN_CALL(cudnnCreateTensorDescriptor(&out_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&in_desc_)); } void Init(const BNStatsFinalizeParam &param, const TShape shape, const OpContext &ctx) { CHECK_GE(param.eps, CUDNN_BN_MIN_EPSILON) << "CuDNN requires eps to be no less than " << CUDNN_BN_MIN_EPSILON; this->param_ = param; InitDescriptors(shape); #if CUDNN_VERSION >= 7600 // Set up the 'Const Param Pack' for the BNForwardFinalizeStatisticsTraining op // Describe pointer alignments train_op_.SetOpConstParamAttr({CUDNN_PARAM_YSUM_PLACEHOLDER, CUDNN_PARAM_YSQSUM_PLACEHOLDER, CUDNN_PARAM_BN_SCALE_PLACEHOLDER, CUDNN_PARAM_BN_BIAS_PLACEHOLDER, CUDNN_PARAM_BN_SAVED_MEAN_PLACEHOLDER, CUDNN_PARAM_BN_SAVED_INVSTD_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_MEAN_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_VAR_PLACEHOLDER, CUDNN_PARAM_BN_EQSCALE_PLACEHOLDER, CUDNN_PARAM_BN_EQBIAS_PLACEHOLDER}, CUDNN_PTR_ELEM_ALIGNED); // Set the I/O descriptors // sum and sum_squares input descriptor (typically fp32). Also // scale, bias, running_mean and running_var input descriptors, as well as the // saved_mean and saved_inv_std output descriptor (typically fp32) train_op_.SetOpConstParamDesc({CUDNN_PARAM_YSTATS_DESC, CUDNN_PARAM_BN_SCALEBIAS_MEANVAR_DESC}, in_desc_); // equiv_scale and equiv_bias output descriptor (typically fp16) train_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_EQSCALEBIAS_DESC, out_desc_); // Set up the 'Const Param Pack' for the BNForwardFinalizeStatisticsInference op inference_op_.SetOpConstParamAttr({CUDNN_PARAM_BN_SCALE_PLACEHOLDER, CUDNN_PARAM_BN_BIAS_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_MEAN_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_VAR_PLACEHOLDER, CUDNN_PARAM_BN_EQSCALE_PLACEHOLDER, CUDNN_PARAM_BN_EQBIAS_PLACEHOLDER}, CUDNN_PTR_ELEM_ALIGNED); // Set the I/O descriptors // scale, bias, running_mean and running_var input descriptors, as well as the // saved_mean and saved_inv_std output descriptor (typically fp32) inference_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_SCALEBIAS_MEANVAR_DESC, in_desc_); // equiv_scale and equiv_bias output descriptor (typically fp16) inference_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_EQSCALEBIAS_DESC, out_desc_); // Perform some actions identically on both train and inference ops. mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); for (auto op : {&train_op_, &inference_op_}) { // Set the mode parameter in the ops, can't be CUDNN_BATCHNORM_PER_ACTIVATION. op->SetOpConstParamAttr(CUDNN_PARAM_BN_MODE, CUDNN_BATCHNORM_SPATIAL); // Check workspace size, also creates 'plan'. size_t workspace_size_bytes = op->GetWorkspaceSizeInBytes(s->dnn_handle_); CHECK_EQ(workspace_size_bytes, 0U) << "Unexpected non-zero workspace size for CuDNNBNStatsFinalize op."; op->SetOpVariantParamAttrPtr(CUDNN_PTR_WORKSPACE, static_cast<void *>(nullptr)); op->SetOpVariantParamAttrPtr(CUDNN_PTR_WORKSPACE, &workspace_size_bytes); } #endif } ~CuDNNBNStatsFinalizeOp() { CUDNN_CALL(cudnnDestroyTensorDescriptor(out_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(in_desc_)); } void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data, const std::vector<TBlob> &aux_states) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(in_data.size(), static_cast<size_t>(bn_stats_finalize::kNumNonAuxInputs)); CHECK_EQ(aux_states.size(), static_cast<size_t>(bn_stats_finalize::kNumAuxStates)); if (ctx.is_train) { CHECK_EQ(out_data.size(), static_cast<size_t>(bn_stats_finalize::kNumOutputs)); CHECK_EQ(req.size(), static_cast<size_t>(bn_stats_finalize::kNumOutputs)); } else { // Only equiv_scale and equiv_bias CHECK_GE(out_data.size(), 2U); CHECK_GE(req.size(), 2U); } CHECK_EQ(req[bn_stats_finalize::kEquivScale], kWriteTo); CHECK_EQ(req[bn_stats_finalize::kEquivBias], kWriteTo); // All inputs, outputs and aux states should have a shape equal to the one used to init the op for (auto &input : in_data) CHECK_EQ(input.shape_, init_shape_); for (auto &output : out_data) CHECK_EQ(output.shape_, init_shape_); for (auto &aux_state : aux_states) CHECK_EQ(aux_state.shape_, init_shape_); int features = in_data[bn_stats_finalize::kSum].shape_[0]; Stream<gpu> *s = ctx.get_stream<gpu>(); DType *equiv_scale = Get1dPtr(out_data[bn_stats_finalize::kEquivScale], features, s); DType *equiv_bias = Get1dPtr(out_data[bn_stats_finalize::kEquivBias], features, s); #if CUDNN_VERSION < 7600 LOG(FATAL) << "cuDNN version 7.6 or later is required."; #else MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, { Tensor<gpu, 1, DTypeParam> sum = in_data[bn_stats_finalize::kSum] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); Tensor<gpu, 1, DTypeParam> sum_squares = in_data[bn_stats_finalize::kSumOfSquares] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); Tensor<gpu, 1, DTypeParam> gamma = in_data[bn_stats_finalize::kGamma] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); Tensor<gpu, 1, DTypeParam> beta = in_data[bn_stats_finalize::kBeta] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); Tensor<gpu, 1, DTypeParam> moving_mean = aux_states[bn_stats_finalize::kMovingMean] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); Tensor<gpu, 1, DTypeParam> moving_inv_var = aux_states[bn_stats_finalize::kMovingVar] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); if (param_.fix_gamma) gamma = 1.f; auto &op = ctx.is_train ? train_op_ : inference_op_; // The prep needed for the train_op_ is a superset of that needed for the inference_op_. // Start here with the common prep needed for the inference_op_: // Set data pointers in the 'variant param pack' op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_SCALE, gamma.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_BIAS, beta.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_RUNNING_MEAN, moving_mean.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_RUNNING_VAR, moving_inv_var.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQSCALE, equiv_scale); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQBIAS, equiv_bias); // Set some additional light-weight parameters in the 'variant param pack' op.SetOpVariantParamAttrPtr<double>(CUDNN_SCALAR_DOUBLE_BN_EPSILON, &param_.eps); // Now add additional prep needed only for train_op_: if (ctx.is_train) { Tensor<gpu, 1, DTypeParam> save_mean = out_data[bn_stats_finalize::kMean] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); Tensor<gpu, 1, DTypeParam> save_inv_var = out_data[bn_stats_finalize::kInvStdDev] .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s); // Set data pointers in the 'variant param pack' op.SetOpVariantParamAttrPtr(CUDNN_PTR_YSUM, sum.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_YSQSUM, sum_squares.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_SAVED_MEAN, save_mean.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_SAVED_INVSTD, save_inv_var.dptr_); // Set some additional light-weight parameters in the 'variant param pack' double avg_factor = 1.0 - param_.momentum; int64_t elem_count = static_cast<int64_t>(param_.elem_count); op.SetOpVariantParamAttrPtr(CUDNN_SCALAR_INT64_T_BN_ACCUMULATION_COUNT, &elem_count); op.SetOpVariantParamAttrPtr(CUDNN_SCALAR_DOUBLE_BN_EXP_AVG_FACTOR, &avg_factor); } // Finally, launch op op.Execute(s->dnn_handle_); // See if copies are required for gamma->gamma_out and beta->beta_out if (req.size() > static_cast<size_t>(bn_stats_finalize::kGammaOut)) { switch (req[bn_stats_finalize::kGammaOut]) { case kWriteInplace: case kNullOp: break; // Nothing to do case kWriteTo: // Copy is only needed when the framework cannot do kWriteInPlace, e.g. where the I/O's // of the op correspond to the I/O's of the symbol (as it might in testing). CopyDTypeParamTensor(out_data[bn_stats_finalize::kGammaOut], in_data[bn_stats_finalize::kGamma], ctx); break; default: LOG(FATAL) << "BNStatsFinalize::Forward(): Unexpected req[] for pass-thru gamma: " << req[bn_stats_finalize::kGammaOut]; } } if (req.size() > static_cast<size_t>(bn_stats_finalize::kBetaOut)) { switch (req[bn_stats_finalize::kBetaOut]) { case kWriteInplace: case kNullOp: break; // Nothing to do case kWriteTo: // Copy is only needed when the framework cannot do kWriteInPlace, e.g. where the I/O's // of the op correspond to the I/O's of the symbol (as it might in testing). CopyDTypeParamTensor(out_data[bn_stats_finalize::kBetaOut], in_data[bn_stats_finalize::kBeta], ctx); break; default: LOG(FATAL) << "BNStatsFinalize::Forward(): Unexpected req[] for pass-thru beta: " << req[bn_stats_finalize::kBetaOut]; } } }) #endif // CUDNN_VERSION >= 7600 } void Backward(const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; // Only incoming gradients (== number of fwd outputs) are inputs of the backward node. CHECK_EQ(inputs.size(), static_cast<size_t>(bn_stats_finalize::kNumOutputs)); // Only outgoing gradients (== number of non-aux fwd inputs) are outputs of the backward node. CHECK_EQ(outputs.size(), static_cast<size_t>(bn_stats_finalize::kNumNonAuxInputs)); CHECK_EQ(req.size(), static_cast<size_t>(bn_stats_finalize::kNumNonAuxInputs)); // We normally expect to see kWriteInplace here, so we will do nothing. // See if copies are required for d_gamma and d_beta switch (req[bn_stats_finalize::kGamma]) { case kWriteInplace: case kNullOp: break; // Nothing to do case kWriteTo: // Copy is only needed when the framework cannot do kWriteInPlace, e.g. where the I/O's // of the op correspond to the I/O's of the symbol (as it might in testing). CopyDTypeParamTensor(outputs[bn_stats_finalize::kGamma], inputs[bn_stats_finalize::kGammaOut], ctx); break; default: LOG(FATAL) << "BNStatsFinalize::Backward(): Unexpected req[] for gamma gradient: " << req[bn_stats_finalize::kGamma]; } switch (req[bn_stats_finalize::kBeta]) { case kWriteInplace: case kNullOp: break; // Nothing to do case kWriteTo: // Copy is only needed when the framework cannot do kWriteInPlace, e.g. where the I/O's // of the op correspond to the I/O's of the symbol (as it might in testing). CopyDTypeParamTensor(outputs[bn_stats_finalize::kBeta], inputs[bn_stats_finalize::kBetaOut], ctx); break; default: LOG(FATAL) << "BNStatsFinalize::Backward(): Unexpected req[] for beta gradient: " << req[bn_stats_finalize::kBeta]; } } /*! * \brief Returns whether the cuDNN library version supports the batchnorm * operation described by `param`. */ static bool Supports(const BNStatsFinalizeParam &param, int dtype, const TShape &shape) { return !param.use_global_stats; } private: // Converts a TBlob to a 1D dptr of the specifed size, checking for that it's contiguous. DType *Get1dPtr(const TBlob &tb, int size, mshadow::Stream<gpu> *s) { mshadow::Tensor<gpu, 1, DType> data = tb.get<gpu, 1, DType>(s); CHECK_EQ(data.CheckContiguous(), true); return data.dptr_; } // Copy a tensor of 'DTypeParam' (typically float). Used as a fallback if no kWriteInplace. void CopyDTypeParamTensor(const TBlob &to_data, const TBlob &from_data, const OpContext &ctx) { using namespace mshadow; mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); CHECK_EQ(from_data.Size(), to_data.Size()) << "Copy requested of unequal-sized Tensors"; MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, { Tensor<gpu, 1, DTypeParam> from = from_data .get_with_shape<gpu, 1, DTypeParam>(Shape1(from_data.Size()), s); Tensor<gpu, 1, DTypeParam> to = to_data .get_with_shape<gpu, 1, DTypeParam>(Shape1(to_data.Size()), s); CUDA_CALL(cudaMemcpyAsync(to.dptr_, from.dptr_, from_data.Size() * sizeof(DTypeParam), cudaMemcpyDeviceToDevice, mshadow::Stream<gpu>::GetStream(s))); }) } void InitDescriptors(const TShape &shape) { using namespace mshadow; init_shape_ = shape; dim_ = init_shape_.ndim(); CHECK_EQ(dim_, 1) << "Expecting 1D 'sum' input."; int c = init_shape_[0]; cudnnTensorFormat_t format = CUDNN_TENSOR_NHWC; CUDNN_CALL(cudnnSetTensor4dDescriptor(out_desc_, format, dtype_, 1, c, 1, 1)); MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, { CUDNN_CALL(cudnnSetTensor4dDescriptor(in_desc_, format, DataType<DTypeParam>::kCudnnFlag, 1, c, 1, 1)); }) } int dim_; cudnnDataType_t dtype_; int dtype_param_; cudnnTensorDescriptor_t out_desc_, in_desc_; BNStatsFinalizeParam param_; // The shape used to init the descriptors of the op TShape init_shape_; #if CUDNN_VERSION >= 7600 // New 'fused op' for BN stats finalize forward (training mode) CuDNNCommonOp train_op_; // New 'fused op' for BN stats finalize forward (inference mode) CuDNNCommonOp inference_op_; #endif }; #endif // defined(__CUDACC__) #endif // MXNET_USE_CUDNN == 1 } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_CUDNN_CUDNN_BN_STATS_FINALIZE_INL_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/replay_games.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 <stdio.h> #include <memory> #include <string> #include <vector> #include "base/commandlineflags.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread_safe_queue.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/color.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/position.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/sgf.h" DEFINE_string(sgf_dir, "", "Directory to load SGF games from."); DEFINE_int32(num_threads, 8, "Number of worker threads."); namespace minigo { namespace { enum class GameOverReason { kMoveLimit, kPassPass, kWholeBoardPassAlive, }; struct GameInfo { GameInfo(GameOverReason game_over_reason, int whole_board_pass_alive_move, int game_length) : game_over_reason(game_over_reason), whole_board_pass_alive_move(whole_board_pass_alive_move), game_length(game_length) {} GameOverReason game_over_reason; int whole_board_pass_alive_move; int game_length; }; GameInfo ProcessSgf(const std::string& path) { std::string contents; MG_CHECK(file::ReadFile(path, &contents)); sgf::Ast ast; MG_CHECK(ast.Parse(contents)); std::vector<std::unique_ptr<sgf::Node>> trees; MG_CHECK(sgf::GetTrees(ast, &trees)); Position position(Color::kBlack); Coord prev_move = Coord::kInvalid; const auto& moves = trees[0]->ExtractMainLine(); auto num_moves = static_cast<int>(moves.size()); for (int i = 0; i < num_moves; ++i) { const auto& move = moves[i]; MG_CHECK(position.legal_move(move.c)); position.PlayMove(move.c); if (move.c == Coord::kPass && prev_move == Coord::kPass) { return GameInfo(GameOverReason::kPassPass, 0, num_moves); } if (position.CalculateWholeBoardPassAlive()) { return GameInfo(GameOverReason::kWholeBoardPassAlive, i, num_moves); } prev_move = move.c; } return GameInfo(GameOverReason::kMoveLimit, 0, num_moves); } void Run() { std::vector<std::string> basenames; MG_CHECK(file::ListDir(FLAGS_sgf_dir, &basenames)); ThreadSafeQueue<std::string> work_queue; for (const auto& basename : basenames) { work_queue.Push(basename); } ThreadSafeQueue<GameInfo> game_info_queue; std::vector<std::unique_ptr<LambdaThread>> threads; for (int i = 0; i < FLAGS_num_threads; ++i) { threads.push_back(absl::make_unique<LambdaThread>([&]() { std::string basename; while (work_queue.TryPop(&basename)) { auto path = file::JoinPath(FLAGS_sgf_dir, basename); game_info_queue.Push(ProcessSgf(path)); } })); threads.back()->Start(); } int num_pass_pass_games = 0; int num_move_limit_games = 0; int num_whole_board_pass_alive_games = 0; int game_length_sum = 0; int whole_board_pass_alive_sum = 0; int min_whole_board_pass_alive = kN * kN * 2; for (size_t i = 0; i < basenames.size(); ++i) { auto info = game_info_queue.Pop(); switch (info.game_over_reason) { case GameOverReason::kMoveLimit: num_move_limit_games += 1; break; case GameOverReason::kPassPass: num_pass_pass_games += 1; break; case GameOverReason::kWholeBoardPassAlive: num_whole_board_pass_alive_games += 1; game_length_sum += info.game_length; whole_board_pass_alive_sum += info.whole_board_pass_alive_move; if (info.whole_board_pass_alive_move < min_whole_board_pass_alive) { min_whole_board_pass_alive = info.whole_board_pass_alive_move; } break; } } for (auto& t : threads) { t->Join(); } MG_LOG(INFO) << "total games: " << basenames.size(); MG_LOG(INFO) << "num move limit games: " << num_move_limit_games; MG_LOG(INFO) << "num whole-board pass-alive games: " << num_whole_board_pass_alive_games; MG_LOG(INFO) << "num pass-pass games: " << num_pass_pass_games; MG_LOG(INFO) << "mean whole-board pass-alive move number: " << static_cast<float>(whole_board_pass_alive_sum) / static_cast<float>(num_whole_board_pass_alive_games); MG_LOG(INFO) << "mean length of whole-board pass-alive games: " << static_cast<float>(game_length_sum) / static_cast<float>(num_whole_board_pass_alive_games); MG_LOG(INFO) << "min whole-board pass-alive move number: " << min_whole_board_pass_alive; } } // namespace } // namespace minigo int main(int argc, char* argv[]) { minigo::Init(&argc, &argv); minigo::Run(); return 0; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/rnn/cfg.cpp<|end_filename|> /******************************************************************************* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mkldnn_common.hpp" #include "rnn/rnn.hpp" namespace rnn { /* cfgs definition arrays: input, states, c_states, weights_input, weights_states, bias, dst_last_iteration, dst_c_last_iteration, dst_last_layer, dst_diff_input, dst_diff_states, dst_c_diff_states, dst_diff_weights_input, dst_diff_weights_states, dst_diff_bias, diff_last_iteration, diff_c_last_iteration, diff_last_layer, params: {data_type, min, max, f_min, f_max, f_mean, f_stddev, eps} */ const int int_max_exact = 1 << 24; const _dt_conf_t conf_f32 = { { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //input { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //c_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //weights_input { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //weights_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //bias { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_last_iteration { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_c_last_iteration { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_last_layer { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_diff_input { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_diff_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_diff_c_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_diff_weights_input { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_diff_weights_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_diff_bias { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //diff_last_iteration { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //diff_c_last_iteration { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //diff_last_layer }; const _dt_conf_t conf_u8u8u8u8 = { { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 5.f, 0. }, //input { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 5.f, 0. }, //states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //c_states { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_input { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 0. }, //bias { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 10.f, 0. }, //dst_iter { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-4 }, //dst_c_last_iteration { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 10.f, 0. }, //dst_layer }; const _dt_conf_t conf_u8u8u8f32 = { { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 5.f, 0. }, //input { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 5.f, 0. }, //states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //c_states { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_input { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 0. }, //bias { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 10.f, 0. }, //dst_iter { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-4 }, //dst_c_last_iteration { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //dst_last_layer }; const _dt_conf_t conf_f32u8f32u8 = { { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 5.f, 0. }, //input { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.05f, 1e-5 }, //states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //c_states { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_input { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 0. }, //bias { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 1e-5 }, //dst_iter { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-4 }, //dst_c_last_iteration { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 10.f, 0. }, //dst_layer }; const _dt_conf_t conf_f32u8f32f32 = { { mkldnn_u8, 0, UINT8_MAX, 0, 127, 64.f, 5.f, 0. }, //input { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.05f, 1e-5 }, //states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-5 }, //c_states { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_input { mkldnn_s8, INT8_MIN, INT8_MAX, -63, 63, 0.f, 10.f, 0. }, //weights_states { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 0. }, //bias { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 1e-5 }, //dst_iter { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.001f, 1e-4 }, //dst_c_last_iteration { mkldnn_f32, -int_max_exact, int_max_exact, -1, 1, 0.f, 0.01f, 1e-5 }, //dst_last_layer }; const int int_max_exact_half = 1<<11; const _dt_conf_t conf_f16 = { #define EPS 1e-1 { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, { mkldnn_f16, -int_max_exact_half, int_max_exact_half, -4, 4, 0, 1, EPS }, #undef EPS }; const dt_conf_t *str2cfg(const char *str) { #define CASE(cfg) \ if (!strcasecmp(STRINGIFY(cfg), str)) \ return CONCAT2(conf_, cfg) CASE(f32); CASE(f16); CASE(u8u8u8u8); CASE(u8u8u8f32); CASE(f32u8f32u8); CASE(f32u8f32f32); #undef CASE []() { SAFE(FAIL, CRIT); return 0; }(); return (const dt_conf_t *)1; } const char *cfg2str(const dt_conf_t *cfg) { #define CASE(_cfg) \ if (cfg == CONCAT2(conf_, _cfg)) \ return STRINGIFY(_cfg) CASE(f32); CASE(f16); CASE(u8u8u8u8); CASE(u8u8u8f32); CASE(f32u8f32u8); CASE(f32u8f32f32); #undef CASE []() { SAFE(FAIL, CRIT); return 0; }(); return NULL; } } // namespace rnn <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/cudnn/cudnn_common_op.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file cudnn_common_op.h * \brief * \author <NAME> */ #ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_COMMON_OP_H_ #define MXNET_OPERATOR_NN_CUDNN_CUDNN_COMMON_OP_H_ #include <cudnn.h> #include <dmlc/logging.h> #include <vector> namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 #if defined(__CUDACC__) // A wrapper using RAII principles to simplify use of the cuDNN 'fused op' API. class CuDNNCommonOp { public: explicit CuDNNCommonOp(cudnnFusedOps_t op_id) : plan_created_(false) { // New 'fused op' descriptor creation CUDNN_CALL(cudnnCreateFusedOpsPlan(&op_, op_id)); CUDNN_CALL(cudnnCreateFusedOpsConstParamPack(&op_const_params_, op_id)); CUDNN_CALL(cudnnCreateFusedOpsVariantParamPack(&op_variant_params_, op_id)); } ~CuDNNCommonOp() { // New 'fused op' descriptor destruction CUDNN_CALL(cudnnDestroyFusedOpsVariantParamPack(op_variant_params_)); CUDNN_CALL(cudnnDestroyFusedOpsConstParamPack(op_const_params_)); CUDNN_CALL(cudnnDestroyFusedOpsPlan(op_)); } // Launch op void Execute(cudnnHandle_t cudnn_handle) { CHECK(plan_created_) << "CuDNNCommonOp exec requested without a valid 'plan', need: " << "<set const params>, GetWorkspaceSizeBytes(), Execute()."; CUDNN_CALL(cudnnFusedOpsExecute(cudnn_handle, op_, op_variant_params_)); } // Set a 'fused op' const param pack attribute given a descriptor (an opaque pointer) 'T'. template <typename T> void SetOpConstParamDesc(cudnnFusedOpsConstParamLabel_t param_label, T *param_ptr) { CUDNN_CALL(cudnnSetFusedOpsConstParamPackAttribute(op_const_params_, param_label, param_ptr)); // Setting a 'const param pack' value invalidates the plan plan_created_ = false; } // Set multiple 'fused op' const param pack attribute given a descriptor (an opaque pointer) 'T'. template <typename T> void SetOpConstParamDesc(const std::vector<cudnnFusedOpsConstParamLabel_t> &param_labels, T *param_ptr) { for (auto param_label : param_labels) SetOpConstParamDesc(param_label, param_ptr); } // Set a 'fused op' const param pack attribute given a value of param 'T'. template <typename T> void SetOpConstParamAttr(cudnnFusedOpsConstParamLabel_t param_label, T param) { CUDNN_CALL(cudnnSetFusedOpsConstParamPackAttribute(op_const_params_, param_label, &param)); // Setting a 'const param pack' value invalidates the plan plan_created_ = false; } // Set multiple 'fused op' const param pack attributes given a value a param 'T'. template <typename T> void SetOpConstParamAttr(const std::vector<cudnnFusedOpsConstParamLabel_t> &param_labels, T param) { for (auto param_label : param_labels) SetOpConstParamAttr(param_label, param); } // Set a 'fused op' variant param pack attribute given a reference to a param 'T'. template <typename T> void SetOpVariantParamAttrPtr(cudnnFusedOpsVariantParamLabel_t param_label, T *param_ptr) { CUDNN_CALL(cudnnSetFusedOpsVariantParamPackAttribute(op_variant_params_, param_label, param_ptr)); } // Set multiple 'fused op' const param pack attributes given a reference to a param 'T'. template <typename T> void SetOpVariantParamAttrPtr(const std::vector<cudnnFusedOpsVariantParamLabel_t> &param_labels, const T *param_ptr) { for (auto param_label : param_labels) SetOpVariantParamAttrPtr(param_label, param_ptr); } // Get the workspace, which requires 'making a plan'. This is required before Execute(). size_t GetWorkspaceSizeInBytes(cudnnHandle_t cudnn_handle) { size_t workspace_bytes = 0U; CUDNN_CALL(cudnnMakeFusedOpsPlan(cudnn_handle, op_, op_const_params_, &workspace_bytes)); plan_created_ = true; return workspace_bytes; } private: // `plan_created_` flag that helps diagnose an improper use. Need the sequence: // <set const params> // GetWorkspaceSizeInBytes() (a.k.a. 'make plan') // <set variant params> // Execute() bool plan_created_; // Op using the generalized 'FusedOp' API of cuDNN cudnnFusedOpsPlan_t op_; // Op parameters are held in a 'const parameter pack' of descriptor info and data ptr alignments. cudnnFusedOpsConstParamPack_t op_const_params_; // Op I/O data ptrs and 'light-weight' parameters are held in a 'variant param pack' cudnnFusedOpsVariantParamPack_t op_variant_params_; }; #endif // defined(__CUDACC__) #endif // MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_CUDNN_CUDNN_COMMON_OP_H_ <|start_filename|>Fujitsu/benchmarks/transformer/implementations/gx_V100x8_ngc20.06_pytorch/gx_V100x8_ngc20.06_pytorch_implementation_closed.json<|end_filename|> { "Starting weights filename?":"N/A", "Weight transformations?":"No", "Weight data type(s)":"fp16", "Input data type(s)":"fp16", "Retraining":"No", } <|start_filename|>Inspur/systems/nf5488_mxnet.json<|end_filename|> { "submitter": "Inspur", "division": "closed", "status": "on-premise", "system_name": "NF5488", "number_of_nodes": "1", "host_processors_per_node": "2", "host_processor_model_name": "AMD EPYC 7742", "hardware": "8 GPUs", "host_processor_core_count": "128", "host_processor_vcpu_count": "0", "host_processor_frequency": "2.25GHz", "host_processor_caches": "L1: 32KB I + 32KB D per core, L2: 512KB per core, L3: 256MB per chip", "host_processor_interconnect": "4x 16GT/s xGMI", "host_memory_capacity": "1TB", "host_storage_type": "SSD", "host_storage_capacity": "11.7TB + 447.1GB", "host_networking": "", "host_networking_topology": "", "host_memory_configuration": "16 x 64GB DDR4 2933 MT/s", "accelerators_per_node": "8", "accelerator_model_name": "NVIDIA A100", "accelerator_host_interconnect": "PCIe Gen4 64 GB/s", "accelerator_frequency": "1410MHz", "accelerator_on-chip_memories": "L1: 108x192KB, L2: 40MB per chip", "accelerator_memory_configuration": "HBM2", "accelerator_memory_capacity": "40G", "accelerator_interconnect": "NVLink 600 GB/s", "accelerator_interconnect_topology": "Mesh", "cooling": "Air-cooled", "hw_notes": "", "framework": "MXNet 1.6.0", "other_software_stack": "cuda 11.0, cudnn 8.0.1, cublas 11.0, gcc 7.5.0", "operating_system": "Ubuntu 18.04.2 LTS (Bionic Beaver)", "sw_notes": "" } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_avx_kernel_b0_sgemm_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_f32.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx_kernel_b0_sgemm_kern::jit_avx_kernel_b0_sgemm_kern() : jit_generator(nullptr, F32_COMPUTE_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define K rdx #define A r8 #define B r9 #define C rcx #define LDC r10 #define AA r15 #define I r11 #define J r12 #define H rax #define AO rbx #define BO rbp #define CO1 r13 #define CO2 r14 #define OLD_C 8+stacksize+rsp #define OLD_LDC 16+stacksize+rsp #else #define M rcx #define N rdx #define K r8 #define A rdi #define B rsi #define C r9 #define LDC r10 #define AA r15 #define I r11 #define J r12 #define H rax #define AO rbx #define BO rbp #define CO1 r13 #define CO2 r14 #define OLD_A 40+stacksize+rsp #define OLD_B 48+stacksize+rsp #define OLD_C 56+stacksize+rsp #define OLD_LDC 64+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l100c; Xbyak::Label l1068; Xbyak::Label l122c; Xbyak::Label l1248; Xbyak::Label l140c; Xbyak::Label l1418; Xbyak::Label l1488; Xbyak::Label l14e4; Xbyak::Label l154c; Xbyak::Label l1710; Xbyak::Label l1720; Xbyak::Label l18e4; Xbyak::Label l18f0; Xbyak::Label l1960; Xbyak::Label l19a4; Xbyak::Label l1a0c; Xbyak::Label l1bd0; Xbyak::Label l1bdc; Xbyak::Label l1da0; Xbyak::Label l1dac; Xbyak::Label l1e1c; Xbyak::Label l1e58; Xbyak::Label l1e5c; Xbyak::Label l1e8c; Xbyak::Label l1ee8; Xbyak::Label l20b0; Xbyak::Label l20cc; Xbyak::Label l2294; Xbyak::Label l22a0; Xbyak::Label l2310; Xbyak::Label l236c; Xbyak::Label l23d4; Xbyak::Label l259c; Xbyak::Label l25ac; Xbyak::Label l2774; Xbyak::Label l2780; Xbyak::Label l27f0; Xbyak::Label l2834; Xbyak::Label l289c; Xbyak::Label l2a0; Xbyak::Label l2a64; Xbyak::Label l2a70; Xbyak::Label l2bc; Xbyak::Label l2c38; Xbyak::Label l2c44; Xbyak::Label l2cb4; Xbyak::Label l2cf0; Xbyak::Label l2cf4; Xbyak::Label l2d24; Xbyak::Label l2d80; Xbyak::Label l2f48; Xbyak::Label l2f64; Xbyak::Label l312c; Xbyak::Label l3138; Xbyak::Label l31a8; Xbyak::Label l3204; Xbyak::Label l326c; Xbyak::Label l3434; Xbyak::Label l3444; Xbyak::Label l360c; Xbyak::Label l3618; Xbyak::Label l3688; Xbyak::Label l36cc; Xbyak::Label l3734; Xbyak::Label l38fc; Xbyak::Label l3908; Xbyak::Label l3ad0; Xbyak::Label l3adc; Xbyak::Label l3b4c; Xbyak::Label l3b88; Xbyak::Label l3b8c; Xbyak::Label l3bbc; Xbyak::Label l3c18; Xbyak::Label l3de0; Xbyak::Label l3df8; Xbyak::Label l3fc0; Xbyak::Label l3fcc; Xbyak::Label l403c; Xbyak::Label l4098; Xbyak::Label l4100; Xbyak::Label l42c8; Xbyak::Label l42d8; Xbyak::Label l44a0; Xbyak::Label l44ac; Xbyak::Label l451c; Xbyak::Label l4560; Xbyak::Label l45c8; Xbyak::Label l4790; Xbyak::Label l479c; Xbyak::Label l48c; Xbyak::Label l4964; Xbyak::Label l4970; Xbyak::Label l498; Xbyak::Label l49e0; Xbyak::Label l4a1c; Xbyak::Label l4a20; Xbyak::Label l50; Xbyak::Label l508; Xbyak::Label l5b0; Xbyak::Label l618; Xbyak::Label l74; Xbyak::Label l7e8; Xbyak::Label l7f8; Xbyak::Label l9c8; Xbyak::Label l9d4; Xbyak::Label la44; Xbyak::Label lac4; Xbyak::Label lb2c; Xbyak::Label lcfc; Xbyak::Label ld0; Xbyak::Label ld08; Xbyak::Label led8; Xbyak::Label lee4; Xbyak::Label lf54; Xbyak::Label lfc8; Xbyak::Label lfdc; preamble(); auto stacksize = get_size_of_abi_save_regs(); #ifdef _WIN32 mov(A, ptr[OLD_A]); mov(B, ptr[OLD_B]); #endif mov(C, ptr[OLD_C]); mov(LDC, ptr[OLD_LDC]); mov(M, qword[M]); mov(N, qword[N]); mov(K, qword[K]); shl(LDC, 0x2); sub(A, -128); sub(B, -128); mov(J, M); cmp(J, 0x10); jl(lfdc, T_NEAR); align(4); L(l50); mov(AA, K); imul(AA, AA, 0x40); add(AA, A); mov(CO1, C); add(C, 0x40); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l5b0, T_NEAR); align(4); L(l74); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l48c, T_NEAR); sub(H, 0x1e); jle(l2a0, T_NEAR); align(4); L(ld0); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(ld0, T_NEAR); align(4); L(l2a0); prefetcht0(byte[CO1+0x3c]); prefetcht0(byte[CO1+LDC*1+0x3c]); prefetcht0(byte[CO2+0x3c]); prefetcht0(byte[CO2+LDC*1+0x3c]); add(H, 0x1e); align(4); L(l2bc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2bc, T_NEAR); align(4); L(l48c); mov(H, K); and_(H, 0x3); je(l508, T_NEAR); align(4); L(l498); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x40]); vmovups(ymm1, yword[AO-0x20]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -64); sub(BO, -16); dec(H); jg(l498, T_NEAR); align(4); L(l508); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vblendps(ymm0, ymm12, ymm13, 0xaa); vblendps(ymm1, ymm12, ymm13, 0x55); vblendps(ymm2, ymm14, ymm15, 0xaa); vblendps(ymm3, ymm14, ymm15, 0x55); vblendps(ymm12, ymm0, ymm2, 0xcc); vblendps(ymm13, ymm1, ymm3, 0xcc); vblendps(ymm14, ymm0, ymm2, 0x33); vblendps(ymm15, ymm1, ymm3, 0x33); vmovups(yword[CO1+0x0], ymm8); vmovups(yword[CO1+0x20], ymm12); vmovups(yword[CO1+LDC*1+0x0], ymm9); vmovups(yword[CO1+LDC*1+0x20], ymm13); vmovups(yword[CO2], ymm10); vmovups(yword[CO2+0x20], ymm14); vmovups(yword[CO2+LDC*1], ymm11); vmovups(yword[CO2+LDC*1+0x20], ymm15); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l74, T_NEAR); align(4); L(l5b0); test(I, 0x2); jle(lac4, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l9c8, T_NEAR); sub(H, 0x1e); jle(l7e8, T_NEAR); align(4); L(l618); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l618, T_NEAR); align(4); L(l7e8); prefetcht0(byte[CO1+0x3c]); prefetcht0(byte[CO1+LDC*1+0x3c]); add(H, 0x1e); align(4); L(l7f8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l7f8, T_NEAR); align(4); L(l9c8); mov(H, K); and_(H, 0x3); je(la44, T_NEAR); align(4); L(l9d4); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x40]); vmovups(ymm1, yword[AO-0x20]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -64); sub(BO, -8); dec(H); jg(l9d4, T_NEAR); align(4); L(la44); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vblendps(ymm0, ymm12, ymm13, 0xaa); vblendps(ymm1, ymm12, ymm13, 0x55); vblendps(ymm2, ymm14, ymm15, 0xaa); vblendps(ymm3, ymm14, ymm15, 0x55); vblendps(ymm12, ymm0, ymm2, 0xcc); vblendps(ymm13, ymm1, ymm3, 0xcc); vblendps(ymm14, ymm0, ymm2, 0x33); vblendps(ymm15, ymm1, ymm3, 0x33); vmovups(yword[CO1+0x0], ymm8); vmovups(yword[CO1+0x20], ymm12); vmovups(yword[CO1+LDC*1+0x0], ymm9); vmovups(yword[CO1+LDC*1+0x20], ymm13); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(lac4); test(I, 0x1); jle(lfc8, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(led8, T_NEAR); sub(H, 0x1e); jle(lcfc, T_NEAR); align(4); L(lb2c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(lb2c, T_NEAR); align(4); L(lcfc); prefetcht0(byte[CO1+0x3c]); add(H, 0x1e); align(4); L(ld08); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(ld08, T_NEAR); align(4); L(led8); mov(H, K); and_(H, 0x3); je(lf54, T_NEAR); align(4); L(lee4); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x40]); vmovups(ymm1, yword[AO-0x20]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -64); sub(BO, -4); dec(H); jg(lee4, T_NEAR); align(4); L(lf54); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vblendps(ymm0, ymm12, ymm13, 0xaa); vblendps(ymm1, ymm12, ymm13, 0x55); vblendps(ymm2, ymm14, ymm15, 0xaa); vblendps(ymm3, ymm14, ymm15, 0x55); vblendps(ymm12, ymm0, ymm2, 0xcc); vblendps(ymm13, ymm1, ymm3, 0xcc); vblendps(ymm14, ymm0, ymm2, 0x33); vblendps(ymm15, ymm1, ymm3, 0x33); vmovups(yword[CO1+0x0], ymm8); vmovups(yword[CO1+0x20], ymm12); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(lfc8); mov(A, AO); sub(J, 0x10); cmp(J, 0x10); jge(l50, T_NEAR); align(4); L(lfdc); test(J, 0x8); jle(l1e5c, T_NEAR); mov(AA, K); imul(AA, AA, 0x20); add(AA, A); mov(CO1, C); add(C, 0x20); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l14e4, T_NEAR); align(4); L(l100c); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l140c, T_NEAR); sub(H, 0x1e); jle(l122c, T_NEAR); align(4); L(l1068); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1068, T_NEAR); align(4); L(l122c); prefetcht0(byte[CO1+0x1c]); prefetcht0(byte[CO1+LDC*1+0x1c]); prefetcht0(byte[CO2+0x1c]); prefetcht0(byte[CO2+LDC*1+0x1c]); add(H, 0x1e); align(4); L(l1248); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1248, T_NEAR); align(4); L(l140c); mov(H, K); and_(H, 0x3); je(l1488, T_NEAR); align(4); L(l1418); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x60]); vmovups(ymm1, yword[AO-0x40]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -32); sub(BO, -16); dec(H); jg(l1418, T_NEAR); align(4); L(l1488); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(yword[CO1+0x0], ymm8); vmovups(yword[CO1+LDC*1+0x0], ymm9); vmovups(yword[CO2], ymm10); vmovups(yword[CO2+LDC*1], ymm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l100c, T_NEAR); align(4); L(l14e4); test(I, 0x2); jle(l19a4, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l18e4, T_NEAR); sub(H, 0x1e); jle(l1710, T_NEAR); align(4); L(l154c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l154c, T_NEAR); align(4); L(l1710); prefetcht0(byte[CO1+0x1c]); prefetcht0(byte[CO1+LDC*1+0x1c]); add(H, 0x1e); align(4); L(l1720); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1720, T_NEAR); align(4); L(l18e4); mov(H, K); and_(H, 0x3); je(l1960, T_NEAR); align(4); L(l18f0); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x60]); vmovups(ymm1, yword[AO-0x40]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -32); sub(BO, -8); dec(H); jg(l18f0, T_NEAR); align(4); L(l1960); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(yword[CO1+0x0], ymm8); vmovups(yword[CO1+LDC*1+0x0], ymm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l19a4); test(I, 0x1); jle(l1e58, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1da0, T_NEAR); sub(H, 0x1e); jle(l1bd0, T_NEAR); align(4); L(l1a0c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1a0c, T_NEAR); align(4); L(l1bd0); prefetcht0(byte[CO1+0x1c]); add(H, 0x1e); align(4); L(l1bdc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1bdc, T_NEAR); align(4); L(l1da0); mov(H, K); and_(H, 0x3); je(l1e1c, T_NEAR); align(4); L(l1dac); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x60]); vmovups(ymm1, yword[AO-0x40]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -32); sub(BO, -4); dec(H); jg(l1dac, T_NEAR); align(4); L(l1e1c); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(yword[CO1+0x0], ymm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l1e58); mov(A, AO); align(4); L(l1e5c); test(J, 0x4); jle(l2cf4, T_NEAR); mov(AA, K); imul(AA, AA, 0x10); add(AA, A); mov(CO1, C); add(C, 0x10); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l236c, T_NEAR); align(4); L(l1e8c); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2294, T_NEAR); sub(H, 0x1e); jle(l20b0, T_NEAR); align(4); L(l1ee8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1ee8, T_NEAR); align(4); L(l20b0); prefetcht0(byte[CO1+0xc]); prefetcht0(byte[CO1+LDC*1+0xc]); prefetcht0(byte[CO2+0xc]); prefetcht0(byte[CO2+LDC*1+0xc]); add(H, 0x1e); align(4); L(l20cc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l20cc, T_NEAR); align(4); L(l2294); mov(H, K); and_(H, 0x3); je(l2310, T_NEAR); align(4); L(l22a0); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x70]); vmovups(ymm1, yword[AO-0x50]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -16); sub(BO, -16); dec(H); jg(l22a0, T_NEAR); align(4); L(l2310); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(xword[CO1+0x0], xmm8); vmovups(xword[CO1+LDC*1+0x0], xmm9); vmovups(xword[CO2], xmm10); vmovups(xword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l1e8c, T_NEAR); align(4); L(l236c); test(I, 0x2); jle(l2834, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2774, T_NEAR); sub(H, 0x1e); jle(l259c, T_NEAR); align(4); L(l23d4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l23d4, T_NEAR); align(4); L(l259c); prefetcht0(byte[CO1+0xc]); prefetcht0(byte[CO1+LDC*1+0xc]); add(H, 0x1e); align(4); L(l25ac); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l25ac, T_NEAR); align(4); L(l2774); mov(H, K); and_(H, 0x3); je(l27f0, T_NEAR); align(4); L(l2780); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x70]); vmovups(ymm1, yword[AO-0x50]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -16); sub(BO, -8); dec(H); jg(l2780, T_NEAR); align(4); L(l27f0); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(xword[CO1+0x0], xmm8); vmovups(xword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l2834); test(I, 0x1); jle(l2cf0, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2c38, T_NEAR); sub(H, 0x1e); jle(l2a64, T_NEAR); align(4); L(l289c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l289c, T_NEAR); align(4); L(l2a64); prefetcht0(byte[CO1+0xc]); add(H, 0x1e); align(4); L(l2a70); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2a70, T_NEAR); align(4); L(l2c38); mov(H, K); and_(H, 0x3); je(l2cb4, T_NEAR); align(4); L(l2c44); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x70]); vmovups(ymm1, yword[AO-0x50]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -16); sub(BO, -4); dec(H); jg(l2c44, T_NEAR); align(4); L(l2cb4); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(xword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l2cf0); mov(A, AO); align(4); L(l2cf4); test(J, 0x2); jle(l3b8c, T_NEAR); mov(AA, K); imul(AA, AA, 0x8); add(AA, A); mov(CO1, C); add(C, 0x8); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l3204, T_NEAR); align(4); L(l2d24); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l312c, T_NEAR); sub(H, 0x1e); jle(l2f48, T_NEAR); align(4); L(l2d80); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2d80, T_NEAR); align(4); L(l2f48); prefetcht0(byte[CO1+0x4]); prefetcht0(byte[CO1+LDC*1+0x4]); prefetcht0(byte[CO2+0x4]); prefetcht0(byte[CO2+LDC*1+0x4]); add(H, 0x1e); align(4); L(l2f64); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2f64, T_NEAR); align(4); L(l312c); mov(H, K); and_(H, 0x3); je(l31a8, T_NEAR); align(4); L(l3138); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x78]); vmovups(ymm1, yword[AO-0x58]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -8); sub(BO, -16); dec(H); jg(l3138, T_NEAR); align(4); L(l31a8); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovlps(qword[CO1+0x0], xmm8); vmovlps(qword[CO1+LDC*1+0x0], xmm9); vmovlps(qword[CO2], xmm10); vmovlps(qword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l2d24, T_NEAR); align(4); L(l3204); test(I, 0x2); jle(l36cc, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l360c, T_NEAR); sub(H, 0x1e); jle(l3434, T_NEAR); align(4); L(l326c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l326c, T_NEAR); align(4); L(l3434); prefetcht0(byte[CO1+0x4]); prefetcht0(byte[CO1+LDC*1+0x4]); add(H, 0x1e); align(4); L(l3444); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3444, T_NEAR); align(4); L(l360c); mov(H, K); and_(H, 0x3); je(l3688, T_NEAR); align(4); L(l3618); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x78]); vmovups(ymm1, yword[AO-0x58]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -8); sub(BO, -8); dec(H); jg(l3618, T_NEAR); align(4); L(l3688); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovlps(qword[CO1+0x0], xmm8); vmovlps(qword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l36cc); test(I, 0x1); jle(l3b88, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l3ad0, T_NEAR); sub(H, 0x1e); jle(l38fc, T_NEAR); align(4); L(l3734); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3734, T_NEAR); align(4); L(l38fc); prefetcht0(byte[CO1+0x4]); add(H, 0x1e); align(4); L(l3908); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3908, T_NEAR); align(4); L(l3ad0); mov(H, K); and_(H, 0x3); je(l3b4c, T_NEAR); align(4); L(l3adc); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x78]); vmovups(ymm1, yword[AO-0x58]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -8); sub(BO, -4); dec(H); jg(l3adc, T_NEAR); align(4); L(l3b4c); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovlps(qword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l3b88); mov(A, AO); align(4); L(l3b8c); test(J, 0x1); jle(l4a20, T_NEAR); mov(AA, K); imul(AA, AA, 0x4); add(AA, A); mov(CO1, C); add(C, 0x4); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l4098, T_NEAR); align(4); L(l3bbc); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l3fc0, T_NEAR); sub(H, 0x1e); jle(l3de0, T_NEAR); align(4); L(l3c18); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3c18, T_NEAR); align(4); L(l3de0); prefetcht0(byte[CO1+0x0]); prefetcht0(byte[CO1+LDC*1+0x0]); prefetcht0(byte[CO2]); prefetcht0(byte[CO2+LDC*1]); add(H, 0x1e); align(4); L(l3df8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3df8, T_NEAR); align(4); L(l3fc0); mov(H, K); and_(H, 0x3); je(l403c, T_NEAR); align(4); L(l3fcc); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x7c]); vmovups(ymm1, yword[AO-0x5c]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -4); sub(BO, -16); dec(H); jg(l3fcc, T_NEAR); align(4); L(l403c); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovss(dword[CO1+0x0], xmm8); vmovss(dword[CO1+LDC*1+0x0], xmm9); vmovss(dword[CO2], xmm10); vmovss(dword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l3bbc, T_NEAR); align(4); L(l4098); test(I, 0x2); jle(l4560, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l44a0, T_NEAR); sub(H, 0x1e); jle(l42c8, T_NEAR); align(4); L(l4100); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l4100, T_NEAR); align(4); L(l42c8); prefetcht0(byte[CO1+0x0]); prefetcht0(byte[CO1+LDC*1+0x0]); add(H, 0x1e); align(4); L(l42d8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l42d8, T_NEAR); align(4); L(l44a0); mov(H, K); and_(H, 0x3); je(l451c, T_NEAR); align(4); L(l44ac); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x7c]); vmovups(ymm1, yword[AO-0x5c]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -4); sub(BO, -8); dec(H); jg(l44ac, T_NEAR); align(4); L(l451c); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovss(dword[CO1+0x0], xmm8); vmovss(dword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l4560); test(I, 0x1); jle(l4a1c, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l4964, T_NEAR); sub(H, 0x1e); jle(l4790, T_NEAR); align(4); L(l45c8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l45c8, T_NEAR); align(4); L(l4790); prefetcht0(byte[CO1+0x0]); add(H, 0x1e); align(4); L(l479c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l479c, T_NEAR); align(4); L(l4964); mov(H, K); and_(H, 0x3); je(l49e0, T_NEAR); align(4); L(l4970); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x7c]); vmovups(ymm1, yword[AO-0x5c]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -4); sub(BO, -4); dec(H); jg(l4970, T_NEAR); align(4); L(l49e0); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovss(dword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l4a1c); mov(A, AO); align(4); L(l4a20); postamble(); } outLocalLabel(); #undef M #undef N #undef K #undef A #undef B #undef C #undef LDC #undef AA #undef I #undef J #undef H #undef AO #undef BO #undef CO1 #undef CO2 #ifdef _WIN32 #undef OLD_A #undef OLD_B #endif #undef OLD_C #undef OLD_LDC } } } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_sse41_kernel_sgemm_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_f32.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_sse41_kernel_sgemm_kern::jit_sse41_kernel_sgemm_kern() : jit_generator(nullptr, F32_COMPUTE_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define K rdx #define A r8 #define B r9 #define C rcx #define LDC r10 #define AA r15 #define I r11 #define J r12 #define H rax #define AO rbx #define BO rbp #define CO1 r13 #define CO2 r14 #define OLD_C 8+stacksize+rsp #define OLD_LDC 16+stacksize+rsp #else #define M rcx #define N rdx #define K r8 #define A rdi #define B rsi #define C r9 #define LDC r10 #define AA r15 #define I r11 #define J r12 #define H rax #define AO rbx #define BO rbp #define CO1 r13 #define CO2 r14 #define OLD_A 40+stacksize+rsp #define OLD_B 48+stacksize+rsp #define OLD_C 56+stacksize+rsp #define OLD_LDC 64+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l101c; Xbyak::Label l1114; Xbyak::Label l1130; Xbyak::Label l1228; Xbyak::Label l1234; Xbyak::Label l1280; Xbyak::Label l130c; Xbyak::Label l136c; Xbyak::Label l1468; Xbyak::Label l1478; Xbyak::Label l1574; Xbyak::Label l1580; Xbyak::Label l15d0; Xbyak::Label l1624; Xbyak::Label l1684; Xbyak::Label l1780; Xbyak::Label l178c; Xbyak::Label l1888; Xbyak::Label l1894; Xbyak::Label l18e4; Xbyak::Label l1928; Xbyak::Label l192c; Xbyak::Label l195c; Xbyak::Label l19b0; Xbyak::Label l1aac; Xbyak::Label l1ac8; Xbyak::Label l1bc4; Xbyak::Label l1bd0; Xbyak::Label l1c20; Xbyak::Label l1cb0; Xbyak::Label l1d14; Xbyak::Label l1e14; Xbyak::Label l1e24; Xbyak::Label l1f24; Xbyak::Label l1f30; Xbyak::Label l1f80; Xbyak::Label l1fd4; Xbyak::Label l2038; Xbyak::Label l2138; Xbyak::Label l2144; Xbyak::Label l2244; Xbyak::Label l2250; Xbyak::Label l22a0; Xbyak::Label l22e4; Xbyak::Label l22e8; Xbyak::Label l2318; Xbyak::Label l236c; Xbyak::Label l2468; Xbyak::Label l2480; Xbyak::Label l257c; Xbyak::Label l2588; Xbyak::Label l25d8; Xbyak::Label l266c; Xbyak::Label l26d0; Xbyak::Label l27c; Xbyak::Label l27d0; Xbyak::Label l27e0; Xbyak::Label l28e0; Xbyak::Label l28ec; Xbyak::Label l293c; Xbyak::Label l298; Xbyak::Label l2994; Xbyak::Label l29f8; Xbyak::Label l2af8; Xbyak::Label l2b04; Xbyak::Label l2c04; Xbyak::Label l2c10; Xbyak::Label l2c60; Xbyak::Label l2ca4; Xbyak::Label l2ca8; Xbyak::Label l444; Xbyak::Label l450; Xbyak::Label l4bc; Xbyak::Label l50; Xbyak::Label l5c0; Xbyak::Label l62c; Xbyak::Label l74; Xbyak::Label l7dc; Xbyak::Label l7ec; Xbyak::Label l99c; Xbyak::Label l9a8; Xbyak::Label la18; Xbyak::Label lab4; Xbyak::Label lb20; Xbyak::Label lcd0; Xbyak::Label lcdc; Xbyak::Label ld0; Xbyak::Label le8c; Xbyak::Label le98; Xbyak::Label lf08; Xbyak::Label lf84; Xbyak::Label lf98; Xbyak::Label lfc8; preamble(); auto stacksize = get_size_of_abi_save_regs(); #ifdef _WIN32 mov(A, ptr[OLD_A]); mov(B, ptr[OLD_B]); #endif mov(C, ptr[OLD_C]); mov(LDC, ptr[OLD_LDC]); mov(M, qword[M]); mov(N, qword[N]); mov(K, qword[K]); shl(LDC, 0x2); sub(A, -128); sub(B, -128); mov(J, M); cmp(J, 0x8); jl(lf98, T_NEAR); align(4); L(l50); mov(AA, K); imul(AA, AA, 0x20); add(AA, A); mov(CO1, C); add(C, 0x20); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l5c0, T_NEAR); align(4); L(l74); lea(CO2, ptr[CO1+LDC*2+0x0]); movups(xmm0, xword[A-0x80]); xorps(xmm8, xmm8); movups(xmm1, xword[A-0x70]); xorps(xmm9, xmm9); movups(xmm2, xword[A-0x60]); xorps(xmm10, xmm10); movups(xmm3, xword[A-0x50]); xorps(xmm11, xmm11); movaps(xmm4, xword[BO-0x80]); xorps(xmm12, xmm12); movaps(xmm5, xword[BO-0x70]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l444, T_NEAR); sub(H, 0x1e); jle(l27c, T_NEAR); align(4); L(ld0); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x30]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO-0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm4, 0xb1); prefetcht0(byte[AO+0x1c0]); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO]); mulps(xmm7, xmm1); movups(xmm1, xword[AO+0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); addps(xmm14, xmm7); add(AA, 0x8); sub(BO, -64); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO+0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO+0x30]); sub(AO, -128); addps(xmm11, xmm6); addps(xmm15, xmm7); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(ld0, T_NEAR); align(4); L(l27c); prefetcht0(byte[CO1+0x1c]); prefetcht0(byte[CO1+LDC*1+0x1c]); prefetcht0(byte[CO2+0x1c]); prefetcht0(byte[CO2+LDC*1+0x1c]); add(H, 0x1e); align(4); L(l298); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x30]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO-0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm4, 0xb1); prefetcht0(byte[AO+0x1c0]); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO]); mulps(xmm7, xmm1); movups(xmm1, xword[AO+0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); addps(xmm14, xmm7); add(AA, 0x8); sub(BO, -64); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO+0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO+0x30]); sub(AO, -128); addps(xmm11, xmm6); addps(xmm15, xmm7); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l298, T_NEAR); align(4); L(l444); mov(H, K); and_(H, 0x3); je(l4bc, T_NEAR); align(4); L(l450); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x70]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x50]); addps(xmm11, xmm6); addps(xmm15, xmm7); sub(AO, -32); sub(BO, -16); dec(H); jg(l450, T_NEAR); align(4); L(l4bc); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movaps(xmm10, xmm1); movaps(xmm11, xmm1); shufps(xmm10, xmm0, 0xcc); shufps(xmm11, xmm0, 0x66); movaps(xmm0, xmm12); unpcklpd(xmm12, xmm13); unpckhpd(xmm0, xmm13); movaps(xmm1, xmm14); unpckhpd(xmm14, xmm15); unpcklpd(xmm1, xmm15); movaps(xmm13, xmm12); shufps(xmm12, xmm14, 0xcc); shufps(xmm13, xmm14, 0x66); movaps(xmm14, xmm1); movaps(xmm15, xmm1); shufps(xmm14, xmm0, 0xcc); shufps(xmm15, xmm0, 0x66); movups(xmm0, xword[CO1+0x0]); addps(xmm8, xmm0); movups(xword[CO1+0x0], xmm8); movups(xmm1, xword[CO1+0x10]); addps(xmm12, xmm1); movups(xword[CO1+0x10], xmm12); movups(xmm0, xword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movups(xword[CO1+LDC*1+0x0], xmm9); movups(xmm1, xword[CO1+LDC*1+0x10]); addps(xmm13, xmm1); movups(xword[CO1+LDC*1+0x10], xmm13); movups(xmm0, xword[CO2]); addps(xmm10, xmm0); movups(xword[CO2], xmm10); movups(xmm1, xword[CO2+0x10]); addps(xmm14, xmm1); movups(xword[CO2+0x10], xmm14); movups(xmm0, xword[CO2+LDC*1]); addps(xmm11, xmm0); movups(xword[CO2+LDC*1], xmm11); movups(xmm1, xword[CO2+LDC*1+0x10]); addps(xmm15, xmm1); movups(xword[CO2+LDC*1+0x10], xmm15); lea(CO1, ptr[CO1+LDC*4+0x0]); lea(CO2, ptr[CO2+LDC*4]); sub(I, 0x4); cmp(I, 0x4); jge(l74, T_NEAR); align(4); L(l5c0); test(I, 0x2); jle(lab4, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movups(xmm0, xword[A-0x80]); xorps(xmm8, xmm8); movups(xmm1, xword[A-0x70]); xorps(xmm9, xmm9); movups(xmm2, xword[A-0x60]); xorps(xmm10, xmm10); movups(xmm3, xword[A-0x50]); xorps(xmm11, xmm11); movddup(xmm4, qword[BO-0x80]); xorps(xmm12, xmm12); movddup(xmm5, qword[BO-0x78]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l99c, T_NEAR); sub(H, 0x1e); jle(l7dc, T_NEAR); align(4); L(l62c); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x30]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO-0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm4, 0xb1); prefetcht0(byte[AO+0x1c0]); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO]); mulps(xmm7, xmm1); movups(xmm1, xword[AO+0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); addps(xmm14, xmm7); add(AA, 0x8); sub(BO, -32); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO+0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO+0x30]); sub(AO, -128); addps(xmm11, xmm6); addps(xmm15, xmm7); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l62c, T_NEAR); align(4); L(l7dc); prefetcht0(byte[CO1+0x1c]); prefetcht0(byte[CO1+LDC*1+0x1c]); add(H, 0x1e); align(4); L(l7ec); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x30]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO-0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm4, 0xb1); prefetcht0(byte[AO+0x1c0]); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO]); mulps(xmm7, xmm1); movups(xmm1, xword[AO+0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); addps(xmm14, xmm7); add(AA, 0x8); sub(BO, -32); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO+0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO+0x30]); sub(AO, -128); addps(xmm11, xmm6); addps(xmm15, xmm7); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l7ec, T_NEAR); align(4); L(l99c); mov(H, K); and_(H, 0x3); je(la18, T_NEAR); align(4); L(l9a8); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x78]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x50]); addps(xmm11, xmm6); addps(xmm15, xmm7); sub(AO, -32); sub(BO, -8); dec(H); jg(l9a8, T_NEAR); align(4); L(la18); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movaps(xmm0, xmm12); unpcklpd(xmm12, xmm13); unpckhpd(xmm0, xmm13); movaps(xmm1, xmm14); unpckhpd(xmm14, xmm15); unpcklpd(xmm1, xmm15); movaps(xmm13, xmm12); shufps(xmm12, xmm14, 0xcc); shufps(xmm13, xmm14, 0x66); movups(xmm0, xword[CO1+0x0]); addps(xmm8, xmm0); movups(xword[CO1+0x0], xmm8); movups(xmm1, xword[CO1+0x10]); addps(xmm12, xmm1); movups(xword[CO1+0x10], xmm12); movups(xmm0, xword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movups(xword[CO1+LDC*1+0x0], xmm9); movups(xmm1, xword[CO1+LDC*1+0x10]); addps(xmm13, xmm1); movups(xword[CO1+LDC*1+0x10], xmm13); lea(CO1, ptr[CO1+LDC*2+0x0]); lea(CO2, ptr[CO2+LDC*2]); align(4); L(lab4); test(I, 0x1); jle(lf84, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movups(xmm0, xword[A-0x80]); xorps(xmm8, xmm8); movups(xmm1, xword[A-0x70]); xorps(xmm9, xmm9); movups(xmm2, xword[A-0x60]); xorps(xmm10, xmm10); movups(xmm3, xword[A-0x50]); xorps(xmm11, xmm11); movss(xmm4, dword[BO-0x80]); xorps(xmm12, xmm12); movss(xmm5, dword[BO-0x7c]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(le8c, T_NEAR); sub(H, 0x1e); jle(lcd0, T_NEAR); align(4); L(lb20); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x30]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO-0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm4, 0xb1); prefetcht0(byte[AO+0x1c0]); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO]); mulps(xmm7, xmm1); movups(xmm1, xword[AO+0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); addps(xmm14, xmm7); add(AA, 0x8); sub(BO, -16); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO+0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO+0x30]); sub(AO, -128); addps(xmm11, xmm6); addps(xmm15, xmm7); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(lb20, T_NEAR); align(4); L(lcd0); prefetcht0(byte[CO1+0x1c]); add(H, 0x1e); align(4); L(lcdc); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x30]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO-0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm4, 0xb1); prefetcht0(byte[AO+0x1c0]); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO]); mulps(xmm7, xmm1); movups(xmm1, xword[AO+0x10]); addps(xmm11, xmm6); addps(xmm15, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm8, xmm5); addps(xmm12, xmm7); pshufd(xmm5, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm2); mulps(xmm7, xmm3); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm5, 0xb1); movaps(xmm7, xmm5); mulps(xmm5, xmm2); mulps(xmm7, xmm3); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); addps(xmm14, xmm7); add(AA, 0x8); sub(BO, -16); movaps(xmm7, xmm6); mulps(xmm6, xmm2); movups(xmm2, xword[AO+0x20]); mulps(xmm7, xmm3); movups(xmm3, xword[AO+0x30]); sub(AO, -128); addps(xmm11, xmm6); addps(xmm15, xmm7); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(lcdc, T_NEAR); align(4); L(le8c); mov(H, K); and_(H, 0x3); je(lf08, T_NEAR); align(4); L(le98); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm8, xmm4); addps(xmm12, xmm7); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); mulps(xmm7, xmm1); addps(xmm9, xmm6); addps(xmm13, xmm7); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); mulps(xmm7, xmm1); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x7c]); addps(xmm14, xmm7); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); mulps(xmm7, xmm1); movups(xmm1, xword[AO-0x50]); addps(xmm11, xmm6); addps(xmm15, xmm7); sub(AO, -32); sub(BO, -4); dec(H); jg(le98, T_NEAR); align(4); L(lf08); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movaps(xmm0, xmm12); unpcklpd(xmm12, xmm13); unpckhpd(xmm0, xmm13); movaps(xmm1, xmm14); unpckhpd(xmm14, xmm15); unpcklpd(xmm1, xmm15); movaps(xmm13, xmm12); shufps(xmm12, xmm14, 0xcc); shufps(xmm13, xmm14, 0x66); movups(xmm0, xword[CO1+0x0]); addps(xmm8, xmm0); movups(xword[CO1+0x0], xmm8); movups(xmm1, xword[CO1+0x10]); addps(xmm12, xmm1); movups(xword[CO1+0x10], xmm12); lea(CO1, ptr[CO1+LDC*1+0x0]); lea(CO2, ptr[CO2+LDC*1]); align(4); L(lf84); mov(A, AO); sub(J, 0x8); cmp(J, 0x8); jge(l50, T_NEAR); align(4); L(lf98); test(J, 0x4); jle(l192c, T_NEAR); mov(AA, K); imul(AA, AA, 0x10); add(AA, A); mov(CO1, C); add(C, 0x10); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l130c, T_NEAR); align(4); L(lfc8); lea(CO2, ptr[CO1+LDC*2+0x0]); movups(xmm0, xword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movups(xmm2, xword[A-0x70]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movaps(xmm4, xword[BO-0x80]); xorps(xmm12, xmm12); movaps(xmm5, xword[BO-0x70]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1228, T_NEAR); sub(H, 0x1e); jle(l1114, T_NEAR); align(4); L(l101c); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x50]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); add(AA, 0x8); sub(BO, -64); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x30]); sub(AO, -64); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l101c, T_NEAR); align(4); L(l1114); prefetcht0(byte[CO1+0xc]); prefetcht0(byte[CO1+LDC*1+0xc]); prefetcht0(byte[CO2+0xc]); prefetcht0(byte[CO2+LDC*1+0xc]); add(H, 0x1e); align(4); L(l1130); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x50]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); add(AA, 0x8); sub(BO, -64); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x30]); sub(AO, -64); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l1130, T_NEAR); align(4); L(l1228); mov(H, K); and_(H, 0x3); je(l1280, T_NEAR); align(4); L(l1234); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x70]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x70]); addps(xmm11, xmm6); sub(AO, -16); sub(BO, -16); dec(H); jg(l1234, T_NEAR); align(4); L(l1280); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movaps(xmm10, xmm1); movaps(xmm11, xmm1); shufps(xmm10, xmm0, 0xcc); shufps(xmm11, xmm0, 0x66); movups(xmm0, xword[CO1+0x0]); addps(xmm8, xmm0); movups(xword[CO1+0x0], xmm8); movups(xmm0, xword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movups(xword[CO1+LDC*1+0x0], xmm9); movups(xmm0, xword[CO2]); addps(xmm10, xmm0); movups(xword[CO2], xmm10); movups(xmm0, xword[CO2+LDC*1]); addps(xmm11, xmm0); movups(xword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); lea(CO2, ptr[CO2+LDC*4]); sub(I, 0x4); cmp(I, 0x4); jge(lfc8, T_NEAR); align(4); L(l130c); test(I, 0x2); jle(l1624, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movups(xmm0, xword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movups(xmm2, xword[A-0x70]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movddup(xmm4, qword[BO-0x80]); xorps(xmm12, xmm12); movddup(xmm5, qword[BO-0x78]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1574, T_NEAR); sub(H, 0x1e); jle(l1468, T_NEAR); align(4); L(l136c); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x50]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); add(AA, 0x8); sub(BO, -32); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x30]); sub(AO, -64); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l136c, T_NEAR); align(4); L(l1468); prefetcht0(byte[CO1+0xc]); prefetcht0(byte[CO1+LDC*1+0xc]); add(H, 0x1e); align(4); L(l1478); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x50]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); add(AA, 0x8); sub(BO, -32); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x30]); sub(AO, -64); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l1478, T_NEAR); align(4); L(l1574); mov(H, K); and_(H, 0x3); je(l15d0, T_NEAR); align(4); L(l1580); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x78]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x70]); addps(xmm11, xmm6); sub(AO, -16); sub(BO, -8); dec(H); jg(l1580, T_NEAR); align(4); L(l15d0); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movups(xmm0, xword[CO1+0x0]); addps(xmm8, xmm0); movups(xword[CO1+0x0], xmm8); movups(xmm0, xword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movups(xword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); lea(CO2, ptr[CO2+LDC*2]); align(4); L(l1624); test(I, 0x1); jle(l1928, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movups(xmm0, xword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movups(xmm2, xword[A-0x70]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movss(xmm4, dword[BO-0x80]); xorps(xmm12, xmm12); movss(xmm5, dword[BO-0x7c]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1888, T_NEAR); sub(H, 0x1e); jle(l1780, T_NEAR); align(4); L(l1684); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x50]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); add(AA, 0x8); sub(BO, -16); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x30]); sub(AO, -64); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l1684, T_NEAR); align(4); L(l1780); prefetcht0(byte[CO1+0xc]); add(H, 0x1e); align(4); L(l178c); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x50]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x40]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); add(AA, 0x8); sub(BO, -16); mulps(xmm6, xmm2); movups(xmm2, xword[AO-0x30]); sub(AO, -64); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l178c, T_NEAR); align(4); L(l1888); mov(H, K); and_(H, 0x3); je(l18e4, T_NEAR); align(4); L(l1894); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x7c]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movups(xmm0, xword[AO-0x70]); addps(xmm11, xmm6); sub(AO, -16); sub(BO, -4); dec(H); jg(l1894, T_NEAR); align(4); L(l18e4); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movups(xmm0, xword[CO1+0x0]); addps(xmm8, xmm0); movups(xword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); lea(CO2, ptr[CO2+LDC*1]); align(4); L(l1928); mov(A, AO); align(4); L(l192c); test(J, 0x2); jle(l22e8, T_NEAR); mov(AA, K); imul(AA, AA, 0x8); add(AA, A); mov(CO1, C); add(C, 0x8); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l1cb0, T_NEAR); align(4); L(l195c); lea(CO2, ptr[CO1+LDC*2+0x0]); movsd(xmm0, qword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movsd(xmm2, qword[A-0x78]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movaps(xmm4, xword[BO-0x80]); xorps(xmm12, xmm12); movaps(xmm5, xword[BO-0x70]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1bc4, T_NEAR); sub(H, 0x1e); jle(l1aac, T_NEAR); align(4); L(l19b0); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x68]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); add(AA, 0x8); sub(BO, -64); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x58]); sub(AO, -32); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l19b0, T_NEAR); align(4); L(l1aac); prefetcht0(byte[CO1+0x4]); prefetcht0(byte[CO1+LDC*1+0x4]); prefetcht0(byte[CO2+0x4]); prefetcht0(byte[CO2+LDC*1+0x4]); add(H, 0x1e); align(4); L(l1ac8); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x68]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); add(AA, 0x8); sub(BO, -64); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x58]); sub(AO, -32); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l1ac8, T_NEAR); align(4); L(l1bc4); mov(H, K); and_(H, 0x3); je(l1c20, T_NEAR); align(4); L(l1bd0); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x70]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x78]); addps(xmm11, xmm6); sub(AO, -8); sub(BO, -16); dec(H); jg(l1bd0, T_NEAR); align(4); L(l1c20); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movaps(xmm10, xmm1); movaps(xmm11, xmm1); shufps(xmm10, xmm0, 0xcc); shufps(xmm11, xmm0, 0x66); movsd(xmm0, qword[CO1+0x0]); addps(xmm8, xmm0); movlps(qword[CO1+0x0], xmm8); movsd(xmm0, qword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movlps(qword[CO1+LDC*1+0x0], xmm9); movsd(xmm0, qword[CO2]); addps(xmm10, xmm0); movlps(qword[CO2], xmm10); movsd(xmm0, qword[CO2+LDC*1]); addps(xmm11, xmm0); movlps(qword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); lea(CO2, ptr[CO2+LDC*4]); sub(I, 0x4); cmp(I, 0x4); jge(l195c, T_NEAR); align(4); L(l1cb0); test(I, 0x2); jle(l1fd4, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movsd(xmm0, qword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movsd(xmm2, qword[A-0x78]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movddup(xmm4, qword[BO-0x80]); xorps(xmm12, xmm12); movddup(xmm5, qword[BO-0x78]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1f24, T_NEAR); sub(H, 0x1e); jle(l1e14, T_NEAR); align(4); L(l1d14); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x68]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); add(AA, 0x8); sub(BO, -32); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x58]); sub(AO, -32); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l1d14, T_NEAR); align(4); L(l1e14); prefetcht0(byte[CO1+0x4]); prefetcht0(byte[CO1+LDC*1+0x4]); add(H, 0x1e); align(4); L(l1e24); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x68]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); add(AA, 0x8); sub(BO, -32); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x58]); sub(AO, -32); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l1e24, T_NEAR); align(4); L(l1f24); mov(H, K); and_(H, 0x3); je(l1f80, T_NEAR); align(4); L(l1f30); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x78]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x78]); addps(xmm11, xmm6); sub(AO, -8); sub(BO, -8); dec(H); jg(l1f30, T_NEAR); align(4); L(l1f80); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movsd(xmm0, qword[CO1+0x0]); addps(xmm8, xmm0); movlps(qword[CO1+0x0], xmm8); movsd(xmm0, qword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movlps(qword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); lea(CO2, ptr[CO2+LDC*2]); align(4); L(l1fd4); test(I, 0x1); jle(l22e4, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movsd(xmm0, qword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movsd(xmm2, qword[A-0x78]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movss(xmm4, dword[BO-0x80]); xorps(xmm12, xmm12); movss(xmm5, dword[BO-0x7c]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2244, T_NEAR); sub(H, 0x1e); jle(l2138, T_NEAR); align(4); L(l2038); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x68]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); add(AA, 0x8); sub(BO, -16); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x58]); sub(AO, -32); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l2038, T_NEAR); align(4); L(l2138); prefetcht0(byte[CO1+0x4]); add(H, 0x1e); align(4); L(l2144); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x68]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x60]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); add(AA, 0x8); sub(BO, -16); mulps(xmm6, xmm2); movsd(xmm2, qword[AO-0x58]); sub(AO, -32); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l2144, T_NEAR); align(4); L(l2244); mov(H, K); and_(H, 0x3); je(l22a0, T_NEAR); align(4); L(l2250); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x7c]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movsd(xmm0, qword[AO-0x78]); addps(xmm11, xmm6); sub(AO, -8); sub(BO, -4); dec(H); jg(l2250, T_NEAR); align(4); L(l22a0); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movsd(xmm0, qword[CO1+0x0]); addps(xmm8, xmm0); movlps(qword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); lea(CO2, ptr[CO2+LDC*1]); align(4); L(l22e4); mov(A, AO); align(4); L(l22e8); test(J, 0x1); jle(l2ca8, T_NEAR); mov(AA, K); imul(AA, AA, 0x4); add(AA, A); mov(CO1, C); add(C, 0x4); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l266c, T_NEAR); align(4); L(l2318); lea(CO2, ptr[CO1+LDC*2+0x0]); movss(xmm0, dword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movss(xmm2, dword[A-0x7c]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movaps(xmm4, xword[BO-0x80]); xorps(xmm12, xmm12); movaps(xmm5, xword[BO-0x70]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l257c, T_NEAR); sub(H, 0x1e); jle(l2468, T_NEAR); align(4); L(l236c); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x78]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x74]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); add(AA, 0x8); sub(BO, -64); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x6c]); sub(AO, -16); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l236c, T_NEAR); align(4); L(l2468); prefetcht0(byte[CO1+0x0]); prefetcht0(byte[CO1+LDC*1+0x0]); prefetcht0(byte[CO2]); prefetcht0(byte[CO2+LDC*1]); add(H, 0x1e); align(4); L(l2480); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x60]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x78]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x50]); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x74]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x40]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movaps(xmm5, xword[BO-0x30]); add(AA, 0x8); sub(BO, -64); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x6c]); sub(AO, -16); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l2480, T_NEAR); align(4); L(l257c); mov(H, K); and_(H, 0x3); je(l25d8, T_NEAR); align(4); L(l2588); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movaps(xmm4, xword[BO-0x70]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x7c]); addps(xmm11, xmm6); sub(AO, -4); sub(BO, -16); dec(H); jg(l2588, T_NEAR); align(4); L(l25d8); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movaps(xmm10, xmm1); movaps(xmm11, xmm1); shufps(xmm10, xmm0, 0xcc); shufps(xmm11, xmm0, 0x66); movss(xmm0, dword[CO1+0x0]); addps(xmm8, xmm0); movss(dword[CO1+0x0], xmm8); movss(xmm0, dword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movss(dword[CO1+LDC*1+0x0], xmm9); movss(xmm0, dword[CO2]); addps(xmm10, xmm0); movss(dword[CO2], xmm10); movss(xmm0, dword[CO2+LDC*1]); addps(xmm11, xmm0); movss(dword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); lea(CO2, ptr[CO2+LDC*4]); sub(I, 0x4); cmp(I, 0x4); jge(l2318, T_NEAR); align(4); L(l266c); test(I, 0x2); jle(l2994, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movss(xmm0, dword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movss(xmm2, dword[A-0x7c]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movddup(xmm4, qword[BO-0x80]); xorps(xmm12, xmm12); movddup(xmm5, qword[BO-0x78]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l28e0, T_NEAR); sub(H, 0x1e); jle(l27d0, T_NEAR); align(4); L(l26d0); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x78]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x74]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); add(AA, 0x8); sub(BO, -32); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x6c]); sub(AO, -16); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l26d0, T_NEAR); align(4); L(l27d0); prefetcht0(byte[CO1+0x0]); prefetcht0(byte[CO1+LDC*1+0x0]); add(H, 0x1e); align(4); L(l27e0); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x70]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x78]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x68]); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x74]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x60]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movddup(xmm5, qword[BO-0x58]); add(AA, 0x8); sub(BO, -32); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x6c]); sub(AO, -16); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l27e0, T_NEAR); align(4); L(l28e0); mov(H, K); and_(H, 0x3); je(l293c, T_NEAR); align(4); L(l28ec); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movddup(xmm4, qword[BO-0x78]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x7c]); addps(xmm11, xmm6); sub(AO, -4); sub(BO, -8); dec(H); jg(l28ec, T_NEAR); align(4); L(l293c); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movss(xmm0, dword[CO1+0x0]); addps(xmm8, xmm0); movss(dword[CO1+0x0], xmm8); movss(xmm0, dword[CO1+LDC*1+0x0]); addps(xmm9, xmm0); movss(dword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); lea(CO2, ptr[CO2+LDC*2]); align(4); L(l2994); test(I, 0x1); jle(l2ca4, T_NEAR); lea(CO2, ptr[CO1+LDC*2+0x0]); movss(xmm0, dword[A-0x80]); xorps(xmm8, xmm8); xorps(xmm9, xmm9); movss(xmm2, dword[A-0x7c]); xorps(xmm10, xmm10); xorps(xmm11, xmm11); movss(xmm4, dword[BO-0x80]); xorps(xmm12, xmm12); movss(xmm5, dword[BO-0x7c]); xorps(xmm13, xmm13); xorps(xmm14, xmm14); xorps(xmm15, xmm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2c04, T_NEAR); sub(H, 0x1e); jle(l2af8, T_NEAR); align(4); L(l29f8); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x78]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x74]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); add(AA, 0x8); sub(BO, -16); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x6c]); sub(AO, -16); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l29f8, T_NEAR); align(4); L(l2af8); prefetcht0(byte[CO1+0x0]); add(H, 0x1e); align(4); L(l2b04); prefetcht0(byte[AO+0x180]); prefetcht0(byte[BO+0x100]); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x78]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x78]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x74]); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x74]); addps(xmm11, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x70]); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x70]); addps(xmm11, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm8, xmm5); pshufd(xmm5, xmm6, 0x1b); mulps(xmm6, xmm2); addps(xmm9, xmm6); pshufd(xmm6, xmm5, 0xb1); mulps(xmm5, xmm2); addps(xmm10, xmm5); movss(xmm5, dword[BO-0x6c]); add(AA, 0x8); sub(BO, -16); mulps(xmm6, xmm2); movss(xmm2, dword[AO-0x6c]); sub(AO, -16); addps(xmm11, xmm6); prefetcht0(byte[AA-0x78]); sub(H, 0x1); jg(l2b04, T_NEAR); align(4); L(l2c04); mov(H, K); and_(H, 0x3); je(l2c60, T_NEAR); align(4); L(l2c10); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm8, xmm4); pshufd(xmm4, xmm6, 0x1b); movaps(xmm7, xmm6); mulps(xmm6, xmm0); addps(xmm9, xmm6); pshufd(xmm6, xmm4, 0xb1); movaps(xmm7, xmm4); mulps(xmm4, xmm0); addps(xmm10, xmm4); movss(xmm4, dword[BO-0x7c]); movaps(xmm7, xmm6); mulps(xmm6, xmm0); movss(xmm0, dword[AO-0x7c]); addps(xmm11, xmm6); sub(AO, -4); sub(BO, -4); dec(H); jg(l2c10, T_NEAR); align(4); L(l2c60); movaps(xmm0, xmm8); unpcklpd(xmm8, xmm9); unpckhpd(xmm0, xmm9); movaps(xmm1, xmm10); unpckhpd(xmm10, xmm11); unpcklpd(xmm1, xmm11); movaps(xmm9, xmm8); shufps(xmm8, xmm10, 0xcc); shufps(xmm9, xmm10, 0x66); movss(xmm0, dword[CO1+0x0]); addps(xmm8, xmm0); movss(dword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); lea(CO2, ptr[CO2+LDC*1]); align(4); L(l2ca4); mov(A, AO); align(4); L(l2ca8); postamble(); } outLocalLabel(); #undef M #undef N #undef K #undef A #undef B #undef C #undef LDC #undef AA #undef I #undef J #undef H #undef AO #undef BO #undef CO1 #undef CO2 #ifdef _WIN32 #undef OLD_A #undef OLD_B #endif #undef OLD_C #undef OLD_LDC } } } } <|start_filename|>NVIDIA/benchmarks/ssd/implementations/pytorch/csrc/nhwc/Descriptors.h<|end_filename|> /****************************************************************************** * * Copyright (c) 2018, NVIDIA CORPORATION. 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. * ******************************************************************************/ #pragma once #include "Exceptions.h" #include <ATen/cudnn/cudnn-wrapper.h> #include <ATen/ATen.h> #include <ATen/TensorUtils.h> #include "ATen/cuda/ATenCUDAGeneral.h" #include <cuda.h> #if !defined(TORCH_CUDA_API) && defined(AT_CUDA_API) #define TORCH_CUDA_API AT_CUDA_API #endif namespace at { namespace native { namespace nhwc { // TODO: Add constructors for all of the descriptors inline int dataSize(cudnnDataType_t dataType) { switch (dataType) { case CUDNN_DATA_HALF: return 2; case CUDNN_DATA_FLOAT: return 4; default: return 8; } } // The stride for a size-1 dimensions is not uniquely determined; in // fact, it can be anything you want, because the fact that the // tensor is size 1 at this dimension means that you will never actually // try advancing your pointer by this stride. // // However, CuDNN has a much more stringent requirement on strides: // if you are passing a contiguous input, it better be the case // that the stride for dim i is the product of the sizes of dims // i+1 to the end. This stride is indeed uniquely determined. This // function modifies 'stride' in place so this invariant holds. static inline void fixSizeOneDimStride(int dim, const int *size, int *stride) { int64_t z = 1; for(int d = dim-1; d >= 0; d--) { if (size[d] == 1) { stride[d] = z; } else { z *= size[d]; } } } template <typename T, cudnnStatus_t (*dtor)(T*)> struct DescriptorDeleter { void operator()(T* x) { if (x != nullptr) { CUDNN_CHECK(dtor(x)); } } }; // A generic class for wrapping cuDNN descriptor types. All you need // is to give the underlying type the Descriptor_t points to (usually, // if it's cudnnTensorDescriptor_t it points to cudnnTensorStruct), // the constructor and the destructor. Subclasses are responsible // for defining a set() function to actually set the descriptor. // // Descriptors default construct to a nullptr, and have a descriptor // initialized the first time you call set() or any other initializing // function. template <typename T, cudnnStatus_t (*ctor)(T**), cudnnStatus_t (*dtor)(T*)> class TORCH_CUDA_API Descriptor { public: // TODO: Figure out why const-correctness doesn't work here // Use desc() to access the underlying descriptor pointer in // a read-only fashion. Most client code should use this. // If the descriptor was never initialized, this will return // nullptr. T* desc() const { return desc_.get(); } T* desc() { return desc_.get(); } // Use mut_desc() to access the underlying desciptor pointer // if you intend to modify what it points to (e.g., using // cudnnSetFooDescriptor). This will ensure that the descriptor // is initialized. Code in this file will use this function. T* mut_desc() { init(); return desc_.get(); } protected: void init() { if (desc_ == nullptr) { T* raw_desc; CUDNN_CHECK(ctor(&raw_desc)); desc_.reset(raw_desc); } } private: std::unique_ptr<T, DescriptorDeleter<T, dtor>> desc_; }; class TORCH_CUDA_API TensorDescriptor : public Descriptor<cudnnTensorStruct, &cudnnCreateTensorDescriptor, &cudnnDestroyTensorDescriptor> { public: TensorDescriptor() {} explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) { set(t, pad); } // Note [CuDNN broadcast padding] // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // pad specifies the minimum dimensionality of the tensor descriptor // we produce (it doesn't have anything to do with, e.g., convolution // padding). If 't' is lower-dimensional than 'pad', the remaining // dimensions (on the right) are padded with ones. This doesn't // affect the underlying data layout. This is particularly useful for // dealing with a pecularity of the CuDNN API, which is that broadcasting in CuDNN is // done in two steps: first, the client code is expected to pad out // (the dimensions) input tensors to be the same dimension as the // target broadcast, and then second, CuDNN takes of actually // broadcasting size 1 dimensions. void set(const at::Tensor &t, size_t pad = 0); void set(cudnnDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0); void print(); private: void set(cudnnDataType_t dataType, int dim, int* size, int* stride) { int cudnn_dims[] = {size[0], size[3], size[1], size[2]}; fixSizeOneDimStride(dim, size, stride); // modified as we're hacking in {N, H, W, C} ordering where we shouldn't be CUDNN_CHECK(cudnnSetTensorNdDescriptorEx(mut_desc(), CUDNN_TENSOR_NHWC, dataType, dim, cudnn_dims)); } }; std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d); class FilterDescriptor : public Descriptor<cudnnFilterStruct, &cudnnCreateFilterDescriptor, &cudnnDestroyFilterDescriptor> { public: void set(const at::Tensor &t, int64_t pad = 0); private: void set(cudnnDataType_t dataType, int dim, int* size) { int cudnn_size[] = {size[0], size[3], size[1], size[2]}; CUDNN_CHECK(cudnnSetFilterNdDescriptor(mut_desc(), dataType, CUDNN_TENSOR_NHWC, dim, cudnn_size)); } }; struct TORCH_CUDA_API ConvolutionDescriptor : public Descriptor<cudnnConvolutionStruct, &cudnnCreateConvolutionDescriptor, &cudnnDestroyConvolutionDescriptor> { void set(cudnnDataType_t dataType, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups) { cudnnDataType_t mathType = dataType; if (dataType == CUDNN_DATA_HALF) mathType = CUDNN_DATA_FLOAT; CUDNN_CHECK(cudnnSetConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, CUDNN_CROSS_CORRELATION, mathType)); #if CUDNN_VERSION >= 7000 CUDNN_CHECK(cudnnSetConvolutionGroupCount(mut_desc(), groups)); CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_DEFAULT_MATH)); if(dataType == CUDNN_DATA_HALF) CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_TENSOR_OP_MATH)); #endif } }; union Constant { float f; double d; Constant(cudnnDataType_t dataType, double value) { if (dataType == CUDNN_DATA_HALF || dataType == CUDNN_DATA_FLOAT) { f = (float) value; } else { d = value; } } }; }}} // namespace <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/async/semaphore.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_SEMAPHORE_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_SEMAPHORE_H_ #include "REDACTEDsynchronization/mutex.h" namespace minigo { class Semaphore { public: void Post() { absl::MutexLock lock(&mutex_); ++count_; } void Wait() { mutex_.LockWhen(absl::Condition(this, &Semaphore::is_non_zero)); --count_; mutex_.Unlock(); } private: bool is_non_zero() const EXCLUSIVE_LOCKS_REQUIRED(&mutex_) { return count_ != 0; } absl::Mutex mutex_; int count_ = 0; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_SEMAPHORE_H_ <|start_filename|>NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/vision.h<|end_filename|> // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. // Copyright (c) 2018-2019 NVIDIA CORPORATION. All rights reserved. #pragma once #include <torch/extension.h> at::Tensor SigmoidFocalLoss_forward_cuda( const at::Tensor& logits, const at::Tensor& targets, const int num_classes, const float gamma, const float alpha); at::Tensor SigmoidFocalLoss_backward_cuda( const at::Tensor& logits, const at::Tensor& targets, const at::Tensor& d_losses, const int num_classes, const float gamma, const float alpha); at::Tensor ROIAlign_forward_cuda(const at::Tensor& input, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int sampling_ratio, const bool is_nhwc); at::Tensor ROIAlign_backward_cuda(const at::Tensor& grad, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int batch_size, const int channels, const int height, const int width, const int sampling_ratio, const bool is_nhwc); std::tuple<at::Tensor, at::Tensor> ROIPool_forward_cuda(const at::Tensor& input, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width); at::Tensor ROIPool_backward_cuda(const at::Tensor& grad, const at::Tensor& input, const at::Tensor& rois, const at::Tensor& argmax, const float spatial_scale, const int pooled_height, const int pooled_width, const int batch_size, const int channels, const int height, const int width); at::Tensor nms_cuda(const at::Tensor boxes, float nms_overlap_thresh); at::Tensor compute_flow_cuda(const at::Tensor& boxes, const int height, const int width); at::Tensor generate_mask_targets_cuda(at::Tensor dense_vector, const std::vector<std::vector<at::Tensor>> polygons, const at::Tensor anchors, const int mask_size); at::Tensor box_iou_cuda(at::Tensor box1, at::Tensor box2); std::vector<at::Tensor> box_encode_cuda(at::Tensor boxes, at::Tensor anchors, float wx, float wy, float ww, float wh); at::Tensor match_proposals_cuda(at::Tensor match_quality_matrix, bool include_low_quality_matches, float low_th, float high_th); // initial_pos_mask is the initial positive masks for boxes, 1 if it is kept and 0 otherwise at::Tensor nms_batched_cuda(const at::Tensor boxes_cat, const std::vector<int> n_boxes_vec, const at::Tensor n_boxes, const at::Tensor initial_pos_mask, const float nms_overlap_thresh); namespace rpn { std::vector<at::Tensor> GeneratePreNMSUprightBoxesBatched_cuda( const int num_images, const int A, const int K_max, const int max_anchors, at::Tensor& hw_array, at::Tensor& num_anchors_per_level, at::Tensor& sorted_indices, // topK sorted pre_nms_topn indices at::Tensor& sorted_scores, // topK sorted pre_nms_topn scores [N, A, H, W] at::Tensor& bbox_deltas, // [N, A*4, H, W] (full, unsorted / sliced) at::Tensor& anchors, // input (full, unsorted, unsliced) at::Tensor& image_shapes, // (h, w) of images const int pre_nms_nboxes, const int rpn_min_size, const float bbox_xform_clip_default, const bool correct_transform_coords); } //namespace rpn <|start_filename|>Fujitsu/systems/gx_V100x8_ngc20.06_mxnet.json<|end_filename|> { "submitter":"Fujitsu", "division":"Closed", "status":"available", "system_name":"PRIMERGY GX2570M5", "number_of_nodes":"1", "host_processors_per_node":"2", "host_processor_model_name":"Intel Xeon Platinum 8268", "host_processor_core_count":"48", "host_processor_vcpu_count":"96", "host_processor_frequency":"2900MHz", "host_processor_caches":"L1: 32KB I + 32KB D per core, L2: 1MB I+D per core, L3: 35.75MB I+D per chip", "host_processor_interconnect":"3x 10.6GT/s UPI", "host_memory_capacity":"384GB", "host_storage_type":"SSD+NVMe", "host_storage_capacity":"960GBx2+1500GBx2", "host_networking":"N/A", "host_networking_topology":"N/A", "host_memory_configuration":"12x32GB", "accelerators_per_node":"8", "accelerator_model_name":"Nvidia Tesla V100", "accelerator_host_interconnect":"PCIe 3.0 x16", "accelerator_frequency":"1530MHz", "accelerator_on-chip_memories":"L1: 80x 128KB, L2: 6MB per chip", "accelerator_memory_configuration":"HBM2", "accelerator_memory_capacity":"32GB", "accelerator_interconnect":"6x 25GT/s NVLink", "accelerator_interconnect_topology":"Mesh", "cooling":"Air-cooled", "hw_notes":"none", "framework":"MXNet NGC20.06", "other_software_stack": "cuda 11.0.167, cudnn 8.0.1.13, cublas 11.0.167, gcc 7.5.0", "operating_system":"Ubuntu 18.04.3 LTS", "sw_notes":"none" } <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/x_ops.cc<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "third_party/tensorflow/core/framework/common_shape_fns.h" #include "third_party/tensorflow/core/framework/op.h" #include "third_party/tensorflow/core/framework/shape_inference.h" #include "x_ops_helper.h" namespace tensorflow { namespace { REGISTER_OP("AssertShapeMatch") .Input("x: int32") .Input("y: int32") .Attr("msg: string = ''") .SetShapeFn([](shape_inference::InferenceContext* c) { return Status::OK(); }) .Doc(R"doc( Asserts that shape vector x and y matches. The i-th dimension matches iff x[i] == y[i] || x[i] == -1 || y[i] == -1. x: A shape vector. y: A shape vector. msg: The error message generated when the assertion failed. )doc"); REGISTER_OP("AssertSameDim0") .Input("x: types") .Attr("msg: string = ''") .Attr("types: list(type)") .SetShapeFn([](shape_inference::InferenceContext* c) { return Status::OK(); }) .Doc(R"doc( Asserts that all input tensors are non-scalar and have the same 0-th dim size. x: The list of tensors. msg: The error message generated when the assertion failed. )doc"); REGISTER_OP("RandomPermutationSequence") .Attr("num: int = 1") .Attr("batch: int = 1") .Attr("repeat: bool = false") .Attr("seed: int = 0") .Output("out: int32") .SetIsStateful() .Doc(R"doc( Generate random samples from [0..num-1] without replacements. num: The number of ids. batch: Each output is a vector of size up to batch. Right now, the last batch from one epoch is the only one that can be smaller than a full batch. repeat: If true, this op keep generating random samples after one epoch. If false, this op errors with `tf.errors.OutOfRangeError` when an epoch finishes. seed: The random seed. out: Each output is a vector of size up to batch. )doc"); REGISTER_OP("BestStep") .Output("best_step: int64") .Attr("hist_file: string") .Attr("tol: float = 0.0") .Attr("minimize: bool = true") .Attr("metric: string = \"\"") .SetIsStateful() .Doc(R"doc( Determines the best global step from a history file. best_step: Shape [2]. best_step[0] is scalar value for best global step. best_step[1] is scalar value for last global step. hist_file: A text file containing 'step score' records, or a file pattern that matches tf event files in the format of /path_to_file/events.out.tfevents*. tol: Difference between previous best score and current score must be greater than this amount to trigger update. minimize: If the metric is being minimized. Recorded in hist_file, smaller scores are better if True, and bigger scores are better if False. metric: The name of the metric being tracked. )doc"); REGISTER_OP("BeamSearchStep") .Input("scores: float32") .Input("atten_probs: float32") .Input("best_scores: float32") .Input("cumulative_scores: float32") .Input("in_scores: float32") .Input("in_hyps: int32") .Input("in_prev_hyps: int32") .Input("in_done_hyps: string") .Input("in_atten_probs: float32") .Input("is_last_chunk: bool") .Input("cur_step: int32") .Output("out_best_scores: float32") .Output("out_cumulative_scores: float32") .Output("out_scores: float32") .Output("out_hyps: int32") .Output("out_prev_hyps: int32") .Output("out_done_hyps: string") .Output("out_atten_probs: float32") .Output("all_done: bool") .Attr("eoc_id: int = -1") .Attr("eos_id: int") .Attr("beam_size: float") .Attr("num_hyps_per_beam: int") .Attr("valid_eos_max_logit_delta: float = 5.0") .Attr("local_eos_threshold: float = -100.0") .Attr("merge_paths: bool = false") .Attr("allow_empty_terminated_hyp: bool = true") .Attr("ensure_full_beam: bool = false") .Attr("force_eos_in_last_step: bool = false") .SetShapeFn([](shape_inference::InferenceContext* c) { c->set_output(0, c->input(2)); c->set_output(1, c->input(3)); c->set_output(2, c->input(4)); c->set_output(3, c->input(5)); c->set_output(4, c->input(6)); c->set_output(5, c->input(7)); c->set_output(6, c->input(8)); c->set_output(7, c->Scalar()); return Status::OK(); }) .Doc(R"doc( Move forward one step in beam search. Let "b" be the number of beams, "k" be the number hyps in each beam, "t" be the maximum decoding steps. The following data structures are allocated before the first decoding step and are passed along from cur step to the next step: in_scores A tensor of shape [t, b * k]. in_scores[i, j] is the local score of the j-th hyp at the i-th decoding step. in_hyps A tensor of shape [t, b * k]. in_hyps[i, j] is the token id of the j-th hyp at the i-th decoding step. in_prev_hyps A tensor of shape [t, b * k]. in_prev_hyps[i, j] stores a pointer of the j-th hyp at time step i to the hyp at previous timestep (i - 1). 0 <= in_prev_hyps[i, j] < b * k. in_done_hyps A tensor of shape [t, b * k]. in_done_hyps[i, j] can be either an empty string, or a serialized Hypothesis proto. Terminated hyps are removed from the beam and are moved to the corresponding in_done_hyps slot. in_atten_probs A tensor of shape [t, b * k, s_len]. in_atten_probs[i, j, ...] is the attention probs over the source words for the j-th hyp at the i-th timestep. Those tensors are modified (with content for the cur_step timestep being filled in) within this op invocation and are passed to the corresponding output tensors. is_last_chunk: A tensor of shape [b * k]. Used by neural transducer, determine whether the current hypothesis reaches the last chunk and should treat the next end-of-chunk symbol as end-of-sentence. scores: A matrix of shape [b * k, vocab_size], where b is the number of active beams, and k is the number of hyps in each beam. Local scores for the current timestep. atten_probs: A matrix of shape [b * k, source_len]. Attention probabilities for the current timestep. best_scores: A vector of size [b], best scores of terminated hyps so far in each of the beams. cumulative_scores: A vector of size [b * k]. The cumulative score of each active hyp before the current step. in_scores: As explained above. in_hyps: As explained above. in_prev_hyps: As explained above. in_done_hyps: As explained above. in_atten_probs: As explained above. cur_step: Current step id. out_best_scores: Updated best scores for each of the beams. out_cumulative_scores: A vector of size [b * k]. The cumulative score of the new hyps after the current decoding step. out_scores: As explained above. out_hyps: As explained above. out_prev_hyps: As explained above. out_done_hyps: As explained above. out_atten_probs: As explained above. all_done: A scalar, whether decoding should terminate for all beams. eoc_id: Token id of the special end of chunk token. eos_id: Token id of the special end of sequence token. beam_size: Search terminates if the delta between the scores of the active hyps in a beam and the best scores exceeds this threashold. num_hyps_per_beam: Number of hyps in a beam. valid_eos_max_logit_delta: We allow </s> to terminate a hyp only if its logit is no more than `valid_eos_max_logit_delta` away from the logit of the best candidate. local_eos_threshold: We allow </s> to terminate a hyp if the local score for </s> is greater than local_eos_threshold. merge_paths: If true, hyps which are identical when epsilons are removed will be combined into a single hyp. The probability for that combined hyp will be the sum of the probabilities of the component hyps. This can only be applied for epsilon-emitting models (RNN-T and NT). allow_empty_terminated_hyp: Whether it is okay to consider a hyp that consists only of epsilons as terminated. By default this is true, as an utterance may consist of silence. It should be set to false when EMBR training epsilon-emitting models (e.g., RNN-T), which are prone to emit all-epsilon hyps even in the absence of silence. Note that a hyp that terminates in EOS is not considered empty, so this flag has no effect for non-epsilon-emitting models. ensure_full_beam: If True, we will not set the all_done output to True until we have found 'num_hyps_per_beam' terminated hyps AND no active hyps have a score within 'beam_size' of the best terminated hyp. If False, only the second condition must be satisfied. Generally this should be False unless beam search is being run as part of minimum word error rate training. force_eos_in_last_step: If true, then if decode does not terminate even after (max - 1) steps, eos symbol is injected into the result and partial hypotheses (with a valid eos symbol in the end) are returned. all_done is set to true for these partials. If false, which is the default behavior, empty hypothesis are returned and all_done is set to false at termination. )doc"); REGISTER_OP("TopKTerminatedHyps") .Input("in_done_hyps: string") .Input("src_seq_lengths: int32") .Output("out_topk_hyps: string") .Attr("k: int") .Attr("num_hyps_per_beam: int") .Attr("length_normalization: float") .Attr("coverage_penalty: float") .Attr("target_seq_length_ratio: float=1.0") .Attr("eoc_id: int=-1") .Attr("merge_paths: bool = false") .SetShapeFn([](shape_inference::InferenceContext* c) { auto batch_size = c->Dim(c->input(1), 0); int k; TF_RETURN_IF_ERROR(c->GetAttr("k", &k)); shape_inference::DimensionOrConstant k_dim = c->UnknownDim(); if (k > 0) { k_dim = k; } c->set_output(0, c->Matrix(batch_size, k_dim)); return Status::OK(); }) .Doc(R"doc( Compute the top k terminated hyps based on normalized score for each beam. Let "b" be the number of beams, "h" be the number hyps in each beam, "t" be the maximum decoding steps. in_done_hyps: A tensor of shape [t, h * b]. Each string in in_done_hyps can be either an empty string, or a serialized Hypothesis proto. If not empty, in_done_hyps[t, i * num_beams + j] represents the i-th hypothesis for beam j that terminates at step t. src_seq_lengths: A tensor of shape [b] of the src sequence lengths. out_topk_hyps: A string tensor of shape [b, k]. topk_hyps[i: ] contains top k terminated hyp for beam 'i', each hyp could be either an empty string or a serialized `Hypothesis` proto. k: number of highest scoring hyps to be returned for each beam. num_hyps_per_beam: Number of hyps per beam in the input `in_done_hyps`. length_normalization: The length normalization ratio. coverage_penalty: The alpha value for coverage penalty. target_seq_length_ratio: Ratio of the average target sequence length over the average source sequence length. eoc_id: Token id of the special end of chunk or blank (epsilon) token. -1 means this model does not use epsilon. merge_paths: If true, hyps which are identical when epsilons are removed will be combined into a single hyp. The probability for that combined hyp will be the sum of the probabilities of the component hyps. This can only be applied for epsilon-emitting models (RNN-T and NT). )doc"); REGISTER_OP("UnpackHyp") .Input("in_hyps: string") .Output("out_ids: int32") .Output("out_seq_lens: int32") .Output("out_scores: float32") .Attr("max_seq_length: int = 0") .SetShapeFn([](shape_inference::InferenceContext* c) { auto batch_size = c->NumElements(c->input(0)); int k; TF_RETURN_IF_ERROR(c->GetAttr("max_seq_length", &k)); shape_inference::DimensionOrConstant k_dim = c->UnknownDim(); if (k > 0) { k_dim = k; } c->set_output(0, c->Matrix(batch_size, k_dim)); c->set_output(1, c->Vector(batch_size)); c->set_output(2, c->Vector(batch_size)); return Status::OK(); }) .Doc(R"doc( Unpacks hyps into tensors of ids, seq_len and scores. in_hyps: A vector of serialized `Hypothesis` protos. out_ids: Output sequences, a matrix of shape (batch_size, max_seq_length). Sequences shorter than max_seq_length are padded with 0s. If max_seq_length is 0, derive it from the longest sequence in input_hyps. out_seq_lens: Length of each of the output sequence, a vector of size `batch_size`. out_scores: Scores for each of the output sequence, a vector of `batch_size`. )doc"); REGISTER_OP("HypsFromBeamSearchOuts") .Input("hyps: int32") .Input("prev_hyps: int32") .Input("done_hyps: bool") .Input("scores: T") .Input("atten_probs: T") .Input("eos_scores: T") .Input("eos_atten_probs: T") .Output("out_hyps: string") .Attr("T: {float, bfloat16} = DT_FLOAT") .Attr("eos_id: int") .Attr("num_hyps_per_beam: int") .SetShapeFn([](shape_inference::InferenceContext* c) { c->set_output(0, c->input(0)); return ::tensorflow::Status::OK(); }) .Doc(R"doc( Generates `Hypothesis` protos from output of a beam search step. hyps: A tensor of shape [t, b * k] with ids of the token selected. prev_hyps: A tensor of shape [t, b * k] with index to the previous hyps which was selected. done_hyps: A boolean tensor of shape [t, b * k] where value indicates if hyps was terminated. scores: A tensor of shape [t, b * k]. in_scores[i, j] is the local score of the j-th hyp at the i-th decoding step. atten_probs: A tensor of shape [t, b * k, s_len]. atten_probs[i, j, ...] is the attention probs over the source words for the j-th hyp at the i-th timestep. eos_scores: A tensor of shape [t, b * k]. eos_scores[i, j] is the local score of the EOS token at the j-th hyp at the i-th decoding step. eos_atten_probs: A tensor of shape [t, b * k, s_len]. eos_atten_probs[i, j, ...] is the attention probs over the source words for the j-th terminated hyp at the i-th timestep. out_hyps: A tensor of shape [t, b * k] with terminated hyps. eos_id: Token id of the special end of sequence token. num_hyps_per_beam: Number of hyps per beam. )doc"); REGISTER_OP("CachedCall") .Output("output: T") .Attr("f: func") .Attr("T: list(type) >= 0") .SetIsStateful() .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( Invokes function f once and memorize its output. output: A list of output tensors whose types are T. f: A function that returns a list of tensors (T). )doc"); REGISTER_OP("VocabTokenToId") .Input("token: string") .Output("id: int32") .Attr("vocab: list(string)") .Attr("load_token_ids_from_vocab: bool = false") .SetIsStateful() .SetShapeFn(shape_inference::UnchangedShape) .Doc(R"doc( Looks up the token in the vocab and return its id. token: A scalar or list of strings. id: A scalar or list of ints. vocab: A list of strings. load_token_ids_from_vocab: Whether token ids are present in vocab (i.e. vocab contains two colums, one for IDs and one for words). If false, line numbers are used. )doc"); REGISTER_OP("VocabIdToToken") .Input("id: int32") .Output("token: string") .Attr("vocab: list(string)") .Attr("load_token_ids_from_vocab: bool = false") .SetIsStateful() .SetShapeFn(shape_inference::UnchangedShape) .Doc(R"doc( Looks up the token at the given id from a vocab. id: A scalar or list of ints. token: A scalar or list of strings. vocab: A list of strings. load_token_ids_from_vocab: Whether token ids are present in vocab (i.e. vocab contains two colums, one for IDs and one for words). If false, line numbers are used. )doc"); REGISTER_OP("TokenInVocab") .Input("token: string") .Output("result: bool") .Attr("vocab: list(string)") .Attr("load_token_ids_from_vocab: bool = false") .SetIsStateful() .SetShapeFn(shape_inference::UnchangedShape) .Doc(R"doc( Checks whether the provided token is in the vocab. token: A scalar or list of strings. result: A scalar or list of bools. vocab: A list of strings. load_token_ids_from_vocab: Whether token ids are present in vocab (i.e. vocab contains two colums, one for IDs and one for words). If false, line numbers are used. )doc"); REGISTER_OP("AsciiToTokenId") .Input("labels: string") .Output("token_ids: int32") .Output("target_ids: int32") .Output("paddings: float") .Attr("append_eos: bool = true") .Attr("maxlen: int = 300") .Attr("pad_to_maxlen: bool = true") .Doc(R"doc( Converts ASCII label strings into token ids. labels: A vector of shape [batch]. token_ids: A matrix of shape [batch, maxlen]. token_ids[i, j] is the i-th sample's j-th token id. token_ids[i, 0] is always <s>. target_ids: A matrix of shape [batch, maxlen]. target_ids[i, j] is the i-th sample's j-th prediction label id. paddings: A matrix of shape [batch, maxlen]. paddings[i, j] == 1.0 indicates that i-th training example' j-th target token is padded and should be ignored. append_eos: Whether to append </s> at the end and treat it as a non-padded label. maxlen: an integer, sequence length of the output tensors. pad_to_maxlen: Whether to pad the output to maxlen. )doc"); REGISTER_OP("StrToVocabTokens") .Input("labels: string") .Output("token_ids: int32") .Output("target_ids: int32") .Output("paddings: float") .Attr("append_eos: bool = true") .Attr("maxlen: int = 300") .Attr("pad_to_maxlen: bool = true") .Attr("vocab_filepath: string") .Attr("load_token_ids_from_vocab: bool = true") .Attr("delimiter: string = ' '") .SetShapeFn([](shape_inference::InferenceContext* c) { auto batch_size = c->Dim(c->input(0), 0); int maxlen; TF_RETURN_IF_ERROR(c->GetAttr("maxlen", &maxlen)); c->set_output(0, c->Matrix(batch_size, maxlen)); c->set_output(1, c->Matrix(batch_size, maxlen)); c->set_output(2, c->Matrix(batch_size, maxlen)); return Status::OK(); }) .Doc(R"doc( Tokenizes string into white space separated tokens according to a vocab file. labels: A vector of shape [batch]. token_ids: A matrix of shape [batch, maxlen]. token_ids[i, j] is the i-th sample's j-th token id. token_ids[i, 0] is always <s>. target_ids: A matrix of shape [batch, maxlen]. target_ids[i, j] is the i-th sample's j-th prediction label id. paddings: A matrix of shape [batch, maxlen]. paddings[i, j] == 1.0 indicates that i-th training example's j-th target token is padded and should be ignored. append_eos: Whether to append </s> at the end and treat it as a non-padded label. maxlen: an integer, sequence length of the output tensors. pad_to_maxlen: Whether to pad the output to maxlen. vocab_filepath: a string, filepath to the vocab file. load_token_ids_from_vocab: Whether token ids are present in vocab (i.e. vocab contains two colums, one for IDs and one for words). If false, line numbers are used. delimiter: The delimiter to split the labels to tokens by. )doc"); REGISTER_OP("IdToAscii") .Input("token_ids: int32") .Input("seq_lengths: int32") .Output("sequence: string") .Doc(R"doc( Converts sequences from token ids to actual ASCII tokens. token_ids: A matrix of shape [batch, seq_len]. seq_lengths: A vector of shape [batch]. seq_lengths[i] is the length of the i-th sequence. Only the first seq_lengths[i] tokens in token_ids[i] are valid tokens for the i-th sequence. sequence: A vector of shape [batch]. The converted string sequence. )doc"); REGISTER_OP("NgramIdToToken") .Input("token_ids: int32") .Input("seq_lengths: int32") .Output("sequences: string") .SetShapeFn([](shape_inference::InferenceContext* c) { c->set_output(0, c->input(1)); return Status::OK(); }) .Attr("ngram_vocab_filepath: string") .Attr("ngram_separator: string = \"\"") .Doc(R"doc( Converts sequences from token ids to actual tokens. token_ids: A matrix of shape [batch, seq_len]. seq_lengths: A vector of shape [batch]. seq_lengths[i] is the length of the i-th sequence. Only the first seq_lengths[i] tokens in token_ids[i] are valid tokens for the i-th sequence. sequences: A vector of shape [batch]. The converted string sequence. ngram_vocab_filepath: filepath to the ngram vocab file. ngram_separator: separator to use when joining ngrams into string. )doc"); REGISTER_OP("BpeWordsToIds") .Input("labels: string") .Output("token_ids: int32") .Output("target_ids: int32") .Output("paddings: float") .Attr("append_eos: bool = true") .Attr("maxlen: int = 300") .Attr("sos_id: int = 1") .Attr("eos_id: int = 2") .Attr("tokenization_filepath: string") .SetShapeFn([](shape_inference::InferenceContext* ctx) { const auto batch_size = ctx->Dim(ctx->input(0), 0); int maxlen; TF_RETURN_IF_ERROR(ctx->GetAttr("maxlen", &maxlen)); ctx->set_output(0, ctx->Matrix(batch_size, maxlen)); ctx->set_output(1, ctx->Matrix(batch_size, maxlen)); ctx->set_output(2, ctx->Matrix(batch_size, maxlen)); return Status::OK(); }) .Doc(R"doc( A tokenizer to convert string to BPE ids. This op is especially convenient for mapping string text to a sequenec of word BPE ids. The `labels` strings are tokenized via BPE. This op is typically used in conjunction with BpeIdsToWords. As the vocabulary file it receives the mapping from each word to the series of BPE ids. An example of lines in the vocabulary file: ... AARON 10005,16,29 AARON'S 10005,16,3466 AARONSON 10005,16,17,447 ... The output tensor `token_ids` is a sequence of integer ids with <s> prepended. The output tensor `target_ids` is a sequence of integer ids with </s> appended. labels: The batch of tf.String tensors. Expected shape is [batch_size]. token_ids: The ids with <s>. The shape is [batch_size, maxlen]. target_ids: The ids with </s>. The shape is [batch_size, maxlen]. paddings: The paddings. The shape is [batch_size, maxlen]. maxlen: Maximum length of token_ids/target_ids/paddings. tokenization_filepath: A path to a text file where each line is a word separated with space form a list of ids which are separated by ','. )doc"); REGISTER_OP("BpeIdsToWords") .Input("token_ids: int32") .Input("seq_lengths: int32") .Output("sequences: string") .Attr("vocab_filepath: string") .SetShapeFn([](shape_inference::InferenceContext* ctx) { const auto batch_size = ctx->Dim(ctx->input(0), 0); ctx->set_output(0, ctx->Vector(batch_size)); return Status::OK(); }) .Doc(R"doc( A tokenizer to map BPE ids to strings. This op is to map a sequence of integer ids to a string. The op is typically used in conjunction with BpeWordsToIds. The op will consume `seq_lengths` of tokens from `token_ids` and convert it to string `sequences`. A space character will be interested inbetween tokens. We do not filter any tokens (i.e., <s> and </s> are not treated specially). token_ids: The ids (can include paddings; length is determined by seq_lengths). The shape is [batch_size, maxlen]. seq_lengths: The length of the ids. The shape is [batch_size]. sequences: The string sequences. The shape is [batch_size]. vocab_filepath: A path to a text file where each line is a BPE string token. )doc"); REGISTER_OP("GenericInput") .Output("out: out_types") .INPUT_ATTRS // Common input attributes. .Attr("out_types: list(type)") .Attr("processor: func") .Attr("dynamic_padding_dimensions: list(int) = []") .Attr("dynamic_padding_constants: list(int) = []") .Doc(R"doc( Produces examples from processed from records. out: The 1st dimension of every tensor is the batch dimension. )doc" INPUT_DOCS R"doc( out_types: A list of tensor types. processor: A function that processes a string (one record) and returns a list of tensors. The last tensor must be a int32 scalar, which is used in conjunction with `bucket_upper_bound` to bucket all the samples. The other tensors belongs to one sample. They have the respective `out_types`. These tensors' first dimension are _not_ the batch dimension. Instead, when multiple samples are merged into a batch, GenericInput's implementation expand the batch dimension (dim 0) and concatenate the corresponding tensors into one tensor. dynamic_padding_dimensions: If not empty, must be the same length as out. Specifies the 0-indexed dimension to pad dynamically for each output. The output is padded to the longest tensor in the batch along the dimension. The first (0-th) dimension is _not_ the batch dimension. A value of -1 indicates the specified output should not be padded, eg. if the output is a scalar rather than a sequence. dynamic_padding_constants: Must be set if `dynamic_padding_dimension` is provided. The constant value to use for padding. )doc"); REGISTER_OP("StaticMapStringInt") .Input("x: string") .Output("y: int32") .Attr("keys: list(string)") .Attr("vals: list(int) = []") .Attr("unk: int = -1") .SetShapeFn([](shape_inference::InferenceContext* c) { c->set_output(0, c->input(0)); return ::tensorflow::Status::OK(); }) .Doc(R"doc( Maps every element of x according a static mapping. x: A Tensor of type string. y: A Tensor of type int32. Same shape of x. keys: The list of keys. vals: The list of values. If empty, defaults to [0 .. len(keys)). unk: The value when the key is not found. )doc"); REGISTER_OP("StaticMapIntString") .Input("x: int32") .Output("y: string") .Attr("keys: list(int) = []") .Attr("vals: list(string)") .Attr("unk: string = ''") .SetShapeFn([](shape_inference::InferenceContext* c) { c->set_output(0, c->input(0)); return ::tensorflow::Status::OK(); }) .Doc(R"doc( Maps every element of x according a static mapping. x: A Tensor of type int32. y: A Tensor of type string. Same shape of x. keys: The list of keys. If empty, defaults to [0 .. len(keys)). vals: The list of values. unk: The value when the key is not found. )doc"); REGISTER_OP("ComputePreconditioners") .Input("inputs: num_tensors * float32") .Input("exponents: num_tensors * float32") .Input("global_step: int32") .Attr("preconditioner_compute_graphdef: string") .Attr("keys: list(string)") .Attr("sync: bool = false") .Attr("num_tensors: int >= 1") .SetIsStateful() .SetShapeFn([](shape_inference::InferenceContext* c) { return Status::OK(); }) .Doc(R"doc( Compute preconditioners for Shampoo optimizer. inputs: A list of Tensors of type float32, of statistic matrices. exponents: A list of scalar Tensors of type float32, exponent for matrix power. global_step: A scalar Tensor of type int32 which indicates the global step. preconditioner_compute_graphdef: A graphdef which indicates the function to run. keys: A list of keys indicating the name of preconditioners. sync: Boolean indicating whether to run preconditioning in synchronous mode. num_tensors: Number of tensor inputs. )doc"); REGISTER_OP("GetPreconditioners") .Input("shapes: num_tensors * Tshape") .Output("outputs: num_tensors * float32") .Output("statuses: num_tensors * bool") .Attr("preconditioner_compute_graphdef: string") .Attr("keys: list(string)") .Attr("Tshape: {int32, int64} = DT_INT32") .Attr("num_tensors: int >= 1") .SetIsStateful() .SetShapeFn([](shape_inference::InferenceContext* c) { std::vector<shape_inference::ShapeHandle> shapes; if (c->input("shapes", &shapes).ok()) { for (int i = 0; i < shapes.size(); ++i) { shape_inference::ShapeHandle out; TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(i, &out)); c->set_output(i, out); c->set_output(shapes.size() + i, c->Scalar()); } } return Status::OK(); }) .Doc(R"doc( Get preconditioners for Shampoo optimizer. shapes: A list of Tensors of type Tshape indicating the size of preconditioner. outputs: A list of Tensors of type float32 which are the preconditioners. statuses: A list of Tensors of type bool which are the preconditioner status. preconditioner_compute_graphdef: A graphdef which indicates the function to run. keys: A list of keys indicating the name of preconditioners. Tshape: The data-type to use for shape. num_tensors: Number of tensor inputs. )doc"); REGISTER_OP("MlPerfSubwordIdToString") .Input("token_ids: int32") .Input("seq_lengths: int32") .Output("sequences: string") .SetShapeFn([](shape_inference::InferenceContext* c) { c->set_output(0, c->input(1)); return Status::OK(); }) .Attr("vocab_filepath: string") .Doc(R"doc( Converts sequences from subword token ids to strings token_ids: A matrix of shape [batch, seq_len]. seq_lengths: A vector of shape [batch]. seq_lengths[i] is the length of the i-th sequence. Only the first seq_lengths[i] tokens in token_ids[i] are valid tokens for the i-th sequence. sequences: A vector of shape [batch]. The converted string sequence. vocab_filepath: filepath to the MLPerf subword vocab file. )doc"); REGISTER_OP("PackSequences") .Input("src_actual_seq_len: int32") .Input("tgt_actual_seq_len: int32") .Input("packed_batch_size: int32") .Input("packed_src_seq_len: int32") .Input("packed_tgt_seq_len: int32") .SetIsStateful() .Output("src_segment_ids: int32") .Output("src_segment_pos: int32") .Output("src_indices_in_input: int32") .Output("tgt_segment_ids: int32") .Output("tgt_segment_pos: int32") .Output("tgt_indices_in_input: int32") .Attr("seed: int = 0") .Doc(R"doc( Produces a packing pattern for the (src, tgt) input pair with the provided lengths, according to the given packed shape. src_actual_seq_len: A tensor of shape [N], where N is the input batch size. This tensor contains the actual lengths for the src sequence. tgt_actual_seq_len: A tensor of shape [N], where N is the input batch size. This tensor contains the actual lengths for the tgt sequence. packed_batch_size: A scalar. The output batch size. The packed output will be of shape [packed_batch_size, packed_{src,tgt}_seq_len] for src and tgt, respectively. packed_src_seq_len: A scalar. The output sequence length for src. A src input with shape [N, src_input_seq_len] will be packed into an output with shape [packed_batch_size, packed_src_seq_len]. packed_tgt_seq_len: A scalar. The output sequence length for tgt. A tgt input with shape [N, tgt_input_seq_len] will be packed into an output with shape [packed_batch_size, packed_tgt_seq_len]. {src,tgt}_segment_ids: A tensor of shape [packed_batch_size, packed_{src,tgt}_seq_len]. Incrementing from 1 to indicate each segment in the packed output, for src and tgt, respectively. Zero is reserved for indicating padding at the end of each row. {src,tgt}_segment_pos: A tensor of shape [packed_batch_size, packed_{src,tgt}_seq_len]. Zero-based index to indicate relative position within each segment, for src and tgt, respectively. Zero is also used to indicate padding. When needed, use `{src,tgt}_segment_ids` to disambiguate. {src,tgt}_indices_in_input: A tensor of shape [packed_batch_size, packed_{src,tgt}_seq_len]. For each segment in the packed output, it contains the original (zero-based) row index of each segment found in `{src,tgt}_actual_seq_len`, respectively. Zero is also used to indicate padding. When needed, use `{src,tgt}_segment_ids` to disambiguate. seed: Seed for random number generator, which is used when we need to drop excessive input sequences. If seed is zero, use completely random seed. For example, the following input: src_actual_seq_len = [3, 2, 1] tgt_actual_seq_len = [4, 1, 5] packed_batch_size = 2 packed_src_seq_len = 5 packed_tgt_seq_len = 5 will result in: src_segment_ids = [ [1, 1, 1, 2, 2], [1, 0, 0, 0, 0] ] src_segment_pos = [ [0, 1, 2, 0, 1], [0, 0, 0, 0, 0] ] src_indices_in_input = [ [0, 0, 0, 1, 1], [2, 0, 0, 0, 0] ] tgt_segment_ids = [ [1, 1, 1, 1, 2], [1, 1, 1, 1, 1] ] tgt_segment_pos = [ [0, 1, 2, 3, 0], [0, 1, 2, 3, 4] ] tgt_indices_in_input = [ [0, 0, 0, 0, 1], [2, 2, 2, 2, 2] ] The packed sequence length can be different between src and tgt. For example, the following input: src_actual_seq_len = [3, 2, 1] tgt_actual_seq_len = [4, 1, 5] packed_batch_size = 2 packed_src_seq_len = 4 packed_tgt_seq_len = 6 will result in: src_segment_ids = [ [1, 1, 1, 0], [1, 1, 2, 0] ] src_segment_pos = [ [0, 1, 2, 0], [0, 1, 0, 0] ] src_indices_in_input = [ [0, 0, 0, 0], [1, 1, 2, 0] ] tgt_segment_ids = [ [1, 1, 1, 1, 0, 0], [1, 2, 2, 2, 2, 2] ] tgt_segment_pos = [ [0, 1, 2, 3, 0, 0], [0, 0, 1, 2, 3, 4] ] tgt_indices_in_input = [ [0, 0, 0, 0, 0, 0], [1, 2, 2, 2, 2, 2] ] If there are too few input sequences to pack into `output_shape`, the op pads the remaining elements in the output. If there are too many input sequences to pack into `output_shape`, the op drops input sequences. The dropping is done randomly uniformly on the input sequences to not bias the distribution of sequence lengths in the packed output. )doc"); REGISTER_OP("ApplyPacking") .Input("input: T") .Input("padding: T") .Input("segment_ids: int32") .Input("indices_in_input: int32") .Output("output: T") .Attr("T: type") .Doc(R"doc( Applies a packing pattern on the input to obtain a packed output. A slightly different semantics when T is tf.string type: the output joins the strings that are packed on the same row, separated by `padding`. input: A tensor of shape [N, seq_len]. The input to apply the packing to. For tf.string typed input, a vector of shape [N] is expected. padding: A scalar to indicate the padding value. This is typically the zero value of T, but may not always be the case, e.g. when the input is a paddings tensor, in which case caller should set padding=1. For tf.string typed input, padding is used as a separator to join all the strings on the same row in the output. segment_ids: A rank 2 tensor of shape `output_shape`. indices_in_input: A rank 2 tensor of shape `output_shape`. output: A tensor of shape `output_shape`. For tf.string typed input, the output is a vector of strings where its length is the same as the number of rows in `output_shape`. The inputs `segment_ids` and `indices_in_input` can be obtained from the outputs of an `PackSequence` op (though only the src or the tgt tensors are needed). Note that ApplyPacking is done on a per column basis (either on the src or on the tgt), as opposed to in PackSequences, when both src and tgt columns must be processed together within the same op. )doc"); REGISTER_OP("Mass") .Input("ids: int32") .Input("weights: float32") .Input("actual_seq_len: int32") .Attr("mask_id: int") .Attr("mask_ratio: float = 0.5") .Attr("mask_minlen: int = 0") .Attr("span_len: int = 100000") .Attr("random_start_prob: float = 0.6") .Attr("keep_prob: float = 0.1") .Attr("rand_prob: float = 0.1") .Attr("mask_prob: float = 0.8") // TODO(alisonlui): This flag is rarely used; remove after verification. .Attr("mask_target: bool = True") .Attr("vocab_size: int") .Attr("first_unreserved_id: int = 4") .Output("src_ids: int32") .Output("tgt_ids: int32") .Output("tgt_labels: int32") .Output("tgt_weights: float32") .Doc(R"doc( Applies masking to implement MASS. ids: Tensor of shape [batch_size, max_seq_len] containing the token ids. Should include EOS token </s>. weights: Tensor of shape [batch_size, max_seq_len]. actual_seq_len: Tensor of shape [batch_size]. mask_id: The id to use for the mask token. mask_ratio: Proportion of src to mask. mask_minlen: Skip sentences too short to mask at least this many tokens. span_len: Split mask_len into segments of this size and randomly distribute those across the src. random_start_prob: The probability that the placement of masked segments will be entirely random. The remaining cases are split evenly between masking at the beginning and at the end of the src. keep_prob/rand_prob/mask_prob: The probability that a token to be masked will be unchanged, replaced with a random token in the vocab, or replaced with the mask_id, respectively. Must sum to 1. mask_target: whether to mask the target (the mask will be the inverse of that of the src). vocab_size: Vocab size used when selecting a random token to replace a masked token. first_unreserved_id: Tokens greater than or equal to this may be selected at random to replace a masked token. src_ids: Masked ids. E.g. s1 s2 s3 m m </s> tgt_ids: Right-shifted ids with BOS token added, where the mask is the positional inverse of that of the source unless mask_target=False. E.g. m m m s3 s4 m tgt_labels: E.g. s1 s2 s3 s4 s5 </s> tgt_weights: weights are zeroed wherever the target is masked. )doc"); } // namespace } // namespace tensorflow <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/jit_uni_dw_convolution.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "c_types_map.hpp" #include "memory_tracking.hpp" #include "mkldnn_thread.hpp" #include "bfloat16.hpp" #include "jit_uni_dw_convolution.hpp" namespace mkldnn { namespace impl { namespace cpu { using namespace mkldnn::impl::status; using namespace mkldnn::impl::memory_tracking::names; using namespace mkldnn::impl::utils; template <cpu_isa_t isa, data_type_t src_type, data_type_t dst_type> void jit_uni_dw_convolution_fwd_t<isa, src_type, dst_type>::execute_forward( const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const data_t *, MKLDNN_ARG_SRC); auto weights = CTX_IN_MEM(const data_t *, MKLDNN_ARG_WEIGHTS); auto dst = CTX_OUT_MEM(dst_data_t *, MKLDNN_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const memory_desc_wrapper bias_d(pd()->weights_md(1)); const auto &jcp = pd()->jcp_; f32_data_t *bias = nullptr; if (pd()->desc()->bias_desc.data_type == data_type::bf16) { auto bias_in = CTX_IN_MEM(const bf16_data_t *, MKLDNN_ARG_BIAS); bias = scratchpad(ctx).template get<f32_data_t>( key_conv_bias_bf16_convert_wsp); cvt_bfloat16_to_float(bias, bias_in, jcp.oc_without_padding); utils::array_set(bias + jcp.oc_without_padding, 0.f, jcp.oc - jcp.oc_without_padding); } else { auto bias_in = CTX_IN_MEM(const f32_data_t *, MKLDNN_ARG_BIAS); if (pd()->wants_padded_bias()) { auto padded_bias = this->scratchpad(ctx).template get<f32_data_t>( key_conv_padded_bias); utils::array_copy(padded_bias, bias_in, jcp.oc_without_padding); utils::array_set(padded_bias + jcp.oc_without_padding, 0.f, jcp.oc - jcp.oc_without_padding); bias = padded_bias; } else bias = const_cast<float*> (bias_in); } int dil_h = jcp.dilate_h + 1; int dil_w = jcp.dilate_w + 1; int str_h = jcp.stride_h; int str_w = jcp.stride_w; auto kernel_params = [&](int ur_w_step, int ow, int oh, int ih, int kh, int kh_padding, int ch, int ch_num, int n) { auto par_conv = jit_conv_call_s(); const int i_l_overflow = nstl::max(0, (jcp.l_pad - ow * str_w)); const int i_r_overflow = nstl::max(jcp.iw, (ow * str_w + (jcp.kw - 1)*dil_w - jcp.l_pad + 1)) - jcp.iw; const int iw = nstl::max((ow*str_w - jcp.l_pad + div_up(i_l_overflow, dil_w)*dil_w), 0); const int kw = div_up(i_l_overflow, dil_w); const int kw_padding = jcp.kw - div_up(i_l_overflow, dil_w) - div_up(i_r_overflow, dil_w); par_conv.src = &src[src_d.blk_off(n, ch, ih, iw)]; par_conv.dst = &dst[dst_d.blk_off(n, ch, oh, ow)]; par_conv.filt = &weights[weights_d.blk_off(ch, 0, 0, kh, kw)]; if (bias) par_conv.bias = &bias[bias_d.blk_off(ch*jcp.ch_block)]; par_conv.kh_padding = (size_t)nstl::max(0, kh_padding); par_conv.kw_padding = (size_t)nstl::max(0, kw_padding); par_conv.ur_w = (size_t)ur_w_step; par_conv.ch_blocks = nstl::min(ch + ch_num, jcp.nb_ch) - ch; return par_conv; }; const int chb_work = utils::div_up(jcp.nb_ch, jcp.nb_ch_blocking); parallel_nd(jcp.mb, chb_work, jcp.oh, [&](int n, int chb, int oh) { int ch = chb * jcp.nb_ch_blocking; int ch_num = jcp.nb_ch_blocking; const int i_t_overflow = nstl::max(0, (int)(jcp.t_pad - oh*str_h)); const int i_b_overflow = nstl::max(jcp.ih, (int)(oh*str_h + (jcp.kh - 1)*dil_h - jcp.t_pad + 1)) - jcp.ih; const int ih = nstl::max((int)(oh*str_h - jcp.t_pad + div_up(i_t_overflow, dil_h)*dil_h), 0); const int kh = div_up(i_t_overflow, dil_h); const int kh_padding = jcp.kh - div_up(i_t_overflow, dil_h) - div_up(i_b_overflow, dil_h); // left border int ow = 0; int l_border = nstl::min(div_up(jcp.l_pad, str_w), jcp.ow); int ur_w_step = 1; for (; ow < l_border; ow++) { jit_conv_call_s par_conv = kernel_params(ur_w_step, ow, oh, ih, kh, kh_padding, ch, ch_num, n); kernel_->jit_ker(&par_conv); } // main loop ur_w_step = (jcp.iw - (jcp.kw - 1)*dil_w + jcp.l_pad - 1) / jcp.stride_w - ow + 1; if (ur_w_step > 0) { jit_conv_call_s par_conv = kernel_params(ur_w_step, ow, oh, ih, kh, kh_padding, ch, ch_num, n); kernel_->jit_ker(&par_conv); ow += ur_w_step; } // right border ur_w_step = 1; for (; ow < jcp.ow; ow++) { jit_conv_call_s par_conv = kernel_params(ur_w_step, ow, oh, ih, kh, kh_padding, ch, ch_num, n); kernel_->jit_ker(&par_conv); } }); if (pd()->wants_zero_pad_dst()) ctx.memory(MKLDNN_ARG_DST)->zero_pad(); } template struct jit_uni_dw_convolution_fwd_t<avx512_core, data_type::bf16, data_type::f32>; template struct jit_uni_dw_convolution_fwd_t<avx512_core, data_type::bf16>; template struct jit_uni_dw_convolution_fwd_t<avx512_common, data_type::f32>; template struct jit_uni_dw_convolution_fwd_t<avx2, data_type::f32>; template struct jit_uni_dw_convolution_fwd_t<sse41, data_type::f32>; template <cpu_isa_t isa, data_type_t diff_dst_type, data_type_t diff_src_type> void jit_uni_dw_convolution_bwd_data_t<isa, diff_dst_type, diff_src_type> ::execute_backward_data(const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const diff_dst_data_t *, MKLDNN_ARG_DIFF_DST); auto weights = CTX_IN_MEM(const wei_data_t *, MKLDNN_ARG_WEIGHTS); auto diff_src = CTX_OUT_MEM(diff_src_data_t *, MKLDNN_ARG_DIFF_SRC); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const memory_desc_wrapper diff_src_d(pd()->diff_src_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const auto &jcp = pd()->jcp_; auto kernel_params = [&](int ur_str_w, int iw, int oh, int ih, int i_t_overflow, int i_b_overflow, int stride_off_h, int ch, int ch_num, int n) { auto par_conv = jit_conv_call_s(); const int i_l_overflow = nstl::max(0, (jcp.kw - 1 - iw - jcp.l_pad)); const int i_r_overflow = nstl::max(0, (jcp.kw - 1 - (jcp.iw - 1 - iw) - jcp.r_pad)); int ow = iw + jcp.l_pad - i_r_overflow; int stride_off_w = ow % jcp.stride_w; ow /= jcp.stride_w; par_conv.src = &diff_src[diff_src_d.blk_off(n, ch, ih, iw)]; par_conv.dst = &diff_dst[diff_dst_d.blk_off(n, ch, oh, ow)]; par_conv.filt = &weights[weights_d.blk_off(ch, 0, 0, i_b_overflow + stride_off_h, i_r_overflow + stride_off_w)]; par_conv.kh_padding = nstl::max(0, jcp.kh - i_t_overflow - i_b_overflow - stride_off_h); par_conv.kw_padding = nstl::max(0, jcp.kw - i_l_overflow - i_r_overflow - stride_off_w); par_conv.ur_str_w = ur_str_w; par_conv.ch_blocks = nstl::min(ch + ch_num, jcp.nb_ch) - ch; return par_conv; }; const int aux_w = nstl::min(jcp.iw, jcp.iw - jcp.kw + jcp.r_pad + jcp.stride_w); const int chb_work = utils::div_up(jcp.nb_ch, jcp.nb_ch_blocking); parallel_nd(jcp.mb, chb_work, jcp.ih, [&](int n, int chb, int ih) { int ch = chb * jcp.nb_ch_blocking; int ch_num = jcp.nb_ch_blocking; const int i_t_overflow = nstl::max(0, (int)(jcp.kh - 1 - ih - jcp.t_pad)); const int i_b_overflow = nstl::max(0, (int)(jcp.kh - 1 - (jcp.ih - 1 - ih) - jcp.b_pad)); int oh = ih + jcp.t_pad - i_b_overflow; int stride_off_h = oh % jcp.stride_h; oh /= jcp.stride_h; for (int i_str_w = 0; i_str_w < jcp.stride_w; i_str_w++) { // left border int iw = i_str_w; int l_border = nstl::min(jcp.kw - 1 - jcp.l_pad, jcp.iw); int ur_str_w = 1; for (; iw < l_border; iw += jcp.stride_w) { jit_conv_call_s par_conv = kernel_params(ur_str_w, iw, oh, ih, i_t_overflow, i_b_overflow, stride_off_h, ch, ch_num, n); kernel_->jit_ker(&par_conv); } // main loop ur_str_w = (aux_w - iw) / jcp.stride_w; if (ur_str_w > 0) { jit_conv_call_s par_conv = kernel_params(ur_str_w, iw, oh, ih, i_t_overflow, i_b_overflow, stride_off_h, ch, ch_num, n); kernel_->jit_ker(&par_conv); iw += ur_str_w * jcp.stride_w; } // right border ur_str_w = 1; for (; iw < jcp.iw; iw += jcp.stride_w) { jit_conv_call_s par_conv = kernel_params(ur_str_w, iw, oh, ih, i_t_overflow, i_b_overflow, stride_off_h, ch, ch_num, n); kernel_->jit_ker(&par_conv); } } }); } template struct jit_uni_dw_convolution_bwd_data_t<avx512_core, data_type::bf16, data_type::f32>; template struct jit_uni_dw_convolution_bwd_data_t<avx512_core, data_type::bf16>; template struct jit_uni_dw_convolution_bwd_data_t<avx512_common, data_type::f32>; template struct jit_uni_dw_convolution_bwd_data_t<avx2, data_type::f32>; template struct jit_uni_dw_convolution_bwd_data_t<sse41, data_type::f32>; template <cpu_isa_t isa, data_type_t src_type, data_type_t diff_weights_type> jit_uni_dw_convolution_bwd_weights_t<isa, src_type, diff_weights_type>:: jit_uni_dw_convolution_bwd_weights_t(const pd_t *apd) : cpu_primitive_t(apd) , acc_ker_(nullptr), kernel_(nullptr) { kernel_ = new jit_uni_dw_conv_bwd_weights_kernel<isa, src_type>( pd()->jcp_); if (pd()->jcp_.nthr_mb > 1 && isa != sse41) acc_ker_ = new cpu_accumulator_1d_t<data_type::f32>(); } template <cpu_isa_t isa, data_type_t src_type, data_type_t diff_weights_type> void jit_uni_dw_convolution_bwd_weights_t<isa, src_type, diff_weights_type> ::execute_backward_weights(const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const diff_dst_data_t *, MKLDNN_ARG_DIFF_DST); auto src = CTX_IN_MEM(const src_data_t *, MKLDNN_ARG_SRC); auto diff_weights = CTX_OUT_MEM(diff_weights_data_t *, MKLDNN_ARG_DIFF_WEIGHTS); auto diff_wei_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_wei_reduction); auto diff_bia_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_bia_reduction); const auto &jcp = pd()->jcp_; float *diff_bias = nullptr; if (jcp.bia_dt == data_type::bf16) { diff_bias = scratchpad(ctx).template get<f32_data_t>( key_conv_bias_bf16_convert_wsp); } else { diff_bias = CTX_OUT_MEM(f32_data_t *, MKLDNN_ARG_DIFF_BIAS); } const size_t wei_size = jcp.ngroups * jcp.kh * jcp.kw; const size_t bias_size = jcp.with_bias ? jcp.ngroups : 0; const int ch_block = jcp.ch_block; auto set_kernel_params = [&](jit_dw_conv_call_s *conv_params, const int batch, const int group, const int oh_start, const int work_size, const unsigned char exec_flag, const size_t kh_padding, const size_t filter_off) { const int tpad_underflow_off = jcp.t_pad - filter_off; conv_params->exec_flags = exec_flag; conv_params->kh_count = jcp.kh - kh_padding; const int oh_s = oh_start; const int oh_e = oh_start + work_size; const int ih_s = oh_s * jcp.stride_h; conv_params->filter_pad_off = filter_off * jcp.kw * ch_block * jcp.typesize_out; conv_params->oh_index = oh_s; conv_params->oh_count = oh_e; size_t diff_dst_off = ((batch * (jcp.ngroups / ch_block) + group) * jcp.oh + oh_start) * jcp.ow; size_t src_off = ((batch * (jcp.ngroups / ch_block) + group) * jcp.ih + ih_s - tpad_underflow_off) * jcp.iw; conv_params->output = &diff_dst[diff_dst_off * ch_block]; conv_params->input = &src[src_off * ch_block]; }; parallel(jcp.nthr, [&](const int ithr, const int nthr) { assert(nthr == jcp.nthr); auto conv_params = jit_dw_conv_call_s(); const int h_block_size = 15; /* assign iteration space to thread */ const int ithr_g = ithr % jcp.nthr_g; const int ithr_mb = (ithr / jcp.nthr_g) % jcp.nthr_mb; /* split dimensions */ int g_start{ 0 }, g_end{ 0 }; balance211(jcp.nb_ch, jcp.nthr_g, ithr_g, g_start, g_end); int mb_start{ 0 }, mb_end{ 0 }; balance211(jcp.mb, jcp.nthr_mb, ithr_mb, mb_start, mb_end); auto i_mb = diff_weights_type == data_type::bf16 ? ithr_mb : ithr_mb - 1; f32_data_t *diff_wei = (ithr_mb == 0 && diff_weights_type == data_type::f32) ? (f32_data_t *)diff_weights : diff_wei_reduction_buf + i_mb * wei_size; auto diff_bia = ithr_mb == 0 ? diff_bias : diff_bia_reduction_buf + (ithr_mb - 1) * bias_size; for (int g = g_start; g < g_end; ++g) { unsigned char zero_filter_flag = FLAG_ZERO_FILTER; unsigned char zero_bias_flag = jcp.with_bias ? FLAG_ZERO_BIAS : 0; size_t diff_wei_off = g * jcp.kh * jcp.kw; conv_params.filter = &diff_wei[diff_wei_off * ch_block]; if (jcp.with_bias) conv_params.bias = &diff_bia[g * ch_block]; for (int mb = mb_start; mb < mb_end; ++mb) { int oh = 0; while (oh < jcp.oh) { const int h_work = nstl::min(h_block_size, jcp.oh - oh); auto kh_t_padding = nstl::max(0, jcp.t_pad - oh); auto kh_b_padding = (oh * jcp.stride_h + jcp.kh > jcp.ih + jcp.t_pad) ? nstl::max(jcp.b_pad - (h_work - 1), 0) : 0; set_kernel_params(&conv_params, mb, g, oh, h_work, zero_filter_flag | zero_bias_flag, kh_t_padding + kh_b_padding, kh_t_padding); kernel_->jit_ker(&conv_params); zero_bias_flag &= ~FLAG_ZERO_BIAS; zero_filter_flag &= ~FLAG_ZERO_FILTER; oh += h_work; } } } }); } /* TODO: Performing a Parallel Reduction could potentially improve performance; * this should be explored in the future if further optimizations are required. */ template <> void jit_uni_dw_convolution_bwd_weights_t<avx512_core, data_type::bf16>::execute_reduction(const exec_ctx_t &ctx) const { auto diff_wei_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_wei_reduction); auto diff_bia_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_bia_reduction); auto diff_weights = CTX_OUT_MEM(diff_weights_data_t *, MKLDNN_ARG_DIFF_WEIGHTS); const auto &jcp = pd()->jcp_; assert(jcp.dwei_dt == data_type::bf16); const size_t wei_size = jcp.ngroups * jcp.kh * jcp.kw; const size_t bias_size = jcp.with_bias ? jcp.ngroups : 0; const int ch_block = jcp.ch_block; float *diff_bias = nullptr; if (jcp.bia_dt == data_type::bf16) { diff_bias = scratchpad(ctx).template get<f32_data_t>( key_conv_bias_bf16_convert_wsp); } else { diff_bias = CTX_OUT_MEM(f32_data_t *, MKLDNN_ARG_DIFF_BIAS); } /* Apply single-threaded 'mb' reduction */ if (jcp.with_bias && jcp.nthr_mb > 1) { for (int thr_mb = 1; thr_mb < jcp.nthr_mb; ++thr_mb) { size_t b_accum_offset = (thr_mb - 1) * bias_size; for (int g = 0; g < jcp.nb_ch; ++g) { /* Reduction on Bias */ PRAGMA_OMP_SIMD() for (int g_block = 0; g_block < ch_block; ++g_block) { size_t bias_offset = g * ch_block + g_block; diff_bias[bias_offset] += diff_bia_reduction_buf[b_accum_offset + bias_offset]; } } } } if (jcp.bia_dt == data_type::bf16) { auto diff_bias_in = CTX_OUT_MEM(bf16_data_t *, MKLDNN_ARG_DIFF_BIAS); cvt_float_to_bfloat16(diff_bias_in, diff_bias, jcp.ngroups); } /* Apply single-threaded 'mb' reduction */ if (jcp.nthr_mb > 1) { for (int thr_mb = 2; thr_mb < jcp.nthr_mb; ++thr_mb) { size_t mb_accum_offset = thr_mb * wei_size; acc_ker_->accumulate(&diff_wei_reduction_buf[0], &diff_wei_reduction_buf[mb_accum_offset], wei_size); } add_floats_and_cvt_to_bfloat16( (bfloat16_t *)&(diff_weights[0]), (float *)&diff_wei_reduction_buf[0], (float *)&diff_wei_reduction_buf[wei_size], wei_size); } else { cvt_float_to_bfloat16( (bfloat16_t *)&(diff_weights[0]), (const float *)&(diff_wei_reduction_buf[0]), wei_size); } } template <> void jit_uni_dw_convolution_bwd_weights_t<sse41, data_type::f32>::execute_reduction(const exec_ctx_t &ctx) const { auto diff_bias = CTX_OUT_MEM(f32_data_t *, MKLDNN_ARG_DIFF_BIAS); auto diff_wei_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_wei_reduction); auto diff_bia_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_bia_reduction); auto diff_weights = CTX_OUT_MEM(f32_data_t *, MKLDNN_ARG_DIFF_WEIGHTS); const auto &jcp = pd()->jcp_; const size_t wei_size = jcp.ngroups * jcp.kh * jcp.kw; const size_t bias_size = jcp.with_bias ? jcp.ngroups : 0; const int ch_block = jcp.ch_block; /* Apply single-threaded 'mb' reduction */ for (int thr_mb = 1; thr_mb < jcp.nthr_mb; ++thr_mb) { size_t mb_accum_offset = (thr_mb - 1) * wei_size; size_t b_accum_offset = (thr_mb - 1) * bias_size; for (int g = 0; g < jcp.nb_ch; ++g) { /* Reduction on Bias */ if (jcp.with_bias) { PRAGMA_OMP_SIMD() for (int g_block = 0; g_block < ch_block; ++g_block) { size_t bias_offset = g * ch_block + g_block; diff_bias[bias_offset] += diff_bia_reduction_buf[b_accum_offset + bias_offset]; } } for (int kh = 0; kh < jcp.kh; ++kh) for (int kw = 0; kw < jcp.kw; ++kw) { size_t wei_offset = (g * jcp.kh + kh) * jcp.kw + kw; PRAGMA_OMP_SIMD() for (int g_block = 0; g_block < ch_block; ++g_block) { const size_t off = wei_offset * ch_block + g_block; diff_weights[off] += diff_wei_reduction_buf[mb_accum_offset + off]; } } } } } template <cpu_isa_t isa, data_type_t src_type, data_type_t diff_weights_type> void jit_uni_dw_convolution_bwd_weights_t<isa, src_type, diff_weights_type>::execute_reduction(const exec_ctx_t &ctx) const { auto diff_wei_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_wei_reduction); auto diff_bia_reduction_buf = scratchpad(ctx).template get<f32_data_t>(key_conv_bia_reduction); auto diff_weights = CTX_OUT_MEM(f32_data_t *, MKLDNN_ARG_DIFF_WEIGHTS); const auto &jcp = pd()->jcp_; const size_t wei_size = jcp.ngroups * jcp.kh * jcp.kw; const size_t bias_size = jcp.with_bias ? jcp.ngroups : 0; const int ch_block = jcp.ch_block; assert(diff_weights_type == data_type::f32 && jcp.dwei_dt == data_type::f32); float *diff_bias = nullptr; if (jcp.bia_dt == data_type::bf16) { diff_bias = scratchpad(ctx).template get<f32_data_t>( key_conv_bias_bf16_convert_wsp); } else { diff_bias = CTX_OUT_MEM(f32_data_t *, MKLDNN_ARG_DIFF_BIAS); } /* Apply single-threaded 'mb' reduction */ for (int thr_mb = 1; thr_mb < jcp.nthr_mb; ++thr_mb) { size_t mb_accum_offset = (thr_mb - 1) * wei_size; size_t b_accum_offset = (thr_mb - 1) * bias_size; for (int g = 0; g < jcp.nb_ch; ++g) { /* Reduction on Bias */ if (jcp.with_bias) { PRAGMA_OMP_SIMD() for (int g_block = 0; g_block < ch_block; ++g_block) { size_t bias_offset = g * ch_block + g_block; diff_bias[bias_offset] += diff_bia_reduction_buf[b_accum_offset + bias_offset]; } } } acc_ker_->accumulate(&diff_weights[0], &diff_wei_reduction_buf[mb_accum_offset], wei_size); } if (jcp.bia_dt == data_type::bf16) { auto diff_bias_in = CTX_OUT_MEM(bf16_data_t *, MKLDNN_ARG_DIFF_BIAS); cvt_float_to_bfloat16(diff_bias_in, diff_bias, jcp.ngroups); } } template struct jit_uni_dw_convolution_bwd_weights_t<avx512_core, data_type::bf16>; template struct jit_uni_dw_convolution_bwd_weights_t<avx512_core, data_type::bf16, data_type::f32>; template struct jit_uni_dw_convolution_bwd_weights_t<avx512_common, data_type::f32>; template struct jit_uni_dw_convolution_bwd_weights_t<avx2, data_type::f32>; template struct jit_uni_dw_convolution_bwd_weights_t<sse41, data_type::f32>; } } } <|start_filename|>NVIDIA/benchmarks/dlrm/implementations/pytorch/Dockerfile<|end_filename|> # Copyright (c) 2020, NVIDIA CORPORATION. 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. ARG FROM_IMAGE_NAME=nvcr.io/nvidia/pytorch:20.06-py3 FROM ${FROM_IMAGE_NAME} # Install Python dependencies RUN pip install --no-cache-dir https://github.com/mlperf/logging/archive/0.7.0-rc2.zip # Install DLRM WORKDIR /workspace/dlrm COPY . . RUN pip install --no-cache-dir -e . ENV LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4 <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/file/utils.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_FILE_UTILS_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_FILE_UTILS_H_ #include <cstdint> #include <string> #include <vector> #include "REDACTEDstrings/string_view.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" namespace minigo { namespace file { MG_WARN_UNUSED_RESULT bool RecursivelyCreateDir(std::string path); // Write a file in one shot. // When compiled with --define=tf=1, uses TensorFlow's file APIs to enable // access to GCS. Only allows local file access otherwise. MG_WARN_UNUSED_RESULT bool WriteFile(std::string path, absl::string_view contents); // Read a file in one shot. // When compiled with --define=tf=1, uses TensorFlow's file APIs to enable // access to GCS. Only allows local file access otherwise. MG_WARN_UNUSED_RESULT bool ReadFile(std::string path, std::string* contents); // Get the modification time for a file. // When compiled with --define=tf=1, uses TensorFlow's file APIs to enable // access to GCS. Only allows local file access otherwise. MG_WARN_UNUSED_RESULT bool GetModTime(std::string path, uint64_t* mtime_usec); // Fills 'files' with the names of the files in 'directory'. // When compiled with --define=tf=1, uses TensorFlow's file APIs to enable // access to GCS. Only allows local file access otherwise. MG_WARN_UNUSED_RESULT bool ListDir(std::string directory, std::vector<std::string>* files); // Check if specified path is a file. // When compiled with --define=tf=1, uses TensorFlow's file APIs to enable // access to GCS. Only allows local file access otherwise. MG_WARN_UNUSED_RESULT bool FileExists(std::string path); } // namespace file } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_FILE_UTILS_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/game_utils.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/game_utils.h" #include <cstring> #include <iostream> #include <utility> #include <vector> #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/str_format.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/sgf.h" namespace minigo { std::string FormatWinStatsTable( const std::vector<std::pair<std::string, WinStats>>& stats) { size_t name_length = 4; for (const auto& name_stats : stats) { name_length = std::max(name_length, name_stats.first.size()); } std::string result; auto append_header = [&](absl::string_view str) { absl::StrAppendFormat(&result, "%*s %s", name_length, "", str); }; auto append_stats = [&](absl::string_view name, const WinStats& stats) { const auto& b = stats.black_wins; const auto& w = stats.white_wins; absl::StrAppendFormat( &result, "\n%-*s %7d %7d %7d %7d %7d %7d", name_length, name, b.total(), b.both_passed, b.opponent_resigned, w.total(), w.both_passed, w.opponent_resigned); }; append_header( " Black Black Black White White White\n"); append_header( " total passes resign total passes resign"); for (const auto& name_stats : stats) { append_stats(name_stats.first, name_stats.second); } return result; } std::string GetOutputName(size_t game_id) { return absl::StrCat(GetHostname(), "-", GetProcessId(), "-", game_id); } void WriteSgf(const std::string& output_dir, const std::string& output_name, const Game& game, bool write_comments) { MG_CHECK(file::RecursivelyCreateDir(output_dir)); bool log_names = game.black_name() != game.white_name(); std::vector<sgf::MoveWithComment> moves; moves.reserve(game.moves().size()); for (size_t i = 0; i < game.moves().size(); ++i) { const auto* move = game.moves()[i].get(); std::string comment; if (write_comments) { if (i == 0) { comment = absl::StrCat("Resign Threshold: ", game.options().resign_threshold, "\n", move->comment); } else { if (log_names) { comment = absl::StrCat(move->color == Color::kBlack ? game.black_name() : game.white_name(), "\n", move->comment); } else { comment = move->comment; } } } moves.emplace_back(move->color, move->c, std::move(comment)); } sgf::CreateSgfOptions options; options.komi = game.options().komi; options.result = game.result_string(); options.black_name = game.black_name(); options.white_name = game.white_name(); options.game_comment = game.comment(); auto sgf_str = sgf::CreateSgfString(moves, options); auto output_path = file::JoinPath(output_dir, output_name + ".sgf"); MG_CHECK(file::WriteFile(output_path, sgf_str)); } void LogEndGameInfo(const Game& game, absl::Duration game_time) { std::cout << game.result_string() << std::endl; std::cout << "Playing game: " << absl::ToDoubleSeconds(game_time) << std::endl; std::cout << "Played moves: " << game.moves().size() << std::endl; if (game.moves().empty()) { return; } int bleakest_move = 0; float q = 0.0; if (game.FindBleakestMove(&bleakest_move, &q)) { std::cout << "Bleakest eval: move=" << bleakest_move << " Q=" << q << std::endl; } // If resignation is disabled, check to see if the first time Q_perspective // crossed the resign_threshold the eventual winner of the game would have // resigned. Note that we only check for the first resignation: if the // winner would have incorrectly resigned AFTER the loser would have // resigned on an earlier move, this is not counted as a bad resignation for // the winner (since the game would have ended after the loser's initial // resignation). if (!game.options().resign_enabled) { for (size_t i = 0; i < game.moves().size(); ++i) { const auto* move = game.moves()[i].get(); float Q_perspective = move->color == Color::kBlack ? move->Q : -move->Q; if (Q_perspective < game.options().resign_threshold) { if ((move->Q < 0) != (game.result() < 0)) { std::cout << "Bad resign: move=" << i << " Q=" << move->Q << std::endl; } break; } } } } } // namespace minigo <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/sample_records.h<|end_filename|> // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_SAMPLE_RECORDS_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_SAMPLE_RECORDS_H_ #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/commandlineflags.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/match.h" #include "REDACTEDstrings/str_format.h" #include "REDACTEDstrings/string_view.h" #include "REDACTEDstrings/strip.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/random.h" #include "third_party/tensorflow/core/lib/core/status.h" #include "third_party/tensorflow/core/lib/io/record_reader.h" #include "third_party/tensorflow/core/lib/io/record_writer.h" #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/platform/file_system.h" DECLARE_double(sample_frac); DECLARE_uint64(num_records); DECLARE_int32(num_read_threads); DECLARE_int32(num_write_threads); DECLARE_int32(compression); DECLARE_int32(files_per_pattern); DECLARE_bool(shuffle); DECLARE_string(dst); DECLARE_uint64(seed); namespace minigo { class ReadThread : public Thread { public: struct Options { float sample_frac = 1; }; ReadThread(std::vector<std::string> paths, const Options& options) : rnd_(FLAGS_seed, Random::kUniqueStream), paths_(std::move(paths)), options_(options) {} std::vector<tensorflow::tstring>& sampled_records() { return sampled_records_; } const std::vector<tensorflow::tstring>& sampled_records() const { return sampled_records_; } private: void Run() override; Random rnd_; const std::vector<std::string> paths_; std::vector<tensorflow::tstring> sampled_records_; const Options options_; }; class WriteThread : public Thread { public: struct Options { int shard = 0; int num_shards = 1; int compression = 1; }; WriteThread(std::vector<tensorflow::tstring> records, const std::string& path, const Options& options); private: void Run() override; std::string path_; std::vector<tensorflow::tstring> records_; const Options options_; }; template <typename T> void MoveAppend(std::vector<T>* src, std::vector<T>* dst) { if (dst->empty()) { *dst = std::move(*src); } else { std::move(std::begin(*src), std::end(*src), std::back_inserter(*dst)); src->clear(); } } std::vector<tensorflow::tstring> Read(std::vector<std::string> paths); void Shuffle(std::vector<tensorflow::tstring>* records); // void Write(std::vector<tensorflow::tstring> records, const std::string& // path); size_t Write(const std::vector<tensorflow::tstring>& records, const std::string& path); // void Run(std::vector<std::string> src_paths, const std::string& dst_path); size_t Run(const std::vector<std::string>& src_paths, const std::string& dst_path); } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_SAMPLE_RECORDS_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/algorithm.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ALGORITHM_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ALGORITHM_H_ #include <algorithm> #include <utility> #include "REDACTEDtypes/span.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" namespace minigo { template <typename T> inline int ArgMax(const T& container) { MG_CHECK(!container.empty()); return std::distance( std::begin(container), std::max_element(std::begin(container), std::end(container))); } template <typename T, typename Compare> inline int ArgMax(const T& container, Compare cmp) { MG_CHECK(!container.empty()); return std::distance(std::begin(container), std::max_element(std::begin(container), std::end(container), std::move(cmp))); } // Calculates ArgMax of an array of floats using SSE instructions and runs about // 5x faster than the ArgMax<float>. int ArgMaxSse(absl::Span<const float> span); } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ALGORITHM_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/include/mkldnn.hpp<|end_filename|> /******************************************************************************* * Copyright 2016-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /// @file /// C++ API #ifndef MKLDNN_HPP #define MKLDNN_HPP #include "mkldnn_config.h" #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <stdlib.h> #include <memory> #include <vector> #include <unordered_map> #include <algorithm> #include <iterator> #include "mkldnn.h" #if MKLDNN_GPU_RUNTIME == MKLDNN_RUNTIME_OCL #include <CL/cl.h> #endif #endif namespace mkldnn { /// @addtogroup cpp_api C++ API /// @{ /// @addtogroup cpp_api_utils Utils /// @{ /// Intel(R) MKL-DNN exception class. /// /// This class captures the status returned by the failed C API function, error /// message, and, optionally, handle of the primitive that caused the error. struct error: public std::exception { mkldnn_status_t status; const char *message; /// Constructs an error instance. /// /// @param astatus The error status returned by the C API. /// @param amessage The error message. error(mkldnn_status_t astatus, const char *amessage) : status(astatus), message(amessage) {} /// Returns the explanatory string. const char *what() const noexcept override { return message; } /// A convenience function for wrapping calls to the C API. Checks the /// return status and throws an #error in case of failure. /// /// @param status The error status returned by the C API. /// @param message The error message. static void wrap_c_api(mkldnn_status_t status, const char *message) { if (status != mkldnn_success) throw error(status, message); } }; /// A class that provides the destructor for an Intel(R) MKL-DNN C handle template <typename T> class handle_traits {}; /// A class for wrapping an Intel(R) MKL-DNN handle. It is used as the base /// class for primitive (#mkldnn_primitive_t), engine (#mkldnn_engine_t), and /// stream (#mkldnn_stream_t) handles. An object of the #mkldnn::handle class /// can be passed by value. This class enables wrapping: /// - Newly constructed handles. /// @n In this case, the constructed handle uses reference counting provided /// by @p std::shared_ptr with a proper deleter function specified through /// the @p handle_traits class. /// - Pre-existing handles returned by the Intel(R) MKL-DNN C API (for /// example, through mkldnn_primitive_get_primitive_desc()). /// @n In this case, an Intel(R) MKL-DNN C API handle is wrapped without a /// deleter because it is assumed that the handle wrapper for the original /// object deletes the handle (this model is similar to @p std::weak_ptr). template <typename T, typename traits=handle_traits<T>> class handle { private: static mkldnn_status_t dummy_destructor(T){ return mkldnn_success; } std::shared_ptr<typename std::remove_pointer<T>::type> _data; handle(const handle &&) = delete; handle &operator=(const handle &&other) = delete; protected: bool operator==(const T other) const { return other == _data.get(); } bool operator!=(const T other) const { return !(*this == other); } public: /// Constructs a C handle wrapper. /// @param t The C handle to wrap. /// @param weak A flag to specify whether to construct a weak wrapper. handle(T t, bool weak = false): _data(0) { reset(t, weak); } /// Empty constructor. /// /// Allows declaring an object before actual initialization /// (mostly for convenience). /// /// @warning /// Uninitialized object cannot be used in any library calls. /// Any attempt to use its methods or passing it to the other library /// function will lead to a thrown exception. handle(): handle((T)0, true) {} handle(const handle &other): _data(other._data) {} handle &operator=(const handle &other) { _data = other._data; return *this; } /// Resets the value of a C handle. /// @param t The new value of the C handle. /// @param weak A flag to specify whether the wrapper should be weak. void reset(T t, bool weak = false) { _data.reset(t, weak ? &dummy_destructor : traits::destructor); } /// Returns the value of the underlying C handle. T get(bool allow_emtpy = false) const { T result = _data.get(); if (allow_emtpy == false && result == nullptr) throw mkldnn::error(mkldnn_invalid_arguments, "attempt to use uninitialized object"); return result; } bool operator==(const handle &other) const { return other._data.get() == _data.get(); } bool operator!=(const handle &other) const { return !(*this == other); } }; #ifndef DOXYGEN_SHOULD_SKIP_THIS template <> struct handle_traits<mkldnn_memory_t> { static constexpr auto destructor = &mkldnn_memory_destroy; }; template <> struct handle_traits<mkldnn_primitive_desc_t> { static constexpr auto destructor = &mkldnn_primitive_desc_destroy; }; template <> struct handle_traits<mkldnn_primitive_t> { static constexpr auto destructor = &mkldnn_primitive_destroy; }; template <> struct handle_traits<mkldnn_primitive_desc_iterator_t> { static constexpr auto destructor = &mkldnn_primitive_desc_iterator_destroy; }; #endif struct stream; struct error; struct memory; struct primitive_desc; /// Base class for all computational primitives. class primitive: public handle<mkldnn_primitive_t> { friend struct error; friend struct stream; using handle::handle; public: /// Kinds of primitives. Used to implement a way to extend the library with /// new primitives without changing the ABI. enum class kind { /// Undefined primitive undef = mkldnn_undefined_primitive, /// A reorder primitive. reorder = mkldnn_reorder, /// A shuffle primitive. shuffle = mkldnn_shuffle, /// A (out-of-place) concat primitive. concat = mkldnn_concat, /// A sum primitive. sum = mkldnn_sum, /// A convolution primitive. convolution = mkldnn_convolution, /// A deconvolution primitive. deconvolution = mkldnn_deconvolution, /// An element-wise primitive. eltwise = mkldnn_eltwise, /// A softmax primitive. softmax = mkldnn_softmax, /// A pooling primitive. pooling = mkldnn_pooling, /// An LRN primitive. lrn = mkldnn_lrn, /// An batch normalization primitive. batch_normalization = mkldnn_batch_normalization, /// An inner product primitive. inner_product = mkldnn_inner_product, /// A rnn primitive. rnn = mkldnn_rnn, }; primitive(const_mkldnn_primitive_desc_t c_pd); primitive(const primitive_desc &pd); /// Returns the descriptor of the underlying C API primitive. inline const_mkldnn_primitive_desc_t get_primitive_desc() const; // TODO: use the C++ API wrapper structure. void execute(stream &astream, const std::unordered_map<int, memory> &args) const; }; inline mkldnn_primitive_kind_t convert_to_c(primitive::kind akind) { return static_cast<mkldnn_primitive_kind_t>(akind); } const_mkldnn_primitive_desc_t primitive::get_primitive_desc() const { const_mkldnn_primitive_desc_t pd; error::wrap_c_api(mkldnn_primitive_get_primitive_desc(get(), &pd), "could not get primitive descriptor by primitive"); return pd; } /// @} /// @addtogroup cpp_api_enums Common data types and enumerations /// A proxy to @ref c_api_types in @ref c_api. /// /// @{ /// Scratchpad mode enum class scratchpad_mode { /// The library manages scratchpad (default) library = mkldnn_scratchpad_mode_library, /// A user shall query and provide the scratchpad memory to primitives user = mkldnn_scratchpad_mode_user, }; inline mkldnn_scratchpad_mode_t convert_to_c(scratchpad_mode mode) { return static_cast<mkldnn_scratchpad_mode_t>(mode); } /// Propagation kind enum class prop_kind { /// Forward data propagation (training mode). In this mode primitives /// perform computations necessary for subsequent backward propagation. forward_training = mkldnn_forward_training, /// Forward data propagation (inference mode). In this mode primitives /// perform only computations that are necessary for inference and omit /// computations that are necessary only for backward propagation. forward_inference = mkldnn_forward_inference, /// Forward data propagation, /// alias for #mkldnn::prop_kind::forward_inference forward_scoring = mkldnn_forward_scoring, /// Forward data propagation, /// alias for #mkldnn::prop_kind::forward_training forward = mkldnn_forward, /// Backward propagation (with respect to all parameters). backward = mkldnn_backward, /// Backward data propagation. backward_data = mkldnn_backward_data, /// Backward weights propagation. backward_weights = mkldnn_backward_weights, /// Backward bias propagation. backward_bias = mkldnn_backward_bias }; inline mkldnn_prop_kind_t convert_to_c(prop_kind kind) { return static_cast<mkldnn_prop_kind_t>(kind); } /// Kinds of algorithms. enum class algorithm { undef = mkldnn_alg_kind_undef, /// Convolution algorithm(either direct or Winograd) is chosen just in time convolution_auto = mkldnn_convolution_auto, /// Direct convolution convolution_direct = mkldnn_convolution_direct, /// Winograd convolution convolution_winograd = mkldnn_convolution_winograd, /// Direct deconvolution deconvolution_direct = mkldnn_deconvolution_direct, /// Winograd deconvolution deconvolution_winograd = mkldnn_deconvolution_winograd, /// Eltwise: ReLU eltwise_relu = mkldnn_eltwise_relu, /// Eltwise: hyperbolic tangent non-linearity (tanh) eltwise_tanh = mkldnn_eltwise_tanh, /// Eltwise: parametric exponential linear unit (elu) eltwise_elu = mkldnn_eltwise_elu, /// Eltwise: square eltwise_square = mkldnn_eltwise_square, /// Eltwise: abs eltwise_abs = mkldnn_eltwise_abs, /// Eltwise: square root eltwise_sqrt = mkldnn_eltwise_sqrt, /// Eltwise: linear eltwise_linear = mkldnn_eltwise_linear, /// Eltwise: bounded_relu eltwise_bounded_relu = mkldnn_eltwise_bounded_relu, /// Eltwise: soft_relu eltwise_soft_relu = mkldnn_eltwise_soft_relu, /// Eltwise: logistic eltwise_logistic = mkldnn_eltwise_logistic, /// Eltwise: exponent eltwise_exp = mkldnn_eltwise_exp, /// Eltwise: gelu eltwise_gelu = mkldnn_eltwise_gelu, /// Local response normalization (LRN) across multiple channels lrn_across_channels = mkldnn_lrn_across_channels, /// LRN within a single channel lrn_within_channel = mkldnn_lrn_within_channel, /// Max pooling pooling_max = mkldnn_pooling_max, /// Average pooling exclude padding, /// alias for #mkldnn::algorithm::pooling_avg_include_padding pooling_avg = mkldnn_pooling_avg, /// Average pooling include padding pooling_avg_include_padding = mkldnn_pooling_avg_include_padding, /// Average pooling exclude padding pooling_avg_exclude_padding = mkldnn_pooling_avg_exclude_padding, /// RNN cell vanilla_rnn = mkldnn_vanilla_rnn, /// LSTM cell vanilla_lstm = mkldnn_vanilla_lstm, /// GRU cell vanilla_gru = mkldnn_vanilla_gru, /// GRU cell with linear before reset /// /// Modification of original GRU cell. Differs from #mkldnn_vanilla_gru /// in how the new memory gate is calculated: /// \f[ c_t = tanh(W_c*x_t + b_{c_x} + r_t*(U_c*h_{t-1}+b_{c_h})) \f] /// Primitive expects 4 biases on input: /// \f$[b_{u}, b_{r}, b_{c_x}, b_{c_h}]\f$ lbr_gru = mkldnn_lbr_gru, }; inline mkldnn_alg_kind_t convert_to_c(algorithm aalgorithm) { return static_cast<mkldnn_alg_kind_t>(aalgorithm); } /// Flags for batch normalization primitive. enum class normalization_flags : unsigned { /// Use global statistics /// /// If specified /// - on forward propagation use mean and variance provided by user (input) /// - on backward propagation reduces the amount of computations, since /// mean and variance are considered as constants /// /// If not specified: /// - on forward propagation mean and variance are computed and stored in /// output /// - on backward propagation compute full derivative wrt to data use_global_stats = mkldnn_use_global_stats, /// Use scale and shift parameters /// /// If specified: /// - on forward propagation use scale and shift (aka scale and bias) for /// the batch normalization results /// - on backward propagation /// (for prop_kind == #mkldnn::prop_kind::backward) compute /// diff wrt to scale and shift (hence one extra output used) /// /// If not specified: /// - on backward propagation /// prop_kind == #mkldnn::prop_kind::backward_data has the /// same behavior as prop_kind == #mkldnn::prop_kind::backward use_scale_shift = mkldnn_use_scaleshift, /// Fuse with ReLU /// /// If specified: /// - on inference this option behaves the same as if the primitive were /// fused with ReLU via post ops API /// - on training primitive requires workspace (required to be able to /// perform backward pass) fuse_norm_relu = mkldnn_fuse_norm_relu }; inline mkldnn_normalization_flags_t convert_to_c( normalization_flags aflag) { return static_cast<mkldnn_normalization_flags_t>(aflag); } enum class rnn_flags : unsigned { undef = mkldnn_rnn_flags_undef }; inline mkldnn_rnn_flags_t convert_to_c( rnn_flags aflag) { return static_cast<mkldnn_rnn_flags_t>(aflag); } #define MKLDNN_DEFINE_BITMASK_OPS(enum_name) \ inline enum_name operator|(enum_name lhs, enum_name rhs) { \ return static_cast<enum_name>( \ static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs)); \ } \ \ inline enum_name operator&(enum_name lhs, enum_name rhs) { \ return static_cast<enum_name>( \ static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs)); \ } \ \ inline enum_name operator^(enum_name lhs, enum_name rhs) { \ return static_cast<enum_name>( \ static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs)); \ } \ \ inline enum_name& operator|=(enum_name &lhs, enum_name rhs) { \ lhs = static_cast<enum_name>( \ static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs)); \ return lhs; \ } \ \ inline enum_name& operator&=(enum_name &lhs, enum_name rhs) { \ lhs = static_cast<enum_name>( \ static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs)); \ return lhs; \ } \ \ inline enum_name& operator^=(enum_name &lhs, enum_name rhs) { \ lhs = static_cast<enum_name>( \ static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs)); \ return lhs; \ } \ \ inline enum_name operator~(enum_name rhs) { \ return static_cast<enum_name>(~static_cast<unsigned>(rhs)); \ } \ MKLDNN_DEFINE_BITMASK_OPS(normalization_flags) MKLDNN_DEFINE_BITMASK_OPS(rnn_flags) #undef MKLDNN_DEFINE_BITMASK_OPS enum class rnn_direction { unidirectional_left2right = mkldnn_unidirectional_left2right, unidirectional_right2left = mkldnn_unidirectional_right2left, unidirectional = mkldnn_unidirectional, bidirectional_concat = mkldnn_bidirectional_concat, bidirectional_sum = mkldnn_bidirectional_sum, }; inline mkldnn_rnn_direction_t convert_to_c(rnn_direction adir) { return static_cast<mkldnn_rnn_direction_t>(adir); } /// Primitive descriptor query specification /// /// In general should be used from C++ API since required queries are directly /// implemented as class members (for instance, a query for source memory /// descriptor). /// /// For more information see @ref mkldnn_query_t. enum class query { /// no query undef = mkldnn_query_undef, /// execution engine engine = mkldnn_query_engine, /// primitive kind primitive_kind = mkldnn_query_primitive_kind, /// number of inputs expected num_of_inputs_s32 = mkldnn_query_num_of_inputs_s32, /// number of outputs expected num_of_outputs_s32 = mkldnn_query_num_of_outputs_s32, /// runtime estimation (seconds), unimplemented time_estimate_f64 = mkldnn_query_time_estimate_f64, /// memory consumption (bytes) /// /// extra (scratch) memory, additional to all inputs and outputs memory /// /// @sa @ref dev_guide_attributes_scratchpad memory_consumption_s64 = mkldnn_query_memory_consumption_s64, /// scratchpad engine /// /// engine to be used for creating scratchpad memory scratchpad_engine = mkldnn_query_scratchpad_engine, /// implementation name impl_info_str = mkldnn_query_impl_info_str, /// op descriptor op_d = mkldnn_query_op_d, /// convolution descriptor convolution_d = mkldnn_query_convolution_d, /// deconvolution descriptor deconvolution_d = mkldnn_query_deconvolution_d, /// shuffle descriptor shuffle_d = mkldnn_query_shuffle_d, /// eltwise descriptor eltwise_d = mkldnn_query_eltwise_d, /// softmax descriptor softmax_d = mkldnn_query_softmax_d, /// pooling descriptor pooling_d = mkldnn_query_pooling_d, /// lrn descriptor lrn_d = mkldnn_query_lrn_d, /// batch normalization descriptor batch_normalization_d = mkldnn_query_batch_normalization_d, /// inner product descriptor inner_product_d = mkldnn_query_inner_product_d, /// rnn descriptor rnn_d = mkldnn_query_rnn_d, /// source memory desc src_md = mkldnn_query_src_md, /// source gradient memory desc diff_src_md = mkldnn_query_diff_src_md, /// weights memory descriptor desc weights_md = mkldnn_query_weights_md, /// weights grad. memory desc diff_weights_md = mkldnn_query_diff_weights_md, /// destination memory desc dst_md = mkldnn_query_dst_md, /// destination grad. memory desc diff_dst_md = mkldnn_query_diff_dst_md, /// workspace memory desc workspace_md = mkldnn_query_workspace_md, /// scratchpad memory desc scratchpad_md = mkldnn_query_scratchpad_md, }; inline mkldnn_query_t convert_to_c(query aquery) { return static_cast<mkldnn_query_t>(aquery); } /// @} /// @addtogroup cpp_api_attr Attributes /// An extension for controlling primitive behavior. /// /// @sa @ref c_api_attributes in @ref c_api /// @{ #ifndef DOXYGEN_SHOULD_SKIP_THIS template <> struct handle_traits<mkldnn_post_ops_t> { static constexpr auto destructor = &mkldnn_post_ops_destroy; }; #endif /// Post operations /// /// @sa @ref dev_guide_attributes_post_ops struct post_ops: public handle<mkldnn_post_ops_t> { /// Creates an empty sequence of post operations. post_ops() { mkldnn_post_ops_t result; error::wrap_c_api(mkldnn_post_ops_create(&result), "could not create post operation sequence"); reset(result); } /// Returns the length of post operations int len() const { return mkldnn_post_ops_len(get()); } /// Returns the kind of post operation with index @p index. primitive::kind kind(int index) const { error::wrap_c_api( index < len() ? mkldnn_success : mkldnn_invalid_arguments, "post_ops index is out of range"); return static_cast<primitive::kind>(mkldnn_post_ops_get_kind(get(), index)); } /// Appends accumulation (sum) post operation. Prior to accumulating the /// result, the previous value would be multiplied by @p scale. /// /// The kind of this post operation is #mkldnn_sum. /// /// This feature might improve performance for cases like residual learning /// blocks, where the result of convolution is accumulated to the previously /// computed activations. The parameter @p scale might be extreme for the /// integer-based computations when the result and previous activations have /// different logical scaling factors. /// /// In the simplest case when the accumulation is the only post operation, /// the computations would be: /// dst[] <- scale * dst[] + op(...) // instead of dst[] <- op(...) /// /// @note /// This post operation (as well as all the others) disregards the /// original layout of the destination; that is, the layout of the /// original destination is expected to be the same as the layout of the /// stored destination. void append_sum(float scale = 1.) { error::wrap_c_api(mkldnn_post_ops_append_sum(get(), scale), "could not append sum"); } /// Gets the parameters of the accumulation (sum) post operation with index /// @p index. void get_params_sum(int index, float &scale) const { error::wrap_c_api(mkldnn_post_ops_get_params_sum(get(), index, &scale), "could not get sum params"); } /// Appends eltwise post operation. /// /// The kind of this post operation is #mkldnn_eltwise. /// /// In the simplest case when the eltwise is the only post operation, the /// computations would be: /// dst[] <- scale * eltwise_op ( op(...) ) // instead of dst[] <- op(...) /// where eltwise_op is configured with the given parameters. void append_eltwise(float scale, algorithm alg, float alpha, float beta) { error::wrap_c_api(mkldnn_post_ops_append_eltwise(get(), scale, convert_to_c(alg), alpha, beta), "could not append eltwise"); } /// Gets the eltwise parameters of the post operation with index @p index. void get_params_eltwise(int index, float &scale, algorithm &alg, float &alpha, float &beta) const { mkldnn_alg_kind_t c_alg; error::wrap_c_api(mkldnn_post_ops_get_params_eltwise(get(), index, &scale, &c_alg, &alpha, &beta), "could not get eltwise params"); alg = static_cast<algorithm>(c_alg); } }; #ifndef DOXYGEN_SHOULD_SKIP_THIS template <> struct handle_traits<mkldnn_primitive_attr_t> { static constexpr auto destructor = &mkldnn_primitive_attr_destroy; }; #endif /// Primitive attributes /// /// @sa @ref dev_guide_attributes struct primitive_attr: public handle<mkldnn_primitive_attr_t> { /// Creates a default primitive attribute. primitive_attr() { mkldnn_primitive_attr_t result; error::wrap_c_api(mkldnn_primitive_attr_create(&result), "could not create a primitive attr"); reset(result); } /// Returns the scratchpad mode. scratchpad_mode get_scratchpad_mode() const { mkldnn_scratchpad_mode_t result; error::wrap_c_api(mkldnn_primitive_attr_get_scratchpad_mode( get(), &result), "could not get scratchpad mode"); return scratchpad_mode(result); } /// Sets scratchpad mode. void set_scratchpad_mode(scratchpad_mode mode) { error::wrap_c_api(mkldnn_primitive_attr_set_scratchpad_mode( get(), mkldnn::convert_to_c(mode)), "could not set scratchpad mode"); } /// Gets correspondence scale @p mask and a constant floating point vector /// of output @p scales previously set by set_output_scales. void get_output_scales(int &mask, std::vector<float> &scales) const { mkldnn_dim_t count; int c_mask; const float *c_scales; error::wrap_c_api(mkldnn_primitive_attr_get_output_scales(get(), &count, &c_mask, &c_scales), "could not get int output scales"); scales.resize(count); mask = c_mask; for (mkldnn_dim_t c = 0; c < count; ++c) scales[c] = c_scales[c]; } /// Sets output scales for primitive operations. The correspondence scale /// @p mask is stored for future use. /// /// The @p mask argument defines the correspondence between the output /// tensor dimensions and the @p scales vector. Set the i-th bit of @p mask /// to 1 to use a dedicated scaling factor for each slice of the output /// tensor over the i-th dimension. Set @p mask to 0 to use a common /// scaling factor for the whole output tensor. /// /// @note /// The dimension order is always native and does not depend on the /// actual layout used. Examples: /// - 2D dimensional data the order of dimensions is always: (n, c) /// - 4D dimensional data the order is always: (n, c, h, w) /// - 5D dimensional weights the order is always: (g, oc, ic, kh, kw) void set_output_scales(int mask, const std::vector<float> &scales) { error::wrap_c_api(mkldnn_primitive_attr_set_output_scales(get(), (mkldnn_dim_t)scales.size(), mask, &scales[0]), "could not set int output scales"); } /// Returns @p post_ops previously set by set_post_ops. const post_ops get_post_ops() const { post_ops result; const_mkldnn_post_ops_t c_result; error::wrap_c_api(mkldnn_primitive_attr_get_post_ops(get(), &c_result), "could not get post operation sequence"); result.reset(const_cast<mkldnn_post_ops_t>(c_result), true); return result; } /// Sets @p post_ops for future use. void set_post_ops(post_ops ops) { error::wrap_c_api(mkldnn_primitive_attr_set_post_ops(get(), ops.get()), "could not set post operation sequence"); } /// Sets quantization @p scale and @p shift for RNN data tensors. For /// performance reasons, the low-precision configuration of the RNN /// primitive expects input activations to have the unsigned int8 data type. /// Scale and shift used to quantize floating-point data to unsigned integer /// must be passed to the RNN primitive using attributes. /// @note /// Quantization scale and shift are common for src_layer, src_iter, /// dst_iter, and dst_layer. void set_rnn_data_qparams(float scale, float shift) { error::wrap_c_api(mkldnn_primitive_attr_set_rnn_data_qparams(get(), scale, shift), "could not set rnn data int scale/shift"); } /// Sets quantization scales @p weights_scales for RNN weights tensors. The /// low-precision configuration of the RNN primitive expects input weights /// to have the signed int8 data type. Scales used to quantize /// floating-point data to signed integer must be passed to the RNN /// primitive using attributes. The @p mask argument defines correspondence /// between output tensor dimensions and the @p weights_scales array. Set /// the i-th bit of @p mask to 1 to use a dedicated scaling factor for each /// slice of the output tensor over the i-th dimension. Set @p mask to 0 to /// use a common scaling factor for the whole output tensor. /// @note /// The dimension order is always native and does not depend on the /// actual layout used. For example, five-dimensional weights always /// have (l, d, i, g, o) logical dimension ordering. /// @note /// Quantization scales are common for weights_layer and /// weights_iteration /// @note /// There is no way to check whether @p count corresponds to @p mask /// until an actual primitive descriptor is created, so it is the user's /// responsibility to set proper values. The following formula must /// hold: /// /// \f[count = \prod\limits_{d \in mask} output.dims[d]\f] void set_rnn_weights_qparams(int mask, const std::vector<float> &scales) { error::wrap_c_api(mkldnn_primitive_attr_set_rnn_weights_qparams(get(), (int)scales.size(), mask, &scales[0]), "could not set rnn weights int scales"); } }; /// @} /// @addtogroup cpp_api_engine Engine /// Engine operations. /// /// @sa @ref c_api_engine in @ref c_api /// @{ #ifndef DOXYGEN_SHOULD_SKIP_THIS template <> struct handle_traits<mkldnn_engine_t> { static constexpr auto destructor = &mkldnn_engine_destroy; }; #endif /// An execution engine. struct engine: public handle<mkldnn_engine_t> { friend class primitive; /// Kinds of engines. enum class kind { /// An unspecified engine any = mkldnn_any_engine, /// CPU engine cpu = mkldnn_cpu, /// GPU engine gpu = mkldnn_gpu, }; engine() = default; /// Returns the number of engines of a certain kind. /// /// @param akind The kind of engines to count. static size_t get_count(kind akind) { return mkldnn_engine_get_count(convert_to_c(akind)); } /// Constructs an engine. /// /// @param akind The kind of engine to construct. /// @param index The index of the engine. Must be less than the value /// returned by #get_count() for this particular kind /// of engine. engine(kind akind, size_t index) { mkldnn_engine_t aengine; error::wrap_c_api( mkldnn_engine_create(&aengine, convert_to_c(akind), index), "could not create an engine"); reset(aengine); } #if MKLDNN_GPU_RUNTIME == MKLDNN_RUNTIME_OCL /// Constructs an engine of particular @p akind associated with the given /// OpenCL @p device and @p context objects. engine(kind akind, cl_device_id device, cl_context context) { mkldnn_engine_t aengine; error::wrap_c_api(mkldnn_engine_create_ocl(&aengine, convert_to_c(akind), device, context), "could not create an engine"); reset(aengine); } #endif /// Constructs an engine from other engine @p aengine. explicit engine(const mkldnn_engine_t& aengine) : handle(aengine, true) {} /// Constructs an engine from the primitive descriptor @p pd /// by querying its engine. engine(const handle<mkldnn_primitive_desc_t> &pd) { mkldnn_engine_t engine_q; error::wrap_c_api( mkldnn_primitive_desc_query(pd.get(), mkldnn::convert_to_c(mkldnn::query::engine), 0, &engine_q), "could not get engine from primitive_desc"); reset(engine_q, true); } /// Returns the kind of the engine. kind get_kind() const { mkldnn_engine_kind_t akind; error::wrap_c_api(mkldnn_engine_get_kind(get(), &akind), "could not get the engine kind"); return static_cast<engine::kind>(akind); } #if MKLDNN_GPU_RUNTIME == MKLDNN_RUNTIME_OCL /// Returns the OpenCL context associated with the engine. cl_context get_ocl_context() const { cl_context context = nullptr; error::wrap_c_api(mkldnn_engine_get_ocl_context(get(), &context), "could not get a context handle"); return context; } /// Returns the OpenCL device associated with the engine. cl_device_id get_ocl_device() const { cl_device_id device = nullptr; error::wrap_c_api(mkldnn_engine_get_ocl_device(get(), &device), "could not get a device handle"); return device; } #endif template <class primitive_desc> static engine query(const primitive_desc &pd) { mkldnn_engine_t engine_q; error::wrap_c_api( mkldnn_primitive_desc_query(pd.get(), mkldnn::convert_to_c(mkldnn::query::engine), 0, &engine_q), "could not get engine from primitive_desc"); return engine(engine_q); } private: static mkldnn_engine_kind_t convert_to_c(kind akind) { return static_cast<mkldnn_engine_kind_t>(akind); } }; /// @} /// @addtogroup cpp_api_stream Stream /// Execution stream operations /// /// @sa @ref c_api_stream in @ref c_api /// @{ #ifndef DOXYGEN_SHOULD_SKIP_THIS template <> struct handle_traits<mkldnn_stream_t> { static constexpr auto destructor = &mkldnn_stream_destroy; }; #endif /// An execution stream. struct stream: public handle<mkldnn_stream_t> { using handle::handle; /// @brief Stream flags. enum class flags : unsigned { /// Default order execution. Either in-order or out-of-order depending /// on the engine runtime default_order = mkldnn_stream_default_order, /// In-order execution. in_order = mkldnn_stream_default_order, /// Out-of-order execution. out_of_order = mkldnn_stream_out_of_order, /// Default stream configuration. default_flags = mkldnn_stream_default_flags, }; stream() = default; /// Constructs a stream. stream(const engine &aengine, flags aflags = flags::default_flags) { mkldnn_stream_t astream; error::wrap_c_api(mkldnn_stream_create(&astream, aengine.get(), static_cast<mkldnn_stream_flags_t>(aflags)), "could not create a stream"); reset(astream); } #if MKLDNN_GPU_RUNTIME == MKLDNN_RUNTIME_OCL /// Constructs a stream associated with the engine @p eng and with the /// OpenCL command queue @p queue. stream(const engine &eng, cl_command_queue queue) { mkldnn_stream_t astream; error::wrap_c_api(mkldnn_stream_create_ocl(&astream, eng.get(), queue), "could not create a stream"); reset(astream); } /// Returns the OpenCL command queue associated with the stream. cl_command_queue get_ocl_command_queue() const { cl_command_queue queue = nullptr; error::wrap_c_api(mkldnn_stream_get_ocl_command_queue(get(), &queue), "could not get OpenCL command queue"); return queue; } #endif /// Waits for all primitives in the stream to finish. stream &wait() { error::wrap_c_api(mkldnn_stream_wait(get()), "could not wait a stream"); return *this; } }; inline stream::flags operator|(stream::flags lhs, stream::flags rhs) { return static_cast<stream::flags>( static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs)); } inline stream::flags operator&(stream::flags lhs, stream::flags rhs) { return static_cast<stream::flags>( static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs)); } inline stream::flags operator^(stream::flags lhs, stream::flags rhs) { return static_cast<stream::flags>( static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs)); } inline stream::flags operator~(stream::flags rhs) { return static_cast<stream::flags>(~static_cast<unsigned>(rhs)); } /// @} /// @addtogroup cpp_api_memory_related Memory and memory related operations /// @{ /// @addtogroup cpp_api_memory Memory /// A primitive to describe and store data. /// /// For more information, refer to @ref c_api_memory in @ref c_api. /// @{ /// Memory that describes the data. struct memory: public handle<mkldnn_memory_t> { typedef mkldnn_dim_t dim; typedef std::vector<dim> dims; template <typename T> static void validate_dims(const std::vector<T> &v) { if (v.size() > MKLDNN_MAX_NDIMS) throw error(mkldnn_invalid_arguments, "invalid dimensions"); } /// Data type specification enum class data_type { /// Undefined data type, used for empty memory descriptors. undef = mkldnn_data_type_undef, /// 16-bit/half-precision floating point. f16 = mkldnn_f16, /// non-standard 16-bit (bfloat16 w/ 7 bit mantissa) floating point. bf16 = mkldnn_bf16, /// 32-bit/single-precision floating point. f32 = mkldnn_f32, /// 32-bit signed integer. s32 = mkldnn_s32, /// 8-bit signed integer. s8 = mkldnn_s8, /// 8-bit unsigned integer. u8 = mkldnn_u8, }; /// Memory format kind enum class format_kind { /// Undefined memory format kind, used for empty memory descriptors. undef = mkldnn_format_kind_undef, /// Unspecified format kind. /// The primitive selects a format automatically. any = mkldnn_format_kind_any, /// A tensor in a generic format described by the stride and blocking /// values in each dimension. See @ref mkldnn_blocking_desc_t for more /// information. blocked = mkldnn_blocked, /// Weights format used in 8bit Winograd convolution wino = mkldnn_format_kind_wino, /// Packed weights format used in RNN packed = mkldnn_format_kind_rnn_packed, }; /// Memory format tag specification. See @ref mkldnn_format_tag_t for a /// detailed description. enum class format_tag { /// Undefined memory format tag undef = mkldnn_format_tag_undef, /// Placeholder memory format tag. The primitive selects a format /// automatically. any = mkldnn_format_tag_any, // Semantic agnostic section // The physical order of dimensions is defined by the permutation of the // characters, assuming that ab..z defines the natural order. // Plain formats a = mkldnn_a, ///< plain 1D tensor ab = mkldnn_ab, ///< plain 2D tensor abc = mkldnn_abc, ///< plain 3D tensor abcd = mkldnn_abcd, ///< plain 4D tensor abcde = mkldnn_abcde, ///< plain 5D tensor abcdef = mkldnn_abcdef, ///< plain 6D tensor // Permuted plain formats abdec = mkldnn_abdec, ///< permuted 5D tensor acb = mkldnn_acb, ///< permuted 3D tensor acbde = mkldnn_acbde, ///< permuted 5D tensor acdb = mkldnn_acdb, ///< permuted 4D tensor acdeb = mkldnn_acdeb, ///< permuted 5D tensor ba = mkldnn_ba, ///< permuted 2D tensor bac = mkldnn_bac, ///< permuted 3D tensor bacd = mkldnn_bacd, ///< permuted 4D tensor bcda = mkldnn_bcda, ///< permuted 4D tensor cba = mkldnn_cba, ///< permuted 3D tensor cdba = mkldnn_cdba, ///< permuted 4D tensor cdeba = mkldnn_cdeba, ///< permuted 5D tensor decab = mkldnn_decab, ///< permuted 5D tensor // Opaque blocked formats Abc16a = mkldnn_Abc16a, ABc16a16b = mkldnn_ABc16a16b, aBc16b = mkldnn_aBc16b, ABc16b16a = mkldnn_ABc16b16a, Abc4a = mkldnn_Abc4a, aBc4b = mkldnn_aBc4b, ABc4b16a4b = mkldnn_ABc4b16a4b, ABc4b4a = mkldnn_ABc4b4a, ABc8a16b2a = mkldnn_ABc8a16b2a, ABc8a8b = mkldnn_ABc8a8b, aBc8b = mkldnn_aBc8b, ABc8b16a2b = mkldnn_ABc8b16a2b, ABc8b8a = mkldnn_ABc8b8a, Abcd16a = mkldnn_Abcd16a, ABcd16a16b = mkldnn_ABcd16a16b, aBcd16b = mkldnn_aBcd16b, ABcd16b16a = mkldnn_ABcd16b16a, aBCd16b16c = mkldnn_aBCd16b16c, aBCd16c16b = mkldnn_aBCd16c16b, Abcd4a = mkldnn_Abcd4a, aBcd4b = mkldnn_aBcd4b, ABcd4b16a4b = mkldnn_ABcd4b16a4b, ABcd4b4a = mkldnn_ABcd4b4a, aBCd4c16b4c = mkldnn_aBCd4c16b4c, aBCd4c4b = mkldnn_aBCd4c4b, ABcd8a16b2a = mkldnn_ABcd8a16b2a, ABcd8a8b = mkldnn_ABcd8a8b, /// 4D tensor blocked by 2nd dimension with block size 8 aBcd8b = mkldnn_aBcd8b, ABcd8b16a2b = mkldnn_ABcd8b16a2b, aBCd8b16c2b = mkldnn_aBCd8b16c2b, /// 4D tensor blocked by 1st and 2nd dimension with block size 8 ABcd8b8a = mkldnn_ABcd8b8a, aBCd8b8c = mkldnn_aBCd8b8c, aBCd8c16b2c = mkldnn_aBCd8c16b2c, aBCd8c8b = mkldnn_aBCd8c8b, Abcde16a = mkldnn_Abcde16a, ABcde16a16b = mkldnn_ABcde16a16b, aBcde16b = mkldnn_aBcde16b, ABcde16b16a = mkldnn_ABcde16b16a, aBCde16b16c = mkldnn_aBCde16b16c, aBCde16c16b = mkldnn_aBCde16c16b, aBCde2c8b4c = mkldnn_aBCde2c8b4c, Abcde4a = mkldnn_Abcde4a, aBcde4b = mkldnn_aBcde4b, ABcde4b4a = mkldnn_ABcde4b4a, aBCde4b4c = mkldnn_aBCde4b4c, aBCde4c16b4c = mkldnn_aBCde4c16b4c, aBCde4c4b = mkldnn_aBCde4c4b, Abcde8a = mkldnn_Abcde8a, ABcde8a8b = mkldnn_ABcde8a8b, aBcde8b = mkldnn_aBcde8b, ABcde8b16a2b = mkldnn_ABcde8b16a2b, aBCde8b16c2b = mkldnn_aBCde8b16c2b, ABcde8b8a = mkldnn_ABcde8b8a, aBCde8b8c = mkldnn_aBCde8b8c, ABcd4a8b8a4b = mkldnn_ABcd4a8b8a4b, ABcd2a8b8a2b = mkldnn_ABcd2a8b8a2b, aBCde4b8c8b4c = mkldnn_aBCde4b8c8b4c, aBCde2b8c8b2c = mkldnn_aBCde2b8c8b2c, aBCde8c16b2c = mkldnn_aBCde8c16b2c, aBCde8c8b = mkldnn_aBCde8c8b, aBcdef16b = mkldnn_aBcdef16b, aBCdef16b16c = mkldnn_aBCdef16b16c, aBCdef16c16b = mkldnn_aBCdef16c16b, aBcdef4b = mkldnn_aBcdef4b, aBCdef4c4b = mkldnn_aBCdef4c4b, aBCdef8b8c = mkldnn_aBCdef8b8c, aBCdef8c16b2c = mkldnn_aBCdef8c16b2c, aBCdef8c8b = mkldnn_aBCdef8c8b, aBdc16b = mkldnn_aBdc16b, aBdc4b = mkldnn_aBdc4b, aBdc8b = mkldnn_aBdc8b, aBdec16b = mkldnn_aBdec16b, aBdec4b = mkldnn_aBdec4b, aBdec8b = mkldnn_aBdec8b, aBdefc16b = mkldnn_aBdefc16b, aCBdef16c16b = mkldnn_aCBdef16c16b, aBdefc4b = mkldnn_aBdefc4b, aBdefc8b = mkldnn_aBdefc8b, Acb16a = mkldnn_Acb16a, Acb4a = mkldnn_Acb4a, Acb8a = mkldnn_Acb8a, aCBd16b16c = mkldnn_aCBd16b16c, aCBd16c16b = mkldnn_aCBd16c16b, aCBde16b16c = mkldnn_aCBde16b16c, aCBde16c16b = mkldnn_aCBde16c16b, Acdb16a = mkldnn_Acdb16a, Acdb4a = mkldnn_Acdb4a, Acdb8a = mkldnn_Acdb8a, Acdeb16a = mkldnn_Acdeb16a, Acdeb4a = mkldnn_Acdeb4a, Acdeb8a = mkldnn_Acdeb8a, BAc16a16b = mkldnn_BAc16a16b, BAc16b16a = mkldnn_BAc16b16a, BAcd16a16b = mkldnn_BAcd16a16b, BAcd16b16a = mkldnn_BAcd16b16a, ABcd32a32b = mkldnn_ABcd32a32b, BAcde16b16 = mkldnn_BAcde16b16a, aBdec32b = mkldnn_aBdec32b, Abcdef16a = mkldnn_Abcdef16a, Acdb32a = mkldnn_Acdb32a, format_tag_last = mkldnn_format_tag_last, x = mkldnn_x, /// 2D CNN activations tensor, /// an alias to #mkldnn::memory::format_tag::ab nc = mkldnn_nc, cn = mkldnn_cn, ncw = mkldnn_ncw, nwc = mkldnn_nwc, /// 4D CNN activations tensor, /// an alias to #mkldnn::memory::format_tag::abcd nchw = mkldnn_nchw, /// 4D CNN activations tensor, /// an alias to #mkldnn::memory::format_tag::acdb nhwc = mkldnn_nhwc, /// 4D CNN activations tensor, /// an alias to #mkldnn::memory::format_tag::bcda chwn = mkldnn_chwn, ncdhw = mkldnn_ncdhw, ndhwc = mkldnn_ndhwc, oi = mkldnn_oi, io = mkldnn_io, oiw = mkldnn_oiw, wio = mkldnn_wio, oihw = mkldnn_oihw, hwio = mkldnn_hwio, ihwo = mkldnn_ihwo, iohw = mkldnn_iohw, oidhw = mkldnn_oidhw, dhwio = mkldnn_dhwio, goiw = mkldnn_goiw, goihw = mkldnn_goihw, hwigo = mkldnn_hwigo, giohw = mkldnn_giohw, goidhw = mkldnn_goidhw, tnc = mkldnn_tnc, ntc = mkldnn_ntc, ldnc = mkldnn_ldnc, ldigo = mkldnn_ldigo, ldgoi = mkldnn_ldgoi, ldgo = mkldnn_ldgo, nCdhw16c = mkldnn_nCdhw16c, nCdhw4c = mkldnn_nCdhw4c, nCdhw8c = mkldnn_nCdhw8c, nChw16c = mkldnn_nChw16c, nChw4c = mkldnn_nChw4c, nChw8c = mkldnn_nChw8c, nCw16c = mkldnn_nCw16c, nCw4c = mkldnn_nCw4c, nCw8c = mkldnn_nCw8c, NCw16n16c = mkldnn_NCw16n16c, NChw16n16c = mkldnn_NChw16n16c, NCdhw16n16c = mkldnn_NCdhw16n16c, NChw32n32c = mkldnn_NChw32n32c, IOhw16i16o = mkldnn_IOhw16i16o, Ohwi32o = mkldnn_Ohwi32o, IOdhw16i16o = mkldnn_IOdhw16i16o, gIOhw16i16o = mkldnn_gIOhw16i16o, gOhwi32o = mkldnn_gOhwi32o, Goidhw16g = mkldnn_Goidhw16g, IOw16o16i = mkldnn_IOw16o16i, OIw16i16o = mkldnn_OIw16i16o, IOw16i16o = mkldnn_IOw16i16o, gIOw16i16o = mkldnn_gIOw16i16o, OIw16o16i = mkldnn_OIw16o16i, Oiw16o = mkldnn_Oiw16o, OIw4i16o4i = mkldnn_OIw4i16o4i, OIw4i4o = mkldnn_OIw4i4o, Oiw4o = mkldnn_Oiw4o, OIw8i16o2i = mkldnn_OIw8i16o2i, OIw8i8o = mkldnn_OIw8i8o, OIw8o16i2o = mkldnn_OIw8o16i2o, OIw8o8i = mkldnn_OIw8o8i, Owi16o = mkldnn_Owi16o, Owi4o = mkldnn_Owi4o, Owi8o = mkldnn_Owi8o, IOhw16o16i = mkldnn_IOhw16o16i, Ohwi16o = mkldnn_Ohwi16o, Ohwi4o = mkldnn_Ohwi4o, Ohwi8o = mkldnn_Ohwi8o, OIhw16i16o = mkldnn_OIhw16i16o, OIhw16o16i = mkldnn_OIhw16o16i, Oihw16o = mkldnn_Oihw16o, OIhw4i16o4i = mkldnn_OIhw4i16o4i, OIhw4i4o = mkldnn_OIhw4i4o, Oihw4o = mkldnn_Oihw4o, OIhw8i16o2i = mkldnn_OIhw8i16o2i, OIhw8i8o = mkldnn_OIhw8i8o, OIhw8o16i2o = mkldnn_OIhw8o16i2o, OIhw8o8i = mkldnn_OIhw8o8i, Odhwi16o = mkldnn_Odhwi16o, Odhwi4o = mkldnn_Odhwi4o, Odhwi8o = mkldnn_Odhwi8o, OIdhw16i16o = mkldnn_OIdhw16i16o, OIdhw16o16i = mkldnn_OIdhw16o16i, Oidhw16o = mkldnn_Oidhw16o, OIdhw4i4o = mkldnn_OIdhw4i4o, Oidhw4o = mkldnn_Oidhw4o, OIdhw8i16o2i = mkldnn_OIdhw8i16o2i, OIdhw8i8o = mkldnn_OIdhw8i8o, OIdhw8o8i = mkldnn_OIdhw8o8i, gIOw16o16i = mkldnn_gIOw16o16i, gOIw16i16o = mkldnn_gOIw16i16o, gOIw16o16i = mkldnn_gOIw16o16i, gOiw16o = mkldnn_gOiw16o, gOIw4i16o4i = mkldnn_gOIw4i16o4i, gOIw4i4o = mkldnn_gOIw4i4o, gOiw4o = mkldnn_gOiw4o, gOIw8i16o2i = mkldnn_gOIw8i16o2i, gOIw8i8o = mkldnn_gOIw8i8o, gOIw8o16i2o = mkldnn_gOIw8o16i2o, gOIw8o8i = mkldnn_gOIw8o8i, gOwi16o = mkldnn_gOwi16o, gOwi4o = mkldnn_gOwi4o, gOwi8o = mkldnn_gOwi8o, gIOhw16o16i = mkldnn_gIOhw16o16i, gOhwi16o = mkldnn_gOhwi16o, gOhwi4o = mkldnn_gOhwi4o, gOhwi8o = mkldnn_gOhwi8o, Goihw16g = mkldnn_Goihw16g, gOIhw16i16o = mkldnn_gOIhw16i16o, gOIhw16o16i = mkldnn_gOIhw16o16i, gOihw16o = mkldnn_gOihw16o, gOIhw2i8o4i = mkldnn_gOIhw2i8o4i, gOIhw4i16o4i = mkldnn_gOIhw4i16o4i, gOIhw4i4o = mkldnn_gOIhw4i4o, gOIhw4o4i = mkldnn_gOIhw4o4i, gOihw4o = mkldnn_gOihw4o, Goihw8g = mkldnn_Goihw8g, gOIhw8i16o2i = mkldnn_gOIhw8i16o2i, gOIhw8i8o = mkldnn_gOIhw8i8o, gOIhw8o16i2o = mkldnn_gOIhw8o16i2o, OIhw4o8i8o4i = mkldnn_OIhw4o8i8o4i, OIhw2o8i8o2i = mkldnn_OIhw2o8i8o2i, gOIhw4o8i8o4i = mkldnn_gOIhw4o8i8o4i, gOIhw2o8i8o2i = mkldnn_gOIhw2o8i8o2i, gOIhw8o8i = mkldnn_gOIhw8o8i, gIOdhw16i16o = mkldnn_gIOdhw16i16o, gOdhwi16o = mkldnn_gOdhwi16o, gOdhwi4o = mkldnn_gOdhwi4o, gOdhwi8o = mkldnn_gOdhwi8o, gOIdhw16i16o = mkldnn_gOIdhw16i16o, gOIdhw16o16i = mkldnn_gOIdhw16o16i, gOidhw16o = mkldnn_gOidhw16o, gOIdhw4i4o = mkldnn_gOIdhw4i4o, gOidhw4o = mkldnn_gOidhw4o, gOIdhw8i16o2i = mkldnn_gOIdhw8i16o2i, gOIdhw8i8o = mkldnn_gOIdhw8i8o, gOIdhw8o8i = mkldnn_gOIdhw8o8i, }; /// A memory descriptor. struct desc { friend struct memory; /// The underlying C API data structure. mkldnn_memory_desc_t data; /// Constructs a zero memory descriptor desc(): data() {} /// Constructs a memory descriptor. /// /// @param adims Data dimensions /// @param adata_type Data precision/type. /// @param aformat_tag Data layout format tag. desc(const dims &adims, data_type adata_type, format_tag aformat_tag) { validate_dims(adims); error::wrap_c_api(mkldnn_memory_desc_init_by_tag(&data, (int)adims.size(), adims.size() == 0 ? nullptr : &adims[0], convert_to_c(adata_type), convert_to_c(aformat_tag)), "could not initialize a memory descriptor by tag"); } /// Constructs a memory descriptor by strides. /// /// @param adims Data dimensions /// @param adata_type Data precision/type. /// @param astrides The strides for dimensions. desc(const dims &adims, data_type adata_type, const dims &astrides) { validate_dims(adims); error::wrap_c_api(mkldnn_memory_desc_init_by_strides(&data, (int)adims.size(), adims.size() == 0 ? nullptr : &adims[0], convert_to_c(adata_type), astrides.size() == 0 ? nullptr : &astrides[0]), "could not initialize a memory descriptor by strides"); } /// Constructs a memory descriptor from a C API data structure. /// /// @param adata A C API #mkldnn_memory_desc_t structure. desc(const mkldnn_memory_desc_t &adata): data(adata) {} /// Constructs a sub-memory descriptor. // /// @param adims Sizes of a sub-memory /// @param offsets Offsets of a sub-memory desc submemory_desc(const dims &adims, const dims &offsets) { mkldnn_memory_desc_t sub_md; error::wrap_c_api(mkldnn_memory_desc_init_submemory(&sub_md, &data, &adims[0], &offsets[0]), "could not initialize a sub-memory"); return desc(sub_md); } /// Returns the number of bytes required to allocate the memory /// described including the padding area. size_t get_size() const { return mkldnn_memory_desc_get_size(&data); } /// Returns true if the memory descriptor describes an empty memory bool is_zero() const { return data.ndims == 0; } bool operator==(const desc &other) const { return mkldnn_memory_desc_equal(&data, &other.data) != 0; } bool operator!=(const desc &other) const { return !operator==(other); } }; memory() = default; /// Constructs a memory. /// /// @param md Memory descriptor. /// @param aengine Engine. /// @param ahandle handle. memory(const desc &md, const engine &aengine, void *ahandle) { mkldnn_memory_t result; error::wrap_c_api(mkldnn_memory_create(&result, &md.data, aengine.get(), ahandle), "could not create a memory"); reset(result); } /// Constructs a memory. /// /// @param md Memory descriptor. /// @param aengine Engine. memory(const desc &md, const engine &aengine) : memory(md, aengine, MKLDNN_MEMORY_ALLOCATE) {} /// Returns the descriptor of the memory. desc get_desc() const { const mkldnn_memory_desc_t *cdesc; error::wrap_c_api(mkldnn_memory_get_memory_desc(get(), &cdesc), "could not get memory descriptor from a memory"); return desc(*cdesc); } /// Returns the engine of the memory. engine get_engine() const { mkldnn_engine_t engine_q; error::wrap_c_api(mkldnn_memory_get_engine(get(), &engine_q), "could not get engine from a memory"); return engine(engine_q); } /// Returns a handle of the data contained in the memory. /// /// On the CPU engine, this is a pointer to the allocated memory. void *get_data_handle() const { void *handle; error::wrap_c_api(mkldnn_memory_get_data_handle(get(), &handle), "could not get native handle"); return handle; } void set_data_handle(void *handle) const { error::wrap_c_api(mkldnn_memory_set_data_handle(get(), handle), "could not set native handle"); } /// Maps the data of the memory. /// /// Mapping allows to read/write directly from/to the memory contents for /// engines that do not support direct memory access. /// /// Mapping is an exclusive operation - a memory object cannot be used in /// other operations until this memory object is unmapped. /// @tparam T Type of the pointer to be mapped. /// /// @note Any primitives working with the memory should be completed before /// mapping. Use stream::wait() to synchronize the corresponding /// execution stream. /// /// @note Map/unmap API is provided mainly for debug/testing purposes and /// its performance may be suboptimal. template <typename T = void> T *map_data() const { void *mapped_ptr; error::wrap_c_api(mkldnn_memory_map_data(get(), &mapped_ptr), "could not map the data"); return static_cast<T *>(mapped_ptr); } /// Unmaps the previously mapped data for the memory. /// /// Any changes of the mapped data are synchronized back to the memory /// after the call is complete. The mapped pointer must be /// obtained through a map_data() call. /// /// @note Map/unmap API is provided mainly for debug/testing purposes and /// its performance may be suboptimal. void unmap_data(void *mapped_ptr) const { error::wrap_c_api(mkldnn_memory_unmap_data(get(), mapped_ptr), "could not unmap the data"); } #if MKLDNN_GPU_RUNTIME == MKLDNN_RUNTIME_OCL /// Returns the OpenCL memory object associated with the memory. cl_mem get_ocl_mem_object() const { cl_mem mem_object; error::wrap_c_api(mkldnn_memory_get_ocl_mem_object(get(), &mem_object), "could not get OpenCL memory object"); return mem_object; } /// Sets the OpenCL memory object @p mem_object associated with the memory. void set_ocl_mem_object(cl_mem mem_object) { error::wrap_c_api(mkldnn_memory_set_ocl_mem_object(get(), mem_object), "could not set OpenCL memory object"); } #endif // Must go away or be private: static mkldnn_data_type_t convert_to_c(data_type adata_type) { return static_cast<mkldnn_data_type_t>(adata_type); } static mkldnn_format_tag_t convert_to_c(format_tag aformat) { return static_cast<mkldnn_format_tag_t>(aformat); } }; inline bool operator==(mkldnn_data_type_t a, memory::data_type b) { return a == memory::convert_to_c(b); } inline bool operator!=(mkldnn_data_type_t a, memory::data_type b) { return !(a == b); } inline bool operator==(memory::data_type a, mkldnn_data_type_t b) { return b == a; } inline bool operator!=(memory::data_type a, mkldnn_data_type_t b) { return !(a == b); } inline bool operator==(mkldnn_format_tag_t a, memory::format_tag b) { return a == memory::convert_to_c(b); } inline bool operator!=(mkldnn_format_tag_t a, memory::format_tag b) { return !(a == b); } inline bool operator==(memory::format_tag a, mkldnn_format_tag_t b) { return b == a; } inline bool operator!=(memory::format_tag a, mkldnn_format_tag_t b) { return !(a == b); } /// @} /// @addtogroup cpp_api_reorder Reorder /// A primitive to copy data between memory formats. /// /// @sa @ref dev_guide_reorder in developer guide /// @sa @ref c_api_reorder in @ref c_api /// @{ /// Initializes a reorder primitive using the description of the source /// (@p src_engine and @p src_md) and destination (@p dst_engine and @p dst_md) /// memory, and an @p attr attribute. struct reorder : public primitive { struct primitive_desc : public handle<mkldnn_primitive_desc_t> { primitive_desc() = default; primitive_desc(const engine &src_engine, const memory::desc &src_md, const engine &dst_engine, const memory::desc &dst_md, const primitive_attr &aattr = primitive_attr()) { mkldnn_primitive_desc_t result; error::wrap_c_api(mkldnn_reorder_primitive_desc_create(&result, &src_md.data, src_engine.get(), &dst_md.data, dst_engine.get(), aattr.get()), "could not create a reorder primitive descriptor"); reset(result); } primitive_desc(const memory &src, const memory &dst, const primitive_attr &aattr = primitive_attr()) { mkldnn_primitive_desc_t result; auto src_md = src.get_desc(); auto dst_md = dst.get_desc(); error::wrap_c_api(mkldnn_reorder_primitive_desc_create(&result, &src_md.data, src.get_engine().get(), &dst_md.data, dst.get_engine().get(), aattr.get()), "could not create a reorder primitive descriptor"); reset(result); } /// Queries scratchpad memory descriptor. /// /// @sa @ref dev_guide_attributes_scratchpad /// Returns a zero_md if no scratchpad is required. memory::desc scratchpad_desc() const { const mkldnn_memory_desc_t *cdesc = mkldnn_primitive_desc_query_md( get(), mkldnn::convert_to_c(query::scratchpad_md), 0); return memory::desc(*cdesc); } engine scratchpad_engine() { mkldnn_engine_t engine_q; error::wrap_c_api( mkldnn_primitive_desc_query(get(), mkldnn::convert_to_c(query::scratchpad_engine), 0, &engine_q), "could not get scratchpad engine from reorder primitive_desc"); return engine(engine_q); } engine get_engine() { return engine::query(*this); } }; reorder() = default; reorder(const primitive_desc &pd): primitive(pd.get()) {} reorder(const memory &src, const memory &dst): primitive(primitive_desc(src, dst).get()) {} using primitive::execute; void execute(stream astream, memory &src, memory &dst) { primitive::execute(astream, {{MKLDNN_ARG_FROM, src}, {MKLDNN_ARG_TO, dst}}); } }; /// @} /// @addtogroup cpp_api_concat Concat /// A primitive to concatenate data by arbitrary dimension. /// /// @sa @ref dev_guide_concat in developer guide /// @sa @ref c_api_concat in @ref c_api /// @{ /// Implements primitive descriptor and primitive for concat. /// /// Creates an out-of-place primitive descriptor for concatenation of @p n /// inputs by @p concat_dimension with resulting @p output_desc memory /// descriptor. @p output_desc can be NULL or specified with the /// #mkldnn::memory::format_tag::any format kind--in this case, the appropriate memory /// format would be chosen automatically. struct concat : public primitive { struct primitive_desc : public handle<mkldnn_primitive_desc_t> { std::vector<mkldnn_memory_desc_t> cpp_to_c( const std::vector<memory::desc> &srcs) { std::vector<mkldnn_memory_desc_t> c_api_srcs; c_api_srcs.reserve(srcs.size()); for (const auto &s : srcs) c_api_srcs.push_back(s.data); return c_api_srcs; } primitive_desc() = default; primitive_desc(const memory::desc &dst, int concat_dimension, const std::vector<memory::desc> &srcs, const engine &aengine, const primitive_attr &aattr = primitive_attr()) { auto c_api_srcs = cpp_to_c(srcs); mkldnn_primitive_desc_t result; error::wrap_c_api( mkldnn_concat_primitive_desc_create(&result, &dst.data, (int)c_api_srcs.size(), concat_dimension, &c_api_srcs[0], aattr.get(), aengine.get()), "could not create a concat primitive descriptor"); reset(result); } primitive_desc(int concat_dimension, const std::vector<memory::desc> &srcs, const engine &aengine, const primitive_attr &aattr = primitive_attr()) { auto c_api_srcs = cpp_to_c(srcs); mkldnn_primitive_desc_t result; error::wrap_c_api( mkldnn_concat_primitive_desc_create(&result, nullptr, (int)c_api_srcs.size(), concat_dimension, &c_api_srcs[0], aattr.get(), aengine.get()), "could not create a concat primitive descriptor"); reset(result); } /// Queries destination memory descriptor. memory::desc dst_desc() const { const mkldnn_memory_desc_t *cdesc = mkldnn_primitive_desc_query_md( get(), mkldnn::convert_to_c(query::dst_md), 0); return memory::desc(*cdesc); } /// Queries scratchpad memory descriptor. /// /// @sa @ref dev_guide_attributes_scratchpad /// Returns a zero_md if no scratchpad is required. memory::desc scratchpad_desc() const { const mkldnn_memory_desc_t *cdesc = mkldnn_primitive_desc_query_md( get(), mkldnn::convert_to_c(query::scratchpad_md), 0); return memory::desc(*cdesc); } engine get_engine() { return engine::query(*this); } }; concat() = default; concat(const primitive_desc &pd): primitive(pd.get()) {} }; /// @} /// @addtogroup cpp_api_sum Sum /// A primitive to sum data. /// /// @sa @ref dev_guide_sum in developer guide /// @sa @ref c_api_sum in @ref c_api /// @{ /// Creates an out-of-place sum primitive descriptor for sum of @p n inputs /// multiplied by the scale with resulting @p output_desc memory descriptor. /// @p output_desc can be NULL or specified with the /// #mkldnn::memory::format_tag::any format kind--in this case, the /// appropriate memory format would be chosen automatically. struct sum : public primitive { struct primitive_desc : public handle<mkldnn_primitive_desc_t> { std::vector<mkldnn_memory_desc_t> cpp_to_c( const std::vector<memory::desc> &srcs) { std::vector<mkldnn_memory_desc_t> c_api_srcs; c_api_srcs.reserve(srcs.size()); for (const auto &s : srcs) c_api_srcs.push_back(s.data); return c_api_srcs; } primitive_desc() = default; primitive_desc(const memory::desc &dst, const std::vector<float> &scales, const std::vector<memory::desc> &srcs, const engine &aengine, const primitive_attr &aattr = primitive_attr()) { error::wrap_c_api(scales.size() == srcs.size() ? mkldnn_success : mkldnn_invalid_arguments, "number of scales not equal to number of srcs"); auto c_api_srcs = cpp_to_c(srcs); mkldnn_primitive_desc_t result; error::wrap_c_api(mkldnn_sum_primitive_desc_create( &result, &dst.data, (int)c_api_srcs.size(), &scales[0], &c_api_srcs[0], aattr.get(), aengine.get()), "could not create a sum primitive descriptor"); reset(result); } primitive_desc(const std::vector<float> &scales, const std::vector<memory::desc> &srcs, const engine &aengine, const primitive_attr &aattr = primitive_attr()) { error::wrap_c_api(scales.size() == srcs.size() ? mkldnn_success : mkldnn_invalid_arguments, "number of scales not equal to number of srcs"); auto c_api_srcs = cpp_to_c(srcs); mkldnn_primitive_desc_t result; error::wrap_c_api(mkldnn_sum_primitive_desc_create(&result, nullptr, (int)c_api_srcs.size(), &scales[0], &c_api_srcs[0], aattr.get(), aengine.get()), "could not create a sum primitive descriptor"); reset(result); } /// Queries destination memory descriptor. memory::desc dst_desc() const { const mkldnn_memory_desc_t *cdesc = mkldnn_primitive_desc_query_md( get(), mkldnn::convert_to_c(query::dst_md), 0); return memory::desc(*cdesc); } /// Queries scratchpad memory descriptor. /// /// @sa @ref dev_guide_attributes_scratchpad /// Returns a zero_md if no scratchpad is required. memory::desc scratchpad_desc() const { const mkldnn_memory_desc_t *cdesc = mkldnn_primitive_desc_query_md( get(), mkldnn::convert_to_c(query::scratchpad_md), 0); return memory::desc(*cdesc); } engine get_engine() { return engine::query(*this); } }; sum() = default; sum(const primitive_desc &pd): primitive(pd.get()) {} }; /// @} /// @} /// @addtogroup cpp_api_primitives Primitives /// @{ /// @addtogroup cpp_api_primitive_descriptors Primitive descriptors /// @{ /// A base class for all primitive descriptors. struct primitive_desc : public handle<mkldnn_primitive_desc_t> { primitive_desc() = default; /// Creates a primitive descriptor from given @p op_desc, @p attr, @p /// engine, and optionally a hint primitive descriptor from forward /// propagation. primitive_desc(const_mkldnn_op_desc_t desc, const primitive_attr *attr, const engine &e, const_mkldnn_primitive_desc_t hint_fwd_pd) { mkldnn_primitive_desc_iterator_t iterator = nullptr; mkldnn_status_t status = mkldnn_primitive_desc_iterator_create( &iterator, desc, attr ? attr->get() : nullptr, e.get(), hint_fwd_pd); error::wrap_c_api(status, "could not create a primitive descriptor iterator"); pd_iterator.reset(iterator); fetch_impl(); } engine get_engine() { return engine::query(*this); } primitive_attr get_primitive_attr() const { const_mkldnn_primitive_attr_t const_cattr; error::wrap_c_api(mkldnn_primitive_desc_get_attr(get(), &const_cattr), "could not get attributes"); mkldnn_primitive_attr_t cattr; error::wrap_c_api(mkldnn_primitive_attr_clone(&cattr, const_cattr), "could not clone attributes"); primitive_attr attr; attr.reset(cattr); return attr; } /// Returns implementation name const char *impl_info_str() const { const char *res; error::wrap_c_api(mkldnn_primitive_desc_query(get(), mkldnn_query_impl_info_str, 0, &res), "could not query implementation info string"); return res; } /// Queries the memory::dim value (same as int64_t) memory::dim query_s64(query q) const { memory::dim res; mkldnn_status_t status = mkldnn_primitive_desc_query(get(), mkldnn::convert_to_c(q), 0, &res); return status == mkldnn_success ? res : 0; } /// Advances the next implementation for the given op descriptor. /// /// Returns: /// - @c true on success /// - @c false if the last implementation reached, and /// the primitive descriptor itself is kept unchanged bool next_impl() { mkldnn_status_t status = mkldnn_primitive_desc_iterator_next( pd_iterator.get()); if (status == mkldnn_iterator_ends) return false; error::wrap_c_api(status, "primitive descriptor iterator next failed"); fetch_impl(); return true; } /// Queries and returns requested memory descriptor. memory::desc query_md(query what, int idx = 0) const { std::vector<query> valid_q{ query::src_md, query::diff_src_md, query::weights_md, query::diff_weights_md, query::dst_md, query::diff_dst_md, query::workspace_md, query::scratchpad_md }; if (!std::any_of(valid_q.cbegin(), valid_q.cend(), [=](query q) { return what == q; })) throw error(mkldnn_invalid_arguments, "invalid memory query"); const mkldnn_memory_desc_t *cdesc = mkldnn_primitive_desc_query_md( get(), mkldnn::convert_to_c(what), idx); return memory::desc(*cdesc); } /// Queries scratchpad memory descriptor. /// /// @sa @ref dev_guide_attributes_scratchpad /// Returns a zero_md if no scratchpad is required. memory::desc scratchpad_desc() const { return query_md(query::scratchpad_md, 0); } private: handle<mkldnn_primitive_desc_iterator_t> pd_iterator; void fetch_impl() { mkldnn_primitive_desc_t pd = mkldnn_primitive_desc_iterator_fetch( pd_iterator.get()); error::wrap_c_api(pd != nullptr ? mkldnn_success : mkldnn_runtime_error, "could not fetch a primitive descriptor from the iterator"); reset(pd); } }; /// @} /// @addtogroup cpp_api_convolution Convolution /// Computes a forward propagation, backward propagation, or weight update /// for convolution operation with bias on a batch of multi-dimensional tensors. /// /// @sa @ref dev_guide_convolution in developer guide /// @sa @ref c_api_convolution in @ref c_api /// @{ /// Convolution forward propagation. /// /// Implements descriptor, primitive descriptor, and primitive /// for the convolution forward propagation. struct convolution_forward: public primitive { /// Descriptor for convolution forward propagation. struct desc { mkldnn_convolution_desc_t data; /// Initializes a descriptor for convolution forward propagation without /// bias using @p aprop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), /// @p aalgorithm, memory descriptors, @p strides, @p padding_l, and /// @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &bias_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_convolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, &bias_desc.data, &dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a convolution forward descriptor"); } /// Initializes a descriptor for convolution forward propagation with /// bias using @p prop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), @p /// aalgorithm, memory descriptors, @p strides, @p padding_l, and @p /// padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_convolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, nullptr, &dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a convolution forward descriptor"); } /// Initializes a descriptor for dilated convolution forward propagation /// without bias using @p prop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), /// @p aalgorithm, memory descriptors, @p strides, @p dilates, /// @p padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &bias_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api( mkldnn_dilated_convolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, &bias_desc.data, &dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated convolution forward descriptor"); } /// Initializes a descriptor for dilated convolution forward propagation /// with bias using @p prop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), /// @p aalgorithm, memory descriptors, @p strides, @p dilates, /// @p padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api( mkldnn_dilated_convolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, nullptr, &dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated convolution forward descriptor"); } }; /// Primitive descriptor for convolution forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for convolution forward /// propagation. primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} /// Initializes a primitive descriptor for convolution forward /// propagation with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries weights memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 1); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } }; convolution_forward() = default; /// Creates a convolution forward propagation primitive from the /// corresponding primitive descriptor. convolution_forward(const primitive_desc &pd): primitive(pd) {} }; /// Convolution backward propagation. /// /// Implements descriptor, primitive descriptor, and primitive for the /// convolution backward propagation. struct convolution_backward_data : public primitive { /// Descriptor for convolution backward propagation. struct desc { mkldnn_convolution_desc_t data; /// Initializes a descriptor for convolution backward propagation /// using @p aalgorithm, memory descriptors, @p strides, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &diff_src_desc, const memory::desc &weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_convolution_backward_data_desc_init( &data, convert_to_c(aalgorithm), &diff_src_desc.data, &weights_desc.data, &diff_dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a convolution backward data descriptor"); } /// Initializes a descriptor for dilated convolution backward /// propagation using @p aalgorithm, memory descriptors, @p strides, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &diff_src_desc, const memory::desc &weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api( mkldnn_dilated_convolution_backward_data_desc_init( &data, convert_to_c(aalgorithm), &diff_src_desc.data, &weights_desc.data, &diff_dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a convolution backward data descriptor"); } }; /// Primitive descriptor for convolution backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes primitive descriptor for convolution backward /// propagation. primitive_desc(const desc &desc, const engine &e, const convolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} /// Initializes primitive descriptor for convolution backward /// propagation with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const convolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries diff source gradient memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries weights memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; convolution_backward_data() = default; /// Creates a convolution backward propagation primitive from the /// corresponding primitive descriptor. convolution_backward_data(const primitive_desc &pd): primitive(pd) {} }; /// Convolution weight update. /// /// Implements descriptor, primitive descriptor, and primitive for the /// convolution weight update. struct convolution_backward_weights : public primitive { /// Descriptor for convolution weight update. struct desc { mkldnn_convolution_desc_t data; /// Initializes a descriptor for convolution weight update with bias /// using @p aalgorithm, memory descriptors, @p strides, @p padding_l, /// and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_convolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, &diff_bias_desc.data, &diff_dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a convolution backward weights descriptor"); } /// Initializes a descriptor for convolution weight update without /// bias using @p aalgorithm, memory descriptors, @p strides, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_convolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, nullptr, &diff_dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a convolution backward weights descriptor"); } /// Initializes a descriptor for dilated convolution weight update /// with bias using @p aalgorithm, memory descriptors, @p strides, /// @p dilates @p padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_convolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, &diff_bias_desc.data, &diff_dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a convolution backward weights descriptor"); } /// Initializes a descriptor for dilated convolution weight update /// without bias using @p aalgorithm, memory descriptors, @p strides, /// @p dilates @p padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_convolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, nullptr, &diff_dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a convolution backward weights descriptor"); } }; /// Primitive descriptor for convolution weight update. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for convolution weight update. primitive_desc(const desc &desc, const engine &e, const convolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} /// Initializes a primitive descriptor for convolution weight update /// with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const convolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries diff weights memory descriptor. memory::desc diff_weights_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; convolution_backward_weights() = default; /// Creates convolution weight update primitive from corresponding /// primitive descriptor. convolution_backward_weights(const primitive_desc &pd): primitive(pd) {} }; /// @} // /// @addtogroup cpp_api_deconvolution Deconvolution /// A primitive to compute deconvolution using different algorithms. /// /// @sa @ref c_api_deconvolution in @ref c_api /// @{ /// Deconvolution forward propagation. /// /// Implements descriptor, primitive descriptor, and primitive /// for the deconvolution forward propagation. struct deconvolution_forward: public primitive { /// Descriptor for convolution forward propagation. struct desc { mkldnn_deconvolution_desc_t data; /// Initializes a descriptor for deconvolution forward propagation /// with bias using @p prop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), @p /// aalgorithm, memory descriptors, @p strides, @p padding_l, and @p /// padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &bias_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_deconvolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, &bias_desc.data, &dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a deconvolution forward descriptor"); } /// Initializes a descriptor for deconvolution forward propagation /// without bias using @p prop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), @p /// aalgorithm, memory descriptors, @p strides, @p padding_l, and @p /// padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_deconvolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, nullptr, &dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a deconvolution forward descriptor"); } /// Initializes a descriptor for dilated deconvolution forward /// propagation with bias using @p aprop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), @p /// aalgorithm memory descriptors, @p strides, @p dilates, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &bias_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_deconvolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, &bias_desc.data, &dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated deconvolution forward descriptor"); } /// Initializes a descriptor for dilated deconvolution forward /// propagation without bias using @p aprop_kind (possible values are /// #mkldnn::forward_training and #mkldnn::forward_inference), @p /// aalgorithm, memory descriptors, @p strides, @p dilates, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_deconvolution_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &weights_desc.data, nullptr, &dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated deconvolution forward descriptor"); } }; /// Primitive descriptor for deconvolution forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for deconvolution forward /// propagation. primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} /// Initializes primitive descriptor for deconvolution forward /// propagation with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries weights memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 1); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } }; deconvolution_forward() = default; /// Creates a deconvolution forward propagation primitive from the /// corresponding primitive descriptor. deconvolution_forward(const primitive_desc &pd): primitive(pd) {} }; /// Deconvolution backward propagation. /// /// Implements descriptor, primitive descriptor, and primitive for the /// deconvolution backward propagation. struct deconvolution_backward_data : public primitive { /// Descriptor for deconvolution backward propagation. struct desc { mkldnn_deconvolution_desc_t data; /// Initializes a descriptor for deconvolution backward propagation /// using @p aalgorithm, memory descriptors, @p strides, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &diff_src_desc, const memory::desc &weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_deconvolution_backward_data_desc_init( &data, convert_to_c(aalgorithm), &diff_src_desc.data, &weights_desc.data, &diff_dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a deconvolution backward data descriptor"); } /// Initializes descriptor for dilated deconvolution backward propagation /// using @p aalgorithm, memory descriptors, @p strides, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &diff_src_desc, const memory::desc &weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_deconvolution_backward_data_desc_init( &data, convert_to_c(aalgorithm), &diff_src_desc.data, &weights_desc.data, &diff_dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated deconvolution backward data descriptor"); } }; /// Primitive descriptor for deconvolution backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for deconvolution backward /// propagation. primitive_desc(const desc &desc, const engine &e, const deconvolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} /// Initializes a primitive descriptor for deconvolution backward /// propagation with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const deconvolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries diff source gradient memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries weights memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; deconvolution_backward_data() = default; /// Creates a deconvolution backward propagation primitive from the /// corresponding primitive descriptor. deconvolution_backward_data(const primitive_desc &pd): primitive(pd) {} }; /// Deconvolution weight update. /// /// Implements descriptor, primitive descriptor, and primitive /// for the deconvolution weight update. struct deconvolution_backward_weights : public primitive { /// Descriptor for deconvolution weight update. struct desc { mkldnn_deconvolution_desc_t data; /// Initializes a descriptor for deconvolution weight update with bias /// using @p aalgorithm, memory descriptors, @p strides, @p padding_l, /// and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_deconvolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, &diff_bias_desc.data, &diff_dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a deconvolution backward weights descriptor"); } /// Initializes a descriptor for deconvolution weight update without /// bias using @p aalgorithm, memory descriptors, @p strides, @p /// padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_deconvolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, nullptr, &diff_dst_desc.data, &strides[0], &padding_l[0], &padding_r[0]), "could not create a deconvolution backward weights descriptor"); } /// Initializes a descriptor for dilated deconvolution weight update /// with bias using @p aalgorithm, memory descriptors, @p strides, @p /// dilates @p padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_deconvolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, &diff_bias_desc.data, &diff_dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated deconvolution backward weights descriptor"); } /// Initializes a descriptor for dilated deconvolution weight update /// without bias using @p aalgorithm, memory descriptors, @p strides, /// @p dilates @p padding_l, and @p padding_r. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. desc(algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &dilates, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(dilates); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_dilated_deconvolution_backward_weights_desc_init( &data, convert_to_c(aalgorithm), &src_desc.data, &diff_weights_desc.data, nullptr, &diff_dst_desc.data, &strides[0], &dilates[0], &padding_l[0], &padding_r[0]), "could not create a dilated deconvolution backward weights descriptor"); } }; /// Primitive descriptor for deconvolution weight update. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for deconvolution weight update. primitive_desc(const desc &desc, const engine &e, const deconvolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} /// Initializes a primitive descriptor for deconvolution weight update /// with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const deconvolution_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries diff weights memory descriptor. memory::desc diff_weights_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; deconvolution_backward_weights() = default; /// Creates a deconvolution weight update primitive from the corresponding /// primitive descriptor. deconvolution_backward_weights(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_lrn LRN /// A primitive to perform local response normalization (LRN) across or within /// channels. /// /// @sa @ref dev_guide_lrn in developer guide /// @sa @ref c_api_lrn in @ref c_api /// @{ /// Local response normalization for forward propagation. Implements /// descriptor, primitive descriptor, and primitive. struct lrn_forward : public primitive { /// Descriptor for local response normalization forward propagation. struct desc { mkldnn_lrn_desc_t data; /// Initializes a descriptor for forward propagation using @p prop_kind /// (possible values are #mkldnn::forward_training and /// #mkldnn::forward_inference), @p aalgorithm, memory descriptor @p /// data_desc, and regularization parameters @p local_size, @p alpha, @p /// beta, and @p k. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, memory::dim local_size, float alpha, float beta, float k = 1.f) { error::wrap_c_api(mkldnn_lrn_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, local_size, alpha, beta, k), "could not create a lrn forward descriptor"); } }; /// Primitive descriptor for local response normalization forward /// propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; lrn_forward() = default; lrn_forward(const primitive_desc &pd): primitive(pd) {} }; /// Local response normalization for backward propagation. Implements /// descriptor, primitive descriptor, and primitive. struct lrn_backward : public primitive { /// Descriptor for local response normalization backward propagation. struct desc { mkldnn_lrn_desc_t data; /// Initializes a descriptor for backward propagation using @p aalgorithm, /// memory descriptors @p data_desc and @p diff_data_desc, and /// regularization parameters @p local_size, @p alpha, @p beta, and /// @p k. desc(algorithm aalgorithm, const memory::desc &data_desc, const memory::desc &diff_data_desc, memory::dim local_size, float alpha, float beta, float k = 1.f) { error::wrap_c_api(mkldnn_lrn_backward_desc_init(&data, convert_to_c(aalgorithm), &diff_data_desc.data, &data_desc.data, local_size, alpha, beta, k), "could not create a lrn backward descriptor"); } }; /// Primitive descriptor for local response normalization backward /// propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const lrn_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const lrn_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries diff source memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; lrn_backward() = default; lrn_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_pooling Pooling /// A primitive to perform max or average pooling. /// /// @sa @ref dev_guide_pooling in developer guide /// @sa @ref c_api_pooling in @ref c_api /// @{ /// Pooling for forward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct pooling_forward : public primitive { /// Descriptor for pooling forward propagation. struct desc { mkldnn_pooling_desc_t data; /// Initializes a pooling descriptor for forward propagation using @p /// aprop_kind (possible values are #mkldnn::forward_training and /// #mkldnn::forward_inference), @p aalgorithm, memory descriptors, and /// pooling parameters in the spatial domain: @p strides, @p kernel /// sizes, @p padding_l, and @p padding_r. desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, const memory::desc &dst_desc, const memory::dims &strides, const memory::dims &kernel, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(kernel); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_pooling_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), convert_to_c(aalgorithm), &src_desc.data, &dst_desc.data, &strides[0], &kernel[0], &padding_l[0], &padding_r[0]), "could not init a forward pooling descriptor"); } }; /// Primitive descriptor for pooling forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; pooling_forward() = default; pooling_forward(const primitive_desc &pd): primitive(pd) {} }; struct pooling_backward : public primitive { /// Descriptor for pooling backward propagation. struct desc { mkldnn_pooling_desc_t data; /// Initializes a pooling descriptor for backward propagation using @p /// aalgorithm, memory descriptors, and pooling parameters in the spatial /// domain: @p strides, @p kernel sizes, @p padding_l, and @p padding_r. desc(algorithm aalgorithm, const memory::desc &diff_src_desc, const memory::desc &diff_dst_desc, const memory::dims &strides, const memory::dims &kernel, const memory::dims &padding_l, const memory::dims &padding_r) { memory::validate_dims(strides); memory::validate_dims(kernel); memory::validate_dims(padding_l); memory::validate_dims(padding_r); error::wrap_c_api(mkldnn_pooling_backward_desc_init(&data, convert_to_c(aalgorithm), &diff_src_desc.data, &diff_dst_desc.data, &strides[0], &kernel[0], &padding_l[0], &padding_r[0]), "could not init a backward pooling descriptor"); } }; /// Primitive descriptor for pooling backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const pooling_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const pooling_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries diff source memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; pooling_backward() = default; pooling_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_eltwise Eltwise /// A primitive to compute element-wise operations such as rectified linear /// unit (ReLU). /// /// Both forward and backward passes support in-place operation; that is, src /// and dst point to the same memory for forward pass, and diff_dst and /// diff_src point to the same memory for backward pass. /// /// @warning Because the original src is required for backward pass, in-place /// forward pass in general cannot be applied during training. However, for /// some kinds of element-wise operations (namely ReLU with alpha parameter /// equals 0), dst and src can be interchangeable for the backward pass, which /// enables performance of in-place forward even for training. /// /// @sa @ref dev_guide_eltwise in developer guide /// @sa @ref c_api_eltwise in @ref c_api /// @{ /// Element-wise operations for forward propagation. Implements descriptor, /// primitive descriptor, and primitive. struct eltwise_forward : public primitive { /// Initializes an eltwise descriptor for forward propagation using @p /// prop_kind (possible values are #mkldnn::forward_training and /// #mkldnn::forward_inference), @p aalgorithm algorithm, memory /// descriptor @p data_desc, @p alpha, and @p beta parameters. struct desc { mkldnn_eltwise_desc_t data; desc(prop_kind aprop_kind, algorithm aalgorithm, const memory::desc &src_desc, float alpha = 0, float beta = 0) { error::wrap_c_api(mkldnn_eltwise_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(aalgorithm), &src_desc.data, alpha, beta), "could not create a eltwise forward descriptor"); } }; /// Primitive descriptor for eltwise forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } }; eltwise_forward() = default; eltwise_forward(const primitive_desc &pd): primitive(pd) {} }; /// Element-wise operations for backward propagation. Implements descriptor, /// primitive descriptor, and primitive. struct eltwise_backward : public primitive { /// Initializes an eltwise descriptor for backward propagation using @p /// aalgorithm algorithm memory descriptors @p diff_data_desc and @p /// data_desc, and the @p alpha and @p beta parameters. struct desc { mkldnn_eltwise_desc_t data; desc(algorithm aalgorithm, const memory::desc &diff_data_desc, const memory::desc &data_desc, float alpha = 0, float beta = 0) { error::wrap_c_api(mkldnn_eltwise_backward_desc_init(&data, mkldnn::convert_to_c(aalgorithm), &diff_data_desc.data, &data_desc.data, alpha, beta), "could not create a eltwise backward descriptor"); } }; /// Primitive descriptor for eltwise backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const eltwise_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const eltwise_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries diff source memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; eltwise_backward() = default; eltwise_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_softmax Softmax /// A primitive to perform softmax. /// /// @sa @ref dev_guide_softmax in developer guide /// @sa @ref c_api_softmax in @ref c_api /// @{ /// Softmax for forward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct softmax_forward : public primitive { /// Descriptor for softmax forward propagation. struct desc { mkldnn_softmax_desc_t data; /// Initializes a softmax descriptor for forward propagation using @p /// prop_kind (possible values are #mkldnn::forward_training and /// #mkldnn::forward_inference) and memory descriptor @p data_desc. desc(prop_kind aprop_kind, const memory::desc &data_desc, int softmax_axis) { error::wrap_c_api(mkldnn_softmax_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &data_desc.data, softmax_axis), "could not create a softmax forward descriptor"); } }; /// Primitive descriptor for softmax forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } }; softmax_forward() = default; softmax_forward(const primitive_desc &pd): primitive(pd) {} }; /// Softmax for backward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct softmax_backward : public primitive { /// Descriptor for softmax backward propagation. struct desc { mkldnn_softmax_desc_t data; /// Initializes a softmax descriptor for backward propagation using /// memory descriptors @p diff_desc and @p data_desc. desc(const memory::desc &diff_desc, const memory::desc &data_desc, int softmax_axis) { error::wrap_c_api(mkldnn_softmax_backward_desc_init(&data, &diff_desc.data, &data_desc.data, softmax_axis), "could not init a backward softmax descriptor"); } }; /// Primitive descriptor for softmax backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const softmax_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const softmax_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } /// Queries diff source memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; softmax_backward() = default; softmax_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_batch_normalization Batch normalization /// A primitive to perform batch normalization. /// /// Both forward and backward passes support in-place operation; that is, src /// and dst point to the same memory for forward pass, and diff_dst and diff_src /// point to the same memory for backward pass. /// /// Batch normalization supports different flavors controlled by /// mkldnn_batch_normalization_desc_t. For example, batch normalization can /// compute the mean and variance on its own or take them as inputs. It can /// either perform scaling and shifting using gamma and beta parameters or not. /// Optionally, it can also perform a fused ReLU, which in case of training /// would also require a workspace. /// /// @sa @ref dev_guide_batch_normalization in developer guide /// @sa @ref c_api_batch_normalization in @ref c_api /// @{ /// Batch normalization for forward propagation. Implements descriptor, /// primitive descriptor, and primitive. struct batch_normalization_forward : public primitive { /// Descriptor for batch normalization forward propagation. struct desc { mkldnn_batch_normalization_desc_t data; /// Initializes a batch normalization descriptor for forward propagation /// using @p prop_kind (possible values are #mkldnn::forward_training and /// #mkldnn::forward_inference), memory descriptor @p data_desc, /// normalization parameter @p epsilon, and @p flags set using bit flags /// of type mkldnn_batch_normalization_desc_t. /// /// @note In-place operation is supported; that is, dst points to the /// same memory as src. desc(prop_kind aprop_kind, const memory::desc &src_desc, float epsilon, normalization_flags flags) { error::wrap_c_api( mkldnn_batch_normalization_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &src_desc.data, epsilon, convert_to_c(flags)), "could not create a batch normalization forward " "descriptor"); } }; /// Primitive descriptor for batch normalization forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for batch normalization forward /// propagation. primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} /// Initializes a primitive descriptor for batch normalization forward /// propagation with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries weights (scale and shift) memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } /// Queries mean memory descriptor. memory::desc mean_desc() const { return stat_desc(mean); } /// Queries variance memory descriptor. memory::desc variance_desc() const { return stat_desc(var); } private: enum { mean = 1, var = 2, }; memory::desc stat_desc(int kind) const { mkldnn_batch_normalization_desc_t *p; error::wrap_c_api(mkldnn_primitive_desc_query( get(), mkldnn::convert_to_c(query::batch_normalization_d), 0, &p), "could not get a batch-normalization descriptor"); return query_md(p->flags & mkldnn_use_global_stats ? query::src_md : query::dst_md, kind); } }; batch_normalization_forward() = default; batch_normalization_forward(const primitive_desc &pd): primitive(pd) {} }; /// Batch normalization backward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct batch_normalization_backward : public primitive { /// Descriptor for batch normalization backward propagation. struct desc { mkldnn_batch_normalization_desc_t data; /// Initializes a batch normalization descriptor for backward /// propagation with respect to data and scale-shift parameters using /// memory descriptors @p data_desc and @p diff_data_desc, normalization /// parameter @p epsilon, and @p flags set using bit flags of type /// mkldnn_batch_normalization_desc_t. /// /// @note In-place operation is supported; that is, diff_src points to /// the same memory as diff_dst. desc(prop_kind aprop_kind, const memory::desc &diff_data_desc, const memory::desc &data_desc, float epsilon, normalization_flags flags) { error::wrap_c_api( mkldnn_batch_normalization_backward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &diff_data_desc.data, &data_desc.data, epsilon, convert_to_c(flags)), "could not create a batch normalization backward " "descriptor"); } }; /// Primitive descriptor for batch normalization backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; /// Initializes a primitive descriptor for batch normalization backward /// propagation. primitive_desc(const desc &desc, const engine &e, const batch_normalization_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} /// Initializes a primitive descriptor for batch normalization backward /// propagation with attributes defined by @p attr. primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const batch_normalization_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries mean memory descriptor. memory::desc mean_desc() const { return query_md(query::src_md, 1); } /// Queries variance memory descriptor. memory::desc variance_desc() const { return query_md(query::src_md, 2); } /// Queries weights (scale and shift) memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } /// Queries diff source memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff weights (scale and shift) memory descriptor. memory::desc diff_weights_desc() const { return query_md(query::diff_weights_md, 0); } }; batch_normalization_backward() = default; batch_normalization_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_inner_product Inner Product /// A primitive to compute an inner product. /// /// @sa @ref dev_guide_inner_product in developer guide /// @sa @ref c_api_inner_product in @ref c_api /// @{ /// Inner product for forward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct inner_product_forward: public primitive { /// Initializes an inner product descriptor for forward propagation using /// @p prop_kind (possible values are #mkldnn::prop_kind::forward_training /// and #mkldnn::prop_kind::forward_inference) and memory descriptors. In /// order to create an inner product without bias, @p bias_desc should /// refer to a descriptor with memory format kind set to /// #mkldnn::memory::format_tag::undef. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. struct desc { mkldnn_inner_product_desc_t data; desc(prop_kind aprop_kind, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &bias_desc, const memory::desc &dst_desc) { error::wrap_c_api( mkldnn_inner_product_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &src_desc.data, &weights_desc.data, &bias_desc.data, &dst_desc.data), "could not create a inner product forward descriptor"); } desc(prop_kind aprop_kind, const memory::desc &src_desc, const memory::desc &weights_desc, const memory::desc &dst_desc) { error::wrap_c_api( mkldnn_inner_product_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &src_desc.data, &weights_desc.data, nullptr, &dst_desc.data), "could not create a inner product forward descriptor"); } }; /// Primitive descriptor for inner product forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries weights memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 1); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } }; inner_product_forward() = default; inner_product_forward(const primitive_desc &pd): primitive(pd) {} }; /// Inner product for backward propagation with respect to data. Implements /// descriptor, primitive descriptor, and primitive. struct inner_product_backward_data: public primitive { /// Initializes an inner product descriptor for backward propagation with /// respect to data using memory descriptors. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. struct desc { mkldnn_inner_product_desc_t data; desc(const memory::desc &diff_src_desc, const memory::desc &weights_desc, const memory::desc &diff_dst_desc) { error::wrap_c_api( mkldnn_inner_product_backward_data_desc_init(&data, &diff_src_desc.data, &weights_desc.data, &diff_dst_desc.data), "could not create a inner product backward data descriptor"); } }; /// Primitive descriptor for inner product backward propagation with /// respect to data. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const inner_product_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const inner_product_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries diff source gradient memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries weights memory descriptor. memory::desc weights_desc() const { return query_md(query::weights_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; inner_product_backward_data() = default; inner_product_backward_data(const primitive_desc &pd): primitive(pd) {} }; /// Inner product for backward propagation with respect to weights. Implements /// descriptor, primitive descriptor, and primitive. struct inner_product_backward_weights: public primitive { /// Initializes an inner product descriptor for backward propagation with /// respect to weights using memory descriptors. /// /// @note Memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. struct desc { mkldnn_inner_product_desc_t data; desc(const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_desc) { error::wrap_c_api( mkldnn_inner_product_backward_weights_desc_init( &data, &src_desc.data, &diff_weights_desc.data, &diff_bias_desc.data, &diff_dst_desc.data), "could not create a inner product backward weights descriptor"); } desc(const memory::desc &src_desc, const memory::desc &diff_weights_desc, const memory::desc &diff_dst_desc) { error::wrap_c_api( mkldnn_inner_product_backward_weights_desc_init( &data, &src_desc.data, &diff_weights_desc.data, nullptr, &diff_dst_desc.data), "could not create a inner product backward weights descriptor"); } }; /// Primitive descriptor for inner product backward propagation with /// respect to weights. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const inner_product_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const inner_product_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries diff weights memory descriptor. memory::desc diff_weights_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; inner_product_backward_weights() = default; inner_product_backward_weights(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_rnn RNN /// A primitive to compute common recurrent layer. /// /// @sa @ref dev_guide_rnn in developer guide /// @sa @ref c_api_rnn in @ref c_api /// @{ /// Vanilla RNN for forward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct vanilla_rnn_forward : public primitive { /// Descriptor for RNN forward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an RNN descriptor for forward propagation using @p /// prop_kind, @p activation, @p direction, and memory descriptors. /// @note If @p prop_kind equals #mkldnn::forward_training, you must /// query a workspace memory descriptor before creating the primitive. /// /// @p alpha, @p beta and @p flags are parameters to the RNN descriptor. /// If @p activation is #eltwise_relu, @p alpha represents the negative /// slope. /// @p beta and @p flags are currently ignored. /// /// @p src_iter_desc, @p bias_desc, and @p dst_iter_desc are allowed /// to point to a zero memory descriptor, which would indicate that /// the RNN primitive should not use them. /// /// @note /// All memory descriptors except @p src_iter_desc can be /// initialized with an #mkldnn::memory::format_tag::any value of @p /// format_kind. desc(prop_kind aprop_kind, algorithm activation, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, rnn_flags flags = rnn_flags::undef, float alpha = 0.0f, float beta = 0.0f) { error::wrap_c_api(mkldnn_vanilla_rnn_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(activation), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, mkldnn::convert_to_c(flags), alpha, beta), "could not create an RNN forward descriptor"); } }; /// Primitive descriptor for RNN forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source iteration memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination iteration memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; vanilla_rnn_forward() = default; vanilla_rnn_forward(const primitive_desc &pd): primitive(pd) {} }; /// Vanilla RNN for backward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct vanilla_rnn_backward : public primitive { /// RNN descriptor for backward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an RNN descriptor for backward propagation using @p /// prop_kind, @p activation, @p direction, and memory descriptors. /// /// @p alpha, @p beta and @p flags are parameters to the RNN descriptor. /// If @p activation is #eltwise_relu, @p alpha represents the negative /// slope. /// @p beta and @p flags are currently ignored. /// /// @note All memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. /// /// @p src_iter_desc (simultaneously with @p diff_src_iter_desc), @p /// bias_desc (simultaneously with @p diff_bias_desc), and @p /// dst_iter_desc (simultaneously with @p diff_src_iter_desc) are /// allowed point to a zero memory descriptor, which would indicate /// that the RNN primitive should not use them and consider them to be /// zero values. desc(prop_kind aprop_kind, algorithm activation, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, const memory::desc &diff_src_layer_desc, const memory::desc &diff_src_iter_desc, const memory::desc &diff_weights_layer_desc, const memory::desc &diff_weights_iter_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_layer_desc, const memory::desc &diff_dst_iter_desc, rnn_flags flags = rnn_flags::undef, float alpha = 0.0f, float beta = 0.0f) { error::wrap_c_api(mkldnn_vanilla_rnn_backward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(activation), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, &diff_src_layer_desc.data, &diff_src_iter_desc.data, &diff_weights_layer_desc.data, &diff_weights_iter_desc.data, &diff_bias_desc.data, &diff_dst_layer_desc.data, &diff_dst_iter_desc.data, mkldnn::convert_to_c(flags), alpha, beta), "could not create an RNN backward descriptor"); } }; /// Primitive descriptor for RNN backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const vanilla_rnn_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const vanilla_rnn_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source iteration memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination iteration memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } /// Queries diff source layer memory descriptor. memory::desc diff_src_layer_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff source iteration memory descriptor. /// /// Returns a zero_md if no diff_src_iter was specified at op_desc /// creation time. memory::desc diff_src_iter_desc() const { return query_md(query::diff_src_md, 1); } /// Queries diff weights layer memory descriptor. memory::desc diff_weights_layer_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff weights iteration memory descriptor. memory::desc diff_weights_iter_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 2); } /// Queries diff destination layer memory descriptor. memory::desc diff_dst_layer_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries diff destination iteration memory descriptor. /// /// Returns a zero_md if no diff_dst_iter was specified at op_desc /// creation time. memory::desc diff_dst_iter_desc() const { return query_md(query::diff_dst_md, 1); } }; vanilla_rnn_backward() = default; vanilla_rnn_backward(const primitive_desc &pd): primitive(pd) {} }; /// LSTM for forward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct lstm_forward : public primitive { /// Descriptor for LSTM forward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an LSTM descriptor for forward propagation using @p /// prop_kind, @p direction, and memory descriptors. /// @note If @p prop_kind equals #mkldnn::forward_training, you must /// query a workspace memory descriptor before creating the primitive. /// /// @p flags is a parameter to the LSTM descriptor and is currently /// ignored. /// /// @p src_iter_desc, @p src_iter_c_desc, @p bias_desc, @p /// dst_iter_desc and @p dst_iter_c_desc are allowed to point /// to a zero memory descriptor, which would indicate that the /// LSTM primitive should not use them. /// /// @note /// All memory descriptors except @p src_iter_desc can be /// initialized with an #mkldnn::memory::format_tag::any value of @p /// format_kind. desc(prop_kind aprop_kind, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &src_iter_c_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, const memory::desc &dst_iter_c_desc, rnn_flags flags = rnn_flags::undef) { error::wrap_c_api(mkldnn_lstm_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &src_iter_c_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, &dst_iter_c_desc.data, mkldnn::convert_to_c(flags)), "could not create an LSTM forward descriptor"); } }; /// Primitive descriptor for LSTM forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source recurrent hidden state memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries source recurrent cell state memory descriptor. memory::desc src_iter_c_desc() const { return query_md(query::src_md, 2); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination recurrent hidden state memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries destination recurrent cell state memory descriptor. memory::desc dst_iter_c_desc() const { return query_md(query::dst_md, 2); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; lstm_forward() = default; lstm_forward(const primitive_desc &pd): primitive(pd) {} }; /// LSTM for backward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct lstm_backward : public primitive { /// LSTM descriptor for backward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an LSTM descriptor for backward propagation using @p /// prop_kind, @p direction, and memory descriptors. /// /// @p flags is a parameter to the LSTM descriptor and is currently /// ignored. /// /// @note All memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. /// /// @p src_iter_desc (simultaneously with @p /// diff_src_iter_desc), @p src_iter_c_desc (simultaneously /// with @p diff_src_iter_c_desc), @p bias_desc /// (simultaneously with @p diff_bias_desc), @p dst_iter_desc /// (simultaneously with @p diff_src_iter_desc) and @p dst_iter_c_desc /// (simultaneously with @p diff_src_iter_c_desc) are allowed /// point to a zero memory descriptor, which would indicate /// that the LSTM primitive should not use them and consider /// them to be zero values. desc(prop_kind aprop_kind, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &src_iter_c_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, const memory::desc &dst_iter_c_desc, const memory::desc &diff_src_layer_desc, const memory::desc &diff_src_iter_desc, const memory::desc &diff_src_iter_c_desc, const memory::desc &diff_weights_layer_desc, const memory::desc &diff_weights_iter_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_layer_desc, const memory::desc &diff_dst_iter_desc, const memory::desc &diff_dst_iter_c_desc, rnn_flags flags = rnn_flags::undef) { error::wrap_c_api(mkldnn_lstm_backward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &src_iter_c_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, &dst_iter_c_desc.data, &diff_src_layer_desc.data, &diff_src_iter_desc.data, &diff_src_iter_c_desc.data, &diff_weights_layer_desc.data, &diff_weights_iter_desc.data, &diff_bias_desc.data, &diff_dst_layer_desc.data, &diff_dst_iter_desc.data, &diff_dst_iter_c_desc.data, mkldnn::convert_to_c(flags)), "could not create an LSTM backward descriptor"); } }; /// Primitive descriptor for LSTM backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const lstm_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const lstm_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source recurrent hidden state memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries source recurrent cell state memory descriptor. memory::desc src_iter_c_desc() const { return query_md(query::src_md, 2); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination recurrent hidden state memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries destination recurrent cell state memory descriptor. memory::desc dst_iter_c_desc() const { return query_md(query::dst_md, 2); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } /// Queries diff source layer memory descriptor. memory::desc diff_src_layer_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff source recurrent hidden state memory descriptor. /// /// Returns a zero_md if no diff_src_iter was specified at op_desc /// creation time. memory::desc diff_src_iter_desc() const { return query_md(query::diff_src_md, 1); } /// Queries diff source recurrent cell state memory descriptor. memory::desc diff_src_iter_c_desc() const { return query_md(query::diff_src_md, 2); } /// Queries diff weights layer memory descriptor. memory::desc diff_weights_layer_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff weights iteration memory descriptor. memory::desc diff_weights_iter_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 2); } /// Queries diff destination layer memory descriptor. memory::desc diff_dst_layer_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries diff destination recurrent hidden state memory descriptor. /// /// Returns a zero_md if no diff_dst_iter was specified at op_desc /// creation time. memory::desc diff_dst_iter_desc() const { return query_md(query::diff_dst_md, 1); } /// Queries diff destination recurrent cell state memory descriptor. memory::desc diff_dst_iter_c_desc() const { return query_md(query::diff_dst_md, 2); } }; lstm_backward() = default; // With last iteration (with and without input src_iter) lstm_backward(const primitive_desc &pd): primitive(pd) {} }; /// GRU for forward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct gru_forward : public primitive { /// Descriptor for GRU forward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes a GRU descriptor for forward propagation using @p /// prop_kind, @p direction, and memory descriptors. /// @note If @p prop_kind equals #mkldnn::forward_training, you must /// query a workspace memory descriptor before creating the primitive. /// /// @p flags is a parameter to the GRU descriptor and is currently /// ignored. /// /// @p src_iter_desc, @p bias_desc, and @p dst_iter_desc are allowed /// to point to a zero memory descriptor, which would indicate that /// the GRU primitive should not use them and will default to zero /// values. /// /// @note /// All memory descriptors except @p src_iter_desc can be /// initialized with an #mkldnn::memory::format_tag::any value of @p /// format_kind. desc(prop_kind aprop_kind, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, rnn_flags flags = rnn_flags::undef) { error::wrap_c_api(mkldnn_gru_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, mkldnn::convert_to_c(flags)), "could not create a GRU forward descriptor"); } }; /// Primitive descriptor for GRU forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source iteration memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination iteration memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; gru_forward() = default; gru_forward(const primitive_desc &pd): primitive(pd) {} }; /// GRU for backward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct gru_backward : public primitive { /// GRU descriptor for backward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an GRU descriptor for backward propagation using @p /// prop_kind, @p direction, and memory descriptors. /// /// @p flags is a parameter to the GRU descriptor and is currently /// ignored. /// /// @note All memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. /// /// @p src_iter_desc (simultaneously with @p diff_src_iter_desc), @p /// bias_desc (simultaneously with @p diff_bias_desc), and @p /// dst_iter_desc (simultaneously with @p diff_src_iter_desc) are /// allowed point to a zero memory descriptor, which would indicate /// that the GRU primitive should not use them and consider them to be /// zero values. desc(prop_kind aprop_kind, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, const memory::desc &diff_src_layer_desc, const memory::desc &diff_src_iter_desc, const memory::desc &diff_weights_layer_desc, const memory::desc &diff_weights_iter_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_layer_desc, const memory::desc &diff_dst_iter_desc, rnn_flags flags = rnn_flags::undef) { error::wrap_c_api(mkldnn_gru_backward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, &diff_src_layer_desc.data, &diff_src_iter_desc.data, &diff_weights_layer_desc.data, &diff_weights_iter_desc.data, &diff_bias_desc.data, &diff_dst_layer_desc.data, &diff_dst_iter_desc.data, mkldnn::convert_to_c(flags)), "could not create an GRU backward descriptor"); } }; /// Primitive descriptor for GRU backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const gru_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const gru_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source iter memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination iteration memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } /// Queries diff source layer memory descriptor. memory::desc diff_src_layer_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff source iteration memory descriptor. /// /// Returns a zero_md if no diff_src_iter was specified at op_desc /// creation time. memory::desc diff_src_iter_desc() const { return query_md(query::diff_src_md, 1); } /// Queries diff weights layer memory descriptor. memory::desc diff_weights_layer_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff weights iteration memory descriptor. memory::desc diff_weights_iter_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 2); } /// Queries diff destination layer memory descriptor. memory::desc diff_dst_layer_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries diff destination iteration memory descriptor. /// /// Returns a zero_md if no diff_dst_iter was specified at op_desc /// creation time. memory::desc diff_dst_iter_desc() const { return query_md(query::diff_dst_md, 1); } }; gru_backward() = default; // With last iteration (with and without input src_iter) gru_backward(const primitive_desc &pd): primitive(pd) {} }; /// LBR_GRU for forward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct lbr_gru_forward : public primitive { /// Descriptor for LBR GRU forward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an LBR GRU descriptor for forward propagation using @p /// prop_kind, @p direction, and memory descriptors. /// @note If @p prop_kind equals #mkldnn::forward_training, you must /// query a workspace memory descriptor before creating the primitive. /// /// @p flags is a parameter to the LBR GRU descriptor and is currently /// ignored. /// /// @p src_iter_desc, @p bias_desc, and @p dst_iter_desc are allowed /// to point to a zero memory descriptor, which would indicate that /// the LBR GRU primitive should not use them and will default to zero /// values. /// /// @note /// All memory descriptors except @p src_iter_desc can be /// initialized with an #mkldnn::memory::format_tag::any value of @p /// format_kind. desc(prop_kind aprop_kind, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, rnn_flags flags = rnn_flags::undef) { error::wrap_c_api(mkldnn_lbr_gru_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, mkldnn::convert_to_c(flags)), "could not create a Linear-before-reset GRU forward descriptor"); } }; /// Primitive descriptor for LBR_GRU forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e) : mkldnn::primitive_desc(&desc.data, nullptr, e, nullptr) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e) : mkldnn::primitive_desc(&desc.data, &attr, e, nullptr) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source iteration memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination iteration memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } }; lbr_gru_forward() = default; lbr_gru_forward(const primitive_desc &pd): primitive(pd) {} }; /// LBR_GRU for backward propagation. /// /// Implements descriptor, primitive descriptor, and primitive. struct lbr_gru_backward : public primitive { /// LBR_GRU descriptor for backward propagation. struct desc { mkldnn_rnn_desc_t data; /// Initializes an LBR_GRU descriptor for backward propagation using @p /// prop_kind, @p direction, and memory descriptors. /// /// @p flags is a parameter to the LBR GRU descriptor and is currently /// ignored. /// /// @note All memory descriptors are allowed to be initialized with /// #mkldnn::memory::format_tag::any value of @p format_kind. /// /// @p src_iter_desc (simultaneously with @p diff_src_iter_desc), @p /// bias_desc (simultaneously with @p diff_bias_desc), and @p /// dst_iter_desc (simultaneously with @p diff_src_iter_desc) are /// allowed point to a zero memory descriptor, which would indicate /// that the LBR GRU primitive should not use them and consider them to be /// zero values. desc(prop_kind aprop_kind, rnn_direction direction, const memory::desc &src_layer_desc, const memory::desc &src_iter_desc, const memory::desc &weights_layer_desc, const memory::desc &weights_iter_desc, const memory::desc &bias_desc, const memory::desc &dst_layer_desc, const memory::desc &dst_iter_desc, const memory::desc &diff_src_layer_desc, const memory::desc &diff_src_iter_desc, const memory::desc &diff_weights_layer_desc, const memory::desc &diff_weights_iter_desc, const memory::desc &diff_bias_desc, const memory::desc &diff_dst_layer_desc, const memory::desc &diff_dst_iter_desc, rnn_flags flags = rnn_flags::undef) { error::wrap_c_api(mkldnn_lbr_gru_backward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), mkldnn::convert_to_c(direction), &src_layer_desc.data, &src_iter_desc.data, &weights_layer_desc.data, &weights_iter_desc.data, &bias_desc.data, &dst_layer_desc.data, &dst_iter_desc.data, &diff_src_layer_desc.data, &diff_src_iter_desc.data, &diff_weights_layer_desc.data, &diff_weights_iter_desc.data, &diff_bias_desc.data, &diff_dst_layer_desc.data, &diff_dst_iter_desc.data, mkldnn::convert_to_c(flags)), "could not create an LBR_GRU backward descriptor"); } }; /// Primitive descriptor for LBR_GRU backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const lbr_gru_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, nullptr, e, hint_fwd_pd.get()) {} primitive_desc(const desc &desc, const primitive_attr &attr, const engine &e, const lbr_gru_forward::primitive_desc &hint_fwd_pd) : mkldnn::primitive_desc(&desc.data, &attr, e, hint_fwd_pd.get()) {} /// Queries source layer memory descriptor. memory::desc src_layer_desc() const { return query_md(query::src_md, 0); } /// Queries source iteration memory descriptor. /// /// Returns a zero_md if no src_iter was specified at op_desc /// creation time. memory::desc src_iter_desc() const { return query_md(query::src_md, 1); } /// Queries weights layer memory descriptor. memory::desc weights_layer_desc() const { return query_md(query::weights_md, 0); } /// Queries weights iteration memory descriptor. memory::desc weights_iter_desc() const { return query_md(query::weights_md, 1); } /// Queries bias memory descriptor. /// /// Returns a zero_md if no bias was specified at op_desc /// creation time. memory::desc bias_desc() const { return query_md(query::weights_md, 2); } /// Queries destination layer memory descriptor. memory::desc dst_layer_desc() const { return query_md(query::dst_md, 0); } /// Queries destination iteration memory descriptor. /// /// Returns a zero_md if no dst_iter was specified at op_desc /// creation time. memory::desc dst_iter_desc() const { return query_md(query::dst_md, 1); } /// Queries workspace memory descriptor. /// /// Returns a zero_md if no worspace is required. memory::desc workspace_desc() const { return query_md(query::workspace_md, 0); } /// Queries diff source layer memory descriptor. memory::desc diff_src_layer_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff source iteration memory descriptor. /// /// Returns a zero_md if no diff_src_iter was specified at op_desc /// creation time. memory::desc diff_src_iter_desc() const { return query_md(query::diff_src_md, 1); } /// Queries diff weights layer memory descriptor. memory::desc diff_weights_layer_desc() const { return query_md(query::diff_weights_md, 0); } /// Queries diff weights iteration memory descriptor. memory::desc diff_weights_iter_desc() const { return query_md(query::diff_weights_md, 1); } /// Queries diff bias memory descriptor. memory::desc diff_bias_desc() const { return query_md(query::diff_weights_md, 2); } /// Queries diff destination layer memory descriptor. memory::desc diff_dst_layer_desc() const { return query_md(query::diff_dst_md, 0); } /// Queries diff destination iteration memory descriptor. /// /// Returns a zero_md if no diff_dst_iter was specified at op_desc /// creation time. memory::desc diff_dst_iter_desc() const { return query_md(query::diff_dst_md, 1); } }; lbr_gru_backward() = default; lbr_gru_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @addtogroup cpp_api_shuffle Shuffle /// A primitive to shuffle data along the axis. /// /// @sa @ref dev_guide_shuffle in developer guide /// @sa @ref c_api_shuffle in @ref c_api /// @{ /// Shuffle for forward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct shuffle_forward : public primitive { /// Descriptor for shuffle forward propagation. struct desc { mkldnn_shuffle_desc_t data; /// Initializes a shuffle descriptor for forward propagation using @p /// prop_kind, memory descriptor @p data_desc, @p axis, and @p /// group_size. desc(prop_kind aprop_kind, const memory::desc &data_desc, int axis, int group_size) { error::wrap_c_api(mkldnn_shuffle_forward_desc_init(&data, mkldnn::convert_to_c(aprop_kind), &data_desc.data, axis, group_size), "could not create a shuffle forward descriptor"); } }; /// Primitive descriptor for shuffle forward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const primitive_attr &aattr = primitive_attr()) : mkldnn::primitive_desc(&desc.data, &aattr, e, nullptr) {} /// Queries source memory descriptor. memory::desc src_desc() const { return query_md(query::src_md, 0); } /// Queries destination memory descriptor. memory::desc dst_desc() const { return query_md(query::dst_md, 0); } }; shuffle_forward() = default; shuffle_forward(const primitive_desc &pd): primitive(pd) {} }; /// Shuffle for backward propagation. Implements descriptor, primitive /// descriptor, and primitive. struct shuffle_backward : public primitive { // Descriptor for shuffle backward propagation. struct desc { mkldnn_shuffle_desc_t data; /// Initializes a shuffle descriptor for backward propagation using /// memory descriptor @p diff_data_desc, @p axis, and @p group_size. desc(const memory::desc &diff_data_desc, int axis, int group_size) { error::wrap_c_api(mkldnn_shuffle_backward_desc_init(&data, &diff_data_desc.data, axis, group_size), "could not create a shuffle backward descriptor"); } }; // Primitive descriptor for shuffle backward propagation. struct primitive_desc : public mkldnn::primitive_desc { primitive_desc() = default; primitive_desc(const desc &desc, const engine &e, const shuffle_forward::primitive_desc &hint_fwd_pd, const primitive_attr &aattr = primitive_attr()) : mkldnn::primitive_desc( &desc.data, &aattr, e, hint_fwd_pd.get()) {} /// Queries diff source gradient memory descriptor. memory::desc diff_src_desc() const { return query_md(query::diff_src_md, 0); } /// Queries diff destination memory descriptor. memory::desc diff_dst_desc() const { return query_md(query::diff_dst_md, 0); } }; shuffle_backward() = default; shuffle_backward(const primitive_desc &pd): primitive(pd) {} }; /// @} /// @} Primitives /// @} C++ API // implementation section #ifndef DOXYGEN_SHOULD_SKIP_THIS inline primitive::primitive(const_mkldnn_primitive_desc_t c_pd) { mkldnn_primitive_t result; error::wrap_c_api(mkldnn_primitive_create(&result, c_pd), "could not create a primitive"); reset(result); } inline primitive::primitive(const primitive_desc &pd): primitive(pd.get()) {} inline void primitive::execute(stream &astream, const std::unordered_map<int, memory> &args) const { std::vector<mkldnn_exec_arg_t> c_args; c_args.reserve(args.size()); for (const auto &a: args) c_args.push_back({a.first, a.second.get()}); error::wrap_c_api(mkldnn_primitive_execute(get(), astream.get(), (int)c_args.size(), c_args.data()), "could not execute a primitive"); } #endif // DOXYGEN_SHOULD_SKIP_THIS } // namespace mkldnn #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/bn_stats_finalize-inl.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file bn_stats_finalize-inl.h * \brief * \author <NAME> */ #ifndef MXNET_OPERATOR_NN_BN_STATS_FINALIZE_INL_H_ #define MXNET_OPERATOR_NN_BN_STATS_FINALIZE_INL_H_ #include <dmlc/logging.h> #include <dmlc/parameter.h> #include <mxnet/operator.h> #include <mshadow/base.h> #include <map> #include <vector> #include <string> #include <utility> #include "../mshadow_op.h" #include "../operator_common.h" #include "../mxnet_op.h" #ifdef __GNUG__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif namespace mxnet { namespace op { namespace bn_stats_finalize { enum BatchNormOpInputs {kSum, kSumOfSquares, kGamma, kBeta, kInMovingMean, kInMovingVar, kNumInputs // Not an I/O! Leave this at the end }; // kGamma: weights, kBeta: biases enum BatchNormOpOutputs {kEquivScale, kEquivBias, kMean, kInvStdDev, kGammaOut, kBetaOut, kNumOutputs // Not an I/O! Leave this at the end }; // req, out_data enum BatchNormOpAuxiliary {kMovingMean, kMovingVar, kNumAuxStates // Not an I/O! Leave this at the end }; // aux_states enum BatchNormCounts {kNumNonAuxInputs = (kNumInputs - kNumAuxStates)}; } // namespace bn_stats_finalize /*! \brief Parameters for BatchNoram operator */ struct BNStatsFinalizeParam : public dmlc::Parameter<BNStatsFinalizeParam> { double eps; float momentum; bool fix_gamma; bool use_global_stats; bool output_mean_var; uint64_t elem_count; DMLC_DECLARE_PARAMETER(BNStatsFinalizeParam) { DMLC_DECLARE_FIELD(eps).set_default(1e-3f) .describe("Epsilon to prevent div 0. " "Must be no less than CUDNN_BN_MIN_EPSILON " "defined in cudnn.h when using cudnn (usually 1e-5)"); DMLC_DECLARE_FIELD(momentum).set_default(0.9f) .describe("Momentum for moving average"); DMLC_DECLARE_FIELD(fix_gamma).set_default(true) .describe("Fix gamma while training"); DMLC_DECLARE_FIELD(use_global_stats).set_default(false) .describe("Whether use global moving statistics instead of local batch-norm. " "This will force change batch-norm into a scale shift operator."); DMLC_DECLARE_FIELD(output_mean_var).set_default(false) .describe("Output the mean and inverse std "); DMLC_DECLARE_FIELD(elem_count) .describe("Number of elements accumulated in 'sum' and 'sum_squares'."); } bool operator==(const BNStatsFinalizeParam& other) const { return this->eps == other.eps && this->momentum == other.momentum && this->fix_gamma == other.fix_gamma && this->use_global_stats == other.use_global_stats && this->output_mean_var == other.output_mean_var && this->elem_count == other.elem_count; } }; typedef ParamOpSign<BNStatsFinalizeParam> BNStatsFinalizeSignature; } // namespace op } // namespace mxnet namespace std { template<> struct hash<mxnet::op::BNStatsFinalizeParam> { size_t operator()(const mxnet::op::BNStatsFinalizeParam& val) { size_t ret = 0; // Not critical, but not sure why eps is left out. Related to being 'double'? ret = dmlc::HashCombine(ret, val.momentum); ret = dmlc::HashCombine(ret, val.fix_gamma); ret = dmlc::HashCombine(ret, val.use_global_stats); ret = dmlc::HashCombine(ret, val.output_mean_var); ret = dmlc::HashCombine(ret, val.elem_count); return ret; } }; } // namespace std namespace mxnet { namespace op { template<typename xpu> void BNStatsFinalizeCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { LOG(FATAL) << "Only gpu impl of BNStatsFinalize exists."; } template<typename xpu> void BNStatsFinalizeGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { LOG(FATAL) << "Only gpu impl of BNStatsFinalize exists."; } } // namespace op } // namespace mxnet #ifdef __GNUG__ #pragma GCC diagnostic pop #endif #endif // MXNET_OPERATOR_NN_BN_STATS_FINALIZE_INL_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/gtests/test_rnn_forward.cpp<|end_filename|> /******************************************************************************* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <utility> #include <numeric> #include "gtest/gtest.h" #include "mkldnn_test_common.hpp" #include "mkldnn.hpp" namespace mkldnn { struct test_rnn_sizes_t { test_rnn_sizes_t( memory::dim l, memory::dim d, memory::dim t, memory::dim mb, memory::dim slc, memory::dim sic, memory::dim dlc, memory::dim dic) : l(l), d(d), t(t), mb(mb), slc(slc), sic(sic), dlc(dlc), dic(dic) {} memory::dim l, d; memory::dim t; memory::dim mb; memory::dim slc, sic, dlc, dic; }; struct test_rnn_formats_t { mkldnn::memory::format_tag src_layer_fmt; mkldnn::memory::format_tag src_iter_fmt; mkldnn::memory::format_tag weights_layer_fmt; mkldnn::memory::format_tag weights_iter_fmt; mkldnn::memory::format_tag bias_fmt; mkldnn::memory::format_tag dst_layer_fmt; mkldnn::memory::format_tag dst_iter_fmt; }; struct test_rnn_extra_t { mkldnn::algorithm activation; rnn_flags flags; float alpha; float beta; }; struct test_rnn_params_t { test_rnn_extra_t extra; prop_kind aprop; mkldnn::rnn_direction direction; test_rnn_formats_t fmts; test_rnn_sizes_t sizes; bool expect_to_fail; mkldnn_status_t expected_status; }; // We assume uniform data type accross tensors for now template <typename T, typename data_t> class rnn_forward_test : public ::testing::TestWithParam<test_rnn_params_t> { private: memory::dim getNGates(); typename T::desc setDesc(prop_kind aprop, algorithm activation, rnn_direction direction, const memory::desc &src_layer_md, const memory::desc &src_iter_md, const memory::desc &src_iter_c_md, const memory::desc &weights_layer_md, const memory::desc &weights_iter_md, const memory::desc &bias_md, const memory::desc &dst_layer_md, const memory::desc &dst_iter_md, const memory::desc &dst_iter_c_md, rnn_flags flags = rnn_flags::undef, float alpha = 0.0f, float beta = 0.0f); bool skipTest(bool src_layer_match, bool src_iter_match, bool src_iter_c_match, bool weights_layer_match, bool weights_iter_match, bool bias_match, bool dst_layer_match, bool dst_iter_match, bool dst_iter_c_match){ // By default, we ignore src_iter_c and dst_iter_c as they are // only supported for lstm. For LSTM tests, this function // should be specialized to handle them. return src_layer_match && src_iter_match && weights_layer_match && weights_iter_match && bias_match && dst_layer_match && dst_iter_match; } memory::desc querySrcIterC(typename T::primitive_desc rpd){ return memory::desc(); } memory::desc queryDstIterC(typename T::primitive_desc rpd){ return memory::desc(); } protected: virtual void SetUp() { auto p = ::testing::TestWithParam<test_rnn_params_t>::GetParam(); catch_expected_failures([=](){Test();}, p.expect_to_fail, p.expected_status, false); } void Test() { auto p = ::testing::TestWithParam<test_rnn_params_t>::GetParam(); auto eng = engine(get_test_engine_kind(), 0); auto strm = stream(eng); //@todo check algorithm is one of the supported by RNN //ASSERT_EQ(p.aalgorithm, algorithm::vanilla_lstm); // Initialize the data memory::data_type prec = data_traits<data_t>::data_type; auto dims = p.sizes; auto t = dims.t, mb = dims.mb, l = dims.l, d = dims.d; auto slc = dims.slc, sic = dims.sic, dlc = dims.dlc, dic = dims.dic; memory::dim g = getNGates(); memory::dim bias_extra_gate = std::is_same<T, lbr_gru_forward>::value ? 1 : 0; auto weights_layer_dims = {l, d, slc, g, dic}; auto weights_iter_dims = {l, d, sic, g, dic}; auto bias_dims = {l, d, g + bias_extra_gate, dic}; auto src_layer_dims = {t, mb, slc}; auto src_iter_dims = {l, d, mb, sic}; auto src_iter_c_dims = {l, d, mb, dic}; auto dst_layer_dims = {t, mb, dlc}; auto dst_iter_dims = {l, d, mb, dic}; auto dst_iter_c_dims = {l, d, mb, dic}; auto weights_layer_md_any = memory::desc({weights_layer_dims}, prec, memory::format_tag::any); auto weights_iter_md_any = memory::desc({weights_iter_dims}, prec, memory::format_tag::any); auto bias_md_any = memory::desc({bias_dims}, prec, memory::format_tag::any); auto src_layer_md_any = memory::desc({src_layer_dims}, prec, memory::format_tag::any); auto src_iter_md_any = memory::desc({src_iter_dims}, prec, memory::format_tag::any); auto src_iter_c_md_any = memory::desc({src_iter_c_dims}, prec, memory::format_tag::any); auto dst_layer_md_any = memory::desc({dst_layer_dims}, prec, memory::format_tag::any); auto dst_iter_md_any = memory::desc({dst_iter_dims}, prec, memory::format_tag::any); auto dst_iter_c_md_any = memory::desc({dst_iter_c_dims}, prec, memory::format_tag::any); auto weights_layer_md_tgt = memory::desc({weights_layer_dims}, prec, p.fmts.weights_layer_fmt); auto weights_iter_md_tgt = memory::desc({weights_iter_dims}, prec, p.fmts.weights_iter_fmt); auto bias_md_tgt = memory::desc({bias_dims}, prec, p.fmts.bias_fmt); auto src_layer_md_tgt = memory::desc({src_layer_dims}, prec, p.fmts.src_layer_fmt); auto src_iter_md_tgt = memory::desc({src_iter_dims}, prec, p.fmts.src_iter_fmt); auto src_iter_c_md_tgt = memory::desc({src_iter_c_dims}, prec, p.fmts.src_iter_fmt); auto dst_layer_md_tgt = memory::desc({dst_layer_dims}, prec, p.fmts.dst_layer_fmt); auto dst_iter_md_tgt = memory::desc({dst_iter_dims}, prec, p.fmts.dst_iter_fmt); auto dst_iter_c_md_tgt = memory::desc({dst_iter_c_dims}, prec, p.fmts.dst_iter_fmt); // Create the reference primitive descriptor auto ref_d = setDesc(p.aprop, p.extra.activation, p.direction, src_layer_md_any, src_iter_md_any, src_iter_c_md_any, weights_layer_md_any, weights_iter_md_any, bias_md_any, dst_layer_md_any, dst_iter_md_any, dst_iter_c_md_any, p.extra.flags, p.extra.alpha, p.extra.beta); typename T::primitive_desc ref_pd(ref_d, eng); // Query the descriptor for memory descriptors auto weights_layer_md_ref = ref_pd.weights_layer_desc(); auto weights_iter_md_ref = ref_pd.weights_iter_desc(); auto bias_md_ref = ref_pd.bias_desc(); auto src_layer_md_ref = ref_pd.src_layer_desc(); auto src_iter_md_ref = ref_pd.src_iter_desc(); auto src_iter_c_md_ref = querySrcIterC(ref_pd); auto dst_layer_md_ref = ref_pd.dst_layer_desc(); auto dst_iter_md_ref = ref_pd.dst_iter_desc(); auto dst_iter_c_md_ref = queryDstIterC(ref_pd); if (skipTest(weights_layer_md_ref == weights_layer_md_tgt, weights_iter_md_ref == weights_iter_md_tgt, bias_md_ref == bias_md_tgt, src_layer_md_ref == src_layer_md_tgt, src_iter_md_ref == src_iter_md_tgt, src_iter_c_md_ref == src_iter_c_md_tgt, dst_layer_md_ref == dst_layer_md_tgt, dst_iter_md_ref == dst_iter_md_tgt, dst_iter_c_md_ref == dst_iter_c_md_tgt)) return; /* initialize data */ auto weights_layer_ref = memory(weights_layer_md_ref, eng); auto weights_iter_ref = memory(weights_iter_md_ref, eng); auto bias_ref = memory(bias_md_ref, eng); auto src_layer_ref = memory(src_layer_md_ref, eng); auto src_iter_ref = memory(src_iter_md_ref, eng); auto src_iter_c_ref = memory(src_iter_c_md_ref, eng); auto dst_layer_ref = memory(dst_layer_md_ref, eng); auto dst_iter_ref = memory(dst_iter_md_ref, eng); auto dst_iter_c_ref = memory(dst_iter_c_md_ref, eng); auto weights_layer_tgt = memory(weights_layer_md_tgt, eng); auto weights_iter_tgt = memory(weights_iter_md_tgt, eng); auto bias_tgt = memory(bias_md_tgt, eng); auto src_layer_tgt = memory(src_layer_md_tgt, eng); auto src_iter_tgt = memory(src_iter_md_tgt, eng); auto src_iter_c_tgt = memory(src_iter_c_md_tgt, eng); auto dst_layer_tgt = memory(dst_layer_md_tgt, eng); auto dst_iter_tgt = memory(dst_iter_md_tgt, eng); auto dst_iter_c_tgt = memory(dst_iter_c_md_tgt, eng); // Assumption: b is a plain layout auto init_tensor = [&](memory a, memory b) { auto b_ptr = map_memory<float>(b); auto desc = a.get_desc(); auto b_dims = desc.data.dims; auto b_ndims = desc.data.ndims; auto n_elems = std::accumulate(b_dims, b_dims + b_ndims, size_t(1), std::multiplies<float>()); const mkldnn::impl::memory_desc_wrapper mdw(desc.data); for(size_t i = 0; i < n_elems; i++) b_ptr[i] = i; reorder(b, a).execute(strm, b, a); strm.wait(); }; init_tensor(weights_layer_ref, weights_layer_tgt); init_tensor(weights_iter_ref, weights_iter_tgt); init_tensor(bias_ref, bias_tgt); init_tensor(src_layer_ref, src_layer_tgt); init_tensor(src_iter_ref, src_iter_tgt); if(std::is_same<T, lstm_forward>::value) init_tensor(src_iter_c_ref, src_iter_c_tgt); // run the non packed version T(ref_pd).execute(strm, { {MKLDNN_ARG_SRC_LAYER, src_layer_ref}, {MKLDNN_ARG_SRC_ITER, src_iter_ref}, {MKLDNN_ARG_SRC_ITER_C, src_iter_c_ref}, {MKLDNN_ARG_WEIGHTS_LAYER, weights_layer_ref}, {MKLDNN_ARG_WEIGHTS_ITER, weights_iter_ref}, {MKLDNN_ARG_BIAS, bias_ref}, {MKLDNN_ARG_DST_LAYER, dst_layer_ref}, {MKLDNN_ARG_DST_ITER, dst_iter_ref}, {MKLDNN_ARG_DST_ITER_C, dst_iter_c_ref}}); strm.wait(); // run the packed version auto tgt_d = setDesc(p.aprop, p.extra.activation, p.direction, src_layer_md_tgt, src_iter_md_tgt, src_iter_c_md_tgt, weights_layer_md_tgt, weights_iter_md_tgt, bias_md_tgt, dst_layer_md_tgt, dst_iter_md_tgt, dst_iter_c_md_tgt, p.extra.flags, p.extra.alpha, p.extra.beta); typename T::primitive_desc tgt_pd(tgt_d, eng); T(tgt_pd).execute(strm, { {MKLDNN_ARG_SRC_LAYER, src_layer_tgt}, {MKLDNN_ARG_SRC_ITER, src_iter_tgt}, {MKLDNN_ARG_SRC_ITER_C, src_iter_c_tgt}, {MKLDNN_ARG_WEIGHTS_LAYER, weights_layer_tgt}, {MKLDNN_ARG_WEIGHTS_ITER, weights_iter_tgt}, {MKLDNN_ARG_BIAS, bias_tgt}, {MKLDNN_ARG_DST_LAYER, dst_layer_tgt}, {MKLDNN_ARG_DST_ITER, dst_iter_tgt}, {MKLDNN_ARG_DST_ITER_C, dst_iter_c_tgt}}); strm.wait(); // compare dst_layer and dst_iter compare_data<data_t>(dst_layer_ref, dst_layer_tgt, 1e-5); compare_data<data_t>(dst_iter_ref, dst_iter_tgt, 1e-5); } }; /* RNN specializations */ template<> memory::dim rnn_forward_test<vanilla_rnn_forward, float>::getNGates(){ return 1; } template<> vanilla_rnn_forward::desc rnn_forward_test<vanilla_rnn_forward, float>::setDesc( prop_kind aprop, algorithm activation, rnn_direction direction, const memory::desc &src_layer_md, const memory::desc &src_iter_md, const memory::desc &src_iter_c_md, const memory::desc &weights_layer_md, const memory::desc &weights_iter_md, const memory::desc &bias_md, const memory::desc &dst_layer_md, const memory::desc &dst_iter_md, const memory::desc &dst_iter_c_md, rnn_flags flags, float alpha, float beta){ vanilla_rnn_forward::desc rnn_d(aprop, activation, direction, src_layer_md, src_iter_md, weights_layer_md, weights_iter_md, bias_md, dst_layer_md, dst_iter_md, flags, alpha, beta); return rnn_d; } /* LSTM specializations */ template<> memory::dim rnn_forward_test<lstm_forward, float>::getNGates(){ return 4; } template<> lstm_forward::desc rnn_forward_test<lstm_forward, float>::setDesc( prop_kind aprop, algorithm activation, rnn_direction direction, const memory::desc &src_layer_md, const memory::desc &src_iter_md, const memory::desc &src_iter_c_md, const memory::desc &weights_layer_md, const memory::desc &weights_iter_md, const memory::desc &bias_md, const memory::desc &dst_layer_md, const memory::desc &dst_iter_md, const memory::desc &dst_iter_c_md, rnn_flags flags, float alpha, float beta){ lstm_forward::desc lstm_d(aprop, direction, src_layer_md, src_iter_md, src_iter_c_md, weights_layer_md, weights_iter_md, bias_md, dst_layer_md, dst_iter_md, dst_iter_c_md, flags); return lstm_d; } template<> bool rnn_forward_test<lstm_forward, float>::skipTest(bool src_layer_match, bool src_iter_match, bool src_iter_c_match, bool weights_layer_match, bool weights_iter_match, bool bias_match, bool dst_layer_match, bool dst_iter_match, bool dst_iter_c_match){ return src_layer_match && src_iter_match && src_iter_c_match && weights_layer_match && weights_iter_match && bias_match && dst_layer_match && dst_iter_match && dst_iter_c_match; } template<> memory::desc rnn_forward_test<lstm_forward, float>::querySrcIterC( lstm_forward::primitive_desc rpd){ return rpd.src_iter_c_desc(); } template<> memory::desc rnn_forward_test<lstm_forward, float>::queryDstIterC( lstm_forward::primitive_desc rpd){ return rpd.src_iter_c_desc(); } /* GRU specializations */ template<> memory::dim rnn_forward_test<gru_forward, float>::getNGates(){ return 3; } template<> gru_forward::desc rnn_forward_test<gru_forward, float>::setDesc( prop_kind aprop, algorithm activation, rnn_direction direction, const memory::desc &src_layer_md, const memory::desc &src_iter_md, const memory::desc &src_iter_c_md, const memory::desc &weights_layer_md, const memory::desc &weights_iter_md, const memory::desc &bias_md, const memory::desc &dst_layer_md, const memory::desc &dst_iter_md, const memory::desc &dst_iter_c_md, rnn_flags flags, float alpha, float beta){ gru_forward::desc gru_d(aprop, direction, src_layer_md, src_iter_md, weights_layer_md, weights_iter_md, bias_md, dst_layer_md, dst_iter_md, flags); return gru_d; } /* LBR GRU specializations */ template<> memory::dim rnn_forward_test<lbr_gru_forward, float>::getNGates(){ return 3; } template<> lbr_gru_forward::desc rnn_forward_test<lbr_gru_forward, float>::setDesc( prop_kind aprop, algorithm activation, rnn_direction direction, const memory::desc &src_layer_md, const memory::desc &src_iter_md, const memory::desc &src_iter_c_md, const memory::desc &weights_layer_md, const memory::desc &weights_iter_md, const memory::desc &bias_md, const memory::desc &dst_layer_md, const memory::desc &dst_iter_md, const memory::desc &dst_iter_c_md, rnn_flags flags, float alpha, float beta){ lbr_gru_forward::desc lbr_gru_d(aprop, direction, src_layer_md, src_iter_md, weights_layer_md, weights_iter_md, bias_md, dst_layer_md, dst_iter_md, flags); return lbr_gru_d; } using eng = engine::kind; using fmt = memory::format_tag; using alg = algorithm; using dir = rnn_direction; using rnn_forward_test_f32 = rnn_forward_test<vanilla_rnn_forward, float>; using lstm_forward_test_f32 = rnn_forward_test<lstm_forward, float>; using gru_forward_test_f32 = rnn_forward_test<gru_forward, float>; using lbr_gru_forward_test_f32 = rnn_forward_test<lbr_gru_forward, float>; using cfg_f32 = test_rnn_params_t; #define PLAIN_RNN(a) {a, rnn_flags::undef, 0.0f, 0.0f} #define NOT_RNN {alg::undef, rnn_flags::undef, 0.0f, 0.0f} TEST_P(rnn_forward_test_f32, TestsRnn) { } CPU_INSTANTIATE_TEST_SUITE_P(TestRnn, rnn_forward_test_f32, ::testing::Values( cfg_f32{PLAIN_RNN(alg::eltwise_tanh), prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, test_rnn_sizes_t(1, 1, 10, 16, 100, 100, 100, 100)}, /* Check for invalid parameters: unsupported unrolling */ cfg_f32{PLAIN_RNN(alg::eltwise_tanh), prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, test_rnn_sizes_t(2, 1, 10, 16, 200, 100, 100, 100), true, mkldnn_invalid_arguments}, cfg_f32{PLAIN_RNN(alg::eltwise_tanh), prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, test_rnn_sizes_t(2, 1, 10, 16, 100, 200, 100, 100), true, mkldnn_invalid_arguments}, /* Check for invalid parameters: inconsistent dimensions */ cfg_f32{PLAIN_RNN(alg::eltwise_tanh), prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, test_rnn_sizes_t(2, 1, 10, 16, 100, 100, 50, 100), true, mkldnn_invalid_arguments} ) ); TEST_P(lstm_forward_test_f32, TestsLSTM) { } CPU_INSTANTIATE_TEST_SUITE_P(TestLSTM, lstm_forward_test_f32, ::testing::Values( cfg_f32{NOT_RNN, prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, test_rnn_sizes_t(1, 1, 10, 16, 100, 100, 100, 100)} ) ); CPU_INSTANTIATE_TEST_SUITE_P(TestLSTM_failure, lstm_forward_test_f32, ::testing::Values( cfg_f32{NOT_RNN, prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, // L D T MB SLC SIC DLC DIC test_rnn_sizes_t(1, 1, 1, 1, 10, 5, 5, 5)} ) ); TEST_P(gru_forward_test_f32, TestsGRU_failure) { } CPU_INSTANTIATE_TEST_SUITE_P(TestGRU_failure, gru_forward_test_f32, ::testing::Values( cfg_f32{NOT_RNN, prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, // L D T MB SLC SIC DLC DIC test_rnn_sizes_t(1, 1, 1, 1, 10, 5, 5, 5)} ) ); TEST_P(lbr_gru_forward_test_f32, TestsGRUlbr_failure) { } CPU_INSTANTIATE_TEST_SUITE_P(TestGRUlbr_failure, lbr_gru_forward_test_f32, ::testing::Values( cfg_f32{NOT_RNN, prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, // L D T MB SLC SIC DLC DIC test_rnn_sizes_t(1, 1, 1, 1, 10, 5, 5, 5)} ) ); TEST_P(rnn_forward_test_f32, TestsRNN_failure) { } CPU_INSTANTIATE_TEST_SUITE_P(TestRNN_failure, rnn_forward_test_f32, ::testing::Values( cfg_f32{PLAIN_RNN(alg::eltwise_logistic), prop_kind::forward_inference, dir::unidirectional_left2right, {fmt::tnc, fmt::ldnc, fmt::ldigo, fmt::ldigo, fmt::ldgo, fmt::tnc, fmt::ldnc}, // L D T MB SLC SIC DLC DIC test_rnn_sizes_t(1, 1, 1, 1, 10, 5, 5, 5)} ) ); } <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-16/lingvo/core/ops/text_packing.cc<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "third_party/tensorflow_models/mlperf/models/rough/transformer_lingvo/lingvo/core/ops/text_packing.h" #include <utility> #include "third_party/tensorflow/core/platform/logging.h" namespace tensorflow { namespace babelfish { TextPacking::TextPacking(int columns, int batch, std::vector<int> times, int align, bool pack, int spread_first_n, bool use_last_fit) : columns_(columns), batch_(batch), times_(std::move(times)), align_(align), pack_(pack), spread_first_n_(std::min(spread_first_n, batch)), use_last_fit_(use_last_fit), wpos_(batch, std::vector<int>(columns, 0)), seq_(batch, 0), last_fit_(0), counter_(0) { CHECK_EQ(columns_, times_.size()) << "The size of `times` must be `columns`"; } bool TextPacking::Add(const std::vector<int>& lens, PackingIndex* p) { CHECK_EQ(columns_, lens.size()); CHECK(p); // Start searching for batch position where 'lens' could fit. // If we find a fit, on next call we start searching from the same position. // Because if we always start from 0 this loop becomes O(N^2) in batch size. // TODO(krikun): add a benchmark for very large batch sizes if (!use_last_fit_) { last_fit_ = 0; } // b is the index of the row on which we see if the current sequence fits. int b = last_fit_; for (int i = 0; i < batch_; i++, b++) { if (counter_ < spread_first_n_) { b = counter_; last_fit_ = 0; } b %= batch_; bool fits = true; for (int c = 0; c < columns_; c++) { if (wpos_[b][c] + lens[c] > times_[c]) { fits = false; break; } } if (fits) { last_fit_ = b; p->batch = b; p->time.resize(columns_); for (int c = 0; c < columns_; c++) { p->time[c] = wpos_[b][c]; wpos_[b][c] += lens[c]; if (align_ > 1) { int r = wpos_[b][c] % align_; if (r) wpos_[b][c] += (align_ - r); } if (!pack_) { wpos_[b][c] = times_[c]; } } seq_[b]++; p->seq = seq_[b]; counter_++; return true; } } return false; } void TextPacking::Reset() { for (int b = 0; b < batch_; b++) { seq_[b] = 0; for (int c = 0; c < columns_; c++) { wpos_[b][c] = 0; } } last_fit_ = 0; counter_ = 0; } } // namespace babelfish } // namespace tensorflow <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/eval.cc<|end_filename|> // Copyright 2020 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/eval.h" // Game options flags. ABSL_FLAG(bool, resign_enabled, true, "Whether resign is enabled."); ABSL_FLAG(double, resign_threshold, -0.999, "Resign threshold."); ABSL_FLAG(uint64, seed, 0, "Random seed. Use default value of 0 to use a time-based seed."); // Tree search flags. ABSL_FLAG(int32, virtual_losses, 8, "Number of virtual losses when running tree search."); ABSL_FLAG(double, value_init_penalty, 2.0, "New children value initialization penalty.\n" "Child value = parent's value - penalty * color, clamped to" " [-1, 1]. Penalty should be in [0.0, 2.0].\n" "0 is init-to-parent, 2.0 is init-to-loss [default].\n" "This behaves similiarly to Leela's FPU \"First Play Urgency\"."); // Inference flags. ABSL_FLAG(std::string, eval_model, "", "Path to a minigo model to evaluate against a target."); ABSL_FLAG(std::string, eval_device, "", "Optional ID of the device to the run inference on for the eval " "model. For TPUs, pass the gRPC address."); ABSL_FLAG(int32, num_eval_readouts, 100, "Number of readouts to make during tree search for the eval " "model.)"); ABSL_FLAG(std::string, target_model, "", "Path to a target minigo model that eval_model is evaluated " "against."); ABSL_FLAG(std::string, target_device, "", "Optional ID of the device to the run inference on for the " "target model. For TPUs, pass the gRPC address."); ABSL_FLAG(int32, num_target_readouts, 100, "Number of readouts to make during tree search for the eval " "model.)"); ABSL_FLAG(int32, parallel_games, 32, "Number of games to play in parallel."); // Output flags. ABSL_FLAG(std::string, output_bigtable, "", "Output Bigtable specification, of the form: " "project,instance,table. " "If empty, no examples are written to Bigtable."); ABSL_FLAG(std::string, sgf_dir, "", "SGF directory for selfplay and puzzles. If empty in selfplay " "mode, no SGF is written."); ABSL_FLAG(std::string, bigtable_tag, "", "Used in Bigtable metadata."); ABSL_FLAG(bool, verbose, true, "Enable verbose logging."); namespace minigo { Evaluator::Evaluator() { // Create a batcher for the eval model. batchers_.push_back(absl::make_unique<BatchingModelFactory>( absl::GetFlag(FLAGS_eval_device), 2)); // If the target model requires a different device, create one & a second // batcher too. if (absl::GetFlag(FLAGS_target_device) != absl::GetFlag(FLAGS_eval_device)) { batchers_.push_back(absl::make_unique<BatchingModelFactory>( absl::GetFlag(FLAGS_target_device), 2)); } } void Evaluator::Reset() { threads_ = std::vector<std::thread>(); } std::vector<std::pair<std::string, WinStats>> Evaluator::Run() { auto start_time = absl::Now(); game_options_.resign_enabled = absl::GetFlag(FLAGS_resign_enabled); game_options_.resign_threshold = -std::abs(absl::GetFlag(FLAGS_resign_threshold)); MctsPlayer::Options player_options; player_options.virtual_losses = absl::GetFlag(FLAGS_virtual_losses); player_options.inject_noise = false; player_options.random_seed = absl::GetFlag(FLAGS_seed); player_options.tree.value_init_penalty = absl::GetFlag(FLAGS_value_init_penalty); player_options.tree.soft_pick_enabled = false; player_options.num_readouts = absl::GetFlag(FLAGS_num_eval_readouts); EvaluatedModel eval_model(batchers_.front().get(), absl::GetFlag(FLAGS_eval_model), player_options); player_options.num_readouts = absl::GetFlag(FLAGS_num_target_readouts); EvaluatedModel target_model(batchers_.back().get(), absl::GetFlag(FLAGS_target_model), player_options); int num_games = absl::GetFlag(FLAGS_parallel_games); for (int thread_id = 0; thread_id < num_games; ++thread_id) { bool swap_models = (thread_id & 1) != 0; threads_.emplace_back(std::bind(&Evaluator::ThreadRun, this, thread_id, swap_models ? &target_model : &eval_model, swap_models ? &eval_model : &target_model)); } for (auto& t : threads_) { t.join(); } MG_LOG(INFO) << "Evaluated " << num_games << " games, total time " << (absl::Now() - start_time); std::vector<std::pair<std::string, WinStats>> win_stats_result( {{eval_model.name(), eval_model.GetWinStats()}, {target_model.name(), target_model.GetWinStats()}}); MG_LOG(INFO) << FormatWinStatsTable(win_stats_result); return win_stats_result; } void Evaluator::ThreadRun(int thread_id, EvaluatedModel* black_model, EvaluatedModel* white_model) { // Only print the board using ANSI colors if stderr is sent to the // terminal. const bool use_ansi_colors = FdSupportsAnsiColors(fileno(stderr)); // The player and other_player reference this pointer. std::unique_ptr<Model> model; std::vector<std::string> bigtable_spec = absl::StrSplit(absl::GetFlag(FLAGS_output_bigtable), ','); bool use_bigtable = bigtable_spec.size() == 3; if (!absl::GetFlag(FLAGS_output_bigtable).empty() && !use_bigtable) { MG_LOG(FATAL) << "Bigtable output must be of the form: project,instance,table"; return; } Game game(black_model->name(), white_model->name(), game_options_); const bool verbose = absl::GetFlag(FLAGS_verbose) && (thread_id == 0); auto black = absl::make_unique<MctsPlayer>( black_model->NewModel(), nullptr, &game, black_model->player_options()); auto white = absl::make_unique<MctsPlayer>( white_model->NewModel(), nullptr, &game, white_model->player_options()); BatchingModelFactory::StartGame(black->model(), white->model()); auto* curr_player = black.get(); auto* next_player = white.get(); while (!game.game_over()) { if (curr_player->root()->position.n() >= kMinPassAliveMoves && curr_player->root()->position.CalculateWholeBoardPassAlive()) { // Play pass moves to end the game. while (!game.game_over()) { MG_CHECK(curr_player->PlayMove(Coord::kPass)); next_player->PlayOpponentsMove(Coord::kPass); std::swap(curr_player, next_player); } break; } auto move = curr_player->SuggestMove(curr_player->options().num_readouts); if (verbose) { std::cerr << curr_player->tree().Describe() << "\n"; } MG_CHECK(curr_player->PlayMove(move)); if (move != Coord::kResign) { next_player->PlayOpponentsMove(move); } if (verbose) { MG_LOG(INFO) << absl::StreamFormat( "%d: %s by %s\nQ: %0.4f", curr_player->root()->position.n(), move.ToGtp(), curr_player->name(), curr_player->root()->Q()); MG_LOG(INFO) << curr_player->root()->position.ToPrettyString( use_ansi_colors); } std::swap(curr_player, next_player); } BatchingModelFactory::EndGame(black->model(), white->model()); if (game.result() > 0) { black_model->UpdateWinStats(game); } else { white_model->UpdateWinStats(game); } if (verbose) { MG_LOG(INFO) << game.result_string(); MG_LOG(INFO) << "Black was: " << game.black_name(); } // Write SGF. std::string output_name = "NO_SGF_SAVED"; if (!absl::GetFlag(FLAGS_sgf_dir).empty()) { output_name = absl::StrCat(GetOutputName(game_id_++), "-", black->name(), "-", white->name()); game.AddComment( absl::StrCat("B inferences: ", black->GetModelsUsedForInference())); game.AddComment( absl::StrCat("W inferences: ", white->GetModelsUsedForInference())); WriteSgf(absl::GetFlag(FLAGS_sgf_dir), output_name, game, true); } if (use_bigtable) { const auto& gcp_project_name = bigtable_spec[0]; const auto& instance_name = bigtable_spec[1]; const auto& table_name = bigtable_spec[2]; tf_utils::WriteEvalRecord(gcp_project_name, instance_name, table_name, game, output_name, absl::GetFlag(FLAGS_bigtable_tag)); } MG_LOG(INFO) << "Thread " << thread_id << " stopping"; } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_avx_kernel_sgemm_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_f32.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx_kernel_sgemm_kern::jit_avx_kernel_sgemm_kern() : jit_generator(nullptr, F32_COMPUTE_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define K rdx #define A r8 #define B r9 #define C rcx #define LDC r10 #define AA r15 #define I r11 #define J r12 #define H rax #define AO rbx #define BO rbp #define CO1 r13 #define CO2 r14 #define OLD_C 8+stacksize+rsp #define OLD_LDC 16+stacksize+rsp #else #define M rcx #define N rdx #define K r8 #define A rdi #define B rsi #define C r9 #define LDC r10 #define AA r15 #define I r11 #define J r12 #define H rax #define AO rbx #define BO rbp #define CO1 r13 #define CO2 r14 #define OLD_A 40+stacksize+rsp #define OLD_B 48+stacksize+rsp #define OLD_C 56+stacksize+rsp #define OLD_LDC 64+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l1064; Xbyak::Label l1078; Xbyak::Label l10a8; Xbyak::Label l1104; Xbyak::Label l12c8; Xbyak::Label l12e4; Xbyak::Label l14a8; Xbyak::Label l14b4; Xbyak::Label l1524; Xbyak::Label l15ac; Xbyak::Label l1614; Xbyak::Label l17d8; Xbyak::Label l17e8; Xbyak::Label l19ac; Xbyak::Label l19b8; Xbyak::Label l1a28; Xbyak::Label l1a84; Xbyak::Label l1aec; Xbyak::Label l1cb0; Xbyak::Label l1cbc; Xbyak::Label l1e80; Xbyak::Label l1e8c; Xbyak::Label l1efc; Xbyak::Label l1f44; Xbyak::Label l1f48; Xbyak::Label l1f78; Xbyak::Label l1fd4; Xbyak::Label l219c; Xbyak::Label l21b8; Xbyak::Label l2380; Xbyak::Label l238c; Xbyak::Label l23fc; Xbyak::Label l2484; Xbyak::Label l24ec; Xbyak::Label l26b4; Xbyak::Label l26c4; Xbyak::Label l288c; Xbyak::Label l2898; Xbyak::Label l2908; Xbyak::Label l2964; Xbyak::Label l29cc; Xbyak::Label l2a0; Xbyak::Label l2b94; Xbyak::Label l2ba0; Xbyak::Label l2bc; Xbyak::Label l2d68; Xbyak::Label l2d74; Xbyak::Label l2de4; Xbyak::Label l2e2c; Xbyak::Label l2e30; Xbyak::Label l2e60; Xbyak::Label l2ebc; Xbyak::Label l3084; Xbyak::Label l30a0; Xbyak::Label l3268; Xbyak::Label l3274; Xbyak::Label l32e4; Xbyak::Label l336c; Xbyak::Label l33d4; Xbyak::Label l359c; Xbyak::Label l35ac; Xbyak::Label l3774; Xbyak::Label l3780; Xbyak::Label l37f0; Xbyak::Label l384c; Xbyak::Label l38b4; Xbyak::Label l3a7c; Xbyak::Label l3a88; Xbyak::Label l3c50; Xbyak::Label l3c5c; Xbyak::Label l3ccc; Xbyak::Label l3d14; Xbyak::Label l3d18; Xbyak::Label l3d48; Xbyak::Label l3da4; Xbyak::Label l3f6c; Xbyak::Label l3f84; Xbyak::Label l414c; Xbyak::Label l4158; Xbyak::Label l41c8; Xbyak::Label l4250; Xbyak::Label l42b8; Xbyak::Label l4480; Xbyak::Label l4490; Xbyak::Label l4658; Xbyak::Label l4664; Xbyak::Label l46d4; Xbyak::Label l4730; Xbyak::Label l4798; Xbyak::Label l48c; Xbyak::Label l4960; Xbyak::Label l496c; Xbyak::Label l498; Xbyak::Label l4b34; Xbyak::Label l4b40; Xbyak::Label l4bb0; Xbyak::Label l4bf8; Xbyak::Label l4bfc; Xbyak::Label l50; Xbyak::Label l508; Xbyak::Label l608; Xbyak::Label l670; Xbyak::Label l74; Xbyak::Label l840; Xbyak::Label l850; Xbyak::Label la20; Xbyak::Label la2c; Xbyak::Label la9c; Xbyak::Label lb4c; Xbyak::Label lbb4; Xbyak::Label ld0; Xbyak::Label ld84; Xbyak::Label ld90; Xbyak::Label lf60; Xbyak::Label lf6c; Xbyak::Label lfdc; preamble(); auto stacksize = get_size_of_abi_save_regs(); #ifdef _WIN32 mov(A, ptr[OLD_A]); mov(B, ptr[OLD_B]); #endif mov(C, ptr[OLD_C]); mov(LDC, ptr[OLD_LDC]); mov(M, qword[M]); mov(N, qword[N]); mov(K, qword[K]); shl(LDC, 0x2); sub(A, -128); sub(B, -128); mov(J, M); cmp(J, 0x10); jl(l1078, T_NEAR); align(4); L(l50); mov(AA, K); imul(AA, AA, 0x40); add(AA, A); mov(CO1, C); add(C, 0x40); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l608, T_NEAR); align(4); L(l74); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l48c, T_NEAR); sub(H, 0x1e); jle(l2a0, T_NEAR); align(4); L(ld0); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(ld0, T_NEAR); align(4); L(l2a0); prefetcht0(byte[CO1+0x3c]); prefetcht0(byte[CO1+LDC*1+0x3c]); prefetcht0(byte[CO2+0x3c]); prefetcht0(byte[CO2+LDC*1+0x3c]); add(H, 0x1e); align(4); L(l2bc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2bc, T_NEAR); align(4); L(l48c); mov(H, K); and_(H, 0x3); je(l508, T_NEAR); align(4); L(l498); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x40]); vmovups(ymm1, yword[AO-0x20]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -64); sub(BO, -16); dec(H); jg(l498, T_NEAR); align(4); L(l508); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vblendps(ymm0, ymm12, ymm13, 0xaa); vblendps(ymm1, ymm12, ymm13, 0x55); vblendps(ymm2, ymm14, ymm15, 0xaa); vblendps(ymm3, ymm14, ymm15, 0x55); vblendps(ymm12, ymm0, ymm2, 0xcc); vblendps(ymm13, ymm1, ymm3, 0xcc); vblendps(ymm14, ymm0, ymm2, 0x33); vblendps(ymm15, ymm1, ymm3, 0x33); vmovups(ymm0, yword[CO1+0x0]); vaddps(ymm8, ymm0, ymm8); vmovups(yword[CO1+0x0], ymm8); vmovups(ymm1, yword[CO1+0x20]); vaddps(ymm12, ymm1, ymm12); vmovups(yword[CO1+0x20], ymm12); vmovups(ymm0, yword[CO1+LDC*1+0x0]); vaddps(ymm9, ymm0, ymm9); vmovups(yword[CO1+LDC*1+0x0], ymm9); vmovups(ymm1, yword[CO1+LDC*1+0x20]); vaddps(ymm13, ymm1, ymm13); vmovups(yword[CO1+LDC*1+0x20], ymm13); vmovups(ymm0, yword[CO2]); vaddps(ymm10, ymm0, ymm10); vmovups(yword[CO2], ymm10); vmovups(ymm1, yword[CO2+0x20]); vaddps(ymm14, ymm1, ymm14); vmovups(yword[CO2+0x20], ymm14); vmovups(ymm0, yword[CO2+LDC*1]); vaddps(ymm11, ymm0, ymm11); vmovups(yword[CO2+LDC*1], ymm11); vmovups(ymm1, yword[CO2+LDC*1+0x20]); vaddps(ymm15, ymm1, ymm15); vmovups(yword[CO2+LDC*1+0x20], ymm15); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l74, T_NEAR); align(4); L(l608); test(I, 0x2); jle(lb4c, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(la20, T_NEAR); sub(H, 0x1e); jle(l840, T_NEAR); align(4); L(l670); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l670, T_NEAR); align(4); L(l840); prefetcht0(byte[CO1+0x3c]); prefetcht0(byte[CO1+LDC*1+0x3c]); add(H, 0x1e); align(4); L(l850); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l850, T_NEAR); align(4); L(la20); mov(H, K); and_(H, 0x3); je(la9c, T_NEAR); align(4); L(la2c); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x40]); vmovups(ymm1, yword[AO-0x20]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -64); sub(BO, -8); dec(H); jg(la2c, T_NEAR); align(4); L(la9c); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vblendps(ymm0, ymm12, ymm13, 0xaa); vblendps(ymm1, ymm12, ymm13, 0x55); vblendps(ymm2, ymm14, ymm15, 0xaa); vblendps(ymm3, ymm14, ymm15, 0x55); vblendps(ymm12, ymm0, ymm2, 0xcc); vblendps(ymm13, ymm1, ymm3, 0xcc); vblendps(ymm14, ymm0, ymm2, 0x33); vblendps(ymm15, ymm1, ymm3, 0x33); vmovups(ymm0, yword[CO1+0x0]); vaddps(ymm8, ymm0, ymm8); vmovups(yword[CO1+0x0], ymm8); vmovups(ymm1, yword[CO1+0x20]); vaddps(ymm12, ymm1, ymm12); vmovups(yword[CO1+0x20], ymm12); vmovups(ymm0, yword[CO1+LDC*1+0x0]); vaddps(ymm9, ymm0, ymm9); vmovups(yword[CO1+LDC*1+0x0], ymm9); vmovups(ymm1, yword[CO1+LDC*1+0x20]); vaddps(ymm13, ymm1, ymm13); vmovups(yword[CO1+LDC*1+0x20], ymm13); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(lb4c); test(I, 0x1); jle(l1064, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(lf60, T_NEAR); sub(H, 0x1e); jle(ld84, T_NEAR); align(4); L(lbb4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(lbb4, T_NEAR); align(4); L(ld84); prefetcht0(byte[CO1+0x3c]); add(H, 0x1e); align(4); L(ld90); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO+0x40]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO+0x60]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO+0x80]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0xa0]); sub(AO, -256); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(ld90, T_NEAR); align(4); L(lf60); mov(H, K); and_(H, 0x3); je(lfdc, T_NEAR); align(4); L(lf6c); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x40]); vmovups(ymm1, yword[AO-0x20]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -64); sub(BO, -4); dec(H); jg(lf6c, T_NEAR); align(4); L(lfdc); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vblendps(ymm0, ymm12, ymm13, 0xaa); vblendps(ymm1, ymm12, ymm13, 0x55); vblendps(ymm2, ymm14, ymm15, 0xaa); vblendps(ymm3, ymm14, ymm15, 0x55); vblendps(ymm12, ymm0, ymm2, 0xcc); vblendps(ymm13, ymm1, ymm3, 0xcc); vblendps(ymm14, ymm0, ymm2, 0x33); vblendps(ymm15, ymm1, ymm3, 0x33); vmovups(ymm0, yword[CO1+0x0]); vaddps(ymm8, ymm0, ymm8); vmovups(yword[CO1+0x0], ymm8); vmovups(ymm1, yword[CO1+0x20]); vaddps(ymm12, ymm1, ymm12); vmovups(yword[CO1+0x20], ymm12); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l1064); mov(A, AO); sub(J, 0x10); cmp(J, 0x10); jge(l50, T_NEAR); align(4); L(l1078); test(J, 0x8); jle(l1f48, T_NEAR); mov(AA, K); imul(AA, AA, 0x20); add(AA, A); mov(CO1, C); add(C, 0x20); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l15ac, T_NEAR); align(4); L(l10a8); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l14a8, T_NEAR); sub(H, 0x1e); jle(l12c8, T_NEAR); align(4); L(l1104); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1104, T_NEAR); align(4); L(l12c8); prefetcht0(byte[CO1+0x1c]); prefetcht0(byte[CO1+LDC*1+0x1c]); prefetcht0(byte[CO2+0x1c]); prefetcht0(byte[CO2+LDC*1+0x1c]); add(H, 0x1e); align(4); L(l12e4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l12e4, T_NEAR); align(4); L(l14a8); mov(H, K); and_(H, 0x3); je(l1524, T_NEAR); align(4); L(l14b4); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x60]); vmovups(ymm1, yword[AO-0x40]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -32); sub(BO, -16); dec(H); jg(l14b4, T_NEAR); align(4); L(l1524); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(ymm0, yword[CO1+0x0]); vaddps(ymm8, ymm0, ymm8); vmovups(yword[CO1+0x0], ymm8); vmovups(ymm0, yword[CO1+LDC*1+0x0]); vaddps(ymm9, ymm0, ymm9); vmovups(yword[CO1+LDC*1+0x0], ymm9); vmovups(ymm0, yword[CO2]); vaddps(ymm10, ymm0, ymm10); vmovups(yword[CO2], ymm10); vmovups(ymm0, yword[CO2+LDC*1]); vaddps(ymm11, ymm0, ymm11); vmovups(yword[CO2+LDC*1], ymm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l10a8, T_NEAR); align(4); L(l15ac); test(I, 0x2); jle(l1a84, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l19ac, T_NEAR); sub(H, 0x1e); jle(l17d8, T_NEAR); align(4); L(l1614); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1614, T_NEAR); align(4); L(l17d8); prefetcht0(byte[CO1+0x1c]); prefetcht0(byte[CO1+LDC*1+0x1c]); add(H, 0x1e); align(4); L(l17e8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l17e8, T_NEAR); align(4); L(l19ac); mov(H, K); and_(H, 0x3); je(l1a28, T_NEAR); align(4); L(l19b8); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x60]); vmovups(ymm1, yword[AO-0x40]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -32); sub(BO, -8); dec(H); jg(l19b8, T_NEAR); align(4); L(l1a28); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(ymm0, yword[CO1+0x0]); vaddps(ymm8, ymm0, ymm8); vmovups(yword[CO1+0x0], ymm8); vmovups(ymm0, yword[CO1+LDC*1+0x0]); vaddps(ymm9, ymm0, ymm9); vmovups(yword[CO1+LDC*1+0x0], ymm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l1a84); test(I, 0x1); jle(l1f44, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l1e80, T_NEAR); sub(H, 0x1e); jle(l1cb0, T_NEAR); align(4); L(l1aec); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1aec, T_NEAR); align(4); L(l1cb0); prefetcht0(byte[CO1+0x1c]); add(H, 0x1e); align(4); L(l1cbc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x20]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO+0x20]); sub(AO, -128); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1cbc, T_NEAR); align(4); L(l1e80); mov(H, K); and_(H, 0x3); je(l1efc, T_NEAR); align(4); L(l1e8c); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x60]); vmovups(ymm1, yword[AO-0x40]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -32); sub(BO, -4); dec(H); jg(l1e8c, T_NEAR); align(4); L(l1efc); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(ymm0, yword[CO1+0x0]); vaddps(ymm8, ymm0, ymm8); vmovups(yword[CO1+0x0], ymm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l1f44); mov(A, AO); align(4); L(l1f48); test(J, 0x4); jle(l2e30, T_NEAR); mov(AA, K); imul(AA, AA, 0x10); add(AA, A); mov(CO1, C); add(C, 0x10); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l2484, T_NEAR); align(4); L(l1f78); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2380, T_NEAR); sub(H, 0x1e); jle(l219c, T_NEAR); align(4); L(l1fd4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l1fd4, T_NEAR); align(4); L(l219c); prefetcht0(byte[CO1+0xc]); prefetcht0(byte[CO1+LDC*1+0xc]); prefetcht0(byte[CO2+0xc]); prefetcht0(byte[CO2+LDC*1+0xc]); add(H, 0x1e); align(4); L(l21b8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l21b8, T_NEAR); align(4); L(l2380); mov(H, K); and_(H, 0x3); je(l23fc, T_NEAR); align(4); L(l238c); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x70]); vmovups(ymm1, yword[AO-0x50]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -16); sub(BO, -16); dec(H); jg(l238c, T_NEAR); align(4); L(l23fc); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(xmm0, xword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovups(xword[CO1+0x0], xmm8); vmovups(xmm0, xword[CO1+LDC*1+0x0]); vaddps(xmm9, xmm0, xmm9); vmovups(xword[CO1+LDC*1+0x0], xmm9); vmovups(xmm0, xword[CO2]); vaddps(xmm10, xmm0, xmm10); vmovups(xword[CO2], xmm10); vmovups(xmm0, xword[CO2+LDC*1]); vaddps(xmm11, xmm0, xmm11); vmovups(xword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l1f78, T_NEAR); align(4); L(l2484); test(I, 0x2); jle(l2964, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l288c, T_NEAR); sub(H, 0x1e); jle(l26b4, T_NEAR); align(4); L(l24ec); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l24ec, T_NEAR); align(4); L(l26b4); prefetcht0(byte[CO1+0xc]); prefetcht0(byte[CO1+LDC*1+0xc]); add(H, 0x1e); align(4); L(l26c4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l26c4, T_NEAR); align(4); L(l288c); mov(H, K); and_(H, 0x3); je(l2908, T_NEAR); align(4); L(l2898); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x70]); vmovups(ymm1, yword[AO-0x50]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -16); sub(BO, -8); dec(H); jg(l2898, T_NEAR); align(4); L(l2908); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(xmm0, xword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovups(xword[CO1+0x0], xmm8); vmovups(xmm0, xword[CO1+LDC*1+0x0]); vaddps(xmm9, xmm0, xmm9); vmovups(xword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l2964); test(I, 0x1); jle(l2e2c, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l2d68, T_NEAR); sub(H, 0x1e); jle(l2b94, T_NEAR); align(4); L(l29cc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l29cc, T_NEAR); align(4); L(l2b94); prefetcht0(byte[CO1+0xc]); add(H, 0x1e); align(4); L(l2ba0); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x50]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x30]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x40]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x20]); sub(AO, -64); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2ba0, T_NEAR); align(4); L(l2d68); mov(H, K); and_(H, 0x3); je(l2de4, T_NEAR); align(4); L(l2d74); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x70]); vmovups(ymm1, yword[AO-0x50]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -16); sub(BO, -4); dec(H); jg(l2d74, T_NEAR); align(4); L(l2de4); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovups(xmm0, xword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovups(xword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l2e2c); mov(A, AO); align(4); L(l2e30); test(J, 0x2); jle(l3d18, T_NEAR); mov(AA, K); imul(AA, AA, 0x8); add(AA, A); mov(CO1, C); add(C, 0x8); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l336c, T_NEAR); align(4); L(l2e60); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l3268, T_NEAR); sub(H, 0x1e); jle(l3084, T_NEAR); align(4); L(l2ebc); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l2ebc, T_NEAR); align(4); L(l3084); prefetcht0(byte[CO1+0x4]); prefetcht0(byte[CO1+LDC*1+0x4]); prefetcht0(byte[CO2+0x4]); prefetcht0(byte[CO2+LDC*1+0x4]); add(H, 0x1e); align(4); L(l30a0); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l30a0, T_NEAR); align(4); L(l3268); mov(H, K); and_(H, 0x3); je(l32e4, T_NEAR); align(4); L(l3274); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x78]); vmovups(ymm1, yword[AO-0x58]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -8); sub(BO, -16); dec(H); jg(l3274, T_NEAR); align(4); L(l32e4); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovsd(xmm0, qword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovlps(qword[CO1+0x0], xmm8); vmovsd(xmm0, qword[CO1+LDC*1+0x0]); vaddps(xmm9, xmm0, xmm9); vmovlps(qword[CO1+LDC*1+0x0], xmm9); vmovsd(xmm0, qword[CO2]); vaddps(xmm10, xmm0, xmm10); vmovlps(qword[CO2], xmm10); vmovsd(xmm0, qword[CO2+LDC*1]); vaddps(xmm11, xmm0, xmm11); vmovlps(qword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l2e60, T_NEAR); align(4); L(l336c); test(I, 0x2); jle(l384c, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l3774, T_NEAR); sub(H, 0x1e); jle(l359c, T_NEAR); align(4); L(l33d4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l33d4, T_NEAR); align(4); L(l359c); prefetcht0(byte[CO1+0x4]); prefetcht0(byte[CO1+LDC*1+0x4]); add(H, 0x1e); align(4); L(l35ac); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l35ac, T_NEAR); align(4); L(l3774); mov(H, K); and_(H, 0x3); je(l37f0, T_NEAR); align(4); L(l3780); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x78]); vmovups(ymm1, yword[AO-0x58]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -8); sub(BO, -8); dec(H); jg(l3780, T_NEAR); align(4); L(l37f0); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovsd(xmm0, qword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovlps(qword[CO1+0x0], xmm8); vmovsd(xmm0, qword[CO1+LDC*1+0x0]); vaddps(xmm9, xmm0, xmm9); vmovlps(qword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l384c); test(I, 0x1); jle(l3d14, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l3c50, T_NEAR); sub(H, 0x1e); jle(l3a7c, T_NEAR); align(4); L(l38b4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l38b4, T_NEAR); align(4); L(l3a7c); prefetcht0(byte[CO1+0x4]); add(H, 0x1e); align(4); L(l3a88); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x68]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x48]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x60]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x40]); sub(AO, -32); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3a88, T_NEAR); align(4); L(l3c50); mov(H, K); and_(H, 0x3); je(l3ccc, T_NEAR); align(4); L(l3c5c); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x78]); vmovups(ymm1, yword[AO-0x58]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -8); sub(BO, -4); dec(H); jg(l3c5c, T_NEAR); align(4); L(l3ccc); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovsd(xmm0, qword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovlps(qword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l3d14); mov(A, AO); align(4); L(l3d18); test(J, 0x1); jle(l4bfc, T_NEAR); mov(AA, K); imul(AA, AA, 0x4); add(AA, A); mov(CO1, C); add(C, 0x4); mov(BO, B); mov(I, N); cmp(I, 0x4); jl(l4250, T_NEAR); align(4); L(l3d48); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l414c, T_NEAR); sub(H, 0x1e); jle(l3f6c, T_NEAR); align(4); L(l3da4); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3da4, T_NEAR); align(4); L(l3f6c); prefetcht0(byte[CO1+0x0]); prefetcht0(byte[CO1+LDC*1+0x0]); prefetcht0(byte[CO2]); prefetcht0(byte[CO2+LDC*1]); add(H, 0x1e); align(4); L(l3f84); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x50]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x40]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -64); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l3f84, T_NEAR); align(4); L(l414c); mov(H, K); and_(H, 0x3); je(l41c8, T_NEAR); align(4); L(l4158); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x7c]); vmovups(ymm1, yword[AO-0x5c]); vbroadcastf128(ymm2, xword[BO-0x70]); sub(AO, -4); sub(BO, -16); dec(H); jg(l4158, T_NEAR); align(4); L(l41c8); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovss(xmm0, dword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovss(dword[CO1+0x0], xmm8); vmovss(xmm0, dword[CO1+LDC*1+0x0]); vaddps(xmm9, xmm0, xmm9); vmovss(dword[CO1+LDC*1+0x0], xmm9); vmovss(xmm0, dword[CO2]); vaddps(xmm10, xmm0, xmm10); vmovss(dword[CO2], xmm10); vmovss(xmm0, dword[CO2+LDC*1]); vaddps(xmm11, xmm0, xmm11); vmovss(dword[CO2+LDC*1], xmm11); lea(CO1, ptr[CO1+LDC*4+0x0]); sub(I, 0x4); cmp(I, 0x4); jge(l3d48, T_NEAR); align(4); L(l4250); test(I, 0x2); jle(l4730, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l4658, T_NEAR); sub(H, 0x1e); jle(l4480, T_NEAR); align(4); L(l42b8); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l42b8, T_NEAR); align(4); L(l4480); prefetcht0(byte[CO1+0x0]); prefetcht0(byte[CO1+LDC*1+0x0]); add(H, 0x1e); align(4); L(l4490); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x68]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x60]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -32); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l4490, T_NEAR); align(4); L(l4658); mov(H, K); and_(H, 0x3); je(l46d4, T_NEAR); align(4); L(l4664); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x7c]); vmovups(ymm1, yword[AO-0x5c]); vbroadcastf128(ymm2, xword[BO-0x78]); sub(AO, -4); sub(BO, -8); dec(H); jg(l4664, T_NEAR); align(4); L(l46d4); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovss(xmm0, dword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovss(dword[CO1+0x0], xmm8); vmovss(xmm0, dword[CO1+LDC*1+0x0]); vaddps(xmm9, xmm0, xmm9); vmovss(dword[CO1+LDC*1+0x0], xmm9); lea(CO1, ptr[CO1+LDC*2+0x0]); align(4); L(l4730); test(I, 0x1); jle(l4bf8, T_NEAR); vxorps(ymm8, ymm8, ymm8); vbroadcastf128(ymm2, xword[BO-0x80]); vxorps(ymm9, ymm9, ymm9); vmovups(ymm0, yword[A-0x80]); vxorps(ymm10, ymm10, ymm10); vmovups(ymm1, yword[A-0x60]); vxorps(ymm11, ymm11, ymm11); lea(CO2, ptr[CO1+LDC*2+0x0]); vxorps(ymm12, ymm12, ymm12); vxorps(ymm13, ymm13, ymm13); vxorps(ymm14, ymm14, ymm14); vxorps(ymm15, ymm15, ymm15); mov(AO, A); mov(H, K); sar(H, 0x2); jle(l4b34, T_NEAR); sub(H, 0x1e); jle(l4960, T_NEAR); align(4); L(l4798); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l4798, T_NEAR); align(4); L(l4960); prefetcht0(byte[CO1+0x0]); add(H, 0x1e); align(4); L(l496c); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x180]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); prefetcht0(byte[BO+0x100]); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x7c]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x7c]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x5c]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x1c0]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x78]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); prefetcht0(byte[AA-0x80]); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x78]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x58]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm2, ymm0); prefetcht0(byte[AO+0x200]); vmulps(ymm7, ymm2, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm3, xword[BO-0x74]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm6, ymm2, ymm0); vmulps(ymm7, ymm2, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm6, ymm2, ymm0); vmovups(ymm0, yword[AO-0x74]); vmulps(ymm7, ymm2, ymm1); vmovups(ymm1, yword[AO-0x54]); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); vmulps(ymm6, ymm3, ymm0); prefetcht0(byte[AO+0x240]); vmulps(ymm7, ymm3, ymm1); vaddps(ymm8, ymm8, ymm6); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm3, ymm3, 0xb1); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm9, ymm9, ymm6); vbroadcastf128(ymm2, xword[BO-0x70]); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm3, ymm3, 0x1b); vmulps(ymm6, ymm3, ymm0); vmulps(ymm7, ymm3, ymm1); vaddps(ymm10, ymm10, ymm6); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm3, ymm3, 0xb1); add(AA, 0x4); vmulps(ymm6, ymm3, ymm0); vmovups(ymm0, yword[AO-0x70]); vmulps(ymm7, ymm3, ymm1); vmovups(ymm1, yword[AO-0x50]); sub(AO, -16); sub(BO, -16); vaddps(ymm11, ymm11, ymm6); vaddps(ymm15, ymm15, ymm7); sub(H, 0x1); jg(l496c, T_NEAR); align(4); L(l4b34); mov(H, K); and_(H, 0x3); je(l4bb0, T_NEAR); align(4); L(l4b40); vmulps(ymm7, ymm2, ymm0); vaddps(ymm8, ymm8, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm12, ymm12, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm9, ymm9, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm13, ymm13, ymm7); vpermilps(ymm2, ymm2, 0x1b); vmulps(ymm7, ymm2, ymm0); vaddps(ymm10, ymm10, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm14, ymm14, ymm7); vpermilps(ymm2, ymm2, 0xb1); vmulps(ymm7, ymm2, ymm0); vaddps(ymm11, ymm11, ymm7); vmulps(ymm7, ymm2, ymm1); vaddps(ymm15, ymm15, ymm7); vmovups(ymm0, yword[AO-0x7c]); vmovups(ymm1, yword[AO-0x5c]); vbroadcastf128(ymm2, xword[BO-0x7c]); sub(AO, -4); sub(BO, -4); dec(H); jg(l4b40, T_NEAR); align(4); L(l4bb0); vblendps(ymm0, ymm8, ymm9, 0xaa); vblendps(ymm1, ymm8, ymm9, 0x55); vblendps(ymm2, ymm10, ymm11, 0xaa); vblendps(ymm3, ymm10, ymm11, 0x55); vblendps(ymm8, ymm0, ymm2, 0xcc); vblendps(ymm9, ymm1, ymm3, 0xcc); vblendps(ymm10, ymm0, ymm2, 0x33); vblendps(ymm11, ymm1, ymm3, 0x33); vmovss(xmm0, dword[CO1+0x0]); vaddps(xmm8, xmm0, xmm8); vmovss(dword[CO1+0x0], xmm8); lea(CO1, ptr[CO1+LDC*1+0x0]); align(4); L(l4bf8); mov(A, AO); align(4); L(l4bfc); postamble(); } outLocalLabel(); #undef M #undef N #undef K #undef A #undef B #undef C #undef LDC #undef AA #undef I #undef J #undef H #undef AO #undef BO #undef CO1 #undef CO2 #ifdef _WIN32 #undef OLD_A #undef OLD_B #endif #undef OLD_C #undef OLD_LDC } } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/model/model.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_MODEL_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_MODEL_H_ #include <string> #include <vector> #include "REDACTEDtypes/span.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/color.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/inline_vector.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/features.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/types.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/position.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/symmetries.h" namespace minigo { // TODO(tommadams): replace all std::vector parameters with absl::Span. class Model { public: // Fills a batch of inference outputs from policy and value tensors. // Args: // model_inputs: the same inputs that were passed to `SetFeatures`. // policy: the policy output from the model. // value: the value output from the model. // model_outputs: the model outputs to fill. `model_inputs.size()` must == // `model_outputs.size()`. // Models that produce quantized outputs should unquantize them into // `Tensor<float>` objects before calling GetOutputs. static void GetOutputs(absl::Span<const ModelInput* const> inputs, const Tensor<float>& policy, const Tensor<float>& value, absl::Span<ModelOutput*> outputs); static void ApplySymmetry(symmetry::Symmetry sym, const ModelOutput& src, ModelOutput* dst); Model(std::string name, const FeatureDescriptor& feature_desc); virtual ~Model(); const std::string& name() const { return name_; } const FeatureDescriptor& feature_descriptor() const { return feature_desc_; } // TODO(tommadams): remove the model_name out parameter: it's no longer needed // with the new concurrent_selfplay implementation. virtual void RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) = 0; private: const std::string name_; const FeatureDescriptor feature_desc_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_MODEL_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ref_batch_normalization.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_REF_BATCH_NORMALIZATION_FWD_HPP #define OCL_REF_BATCH_NORMALIZATION_FWD_HPP #include <assert.h> #include "common/c_types_map.hpp" #include "ocl/cl_engine.hpp" #include "ocl/jit_ref_bnorm_common_kernel.hpp" #include "ocl/ocl_batch_normalization_pd.hpp" #include "ocl/ocl_stream.hpp" #include "ocl/ocl_utils.hpp" extern const char *ref_bnorm_common_kernel; namespace mkldnn { namespace impl { namespace ocl { template <impl::data_type_t data_type> struct ref_batch_normalization_fwd_t : public primitive_t { struct pd_t : public ocl_batch_normalization_fwd_pd_t { pd_t(engine_t *engine, const batch_normalization_desc_t *adesc, const primitive_attr_t *attr, const batch_normalization_fwd_pd_t *hint_fwd_pd) : ocl_batch_normalization_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) , jbn_() , jit_off_() {} DECLARE_COMMON_PD_T("ocl:ref:any", ref_batch_normalization_fwd_t); status_t init() { auto *cl_engine = utils::downcast<cl_engine_t *>(engine()); bool ok = true && is_fwd() && utils::everyone_is(data_type, src_md()->data_type, dst_md()->data_type) && IMPLICATION(data_type == data_type::f16, !is_training() && stats_is_src()) && (attr()->has_default_values() || with_relu_post_op()) && cl_engine->mayiuse(cl_device_ext_t::intel_subgroups); if (!ok) return status::unimplemented; if (src_md()->data_type == data_type::s8 && !stats_is_src()) return status::unimplemented; if (is_training() && fuse_norm_relu()) init_default_ws(8); return jit_ref_bnorm_common_kernel::init_conf( jbn_, desc_, src_md(), this, jit_off_); } jit_bnorm_conf_t jbn_; jit_offsets jit_off_; }; status_t init() override { auto jit = ocl_jit_t(ref_bnorm_common_kernel); jit_ref_bnorm_common_kernel::init_const_def( jit, pd()->jbn_, pd()->jit_off_); status_t status = jit.build(engine()); if (status != status::success) return status; kernel_ = jit.get_kernel("ref_bnorm_fwd_kernel"); if (!kernel_) return status::runtime_error; if (pd()->jbn_.use_16mb_unroll && pd()->jbn_.calculate_stats) { size_t size = 2 * pd()->jbn_.mb_chunk * pd()->jbn_.sp_chunk * pd()->jbn_.ic * sizeof(data_t); memory_storage_t *temp_reduce_ptr; engine()->create_memory_storage(&temp_reduce_ptr, size); temp_reduce.reset(temp_reduce_ptr); if (!temp_reduce) return status::runtime_error; calculate_mean_kernel_ = jit.get_kernel("calculate_mean"); if (!calculate_mean_kernel_) return status::runtime_error; calculate_variance_kernel_ = jit.get_kernel("calculate_variance"); if (!calculate_variance_kernel_) return status::runtime_error; reduce_mean_kernel_ = jit.get_kernel("reduce_mean"); if (!reduce_mean_kernel_) return status::runtime_error; reduce_variance_kernel_ = jit.get_kernel("reduce_variance"); if (!reduce_variance_kernel_) return status::runtime_error; } return status::success; } ref_batch_normalization_fwd_t(const pd_t *apd) : primitive_t(apd) { ker_ = new jit_ref_bnorm_common_kernel(pd()->jbn_); } ~ref_batch_normalization_fwd_t() { delete ker_; } typedef typename prec_traits<data_type>::type data_t; virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_forward(ctx); } private: status_t execute_forward(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } jit_ref_bnorm_common_kernel *ker_; ocl_kernel_t kernel_; ocl_kernel_t calculate_mean_kernel_; ocl_kernel_t reduce_mean_kernel_; ocl_kernel_t calculate_variance_kernel_; ocl_kernel_t reduce_variance_kernel_; std::unique_ptr<memory_storage_t> temp_reduce; }; template <impl::data_type_t data_type> struct ref_batch_normalization_bwd_t : public primitive_t { struct pd_t : public ocl_batch_normalization_bwd_pd_t { pd_t(engine_t *engine, const batch_normalization_desc_t *adesc, const primitive_attr_t *attr, const batch_normalization_fwd_pd_t *hint_fwd_pd) : ocl_batch_normalization_bwd_pd_t(engine, adesc, attr, hint_fwd_pd) , jbn_() , jit_off_() {} DECLARE_COMMON_PD_T("ocl:ref:any", ref_batch_normalization_bwd_t); status_t init() { bool ok = true && is_bwd() && utils::everyone_is(data_type, src_md()->data_type, diff_src_md()->data_type) && IMPLICATION(use_scaleshift(), utils::everyone_is(data_type, weights_md()->data_type, diff_weights_md()->data_type)) && attr()->has_default_values(); if (!ok) return status::unimplemented; if (fuse_norm_relu()) { init_default_ws(8); if (!compare_ws(hint_fwd_pd_)) return status::unimplemented; } return jit_ref_bnorm_common_kernel::init_conf( jbn_, desc_, diff_src_md(), this, jit_off_); } jit_bnorm_conf_t jbn_; jit_offsets jit_off_; }; status_t init() override { auto jit = ocl_jit_t(ref_bnorm_common_kernel); jit_ref_bnorm_common_kernel::init_const_def( jit, pd()->jbn_, pd()->jit_off_); status_t status = jit.build(engine()); if (status != status::success) return status; kernel_ = jit.get_kernel("ref_bnorm_bwd_kernel"); if (!kernel_) return status::runtime_error; if (pd()->jbn_.use_16mb_unroll) { size_t size = 2 * pd()->jbn_.mb_chunk * pd()->jbn_.sp_chunk * pd()->jbn_.ic * sizeof(data_t); memory_storage_t *temp_reduce_ptr; engine()->create_memory_storage(&temp_reduce_ptr, size); temp_reduce.reset(temp_reduce_ptr); if (!temp_reduce) return status::runtime_error; calculate_stats_kernel_ = jit.get_kernel("calculate_stats"); if (!calculate_stats_kernel_) return status::runtime_error; reduce_stats_kernel_ = jit.get_kernel("reduce_stats"); if (!reduce_stats_kernel_) return status::runtime_error; } return status::success; } ref_batch_normalization_bwd_t(const pd_t *apd) : primitive_t(apd) { ker_ = new jit_ref_bnorm_common_kernel(pd()->jbn_); } ~ref_batch_normalization_bwd_t() { delete ker_; } typedef typename prec_traits<data_type>::type data_t; virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_backward(ctx); } private: status_t execute_backward(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } jit_ref_bnorm_common_kernel *ker_; ocl_kernel_t kernel_; ocl_kernel_t calculate_stats_kernel_; ocl_kernel_t reduce_stats_kernel_; std::unique_ptr<memory_storage_t> temp_reduce; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/normalized_convolution.cu<|end_filename|> /* * 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. */ /*! * Copyright (c) 2017 by Contributors * \file normalized_convolution.cu * \brief * \author <NAME> */ #include "./normalized_convolution-inl.h" #include <vector> #if MXNET_USE_CUDNN == 1 #include "./cudnn/cudnn_normalized_convolution-inl.h" #endif // MXNET_USE_CUDNN namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 template<typename DType> static CuDNNNormalizedConvolutionOp<DType>& GetCuDNNNormalizedConvOp( const NormalizedConvolutionParam& param, bool output_stats, const std::vector<mxnet::TShape>& in_shape, const std::vector<mxnet::TShape>& out_shape, const OpContext& ctx) { #if DMLC_CXX11_THREAD_LOCAL static thread_local std::unordered_map<NormalizedConvSignature, std::shared_ptr<CuDNNNormalizedConvolutionOp<DType> >, OpHash> ops; #else static MX_THREAD_LOCAL std::unordered_map<NormalizedConvSignature, std::shared_ptr<CuDNNNormalizedConvolutionOp<DType> >, OpHash> ops; #endif NormalizedConvSignature key(param); size_t ndim = 0; for (auto &s : in_shape) ndim += s.ndim(); for (auto &s : out_shape) ndim += s.ndim(); key.Reserve(1 /* for output_stats */ + ndim /* for in and out shapes */ + 1 /* for dev_id */); key.AddSign(output_stats); key.AddSign(in_shape); key.AddSign(out_shape); key.AddSign(ctx.run_ctx.ctx.dev_id); auto it = ops.find(key); if (it == ops.end()) { std::shared_ptr<CuDNNNormalizedConvolutionOp<DType>> op( new CuDNNNormalizedConvolutionOp<DType>()); auto ins_ret = ops.insert(std::pair<NormalizedConvSignature, std::shared_ptr<CuDNNNormalizedConvolutionOp<DType>>>(key, op)); CHECK(ins_ret.second); it = ins_ret.first; it->second->Init(param, output_stats, in_shape, out_shape, ctx); } return *it->second; } #endif template<> void NormalizedConvolutionCompute<gpu>(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const NormalizedConvolutionParam& param = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); int dtype = inputs[normalized_conv::kData].type_flag_; mxnet::TShape in_data_shape = inputs[normalized_conv::kData].shape_; #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { if (!CuDNNNormalizedConvolutionOp<DType>::Supports(param, in_data_shape, ctx.run_ctx.ctx.dev_id)) { LOG(WARNING) << "This NormalizedConvolution is not supported by cudnn" << ", MXNET NormalizedConvolution is applied."; NormalizedConvolutionOp<gpu, DType> op; op.Init(param); op.Forward(ctx, inputs, req, outputs); } else { std::vector<mxnet::TShape> in_shape(inputs.size()); std::vector<mxnet::TShape> out_shape(outputs.size()); bool output_stats = CuDNNNormalizedConvolutionOp<DType>::OutputStats(ctx, req); for (size_t i = 0; i < in_shape.size(); i++) in_shape[i] = inputs[i].shape_; for (size_t i = 0; i < out_shape.size(); i++) out_shape[i] = outputs[i].shape_; CuDNNNormalizedConvolutionOp<DType> &op = GetCuDNNNormalizedConvOp<DType>(param, output_stats, in_shape, out_shape, ctx); op.Forward(ctx, inputs, req, outputs); } }) #else MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { NormalizedConvolutionOp<gpu, DType> op; op.Init(param); op.Forward(ctx, inputs, req, outputs); }) #endif // MXNET_USE_CUDNN } template<> void NormalizedConvolutionGradCompute<gpu>(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const NormalizedConvolutionParam& param = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); size_t num_fwd_inputs = normalized_conv::NumInputs(param.no_equiv_scale_bias); size_t num_fwd_ios = inputs.size(); size_t num_fwd_outputs = num_fwd_ios - num_fwd_inputs; std::vector<TBlob> fwd_out_data(inputs.begin(), inputs.begin() + num_fwd_outputs); std::vector<TBlob> fwd_in_data(inputs.begin() + num_fwd_outputs, inputs.end()); // Remember, for fwd_out_data[kOut], we've swapped in the gradient for the output itself. const TBlob &out_grad = fwd_out_data[normalized_conv::kOut]; // Gradient types will be the same as the corresponding output int dtype = out_grad.type_flag_; mxnet::TShape in_data_shape = fwd_in_data[normalized_conv::kData].shape_; #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { if (!CuDNNNormalizedConvolutionOp<DType>::Supports(param, in_data_shape, ctx.run_ctx.ctx.dev_id)) { LOG(WARNING) << "This NormalizedConvolution is not supported by cudnn" << ", MXNET NormalizedConvolution is applied."; NormalizedConvolutionOp<gpu, DType> op; op.Init(param); op.Backward(ctx, std::vector<TBlob>{out_grad}, fwd_in_data, req, outputs); } else { std::vector<mxnet::TShape> in_shape(fwd_in_data.size()); std::vector<mxnet::TShape> out_shape(fwd_out_data.size()); for (size_t i = 0; i < in_shape.size(); i++) in_shape[i] = fwd_in_data[i].shape_; for (size_t i = 0; i < out_shape.size(); i++) out_shape[i] = fwd_out_data[i].shape_; // The Backward() call performs the same function, regardless of 'output_stats', so in that // sense, the setting is arbitrary. However, all configurations of NormalizedConvolution // will have a 'false' version after they have gone through the validation step. Since // we can't call the OutputStats(ctx, req) routine since 'req' refers to the forward outputs, // we just assume 'false' for simplicity: bool output_stats = false; CuDNNNormalizedConvolutionOp<DType> &op = GetCuDNNNormalizedConvOp<DType>(param, output_stats, in_shape, out_shape, ctx); op.Backward(ctx, std::vector<TBlob>{out_grad}, fwd_in_data, req, outputs); } }) #else MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { NormalizedConvolutionOp<gpu, DType> op; op.Init(param); op.Backward(ctx, std::vector<TBlob>{out_grad}, fwd_in_data, req, outputs); }) #endif // MXNET_USE_CUDNN } NNVM_REGISTER_OP(NormalizedConvolution) .set_attr<FCompute>("FCompute<gpu>", NormalizedConvolutionCompute<gpu>); NNVM_REGISTER_OP(_backward_NormalizedConvolution) .set_attr<FCompute>("FCompute<gpu>", NormalizedConvolutionGradCompute<gpu>); } // namespace op } // namespace mxnet <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/dual_net/tf_dual_net.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/dual_net/tf_dual_net.h" #include <algorithm> #include <thread> // NOLINT #include <utility> #include <vector> #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/match.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDsynchronization/notification.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "third_party/tensorflow/core/common_runtime/device.h" #include "third_party/tensorflow/core/framework/graph.pb.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/lib/core/errors.h" #include "third_party/tensorflow/core/lib/core/status.h" #include "third_party/tensorflow/core/platform/protobuf.h" #include "third_party/tensorflow/core/public/session.h" #include "third_party/tracing_framework_bindings_cpp/macros.h" namespace minigo { namespace { void PlaceOnDevice(tensorflow::GraphDef* graph_def, const std::string& device) { for (auto& node : *graph_def->mutable_node()) { node.set_device(device); } } class TfDualNet : public Model { public: TfDualNet(const std::string& graph_path, const FeatureDescriptor& feature_desc, const tensorflow::GraphDef& graph_def); ~TfDualNet() override; void RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) override; private: void Reserve(int capacity); std::unique_ptr<tensorflow::Session> session_; tensorflow::Session::CallableHandle handle_; std::vector<tensorflow::Tensor> inputs_; std::vector<tensorflow::Tensor> outputs_; const std::string graph_path_; int batch_capacity_ = 0; tensorflow::DataType input_type_ = tensorflow::DT_INVALID; }; TfDualNet::TfDualNet(const std::string& graph_path, const FeatureDescriptor& feature_desc, const tensorflow::GraphDef& graph_def) : Model(std::string(file::Stem(file::Basename(graph_path))), feature_desc), graph_path_(graph_path) { tensorflow::SessionOptions session_options; session_options.config.mutable_gpu_options()->set_allow_growth(true); // session_options.config.set_inter_op_parallelism_threads(1); // auto* thread_pool_options = // session_options.config.add_session_inter_op_thread_pool(); // thread_pool_options->set_num_threads(1); // thread_pool_options->set_global_name("TfDualNet"); session_.reset(tensorflow::NewSession(session_options)); TF_CHECK_OK(session_->Create(graph_def)); tensorflow::CallableOptions callable_options; callable_options.add_feed("pos_tensor"); callable_options.add_fetch("policy_output"); callable_options.add_fetch("value_output"); callable_options.add_target("policy_output"); callable_options.add_target("value_output"); // Timeout after 30 seconds. callable_options.mutable_run_options()->set_timeout_in_ms(30 * 1000); TF_CHECK_OK(session_->MakeCallable(callable_options, &handle_)); for (const auto& node : graph_def.node()) { if (node.name() == "pos_tensor") { auto it = node.attr().find("dtype"); MG_CHECK(it != node.attr().end()); input_type_ = it->second.type(); break; } } const auto* desc = proto2::GetEnumDescriptor<tensorflow::DataType>(); const auto* value = desc->FindValueByNumber(input_type_); MG_CHECK(value != nullptr); MG_LOG(INFO) << "Model " << graph_path_ << " has input type " << value->name(); MG_CHECK(input_type_ == tensorflow::DT_FLOAT || input_type_ == tensorflow::DT_BOOL) << input_type_; } TfDualNet::~TfDualNet() { if (session_ != nullptr) { TF_CHECK_OK(session_->ReleaseCallable(handle_)); TF_CHECK_OK(session_->Close()); } } void TfDualNet::RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) { Reserve(inputs.size()); WTF_SCOPE("TfDualNet::Run: inputs, capacity", size_t, int) (inputs.size(), batch_capacity_); MG_CHECK(inputs.size() == outputs->size()); auto shape = feature_descriptor().GetInputShape(batch_capacity_); if (input_type_ == tensorflow::DT_FLOAT) { WTF_SCOPE("Features::SetFloat: inputs", int)(inputs.size()); Tensor<float> features(shape, inputs_[0].flat<float>().data()); feature_descriptor().set_floats(inputs, &features); } else { WTF_SCOPE("Features::SetBool: inputs", size_t)(inputs.size()); static_assert(sizeof(bool) == sizeof(uint8_t), "bool must be 1 byte"); Tensor<uint8_t> features( shape, reinterpret_cast<uint8_t*>(inputs_[0].flat<bool>().data())); feature_descriptor().set_bytes(inputs, &features); } // Run the model. { WTF_SCOPE("Session::Run: capacity", int)(batch_capacity_); outputs_.clear(); TF_CHECK_OK(session_->RunCallable(handle_, inputs_, &outputs_, nullptr)); } Tensor<float> policy({batch_capacity_, kNumMoves}, outputs_[0].flat<float>().data()); Tensor<float> value({batch_capacity_}, outputs_[1].flat<float>().data()); { WTF_SCOPE("Model::GetOutputs: outputs", size_t)(outputs->size()); Model::GetOutputs(inputs, policy, value, absl::MakeSpan(*outputs)); } if (model_name != nullptr) { *model_name = graph_path_; } } void TfDualNet::Reserve(int capacity) { MG_CHECK(capacity > 0); if (capacity <= batch_capacity_ && capacity > 3 * batch_capacity_ / 4) { return; } inputs_.clear(); // pos_tensor auto shape = feature_descriptor().GetInputShape(capacity); inputs_.emplace_back( input_type_, tensorflow::TensorShape({shape[0], shape[1], shape[2], shape[3]})); batch_capacity_ = capacity; } } // namespace TfDualNetFactory::TfDualNetFactory(absl::string_view device) { // Place all models on the GPU by default, or if the user has explicitly // requested it. place_on_gpu_ = device.empty() || device == "gpu"; if (!place_on_gpu_) { MG_CHECK(device == "cpu") << "Unrecognized device \"" << device << "\""; } } std::unique_ptr<Model> TfDualNetFactory::NewModel(const ModelDefinition& def) { MG_CHECK(def.metadata.Get<std::string>("engine") == "tf"); tensorflow::protobuf::io::CodedInputStream coded_stream( reinterpret_cast<const uint8_t*>(def.model_bytes.data()), def.model_bytes.size()); coded_stream.SetTotalBytesLimit(1024 * 1024 * 1024); tensorflow::GraphDef graph_def; MG_CHECK(graph_def.ParseFromCodedStream(&coded_stream) && coded_stream.ConsumedEntireMessage()); // Check that we're not loading a TPU model. for (const auto& node : graph_def.node()) { MG_CHECK(!absl::StartsWithIgnoreCase(node.name(), "tpu")) << "found node named \"" << node.name() << "\", this model looks like it was compiled for TPU"; } auto feature_desc = FeatureDescriptor::Create(def.metadata.Get<std::string>("input_features"), def.metadata.Get<std::string>("input_layout")); if (place_on_gpu_) { PlaceOnDevice(&graph_def, "/gpu:0"); } return absl::make_unique<TfDualNet>(def.path, feature_desc, graph_def); } } // namespace minigo <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/ml_perf_subword_op.h<|end_filename|> /* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_LINGVO_CORE_OPS_ML_PERF_SUBWORD_OP_H_ #define THIRD_PARTY_PY_LINGVO_CORE_OPS_ML_PERF_SUBWORD_OP_H_ #include <string> #include <vector> #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/platform/macros.h" namespace tensorflow { namespace babelfish { // Subword vocabulary class. class MlPerfSubword { public: MlPerfSubword() {} ~MlPerfSubword() {} Status Load(const string& vocab_glob); Status LoadLines(const std::vector<string>& lines); void Decode(const std::vector<int32>& ids, string* out); private: std::vector<string> id_to_token_; }; } // namespace babelfish } // namespace tensorflow #endif // THIRD_PARTY_PY_LINGVO_CORE_OPS_MLPERF_SUBWORD_OP_H <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/alm.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file alm.cc * \brief Automatic Layout Manager * \author <NAME> */ #include "./alm.h" #include <vector> #include <string> #include <sstream> #include <set> #include <map> #include "../operator/operator_common.h" namespace mxnet { namespace exec { using ALM = AutomaticLayoutManager; using BGNode = ALM::BGNode; namespace { static inline bool isNative(const BGNode& node) { return node.data.is_added == false; } static inline void addAllTo(std::queue<BGNode*>* queue, std::set<BGNode*>&& set) { for (auto ndPtr : set) { queue->push(ndPtr); } } template <typename Iterable> static inline bool isIdentity(Iterable arr) { int i = 0; for (const auto& elem : arr) { if (elem != i++) return false; } return true; } /*! * \brief Determines pass direction of transpose node created by collapsing two other. * \param t1 Pass direction of first transpose node. * \param t2 Pass direction of second transpose node. * \return Pass direction for new node. */ static inline ALM::passdir_t mergeDirs(ALM::passdir_t t1, ALM::passdir_t t2) { auto opposite = [](ALM::passdir_t t) { switch (t) { case ALM::kBWD: return ALM::kFWD; case ALM::kFWD: return ALM::kBWD; default: return ALM::kNONE; } }; if (t1 == opposite(t2)) return ALM::kNONE; else return t1 != ALM::kNONE ? t1 : t2; } } // namespace /*! * \brief Applies one transpose axes on the top of another. * Results in axes of a transpose created by merging the transposes * represented by given axes. * \param ax1 First transpose axes. * \param ax2 Second transpose axes. Those are to be applied on the first. * \return Axes of result transpose. */ static inline nnvm::TShape apply(const nnvm::TShape& ax1, const nnvm::TShape& ax2) { nnvm::TShape axes = ax1; CHECK_EQ(ax1.ndim(), ax2.ndim()) << "Axes ndim missmatch"; for (size_t i = 0; i < ax1.ndim(); i++) { axes[i] = ax1[ax2[i]]; } return axes; } nnvm::NodePtr ALM::CreateTransposeNode(const NodeInfo& info) { nnvm::NodePtr newptr = nnvm::Node::Create(); newptr->attrs.op = nnvm::Op::Get("transpose"); newptr->attrs.name = getNextName(); // set tranpose axes std::stringstream ss; ss << info.axes; newptr->attrs.dict["axes"] = ss.str(); newptr->op()->attr_parser(&(newptr->attrs)); return newptr; } void ALM::run(std::unordered_map<std::string, std::string> targets) { targets_.clear(); for (auto pair : targets) { auto targetLayout = mshadow::layoutFlag(pair.second); if (targetLayout != mshadow::kUNKNOWN) this->targets_[pair.first] = targetLayout; else LOG(WARNING) << "Unknown layout: " << pair.second << ". ignoring..."; } // surround targets with transposes std::queue<BGNode*> newTransps; size_t num_nodes = bigraph_.nodes().size(); for (size_t i = 0; i < num_nodes; ++i) { BGNode& node = *(bigraph_.nodes()[i]); if (node.nnvmptr->op() != nullptr && targets_.find(node.nnvmptr->op()->name) != targets_.end()) { auto targetLayout = targets_[node.nnvmptr->op()->name]; addAllTo(&newTransps, changeLayout(&node, targetLayout)); } } // push transposes through a graph std::vector<BGNode*> ready; while (!newTransps.empty()) { BGNode* t = newTransps.front(); newTransps.pop(); if (t->data.blacklisted) { continue; } if (t->data.pass_direction != kNONE) { addAllTo(&newTransps, passTranspose(t)); } else { ready.push_back(t); } } // eliminates identity transposes for (auto t : ready) { if (isIdentity(t->data.axes)) { deleteNode(t); } } } void ALM::deleteNode(BGNode* node) { bigraph_.DeleteNode(*node); node->data.blacklisted = true; } BGNode* ALM::mergeTransposes(BGNode* first, BGNode* second) { auto getAxes = [](BGNode* node) { if (node->nnvmptr) { CHECK_EQ(node->nnvmptr->op()->name, "transpose"); auto& dict = node->nnvmptr->attrs.dict; CHECK(dict.find("axes") != dict.end()) << "Transpose node should have \"axes\" param"; std::stringstream ss; ss << dict["axes"]; ss >> node->data.axes; } return node->data.axes; }; CHECK_EQ(first->inputs.size(), 1) << "Transpose node should have exactly one input"; CHECK_EQ(second->inputs.size(), 1) << "Transpose node should have exactly one input"; // let first be the father of second if (first != second->inputs[0].src_node) std::swap(first, second); CHECK_EQ(first, second->inputs[0].src_node) << "Only adjacent nodes can be merged"; const auto& ax1 = getAxes(first); const auto& ax2 = getAxes(second); CHECK_EQ(ax1.ndim(), ax2.ndim()) << "Axes size mismatch"; nnvm::TShape axes = apply(ax1, ax2); // get future pass_direction auto newPassDir = mergeDirs(first->data.pass_direction, second->data.pass_direction); BGNode* node_to_delete; if (first->outputs[0].size() > 1) { node_to_delete = bigraph_.DetachEdge(second->inputs[0]); } else { node_to_delete = first; } deleteNode(node_to_delete); // now modify second's axes and if result is identity -- delete it if (isIdentity(axes)) { deleteNode(second); return nullptr; } else { std::stringstream ss; ss << axes; second->nnvmptr->attrs.dict["axes"] = ss.str(); second->nnvmptr->op()->attr_parser(&(second->nnvmptr->attrs)); second->data = NodeInfo(newPassDir, axes, true); return second; } } std::set<BGNode*> ALM::passTranspose(BGNode* t_ptr) { CHECK_EQ(t_ptr->inputs.size(), 1) << "Transpose node should have exactly one input"; CHECK_EQ(t_ptr->outputs.size(), 1) << "Transpose node should have exactly one output"; CHECK_EQ(t_ptr->outputs[0].size(), 1) << "Transpose node should have exactly one consumer"; // get node to pass transpose through BGNode* node; index_t index; if (t_ptr->data.pass_direction == kFWD) { node = t_ptr->outputs[0][0].dst_node; index = t_ptr->outputs[0][0].dst_id; } else if (t_ptr->data.pass_direction == kBWD) { node = t_ptr->inputs[0].src_node; index = t_ptr->inputs[0].src_id; } else { return {t_ptr}; } // if it's an output, skip if (node == nullptr) { t_ptr->data.pass_direction = kNONE; return {t_ptr}; } // if it's a data node, skip if (node->nnvmptr && node->nnvmptr->op() == nullptr) { t_ptr->data.pass_direction = kNONE; return {t_ptr}; } // if it's transpose too -- just merge it if ((node->nnvmptr && node->nnvmptr->op()->name == "transpose")) { auto newNode = mergeTransposes(t_ptr, node); if (newNode != nullptr) return {newNode}; else return { }; } // get changeLayout function auto opMap = Op::GetAttr<mxnet::alm::FChangeLayout>("FChangeLayout"); auto changeLayout = opMap.get(node->nnvmptr->op(), nullptr); if (changeLayout == nullptr) { t_ptr->data.pass_direction = kNONE; return {t_ptr}; } // set vectors std::vector<nnvm::TShape> inpTransposes(node->inputs.size()); std::vector<nnvm::TShape> outTransposes(node->outputs.size()); auto axes = t_ptr->data.axes; if (t_ptr->data.pass_direction == kFWD) { inpTransposes[index] = common::ReverseTransposeAxes(axes); } else if (t_ptr->data.pass_direction == kBWD) { outTransposes[index] = common::ReverseTransposeAxes(axes); } // changeLayout changeLayout(&node->nnvmptr->attrs, mshadow::kUNKNOWN, &inpTransposes, &outTransposes); // if changeLayout fails axes vectors should be cleared if (inpTransposes.empty() || outTransposes.empty()) { t_ptr->data.pass_direction = kNONE; return {t_ptr}; } auto newNodes = surroundNode(node, &inpTransposes, &outTransposes); // collapse neighbour transposes auto ndIter = newNodes.end(); if (t_ptr->data.pass_direction == kFWD) ndIter = newNodes.find(t_ptr->outputs[0][0].dst_node); else ndIter = newNodes.find(t_ptr->inputs[0].src_node); CHECK(ndIter != newNodes.end()) << "One opposite node should be created"; auto mergedNd = mergeTransposes(t_ptr, *ndIter); CHECK(mergedNd == nullptr) << "Opposite transposes should collapse to nothing"; newNodes.erase(ndIter); if (node->nnvmptr->op()->attr_parser) node->nnvmptr->op()->attr_parser(&(node->nnvmptr->attrs)); return newNodes; } BGNode* ALM::insertTransposeBetween(const BGEdge* edge, const NodeInfo& newInfo) { nnvm::NodePtr nnvm_node = CreateTransposeNode(newInfo); BGNode* new_node = bigraph_.InsertNode(nnvm_node, *edge); new_node->data = newInfo; return new_node; } std::set<BGNode*> ALM::changeLayout(BGNode* node, mshadow::LayoutFlag targetLayout) { if (node->nnvmptr->attrs.dict["layout"] == mshadow::toString(targetLayout)) return { }; std::vector<nnvm::TShape> inpTransposes; std::vector<nnvm::TShape> outTransposes; auto opMap = Op::GetAttr<mxnet::alm::FChangeLayout>("FChangeLayout"); auto changeLayout = opMap.get(node->nnvmptr->op(), nullptr); if (changeLayout == nullptr) return { }; auto srcLayout = changeLayout(&node->nnvmptr->attrs, targetLayout, &inpTransposes, &outTransposes); if (srcLayout == mshadow::kUNKNOWN) { LOG(WARNING) << "ALM failed to change layout of " << node->nnvmptr->op()->name << " from " << node->nnvmptr->attrs.dict["layout"] << " to " << mshadow::toString(targetLayout); return { }; } auto newNodes = surroundNode(node, &inpTransposes, &outTransposes); node->nnvmptr->op()->attr_parser(&(node->nnvmptr->attrs)); return newNodes; } std::set<BGNode*> ALM::surroundNode(BGNode* node, std::vector<nnvm::TShape>* inpAxes, std::vector<nnvm::TShape>* outAxes) { std::set<BGNode*> created; if (node->inputs.empty()) { LOG(FATAL) << "Node does not have any input"; } else { CHECK_EQ(node->inputs.size(), inpAxes->size()); for (size_t i = 0; i < inpAxes->size(); i++) { if (inpAxes->at(i).ndim() <= 0 || isIdentity(inpAxes->at(i))) continue; NodeInfo newInfo(kBWD, inpAxes->at(i), true); auto ndPtr = insertTransposeBetween(&(node->inputs[i]), newInfo); created.insert(ndPtr); } } CHECK(!node->outputs.empty()) << "Node has to have outputs to be able to be surrounded."; CHECK(outAxes->size() == node->outputs.size()); for (size_t i = 0; i < node->outputs.size(); ++i) { const auto& axes = (*outAxes)[i]; if (axes.ndim() <= 0 || isIdentity(axes)) continue; for (const auto& edge : node->outputs[i]) { NodeInfo newInfo(kFWD, axes, true); auto ndPtr = insertTransposeBetween(&edge, newInfo); created.insert(ndPtr); } } return created; } } // namespace exec } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/src/lang/expr_operator.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2017 by Contributors * \file expr_operator.cc */ #include <tvm/base.h> #include <tvm/ir.h> #include <tvm/expr_operator.h> #include <cmath> // Centralized header for constant folders. #include "../arithmetic/const_fold.h" namespace tvm { // simple cast that only checks if type matches and cast inline Expr SimpleCast(const Type& t, Expr value) { if (value.type() == t) return value; return ir::Cast::make(t, value); } // The public function with a quick checking path. void BinaryOpMatchTypes(Expr& lhs, Expr& rhs) { // NOLINT(*) if (lhs.type() == rhs.type()) return; Type ltype = lhs.type(); Type rtype = rhs.type(); if (ltype.lanes() == 1 && rtype.lanes() != 1) { lhs = ir::Broadcast::make(lhs, rtype.lanes()); } else if (rtype.lanes() == 1 && ltype.lanes() != 1) { rhs = ir::Broadcast::make(rhs, ltype.lanes()); } else { CHECK(ltype.lanes() == rtype.lanes()) << "Cannot match type " << ltype << " vs " << rtype; } if (lhs.type() == rhs.type()) return; // Only do very simple type coversion // int->float, int(32)->int(64) // require the types to be relatively consistent // This will the reduce amount code generated by operators // and also help user to find potential type conversion problems. if (!lhs.type().is_float() && rhs.type().is_float()) { // int->float lhs = cast(rhs.type(), lhs); } else if (lhs.type().is_float() && !rhs.type().is_float()) { // int->float rhs = cast(lhs.type(), rhs); } else if ((lhs.type().is_int() && rhs.type().is_int()) || (lhs.type().is_uint() && rhs.type().is_uint())) { // promote int to higher bits if (lhs.type().bits() < rhs.type().bits()) { lhs = cast(rhs.type(), lhs); } else { rhs = cast(lhs.type(), rhs); } } else if ((lhs.type().is_int() && rhs.type().is_uint()) || (lhs.type().is_uint() && rhs.type().is_int())) { int bits = std::max(lhs.type().bits(), rhs.type().bits()); lhs = SimpleCast(Int(bits, lhs.type().lanes()), lhs); rhs = SimpleCast(Int(bits, rhs.type().lanes()), rhs); } else { LOG(FATAL) << "Cannot match type " << ltype << " vs " << rtype; } } template<typename ValueType> inline bool ConstPowerHelper(ValueType val, int *shift) { if (val <= 0) return false; shift[0] = 0; while (val != 0) { if (val & 1) { return (val == 1); } ++shift[0]; val = val >> 1; } return true; } bool is_const_power_of_two_integer(const Expr& x, int* shift) { if (const auto* op = x.as<ir::IntImm>()) { return ConstPowerHelper(op->value, shift); } else if (const auto* op = x.as<ir::UIntImm>()) { return ConstPowerHelper(op->value, shift); } else { return false; } } Expr cast(const Type& t, Expr value) { using ir::IntImm; using ir::FloatImm; if (value.type() == t) return value; // const fold IntImm as they are used in index computations if (t.lanes() == 1) { if (const IntImm* op = value.as<IntImm>()) { return make_const(t, op->value); } else if (const FloatImm* op = value.as<FloatImm>()) { return make_const(t, op->value); } return ir::Cast::make(t, value); } else { if (value.type().lanes() == 1) { // manually unroll cast Type vtype = t.element_of(); if (value.type() != vtype) { if (const IntImm* op = value.as<IntImm>()) { value = make_const(vtype, op->value); } else if (const FloatImm* op = value.as<FloatImm>()) { value = make_const(vtype, op->value); } else { value = ir::Cast::make(vtype, value); } } return ir::Broadcast::make(value, t.lanes()); } else { CHECK(value.type().lanes() == t.lanes()); return ir::Cast::make(t, value); } } } Expr reinterpret(const Type& t, Expr value) { if (value.type() == t) return value; return ir::Call::make(t, ir::Call::reinterpret, { value }, ir::Call::PureIntrinsic); } Expr operator+(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Add>(a, b); if (ret.defined()) return ret; return ir::Add::make(a, b); } // negation Expr operator-(Expr a) { using ir::IntImm; using ir::FloatImm; const IntImm* pa = a.as<IntImm>(); const FloatImm* fa = a.as<FloatImm>(); if (pa) return ir::IntImm::make(a.type(), -pa->value); if (fa) return ir::FloatImm::make(a.type(), -fa->value); return make_zero(a.type()) - a; } Expr operator-(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Sub>(a, b); if (ret.defined()) return ret; return ir::Sub::make(a, b); } Expr operator*(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Mul>(a, b); if (ret.defined()) return ret; return ir::Mul::make(a, b); } Expr operator/(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Div>(a, b); if (ret.defined()) return ret; return ir::Div::make(a, b); } Expr operator%(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Mod>(a, b); if (ret.defined()) return ret; return ir::Mod::make(a, b); } Expr floordiv(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::FloorDiv>(a, b); if (ret.defined()) return ret; return ir::FloorDiv::make(a, b); } Expr floormod(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::FloorMod>(a, b); if (ret.defined()) return ret; return ir::FloorMod::make(a, b); } Expr min(Expr a, Expr b) { // inf-aware simplificaiton using arith::is_pos_inf; using arith::is_neg_inf; if (is_pos_inf(a)) return b; if (is_neg_inf(a)) return a; if (is_pos_inf(b)) return a; if (is_neg_inf(b)) return b; BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Min>(a, b); if (ret.defined()) return ret; return ir::Min::make(a, b); } Expr max(Expr a, Expr b) { // inf-aware simplificaiton using arith::is_pos_inf; using arith::is_neg_inf; if (is_pos_inf(a)) return a; if (is_neg_inf(a)) return b; if (is_pos_inf(b)) return b; if (is_neg_inf(b)) return a; BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::Max>(a, b); if (ret.defined()) return ret; return ir::Max::make(a, b); } Expr if_then_else(Expr cond, Expr true_value, Expr false_value) { using ir::IntImm; using ir::UIntImm; CHECK(cond.type() == Bool(1)) << "if_then_else only accept a single condition"; BinaryOpMatchTypes(true_value, false_value); if (const UIntImm* op = cond.as<UIntImm>()) { if (op->value != 0) { return true_value; } else { return false_value; } } else if (const IntImm* op = cond.as<IntImm>()) { if (op->value != 0) { return true_value; } else { return false_value; } } return ir::Call::make( true_value.type(), ir::intrinsic::tvm_if_then_else, {cond, true_value, false_value}, ir::Call::PureIntrinsic); } Expr likely(Expr cond) { if (is_const(cond)) return cond; return ir::Call::make(cond.type(), ir::Call::likely, { cond }, ir::Call::PureIntrinsic); } Expr operator>(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::GT>(a, b); if (ret.defined()) return ret; return ir::GT::make(a, b); } Expr operator>=(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::GE>(a, b); if (ret.defined()) return ret; return ir::GE::make(a, b); } Expr operator<(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::LT>(a, b); if (ret.defined()) return ret; return ir::LT::make(a, b); } Expr operator<=(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::LE>(a, b); if (ret.defined()) return ret; return ir::LE::make(a, b); } Expr operator==(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::EQ>(a, b); if (ret.defined()) return ret; return ir::EQ::make(a, b); } Expr operator!=(Expr a, Expr b) { BinaryOpMatchTypes(a, b); Expr ret = arith::TryConstFold<ir::NE>(a, b); if (ret.defined()) return ret; return ir::NE::make(a, b); } Expr operator&&(Expr a, Expr b) { CHECK(a.type().is_bool()); CHECK(b.type().is_bool()); Expr ret = arith::TryConstFold<ir::And>(a, b); if (ret.defined()) return ret; return ir::And::make(a, b); } Expr operator||(Expr a, Expr b) { CHECK(a.type().is_bool()); CHECK(b.type().is_bool()); Expr ret = arith::TryConstFold<ir::Or>(a, b); if (ret.defined()) return ret; return ir::Or::make(a, b); } Expr operator!(Expr a) { CHECK(a.type().is_bool()); Expr ret = arith::TryConstFold<ir::Not>(a); if (ret.defined()) return ret; return ir::Not::make(a); } Expr operator>>(Expr a, Expr b) { BinaryOpMatchTypes(a, b); TVM_INDEX_CONST_PROPAGATION({ const Type& rtype = a.type(); if (pa && pb) return IntImm::make(rtype, (pa->value >> pb->value)); if (pb) { if (pb->value == 0) return a; } }); return ir::Call::make(a.type(), ir::Call::shift_right, { a, b }, ir::Call::PureIntrinsic); } Expr operator<<(Expr a, Expr b) { BinaryOpMatchTypes(a, b); TVM_INDEX_CONST_PROPAGATION({ const Type& rtype = a.type(); if (pa && pb) return IntImm::make(rtype, (pa->value << pb->value)); if (pb) { if (pb->value == 0) return a; } }); return ir::Call::make(a.type(), ir::Call::shift_left, { a, b }, ir::Call::PureIntrinsic); } Expr operator&(Expr a, Expr b) { BinaryOpMatchTypes(a, b); TVM_INDEX_CONST_PROPAGATION({ const Type& rtype = a.type(); if (pa && pb) return IntImm::make(rtype, (pa->value & pb->value)); }); return ir::Call::make(a.type(), ir::Call::bitwise_and, { a, b }, ir::Call::PureIntrinsic); } Expr operator|(Expr a, Expr b) { BinaryOpMatchTypes(a, b); TVM_INDEX_CONST_PROPAGATION({ const Type& rtype = a.type(); if (pa && pb) return IntImm::make(rtype, (pa->value | pb->value)); }); return ir::Call::make(a.type(), ir::Call::bitwise_or, { a, b }, ir::Call::PureIntrinsic); } Expr operator^(Expr a, Expr b) { BinaryOpMatchTypes(a, b); TVM_INDEX_CONST_PROPAGATION({ const Type& rtype = a.type(); if (pa && pb) return IntImm::make(rtype, (pa->value ^ pb->value)); }); return ir::Call::make(a.type(), ir::Call::bitwise_xor, { a, b }, ir::Call::PureIntrinsic); } Expr operator~(Expr a) { CHECK(a.type().is_int() || a.type().is_uint()); return ir::Call::make(a.type(), ir::Call::bitwise_not, { a }, ir::Call::PureIntrinsic); } Expr pow(Expr x, Expr y) { BinaryOpMatchTypes(x, y); CHECK(x.type().is_float()) << "power only applies to float"; return ir::Call::make(x.type(), "pow", { x, y }, ir::Call::PureIntrinsic); } Expr abs(Expr x) { if (x.type().is_int()) { using ir::IntImm; const IntImm* px = x.as<IntImm>(); if (px) { return ir::IntImm::make(x.type(), std::abs(px->value)); } return ir::Select::make(x >= make_zero(x.type()), x, -x); } else if (x.type().is_float()) { using ir::FloatImm; const FloatImm* fx = x.as<FloatImm>(); if (fx) { return ir::FloatImm::make(x.type(), std::fabs(fx->value)); } return ir::Call::make(x.type(), "fabs", {x}, ir::Call::PureIntrinsic); } else if (x.type().is_uint()) { return x; } else { LOG(FATAL) << "Data type " << x.type() <<" not supported for absolute op. Skipping absolute op..."; return x; } } Expr sum(Expr source, Array<IterVar> rdom) { Var x("x", source.type()), y("y", source.type()); Expr result = ir::Add::make(x, y); Expr identity_element = make_zero(source.type()); ir::CommReducer combiner = ir::CommReducerNode::make({x}, {y}, {result}, {identity_element}); return ir::Reduce::make(combiner, {source}, rdom, make_const(Bool(1), true), 0); } Expr all(Expr source, Array<IterVar> rdom) { CHECK(source.type().is_bool()); Var x("x", source.type()), y("y", source.type()); Expr result = ir::And::make(x, y); Expr identity_element = make_const(source.type(), true); ir::CommReducer combiner = ir::CommReducerNode::make({x}, {y}, {result}, {identity_element}); return ir::Reduce::make(combiner, {source}, rdom, make_const(Bool(1), true), 0); } Expr max(Expr source, Array<IterVar> rdom) { Var x("x", source.type()), y("y", source.type()); Expr result = ir::Max::make(x, y); Expr identity_element = source.type().min(); ir::CommReducer combiner = ir::CommReducerNode::make({x}, {y}, {result}, {identity_element}); return ir::Reduce::make(combiner, {source}, rdom, make_const(Bool(1), true), 0); } Expr min(Expr source, Array<IterVar> rdom) { Var x("x", source.type()), y("y", source.type()); Expr result = ir::Min::make(x, y); Expr identity_element = source.type().max(); ir::CommReducer combiner = ir::CommReducerNode::make({x}, {y}, {result}, {identity_element}); return ir::Reduce::make(combiner, {source}, rdom, make_const(Bool(1), true), 0); } Expr prod(Expr source, Array<IterVar> rdom) { Var x("x", source.type()), y("y", source.type()); Expr result = ir::Mul::make(x, y); Expr identity_element = make_const(source.type(), 1); ir::CommReducer combiner = ir::CommReducerNode::make({x}, {y}, {result}, {identity_element}); return ir::Reduce::make(combiner, {source}, rdom, make_const(Bool(1), true), 0); } Expr fmod(Expr x, Expr y) { BinaryOpMatchTypes(x, y); CHECK(x.type().is_float()) << "fmod only applies to float"; return ir::Call::make(x.type(), "fmod", { x, y }, ir::Call::PureIntrinsic); } Expr floor(Expr x) { using ir::FloatImm; const FloatImm* fx = x.as<FloatImm>(); if (fx) return FloatImm::make(x.type(), std::floor(fx->value)); return ir::Call::make(x.type(), "floor", {x}, ir::Call::PureIntrinsic); } Expr ceil(Expr x) { using ir::FloatImm; const FloatImm* fx = x.as<FloatImm>(); if (fx) return FloatImm::make(x.type(), std::ceil(fx->value)); return ir::Call::make(x.type(), "ceil", {x}, ir::Call::PureIntrinsic); } Expr round(Expr x) { using ir::FloatImm; const FloatImm* fx = x.as<FloatImm>(); if (fx) return FloatImm::make(x.type(), std::nearbyint(fx->value)); return ir::Call::make(x.type(), "round", {x}, ir::Call::PureIntrinsic); } Expr trunc(Expr x) { using ir::FloatImm; const FloatImm* fx = x.as<FloatImm>(); if (fx) { return FloatImm::make(x.type(), (fx->value < 0 ? std::ceil(fx->value) : std::floor(fx->value))); } return ir::Call::make(x.type(), "trunc", {x}, ir::Call::PureIntrinsic); } } // namespace tvm <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/src/arithmetic/int_set.cc<|end_filename|> /* * 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 int_set.cc * \brief The integer set functions */ #include <tvm/ir.h> #include <tvm/ir_functor_ext.h> #include <tvm/api_registry.h> #include <utility> #include <algorithm> #include <unordered_map> #include "int_set.h" #include "pattern_match.h" namespace tvm { namespace arith { Expr SymbolicLimits::pos_inf_ = Var("pos_inf", Handle()); Expr SymbolicLimits::neg_inf_ = Var("neg_inf", Handle()); IntervalSet::IntervalSet(Expr min_value, Expr max_value) { auto node = make_node<IntervalSetNode>(); node->min_value = std::move(min_value); node->max_value = std::move(max_value); node_ = std::move(node); } IntervalSet MakeIntervalSet(Expr min_value, Expr max_value) { return IntervalSet(min_value, max_value); } TVM_REGISTER_API("arith._make_IntervalSet") .set_body_typed(MakeIntervalSet); IntervalSet Intersect(Analyzer* analyzer, IntervalSet a, IntervalSet b) { Expr max_value = min(a->max_value, b->max_value); Expr min_value = max(a->min_value, b->min_value); if ((max_value.type().is_int() || max_value.type().is_uint()) && (min_value.type().is_int() || min_value.type().is_uint()) && analyzer->CanProveGreaterEqual(min_value - max_value, 1)) { return IntervalSet::Empty(); } else { return IntervalSet(min_value, max_value); } } IntervalSet Union(Analyzer* analyzer, IntervalSet a, IntervalSet b) { Expr max_value = max(a->max_value, b->max_value); Expr min_value = min(a->min_value, b->min_value); return IntervalSet(min_value, max_value); } // type traits template<typename OP> struct is_logical_op { static const bool value = false; }; #define TVM_DECLARE_LOGICAL_OP(OP) \ template<> \ struct is_logical_op<ir::OP> { \ static const bool value = true; \ }; TVM_DECLARE_LOGICAL_OP(And); TVM_DECLARE_LOGICAL_OP(Or); TVM_DECLARE_LOGICAL_OP(EQ); TVM_DECLARE_LOGICAL_OP(NE); TVM_DECLARE_LOGICAL_OP(GE); TVM_DECLARE_LOGICAL_OP(GT); TVM_DECLARE_LOGICAL_OP(LE); TVM_DECLARE_LOGICAL_OP(LT); TVM_DECLARE_LOGICAL_OP(Not); /*! * \brief Combine two interval set under arithmetic operations. * \note this can possibly relax the set. */ template<typename Op> inline IntervalSet Combine(Analyzer* analyzer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { Expr res = TryConstFold<Op>(a->min_value, b->min_value); if (!res.defined()) res = Op::make(a->min_value, b->min_value); return IntervalSet::SinglePoint(res); } if (is_logical_op<Op>::value) { return IntervalSet(make_const(a->min_value.type(), 0), make_const(a->min_value.type(), 1)); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; if (a->IsEverything()) return a; if (b->IsEverything()) return b; return IntervalSet::Everything(); } template<> inline IntervalSet Combine<ir::Add>(Analyzer* analyer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(a->min_value + b->min_value); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; Expr min_value = a->HasLowerBound() && b->HasLowerBound() ? a->min_value + b->min_value : neg_inf(); Expr max_value = a->HasUpperBound() && b->HasUpperBound() ? a->max_value + b->max_value : pos_inf(); return IntervalSet(min_value, max_value); } template<> inline IntervalSet Combine<ir::Sub>(Analyzer* analyer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(a->min_value - b->min_value); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; Expr min_value = a->HasLowerBound() && b->HasUpperBound() ? a->min_value - b->max_value : neg_inf(); Expr max_value = a->HasUpperBound() && b->HasLowerBound() ? a->max_value - b->min_value : pos_inf(); return IntervalSet(min_value, max_value); } template<> inline IntervalSet Combine<ir::Mul>(Analyzer* analyzer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(a->min_value * b->min_value); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; if (a->IsSinglePoint()) { std::swap(a, b); } if (b->IsSinglePoint()) { if (is_zero(b->min_value)) return b; if (is_one(b->min_value)) return a; if (analyzer->CanProveGreaterEqual(b->min_value, 0)) { Expr min_value = a->HasLowerBound() ? a->min_value * b->min_value : neg_inf(); Expr max_value = a->HasUpperBound() ? a->max_value * b->min_value : pos_inf(); return IntervalSet(min_value, max_value); } else if (analyzer->CanProveGreaterEqual(-b->min_value, 1)) { Expr min_value = a->HasUpperBound() ? a->max_value * b->min_value : neg_inf(); Expr max_value = a->HasLowerBound() ? a->min_value * b->min_value : pos_inf(); return IntervalSet(min_value, max_value); } else if (a->HasUpperBound() && a->HasLowerBound()) { using ir::Select; Expr sign = b->min_value >= make_zero(b->min_value.type().element_of()); Expr e1 = a->min_value * b->min_value; Expr e2 = a->max_value * b->min_value; return IntervalSet(Select::make(sign, e1, e2), Select::make(sign, e2, e1)); } } DLOG(WARNING) << "Return Everything in CombineInterval Mul"; return IntervalSet::Everything(); } template<> inline IntervalSet Combine<ir::Div>(Analyzer* analyzer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(a->min_value / b->min_value); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; if (b->IsSinglePoint()) { if (is_zero(b->min_value)) { LOG(FATAL) << "Divide by zero in CombineInterval Div"; } if (is_one(b->min_value)) return a; // no relaxation is needed in here due to set is inclusive if (analyzer->CanProveGreaterEqual(b->min_value, 0)) { Expr min_value = a->HasLowerBound() ? a->min_value / b->min_value : neg_inf(); Expr max_value = a->HasUpperBound() ? a->max_value / b->min_value : pos_inf(); return IntervalSet(min_value, max_value); } else if (analyzer->CanProveGreaterEqual(-b->min_value, 1)) { Expr min_value = a->HasUpperBound() ? a->max_value / b->min_value : neg_inf(); Expr max_value = a->HasLowerBound() ? a->min_value / b->min_value : pos_inf(); return IntervalSet(min_value, max_value); } else if (a->HasUpperBound() && a->HasLowerBound()) { using ir::Select; Expr sign = b->min_value >= make_zero(b->min_value.type().element_of()); Expr e1 = a->min_value / b->min_value; Expr e2 = a->max_value / b->min_value; return IntervalSet(Select::make(sign, e1, e2), Select::make(sign, e2, e1)); } } DLOG(WARNING) << "Return Everything in CombineInterval Div"; return IntervalSet::Everything(); } template<> inline IntervalSet Combine<ir::Mod>(Analyzer* analyzer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(a->min_value % b->min_value); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; if (b->IsSinglePoint()) { const Expr& divisor = b->min_value; if (is_zero(divisor)) { LOG(FATAL) << "Modular by zero in CombineInterval Mod"; } // We need to add more bound constraints throughout the code. // The logic below assumes a is non-negative, which usually // is the case of our application. // TODO(tqchen): add bound constraints for a. if (analyzer->CanProveGreaterEqual(divisor, 0)) { return IntervalSet(make_zero(divisor.type()), divisor - 1); } else { Expr bound = abs(divisor) - 1; return IntervalSet(-bound, bound); } } DLOG(WARNING) << "Return Everything in CombineInterval Mod"; return IntervalSet::Everything(); } template<> inline IntervalSet Combine<ir::FloorDiv>(Analyzer* analyzer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(floordiv(a->min_value, b->min_value)); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; if (b->IsSinglePoint()) { if (is_zero(b->min_value)) { LOG(FATAL) << "Divide by zero in CombineInterval Div"; } if (is_one(b->min_value)) return a; // no relaxation is needed in here due to set is inclusive if (analyzer->CanProveGreaterEqual(b->min_value, 0)) { Expr min_value = a->HasLowerBound() ? floordiv(a->min_value, b->min_value) : neg_inf(); Expr max_value = a->HasUpperBound() ? floordiv(a->max_value, b->min_value) : pos_inf(); return IntervalSet(min_value, max_value); } else if (analyzer->CanProveGreaterEqual(-b->min_value, 1)) { Expr min_value = a->HasUpperBound() ? floordiv(a->max_value, b->min_value) : neg_inf(); Expr max_value = a->HasLowerBound() ? floordiv(a->min_value, b->min_value) : pos_inf(); return IntervalSet(min_value, max_value); } else if (a->HasUpperBound() && a->HasLowerBound()) { using ir::Select; Expr sign = b->min_value >= make_zero(b->min_value.type().element_of()); Expr e1 = floordiv(a->min_value, b->min_value); Expr e2 = floordiv(a->max_value, b->min_value); return IntervalSet(Select::make(sign, e1, e2), Select::make(sign, e2, e1)); } } DLOG(WARNING) << "Return Everything in CombineInterval Div"; return IntervalSet::Everything(); } template<> inline IntervalSet Combine<ir::FloorMod>(Analyzer* analyzer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(floormod(a->min_value, b->min_value)); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; if (b->IsSinglePoint()) { const Expr& divisor = b->min_value; if (is_zero(divisor)) { LOG(FATAL) << "Modular by zero in CombineInterval Mod"; } if (analyzer->CanProveGreaterEqual(divisor, 0)) { return IntervalSet(make_zero(divisor.type()), divisor - 1); } else { Expr bound = abs(divisor) - 1; return IntervalSet(-bound, bound); } } DLOG(WARNING) << "Return Everything in CombineInterval Mod"; return IntervalSet::Everything(); } template<> inline IntervalSet Combine<ir::Max>(Analyzer* analzyer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(max(a->min_value, b->min_value)); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; return IntervalSet(max(a->min_value, b->min_value), max(a->max_value, b->max_value)); } template<> inline IntervalSet Combine<ir::Min>(Analyzer* analzyer, IntervalSet a, IntervalSet b) { if (a->IsSinglePoint() && b->IsSinglePoint()) { return IntervalSet::SinglePoint(min(a->min_value, b->min_value)); } if (a->IsEmpty()) return a; if (b->IsEmpty()) return b; return IntervalSet(min(a->min_value, b->min_value), min(a->max_value, b->max_value)); } // internal helper function to get an interval set IntervalSet ToIntervalSet(IntSet set) { if (auto* node = set.as<IntervalSetNode>()) { return GetRef<IntervalSet>(node); } DLOG(INFO) << "cannot resolve int set " << set; return IntervalSet::Everything(); } using namespace ir; // Simplified version of int set evaluator that operates on IntervalSet // We might use better set analysis in the future to replace the intervalset. class IntervalSetEvaluator : public ExprFunctor<IntervalSet(const Expr&)> { public: IntervalSetEvaluator(Analyzer* analyzer, const Map<Var, IntSet>& dom_map, bool eval_vec = false) : analyzer_(analyzer), dom_map_(dom_map), eval_vec_(eval_vec) { } IntervalSet Eval(const Expr& val) { return this->VisitExpr(val); } // evaluate and relax the set IntervalSet Eval(IntervalSet val) { // avoid recursive indefinite recursive expansion. if (static_cast<size_t>(recur_depth_) >= dom_map_.size()) return val; ++recur_depth_; IntervalSet min_set = this->Eval(val->min_value); IntervalSet max_set = this->Eval(val->max_value); --recur_depth_; return IntervalSet(min_set->min_value, max_set->max_value); } IntervalSet VisitExpr_(const IntImm* op) final { return IntervalSet::SinglePoint(GetRef<Expr>(op)); } IntervalSet VisitExpr_(const UIntImm* op) final { return IntervalSet::SinglePoint(GetRef<Expr>(op)); } IntervalSet VisitExpr_(const Variable* op) final { Var var = GetRef<Var>(op); auto it = dom_map_.find(var); if (it != dom_map_.end()) { IntervalSet res = ToIntervalSet((*it).second); if (res->min_value.same_as(var) && res->max_value.same_as(var)) { return res; } // recursively evaluate mapped result // in case the domain contains variables to be relaxed. return Eval(res); } else { return IntervalSet::SinglePoint(var); } } IntervalSet VisitExpr_(const Add* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Sub* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Mul* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Div* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Mod* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const FloorDiv* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const FloorMod* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Min* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Max* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const EQ* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const NE* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const LT* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const LE* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const GT* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const GE* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const And* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Or* op) final { return VisitBinaryExpr_(op); } IntervalSet VisitExpr_(const Ramp* op) final { CHECK(eval_vec_); IntervalSet base = Eval(op->base); PVar<Integer> stride; if (stride.Match(op->stride)) { Type t = op->base.type(); int64_t vstride = stride.Eval()->value; if (vstride> 0) { return Combine<Add>( analyzer_, base, IntervalSet(make_zero(t), make_const(t, vstride * op->lanes - 1))); } else { return Combine<Add>( analyzer_, base, IntervalSet(make_const(t, vstride * op->lanes + 1), make_zero(t))); } } DLOG(WARNING) << "cannot evaluate set on expression " << GetRef<Expr>(op); return IntervalSet::Everything(); } IntervalSet VisitExpr_(const Broadcast* op) final { CHECK(eval_vec_); return VisitExpr(op->value); } IntervalSet VisitExpr_(const Select* op) final { IntervalSet true_set = this->Eval(op->true_value); IntervalSet false_set = this->Eval(op->false_value); return Union(analyzer_, false_set, true_set); } IntervalSet VisitExprDefault_(const Node* op) final { DLOG(WARNING) << "cannot evaluate set type " << op->type_key(); return IntervalSet::Everything(); } private: // whether set is exactly single point that equals value. bool MatchPoint(const IntervalSet& set, const Expr& value) const { return set->min_value.same_as(value) && set->max_value.same_as(value); } template<typename T> inline IntervalSet VisitBinaryExpr_(const T* op) { IntervalSet a = this->Eval(op->a); IntervalSet b = this->Eval(op->b); if (MatchPoint(a, op->a) && MatchPoint(b, op->b)) { return IntervalSet::SinglePoint(GetRef<Expr>(op)); } return Combine<T>(analyzer_, a, b); } // recursive depth int recur_depth_{0}; // analyzer Analyzer* analyzer_; const Map<Var, IntSet>& dom_map_; bool eval_vec_{false}; }; class IntSetAnalyzer::Impl { public: explicit Impl(Analyzer* analyzer) : analyzer_(analyzer) { } IntSet Eval(const Expr& expr, const Map<Var, IntSet>& dom_map) const { return IntervalSetEvaluator(analyzer_, dom_map).Eval(expr); } private: Analyzer* analyzer_; }; IntSetAnalyzer::IntSetAnalyzer(Analyzer* parent) : impl_(new Impl(parent)) { } IntSetAnalyzer::~IntSetAnalyzer() { delete impl_; } IntSet IntSetAnalyzer::operator()(const Expr& expr, const Map<Var, IntSet>& dom_map) { return impl_->Eval(expr, dom_map); } // Quickly adapt to IntSet interface // TODO(tqchen): revisit IntSet interface as well. Range IntSet::cover_range(Range max_range) const { IntSet temp; const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); CHECK(s_int != nullptr); if (s_int->HasUpperBound() && s_int->HasLowerBound()) { return Range::make_by_min_extent( s_int->min_value, Simplify(s_int->max_value + 1 - s_int->min_value)); } return max_range; } Expr IntSet::min() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); CHECK(s_int); return s_int->min_value; } Expr IntSet::max() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); CHECK(s_int); return s_int->max_value; } bool IntSet::is_nothing() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); return (s_int && s_int->IsEmpty()); } bool IntSet::is_everything() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); return (s_int && s_int->IsEverything()); } bool IntSet::is_single_point() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); return (s_int && s_int->IsSinglePoint()); } bool IntSet::can_prove_positive() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); return (s_int && is_positive_const(ir::Simplify(s_int->min_value))); } bool IntSet::can_prove_negative() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); return (s_int && is_negative_const(ir::Simplify(s_int->max_value))); } bool IntSet::can_prove_non_positive() const { if (const auto* s_int = (*this).as<IntervalSetNode>()) { auto max = ir::Simplify(s_int->max_value); return is_zero(max) || is_negative_const(max); } return false; } bool IntSet::can_prove_non_negative() const { if (const IntervalSetNode* s_int = (*this).as<IntervalSetNode>()) { auto min = ir::Simplify(s_int->min_value); return is_zero(min) || is_positive_const(min); } return false; } SignType IntSet::sign_type() const { if (can_prove_positive()) { return kPositive; } else if (can_prove_negative()) { return kNegative; } else if (is_single_point() && is_zero(point_value())) { return kZero; } else { return kUnknown; } } Expr IntSet::point_value() const { const IntervalSetNode* s_int = (*this).as<IntervalSetNode>(); CHECK(s_int && s_int->IsSinglePoint()); return s_int->min_value; } IntSet IntSet::nothing() { return IntervalSet::Empty(); } IntSet IntSet::everything() { return IntervalSet::Everything(); } IntSet IntSet::single_point(Expr x) { return IntervalSet::SinglePoint(x); } IntSet IntSet::interval(Expr min, Expr max) { if (min.same_as(max)) { return IntSet::single_point(min); } return IntervalSet(min, max); } // Range related code inline bool ProveEqual(Expr lhs, Expr rhs) { return is_zero(ir::Simplify(lhs - rhs)); } IntSet IntSet::range(Range r) { // must make sure it can be matched back by MatchRange. if (is_one(r->extent)) { return IntSet::single_point(r->min); } return IntervalSet(r->min, r->extent + r->min - 1); } bool IntSet::match_range(const Range& b) const { const IntSet& a = *this; const IntervalSetNode* a_int = a.as<IntervalSetNode>(); if (!a_int) return false; return ProveEqual(a_int->min_value, b->min) && ProveEqual(a_int->max_value, b->extent + b->min - 1); } IntSet Union(const Array<IntSet>& sets) { if (sets.size() == 0) return IntSet::nothing(); if (sets.size() == 1) return sets[0]; Analyzer ana; IntervalSet x = ToIntervalSet(sets[0]); for (size_t i = 1; i < sets.size(); ++i) { x = Union(&ana, x, ToIntervalSet(sets[i])); } return IntervalSet(ir::Simplify(x->min_value), ir::Simplify(x->max_value)); } IntSet Intersect(const Array<IntSet>& sets) { if (sets.size() == 0) return IntSet::nothing(); if (sets.size() == 1) return sets[0]; Analyzer ana; IntervalSet x = ToIntervalSet(sets[0]); for (size_t i = 1; i < sets.size(); ++i) { x = Intersect(&ana, x, ToIntervalSet(sets[i])); } return IntervalSet(ir::Simplify(x->min_value), ir::Simplify(x->max_value)); } Map<Var, IntSet> ConvertDomMap(const Map<IterVar, IntSet>& dom_map) { Map<Var, IntSet> dmap; for (auto kv : dom_map) { dmap.Set(kv.first->var, kv.second); } return dmap; } Map<Var, IntSet> ConvertDomMap( const std::unordered_map<const Variable*, IntSet>& dom_map) { Map<Var, IntSet> dmap; for (auto kv : dom_map) { dmap.Set(GetRef<Var>(kv.first), kv.second); } return dmap; } IntSet EvalSet(Expr e, const Map<Var, IntSet>& dom_map) { Analyzer ana; return IntervalSetEvaluator(&ana, dom_map, false).Eval(e); } IntSet IntSet::vector(Expr x) { Analyzer ana; Map<Var, IntSet> dmap; return IntervalSetEvaluator(&ana, dmap, true).Eval(x); } IntSet EvalSet(Expr e, const Map<IterVar, IntSet>& dom_map) { return EvalSet(e, ConvertDomMap(dom_map)); } IntSet EvalSet(Expr e, const std::unordered_map<const Variable*, IntSet>& dom_map) { return EvalSet(e, ConvertDomMap(dom_map)); } IntSet EvalSet(Range r, const Map<Var, IntSet>& dom_map) { Analyzer ana; IntervalSetEvaluator m(&ana, dom_map); // Simplifying first can give tighter bounds if r->min and r->extent share variables Expr sum = r->min + r->extent - 1; auto res = m.Eval(IntervalSet(r->min, Simplify(sum))); return res; } IntSet EvalSet(Range r, const std::unordered_map<const Variable*, IntSet>& dom_map) { return EvalSet(r, ConvertDomMap(dom_map)); } IntSet EvalSet(IntSet s, const std::unordered_map<const Variable*, IntSet>& dom_map) { Analyzer ana; auto dmap = ConvertDomMap(dom_map); IntervalSetEvaluator m(&ana, dmap); const IntervalSetNode* s_int = s.as<IntervalSetNode>(); Expr vmax = s_int->HasUpperBound() ? m.Eval(s_int->max_value).max() : s_int->max_value; Expr vmin = s_int->HasLowerBound() ? m.Eval(s_int->min_value).min() : s_int->min_value; return IntervalSet(vmin, vmax); } class SubExprIntervalSetEvaluator : public IntervalSetEvaluator { public: explicit SubExprIntervalSetEvaluator( Analyzer* analyzer, const Map<Var, IntSet>& dom_map) : IntervalSetEvaluator(analyzer, dom_map) {} IntervalSet VisitExpr(const Expr& n) final { IntervalSet ret = IntervalSetEvaluator::VisitExpr(n); expr_map[n] = ret; return ret; } ExprIntSetMap expr_map; }; ExprIntSetMap EvalSetForEachSubExpr( Expr e, const std::unordered_map<const Variable*, IntSet>& dom_map) { Analyzer ana; auto dmap = ConvertDomMap(dom_map); SubExprIntervalSetEvaluator m(&ana, dmap); m.Eval(e); return m.expr_map; } IntSet EvalSet(Range r, const Map<IterVar, IntSet>& dom_map) { return EvalSet(r, ConvertDomMap(dom_map)); } TVM_STATIC_IR_FUNCTOR(IRPrinter, vtable) .set_dispatch<IntervalSetNode>([](const IntervalSetNode *op, IRPrinter *p) { p->stream << "IntervalSet" << "[" << op->min_value << ", " << op->max_value << ']'; }); } // namespace arith } // namespace tvm <|start_filename|>NVIDIA/benchmarks/dlrm/implementations/pytorch/src/pytorch_ops.cpp<|end_filename|> #include <torch/extension.h> torch::Tensor dotBasedInteractFwdTorch(torch::Tensor input, torch::Tensor bottom_mlp_output, uint pad); std::vector<torch::Tensor> dotBasedInteractBwdTorch(torch::Tensor input, torch::Tensor upstreamGrad, uint pad); torch::Tensor gather_gpu_fwd(torch::Tensor input, torch::Tensor weight); torch::Tensor gather_gpu_bwd(const torch::Tensor grad, const torch::Tensor indices, const int num_features); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("dotBasedInteractFwd", &dotBasedInteractFwdTorch, "", py::arg("input"), py::arg("bottom_mlp_output"), py::arg("pad")); m.def("dotBasedInteractBwd", &dotBasedInteractBwdTorch, "", py::arg("input"), py::arg("upstreamGrad"), py::arg("pad")); m.def("gather_gpu_fwd", &gather_gpu_fwd, "Embedding gather", py::arg("indices"), py::arg("weight")); m.def("gather_gpu_bwd", &gather_gpu_bwd, "Embedding gather backward", py::arg("grad"), py::arg("indices"), py::arg("num_features")); } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/file/directory_watcher.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/directory_watcher.h" #include <utility> #include <vector> #include "base/logging.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/poll_thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "third_party/tensorflow/core/lib/io/path.h" #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/platform/file_system.h" namespace minigo { namespace { bool ParseModelPathPattern(const std::string& pattern, std::string* directory, std::string* basename_pattern) { if (pattern.find("%d/saved_model.pb") != std::string::npos) { *directory = std::string( file::SplitPath(std::string(file::SplitPath(pattern).first)).first); *basename_pattern = "*/saved_model.pb"; } else { auto pair = file::SplitPath(pattern); *directory = std::string(pair.first); if (directory->find('%') != std::string::npos || directory->find('*') != std::string::npos) { MG_LOG(ERROR) << "invalid pattern \"" << pattern << "\": directory part must not contain '*' or '%'"; return false; } if (directory->empty()) { MG_LOG(ERROR) << "directory not be empty"; return false; } *basename_pattern = std::string(pair.second); auto it = basename_pattern->find('%'); if (it == std::string::npos || basename_pattern->find("%d") != it || basename_pattern->rfind("%d") != it) { MG_LOG(ERROR) << "invalid pattern \"" << pattern << "\": basename must contain " << " exactly one \"%d\" and no other matchers"; return false; } } return true; } bool MatchBasename(const std::string& basename, const std::string& pattern, int* generation) { int gen = 0; int n = 0; if (sscanf(basename.c_str(), pattern.c_str(), &gen, &n) != 1 || n != static_cast<int>(basename.size())) { return false; } *generation = gen; return true; } } // namespace DirectoryWatcher::DirectoryWatcher( const std::string& pattern, absl::Duration poll_interval, std::function<void(const std::string&)> callback) : callback_(std::move(callback)) { MG_CHECK(ParseModelPathPattern(pattern, &directory_, &basename_pattern_)); basename_and_length_pattern_ = absl::StrCat(basename_pattern_, "%n"); poll_thread_ = absl::make_unique<PollThread>( "DirWatcher", poll_interval, std::bind(&DirectoryWatcher::Poll, this)); poll_thread_->Start(); } DirectoryWatcher::~DirectoryWatcher() { poll_thread_->Join(); } void DirectoryWatcher::Poll() { const std::string* latest_basename = nullptr; std::string new_latest_path; if (basename_pattern_.find("saved_model.pb") != std::string::npos) { std::vector<std::string> matched_entries; TF_CHECK_OK(tensorflow::Env::Default()->GetMatchingPaths( file::JoinPath(directory_, basename_pattern_), &matched_entries)); // Find the model directory with the largest integer name. std::sort(matched_entries.begin(), matched_entries.end(), std::greater<std::string>()); if (matched_entries.empty()) { return; } new_latest_path = std::string(file::SplitPath(matched_entries[0]).first); } else { // List all the files in the given directory. std::vector<std::string> basenames; if (!file::ListDir(directory_, &basenames)) { return; } // Find the file basename that contains the largest integer. int latest_generation = -1; for (const auto& basename : basenames) { int generation = 0; if (!MatchBasename(basename, basename_and_length_pattern_, &generation)) { continue; } if (latest_basename == nullptr || generation > latest_generation) { latest_basename = &basename; latest_generation = generation; } } if (latest_basename == nullptr) { // Didn't find any matching files. return; } // Build the full path to the latest model. new_latest_path = file::JoinPath(directory_, *latest_basename); } if (new_latest_path == latest_path_) { // The latest path hasn't changed. return; } // Update the latest known path and invoke the callback. latest_path_ = std::move(new_latest_path); callback_(latest_path_); } } // namespace minigo <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/generic_input_op_kernels.cc<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <functional> #include "REDACTEDsubmissions/training/v0_7/models/prod/transformer_lingvo/lingvo/core/ops/input_common.h" #include "third_party/tensorflow/core/common_runtime/function.h" #include "third_party/tensorflow/core/framework/function.h" #include "third_party/tensorflow/core/framework/op_kernel.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/tensor_shape.h" #include "third_party/tensorflow/core/framework/types.h" #include "third_party/tensorflow/core/lib/core/threadpool.h" #include "third_party/tensorflow/core/lib/strings/strcat.h" #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/util/work_sharder.h" namespace tensorflow { namespace babelfish { namespace { typedef std::function<void()> Closure; typedef std::function<void(Closure)> Runner; // ThreadLocalRunner::PerThread() is a thread local object which owns a thread // pool with one thread. That thread is configured to disable as much // TensorFlow runtime parallelism as we can. // // NOTE: Maybe a cpu-local object will work better, and the thread in // ThreadLocalRunner can be affined to one cpu. class ThreadLocalRunner { public: static ThreadLocalRunner& PerThread() { thread_local ThreadLocalRunner tl_runner; return tl_runner; } ThreadLocalRunner() : pool_(Env::Default(), "single", 1) { runner_ = [this](Closure c) { pool_.Schedule(Wrapper(c)); }; } Runner* runner() { return &runner_; } private: thread::ThreadPool pool_; Runner runner_; class Wrapper : Closure { public: explicit Wrapper(Closure c) : c_(std::move(c)) {} void operator()() const { ScopedPerThreadMaxParallelism scope(1); c_(); } private: Closure c_; }; }; class GenericInputProcessor : public RecordProcessor { public: explicit GenericInputProcessor(OpKernelConstruction* ctx) { auto flib = ctx->function_library(); OP_REQUIRES(ctx, flib != nullptr, errors::Internal("No function library")); OP_REQUIRES_OK(ctx, flib->Clone(&fld_, &pflr_, &flib_)); const NameAttrList* func; OP_REQUIRES_OK(ctx, ctx->GetAttr("processor", &func)); OP_REQUIRES_OK(ctx, flib_->Instantiate(func->name(), AttrSlice(&func->attr()), &handle_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("num_threads", &num_merger_threads_)); num_merger_threads_ = std::max(4, num_merger_threads_ / 4); // An estimate. merger_ = new thread::ThreadPool( Env::Default(), ThreadOptions(), "generic_input_merger", num_merger_threads_, /* low_latency_hint */ false); merger_runner_ = [this](Closure c) { merger_->Schedule(c); }; OP_REQUIRES_OK(ctx, ctx->GetAttr("dynamic_padding_dimensions", &dynamic_padding_dimensions_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("dynamic_padding_constants", &dynamic_padding_constants_)); } ~GenericInputProcessor() { delete merger_; } Status Process(const Record& record, int64* bucket_key, TensorVec* sample) override { // We expect that this input processor is used in conjunction with // RecordBatcher, which uses multiple threads to call this input // processor's Process(). Therefore, there is not much need for // processing each individual record using multiple threads // (tf_compute). FunctionLibraryRuntime::Options opts; // Create a step container that uses resource manager to cleanup state // after the step is complete. ScopedStepContainer step_container( step_id_counter_.fetch_add(1), [this](const string& name) { auto status = flib_->device()->resource_manager()->Cleanup(name); if (!status.ok()) { LOG(ERROR) << "Error cleaning up resources:" << status; } }, "GenericInputProcessor"); opts.step_container = &step_container; opts.runner = ThreadLocalRunner::PerThread().runner(); // Generates <source_id, record> pair as the resulting Tensors. TensorVec args(2); args[0] = Tensor(DT_INT32, {}); args[0].scalar<int32>()() = record.source_id; args[1] = Tensor(DT_STRING, {}); args[1].scalar<tensorflow::tstring>()().append(record.value.ToString()); *bucket_key = 1; sample->clear(); Status status; Notification done; flib_->Run(opts, handle_, args, sample, [&](const Status& s) { status = s; done.Notify(); }); done.WaitForNotification(); TF_RETURN_IF_ERROR(status); if (sample->size() < 2) { LOG(FATAL) << "Generic input processor must return at least 2 tensors. but got " << sample->size(); } const auto& bucket_key_tensor = (*sample)[sample->size() - 1]; if (bucket_key_tensor.dtype() != DT_INT32 || !TensorShapeUtils::IsScalar(bucket_key_tensor.shape())) { LOG(FATAL) << "Bucket key tensor is not an int32 scalar: " << DataTypeString(bucket_key_tensor.dtype()); } *bucket_key = bucket_key_tensor.scalar<int32>()(); if (*bucket_key < 0) { return tensorflow::errors::Cancelled( strings::StrCat("Batch has negative bucket key: ", *bucket_key)); } sample->pop_back(); return Status::OK(); } Status Merge(int64 bucket_size, const std::vector<TensorVec>& samples, TensorVec* batch) override { CHECK(!samples.empty()); const auto num_samples = samples.size(); const auto num_outs = samples[0].size(); std::vector<TensorVec> padded_samples(samples.begin(), samples.end()); if (!dynamic_padding_dimensions_.empty()) { CHECK(dynamic_padding_dimensions_.size() == num_outs); CHECK(dynamic_padding_constants_.size() == num_outs); for (int j = 0; j < num_outs; ++j) { const int pad_dim = dynamic_padding_dimensions_[j]; if (pad_dim == -1) { continue; } const int pad_value = dynamic_padding_constants_[j]; int64 max_length = 0; for (int i = 0; i < samples.size(); ++i) { max_length = std::max(max_length, samples[i][j].dim_size(pad_dim)); } for (int i = 0; i < samples.size(); ++i) { const auto& src = samples[i][j]; if (src.dims() > 0 && src.dim_size(pad_dim) < max_length) { DataType dtype = src.dtype(); TensorShape dst_shape(src.shape()); dst_shape.set_dim(pad_dim, max_length); Tensor dst(dtype, dst_shape); switch (dtype) { #define CASE(T) \ case DataTypeToEnum<T>::value: \ dst.flat<T>().setConstant(pad_value); \ if (src.NumElements() > 0) { \ auto src_t = src.flat_inner_outer_dims<T, 2>(pad_dim - 1); \ auto dst_t = dst.flat_inner_outer_dims<T, 2>(pad_dim - 1); \ typedef Eigen::DSizes<Eigen::DenseIndex, 2> DSizes; \ dst_t.slice(DSizes(), DSizes(src_t.dimensions())) = src_t; \ } \ break CASE(float); CASE(int32); CASE(int64); #undef CASE default: LOG(FATAL) << "Unexpected " << DataTypeString(dtype); } std::swap(padded_samples[i][j], dst); } } } } // Validate that samples can be merged: samples[:][i] has the same // type and shape. for (int i = 1; i < padded_samples.size(); ++i) { if (padded_samples[i].size() != num_outs) { LOG(FATAL) << "Samples have different sizes: " << samples[i].size() << " vs. " << num_outs; } for (int j = 0; j < num_outs; ++j) { if (padded_samples[i][j].dtype() != padded_samples[0][j].dtype()) { LOG(FATAL) << "Mismatch data types of samples (" << i << "/" << j << "): " << samples[i][j].dtype() << " vs. " << samples[0][j].dtype(); } if (padded_samples[i][j].shape() != padded_samples[0][j].shape()) { LOG(FATAL) << "Mismatch shape of samples (" << i << "/" << j << "): " << samples[i][j].shape().DebugString() << " vs. " << samples[0][j].shape().DebugString(); } } } batch->clear(); for (int i = 0; i < num_outs; ++i) { DataType dtype = padded_samples[0][i].dtype(); switch (dtype) { case DT_FLOAT: case DT_UINT8: case DT_INT32: case DT_INT64: case DT_STRING: case DT_BFLOAT16: case DT_COMPLEX64: case DT_COMPLEX128: case DT_BOOL: break; default: LOG(FATAL) << DataTypeString(dtype) << " is not supported."; } TensorShape shape = padded_samples[0][i].shape(); shape.InsertDim(0, num_samples); // The merged tensor is 1-rank higher and its 1st dimension // is the num_samples. batch->push_back(Tensor(dtype, shape)); } Sharder::Do( num_samples /* total */, 1000 /* cost_per_unit */, [&](int64 start, int64 limit) { for (int i = 0; i < num_outs; ++i) { DataType dtype = padded_samples[0][i].dtype(); Tensor* merged = &(*batch)[i]; for (int j = start; j < limit; ++j) { switch (dtype) { #define CASE(T) \ case DataTypeToEnum<T>::value: \ merged->flat_outer_dims<T>().chip<0>(j) = padded_samples[j][i].flat<T>(); \ break CASE(float); CASE(int32); CASE(int64); CASE(tstring); CASE(uint8); CASE(bfloat16); CASE(complex64); CASE(complex128); CASE(bool); #undef CASE default: LOG(FATAL) << "Unexpected " << DataTypeString(dtype); } } } }, merger_runner_, 1 + num_merger_threads_); return Status::OK(); } private: std::unique_ptr<FunctionLibraryDefinition> fld_; std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_; FunctionLibraryRuntime* flib_ = nullptr; // Not owned. FunctionLibraryRuntime::Handle handle_; std::atomic_int_fast64_t step_id_counter_; int num_merger_threads_ = -1; thread::ThreadPool* merger_ = nullptr; Runner merger_runner_; std::vector<int32> dynamic_padding_dimensions_; std::vector<int32> dynamic_padding_constants_; TF_DISALLOW_COPY_AND_ASSIGN(GenericInputProcessor); }; REGISTER_KERNEL_BUILDER(Name("GenericInput").Device(DEVICE_CPU), InputOp<GenericInputProcessor>); } // namespace } // namespace babelfish } // namespace tensorflow <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/contrib/roi_align.cu<|end_filename|> /* * 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. */ /*! * Copyright (c) 2018 by Contributors * \file roi_align.cu * \brief roi align operator * \author <NAME>, Shesung * Adapted from Caffe2 */ #include "./roi_align-inl.h" #include "../mxnet_op.h" namespace mxnet { namespace op { using namespace mshadow::cuda; // The maximum number of blocks to use in the default kernel call. constexpr int ROI_MAXIMUM_NUM_BLOCKS = 4096; const int max_threads = 512; /** * @brief Compute the number of blocks needed to run N threads. */ inline int ROI_GET_BLOCKS(const int N) { return std::max( std::min( (N + max_threads - 1) / max_threads, ROI_MAXIMUM_NUM_BLOCKS), // Use at least 1 block, since CUDA does not allow empty block 1); } template <typename T> __device__ T bilinear_interpolate( const T* bottom_data, const int height, const int width, T y, T x, const int index /* index for debug only*/) { // deal with cases that inverse elements are out of feature map boundary if (y < -1.0 || y > height || x < -1.0 || x > width) { // empty return 0; } if (y <= 0) { y = 0; } if (x <= 0) { x = 0; } int y_low = static_cast<int>(y); int x_low = static_cast<int>(x); int y_high; int x_high; if (y_low >= height - 1) { y_high = y_low = height - 1; y = (T)y_low; } else { y_high = y_low + 1; } if (x_low >= width - 1) { x_high = x_low = width - 1; x = (T)x_low; } else { x_high = x_low + 1; } T ly = y - y_low; T lx = x - x_low; T hy = 1. - ly, hx = 1. - lx; // do bilinear interpolation T v1 = bottom_data[y_low * width + x_low]; T v2 = bottom_data[y_low * width + x_high]; T v3 = bottom_data[y_high * width + x_low]; T v4 = bottom_data[y_high * width + x_high]; T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx; T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } template <typename T> __global__ void RoIAlignForwardKernel( const int nthreads, const T* bottom_data, const T spatial_scale, const bool position_sensitive, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int sampling_ratio, const T* bottom_rois, T* top_data) { CUDA_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int c = (index / pooled_width / pooled_height) % channels; int n = index / pooled_width / pooled_height / channels; const T* offset_bottom_rois = bottom_rois + n * 5; int roi_batch_ind = offset_bottom_rois[0]; if (roi_batch_ind < 0) { top_data[index] = 0.; continue; } // Do not using rounding; this implementation detail is critical T roi_start_w = offset_bottom_rois[1] * spatial_scale; T roi_start_h = offset_bottom_rois[2] * spatial_scale; T roi_end_w = offset_bottom_rois[3] * spatial_scale; T roi_end_h = offset_bottom_rois[4] * spatial_scale; // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); // Force malformed ROIs to be 1x1 T roi_width = max(roi_end_w - roi_start_w, (T)1.); T roi_height = max(roi_end_h - roi_start_h, (T)1.); T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height); T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width); int c_unpooled = c; int channels_unpooled = channels; if (position_sensitive) { c_unpooled = c * pooled_height * pooled_width + ph * pooled_width + pw; channels_unpooled = channels * pooled_height * pooled_width; } const T* offset_bottom_data = bottom_data + (roi_batch_ind * channels_unpooled + c_unpooled) * height * width; // We use roi_bin_grid to sample the grid and mimic integral int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); // We do average (integral) pooling inside a bin const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 T output_val = 0.; for (int iy = 0; iy < roi_bin_grid_h; iy++) { // e.g., iy = 0, 1 const T y = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5 for (int ix = 0; ix < roi_bin_grid_w; ix++) { const T x = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w); T val = bilinear_interpolate( offset_bottom_data, height, width, y, x, index); output_val += val; } } output_val /= count; top_data[index] = output_val; } } template <typename T> __device__ void bilinear_interpolate_gradient( const int height, const int width, T y, T x, T* w1, T* w2, T* w3, T* w4, int* x_low, int* x_high, int* y_low, int* y_high, const int /*index*/ /* index for debug only*/) { // deal with cases that inverse elements are out of feature map boundary if (y < -1.0 || y > height || x < -1.0 || x > width) { // empty *w1 = *w2 = *w3 = *w4 = 0.; *x_low = *x_high = *y_low = *y_high = -1; return; } if (y <= 0) { y = 0; } if (x <= 0) { x = 0; } *y_low = static_cast<int>(y); *x_low = static_cast<int>(x); if (*y_low >= height - 1) { *y_high = *y_low = height - 1; y = (T)*y_low; } else { *y_high = *y_low + 1; } if (*x_low >= width - 1) { *x_high = *x_low = width - 1; x = (T)*x_low; } else { *x_high = *x_low + 1; } T ly = y - *y_low; T lx = x - *x_low; T hy = 1. - ly, hx = 1. - lx; *w1 = hy * hx, *w2 = hy * lx, *w3 = ly * hx, *w4 = ly * lx; return; } template <typename T> __global__ void RoIAlignBackwardKernel( const int nthreads, const T* top_diff, const int num_rois, const T spatial_scale, const bool position_sensitive, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int sampling_ratio, T* bottom_diff, const T* bottom_rois) { CUDA_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int c = (index / pooled_width / pooled_height) % channels; int n = index / pooled_width / pooled_height / channels; const T* offset_bottom_rois = bottom_rois + n * 5; int roi_batch_ind = offset_bottom_rois[0]; if (roi_batch_ind < 0) continue; // Do not using rounding; this implementation detail is critical T roi_start_w = offset_bottom_rois[1] * spatial_scale; T roi_start_h = offset_bottom_rois[2] * spatial_scale; T roi_end_w = offset_bottom_rois[3] * spatial_scale; T roi_end_h = offset_bottom_rois[4] * spatial_scale; // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); // Force malformed ROIs to be 1x1 T roi_width = max(roi_end_w - roi_start_w, (T)1.); T roi_height = max(roi_end_h - roi_start_h, (T)1.); T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height); T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width); int c_unpooled = c; int channels_unpooled = channels; if (position_sensitive) { c_unpooled = c * pooled_height * pooled_width + ph * pooled_width + pw; channels_unpooled = channels * pooled_height * pooled_width; } T* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels_unpooled + c_unpooled) * height * width; int top_offset = (n * channels + c) * pooled_height * pooled_width; const T* offset_top_diff = top_diff + top_offset; const T top_diff_this_bin = offset_top_diff[ph * pooled_width + pw]; // We use roi_bin_grid to sample the grid and mimic integral int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); // We do average (integral) pooling inside a bin const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 for (int iy = 0; iy < roi_bin_grid_h; iy++) { // e.g., iy = 0, 1 const T y = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5 for (int ix = 0; ix < roi_bin_grid_w; ix++) { const T x = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w); T w1, w2, w3, w4; int x_low, x_high, y_low, y_high; bilinear_interpolate_gradient( height, width, y, x, &w1, &w2, &w3, &w4, &x_low, &x_high, &y_low, &y_high, index); T g1 = top_diff_this_bin * w1 / count; T g2 = top_diff_this_bin * w2 / count; T g3 = top_diff_this_bin * w3 / count; T g4 = top_diff_this_bin * w4 / count; if (x_low >= 0 && x_high >= 0 && y_low >= 0 && y_high >= 0) { atomicAdd( offset_bottom_diff + y_low * width + x_low, static_cast<T>(g1)); atomicAdd( offset_bottom_diff + y_low * width + x_high, static_cast<T>(g2)); atomicAdd( offset_bottom_diff + y_high * width + x_low, static_cast<T>(g3)); atomicAdd( offset_bottom_diff + y_high * width + x_high, static_cast<T>(g4)); } // if } // ix } // iy } // CUDA_KERNEL_LOOP } // RoIAlignBackward template<typename xpu> void ROIAlignForwardCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& in_data, const std::vector<OpReqType>& req, const std::vector<TBlob>& out_data) { using namespace mshadow; size_t expected_in = 2; size_t expected_out = 1; CHECK_EQ(in_data.size(), expected_in); CHECK_EQ(out_data.size(), expected_out); CHECK_EQ(out_data[roialign::kOut].shape_[0], in_data[roialign::kBox].shape_[0]); const ROIAlignParam param = nnvm::get<ROIAlignParam>(attrs.parsed); const int count = out_data[roialign::kOut].Size(); const int num_rois = in_data[roialign::kBox].size(0); const int channels = out_data[roialign::kOut].size(1); // channels of pooled output const int height = in_data[roialign::kData].size(2); const int width = in_data[roialign::kData].size(3); const int pooled_height = out_data[roialign::kOut].size(2); const int pooled_width = out_data[roialign::kOut].size(3); Stream<gpu> *s = ctx.get_stream<gpu>(); cudaStream_t stream = mshadow::Stream<gpu>::GetStream(s); MSHADOW_REAL_TYPE_SWITCH(in_data[0].type_flag_, DType, { const DType *bottom_data = in_data[roialign::kData].dptr<DType>(); const DType *bottom_rois = in_data[roialign::kBox].dptr<DType>(); DType *top_data = out_data[roialign::kOut].dptr<DType>(); RoIAlignForwardKernel<DType> <<<ROI_GET_BLOCKS(count), max_threads, 0, stream>>>( count, bottom_data, param.spatial_scale, param.position_sensitive, channels, height, width, pooled_height, pooled_width, param.sample_ratio, bottom_rois, top_data); }) } template<typename xpu> void ROIAlignBackwardCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 2); // the order here relates to the order in ROIAlignGrad std::vector<TBlob> out_grad(1, inputs[0]); std::vector<TBlob> in_data(1, inputs[1]); // std::vector<TBlob> out_data(1, inputs[2]); CHECK_EQ(out_grad[0].shape_[0], in_data[0].shape_[0]); CHECK_NE(req[0], kWriteInplace) << "ROIAlign: Backward doesn't support kWriteInplace."; CHECK_NE(req[1], kWriteInplace) << "ROIAlign: Backward doesn't support kWriteInplace."; const ROIAlignParam param = nnvm::get<ROIAlignParam>(attrs.parsed); const int count = out_grad[0].Size(); const int num_rois = in_data[0].size(0); const int channels = out_grad[0].size(1); // channels of pooled output const int height = outputs[0].size(2); const int width = outputs[0].size(3); const int pooled_height = out_grad[0].size(2); const int pooled_width = out_grad[0].size(3); Stream<gpu> *s = ctx.get_stream<gpu>(); cudaStream_t stream = mshadow::Stream<gpu>::GetStream(s); // assume all the data and gradient have the same type MSHADOW_REAL_TYPE_SWITCH(out_grad[0].type_flag_, DType, { const DType *top_diff = out_grad[0].dptr<DType>(); const DType *bottom_rois = in_data[0].dptr<DType>(); DType *grad_in = outputs[0].dptr<DType>(); if (kWriteTo == req[roialign::kBox]) { Fill<false>(s, outputs[1], kWriteTo, static_cast<DType>(0)); } if (kNullOp == req[roialign::kData]) return; if (kWriteTo == req[roialign::kData]) { Fill<false>(s, outputs[0], kWriteTo, static_cast<DType>(0)); } RoIAlignBackwardKernel<DType> <<<ROI_GET_BLOCKS(count), max_threads, 0, stream>>>( count, top_diff, num_rois, param.spatial_scale, param.position_sensitive, channels, height, width, pooled_height, pooled_width, param.sample_ratio, grad_in, bottom_rois); }) } NNVM_REGISTER_OP(_contrib_ROIAlign) .set_attr<FCompute>("FCompute<gpu>", ROIAlignForwardCompute<gpu>); NNVM_REGISTER_OP(_backward_ROIAlign) .set_attr<FCompute>("FCompute<gpu>", ROIAlignBackwardCompute<gpu>); } // namespace op } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/nhwc_pooling.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <assert.h> #include <math.h> #include "c_types_map.hpp" #include "type_helpers.hpp" #include "math_utils.hpp" #include "mkldnn_thread.hpp" #include "nstl.hpp" #include "nhwc_pooling.hpp" namespace mkldnn { namespace impl { namespace cpu { #define MEM_D(name) name##_d #define DECLARE_READ_STRIDES(name) \ const size_t name##_n_stride = MEM_D(name).blocking_desc().strides[0]; \ const size_t name##_d_stride = (!is_3d) \ ? 0 \ : MEM_D(name).blocking_desc().strides[2]; \ const size_t name##_h_stride = (!is_3d) \ ? MEM_D(name).blocking_desc().strides[2] \ : MEM_D(name).blocking_desc().strides[3]; \ const size_t name##_w_stride = (!is_3d) \ ? MEM_D(name).blocking_desc().strides[3] \ : MEM_D(name).blocking_desc().strides[4]; namespace nhwc_pooling { size_t strided_offset(const int _n, const size_t _sn, const int _d, const size_t _sd, const int _h, const size_t _sh, const int _w, const size_t _sw) { return _n * _sn + _d * _sd + _h * _sh + _w * _sw; } } template <data_type_t d_type> void nhwc_pooling_fwd_t<d_type>::array_div_by_const(const int n, const ker_data_t *src, const size_t num, ker_data_t *dst) const { for (int i = 0; i < n; ++i) { float ftmp = (float)src[i]; ftmp = ftmp / num; dst[i] = math::out_round<ker_data_t>(ftmp); } } template <data_type_t d_type> void nhwc_pooling_fwd_t<d_type>::array_add( const int n, const ker_data_t *src, ker_data_t *dst) const { for (int i = 0; i < n; ++i) { dst[i] += src[i]; } } using namespace nstl; using namespace nhwc_pooling; template <data_type_t d_type> void nhwc_pooling_fwd_t<d_type>::execute_forward(const exec_ctx_t &ctx) const { auto alg = pd()->desc()->alg_kind; auto src = CTX_IN_MEM(const data_t *, MKLDNN_ARG_SRC); auto dst = CTX_OUT_MEM(data_t *, MKLDNN_ARG_DST); auto ws = CTX_OUT_MEM(unsigned char *, MKLDNN_ARG_WORKSPACE); const memory_desc_wrapper MEM_D(src)(pd()->src_md()); const memory_desc_wrapper MEM_D(dst)(pd()->dst_md()); const memory_desc_wrapper MEM_D(ws)(pd()->workspace_md()); const int MB = pd()->MB(); const int OD = pd()->OD(); const int OC = pd()->C(); const int OH = pd()->OH(); const int OW = pd()->OW(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int KD = pd()->KD(); const int KH = pd()->KH(); const int KW = pd()->KW(); const int SD = pd()->KSD(); const int SH = pd()->KSH(); const int SW = pd()->KSW(); const int padF = pd()->padFront(); const int padT = pd()->padT(); const int padL = pd()->padL(); const bool is_3d = pd()->desc()->src_desc.ndims == 5; const data_type_t ws_dt = ws ? ws_d.data_type() : data_type::undef; DECLARE_READ_STRIDES(src); DECLARE_READ_STRIDES(dst); auto apply_offset = [=](int index, int offset) { return (index > offset) ? index - offset : 0; }; parallel_nd(MB, OD, OH, OW, [&](int mb, int od, int oh, int ow) { size_t dst_offset_init = strided_offset(mb, dst_n_stride, od, dst_d_stride, oh, dst_h_stride, ow, dst_w_stride); if (alg == alg_kind::pooling_max) { size_t ws_offset_init = 0; if (ws) { DECLARE_READ_STRIDES(ws); ws_offset_init = strided_offset(mb, ws_n_stride, od, ws_d_stride, oh, ws_h_stride, ow, ws_w_stride); } // Note: GCC 4.8.5 won't vectorize below // simple loops unless they are singled out // into separate helper routines: // array_nhwc_initialize, array_nhwc_max if (!ws) array_nhwc_initialize<false>( OC, dst + dst_offset_init, ws, ws_offset_init, ws_dt); else array_nhwc_initialize<true>( OC, dst + dst_offset_init, ws, ws_offset_init, ws_dt); for (int kd = 0; kd < KD; ++kd) for (int kh = 0; kh < KH; ++kh) for (int kw = 0; kw < KW; ++kw) { const int id = od * SD - padF + kd; const int ih = oh * SH - padT + kh; const int iw = ow * SW - padL + kw; if (id < 0 || id >= ID) continue; if (ih < 0 || ih >= IH) continue; if (iw < 0 || iw >= IW) continue; size_t src_offset_init = strided_offset(mb, src_n_stride, id, src_d_stride, ih, src_h_stride, iw, src_w_stride); if (!ws) array_nhwc_max<false>(OC, dst + dst_offset_init, src + src_offset_init, ws, ws_offset_init, ws_dt, kd * KH * KW + kh * KW + kw); else array_nhwc_max<true>(OC, dst + dst_offset_init, src + src_offset_init, ws, ws_offset_init, ws_dt, kd * KH * KW + kh * KW + kw); } } else { // pooling_avg auto d = dst + dst_offset_init; utils::array_set(d, 0, OC); auto id_start = apply_offset(od * SD, padF); auto ih_start = apply_offset(oh * SH, padT); auto iw_start = apply_offset(ow * SW, padL); auto id_end = min(od * SD - padF + KD, ID); auto ih_end = min(oh * SH - padT + KH, IH); auto iw_end = min(ow * SW - padL + KW, IW); // it is cheaper to actually count this in a loop // as the typical kernel is small size_t num_summands = 0; for (int id = id_start; id < id_end; ++id) for (int ih = ih_start; ih < ih_end; ++ih) for (int iw = iw_start; iw < iw_end; ++iw) { size_t src_offset_init = strided_offset(mb, src_n_stride, id, src_d_stride, ih, src_h_stride, iw, src_w_stride); auto s = src + src_offset_init; // need to move the loop to separate function // for GCC 4.8.5 to vectorize array_add(OC, s, d); num_summands++; } num_summands = (alg == alg_kind::pooling_avg_include_padding) ? KW * KH * KD : num_summands; // need to move the loop to separate function // for GCC 4.8.5 to vectorize array_div_by_const(OC, d, num_summands, d); } }); } template <> void nhwc_pooling_fwd_t<data_type::bf16>::execute_forward( const exec_ctx_t &ctx) const { auto alg = pd()->desc()->alg_kind; auto src = CTX_IN_MEM(const data_t *, MKLDNN_ARG_SRC); auto dst = CTX_OUT_MEM(data_t *, MKLDNN_ARG_DST); auto ws = CTX_OUT_MEM(unsigned char *, MKLDNN_ARG_WORKSPACE); auto scratchpad = this->scratchpad(ctx); float *bf16cvt_src_wsp = scratchpad.template get<float>( memory_tracking::names::key_pool_src_bf16cvt); float *bf16cvt_dst_wsp = scratchpad.template get<float>( memory_tracking::names::key_pool_dst_bf16cvt); const memory_desc_wrapper MEM_D(src)(pd()->src_md()); const memory_desc_wrapper MEM_D(dst)(pd()->dst_md()); const memory_desc_wrapper MEM_D(ws)(pd()->workspace_md()); const int MB = pd()->MB(); const int OD = pd()->OD(); const int OC = pd()->C(); const int OH = pd()->OH(); const int OW = pd()->OW(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int KD = pd()->KD(); const int KH = pd()->KH(); const int KW = pd()->KW(); const int SD = pd()->KSD(); const int SH = pd()->KSH(); const int SW = pd()->KSW(); const int padF = pd()->padFront(); const int padT = pd()->padT(); const int padL = pd()->padL(); const bool is_3d = pd()->desc()->src_desc.ndims == 5; const data_type_t ws_dt = ws ? ws_d.data_type() : data_type::undef; DECLARE_READ_STRIDES(src); DECLARE_READ_STRIDES(dst); auto apply_offset = [=](int index, int offset) { return (index > offset) ? index - offset : 0; }; parallel_nd(MB, OD, OH, OW, [&](int mb, int od, int oh, int ow) { size_t dst_offset_init = strided_offset(mb, dst_n_stride, od, dst_d_stride, oh, dst_h_stride, ow, dst_w_stride); if (alg == alg_kind::pooling_max) { size_t ws_offset_init = 0; if (ws) { DECLARE_READ_STRIDES(ws); ws_offset_init = strided_offset(mb, ws_n_stride, od, ws_d_stride, oh, ws_h_stride, ow, ws_w_stride); } size_t ithr = mkldnn_get_thread_num(); float *dst_f32 = &bf16cvt_dst_wsp[ithr * OC]; float *src_f32 = &bf16cvt_src_wsp[ithr * OC]; // Note: GCC 4.8.5 won't vectorize below // simple loops unless they are singled out // into separate helper routines: // array_nhwc_initialize, array_nhwc_max if (!ws) array_nhwc_initialize<false>( OC, dst_f32, ws, ws_offset_init, ws_dt); else array_nhwc_initialize<true>( OC, dst_f32, ws, ws_offset_init, ws_dt); for (int kd = 0; kd < KD; ++kd) for (int kh = 0; kh < KH; ++kh) for (int kw = 0; kw < KW; ++kw) { const int id = od * SD - padF + kd; const int ih = oh * SH - padT + kh; const int iw = ow * SW - padL + kw; if (id < 0 || id >= ID) continue; if (ih < 0 || ih >= IH) continue; if (iw < 0 || iw >= IW) continue; size_t src_offset_init = strided_offset(mb, src_n_stride, id, src_d_stride, ih, src_h_stride, iw, src_w_stride); cvt_bfloat16_to_float(src_f32, &src[src_offset_init], OC); if (!ws) array_nhwc_max<false>(OC, dst_f32, src_f32, ws, ws_offset_init, ws_dt, kd * KH * KW + kh * KW + kw); else array_nhwc_max<true>(OC, dst_f32, src_f32, ws, ws_offset_init, ws_dt, kd * KH * KW + kh * KW + kw); } cvt_float_to_bfloat16(dst + dst_offset_init, dst_f32, OC); } else { // pooling_avg size_t ithr = mkldnn_get_thread_num(); float *dst_f32 = &bf16cvt_dst_wsp[ithr * OC]; float *src_f32 = &bf16cvt_src_wsp[ithr * OC]; utils::array_set(dst_f32, 0, OC); auto id_start = apply_offset(od * SD, padF); auto ih_start = apply_offset(oh * SH, padT); auto iw_start = apply_offset(ow * SW, padL); auto id_end = min(od * SD - padF + KD, ID); auto ih_end = min(oh * SH - padT + KH, IH); auto iw_end = min(ow * SW - padL + KW, IW); // it is cheaper to actually count this in a loop // as the typical kernel is small size_t num_summands = 0; for (int id = id_start; id < id_end; ++id) for (int ih = ih_start; ih < ih_end; ++ih) for (int iw = iw_start; iw < iw_end; ++iw) { size_t src_offset_init = strided_offset(mb, src_n_stride, id, src_d_stride, ih, src_h_stride, iw, src_w_stride); cvt_bfloat16_to_float(src_f32, &src[src_offset_init], OC); // need to move the loop to separate function // for GCC 4.8.5 to vectorize array_add(OC, src_f32, dst_f32); num_summands++; } num_summands = (alg == alg_kind::pooling_avg_include_padding) ? KW * KH * KD : num_summands; // need to move the loop to separate function // for GCC 4.8.5 to vectorize array_div_by_const(OC, dst_f32, num_summands, dst_f32); cvt_float_to_bfloat16(dst + dst_offset_init, dst_f32, OC); } }); } template <data_type_t d_type> void nhwc_pooling_bwd_t<d_type>::execute_backward(const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const data_t *, MKLDNN_ARG_DIFF_DST); auto ws = CTX_IN_MEM(const unsigned char *, MKLDNN_ARG_WORKSPACE); auto diff_src = CTX_OUT_MEM(data_t *, MKLDNN_ARG_DIFF_SRC); const memory_desc_wrapper MEM_D(diff_src)(pd()->diff_src_md()); const memory_desc_wrapper MEM_D(diff_dst)(pd()->diff_dst_md()); const memory_desc_wrapper MEM_D(ws)(pd()->workspace_md()); const int MB = pd()->MB(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int KD = pd()->KD(); const int KH = pd()->KH(); const int KW = pd()->KW(); const int SD = pd()->KSD(); const int SH = pd()->KSH(); const int SW = pd()->KSW(); const int OC = pd()->C(); const int padF = pd()->padFront(); const int padT = pd()->padT(); const int padL = pd()->padL(); const int OD = pd()->OD(); const int OH = pd()->OH(); const int OW = pd()->OW(); const bool is_3d = pd()->desc()->diff_src_desc.ndims == 5; auto alg = pd()->desc()->alg_kind; DECLARE_READ_STRIDES(diff_src); DECLARE_READ_STRIDES(diff_dst); auto apply_offset = [=](int index, int offset) { return (index > offset) ? index - offset : 0; }; parallel_nd(MB, ID, IH, IW, [&](int mb, int id, int ih, int iw) { size_t src_offset_init = strided_offset(mb, diff_src_n_stride, id, diff_src_d_stride, ih, diff_src_h_stride, iw, diff_src_w_stride); for (int oc = 0; oc < OC; ++oc) diff_src[src_offset_init + oc] = data_type_t(0); // Find out which output cells may correspond to current // input position. Current input postition divided by // stride, with integer divide rounding down, is the // right-most output. // Left-most output may be computed if we decrement input // by (kernel_size - 1) and then do the same division by // stride. int od_left = max((id + padF - KD + 1) / SD, 0); int oh_left = max((ih + padT - KH + 1) / SH, 0); int ow_left = max((iw + padL - KW + 1) / SW, 0); // Notice +1 here to preserve the C loop "less than" // condition for continuing the for loop. int od_right = min((id + padF) / SD + 1, OD); int oh_right = min((ih + padT) / SH + 1, OH); int ow_right = min((iw + padL) / SW + 1, OW); for (int od = od_left; od < od_right; ++od) for (int oh = oh_left; oh < oh_right; ++oh) for (int ow = ow_left; ow < ow_right; ++ow) { const int kd = id - od*SD + padF; const int kh = ih - oh*SH + padT; const int kw = iw - ow*SW + padL; if (kd < 0 || kd >= KD) continue; if (kh < 0 || kh >= KH) continue; if (kw < 0 || kw >= KW) continue; size_t dst_offset_init = strided_offset(mb, diff_dst_n_stride, od, diff_dst_d_stride, oh, diff_dst_h_stride, ow, diff_dst_w_stride); if (alg == alg_kind::pooling_max) { DECLARE_READ_STRIDES(ws); size_t ws_offset_init = strided_offset(mb, ws_n_stride, od, ws_d_stride, oh, ws_h_stride, ow, ws_w_stride); const int index = kd * KH * KW + kh * KW + kw; PRAGMA_OMP_SIMD() for (int oc = 0; oc < OC; ++oc) { const int index_from_ws = (MEM_D(ws).data_type() == data_type::u8) ? (int)ws[ws_offset_init + oc] : ((int *)ws)[ws_offset_init + oc]; const data_t d = diff_dst[dst_offset_init + oc]; // Check if kernel windows are disjoint, in this case // there's no update needed and we just write there once // otherwise we add value to the contents. auto value = (index_from_ws == index) ? d : data_type_t(0); if (!(KD == SD && KH == SH && KW == SW)) diff_src[src_offset_init + oc] += value; else diff_src[src_offset_init + oc] = value; } } else { // pooling_avg auto id_start = apply_offset(od * SD, padF); auto ih_start = apply_offset(oh * SH, padT); auto iw_start = apply_offset(ow * SW, padL); auto id_end = min(od * SD - padF + KD, ID); auto ih_end = min(oh * SH - padT + KH, IH); auto iw_end = min(ow * SW - padL + KW, IW); auto num_summands = (alg == alg_kind::pooling_avg_include_padding) ? KW * KH * KD : (ih_end - ih_start) * (iw_end - iw_start) * (id_end - id_start); PRAGMA_OMP_SIMD() for (int oc = 0; oc < OC; ++oc) { const data_t d = diff_dst[dst_offset_init + oc]; // Check if kernel windows are disjoint, in this case // there's no update needed and we just write there once // otherwise we add value to the contents. if (!(KD == SD && KH == SH && KW == SW)) diff_src[src_offset_init + oc] += d / num_summands; else diff_src[src_offset_init + oc] = d / num_summands; } } } }); } template <> void nhwc_pooling_bwd_t<data_type::bf16>::execute_backward( const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const data_t *, MKLDNN_ARG_DIFF_DST); auto ws = CTX_IN_MEM(const unsigned char *, MKLDNN_ARG_WORKSPACE); auto diff_src = CTX_OUT_MEM(data_t *, MKLDNN_ARG_DIFF_SRC); auto scratchpad = this->scratchpad(ctx); float *bf16cvt_dsrc = scratchpad.template get<float>( memory_tracking::names::key_pool_src_bf16cvt); float *bf16cvt_ddst = scratchpad.template get<float>( memory_tracking::names::key_pool_dst_bf16cvt); const memory_desc_wrapper MEM_D(diff_src)(pd()->diff_src_md()); const memory_desc_wrapper MEM_D(diff_dst)(pd()->diff_dst_md()); const memory_desc_wrapper MEM_D(ws)(pd()->workspace_md()); const int MB = pd()->MB(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int KD = pd()->KD(); const int KH = pd()->KH(); const int KW = pd()->KW(); const int SD = pd()->KSD(); const int SH = pd()->KSH(); const int SW = pd()->KSW(); const int OC = pd()->C(); const int padF = pd()->padFront(); const int padT = pd()->padT(); const int padL = pd()->padL(); const int OD = pd()->OD(); const int OH = pd()->OH(); const int OW = pd()->OW(); const bool is_3d = pd()->desc()->diff_src_desc.ndims == 5; auto alg = pd()->desc()->alg_kind; DECLARE_READ_STRIDES(diff_src); DECLARE_READ_STRIDES(diff_dst); auto apply_offset = [=](int index, int offset) { return (index > offset) ? index - offset : 0; }; parallel_nd(MB, ID, IH, IW, [&](int mb, int id, int ih, int iw) { size_t src_offset_init = strided_offset(mb, diff_src_n_stride, id, diff_src_d_stride, ih, diff_src_h_stride, iw, diff_src_w_stride); float *diff_dst_fp32 = &bf16cvt_ddst[mkldnn_get_thread_num() * OC]; float *diff_src_fp32 = &bf16cvt_dsrc[mkldnn_get_thread_num() * OC]; for (int oc = 0; oc < OC; ++oc) { diff_src_fp32[oc] = 0.f; diff_src[src_offset_init + oc] = (bfloat16_t)0.f; } // Find out which output cells may correspond to current // input position. Current input postition divided by // stride, with integer divide rounding down, is the // right-most output. // Left-most output may be computed if we decrement input // by (kernel_size - 1) and then do the same division by // stride. int od_left = max((id + padF - KD + 1) / SD, 0); int oh_left = max((ih + padT - KH + 1) / SH, 0); int ow_left = max((iw + padL - KW + 1) / SW, 0); // Notice +1 here to preserve the C loop "less than" // condition for continuing the for loop. int od_right = min((id + padF) / SD + 1, OD); int oh_right = min((ih + padT) / SH + 1, OH); int ow_right = min((iw + padL) / SW + 1, OW); for (int od = od_left; od < od_right; ++od) for (int oh = oh_left; oh < oh_right; ++oh) for (int ow = ow_left; ow < ow_right; ++ow) { const int kd = id - od * SD + padF; const int kh = ih - oh * SH + padT; const int kw = iw - ow * SW + padL; if (kd < 0 || kd >= KD) continue; if (kh < 0 || kh >= KH) continue; if (kw < 0 || kw >= KW) continue; size_t dst_offset_init = strided_offset(mb, diff_dst_n_stride, od, diff_dst_d_stride, oh, diff_dst_h_stride, ow, diff_dst_w_stride); cvt_bfloat16_to_float(diff_dst_fp32, &diff_dst[dst_offset_init], OC); if (alg == alg_kind::pooling_max) { DECLARE_READ_STRIDES(ws); size_t ws_offset_init = strided_offset(mb, ws_n_stride, od, ws_d_stride, oh, ws_h_stride, ow, ws_w_stride); const int index = kd * KH * KW + kh * KW + kw; PRAGMA_OMP_SIMD() for (int oc = 0; oc < OC; ++oc) { const int index_from_ws = (MEM_D(ws).data_type() == data_type::u8) ? (int)ws[ws_offset_init + oc] : ((int *)ws)[ws_offset_init + oc]; // Check if kernel windows are disjoint, in this case // there's no update needed and we just write there once // otherwise we add value to the contents. float value = (index_from_ws == index) ? diff_dst_fp32[oc] : 0.0f; if (!(KD == SD && KH == SH && KW == SW)) diff_src_fp32[oc] += value; else diff_src_fp32[oc] = value; } } else { // pooling_avg auto id_start = apply_offset(od * SD, padF); auto ih_start = apply_offset(oh * SH, padT); auto iw_start = apply_offset(ow * SW, padL); auto id_end = min(od * SD - padF + KD, ID); auto ih_end = min(oh * SH - padT + KH, IH); auto iw_end = min(ow * SW - padL + KW, IW); auto num_summands = (alg == alg_kind::pooling_avg_include_padding) ? KW * KH * KD : (ih_end - ih_start) * (iw_end - iw_start) * (id_end - id_start); PRAGMA_OMP_SIMD() for (int oc = 0; oc < OC; ++oc) { // Check if kernel windows are disjoint, in this case // there's no update needed and we just write there once // otherwise we add value to the contents. if (!(KD == SD && KH == SH && KW == SW)) diff_src_fp32[oc] += diff_dst_fp32[oc] / num_summands; else diff_src_fp32[oc] = diff_dst_fp32[oc] / num_summands; } } cvt_float_to_bfloat16(&diff_src[src_offset_init], diff_src_fp32, OC); } }); } template struct nhwc_pooling_fwd_t<data_type::f32>; template struct nhwc_pooling_bwd_t<data_type::f32>; template struct nhwc_pooling_fwd_t<data_type::bf16>; template struct nhwc_pooling_bwd_t<data_type::bf16>; } } } // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/bf16/jit_avx512_core_s16_copy_bt_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_s16.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx512_core_s16_copy_bt_kern::jit_avx512_core_s16_copy_bt_kern() : jit_generator(nullptr, S16_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rax #define B rdi #define I rax #define A1 rsi #define A2 r10 #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l13c; Xbyak::Label l170; Xbyak::Label l18c; Xbyak::Label l19c; Xbyak::Label l1a8; Xbyak::Label l1b8; Xbyak::Label l234; Xbyak::Label l24; Xbyak::Label l27c; Xbyak::Label l2a8; Xbyak::Label l2c4; Xbyak::Label l2d4; Xbyak::Label l2e0; Xbyak::Label l2f0; Xbyak::Label l368; Xbyak::Label l38; Xbyak::Label l3ac; Xbyak::Label l3d8; Xbyak::Label l3f4; Xbyak::Label l402; Xbyak::Label l40c; Xbyak::Label l41c; Xbyak::Label l494; Xbyak::Label l4dc; Xbyak::Label l50c; Xbyak::Label l524; Xbyak::Label l534; Xbyak::Label le0; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); shl(LDA, 1); lea(LDA3, ptr[LDA+LDA*2]); sub(A, -128); sub(B, -128); cmp(N, 0x8); jl(l19c, T_NEAR); align(4); L(l24); mov(A1, A); add(A, 0x10); mov(I, M); sar(I, 0x3); jle(le0, T_NEAR); align(4); L(l38); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x40], ymm0); vmovdqu(yword[B-0x20], ymm2); sub(B, -128); dec(I); jg(l38, T_NEAR); align(4); L(le0); test(M, 0x4); jle(l13c, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm2); sub(B, -64); align(4); L(l13c); test(M, 0x2); jle(l170, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm0, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm0); sub(B, -32); align(4); L(l170); test(M, 0x1); jle(l18c, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l18c); sub(N, 0x8); cmp(N, 0x8); jge(l24, T_NEAR); align(4); L(l19c); cmp(N, 0x4); jl(l2d4, T_NEAR); align(4); L(l1a8); mov(A1, A); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(l234, T_NEAR); align(4); L(l1b8); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vperm2f128(ymm0, ymm0, ymm2, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vperm2f128(ymm0, ymm0, ymm2, 0x20); vmovdqu(yword[B-0x60], ymm0); sub(B, -64); dec(I); jg(l1b8, T_NEAR); align(4); L(l234); test(M, 0x4); jle(l27c, T_NEAR); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vmovdqu(xword[B-0x80], xmm0); vmovdqu(xword[B-0x70], xmm2); sub(B, -32); align(4); L(l27c); test(M, 0x2); jle(l2a8, T_NEAR); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l2a8); test(M, 0x1); jle(l2c4, T_NEAR); vmovq(xmm0, qword[A1-0x80]); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l2c4); sub(N, 0x4); cmp(N, 0x4); jge(l1a8, T_NEAR); align(4); L(l2d4); cmp(N, 0x2); jl(l402, T_NEAR); align(4); L(l2e0); mov(A1, A); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l368, T_NEAR); align(4); L(l2f0); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x70], xmm0); sub(B, -32); dec(I); jg(l2f0, T_NEAR); align(4); L(l368); test(M, 0x4); jle(l3ac, T_NEAR); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l3ac); test(M, 0x2); jle(l3d8, T_NEAR); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l3d8); test(M, 0x1); jle(l3f4, T_NEAR); vmovd(xmm0, dword[A1-0x80]); vmovd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l3f4); sub(N, 0x2); cmp(N, 0x2); jge(l2e0, T_NEAR); align(4); L(l402); cmp(N, 0x1); jl(l534, T_NEAR); align(4); L(l40c); mov(A1, A); add(A, 0x2); mov(LDA3, M); sar(LDA3, 0x3); jle(l494, T_NEAR); align(4); L(l41c); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x7); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); dec(LDA3); jg(l41c, T_NEAR); align(4); L(l494); test(M, 0x4); jle(l4dc, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x3); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l4dc); test(M, 0x2); jle(l50c, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); vmovd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l50c); test(M, 0x1); jle(l524, T_NEAR); mov(ax, word[A1-0x80]); mov(word[B-0x80], ax); sub(B, -2); align(4); L(l524); sub(N, 0x1); cmp(N, 0x1); jge(l40c, T_NEAR); align(4); L(l534); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/linalg.h<|end_filename|> /* * 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 linalg.h * \brief Unified tensor interface for advanced linear algebra functions * (specifically BLAS3/LAPACK) from within mxnet. */ #ifndef MXNET_OPERATOR_LINALG_H_ #define MXNET_OPERATOR_LINALG_H_ #include <mshadow/tensor.h> #include <mxnet/op_attr_types.h> #include "./c_lapack_api.h" using namespace mshadow; // The purpose of this header is to expose the interfaces of the advanced // linear algebra functions without clutter by the implementations. In contrast // to the implementations in linalg_inline.h, no macros are used to generate // similar functions that just differ by name/type in order to improve readability. // // Guidelines for extensions: // For any type of computation the following should be provided at minimum: // - 1 templated function supporting cpu/gpu float/double in non-batch mode // - 1 templated function supporting cpu/gpu float/double in batch mode // Naming conventions: // - linalg_<func>() // - linalg_batch_<func>() // Signatures of CPU/GPU versions should be equivalent whenever possible including // that a stream is supplied to the cpu-versions as (optional) last argument. // The batched versions all work on tensors with one more dimension as the // non-batched ones and the first/highest dimension iterates over the elements // within the batch. //////////////////////////////// GEMM //////////////////////////////////////////// // CPU/GPU-versions of BLAS3 function "gemm". Please refer to the BLAS3-documentation // for further information about the function and its parameters. // Note that this is C = gemm(A,B,C), so C is input and output parameter. // C = alpha * A * B + beta * C template<typename xpu, typename DType> void linalg_gemm(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 2, DType>& B, const Tensor<xpu, 2, DType>& C, DType alpha, DType beta, bool tA, bool tB, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_batch_gemm(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& B, const Tensor<xpu, 3, DType>& C, DType alpha, DType beta, bool tA, bool tB, Stream<xpu> *s = 0); // Version of batch gemmm where rows are indexed at axis 1 and columns at axis 3. template<typename xpu, typename DType> void linalg_batch_gemm(const Tensor<xpu, 4, DType>& A, const Tensor<xpu, 4, DType>& B, const Tensor<xpu, 4, DType>& C, DType alpha, DType beta, bool tA, bool tB, Stream<xpu> *s = 0); // Signatures with an added 'req' arg. template<typename xpu, typename DType> inline void linalg_gemm(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 2, DType>& B, const Tensor<xpu, 2, DType>& C, bool tA, bool tB, Stream<xpu> *s = 0, mxnet::OpReqType req = mxnet::kWriteTo); template<typename xpu, typename DType> inline void linalg_batch_gemm(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& B, const Tensor<xpu, 3, DType>& C, bool tA, bool tB, Stream<xpu> *s = 0, mxnet::OpReqType req = mxnet::kWriteTo); //////////////////////////////// TRSM //////////////////////////////////////////// // CPU/GPU-versions of BLAS3 function "trsm". Please refer to the BLAS3-documentation // for further information about the function and its parameters. // Note that this is B = trsm(A,B), so B is input and output parameter. template<typename xpu, typename DType> void linalg_trsm(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 2, DType>& B, DType alpha, bool rightside, bool lower, bool transpose, Stream<xpu> *s = 0); template<typename xpu, typename DType> inline void linalg_batch_trsm(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& B, DType alpha, bool rightside, bool lower, bool transpose, Stream<xpu> *s = 0); //////////////////////////////// TRMM //////////////////////////////////////////// // CPU/GPU-versions of BLAS3 function "trmm". Please refer to the BLAS3-documentation // for further information about the function and its parameters. // Note that this is B = trmm(A,B), so B is input and output parameter. template<typename xpu, typename DType> void linalg_trmm(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 2, DType>& B, DType alpha, bool rightside, bool lower, bool transpose, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_batch_trmm(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& B, DType alpha, bool rightside, bool lower, bool transpose, Stream<xpu> *s = 0); //////////////////////////////// POTRF //////////////////////////////////////////// // CPU/GPU-versions of LAPACK function "potrf". Please refer to the LAPACK-documentation // for further information about the function and its parameters. // Note that this is A = potrf(A), so A is input and output parameter. template<typename xpu, typename DType> void linalg_potrf(const Tensor<xpu, 2, DType>& A, bool lower, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_batch_potrf(const Tensor<xpu, 3, DType>& A, bool lower, Stream<xpu> *s = 0); //////////////////////////////// POTRI //////////////////////////////////////////// // CPU/GPU-versions of LAPACK function "potri". Please refer to the LAPACK-documentation // for further information about the function and its parameters. // Note that this is A = potri(A), so A is input and output parameter. template<typename xpu, typename DType> void linalg_potri(const Tensor<xpu, 2, DType>& A, bool lower, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_batch_potri(const Tensor<xpu, 3, DType>& A, bool lower, Stream<xpu> *s = 0); //////////////////////////////// SYRK //////////////////////////////////////////// // CPU/GPU-versions of BLAS3 function "syrk". Please refer to the BLAS3-documentation // for further information about the function and its parameters. // Note that this is B = syrk(A, B), so that B is input and output parameter. template<typename xpu, typename DType> void linalg_syrk(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 2, DType>& B, DType alpha, DType beta, bool tA, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_batch_syrk(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& B, DType alpha, DType beta, bool tA, Stream<xpu> *s = 0); //////////////////////////////// GELQF //////////////////////////////////////////// // CPU/GPU-versions of LAPACK functions "gelqf", "orglq". Please refer to the // LAPACK documentation for further details. // Note: // - Both functions have A as input and output parameter // - Both functions require extra workspace, passed as 1D tensor // - We call orglq after gelqf. Apart from A, they also communicate via the // first part of the workspace. template<typename xpu, typename DType> void linalg_gelqf(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 1, DType>& work, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_orglq(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 1, DType>& work, Stream<xpu> *s = 0); // This function determines the amount of workspace needed for linalg_gelqf, // linalg_orglq. The workspace can be used for both. The first m entries are // used to communicate information from gelqf to orglq. template<typename xpu, typename DType> int linalg_gelqf_workspace_query(const Tensor<xpu, 2, DType>& A, Stream<xpu> *s = 0); //////////////////////////////// SYEVD //////////////////////////////////////////// // CPU/GPU-versions of LAPACK function "syevd". Please refer to the // LAPACK documentation for further details. // Note: // - A is input and output parameter (overwritten by U) // - Input A is symmetric, we access the lower triangle only template<typename xpu, typename DType> void linalg_syevd(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 1, DType>& L, const Tensor<xpu, 1, DType>& work, Stream<xpu> *s = 0); // This function determines the amount of workspace needed for linalg_syevd // which is returned as number of elements of type DType. template<typename xpu, typename DType> int linalg_syevd_workspace_query(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 1, DType>& L, Stream<xpu> *s = 0); //////////////////////////////// GESVD //////////////////////////////////////////// // CPU/GPU-versions of LAPACK function "gesvd". Please refer to the // LAPACK documentation for further details. // Note: V is input and output parameter (it overwrites A) template<typename xpu, typename DType> void linalg_gesvd(const Tensor<xpu, 2, DType>& UT, const Tensor<xpu, 1, DType>& L, const Tensor<xpu, 2, DType>& V, const Tensor<xpu, 1, DType>& work, Stream<xpu>* s = 0); // This function determines the amount of workspace needed for linalg_gesvd // which is returned as number of elements of type DType. template<typename xpu, typename DType> int linalg_gesvd_workspace_query(const Tensor<xpu, 2, DType>& UT, const Tensor<xpu, 1, DType>& L, const Tensor<xpu, 2, DType>& V, Stream<xpu>* s = 0); //////////////////////////////// GETRF //////////////////////////////////////////// // CPU/GPU-versions of LAPACK function "getrf". Please refer to the // LAPACK documentation for further details. // Note: // - A is input and output parameter (overwritten by LU) // - Param check_singular is only useful in cpu version. If check_singular is false, // don't throw error when A is non-invertible matrix. template<typename xpu, typename DType> void linalg_getrf(const Tensor<xpu, 2, DType>& A, const Tensor<xpu, 1, int>& pivot, bool check_singular, Stream<xpu> *s = 0); template<typename xpu, typename DType> void linalg_batch_getrf(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 2, int>& pivot, bool check_singular, Stream<xpu> *s = 0); //////////////////////////////// GETRI //////////////////////////////////////////// // CPU/GPU-versions of LAPACK function "getri". Please refer to the // LAPACK documentation for further details. // Note: // - pivot and LU is the output of getrf(A) // - LU is also the output parameter (overwritten by inverse(A)) template<typename xpu, typename DType> void linalg_getri(const Tensor<xpu, 2, DType>& LU, const Tensor<xpu, 1, int>& pivot, \ const Tensor<xpu, 1, DType>& work, Stream<xpu> *s = 0); // Note that this function only implements GPU version with "getriBatched" in cuBLAS. // Unlike lapack routines in cpu, it is computed out-of-place, so the final matrix // inverse is stored in A. template<typename xpu, typename DType> void linalg_batch_getri(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& LU, const Tensor<xpu, 2, int>& pivot, Stream<xpu> *s = 0); //////////////////////////////// INVERSE //////////////////////////////////////////// // CPU/GPU-versions of matrix inverse combining LAPACK function "getrf" and "getri" // Note that A = inverse(B) template<typename xpu, typename DType> void linalg_batch_inverse(const Tensor<xpu, 3, DType>& A, const Tensor<xpu, 3, DType>& B, const mxnet::OpContext& ctx); //////////////////////////////// DET //////////////////////////////////////////// // CPU/GPU-versions of helper functions used in matrix determinant operators // Helper function in determinant backward computation: compute matrix inverse // from LU and pivot using temp workspace, the result is stored back to LU template<typename xpu, typename DType> void linalg_batch_det_backward_helper(const Tensor<xpu, 3, DType>& LU, const Tensor<xpu, 2, int>& pivot, const Tensor<xpu, 1, DType>& det, const Tensor<xpu, 3, DType>& temp, const DType zero_det, const mxnet::OpContext& ctx); #include "linalg_impl.h" #endif // MXNET_OPERATOR_LINALG_H_ <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/assert_kernels.cc<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "third_party/tensorflow/core/framework/op_kernel.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/tensor_shape.h" namespace tensorflow { namespace babelfish { namespace { static const int kUnknown = -1; class AssertShapeMatchOp : public OpKernel { public: explicit AssertShapeMatchOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("msg", &msg_)); } ~AssertShapeMatchOp() override {} void Compute(OpKernelContext* ctx) override { const Tensor& x = ctx->input(0); const Tensor& y = ctx->input(1); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(x.shape()), errors::InvalidArgument("x must be a vector.")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(y.shape()), errors::InvalidArgument("y must be a vector.")); bool match = true; if (x.NumElements() != y.NumElements()) { match = false; } else { auto Tx = x.flat<int32>(); auto Ty = y.flat<int32>(); for (int i = 0; i < x.NumElements(); ++i) { if ((Tx(i) != kUnknown) && (Ty(i) != kUnknown) && (Tx(i) != Ty(i))) { match = false; } } } OP_REQUIRES(ctx, match, errors::InvalidArgument(msg_, " mismatch shape: x=[", x.SummarizeValue(10), "] y=[", y.SummarizeValue(10), "]")); } private: string msg_; }; REGISTER_KERNEL_BUILDER(Name("AssertShapeMatch").Device(DEVICE_CPU), AssertShapeMatchOp); #if GOOGLE_CUDA REGISTER_KERNEL_BUILDER( Name("AssertShapeMatch").Device(DEVICE_GPU).HostMemory("x").HostMemory("y"), AssertShapeMatchOp); #endif class AssertSameDim0Op : public OpKernel { public: explicit AssertSameDim0Op(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("msg", &msg_)); } ~AssertSameDim0Op() override {} void Compute(OpKernelContext* ctx) override { if (ctx->num_inputs() == 0) { // A no-op for empty list of inputs. return; } const auto& x = ctx->input(0); OP_REQUIRES(ctx, !TensorShapeUtils::IsScalar(x.shape()), errors::InvalidArgument(msg_, " 0-th input is a scalar.")); const auto dim0 = x.dim_size(0); for (int i = 1; i < ctx->num_inputs(); ++i) { const auto& y = ctx->input(i); OP_REQUIRES( ctx, !TensorShapeUtils::IsScalar(y.shape()), errors::InvalidArgument(msg_, " ", i, "-th input is a scalar.")); OP_REQUIRES(ctx, dim0 == y.dim_size(0), errors::InvalidArgument( msg_, " ", i, "-th input has a different dim0: ", dim0, " ", y.dim_size(0))); } } private: string msg_; }; REGISTER_KERNEL_BUILDER(Name("AssertSameDim0").Device(DEVICE_CPU), AssertSameDim0Op); #if GOOGLE_CUDA REGISTER_KERNEL_BUILDER(Name("AssertSameDim0").Device(DEVICE_GPU), AssertSameDim0Op); #endif } // namespace } // namespace babelfish } // namespace tensorflow <|start_filename|>NVIDIA/benchmarks/ssd/implementations/pytorch/csrc/nhwc/batch_norm.cu<|end_filename|> /****************************************************************************** * * Copyright (c) 2018, NVIDIA CORPORATION. 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 <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <ATen/cudnn/Handle.h> #include <THC/THCNumerics.cuh> #include <torch/torch.h> #include <torch/extension.h> #include "THC/THC.h" #include "Descriptors.h" #include <cuda.h> inline size_t round_up_to_multiple(size_t x, int multiple) { return ((x + multiple - 1) / multiple) * multiple; } const float BN_MIN_EPSILON = 1e-4; // TODO: Stop manually allocating CUDA memory; allocate an ATen byte // tensor instead. struct Workspace { Workspace(size_t size) : size(size), data(NULL) { data = THCudaMalloc(at::globalContext().lazyInitCUDA(), size); } Workspace(const Workspace&) = delete; Workspace(Workspace&&) = default; Workspace& operator=(Workspace&&) = default; ~Workspace() { if (data) { THCudaFree(at::globalContext().lazyInitCUDA(), data); } } size_t size; void* data; }; // Return {y. save_mean, save_var, reserve} std::vector<at::Tensor> nhwc_bn_fwd_train_cudnn_impl( const at::Tensor& x_t, const at::Tensor& z_t, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const float momentum, const float epsilon, const bool fuse_relu, const bool fuse_add) { // We assume later that both x and z are contiguous at::Tensor x = x_t.contiguous(); const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // Allocate output tensor at::Tensor z, y = at::empty_like(x); // ({N, H, W, C}, x.options()); // Setup tensor descriptors at::native::nhwc::TensorDescriptor x_desc, y_desc, z_desc, bn_desc; x_desc.set(x); y_desc.set(y); if (fuse_add) { z = z_t.contiguous(); z_desc.set(z); } auto bn_mode = CUDNN_BATCHNORM_SPATIAL_PERSISTENT; auto bn_op = fuse_relu ? ((fuse_add) ? CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION : CUDNN_BATCHNORM_OPS_BN_ACTIVATION) : CUDNN_BATCHNORM_OPS_BN; // get derived tensor descriptor cudnnDeriveBNTensorDescriptor(bn_desc.mut_desc(), x_desc.desc(), bn_mode); // create activation descriptor cudnnActivationDescriptor_t activ_desc; cudnnCreateActivationDescriptor(&activ_desc); cudnnSetActivationDescriptor(activ_desc, CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); // get the workspace size and allocate size_t ws_num_bytes; AT_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( at::native::getCudnnHandle(), bn_mode, bn_op, x_desc.desc(), x_desc.desc(), y_desc.desc(), bn_desc.desc(), (fuse_relu) ? activ_desc : nullptr, &ws_num_bytes)); Workspace ws(ws_num_bytes); // get the reserved size and allocate as tensor size_t reserve_num_bytes; AT_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( at::native::getCudnnHandle(), bn_mode, bn_op, (fuse_relu) ? activ_desc : nullptr, x_desc.desc(), &reserve_num_bytes)); at::Tensor reserve = torch::empty({static_cast<long>(reserve_num_bytes)}, torch::CUDA(at::kByte)); // call cuDNN float one = 1.f, zero = 0.f; auto eps = std::max(epsilon, BN_MIN_EPSILON); at::Tensor save_mean = torch::empty({C}, scale.options()); at::Tensor save_var = torch::empty({C}, scale.options()); AT_CUDNN_CHECK(cudnnBatchNormalizationForwardTrainingEx( at::native::getCudnnHandle(), bn_mode, bn_op, &one, &zero, x_desc.desc(), x.data_ptr<at::Half>(), fuse_add ? z_desc.desc() : nullptr, // z descriptor for BN-Add-Relu fuse_add ? z.data_ptr<at::Half>() : nullptr, // z for BN-Add-ReLU y_desc.desc(), y.data_ptr<at::Half>(), bn_desc.desc(), scale.data_ptr<float>(), bias.data_ptr<float>(), momentum, running_mean.data_ptr<float>(), running_inv_var.data_ptr<float>(), eps, save_mean.data_ptr<float>(), save_var.data_ptr<float>(), (fuse_relu) ? activ_desc : nullptr, ws.data, ws_num_bytes, reserve.data_ptr<uint8_t>(), // reserve space ptr reserve.numel())); // reserve space bytes return {y, save_mean, save_var, reserve}; } // Return {y. save_mean, save_var, reserve} std::vector<at::Tensor> nhwc_bn_fwd_train_cudnn( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const float momentum, const float epsilon, const bool fuse_relu) { return nhwc_bn_fwd_train_cudnn_impl( x, at::Tensor(), scale, bias, running_mean, running_inv_var, momentum, epsilon, fuse_relu, false /* fuse add */); } std::vector<at::Tensor> nhwc_bn_add_fwd_train_cudnn( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const float momentum, const float epsilon, const bool fuse_relu) { return nhwc_bn_fwd_train_cudnn_impl( x, z, scale, bias, running_mean, running_inv_var, momentum, epsilon, fuse_relu, true /* fuse add */); } at::Tensor nhwc_bn_fwd_eval_cudnn_impl( const at::Tensor& x_t, const at::Tensor& z_t, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const float momentum, const float epsilon, const bool fuse_relu, const bool fuse_add) { // We assume later that both x and z are contiguous at::Tensor x = x_t.contiguous(); const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // Allocate output tensor at::Tensor z, y = torch::empty({N, H, W, C}, x.options()); // this does BN and optional fused Relu // Setup tensor descriptors at::native::nhwc::TensorDescriptor x_desc, y_desc, z_desc, bn_desc; x_desc.set(x); y_desc.set(y); if (fuse_add) { z = z_t.contiguous(); z_desc.set(z); } auto bn_mode = CUDNN_BATCHNORM_SPATIAL_PERSISTENT; // get derived tensor descriptor AT_CUDNN_CHECK(cudnnDeriveBNTensorDescriptor(bn_desc.mut_desc(), x_desc.desc(), bn_mode)); // call cuDNN float one = 1.f, zero = 0.f; auto eps = std::max(epsilon, BN_MIN_EPSILON); AT_CUDNN_CHECK(cudnnBatchNormalizationForwardInference( at::native::getCudnnHandle(), CUDNN_BATCHNORM_SPATIAL, &one, &zero, x_desc.desc(), x.data_ptr<at::Half>(), y_desc.desc(), y.data_ptr<at::Half>(), bn_desc.desc(), scale.data_ptr<float>(), bias.data_ptr<float>(), running_mean.data_ptr<float>(), running_inv_var.data_ptr<float>(), eps)); if (fuse_add) { y += z; } if (fuse_relu) { y = y.relu_(); } return y; } at::Tensor nhwc_bn_fwd_eval_cudnn( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const float momentum, const float epsilon, const bool fuse_relu) { return nhwc_bn_fwd_eval_cudnn_impl( x, at::Tensor(), scale, bias, running_mean, running_inv_var, momentum, epsilon, fuse_relu, false); } at::Tensor nhwc_bn_add_fwd_eval_cudnn( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const float momentum, const float epsilon, const bool fuse_relu) { return nhwc_bn_fwd_eval_cudnn_impl( x, z, scale, bias, running_mean, running_inv_var, momentum, epsilon, fuse_relu, true); } std::vector<at::Tensor> nhwc_bn_bwd_cudnn_impl( const at::Tensor& x_t, const at::Tensor& y_t, const at::Tensor& dy_t, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& save_mean, const at::Tensor& save_var, const at::Tensor& reserve, const float momentum, const float epsilon, const bool fuse_relu, const bool fuse_add) { // We assume that x, y, dy are all contiguous at::Tensor x = x_t.contiguous(); at::Tensor y = y_t.contiguous(); at::Tensor dy = dy_t.contiguous(); // shape const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // outputs at::Tensor x_grad, scale_grad, bias_grad, z_grad; // Allocate outputs x_grad = at::empty_like(x); scale_grad = at::empty_like(scale); bias_grad = at::empty_like(bias); // Setup tensor descriptors at::native::nhwc::TensorDescriptor x_desc, y_desc, dx_desc, dy_desc, dz_desc, bn_desc; x_desc.set(x); y_desc.set(y); dx_desc.set(x_grad); dy_desc.set(dy); if (fuse_add) { z_grad = at::empty_like(x); dz_desc.set(z_grad); } else { z_grad = torch::empty({}, torch::CUDA(at::kFloat)); } auto bn_mode = CUDNN_BATCHNORM_SPATIAL_PERSISTENT; auto bn_op = fuse_relu ? ((fuse_add) ? CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION : CUDNN_BATCHNORM_OPS_BN_ACTIVATION) : CUDNN_BATCHNORM_OPS_BN; // get derived tensor descriptor AT_CUDNN_CHECK(cudnnDeriveBNTensorDescriptor(bn_desc.mut_desc(), x_desc.desc(), bn_mode)); // create activation descriptor cudnnActivationDescriptor_t activ_desc; cudnnCreateActivationDescriptor(&activ_desc); AT_CUDNN_CHECK(cudnnSetActivationDescriptor(activ_desc, CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0)); // get the workspace size and allocate size_t ws_num_bytes; AT_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( at::native::getCudnnHandle(), bn_mode, bn_op, x_desc.desc(), y_desc.desc(), dy_desc.desc(), fuse_add ? dz_desc.desc() : nullptr, // dz_desc dx_desc.desc(), bn_desc.desc(), (fuse_relu) ? activ_desc : nullptr, &ws_num_bytes)); Workspace ws(ws_num_bytes); // get the reserved size and allocate as tensor // call cuDNN float one = 1.f, zero = 0.f; auto eps = std::max(epsilon, BN_MIN_EPSILON); AT_CUDNN_CHECK(cudnnBatchNormalizationBackwardEx( at::native::getCudnnHandle(), bn_mode, bn_op, &one, &zero, &one, &zero, x_desc.desc(), x.data_ptr<at::Half>(), y_desc.desc(), y.data_ptr<at::Half>(), dy_desc.desc(), dy.data_ptr<at::Half>(), fuse_add ? dz_desc.desc() : nullptr, // dz_desc fuse_add ? z_grad.data_ptr<at::Half>() : nullptr, // dz_data dx_desc.desc(), x_grad.data_ptr<at::Half>(), bn_desc.desc(), scale.data_ptr<float>(), bias.data_ptr<float>(), scale_grad.data_ptr<float>(), bias_grad.data_ptr<float>(), eps, save_mean.data_ptr<float>(), save_var.data_ptr<float>(), (fuse_relu) ? activ_desc : nullptr, ws.data, ws_num_bytes, (fuse_add) ? reserve.data_ptr<uint8_t>() : nullptr, // reserve space ptr (fuse_add) ? reserve.numel() : 0)); // reserve space bytes return std::vector<at::Tensor>{x_grad, z_grad, scale_grad, bias_grad}; } std::vector<at::Tensor> nhwc_bn_bwd_cudnn( const at::Tensor& x, const at::Tensor& y, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& save_mean, const at::Tensor& save_var, const at::Tensor& reserve, const float momentum, const float epsilon, const bool fuse_relu) { return nhwc_bn_bwd_cudnn_impl( x, y, dy, scale, bias, running_mean, running_inv_var, save_mean, save_var, reserve, momentum, epsilon, fuse_relu, false); } std::vector<at::Tensor> nhwc_bn_add_bwd_cudnn( const at::Tensor& x, const at::Tensor& y, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& save_mean, const at::Tensor& save_var, const at::Tensor& reserve, const float momentum, const float epsilon, const bool fuse_relu) { return nhwc_bn_bwd_cudnn_impl( x, y, dy, scale, bias, running_mean, running_inv_var, save_mean, save_var, reserve, momentum, epsilon, fuse_relu, true); } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ref_convolution.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "ocl/ref_convolution.hpp" namespace mkldnn { namespace impl { namespace ocl { status_t ref_convolution_fwd_t::execute_forward(const exec_ctx_t &ctx) const { auto &src = CTX_IN_STORAGE(MKLDNN_ARG_SRC); auto &weights = CTX_IN_STORAGE(MKLDNN_ARG_WEIGHTS); auto &bias = CTX_IN_STORAGE(MKLDNN_ARG_BIAS); auto &dst = CTX_OUT_STORAGE(MKLDNN_ARG_DST); auto eltwise_alpha = pd()->eltwise_alpha(); auto eltwise_beta = pd()->eltwise_beta(); auto sum_scale = pd()->sum_scale(); kernel_.set_arg(0, src); kernel_.set_arg(1, weights); kernel_.set_arg(2, bias); kernel_.set_arg(3, dst); kernel_.set_arg(4, eltwise_alpha); kernel_.set_arg(5, eltwise_beta); kernel_.set_arg(6, sum_scale); if (utils::one_of(pd()->src_md()->data_type, data_type::u8, data_type::s8)) { float scales = pd()->attr()->output_scales_.scales_[0]; kernel_.set_arg(7, scales); } auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); const auto *jit_kernel = this->pd()->kernel(); auto nd_range = cl_nd_range_t(jit_kernel->gws()); status_t status = executor.parallel_for(nd_range, kernel_); return status; } status_t ref_convolution_bwd_data_t::execute_backward_data (const exec_ctx_t &ctx) const { auto &diff_dst = CTX_IN_STORAGE(MKLDNN_ARG_DIFF_DST); auto &weights = CTX_IN_STORAGE(MKLDNN_ARG_WEIGHTS); auto &diff_src = CTX_OUT_STORAGE(MKLDNN_ARG_DIFF_SRC); kernel_.set_arg(0, diff_src); kernel_.set_arg(1, weights); kernel_.set_arg(2, diff_dst); auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); const auto *jit_kernel = this->pd()->kernel(); auto nd_range = cl_nd_range_t(jit_kernel->gws()); status_t status = executor.parallel_for(nd_range, kernel_); return status; } status_t ref_convolution_bwd_weights_t::execute_backward_weights (const exec_ctx_t &ctx) const { auto &src = CTX_IN_STORAGE(MKLDNN_ARG_SRC); auto &diff_dst = CTX_IN_STORAGE(MKLDNN_ARG_DIFF_DST); auto &diff_weights = CTX_OUT_STORAGE(MKLDNN_ARG_DIFF_WEIGHTS); auto &diff_bias = CTX_OUT_STORAGE(MKLDNN_ARG_DIFF_BIAS); kernel_.set_arg(0, src); kernel_.set_arg(1, diff_weights); kernel_.set_arg(2, diff_bias); kernel_.set_arg(3, diff_dst); auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); const auto *jit_kernel = this->pd()->kernel(); auto nd_range = cl_nd_range_t(jit_kernel->gws()); status_t status = executor.parallel_for(nd_range, kernel_); return status; } } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/model/types.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_TYPES_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_TYPES_H_ #include <iostream> #include <vector> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/inline_vector.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/position.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/symmetries.h" namespace minigo { // Holds the shape of a tensor and provides a place to put shape-related logic // that isn't coupled to a specific tensor implementation. class TensorShape { public: // Maximum number of dimensions supported. static constexpr int kMaxDims = 4; // Creates an empty tensor shape. // Equivalent to calling `TensorShape({})`. TensorShape() {} // Creates a tensor shape of the given dimensions. // CHECK fails if `shape.size() > TensorShape::kMaxDims`. TensorShape(std::initializer_list<int> shape) { for (auto x : shape) { impl_.push_back(x); } } // Returns true if the shape matches. // Certain dimensions in the shape can be ignored by passing -1: // TensorShape shape(1, 2, 3, 4); // MG_CHECK(shape.is({1, 2, -1, 4}); bool is(std::initializer_list<int> shape) const { if (static_cast<size_t>(impl_.size()) != shape.size()) { return false; } int i = 0; for (auto x : shape) { if (x >= 0 && x != impl_[i]) { return false; } i += 1; } return true; } // (in)equality comparison operators. // Unlike `is`, these operators do not treat negative dimensions specially. bool operator==(const TensorShape& other) const { if (impl_.size() != other.size()) { return false; } for (int i = 0; i < impl_.size(); ++i) { if (impl_[i] != other[i]) { return false; } } return true; } bool operator!=(const TensorShape& other) const { return !(*this == other); } bool empty() const { return impl_.empty(); } int size() const { return impl_.size(); } int operator[](int i) const { return impl_[i]; } // Returns the number of elements in the tensor. int num_elements() const { if (empty()) { return 0; } int result = impl_[0]; for (int i = 1; i < impl_.size(); ++i) { result *= impl_[i]; } return result; } private: inline_vector<int, kMaxDims> impl_; }; std::ostream& operator<<(std::ostream& os, const TensorShape& shape); // A simple tensor representation that abstracts a real engine-specific // tensor. Tensor does not own the memory pointed to by `data`. // Tensors are assumed to be tightly packed for now. template <typename T> struct Tensor { Tensor() = default; Tensor(const TensorShape& shape, T* data) : shape(shape), data(data) {} TensorShape shape; T* data = nullptr; }; template <typename T> class BackedTensor { public: BackedTensor() = default; BackedTensor(const TensorShape& shape) { resize(shape); } void resize(const TensorShape& shape) { int size; if (shape.empty()) { size = 0; } else { size = shape[0]; for (int i = 1; i < shape.size(); ++i) { size *= shape[i]; } } if (static_cast<size_t>(size) > buffer_.size()) { buffer_.resize(size); } tensor_ = {shape, buffer_.data()}; } const Tensor<T>& tensor() const { return tensor_; } Tensor<T>& tensor() { return tensor_; } private: Tensor<T> tensor_; std::vector<T> buffer_; }; struct ModelInput { // Symmetry to apply to the input features when performing inference. symmetry::Symmetry sym = symmetry::kNumSymmetries; // position_history[0] holds the current position and position_history[i] // holds the position from i moves ago. inline_vector<const Position*, kMaxPositionHistory> position_history; }; struct ModelOutput { std::array<float, kNumMoves> policy; float value; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_TYPES_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/include/mxnet/op_attr_types.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2016 by Contributors * \file op_attr_types.h * \brief Additional operator attributes * beside the ones provided by NNVM */ #ifndef MXNET_OP_ATTR_TYPES_H_ #define MXNET_OP_ATTR_TYPES_H_ #include <mshadow/tensor.h> #include <nnvm/op_attr_types.h> #include <vector> #include <functional> #include "./base.h" #include "./ndarray.h" #include "./engine.h" #include "./resource.h" namespace mxnet { using nnvm::NodeAttrs; /*! \brief operation request type to Forward and Backward */ enum OpReqType { /*! \brief no operation, do not write anything */ kNullOp, /*! \brief write gradient to provided space */ kWriteTo, /*! * \brief perform an inplace write, * This option only happen when * Target shares memory with one of input arguments. */ kWriteInplace, /*! \brief add to the provided space */ kAddTo }; /*! * \brief All the possible information needed by Operator.Forward and Backward * This is the superset of RunContext. * We use this data structure to bookkeep everything needed by Forward and Backward. * \sa Resource */ struct OpContext { /*! \brief whether there is a backward phase to compute gradients. */ bool need_grad; /*! \brief whether it is training phase */ bool is_train; /*! \brief whether it is cac-gradient-skip */ bool is_cac_gradient_skip; /*! \brief RunContext related resources */ RunContext run_ctx; /*! \brief the callback when operation completes, used by asynchronize ops */ engine::CallbackOnComplete async_on_complete; /*! \brief Resources requested by the operator */ std::vector<Resource> requested; /*! * \brief get mshadow stream from Context * \return the mshadow stream * \tparam xpu the device type of the stream */ template<typename xpu> inline mshadow::Stream<xpu>* get_stream() const { return run_ctx.get_stream<xpu>(); } #if MXNET_USE_CUDA /*! * \brief get auxilary gpu stream auto-syncing object from Context * \return the aux stream auto-syncing object */ inline SyncedGPUAuxStream get_gpu_aux_stream() const { return run_ctx.get_gpu_aux_stream(); } #endif }; /*! \brief the execution type of the operator */ enum class ExecType { /*! \brief Forward/Backward are synchronous calls */ kSync, /*! * \brief Forward/Backward are asynchronous, * will call OpContext.async_on_complete when operation finishes. */ kAsync, /*! * \brief Cross device copy operation, this is a special operator that indicates it will copy * across devices. For example the input and output for this type of operator can potentially * reside on different devices. In the current implementation, a copy operator is specially * handled by an executor. This flag is used for special case treatment and future extension of * different copy ops. */ kCrossDeviceCopy, /*! * \brief A subgraph execution should happen in the main thread, instead of * in the execution engine. */ kSubgraphExec, }; /*! \brief the dispatch mode of the operator */ enum class DispatchMode { kUndefined = -1, // dispatch on FCompute or FStatefulCompute kFCompute, // dispatch on FComputeEx or FStatefulComputeEx, if available kFComputeEx, // dispatch on FCompute or FStatefulCompute, and performs storage fallback kFComputeFallback, // special dispatch mode for variables kVariable, }; /*! \brief the quantization type of the operator */ enum class QuantizeType { // This operator doesn't support quantization kNone = 0, // This operator can get huge benefit from quantization, thus must be quantized kMust, // This operator support quantization, but will be decided depending on the connection kSupport, }; /*! * \brief Operator state. This is a pointer type, its content is mutable * even if OpStatePtr is const. */ class OpStatePtr { public: /* \brief Create a OpStatePtr with state of type T. * \param args Arguments passed to T's constructor. */ template<typename T, typename... Args> static OpStatePtr Create(Args&&... args) { OpStatePtr ret; auto state = new T(std::forward<Args>(args)...); auto var = Engine::Get()->NewVariable(); ret.ptr_.reset( new OpState(var, state), [](OpState* p) { Engine::Get()->DeleteVariable([](RunContext s) {}, Context::CPU(), p->var); delete reinterpret_cast<T*>(p->state); delete p; }); return ret; } /* \brief Get engine variable associated with this state */ engine::VarHandle get_var() const { return ptr_->var; } /* \brief Get state of type T */ template<typename T> T& get_state() const { return *reinterpret_cast<T*>(ptr_->state); } /* \brief clear state */ void reset() { ptr_.reset(); } /* \brief checks whether the managed object is managed only by the current OpStatePtr instance */ bool unique() const { return ptr_.unique(); } /* \brief Whether state is empty */ explicit operator bool() const { return ptr_ ? true : false; } private: /* \brief state structure */ struct OpState { engine::VarHandle var; void* state; OpState(engine::VarHandle var_, void* state_) : var(var_), state(state_) {} OpState(const OpState& other) = delete; OpState& operator=(const OpState& other) = delete; }; /* \brief shared pointer to state */ std::shared_ptr<OpState> ptr_; }; /*! * \brief Create a Layer style, forward/backward operator. * This is easy to write code that contains state. * OpStatePtr is a pointer type, it's content is mutable even if * OpStatePtr is constant. * * * This is not the only way to register an op execution function. * More simpler or specialized operator form can be registered * * \note Register under "FCreateLayerOp" */ using FCreateOpState = std::function<OpStatePtr (const NodeAttrs& attrs, Context ctx, const mxnet::ShapeVector& in_shape, const std::vector<int>& in_type)>; /*! * \brief Whether the operator always produces the same * output given the same input. * This enables certain optimizations * like common expression elimination. * * \note Register under "THasDeterministicOutput" */ using THasDeterministicOutput = bool; /*! * \brief Execution mode of this operator. */ using FExecType = std::function<ExecType (const NodeAttrs& attrs)>; /*! * \brief Resiger a compute function for stateful operator. * OpStatePtr is a pointer type, it's content is mutable even if * OpStatePtr is constant. * * \note Register under "FStatefulCompute<cpu>" and "FStatefulCompute<gpu>" */ using FStatefulCompute = std::function<void (const OpStatePtr& state, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs)>; /*! * \brief Resiger a compute function for stateful operator using NDArray interface. * OpStatePtr is a pointer type, it's content is mutable even if * OpStatePtr is constant. * * \note Register under "FStatefulComputeEx<cpu>" and "FStatefulComputeEx<gpu>" */ using FStatefulComputeEx = std::function<void (const OpStatePtr& state, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs)>; /*! * \brief The resource request from the operator. * An operator could register ResourceRequestEx, or ResourceRequest, or neither. * * \note Register under "FResourceRequest" */ using FResourceRequest = std::function< std::vector<ResourceRequest> (const NodeAttrs& n)>; /*! * \brief The resource request from the operator. * An operator could register ResourceRequestEx, or ResourceRequest, or neither. * If an operator registers both ResourceRequestEx and ResourceRequest, * ResourceRequest is ignored. * * \note Register under "FResourceRequestEx" */ using FResourceRequestEx = std::function< std::vector<ResourceRequest> (const NodeAttrs& n, const int dev_mask, const DispatchMode dispatch_mode)>; /*! * \brief Register an operator called as a NDArray function * * \note Register under "FNDArrayFunction" */ using FNDArrayFunction = std::function<void (const nnvm::NodeAttrs& attrs, const std::vector<NDArray>& inputs, std::vector<NDArray>* outputs)>; /*! * \brief Register a compute function for simple stateless forward only operator * * \note Register under "FCompute<cpu>" and "FCompute<gpu>" */ using FCompute = std::function<void (const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs)>; /*! * \brief Register an NDArray compute function for simple stateless forward only operator * \note Register under "FComputeEx<xpu>" and "FComputeEx<xpu>" * Dispatched only when inferred dispatch_mode is FDispatchComputeEx */ using FComputeEx = std::function<void (const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs)>; /*! * \brief Register a storage and dispatch mode inference function based on * storage types of the inputs and outputs, and the dev_mask for the operator. * * \note Register under "FInferStorageType" */ using FInferStorageType = std::function<bool (const NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int>* in_attrs, std::vector<int>* out_attrs)>; /*! * \brief Register a quantized node creation function based on the attrs of the node * \note Register under "FQuantizedOp" for non-quantized operators */ using FQuantizable = std::function<QuantizeType (const NodeAttrs& attrs)>; /*! * \brief Register a quantized node creation function based on the attrs of the node * \note Register under "FQuantizedOp" for non-quantized operators */ using FQuantizedOp = std::function<nnvm::NodePtr (const NodeAttrs& attrs)>; /*! * \brief Register a function to determine if the output of a quantized operator * needs to be requantized. This is usually used for the operators * taking int8 data types while accumulating in int32, e.g. quantized_conv. * \note Register under "FNeedRequantize" for non-quantized operators */ using FNeedRequantize = std::function<bool (const NodeAttrs& attrs)>; /*! * \brief Register a function to determine if the input of a quantized operator * needs to be quantized. This is usually used for the quantized operators * which can handle fp32 inputs directly. */ using FAvoidQuantizeInput = std::function<bool (const NodeAttrs& attrs, size_t index)>; /*! * \brief Register a function to determine if the input of a quantized operator * needs to be calibrated. This is usually used for the quantized operators * which need calibration on its input. */ using FNeedCalibrateInput = std::function<std::vector<int> (const NodeAttrs& attrs)>; /*! * \brief Register a function to determine if the output of a quantized operator * needs to be calibrated. This is usually used for the quantized operators * which need calibration on its output. */ using FNeedCalibrateOutput = std::function<std::vector<int> (const NodeAttrs& attrs)>; } // namespace mxnet #endif // MXNET_OP_ATTR_TYPES_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/alm.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file alm.h * \brief Automatic Layout Manager * \author <NAME> */ #ifndef MXNET_EXECUTOR_ALM_H_ #define MXNET_EXECUTOR_ALM_H_ #include <nnvm/graph.h> #include <nnvm/node.h> #include <nnvm/symbolic.h> #include <mshadow/base.h> #include <mshadow/tensor.h> #include <string> #include <utility> #include <vector> #include <unordered_set> #include <set> #include <queue> #include "./exec_pass.h" #include "./simple_partition_pass.h" namespace mxnet { namespace exec { class AutomaticLayoutManager { public: enum passdir_t {kNONE, kFWD, kBWD}; struct NodeInfo { bool blacklisted = false; passdir_t pass_direction; nnvm::TShape axes; bool is_added = false; NodeInfo(): pass_direction(kNONE) { } NodeInfo(passdir_t pd, nnvm::TShape ax, bool is_added): pass_direction(pd), axes(ax), is_added(is_added) { } }; using BG = BidirectionalGraph<NodeInfo>; using BGNode = BG::Node; using BGEdge = BG::EdgeRef; const std::string name_base_ = "ALM_transpose_"; nnvm::Graph graph_; BidirectionalGraph<NodeInfo> bigraph_; explicit AutomaticLayoutManager(const nnvm::Symbol& symbol): graph_(symbol2Graph(symbol)), bigraph_(&graph_) { } AutomaticLayoutManager(AutomaticLayoutManager&) = delete; AutomaticLayoutManager(AutomaticLayoutManager&&) = delete; AutomaticLayoutManager operator=(AutomaticLayoutManager&) = delete; AutomaticLayoutManager operator=(AutomaticLayoutManager&&) = delete; void run(std::unordered_map<std::string, std::string> targets); nnvm::Symbol GetOptimizedSymbol() const { nnvm::Symbol s; s.outputs = graph_.outputs; return s.Copy(); } private: std::unordered_map<std::string, mshadow::LayoutFlag> targets_; std::unordered_set<std::shared_ptr<BGNode>> newNodes_; unsigned n_newNodes = 0; std::string getNextName() { return name_base_ + std::to_string(n_newNodes++); } nnvm::Graph symbol2Graph(const nnvm::Symbol &s) { nnvm::Graph g; g.outputs = s.outputs; return g; } nnvm::NodePtr CreateTransposeNode(const NodeInfo& info); /*! * \brief Repins all inputs and outputs excluding it from the graph, * both for BGNode as for eventually nnvm::Node inside. * Then marks node as blacklisted. * \param node Node that's to be deleted. */ void deleteNode(BGNode* node); /*! * \brief Changes layout of given node (this node has to have "layout" attribute) * and surrounds it with proper transposes. * \param node Pointer to node that layout has to be changed. * \return Set of pointers to created Transposes or empty set if function failed, * and no tranpose was created. */ std::set<BGNode*> changeLayout(BGNode* node, mshadow::LayoutFlag layout); /*! * \brief If possible passes transpose further (forward or backward) * by removing it and creating another on all the others edges * of the next/previous node, or merge with it if it's also transpose. * \param t_ptr Pointer to the transpose node that's need to be passed. * \return Set of pointers to created Transposes, empty set if the tranpose * collapsed with another, empty set if transpose collapsed to identity * with the next or {t_ptr} if function failed and t_ptr was not removed. */ std::set<BGNode*> passTranspose(BGNode* t_ptr); /*! * \brief Merge two adjacent transpose nodes. * \param first Pointer to the first transpose node. * \param second Pointer to the second transpose node. * \return Pointer to eventually created node, or nullptr * if none was created. */ BGNode* mergeTransposes(BGNode* first, BGNode* second); /*! * \brief Create new nnvm::Node with transpose operation, * put it in given node and register it. * \param node Empty BidirectionalGraph<NodeInfo>::Node. */ void addTransposeOp(BGNode* node); /*! * \brief Inserts new ALM transpose node in between two given. * \param edge Edge on which transpose will be inserted. * \param newInfo NodeInfo for the new transpose node. * \return Pointer tho the node that was created. */ BGNode* insertTransposeBetween(const BGEdge* edge, const NodeInfo& newInfo); /*! * \brief Surrounds given node with transposes, according to given axes. * \param node Node to be surrounded. * \param inpAxes Vector of axes for input transposes. * \param outAxes Vector of axes for output transposes. * \return Set of pointers to created transposes. */ std::set<BGNode*> surroundNode(BGNode* node, std::vector<nnvm::TShape>* inpAxes, std::vector<nnvm::TShape>* outAxes); }; } // namespace exec } // namespace mxnet #endif // MXNET_EXECUTOR_ALM_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_sse41_f32_copy_at_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_f32.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_sse41_f32_copy_at_kern::jit_sse41_f32_copy_at_kern() : jit_generator(nullptr, F32_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rsi #define B rdi #define I rax #define A1 r10 #define A2 rsi #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l130; Xbyak::Label l1b4; Xbyak::Label l21c; Xbyak::Label l22c; Xbyak::Label l24c; Xbyak::Label l2b0; Xbyak::Label l2fc; Xbyak::Label l33c; Xbyak::Label l340; Xbyak::Label l360; Xbyak::Label l39c; Xbyak::Label l3cc; Xbyak::Label l3f8; Xbyak::Label l3fc; Xbyak::Label l41c; Xbyak::Label l458; Xbyak::Label l488; Xbyak::Label l4ac; Xbyak::Label l4b0; Xbyak::Label l4b8; Xbyak::Label l4d4; Xbyak::Label l4f0; Xbyak::Label l54; Xbyak::Label l5c8; Xbyak::Label l65c; Xbyak::Label l6cc; Xbyak::Label l6dc; Xbyak::Label l6fc; Xbyak::Label l70; Xbyak::Label l76c; Xbyak::Label l7c0; Xbyak::Label l804; Xbyak::Label l808; Xbyak::Label l828; Xbyak::Label l868; Xbyak::Label l89c; Xbyak::Label l8cc; Xbyak::Label l8d0; Xbyak::Label l8f0; Xbyak::Label l930; Xbyak::Label l964; Xbyak::Label l98c; Xbyak::Label l990; Xbyak::Label l998; Xbyak::Label l9a4; Xbyak::Label l9c0; Xbyak::Label la98; Xbyak::Label lb2c; Xbyak::Label lb9c; Xbyak::Label lbac; Xbyak::Label lbcc; Xbyak::Label lc3c; Xbyak::Label lc90; Xbyak::Label lcd4; Xbyak::Label lcd8; Xbyak::Label lcf8; Xbyak::Label ld38; Xbyak::Label ld6c; Xbyak::Label ld9c; Xbyak::Label lda0; Xbyak::Label ldc0; Xbyak::Label le00; Xbyak::Label le34; Xbyak::Label le5c; Xbyak::Label le60; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); sub(A, 0x0); sub(B, -128); shl(LDA, 0x2); lea(LDA3, ptr[LDA+LDA*2]); movss(xmm6, dword[ALPHA]); pshufd(xmm6, xmm6, 0x0); pcmpeqb(xmm3, xmm3); psrld(xmm3, 0x17); pslld(xmm3, 0x19); psrld(xmm3, 0x2); pcmpeqb(xmm4, xmm4); pslld(xmm4, 0x1f); ucomiss(xmm6, xmm3); jne(l4b8, T_NEAR); cmp(N, 0x8); jl(l22c, T_NEAR); align(4); L(l54); mov(A1, A); mov(I, LDA); imul(I, I, 0x8); add(A, I); mov(I, M); sar(I, 0x2); jle(l130, T_NEAR); align(4); L(l70); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movups(xmm2, xword[A1+LDA*2]); movups(xmm3, xword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); movups(xword[B-0x80], xmm0); movups(xword[B-0x60], xmm1); movups(xword[B-0x40], xmm2); movups(xword[B-0x20], xmm3); lea(A2, ptr[A1+LDA*4]); movups(xmm0, xword[A2]); movups(xmm1, xword[A2+LDA*1]); movups(xmm2, xword[A2+LDA*2]); movups(xmm3, xword[A2+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); movups(xword[B-0x70], xmm0); movups(xword[B-0x50], xmm1); movups(xword[B-0x30], xmm2); movups(xword[B-0x10], xmm3); lea(A2, ptr[A2+LDA*4]); sub(A1, -16); sub(B, -128); dec(I); jg(l70, T_NEAR); align(4); L(l130); test(M, 0x2); jle(l1b4, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); movhps(xmm0, qword[A1+LDA*2]); movhps(xmm1, qword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); movups(xword[B-0x80], xmm0); movups(xword[B-0x60], xmm1); lea(A2, ptr[A1+LDA*4]); movsd(xmm0, qword[A2]); movsd(xmm1, qword[A2+LDA*1]); movhps(xmm0, qword[A2+LDA*2]); movhps(xmm1, qword[A2+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); movups(xword[B-0x70], xmm0); movups(xword[B-0x50], xmm1); lea(A2, ptr[A2+LDA*4]); sub(A1, -8); sub(B, -64); align(4); L(l1b4); test(M, 0x1); jle(l21c, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A1+LDA*2]); movss(xmm3, dword[A1+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); movups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); movss(xmm0, dword[A2]); movss(xmm1, dword[A2+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A2+LDA*2]); movss(xmm3, dword[A2+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); movups(xword[B-0x70], xmm0); lea(A2, ptr[A2+LDA*4]); sub(A1, -4); sub(B, -32); align(4); L(l21c); sub(N, 0x8); cmp(N, 0x8); jge(l54, T_NEAR); align(4); L(l22c); cmp(N, 0x4); jl(l340, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(l2b0, T_NEAR); align(4); L(l24c); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movups(xmm2, xword[A1+LDA*2]); movups(xmm3, xword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); movups(xword[B-0x80], xmm0); movups(xword[B-0x70], xmm1); movups(xword[B-0x60], xmm2); movups(xword[B-0x50], xmm3); lea(A2, ptr[A1+LDA*4]); sub(A1, -16); sub(B, -64); dec(I); jg(l24c, T_NEAR); align(4); L(l2b0); test(M, 0x2); jle(l2fc, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); movhps(xmm0, qword[A1+LDA*2]); movhps(xmm1, qword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); movups(xword[B-0x80], xmm0); movups(xword[B-0x70], xmm1); lea(A2, ptr[A1+LDA*4]); sub(A1, -8); sub(B, -32); align(4); L(l2fc); test(M, 0x1); jle(l33c, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A1+LDA*2]); movss(xmm3, dword[A1+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); movups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); sub(A1, -4); sub(B, -16); align(4); L(l33c); sub(N, 0x4); align(4); L(l340); cmp(N, 0x2); jl(l3fc, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l39c, T_NEAR); align(4); L(l360); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm4); movlps(qword[B-0x80], xmm0); movhps(qword[B-0x78], xmm0); movlps(qword[B-0x70], xmm1); movhps(qword[B-0x68], xmm1); lea(A2, ptr[A1+LDA*2]); sub(A1, -16); sub(B, -32); dec(I); jg(l360, T_NEAR); align(4); L(l39c); test(M, 0x2); jle(l3cc, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); unpcklps(xmm0, xmm1); movlps(qword[B-0x80], xmm0); movhps(qword[B-0x78], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -8); sub(B, -16); align(4); L(l3cc); test(M, 0x1); jle(l3f8, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movlps(qword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -4); sub(B, -8); align(4); L(l3f8); sub(N, 0x2); align(4); L(l3fc); cmp(N, 0x1); jl(l4b0, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l458, T_NEAR); align(4); L(l41c); movups(xmm0, xword[A1]); pshufd(xmm1, xmm0, 0x55); pshufd(xmm2, xmm0, 0xaa); pshufd(xmm3, xmm0, 0xff); movss(dword[B-0x80], xmm0); movss(dword[B-0x7c], xmm1); movss(dword[B-0x78], xmm2); movss(dword[B-0x74], xmm3); lea(A2, ptr[A1+LDA*1]); sub(A1, -16); sub(B, -16); dec(I); jg(l41c, T_NEAR); align(4); L(l458); test(M, 0x2); jle(l488, T_NEAR); movsd(xmm0, qword[A1]); pshufd(xmm1, xmm0, 0x55); movss(dword[B-0x80], xmm0); movss(dword[B-0x7c], xmm1); lea(A2, ptr[A1+LDA*1]); sub(A1, -8); sub(B, -8); align(4); L(l488); test(M, 0x1); jle(l4ac, T_NEAR); movss(xmm0, dword[A1]); movss(dword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*1]); sub(A1, -4); sub(B, -4); align(4); L(l4ac); sub(N, 0x1); align(4); L(l4b0); jmp(le60, T_NEAR); align(4); L(l4b8); xorps(xmm3, xmm4); ucomiss(xmm6, xmm3); jne(l998, T_NEAR); movaps(xmm6, xmm4); cmp(N, 0x8); jl(l6dc, T_NEAR); align(4); L(l4d4); mov(A1, A); mov(I, LDA); imul(I, I, 0x8); add(A, I); mov(I, M); sar(I, 0x2); jle(l5c8, T_NEAR); align(4); L(l4f0); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movups(xmm2, xword[A1+LDA*2]); movups(xmm3, xword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); xorps(xmm0, xmm6); xorps(xmm1, xmm6); xorps(xmm2, xmm6); xorps(xmm3, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x60], xmm1); movups(xword[B-0x40], xmm2); movups(xword[B-0x20], xmm3); lea(A2, ptr[A1+LDA*4]); movups(xmm0, xword[A2]); movups(xmm1, xword[A2+LDA*1]); movups(xmm2, xword[A2+LDA*2]); movups(xmm3, xword[A2+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); xorps(xmm0, xmm6); xorps(xmm1, xmm6); xorps(xmm2, xmm6); xorps(xmm3, xmm6); movups(xword[B-0x70], xmm0); movups(xword[B-0x50], xmm1); movups(xword[B-0x30], xmm2); movups(xword[B-0x10], xmm3); lea(A2, ptr[A2+LDA*4]); sub(A1, -16); sub(B, -128); dec(I); jg(l4f0, T_NEAR); align(4); L(l5c8); test(M, 0x2); jle(l65c, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); movhps(xmm0, qword[A1+LDA*2]); movhps(xmm1, qword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); xorps(xmm0, xmm6); xorps(xmm1, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x60], xmm1); lea(A2, ptr[A1+LDA*4]); movsd(xmm0, qword[A2]); movsd(xmm1, qword[A2+LDA*1]); movhps(xmm0, qword[A2+LDA*2]); movhps(xmm1, qword[A2+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); xorps(xmm0, xmm6); xorps(xmm1, xmm6); movups(xword[B-0x70], xmm0); movups(xword[B-0x50], xmm1); lea(A2, ptr[A2+LDA*4]); sub(A1, -8); sub(B, -64); align(4); L(l65c); test(M, 0x1); jle(l6cc, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A1+LDA*2]); movss(xmm3, dword[A1+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); xorps(xmm0, xmm6); movups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); movss(xmm0, dword[A2]); movss(xmm1, dword[A2+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A2+LDA*2]); movss(xmm3, dword[A2+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); xorps(xmm0, xmm6); movups(xword[B-0x70], xmm0); lea(A2, ptr[A2+LDA*4]); sub(A1, -4); sub(B, -32); align(4); L(l6cc); sub(N, 0x8); cmp(N, 0x8); jge(l4d4, T_NEAR); align(4); L(l6dc); cmp(N, 0x4); jl(l808, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(l76c, T_NEAR); align(4); L(l6fc); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movups(xmm2, xword[A1+LDA*2]); movups(xmm3, xword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); xorps(xmm0, xmm6); xorps(xmm1, xmm6); xorps(xmm2, xmm6); xorps(xmm3, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x70], xmm1); movups(xword[B-0x60], xmm2); movups(xword[B-0x50], xmm3); lea(A2, ptr[A1+LDA*4]); sub(A1, -16); sub(B, -64); dec(I); jg(l6fc, T_NEAR); align(4); L(l76c); test(M, 0x2); jle(l7c0, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); movhps(xmm0, qword[A1+LDA*2]); movhps(xmm1, qword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); xorps(xmm0, xmm6); xorps(xmm1, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x70], xmm1); lea(A2, ptr[A1+LDA*4]); sub(A1, -8); sub(B, -32); align(4); L(l7c0); test(M, 0x1); jle(l804, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A1+LDA*2]); movss(xmm3, dword[A1+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); xorps(xmm0, xmm6); movups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); sub(A1, -4); sub(B, -16); align(4); L(l804); sub(N, 0x4); align(4); L(l808); cmp(N, 0x2); jl(l8d0, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l868, T_NEAR); align(4); L(l828); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm4); xorps(xmm0, xmm6); xorps(xmm1, xmm6); movlps(qword[B-0x80], xmm0); movhps(qword[B-0x78], xmm0); movlps(qword[B-0x70], xmm1); movhps(qword[B-0x68], xmm1); lea(A2, ptr[A1+LDA*2]); sub(A1, -16); sub(B, -32); dec(I); jg(l828, T_NEAR); align(4); L(l868); test(M, 0x2); jle(l89c, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); unpcklps(xmm0, xmm1); xorps(xmm0, xmm6); movlps(qword[B-0x80], xmm0); movhps(qword[B-0x78], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -8); sub(B, -16); align(4); L(l89c); test(M, 0x1); jle(l8cc, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); xorps(xmm0, xmm6); movlps(qword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -4); sub(B, -8); align(4); L(l8cc); sub(N, 0x2); align(4); L(l8d0); cmp(N, 0x1); jl(l990, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l930, T_NEAR); align(4); L(l8f0); movups(xmm0, xword[A1]); xorps(xmm0, xmm6); pshufd(xmm1, xmm0, 0x55); pshufd(xmm2, xmm0, 0xaa); pshufd(xmm3, xmm0, 0xff); movss(dword[B-0x80], xmm0); movss(dword[B-0x7c], xmm1); movss(dword[B-0x78], xmm2); movss(dword[B-0x74], xmm3); lea(A2, ptr[A1+LDA*1]); sub(A1, -16); sub(B, -16); dec(I); jg(l8f0, T_NEAR); align(4); L(l930); test(M, 0x2); jle(l964, T_NEAR); movsd(xmm0, qword[A1]); xorps(xmm0, xmm6); pshufd(xmm1, xmm0, 0x55); movss(dword[B-0x80], xmm0); movss(dword[B-0x7c], xmm1); lea(A2, ptr[A1+LDA*1]); sub(A1, -8); sub(B, -8); align(4); L(l964); test(M, 0x1); jle(l98c, T_NEAR); movss(xmm0, dword[A1]); xorps(xmm0, xmm6); movss(dword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*1]); sub(A1, -4); sub(B, -4); align(4); L(l98c); sub(N, 0x1); align(4); L(l990); jmp(le60, T_NEAR); align(4); L(l998); cmp(N, 0x8); jl(lbac, T_NEAR); align(4); L(l9a4); mov(A1, A); mov(I, LDA); imul(I, I, 0x8); add(A, I); mov(I, M); sar(I, 0x2); jle(la98, T_NEAR); align(4); L(l9c0); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movups(xmm2, xword[A1+LDA*2]); movups(xmm3, xword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); mulps(xmm0, xmm6); mulps(xmm1, xmm6); mulps(xmm2, xmm6); mulps(xmm3, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x60], xmm1); movups(xword[B-0x40], xmm2); movups(xword[B-0x20], xmm3); lea(A2, ptr[A1+LDA*4]); movups(xmm0, xword[A2]); movups(xmm1, xword[A2+LDA*1]); movups(xmm2, xword[A2+LDA*2]); movups(xmm3, xword[A2+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); mulps(xmm0, xmm6); mulps(xmm1, xmm6); mulps(xmm2, xmm6); mulps(xmm3, xmm6); movups(xword[B-0x70], xmm0); movups(xword[B-0x50], xmm1); movups(xword[B-0x30], xmm2); movups(xword[B-0x10], xmm3); lea(A2, ptr[A2+LDA*4]); sub(A1, -16); sub(B, -128); dec(I); jg(l9c0, T_NEAR); align(4); L(la98); test(M, 0x2); jle(lb2c, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); movhps(xmm0, qword[A1+LDA*2]); movhps(xmm1, qword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); mulps(xmm0, xmm6); mulps(xmm1, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x60], xmm1); lea(A2, ptr[A1+LDA*4]); movsd(xmm0, qword[A2]); movsd(xmm1, qword[A2+LDA*1]); movhps(xmm0, qword[A2+LDA*2]); movhps(xmm1, qword[A2+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); mulps(xmm0, xmm6); mulps(xmm1, xmm6); movups(xword[B-0x70], xmm0); movups(xword[B-0x50], xmm1); lea(A2, ptr[A2+LDA*4]); sub(A1, -8); sub(B, -64); align(4); L(lb2c); test(M, 0x1); jle(lb9c, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A1+LDA*2]); movss(xmm3, dword[A1+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); mulps(xmm0, xmm6); movups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); movss(xmm0, dword[A2]); movss(xmm1, dword[A2+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A2+LDA*2]); movss(xmm3, dword[A2+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); mulps(xmm0, xmm6); movups(xword[B-0x70], xmm0); lea(A2, ptr[A2+LDA*4]); sub(A1, -4); sub(B, -32); align(4); L(lb9c); sub(N, 0x8); cmp(N, 0x8); jge(l9a4, T_NEAR); align(4); L(lbac); cmp(N, 0x4); jl(lcd8, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(lc3c, T_NEAR); align(4); L(lbcc); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movups(xmm2, xword[A1+LDA*2]); movups(xmm3, xword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm5, xmm2); unpcklps(xmm2, xmm3); unpckhps(xmm5, xmm3); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm2); unpckhpd(xmm1, xmm2); movaps(xmm2, xmm4); movaps(xmm3, xmm4); unpcklpd(xmm2, xmm5); unpckhpd(xmm3, xmm5); mulps(xmm0, xmm6); mulps(xmm1, xmm6); mulps(xmm2, xmm6); mulps(xmm3, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x70], xmm1); movups(xword[B-0x60], xmm2); movups(xword[B-0x50], xmm3); lea(A2, ptr[A1+LDA*4]); sub(A1, -16); sub(B, -64); dec(I); jg(lbcc, T_NEAR); align(4); L(lc3c); test(M, 0x2); jle(lc90, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); movhps(xmm0, qword[A1+LDA*2]); movhps(xmm1, qword[A1+LDA3*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm0); unpcklpd(xmm0, xmm4); unpckhpd(xmm1, xmm4); mulps(xmm0, xmm6); mulps(xmm1, xmm6); movups(xword[B-0x80], xmm0); movups(xword[B-0x70], xmm1); lea(A2, ptr[A1+LDA*4]); sub(A1, -8); sub(B, -32); align(4); L(lc90); test(M, 0x1); jle(lcd4, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); movss(xmm2, dword[A1+LDA*2]); movss(xmm3, dword[A1+LDA3*1]); unpcklps(xmm2, xmm3); unpcklpd(xmm0, xmm2); mulps(xmm0, xmm6); movups(xword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*4]); sub(A1, -4); sub(B, -16); align(4); L(lcd4); sub(N, 0x4); align(4); L(lcd8); cmp(N, 0x2); jl(lda0, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(ld38, T_NEAR); align(4); L(lcf8); movups(xmm0, xword[A1]); movups(xmm1, xword[A1+LDA*1]); movaps(xmm4, xmm0); unpcklps(xmm0, xmm1); unpckhps(xmm4, xmm1); movaps(xmm1, xmm4); mulps(xmm0, xmm6); mulps(xmm1, xmm6); movlps(qword[B-0x80], xmm0); movhps(qword[B-0x78], xmm0); movlps(qword[B-0x70], xmm1); movhps(qword[B-0x68], xmm1); lea(A2, ptr[A1+LDA*2]); sub(A1, -16); sub(B, -32); dec(I); jg(lcf8, T_NEAR); align(4); L(ld38); test(M, 0x2); jle(ld6c, T_NEAR); movsd(xmm0, qword[A1]); movsd(xmm1, qword[A1+LDA*1]); unpcklps(xmm0, xmm1); mulps(xmm0, xmm6); movlps(qword[B-0x80], xmm0); movhps(qword[B-0x78], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -8); sub(B, -16); align(4); L(ld6c); test(M, 0x1); jle(ld9c, T_NEAR); movss(xmm0, dword[A1]); movss(xmm1, dword[A1+LDA*1]); unpcklps(xmm0, xmm1); mulps(xmm0, xmm6); movlps(qword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*2]); sub(A1, -4); sub(B, -8); align(4); L(ld9c); sub(N, 0x2); align(4); L(lda0); cmp(N, 0x1); jl(le60, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(le00, T_NEAR); align(4); L(ldc0); movups(xmm0, xword[A1]); mulps(xmm0, xmm6); pshufd(xmm1, xmm0, 0x55); pshufd(xmm2, xmm0, 0xaa); pshufd(xmm3, xmm0, 0xff); movss(dword[B-0x80], xmm0); movss(dword[B-0x7c], xmm1); movss(dword[B-0x78], xmm2); movss(dword[B-0x74], xmm3); lea(A2, ptr[A1+LDA*1]); sub(A1, -16); sub(B, -16); dec(I); jg(ldc0, T_NEAR); align(4); L(le00); test(M, 0x2); jle(le34, T_NEAR); movsd(xmm0, qword[A1]); mulps(xmm0, xmm6); pshufd(xmm1, xmm0, 0x55); movss(dword[B-0x80], xmm0); movss(dword[B-0x7c], xmm1); lea(A2, ptr[A1+LDA*1]); sub(A1, -8); sub(B, -8); align(4); L(le34); test(M, 0x1); jle(le5c, T_NEAR); movss(xmm0, dword[A1]); mulps(xmm0, xmm6); movss(dword[B-0x80], xmm0); lea(A2, ptr[A1+LDA*1]); sub(A1, -4); sub(B, -4); align(4); L(le5c); sub(N, 0x1); align(4); L(le60); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/inline_vector.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_INLINE_VECTOR_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_INLINE_VECTOR_H_ #include <cstdint> #include <new> #include <utility> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" namespace minigo { // inline_vector is an std::vector-like container that uses inline storage, thus // avoiding heap allocations. // Since we currently only need to store POD types in inline_vector, this is // a fairly bare bones implementation. template <typename T, int Capacity> class inline_vector { public: inline_vector() = default; ~inline_vector() { clear(); } inline_vector(const inline_vector& other) { for (const auto& x : other) { push_back(x); } } inline_vector& operator=(const inline_vector& other) { if (&other != this) { clear(); for (const auto& x : other) { push_back(x); } } return *this; } void clear() { for (T& x : *this) { x.~T(); } size_ = 0; } int size() const { return size_; } int capacity() const { return Capacity; } bool empty() const { return size_ == 0; } T* data() { return reinterpret_cast<T*>(storage_); } const T* data() const { return reinterpret_cast<const T*>(storage_); } T* begin() { return data(); } const T* begin() const { return data(); } T* end() { return data() + size_; } const T* end() const { return data() + size_; } T& operator[](int idx) { MG_DCHECK(idx >= 0); MG_DCHECK(idx < size_); return data()[idx]; } const T& operator[](int idx) const { MG_DCHECK(idx >= 0); MG_DCHECK(idx < size_); return data()[idx]; } void push_back(const T& t) { MG_CHECK(size_ < Capacity); new (data() + size_) T(t); ++size_; } template <typename... Args> void emplace_back(Args&&... args) { MG_CHECK(size_ < Capacity); new (data() + size_) T(std::forward<Args>(args)...); ++size_; } T& front() { return data()[0]; } const T& front() const { return data()[0]; } T& back() { return data()[size_ - 1]; } const T& back() const { return data()[size_ - 1]; } void pop_back() { MG_CHECK(size_ > 0); --size_; } void resize(int size) { MG_CHECK(size >= 0); MG_CHECK(size <= Capacity); size_ = size; } void resize(int size, const T& t) { MG_CHECK(size >= 0); MG_CHECK(size <= Capacity); for (int i = size_; i < size; ++i) { data()[i] = t; } size_ = size; } private: int size_ = 0; uint8_t MG_ALIGN(alignof(T)) storage_[Capacity * sizeof(T)]; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_INLINE_VECTOR_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/simple_partition_pass.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file simple_partition_pass.cc * \brief * \author <NAME> */ #include "./simple_partition_pass.h" namespace mxnet { namespace exec { nnvm::NodeEntryMap<uint32_t> GetSubgraphOutputs(Graph g, NodeRawPtrSet subgraph_set) { nnvm::NodeEntryMap<uint32_t> outputs; uint32_t count = 0; for (auto& e : g.outputs) { if (subgraph_set.count(e.node.get()) && !outputs.count(e)) { outputs.insert({e, count++}); } } DFSVisit(g.outputs, [&subgraph_set, &outputs, &count](const nnvm::NodePtr &node){ if (!subgraph_set.count(node.get())) { for (auto& e : node->inputs) { if (subgraph_set.count(e.node.get()) && !outputs.count(e)) { outputs.insert({e, count++}); } } } }); return outputs; } std::vector<nnvm::NodeEntry> GetSubgraphInputs(Graph g, NodeRawPtrSet subgraph_set) { std::vector<nnvm::NodeEntry> inputs; nnvm::NodeEntryMap<nnvm::NodeEntry> entry_map; DFSVisit(g.outputs, [&subgraph_set, &inputs, &entry_map](const nnvm::NodePtr &node){ if (subgraph_set.count(node.get())) { for (auto &e : node->inputs) { if (!subgraph_set.count(e.node.get())) { if (entry_map.count(e)) { e = entry_map[e]; } else { auto new_node = nnvm::Node::Create(); new_node->attrs.name = "input_" + std::to_string(inputs.size()); entry_map.insert({e, nnvm::NodeEntry{new_node, 0, 0}}); inputs.push_back(e); e.node = new_node; e.index = 0; } } } } }); // Fix ordering of w.r.t to topology Graph _g; _g.outputs = g.outputs; const auto &idx = _g.indexed_graph(); std::sort(inputs.begin(), inputs.end(), [&idx, &entry_map](const nnvm::NodeEntry lhs, const nnvm::NodeEntry rhs) { return idx.entry_id(entry_map.at(lhs)) < idx.entry_id(entry_map.at(rhs)); }); return inputs; } std::unordered_map<uint32_t, uint32_t> GetGraphInputsMap(const Graph& g) { std::unordered_map<uint32_t, uint32_t> outputs; auto& idx = g.indexed_graph(); outputs.reserve(idx.num_nodes()); std::vector<uint32_t> input_nodes = idx.input_nodes(); for (size_t i = 0; i < input_nodes.size(); ++i) { outputs[input_nodes[i]] = static_cast<uint32_t>(i); } return outputs; } } // namespace exec } // namespace mxnet <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/wtf_saver.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_WTF_SAVER_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_WTF_SAVER_H_ #include <string> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread.h" #include "third_party/tracing_framework_bindings_cpp/runtime.h" namespace minigo { class WtfSaver { public: explicit WtfSaver(std::string path, absl::Duration poll_interval); ~WtfSaver(); private: void Poll(); const std::string path_; wtf::Runtime::SaveOptions options_; wtf::Runtime::SaveCheckpoint checkpoint_; std::unique_ptr<Thread> poll_thread_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_WTF_SAVER_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/gemm_inner_product.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "ocl/ocl_stream.hpp" #include "ocl/gemm_inner_product.hpp" namespace mkldnn { namespace impl { namespace ocl { template <data_type_t src_type, data_type_t wei_type, data_type_t dst_type, data_type_t acc_type> status_t gemm_inner_product_fwd_t<src_type, wei_type, dst_type, acc_type>::execute_forward(const exec_ctx_t &ctx) const { exec_args_t gemm_args; gemm_args[MKLDNN_ARG_SRC_0] = ctx.args().at(MKLDNN_ARG_WEIGHTS); gemm_args[MKLDNN_ARG_SRC_1] = ctx.args().at(MKLDNN_ARG_SRC); gemm_args[MKLDNN_ARG_DST] = ctx.args().at(MKLDNN_ARG_DST); exec_ctx_t gemm_ctx(ctx.stream(), std::move(gemm_args)); status_t gemm_exec_status = gemm_->execute(gemm_ctx); if (gemm_exec_status != status::success) return gemm_exec_status; if (pd()->with_bias()) { auto &bias = CTX_IN_STORAGE(MKLDNN_ARG_BIAS); auto &dst = CTX_OUT_STORAGE(MKLDNN_ARG_DST); bias_kernel_.set_arg(0, bias); bias_kernel_.set_arg(1, dst); auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); auto nd_range = cl_nd_range_t({ pd()->MB() * pd()->OC() }); status_t bias_status = executor.parallel_for(nd_range, bias_kernel_); if (bias_status != status::success) return bias_status; } return status::success; } using namespace data_type; template struct gemm_inner_product_fwd_t<f16>; template struct gemm_inner_product_fwd_t<f32>; template <data_type_t diff_src_type, data_type_t wei_type, data_type_t diff_dst_type, data_type_t acc_type> status_t gemm_inner_product_bwd_data_t<diff_src_type, wei_type, diff_dst_type, acc_type>::execute_backward_data(const exec_ctx_t &ctx) const { exec_args_t gemm_args; gemm_args[MKLDNN_ARG_SRC_0] = ctx.args().at(MKLDNN_ARG_WEIGHTS); gemm_args[MKLDNN_ARG_SRC_1] = ctx.args().at(MKLDNN_ARG_DIFF_DST); gemm_args[MKLDNN_ARG_DST] = ctx.args().at(MKLDNN_ARG_DIFF_SRC); exec_ctx_t gemm_ctx(ctx.stream(), std::move(gemm_args)); status_t gemm_exec_status = gemm_->execute(gemm_ctx); if (gemm_exec_status != status::success) return gemm_exec_status; return status::success; } template struct gemm_inner_product_bwd_data_t<f32>; template <data_type_t data_type> status_t gemm_inner_product_bwd_weights_t<data_type>::execute_backward_weights( const exec_ctx_t &ctx) const { exec_args_t gemm_args; if (pd()->wei_tr()) { gemm_args[MKLDNN_ARG_SRC_0] = ctx.args().at(MKLDNN_ARG_DIFF_DST); gemm_args[MKLDNN_ARG_SRC_1] = ctx.args().at(MKLDNN_ARG_SRC); } else { gemm_args[MKLDNN_ARG_SRC_0] = ctx.args().at(MKLDNN_ARG_SRC); gemm_args[MKLDNN_ARG_SRC_1] = ctx.args().at(MKLDNN_ARG_DIFF_DST); } gemm_args[MKLDNN_ARG_DST] = ctx.args().at(MKLDNN_ARG_DIFF_WEIGHTS); exec_ctx_t gemm_ctx(ctx.stream(), std::move(gemm_args)); status_t gemm_exec_status = gemm_->execute(gemm_ctx); if (gemm_exec_status != status::success) return gemm_exec_status; if (pd()->with_bias()) { auto &diff_dst = CTX_IN_STORAGE(MKLDNN_ARG_DIFF_DST); auto &diff_bias = CTX_OUT_STORAGE(MKLDNN_ARG_DIFF_BIAS); bias_kernel_.set_arg(0, diff_dst); bias_kernel_.set_arg(1, diff_bias); auto &executor = *(utils::downcast<cl_stream_t *>(ctx.stream())->cl_executor()); auto nd_range = cl_nd_range_t({ pd()->OC() }); status_t bias_status = executor.parallel_for(nd_range, bias_kernel_); if (bias_status != status::success) return bias_status; } return status::success; } template struct gemm_inner_product_bwd_weights_t<f32>; } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/model/inference_cache.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/inference_cache.h" #include <tuple> #include "REDACTEDmemory/memory.h" namespace minigo { std::ostream& operator<<(std::ostream& os, InferenceCache::Key key) { return os << absl::StreamFormat("%016x:%016x", key.cache_hash_, key.stone_hash_); } InferenceCache::Key InferenceCache::Key::CreateTestKey( zobrist::Hash cache_hash, zobrist::Hash stone_hash) { InferenceCache::Key key; key.cache_hash_ = cache_hash; key.stone_hash_ = stone_hash; return key; } InferenceCache::Key::Key(Coord prev_move, symmetry::Symmetry canonical_sym, const Position& position) { cache_hash_ ^= zobrist::ToPlayHash(position.to_play()); if (prev_move == Coord::kPass) { cache_hash_ ^= zobrist::OpponentPassedHash(); } const auto& coord_symmetry = symmetry::kCoords[canonical_sym]; const auto& stones = position.stones(); for (int real_c = 0; real_c < kN * kN; ++real_c) { auto symmetric_c = coord_symmetry[real_c]; auto h = zobrist::MoveHash(symmetric_c, stones[real_c].color()); stone_hash_ ^= h; cache_hash_ ^= h; if (stones[real_c].color() == Color::kEmpty && !position.legal_move(real_c)) { cache_hash_ ^= zobrist::IllegalEmptyPointHash(symmetric_c); } } } InferenceCache::~InferenceCache() = default; std::ostream& operator<<(std::ostream& os, const InferenceCache::Stats& stats) { auto num_lookups = stats.num_hits + stats.num_complete_misses + stats.num_symmetry_misses; auto hit_rate = static_cast<float>(stats.num_hits) / static_cast<float>(num_lookups); auto full = static_cast<float>(stats.size) / static_cast<float>(stats.capacity); return os << "size:" << stats.size << " capacity:" << stats.capacity << " full:" << (100 * full) << "%" << " hits:" << stats.num_hits << " complete_misses:" << stats.num_complete_misses << " symmetry_misses:" << stats.num_symmetry_misses << " hit_rate:" << (100 * hit_rate) << "%"; } void NullInferenceCache::Clear() {} void NullInferenceCache::Merge(Key key, symmetry::Symmetry canonical_sym, symmetry::Symmetry inference_sym, ModelOutput* output) {} bool NullInferenceCache::TryGet(Key key, symmetry::Symmetry canonical_sym, symmetry::Symmetry inference_sym, ModelOutput* output) { stats_.num_complete_misses += 1; return false; } InferenceCache::Stats NullInferenceCache::GetStats() const { return stats_; } size_t BasicInferenceCache::CalculateCapacity(size_t size_mb) { // Minimum load factory of an absl::node_hash_map at the time of writing, // taken from https://abseil.io/docs/cpp/guides/container. // This is a pessimistic estimate of the cache's load factor but since the // size of each node pointer is much smaller than that of the node itself, it // shouldn't make that much difference either way. float load_factor = 0.4375; // absl::node_hash_map allocates each (key, value) pair on the heap and stores // pointers to those pairs in the table itself, along with one byte of hash // for each element. float element_size = sizeof(Map::value_type) + (sizeof(Map::value_type*) + 1) / load_factor; return static_cast<size_t>(size_mb * 1024.0f * 1024.0f / element_size); } BasicInferenceCache::BasicInferenceCache(size_t capacity) { MG_CHECK(capacity > 0); stats_.capacity = capacity; Clear(); } void BasicInferenceCache::Clear() { // Init the LRU list. list_.prev = &list_; list_.next = &list_; map_.clear(); } void BasicInferenceCache::Merge(Key key, symmetry::Symmetry canonical_sym, symmetry::Symmetry inference_sym, ModelOutput* output) { if (map_.size() == stats_.capacity) { // Cache is full, remove the last element from the LRU queue. auto it = map_.find(static_cast<Element*>(list_.prev)->key); MG_CHECK(it != map_.end()); Unlink(&it->second); map_.erase(it); stats_.size -= 1; } // Symmetry that converts the model output into canonical form. auto inverse_canonical_sym = symmetry::Inverse(canonical_sym); auto canonical_inference_sym = symmetry::Concat(inference_sym, inverse_canonical_sym); int sym_bit = (1 << canonical_inference_sym); auto result = map_.try_emplace(key, key, canonical_inference_sym); auto inserted = result.second; auto* elem = &result.first->second; if (inserted) { // Transform the model output into canonical form. Model::ApplySymmetry(inverse_canonical_sym, *output, &elem->output); elem->valid_symmetry_bits = sym_bit; elem->num_valid_symmetries = 1; stats_.size += 1; } else { // The element was already in the cache. Unlink(elem); if ((elem->valid_symmetry_bits & sym_bit) == 0) { const auto& coord_symmetry = symmetry::kCoords[inverse_canonical_sym]; // This is a new symmetry for this key: merge it in. float n = static_cast<float>(elem->num_valid_symmetries); float a = n / (n + 1); float b = 1 / (n + 1); auto& cached = elem->output; for (size_t i = 0; i < kNumMoves; ++i) { cached.policy[i] = a * cached.policy[i] + b * output->policy[coord_symmetry[i]]; } cached.value = a * cached.value + b * output->value; elem->valid_symmetry_bits |= sym_bit; elem->num_valid_symmetries += 1; } Model::ApplySymmetry(canonical_sym, elem->output, output); } PushFront(elem); } bool BasicInferenceCache::TryGet(Key key, symmetry::Symmetry canonical_sym, symmetry::Symmetry inference_sym, ModelOutput* output) { auto it = map_.find(key); if (it == map_.end()) { stats_.num_complete_misses += 1; return false; } auto* elem = &it->second; Unlink(elem); PushFront(elem); // Symmetry that converts the model output into canonical form. auto inverse_canonical_sym = symmetry::Inverse(canonical_sym); auto canonical_inference_sym = symmetry::Concat(inference_sym, inverse_canonical_sym); int sym_bit = (1 << canonical_inference_sym); if ((elem->valid_symmetry_bits & sym_bit) == 0) { // We have some symmetries for this position, just not the one requested. stats_.num_symmetry_misses += 1; return false; } Model::ApplySymmetry(canonical_sym, elem->output, output); stats_.num_hits += 1; return true; } BasicInferenceCache::Stats BasicInferenceCache::GetStats() const { return stats_; } ThreadSafeInferenceCache::ThreadSafeInferenceCache(size_t total_capacity, int num_shards) { shards_.reserve(num_shards); size_t shard_capacity_sum = 0; for (int i = 0; i < num_shards; ++i) { auto a = i * total_capacity / num_shards; auto b = (i + 1) * total_capacity / num_shards; auto shard_capacity = b - a; shard_capacity_sum += shard_capacity; shards_.push_back(absl::make_unique<Shard>(shard_capacity)); } MG_CHECK(shard_capacity_sum == total_capacity); } void ThreadSafeInferenceCache::Clear() { for (auto& shard : shards_) { absl::MutexLock lock(&shard->mutex); shard->cache.Clear(); } } void ThreadSafeInferenceCache::Merge(Key key, symmetry::Symmetry canonical_sym, symmetry::Symmetry inference_sym, ModelOutput* output) { auto* shard = shards_[key.Shard(shards_.size())].get(); absl::MutexLock lock(&shard->mutex); shard->cache.Merge(key, canonical_sym, inference_sym, output); } bool ThreadSafeInferenceCache::TryGet(Key key, symmetry::Symmetry canonical_sym, symmetry::Symmetry inference_sym, ModelOutput* output) { auto* shard = shards_[key.Shard(shards_.size())].get(); absl::MutexLock lock(&shard->mutex); return shard->cache.TryGet(key, canonical_sym, inference_sym, output); } InferenceCache::Stats ThreadSafeInferenceCache::GetStats() const { Stats result; for (auto& shard : shards_) { absl::MutexLock lock(&shard->mutex); auto s = shard->cache.GetStats(); result.size += s.size; result.capacity += s.capacity; result.num_hits += s.num_hits; result.num_complete_misses += s.num_complete_misses; result.num_symmetry_misses += s.num_symmetry_misses; } return result; } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/cl_executor.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CL_EXECUTOR_HPP #define CL_EXECUTOR_HPP #include "common/c_types_map.hpp" #include "ocl/ocl_utils.hpp" namespace mkldnn { namespace impl { namespace ocl { // Executor provides OpenCL-like functionality whose implementation // is specific for a given stream. struct cl_executor_t { cl_executor_t(stream_t *stream) : stream_(stream) {} virtual ~cl_executor_t() = default; stream_t *stream() { return stream_; } virtual status_t parallel_for( const cl_nd_range_t &range, const ocl_kernel_t &kernel) = 0; virtual status_t copy(const memory_storage_t &src, const memory_storage_t &dst, size_t size) = 0; private: stream_t *stream_; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/common/float16.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef FLOAT16_HPP #define FLOAT16_HPP #include <cmath> #include <cstdint> #include <limits> #include <type_traits> namespace mkldnn { namespace impl { namespace f16_support { struct float16_t { uint16_t raw; constexpr float16_t(uint16_t raw, bool) : raw(raw) {} float16_t() = default; float16_t(float f) { (*this) = f; } float16_t &operator=(float f); operator float() const; float f() { return (float)(*this); } float16_t &operator+=(float16_t a) { (*this) = float(f() + a.f()); return *this; } }; static_assert(sizeof(float16_t) == 2, "float16_t must be 2 bytes"); union float_raw { float f; uint32_t i; }; static inline uint32_t float_to_raw(float f) { float_raw r; r.f = f; return r.i; } static inline float raw_to_float(uint32_t i) { float_raw r; r.i = i; return r.f; } inline float16_t &float16_t::operator=(float f) { uint32_t i = float_to_raw(f); uint32_t s = i >> 31; uint32_t e = (i >> 23) & 0xFF; uint32_t m = i & 0x7FFFFF; uint32_t ss = s; uint32_t mm = m >> 13; uint32_t r = m & 0x1FFF; uint32_t ee = 0; int32_t eee = (e - 127) + 15; if (e == 0) { // Denormal/zero floats all become zero. ee = 0; mm = 0; } else if (e == 0xFF) { // Preserve inf/nan. ee = 0x1F; if (m != 0 && mm == 0) mm = 1; } else if (eee > 0 && eee < 0x1F) { // Normal range. Perform round to even on mantissa. ee = eee; if (r > (0x1000 - (mm & 1))) { // Round up. mm++; if (mm == 0x400) { // Rounds up to next dyad (or inf). mm = 0; ee++; } } } else if (eee >= 0x1F) { // Overflow. ee = 0x1F; mm = 0; } else { // Underflow. Scale the input float, converting it // into an equivalent denormal. float ff = f * raw_to_float(0x01000000); uint32_t ii = float_to_raw(ff); ee = 0; mm = ii; } this->raw = (ss << 15) | (ee << 10) | mm; return *this; } inline float16_t::operator float() const { uint32_t ss = raw >> 15; uint32_t ee = (raw >> 10) & 0x1F; uint32_t mm = raw & 0x3FF; uint32_t s = ss; uint32_t eee = ee - 15 + 127; uint32_t m = mm << 13; uint32_t e; if (ee == 0) { if (mm == 0) e = 0; else { // Half denormal -> float normal return (ss ? -1 : 1) * std::scalbn((float)mm, -24); } } else if (ee == 0x1F) { // inf/nan e = 0xFF; } else e = eee; uint32_t f = (s << 31) | (e << 23) | m; return raw_to_float(f); } } // namespace f16_support using f16_support::float16_t; } // namespace impl } // namespace mkldnn #endif <|start_filename|>NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/ROIAlign_cuda.cu<|end_filename|> // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <THC/THC.h> #include <THC/THCAtomics.cuh> #include <THC/THCDeviceUtils.cuh> // TODO make it in a common file #define CUDA_1D_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; \ i += blockDim.x * gridDim.x) template <typename U, typename T> __device__ T bilinear_interpolate(const U* bottom_data, const int height, const int width, T y, T x, const int index /* index for debug only*/) { // deal with cases that inverse elements are out of feature map boundary if (y < -1.0 || y > height || x < -1.0 || x > width) { //empty return 0; } if (y <= 0) y = 0; if (x <= 0) x = 0; int y_low = (int) y; int x_low = (int) x; int y_high; int x_high; if (y_low >= height - 1) { y_high = y_low = height - 1; y = (T) y_low; } else { y_high = y_low + 1; } if (x_low >= width - 1) { x_high = x_low = width - 1; x = (T) x_low; } else { x_high = x_low + 1; } T ly = y - y_low; T lx = x - x_low; T hy = 1. - ly, hx = 1. - lx; // do bilinear interpolation T v1 = bottom_data[y_low * width + x_low]; T v2 = bottom_data[y_low * width + x_high]; T v3 = bottom_data[y_high * width + x_low]; T v4 = bottom_data[y_high * width + x_high]; T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx; T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } // rois in math type (float). This is because ROIs come in as float. // TODO: Change other blocks producing ROI to support half type as well template <typename U, typename T> __global__ void RoIAlignForward(const int nthreads, const U* bottom_data, const T spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int sampling_ratio, const T* bottom_rois, U* top_data) { CUDA_1D_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int c = (index / pooled_width / pooled_height) % channels; int n = index / pooled_width / pooled_height / channels; const T* offset_bottom_rois = bottom_rois + n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Do not using rounding; this implementation detail is critical T roi_start_w = offset_bottom_rois[1] * spatial_scale; T roi_start_h = offset_bottom_rois[2] * spatial_scale; T roi_end_w = offset_bottom_rois[3] * spatial_scale; T roi_end_h = offset_bottom_rois[4] * spatial_scale; // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); // Force malformed ROIs to be 1x1 T roi_width = max(roi_end_w - roi_start_w, (T)1.); T roi_height = max(roi_end_h - roi_start_h, (T)1.); T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height); T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width); const U* offset_bottom_data = bottom_data + (roi_batch_ind * channels + c) * height * width; // We use roi_bin_grid to sample the grid and mimic integral int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); // We do average (integral) pooling inside a bin const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 T output_val = 0.; for (int iy = 0; iy < roi_bin_grid_h; iy ++) // e.g., iy = 0, 1 { const T y = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5 for (int ix = 0; ix < roi_bin_grid_w; ix ++) { const T x = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w); T val = bilinear_interpolate(offset_bottom_data, height, width, y, x, index); output_val += val; } } output_val /= count; top_data[index] = output_val; } } template <typename U, typename T> __device__ T bilinear_interpolate_nhwc(const U* bottom_data, const int height, const int width, const int channels, T y, T x, const int index /* index for debug only*/) { // deal with cases that inverse elements are out of feature map boundary if (y < -1.0 || y > height || x < -1.0 || x > width) { //empty return 0; } if (y <= 0) y = 0; if (x <= 0) x = 0; int y_low = (int) y; int x_low = (int) x; int y_high; int x_high; if (y_low >= height - 1) { y_high = y_low = height - 1; y = (T) y_low; } else { y_high = y_low + 1; } if (x_low >= width - 1) { x_high = x_low = width - 1; x = (T) x_low; } else { x_high = x_low + 1; } T ly = y - y_low; T lx = x - x_low; T hy = 1. - ly, hx = 1. - lx; // do bilinear interpolation T v1 = bottom_data[channels * (y_low * width + x_low)]; T v2 = bottom_data[channels * (y_low * width + x_high)]; T v3 = bottom_data[channels * (y_high * width + x_low)]; T v4 = bottom_data[channels * (y_high * width + x_high)]; T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx; T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } // rois in math type (float). This is because ROIs come in as float. // TODO: Change other blocks producing ROI to support half type as well template <typename U, typename T> __global__ void RoIAlignForwardNHWC(const int nthreads, const U* bottom_data, const T spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int sampling_ratio, const T* bottom_rois, U* top_data) { CUDA_1D_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int c = index % channels; int pw = (index / channels) % pooled_width; int ph = (index / channels / pooled_width) % pooled_height; int n = index / pooled_width / pooled_height / channels; const T* offset_bottom_rois = bottom_rois + n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Do not using rounding; this implementation detail is critical T roi_start_w = offset_bottom_rois[1] * spatial_scale; T roi_start_h = offset_bottom_rois[2] * spatial_scale; T roi_end_w = offset_bottom_rois[3] * spatial_scale; T roi_end_h = offset_bottom_rois[4] * spatial_scale; // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); // Force malformed ROIs to be 1x1 T roi_width = max(roi_end_w - roi_start_w, (T)1.); T roi_height = max(roi_end_h - roi_start_h, (T)1.); T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height); T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width); const U* offset_bottom_data = bottom_data + (roi_batch_ind * channels * height * width + c); // We use roi_bin_grid to sample the grid and mimic integral int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); // We do average (integral) pooling inside a bin const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 T output_val = 0.; for (int iy = 0; iy < roi_bin_grid_h; iy ++) // e.g., iy = 0, 1 { const T y = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5 for (int ix = 0; ix < roi_bin_grid_w; ix ++) { const T x = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w); T val = bilinear_interpolate_nhwc(offset_bottom_data, height, width, channels, y, x, index); output_val += val; } } output_val /= count; top_data[index] = output_val; } } template <typename T> __device__ void bilinear_interpolate_gradient( const int height, const int width, T y, T x, T & w1, T & w2, T & w3, T & w4, int & x_low, int & x_high, int & y_low, int & y_high, const int index /* index for debug only*/) { // deal with cases that inverse elements are out of feature map boundary if (y < -1.0 || y > height || x < -1.0 || x > width) { //empty w1 = w2 = w3 = w4 = 0.; x_low = x_high = y_low = y_high = -1; return; } if (y <= 0) y = 0; if (x <= 0) x = 0; y_low = (int) y; x_low = (int) x; if (y_low >= height - 1) { y_high = y_low = height - 1; y = (T) y_low; } else { y_high = y_low + 1; } if (x_low >= width - 1) { x_high = x_low = width - 1; x = (T) x_low; } else { x_high = x_low + 1; } T ly = y - y_low; T lx = x - x_low; T hy = 1. - ly, hx = 1. - lx; // reference in forward // T v1 = bottom_data[y_low * width + x_low]; // T v2 = bottom_data[y_low * width + x_high]; // T v3 = bottom_data[y_high * width + x_low]; // T v4 = bottom_data[y_high * width + x_high]; // T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx; return; } template <typename U, typename T> __global__ void RoIAlignBackwardFeature(const int nthreads, const U* top_diff, const int num_rois, const T spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int sampling_ratio, U* bottom_diff, const T* bottom_rois) { CUDA_1D_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int c = (index / pooled_width / pooled_height) % channels; int n = index / pooled_width / pooled_height / channels; const T* offset_bottom_rois = bottom_rois + n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Do not using rounding; this implementation detail is critical T roi_start_w = offset_bottom_rois[1] * spatial_scale; T roi_start_h = offset_bottom_rois[2] * spatial_scale; T roi_end_w = offset_bottom_rois[3] * spatial_scale; T roi_end_h = offset_bottom_rois[4] * spatial_scale; // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); // Force malformed ROIs to be 1x1 T roi_width = max(roi_end_w - roi_start_w, (T)1.); T roi_height = max(roi_end_h - roi_start_h, (T)1.); T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height); T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width); U* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels + c) * height * width; int top_offset = (n * channels + c) * pooled_height * pooled_width; const U* offset_top_diff = top_diff + top_offset; const T top_diff_this_bin = offset_top_diff[ph * pooled_width + pw]; // We use roi_bin_grid to sample the grid and mimic integral int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); // We do average (integral) pooling inside a bin const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 for (int iy = 0; iy < roi_bin_grid_h; iy ++) // e.g., iy = 0, 1 { const T y = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5 for (int ix = 0; ix < roi_bin_grid_w; ix ++) { const T x = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w); T w1, w2, w3, w4; int x_low, x_high, y_low, y_high; bilinear_interpolate_gradient(height, width, y, x, w1, w2, w3, w4, x_low, x_high, y_low, y_high, index); T g1 = top_diff_this_bin * w1 / count; T g2 = top_diff_this_bin * w2 / count; T g3 = top_diff_this_bin * w3 / count; T g4 = top_diff_this_bin * w4 / count; if (x_low >= 0 && x_high >= 0 && y_low >= 0 && y_high >= 0) { atomicAdd(offset_bottom_diff + y_low * width + x_low, static_cast<T>(g1)); atomicAdd(offset_bottom_diff + y_low * width + x_high, static_cast<T>(g2)); atomicAdd(offset_bottom_diff + y_high * width + x_low, static_cast<T>(g3)); atomicAdd(offset_bottom_diff + y_high * width + x_high, static_cast<T>(g4)); } // if } // ix } // iy } // CUDA_1D_KERNEL_LOOP } // RoIAlignBackward template <typename U, typename T> __global__ void RoIAlignBackwardFeatureNHWC(const int nthreads, const U* top_diff, const int num_rois, const T spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int sampling_ratio, U* bottom_diff, const T* bottom_rois) { CUDA_1D_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int c = index % channels; int pw = (index / channels) % pooled_width; int ph = (index / channels / pooled_width) % pooled_height; int n = index / pooled_width / pooled_height / channels; const T* offset_bottom_rois = bottom_rois + n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Do not using rounding; this implementation detail is critical T roi_start_w = offset_bottom_rois[1] * spatial_scale; T roi_start_h = offset_bottom_rois[2] * spatial_scale; T roi_end_w = offset_bottom_rois[3] * spatial_scale; T roi_end_h = offset_bottom_rois[4] * spatial_scale; // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); // Force malformed ROIs to be 1x1 T roi_width = max(roi_end_w - roi_start_w, (T)1.); T roi_height = max(roi_end_h - roi_start_h, (T)1.); T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height); T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width); U* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels * height * width + c); int top_offset = n * channels * pooled_height * pooled_width + c; const U* offset_top_diff = top_diff + top_offset; const T top_diff_this_bin = offset_top_diff[channels * (ph * pooled_width + pw)]; // We use roi_bin_grid to sample the grid and mimic integral int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); // We do average (integral) pooling inside a bin const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 for (int iy = 0; iy < roi_bin_grid_h; iy ++) // e.g., iy = 0, 1 { const T y = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5 for (int ix = 0; ix < roi_bin_grid_w; ix ++) { const T x = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w); T w1, w2, w3, w4; int x_low, x_high, y_low, y_high; bilinear_interpolate_gradient(height, width, y, x, w1, w2, w3, w4, x_low, x_high, y_low, y_high, index); T g1 = top_diff_this_bin * w1 / count; T g2 = top_diff_this_bin * w2 / count; T g3 = top_diff_this_bin * w3 / count; T g4 = top_diff_this_bin * w4 / count; if (x_low >= 0 && x_high >= 0 && y_low >= 0 && y_high >= 0) { atomicAdd(offset_bottom_diff + channels * (y_low * width + x_low), static_cast<T>(g1)); atomicAdd(offset_bottom_diff + channels * (y_low * width + x_high), static_cast<T>(g2)); atomicAdd(offset_bottom_diff + channels * (y_high * width + x_low), static_cast<T>(g3)); atomicAdd(offset_bottom_diff + channels * (y_high * width + x_high), static_cast<T>(g4)); } // if } // ix } // iy } // CUDA_1D_KERNEL_LOOP } // RoIAlignBackward at::Tensor ROIAlign_forward_cuda(const at::Tensor& input, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int sampling_ratio, const bool is_nhwc) { AT_ASSERTM(input.is_cuda(), "input must be a CUDA tensor"); AT_ASSERTM(rois.is_cuda(), "rois must be a CUDA tensor"); auto num_rois = rois.size(0); auto channels = is_nhwc ? input.size(3) : input.size(1); auto height = is_nhwc ? input.size(1) : input.size(2); auto width = is_nhwc ? input.size(2) : input.size(3); auto output = is_nhwc ? at::empty({num_rois, pooled_height, pooled_width, channels}, input.options()) : at::empty({num_rois, channels, pooled_height, pooled_width}, input.options()); auto output_size = num_rois * pooled_height * pooled_width * channels; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (output.numel() == 0) { THCudaCheck(cudaGetLastError()); return output; } int gridSize; int blockSize; cudaOccupancyMaxPotentialBlockSize(&gridSize, &blockSize, (void*) RoIAlignForward<float, float>, 0, // dynamic memory 0); // maximum utilized threads dim3 grid(gridSize); dim3 block(blockSize); //TODO: Math type is hard coded to float assuming double is not used, if needed, add a case for double as well. //In case of double, it should be <double, double>, not <double, float> //TODO: ROIs come in as float, fix other blocks so they come in as same type as input. if (!is_nhwc){ AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "ROIAlign_forward", [&] { RoIAlignForward<scalar_t, float><<<grid, block, 0, stream>>>( output_size, input.contiguous().data_ptr<scalar_t>(), spatial_scale, channels, height, width, pooled_height, pooled_width, sampling_ratio, rois.contiguous().data_ptr<float>(), output.data_ptr<scalar_t>()); }); } else{ AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "ROIAlign_forward", [&] { RoIAlignForwardNHWC<scalar_t, float><<<grid, block, 0, stream>>>( output_size, input.contiguous().data_ptr<scalar_t>(), spatial_scale, channels, height, width, pooled_height, pooled_width, sampling_ratio, rois.contiguous().data_ptr<float>(), output.data_ptr<scalar_t>()); }); } THCudaCheck(cudaGetLastError()); return output; } // TODO remove the dependency on input and use instead its sizes -> save memory // NHWC + layout transposes are faster than NCHW, so just keep the NHWC implementation for backward pass at::Tensor ROIAlign_backward_cuda(const at::Tensor& grad, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int batch_size, const int channels, const int height, const int width, const int sampling_ratio, const bool is_nhwc) { AT_ASSERTM(grad.is_cuda(), "grad must be a CUDA tensor"); AT_ASSERTM(rois.is_cuda(), "rois must be a CUDA tensor"); auto num_rois = rois.size(0); auto grad_input = is_nhwc ? at::zeros({batch_size, height, width, channels}, grad.options()) : at::zeros({batch_size, channels, height, width}, grad.options()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); // handle possibly empty gradients if (grad.numel() == 0) { THCudaCheck(cudaGetLastError()); return grad_input; } int gridSize; int blockSize; cudaOccupancyMaxPotentialBlockSize(&gridSize, &blockSize, (void*) RoIAlignBackwardFeature<float, float>, 0, // dynamic memory 0); // maximum utilized threads dim3 grid(gridSize); dim3 block(blockSize); //TODO: Math type is hard coded to float assuming double is not used, if needed, add a case for double as well. //In case of double, it should be <double, double>, not <double, float> //TODO: ROIs come in as float, fix other blocks so they come in as same type as input. if (!is_nhwc){ AT_DISPATCH_FLOATING_TYPES_AND_HALF(grad.scalar_type(), "ROIAlign_backward", [&] { RoIAlignBackwardFeature<scalar_t, float><<<grid, block, 0, stream>>>( grad.numel(), grad.contiguous().data_ptr<scalar_t>(), num_rois, spatial_scale, channels, height, width, pooled_height, pooled_width, sampling_ratio, grad_input.data_ptr<scalar_t>(), rois.contiguous().data_ptr<float>()); }); } else{ AT_DISPATCH_FLOATING_TYPES_AND_HALF(grad.scalar_type(), "ROIAlign_backward", [&] { RoIAlignBackwardFeatureNHWC<scalar_t, float><<<grid, block, 0, stream>>>( grad.numel(), grad.contiguous().data_ptr<scalar_t>(), num_rois, spatial_scale, channels, height, width, pooled_height, pooled_width, sampling_ratio, grad_input.data_ptr<scalar_t>(), rois.contiguous().data_ptr<float>()); }); } THCudaCheck(cudaGetLastError()); return grad_input; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/jit_simple_sum_kernel.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef JIT_SIMPLE_SUM_KERNEL_HPP #define JIT_SIMPLE_SUM_KERNEL_HPP #include "common/c_types_map.hpp" #include "ocl/jit_primitive_conf.hpp" namespace mkldnn { namespace impl { namespace ocl { struct jit_simple_sum_kernel { jit_simple_sum_kernel(jit_simple_sum_conf_t ajss) : jss(ajss){}; ~jit_simple_sum_kernel(){}; static status_t init_conf( jit_simple_sum_conf_t &jss, const memory_desc_t *data_d) { return status::success; }; static status_t init_const_def( ocl_jit_t &jit, const jit_simple_sum_conf_t &jss) { return status::success; } jit_simple_sum_conf_t jss; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/sgf.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_SGF_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_SGF_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "REDACTEDstrings/string_view.h" #include "REDACTEDtypes/span.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/color.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/coord.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/move.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" namespace minigo { namespace sgf { constexpr char kProgramIdentifier[] = "Minigo"; // Abstract syntax tree for an SGF file. // The Ast class just holds the structure and contents of the tree and doesn't // infer any meaning from the property IDs or values. class Ast { public: struct Property { std::string ToString() const; std::string id; std::vector<std::string> values; }; struct Node { std::string ToString() const; const Property* FindProperty(absl::string_view id) const; std::vector<Property> properties; }; struct Tree { std::string ToString() const; std::vector<Node> nodes; std::vector<Tree> children; }; // Parses the SGF file. MG_WARN_UNUSED_RESULT bool Parse(std::string contents); // Returns a non-empty string containing error information if the most recent // call to Parse returned false. const std::string& error() const { return error_; } const std::vector<Tree>& trees() const { return trees_; } private: std::string error_; std::vector<Tree> trees_; std::string contents_; }; // TODO(tommadams): Replace sgf::MoveWithComment with sgf::Node. // A single move with a (possibly empty) comment. struct MoveWithComment { MoveWithComment() = default; MoveWithComment(Move move, std::string comment) : move(move), comment(std::move(comment)) {} MoveWithComment(Color color, Coord c, std::string comment) : move(color, c), comment(std::move(comment)) {} // MoveWithComment is convertible to a Move for ease of use. operator Move() const { return move; } Move move; std::string comment; bool operator==(const MoveWithComment& other) const { return move == other.move && comment == other.comment; } }; std::ostream& operator<<(std::ostream& ios, const MoveWithComment& move); struct Node { Node(Move move, std::string comment) : move(move), comment(std::move(comment)) {} // Returns a flattened copy of the main line moves: the chain of moves formed // by this node and its left-most descendants. std::vector<Move> ExtractMainLine() const; const Move move; std::string comment; std::vector<std::unique_ptr<Node>> children; }; struct CreateSgfOptions { std::string black_name = kProgramIdentifier; std::string white_name = kProgramIdentifier; std::string ruleset = "Chinese"; float komi = 7.5; std::string result; std::string game_comment; }; // Returns a valid SGF file for the given move sequence. std::string CreateSgfString(absl::Span<const MoveWithComment> moves, const CreateSgfOptions& options); // Extracts the complete game trees from an SGF AST. MG_WARN_UNUSED_RESULT bool GetTrees(const Ast& ast, std::vector<std::unique_ptr<Node>>* trees); } // namespace sgf } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_SGF_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/simple_partition_pass.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file simple_partition_pass.h * \brief Simple pass for partitioning a graph. * \author <NAME> */ #ifndef MXNET_EXECUTOR_SIMPLE_PARTITION_PASS_H_ #define MXNET_EXECUTOR_SIMPLE_PARTITION_PASS_H_ #include <mxnet/base.h> #include <mxnet/op_attr_types.h> #include <mxnet/operator.h> #include <nnvm/graph_attr_types.h> #include <utility> #include <deque> #include <algorithm> #include <vector> #include "exec_pass.h" #include "bidirectional_graph.h" namespace mxnet { namespace exec { using NodeEntrySet = std::unordered_set<nnvm::NodeEntry, nnvm::NodeEntryHash, nnvm::NodeEntryEqual>; using NodeRawPtrSet = std::unordered_set<nnvm::Node*>; /*! * \brief Get the output nodes of the subgraph in the main graph. * \return a map between the node in the main graph and the output index of the subgraph node */ nnvm::NodeEntryMap<uint32_t> GetSubgraphOutputs(Graph g, NodeRawPtrSet subgraph_set); /*! * \brief Create new input nodes of the subgraph and plug them. * \return the inputs of the subgraph node in the main graph */ std::vector<nnvm::NodeEntry> GetSubgraphInputs(Graph g, NodeRawPtrSet subgraph_set); std::unordered_map<uint32_t, uint32_t> GetGraphInputsMap(const Graph& g); /*! * \brief Helper function to display what nodes are in a specific subset. */ inline void dispNodesSet(Graph g, NodeRawPtrSet s) { DFSVisit(g.outputs, [&s](const nnvm::NodePtr n) { if (s.count(n.get())) { std::cout << " Y " << n->attrs.name << std::endl; } else { std::cout << " N " << n->attrs.name << std::endl; } }); } /*! * \brief Replace a set of nodes by a subgraph node. */ template<typename FCreateNode> Graph ReplaceSubgraphs(Graph&& g, const std::vector<NodeRawPtrSet>& subgraph_sets, FCreateNode create_subgraph_node) { for (auto subgraph_set : subgraph_sets) { // Create MXNet subgraph Graph subgraph; const auto sub_outputs_in_main = GetSubgraphOutputs(g, subgraph_set); subgraph.outputs.resize(sub_outputs_in_main.size()); for (auto p : sub_outputs_in_main) { subgraph.outputs[p.second] = p.first; } // To generate a subgraph an input has to be replaced by data node (no op) // and it has to be agnostic to the node from which it's an output // (For example, even if two inputs are two different outputs from the same node, // they need to be replaced by two completely separate data nodes) auto inputs = GetSubgraphInputs(subgraph, subgraph_set); auto subgraph_node = create_subgraph_node(subgraph); subgraph_node->inputs = inputs; // replug inputs of node out of subgraph to be output of the subgraph node // if it was a node in the subgraph DFSVisit(g.outputs, [&subgraph_node, &subgraph_set, &sub_outputs_in_main](const nnvm::NodePtr node) { if (!subgraph_set.count(node.get())) { for (auto &e : node->inputs) { auto it = sub_outputs_in_main.find(e); if (it != sub_outputs_in_main.end()) { e.node = subgraph_node; e.index = it->second; } } } }); // replug outputs of the graph to be output of the subgraph node // if it was a node in the subgraph for (auto &e : g.outputs) { auto it = sub_outputs_in_main.find(e); if (it != sub_outputs_in_main.end()) { e.node = subgraph_node; e.index = it->second; } } // move control dependencies between nodes of the subgraph and out of the subgraph // to a dependencies between the subgraph node and the nodes out of the subgraph DFSVisit(g.outputs, [&subgraph_node, &subgraph_set](const nnvm::NodePtr& node) { for (auto &e : node->control_deps) { if (subgraph_set.count(e.get())) e = subgraph_node; } }); DFSVisit(subgraph.outputs, [&subgraph_node, &subgraph_set](const nnvm::NodePtr& node) { auto it = node->control_deps.begin(); while (it != node->control_deps.end()) { if (subgraph_set.count(it->get())) { ++it; } else { subgraph_node->control_deps.push_back(*it); it = node->control_deps.erase(it); } } }); } Graph new_graph; new_graph.outputs = g.outputs; return new_graph; } /* \brief Get all subsets of nodes, where: * - graph constructed from nodes in each subset is a connected graph * - every node fulfills a predicate is_compatible * - if nodes u and v are part of a subset, then for each path between * u and v in the original directed graph, all nodes on those paths * are also part of the subset * \param g NNVM graph * \param is_compatible A function taking nnvm::Node* and returning bool * which identifies which nodes should be included in * subsets. */ template<typename FCompatible> std::vector<NodeRawPtrSet> GetCompatibleSubsets(Graph* g, FCompatible is_compatible) { BidirectionalGraph<> biG(g); std::vector<std::unordered_set<BidirectionalGraph<>::Node*>> subsets = biG.get_subsets(is_compatible); std::vector<NodeRawPtrSet> nnvm_subsets; nnvm_subsets.reserve(subsets.size()); for (auto& subset : subsets) { if (subset.size() > 1) { NodeRawPtrSet node_set; node_set.reserve(subset.size()); for (auto& n : subset) { node_set.insert(n->nnvmptr); } nnvm_subsets.push_back(node_set); } } return nnvm_subsets; } } // namespace exec } // namespace mxnet #endif // MXNET_EXECUTOR_SIMPLE_PARTITION_PASS_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/c_api/c_api_gpuipc.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file c_api_gpuipc.cc * \brief auxilary functions to initialize GPU Inter-Process-Communication * \author <NAME> */ #include <cuda.h> #include <stdio.h> #include <mxnet/base.h> #include <mxnet/c_api.h> #include <nnvm/c_api.h> #include <nnvm/pass.h> #include <nnvm/pass_functions.h> #include "./c_api_common.h" #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess && __err != cudaErrorPeerAccessAlreadyEnabled) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) namespace gpuipc { // from: src/operator/nn/cudnn/nhwc_batch_norm_kernel.h // The number of threads per pixel. const int THREADS_PER_PIXEL = 16; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The number of reducing ops, each uses its own space : mean, var, dscale, dbias const int REDUCE_OPS = 4; // Maximum block.y supported - limited due to buffer allocation const int MAX_BLOCK_Y = 256; const int MAX_OFFSET = REDUCE_OPS*MAX_BLOCK_Y; const int BYTES_PER_ELEM = 4; // Buffer size per sync step const int SINGLE_SYNC_BUFFER_BYTES = MAX_OFFSET*THREADS_PER_PIXEL*(1+ELEMENTS_PER_LDG)*BYTES_PER_ELEM; }; // namespace gpuipc // Initialize IPC exchange buffers on GPUs 0..gpus. Turn on peer access for GPUs expected // to communicate. This function would be used to initialize exchange buffers for group BN // in case of a single process driving multiple GPUs. // // input : // gpus - number of gpus used by the process (not the group size) // sync_steps - number of group synchronization steps. Effectively = log2(group_size) // // output : // xbuf_ptr - a preallocated array of void_ptr is filled in with buffer pointers // such that xbuf_ptr[i] would contain the pointer for buffer allocated on GPU i // // FIXME: pass gpus as a list? Currently will assume GPUs 0..gpus participate // int MXInitXBuf(int gpus, int sync_steps, void** xbuf_ptr) { const int buffer_size = sync_steps*gpuipc::SINGLE_SYNC_BUFFER_BYTES; for (int i=0; i < gpus; ++i) { uint8_t *data; cudaCheckErrors("MXInitXBuf"); cudaSetDevice(i); cudaCheckErrors("MXInitXBuf: set device"); for (int j=0; j < sync_steps; ++j) { cudaDeviceEnablePeerAccess(i^(1 << j), 0); cudaCheckErrors("MXInitXBuf: enable p2p"); } cudaMalloc(&data, buffer_size); cudaMemset(data, 0, buffer_size); cudaCheckErrors("MXInitXBuf: malloc/memset"); cudaIpcMemHandle_t my_handle; cudaIpcGetMemHandle(&my_handle, data); xbuf_ptr[i] = data; } return 0; } // Initialize IPC exchange buffers on a single GPU. Turn on peer access for GPUs expected // to communicate. This function would be used to initialize exchange buffers for group BN // in case of a GPU per process. // // input : // gpu_id - id of gpu used by the process // sync_steps - number of group synchronization steps. Effectively = log2(group_size) // // output : // xbuf_ptr - a preallocated array of void_ptr is filled in with buffer pointers // such that xbuf_ptr[i] would contain the pointer for buffer allocated on GPU i. // All other entries remain unchanged // hndl_ptr - a pointer to cudaIpcMemHandle_t buffer. Will be filled in with // handle information of allocated buffer // int MXInitXBufSingle(int gpu_id, int sync_steps, void** xbuf_ptr, void* hndl_ptr) { const int buffer_size = sync_steps*gpuipc::SINGLE_SYNC_BUFFER_BYTES; uint8_t *data; cudaCheckErrors("MXInitXBufSingle: init"); cudaSetDevice(gpu_id); cudaCheckErrors("MXInitXBufSingle: set device"); for (int j=0; j < sync_steps; ++j) { cudaDeviceEnablePeerAccess(gpu_id^(1 << j), 0); cudaCheckErrors("MXInitXBufSingle: enable p2p"); } cudaMalloc(&data, buffer_size); cudaMemset(data, 0, buffer_size); cudaCheckErrors("MXInitXBufSingle: malloc/memset"); cudaIpcMemHandle_t my_handle; cudaIpcGetMemHandle(&my_handle, data); cudaCheckErrors("MXInitXBufSingle: get handle"); xbuf_ptr[gpu_id] = data; memcpy(hndl_ptr, (unsigned char *)(&my_handle), sizeof(my_handle)); return 0; } // Initialize IPC exchange buffers from IPC handles list. // This function would be used to initialize exchange buffers for group BN in case of a // GPU per process. For any GPU [i] that is expected to communicate with current GPU, will // open IPC handle from hndl_ptr[i] and store a pointer to local reflected buffer to xbuf_ptr[i]. // This function concludes the process of establishing exchange buffers in process per GPU // environment after this function xbuf_ptr will obtain buffers for exchange with other GPUs // similarly to the condition after calling MXInitXBuf in case of a single process. // // input : // gpu_id - id of gpu used by the process // gpus - number of gpus used by the process (not the group size) // sync_steps - number of group syncronization steps. Effectively = log2(group_size) // hndl_ptr - array of pointer to cudaIpcMemHandle_t buffers received from other GPUs // // output : // xbuf_ptr - a preallocated array of void_ptr is filled in with buffer pointers // such that xbuf_ptr[i] would contain the pointer for buffer allocated on GPU i. // All other entries remain unchanged // int MXOpenIpcHandles(int gpu_id, int gpus, int sync_steps, void** xbuf_ptr, void** hndl_ptr) { for (int i=0; i < gpus; ++i) { for (int j=0; j < sync_steps; ++j) { if (i == (gpu_id^(1 << j))) { uint8_t *data; cudaIpcMemHandle_t* my_handle = (reinterpret_cast<cudaIpcMemHandle_t*>(hndl_ptr))+i; cudaIpcOpenMemHandle(reinterpret_cast<void **>(&data), *my_handle, cudaIpcMemLazyEnablePeerAccess); cudaCheckErrors("MXOpenIpcHandles: ipc open failed"); xbuf_ptr[i] = data; } } } return 0; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/bidirectional_graph.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file bidirectional_graph.h * \brief Bidirectional graph data structure * \author <NAME>, <NAME> */ #ifndef MXNET_EXECUTOR_BIDIRECTIONAL_GRAPH_H_ #define MXNET_EXECUTOR_BIDIRECTIONAL_GRAPH_H_ #include <mxnet/base.h> #include <vector> #include <algorithm> #include <deque> #include <utility> namespace mxnet { namespace exec { namespace { struct _dummy {}; } /*! * \brief Custom graph class, which contains bi-directional nodes * required for traversing in both directions (from outputs to inputs * and vice versa). It is a non-owning layer on top of NNVM graph, since * NNVM graph enables traversing only in 1 direction (from outputs to inputs). */ template <typename DataStruct = _dummy> class BidirectionalGraph { public: struct Node; struct EdgeRef { Node* src_node; index_t src_id; Node* dst_node; index_t dst_id; EdgeRef() : src_node(nullptr), src_id(-1), dst_node(nullptr), dst_id(-1) {} EdgeRef(Node* src, index_t src_id, Node* dst, index_t dst_id) : src_node(src), src_id(src_id), dst_node(dst), dst_id(dst_id) {} bool operator==(const EdgeRef& other) { return (src_node == other.src_node) && (src_id == other.src_id) && (dst_node == other.dst_node) && (dst_id == other.dst_id); } }; struct Node { nnvm::Node* nnvmptr; std::vector<EdgeRef> inputs; std::vector<std::vector<EdgeRef>> outputs; DataStruct data; Node() = default; Node(nnvm::Node* nptr, std::vector<EdgeRef> inps, std::vector<std::vector<EdgeRef>> outs, DataStruct ds): nnvmptr(nptr), inputs(inps), outputs(outs), data(ds) { } std::vector<Node*> GetDataConsumers() const { std::vector<Node*> ret; for (const auto& out : outputs) { for (const auto& edge : out) { if (edge.dst_node != nullptr) { if (std::find(ret.begin(), ret.end(), edge.dst_node) == ret.end()) { ret.emplace_back(edge.dst_node); } } } } return ret; } std::vector<Node*> GetDataProducers() const { std::vector<Node*> ret; for (const auto& edge : inputs) { if (edge.src_node != nullptr) { if (std::find(ret.begin(), ret.end(), edge.src_node) == ret.end()) { ret.emplace_back(edge.src_node); } } } return ret; } }; explicit BidirectionalGraph<DataStruct>(nnvm::Graph* g) { auto& idx = g->indexed_graph(); auto num_nodes = idx.num_nodes(); nodes_.reserve(num_nodes); nnvm2nid.reserve(num_nodes); outputs.reserve(idx.outputs().size()); nnvm_outputs = &(g->outputs); // Create all the nodes in a new graph from // nodes in the NNVM graph and store them // in nodes array DFSVisit(g->outputs, [this](const nnvm::NodePtr& n) { MakeNode(n); }); // Create all connections between nodes in // the graph (both directions) for (const auto& it : nnvm2nid) { nnvm::Node* nnvmnode = it.first; uint32_t nid = it.second; for (size_t i = 0; i < nnvmnode->inputs.size(); ++i) { const auto& entry = nnvmnode->inputs[i]; uint32_t input_nid = nnvm2nid[entry.node.get()]; nodes_[input_nid]->outputs[entry.index].emplace_back(nodes_[input_nid].get(), entry.index, nodes_[nid].get(), i); nodes_[nid]->inputs[i] = {nodes_[input_nid].get(), static_cast<index_t>(entry.index), nodes_[nid].get(), static_cast<index_t>(i)}; } } // Create output connections from the graph for (auto& e : g->outputs) { uint32_t nid = nnvm2nid[e.node.get()]; nodes_[nid]->outputs[e.index].emplace_back(nodes_[nid].get(), e.index, nullptr, outputs.size()); outputs.emplace_back(nodes_[nid].get(), e.index, nullptr, outputs.size()); } } // Graph manipulation /* \brief Insert a node between two other nodes. */ Node* InsertNode(const nnvm::NodePtr node, const EdgeRef& edge) { Node* src = edge.src_node; Node* dst = edge.dst_node; auto& new_node = MakeNode(node); CHECK_EQ(new_node.outputs.size(), 1) << "Can insert only nodes with a single output"; CHECK_EQ(new_node.inputs.size(), 1) << "Can insert only nodes with a single input"; const EdgeRef ref_edge = edge; // Update bidirectional graph for (auto& e : src->outputs[ref_edge.src_id]) { if (e == ref_edge) { e.dst_node = &new_node; e.dst_id = 0; new_node.inputs[0] = e; break; } } if (dst != nullptr) { for (auto& e : dst->inputs) { if (e == ref_edge) { e.src_node = &new_node; e.src_id = 0; new_node.outputs[0].emplace_back(e); break; } } } else { EdgeRef e = ref_edge; e.src_node = &new_node; e.src_id = 0; new_node.outputs[0].emplace_back(e); outputs[ref_edge.dst_id] = e; } // Update underlying NNVM graph nnvm::NodeEntry& entry_to_update = (dst != nullptr) ? dst->nnvmptr->inputs[ref_edge.dst_id] : (*nnvm_outputs)[ref_edge.dst_id]; nnvm::NodeEntry dst_entry = entry_to_update; nnvm::NodeEntry new_entry(node, 0, dst_entry.version); entry_to_update = std::move(new_entry); node->inputs.resize(1); node->inputs[0] = std::move(dst_entry); return &new_node; } /* \brief Delete a node. */ void DeleteNode(const Node& node) { CHECK(node.inputs.size() == 1 && node.outputs.size() == 1) << "Only a node with a single input and output may be deleted"; const EdgeRef& input_edge = node.inputs[0]; std::vector<EdgeRef> output_edges = node.outputs[0]; Node* src_node = input_edge.src_node; auto& src_node_outputs = src_node->outputs[input_edge.src_id]; for (auto& edge : output_edges) { edge.src_node = src_node; edge.src_id = edge.src_id; } std::remove(src_node_outputs.begin(), src_node_outputs.end(), input_edge); src_node_outputs.insert(src_node_outputs.end(), output_edges.begin(), output_edges.end()); const nnvm::NodeEntry& nnvm_entry = node.nnvmptr->inputs[0]; for (const auto& edge : output_edges) { if (edge.dst_node != nullptr) { edge.dst_node->inputs[edge.dst_id] = edge; edge.dst_node->nnvmptr->inputs[edge.dst_id] = nnvm_entry; } else { outputs[edge.dst_id] = edge; (*nnvm_outputs)[edge.dst_id] = nnvm_entry; } } } std::pair<Node*, nnvm::NodePtr> CopyNode(Node* node) { nnvm::NodePtr nnvm_node = nnvm::Node::Create(); nnvm_node->attrs = node->nnvmptr->attrs; return std::make_pair(&(MakeNode(nnvm_node)), nnvm_node); } Node* DetachEdge(const EdgeRef& e) { Node* new_node; nnvm::NodePtr new_nnvm_node; std::tie(new_node, new_nnvm_node) = CopyNode(e.src_node); // Copy input edges CHECK_EQ(new_node->inputs.size(), e.src_node->inputs.size()); for (size_t i = 0; i < new_node->inputs.size(); ++i) { const auto& edge = e.src_node->inputs[i]; new_node->inputs[i] = {edge.src_node, edge.src_id, new_node, edge.dst_id}; } new_nnvm_node->inputs = e.src_node->nnvmptr->inputs; // Rewire output edges std::remove(e.src_node->outputs[e.src_id].begin(), e.src_node->outputs[e.src_id].end(), e); if (e.dst_node != nullptr) { e.dst_node->inputs[e.dst_id].src_node = new_node; e.dst_node->nnvmptr->inputs[e.dst_id].node = new_nnvm_node; } else { outputs[e.dst_id].src_node = new_node; (*nnvm_outputs)[e.dst_id].node = new_nnvm_node; } CHECK_EQ(new_node->outputs.size(), e.src_node->outputs.size()); new_node->outputs[e.src_id].emplace_back(new_node, e.src_id, e.dst_node, e.dst_id); return new_node; } /* \brief Get all subsets of nodes, where: * - graph constructed from nodes in each subset is a connected graph * - every node fulfills a predicate is_compatible * - if nodes u and v are part of a subset, then for each path between * u and v in the original directed graph, all nodes on those paths * are also part of the subset * \param is_compatible A function taking nnvm::Node* and returning bool * which identifies which nodes should be included in * subsets. */ template<typename FCompatible> std::vector<std::unordered_set<Node*>> get_subsets(FCompatible is_compatible) { std::vector<std::unordered_set<Node*>> subgraphs; std::unordered_set<Node*> incomp_set; std::vector<std::pair<bool, PairSet>> separation_sets; // Check each node for compatibility // and, if it is incompatible, mark nodes // on each side of it as not possible to be // in the same subset for (const auto& node : nodes_) { if (!is_compatible(node->nnvmptr)) { incomp_set.insert(node.get()); } } for (auto& node_ptr : nodes_) { Node& node = *node_ptr; if (incomp_set.count(&node) != 0) { // Check if all your inputs are incompatible too. // If so, then your separation set does not matter, // because it will covered by the sets of your inputs bool inside_node = true; for (const auto& input_edge : node.inputs) { if (incomp_set.count(input_edge.src_node) == 0) { inside_node = false; } } if (!inside_node) { std::unordered_set<Node*> in_graph; std::unordered_set<Node*> out_graph; std::vector<Node*> dummy_head; dummy_head.emplace_back(&node); DFS(dummy_head, false, [&out_graph](Node* node) { out_graph.insert(node); }); DFS(dummy_head, true, [&in_graph](Node* node) { in_graph.insert(node); }); separation_sets.push_back(std::make_pair(true, std::make_pair(in_graph, out_graph))); } else { separation_sets.push_back(std::make_pair(false, PairSet())); } } else { separation_sets.push_back(std::make_pair(false, PairSet())); } } IncompMap incomp_map; // For each node construct the map of nodes that cannot be in // the same subset index_t num_nodes = nodes_.size(); for (index_t i = 0; i < num_nodes; ++i) { const auto n = nodes_[i].get(); if (incomp_set.count(n) == 0) { for (index_t j = i + 1; j < num_nodes; ++j) { const auto& sep_set_pair = separation_sets[j]; if (sep_set_pair.first && incomp_map[n].count(nodes_[j].get()) == 0) { const auto& p = sep_set_pair.second; if (p.first.count(n)) { incomp_map[n].insert(p.second.begin(), p.second.end()); } else if (p.second.count(n)) { incomp_map[n].insert(p.first.begin(), p.first.end()); } } } for (index_t j = i - 1; j >= 0; --j) { const auto& sep_set_pair = separation_sets[j]; if (sep_set_pair.first && incomp_map[n].count(nodes_[j].get()) == 0) { const auto& p = sep_set_pair.second; if (p.first.count(n)) { incomp_map[n].insert(p.second.begin(), p.second.end()); } else if (p.second.count(n)) { incomp_map[n].insert(p.first.begin(), p.first.end()); } } } for (Node* incomp_n : incomp_set) { incomp_map[n].erase(incomp_n); } } } std::unordered_set<Node*> unused_set; for (auto& n : nodes_) { if (incomp_set.count(n.get()) == 0) { unused_set.insert(n.get()); } } std::unordered_set<Node*> visited; std::deque<Node*> queue; for (const auto& out : outputs) { queue.emplace_back(out.src_node); } // Create subsets while (!queue.empty()) { Node* vertex = queue.front(); queue.pop_front(); if (!visited.count(vertex)) { visited.insert(vertex); if (unused_set.count(vertex)) { subgraphs.emplace_back(naive_grow_subgraph(vertex, &unused_set, &incomp_map)); } for (const EdgeRef& input : vertex->inputs) { if (input.src_node != nullptr) { queue.emplace_back(input.src_node); } } } } return subgraphs; } std::vector<std::unique_ptr<Node>>& nodes() { return nodes_; } private: using PairSet = std::pair<std::unordered_set<Node*>, std::unordered_set<Node*>>; using PairVec = std::pair<std::vector<Node*>, std::vector<Node*>>; using IncompMap = std::unordered_map<Node*, std::unordered_set<Node*>>; Node& MakeNode(const nnvm::NodePtr& n) { nnvm2nid[n.get()] = static_cast<uint32_t>(nodes_.size()); nodes_.emplace_back(); nodes_.back().reset(new Node()); Node& new_node = *(nodes_.back()); new_node.nnvmptr = n.get(); if (n->num_inputs() == nnvm::kVarg || n->is_variable()) { new_node.inputs.resize(n->inputs.size()); } else { new_node.inputs.resize(n->num_inputs()); } if (!n->is_variable() && n->inputs.size() != 0) { CHECK_EQ(new_node.inputs.size(), n->inputs.size()) << "Number of inputs to operator " << n->op()->name << " (" << n->num_inputs() << ") does not match the actual number of inputs provided to operator " << n->attrs.name << " (" << n->inputs.size() << ")."; } new_node.outputs.resize(n->num_outputs()); return new_node; } /* \brief Traverse the graph using DFS in either direction. * \param heads Starting nodes for the DFS algorithm. * \param reverse If true, DFS will traverse the graph from * outputs to inputs. Otherwise, it will * traverse the graph from inputs to outputs. * \param fvisit Function to call on each visisted node. */ template <typename FVisit> void DFS(const std::vector<Node*>& heads, bool reverse, FVisit fvisit) { std::unordered_set<Node*> visited; std::vector<Node*> vec(heads.begin(), heads.end()); visited.reserve(heads.size()); while (!vec.empty()) { Node* vertex = vec.back(); vec.pop_back(); if (visited.count(vertex) == 0) { visited.insert(vertex); fvisit(vertex); std::vector<Node*> nexts = reverse ? vertex->GetDataProducers() : vertex->GetDataConsumers(); for (Node* node : nexts) { if (visited.count(node) == 0) { vec.emplace_back(node); } } } } } /* \brief Get the connected subgraph that contains the head node, * only previously unused nodes, according to the rules * from incompatibility map. * \param head Node which needs to be part of the returned subgraph. * \param unused_set Only nodes from this set will be considered when * adding to the growing subgraph. * \param incomp_map Map containing data on which nodes are incompatible * to be in the same subgraph. */ std::unordered_set<Node*> naive_grow_subgraph(Node* head, std::unordered_set<Node*>* unused_set, IncompMap* incomp_map) { std::unordered_set<Node*> subgraph; std::unordered_set<Node*> incomp_set; std::vector<Node*> stack; stack.emplace_back(head); while (!stack.empty()) { Node* vertex = stack.back(); stack.pop_back(); if (unused_set->count(vertex) && !incomp_set.count(vertex)) { unused_set->erase(vertex); subgraph.insert(vertex); incomp_set.insert((*incomp_map)[vertex].begin(), (*incomp_map)[vertex].end()); for (Node* input : vertex->GetDataProducers()) { if (unused_set->count(input) && !incomp_set.count(input)) { stack.emplace_back(input); } } for (Node* output : vertex->GetDataConsumers()) { if (unused_set->count(output) && !incomp_set.count(output)) { stack.emplace_back(output); } } } } return subgraph; } friend class nnvm::Graph; std::vector<std::unique_ptr<Node>> nodes_; std::unordered_map<nnvm::Node*, uint32_t> nnvm2nid; std::vector<EdgeRef> outputs; std::vector<nnvm::NodeEntry>* nnvm_outputs; }; // class BidirectionalGraph } // namespace exec } // namespace mxnet #endif // MXNET_EXECUTOR_BIDIRECTIONAL_GRAPH_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/cublas_fully_connected-inl.h<|end_filename|> /*! * Copyright (c) 2017 by Contributors * \file cublas_fully_connected-inl.h * \brief fully connect operator and symbol with direct use of cuBLAS */ #ifndef MXNET_OPERATOR_NN_CUBLAS_FULLY_CONNECTED_INL_H_ #define MXNET_OPERATOR_NN_CUBLAS_FULLY_CONNECTED_INL_H_ #include <dmlc/logging.h> #include <dmlc/parameter.h> #include <mxnet/operator.h> #include <map> #include <vector> #include <string> #include <utility> #include "../operator_common.h" #include "../elemwise_op_common.h" #include "./fully_connected-inl.h" #include "../../common/cuda_utils.h" namespace mxnet { namespace op { #if MXNET_USE_CUDA && CUDA_VERSION >= 8000 /** * \brief This is the implementation of fully connected operator for cuBLAS. */ template<typename DType> class CuBLASFullyConnectedOp { public: CuBLASFullyConnectedOp() { } ~CuBLASFullyConnectedOp() { } void Init(const FullyConnectedParam &p, const Context& ctx) { using namespace mshadow; this->param_ = p; verbose_msg_logged = false; // If no local setting for TensorCore use policy, look to global policy. if (!param_.cublas_tensor_core.has_value()) param_.cublas_tensor_core = GetEnvAllowTensorCore(); if (!SupportsFloat16Compute(ctx.dev_id)) { // Only warn user if the precision was set explicitly, i.e. silently // fail-over to pseudo-fp16 on Maxwell or earlier GPUs. if (param_.cublas_algo_fwd_prec == kFloat16 || param_.cublas_algo_bwd_prec == kFloat16) LOG(WARNING) << "Requested FullyConnected fp16 compute precision " << "not supported by this gpu arch, using fp32 instead."; // Remap precision to float32 whenever float16 would have been attempted. if (param_.cublas_algo_fwd_prec == kFloat16 || (param_.cublas_algo_fwd_prec == -1 && DataType<DType>::kFlag == kFloat16)) param_.cublas_algo_fwd_prec = kFloat32; if (param_.cublas_algo_bwd_prec == kFloat16 || (param_.cublas_algo_bwd_prec == -1 && DataType<DType>::kFlag == kFloat16)) param_.cublas_algo_bwd_prec = kFloat32; } // If the user didn't specify the algos, set up the proper default. int default_algo = static_cast<int>(CUBLAS_GEMM_DFALT); #if CUDA_VERSION >= 9000 // The cublas_tensor_core flag specifies the policy for fp16-I/O GEMMs only. // While TensorCore algos exist for fp32-I/O GEMMs, we do not enable it by // default based on this flag. if (DataType<DType>::kFlag == kFloat16 && param_.cublas_tensor_core.value()) default_algo = static_cast<int>(CUBLAS_GEMM_DFALT_TENSOR_OP); #endif if (!param_.cublas_algo_fwd.has_value()) param_.cublas_algo_fwd = default_algo; if (!param_.cublas_algo_bwd_data.has_value()) param_.cublas_algo_bwd_data = default_algo; if (!param_.cublas_algo_bwd_weights.has_value()) param_.cublas_algo_bwd_weights = default_algo; } void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data) { using mshadow::Shape2; using mshadow::expr::repmat; if (req[fullc::kOut] == kNullOp) return; CHECK_EQ(req[fullc::kOut], kWriteTo); size_t expected = param_.no_bias ? 2 : 3; CHECK_EQ(in_data.size(), expected); CHECK_EQ(out_data.size(), 1U); mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); CHECK_EQ(s->blas_handle_ownership_, mshadow::Stream<gpu>::OwnHandle) << "Must init CuBLAS handle in stream"; // Note: data is in row-major order. Assume a data input with batch size 'B' // and a number of input features 'IF', and an output with batch size 'B' // and output features 'OF'. Then the shape of this operation's I/O's are: // // Data input: B x IF // Weights input: OF x IF // Output: B x OF // // Now consider an operation dot(A,B) -> C, where // // A has shape (m,k) // B has shape (k,n) // C has shape (m,n) // // Matching C's shape to our Output, we have m=B and n=OF. What remains is k=IF. // // dot ( m x k , k x n ) -> m x n // dot ( B x IF, IF x OF ) -> B x OF // dot ( Data, Weights.transpose() ) -> Output // int m = 0, k = 0, n = 0; GetForwardMKN(in_data[fullc::kData], in_data[fullc::kWeight], out_data[fullc::kOut], param_.flatten, &m, &k, &n); // Log algos selected. No selection shows up as -1 or 99. This occurs here rather than in // the constructor so that layer shape info can be displayed. if (param_.cublas_algo_verbose && !verbose_msg_logged) { LOG(INFO) << "FC layer algo with (batchsize, in-features, out-features) = " << "(" << m << "," << k << "," << n << ")"; LOG(INFO) << " forward: " << param_.cublas_algo_fwd.value(); LOG(INFO) << " backprop-to-data: " << param_.cublas_algo_bwd_data.value(); LOG(INFO) << " backprop-to-weights: " << param_.cublas_algo_bwd_weights.value(); LOG(INFO) << ""; verbose_msg_logged = true; } mshadow::Tensor<gpu, 2, DType> data = in_data[fullc::kData].get_with_shape<gpu, 2, DType>(Shape2(m, k), s); mshadow::Tensor<gpu, 2, DType> wmat = in_data[fullc::kWeight].get<gpu, 2, DType>(s); mshadow::Tensor<gpu, 2, DType> out = out_data[fullc::kOut].get_with_shape<gpu, 2, DType>(Shape2(m, n), s); // Performs fully_connected-inl.h line: out = dot(data, wmat.T()); ExpandedDot(s, false, true, kWriteTo, data, wmat, out, param_.cublas_algo_fwd_prec, param_.cublas_algo_fwd.value()); if (!param_.no_bias) { mshadow::Tensor<gpu, 1, DType> bias = in_data[fullc::kBias].get_with_shape<gpu, 1, DType>(Shape1(n), s); AddBias(bias, data, out, s); } } void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad) { using mshadow::Shape2; using mshadow::expr::sum_rows; CHECK_EQ(out_grad.size(), 1U); size_t expected = param_.no_bias ? 2 : 3; CHECK(in_grad.size() == expected); CHECK_EQ(req.size(), expected); // TODO(bing): check the BLAS Handle, be careful // maybe need blas handle from context mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); CHECK_EQ(s->blas_handle_ownership_, mshadow::Stream<gpu>::OwnHandle) << "Must init CuBLAS handle in stream"; // For back-prop to weights: // // Data input: B x IF // "Output" gradient (an input): B x OF // Weights gradient (an output): OF x IF // // Matching C's shape to the Weights grad, we have m=OF and n=IF. What remains is k=B. // // dot ( m x k , k x n ) -> m x n // dot ( OF x B, B x IF ) -> OF x IF // dot ( OutGradient.transpose(), Data ) -> Weights int m = 0, k = 0, n = 0; GetForwardMKN(in_data[fullc::kData], in_data[fullc::kWeight], out_grad[fullc::kOut], param_.flatten, &m, &k, &n); mshadow::Tensor<gpu, 2, DType> data = in_data[fullc::kData].get_with_shape<gpu, 2, DType>(Shape2(m, k), s); mshadow::Tensor<gpu, 2, DType> wmat = in_data[fullc::kWeight].get<gpu, 2, DType>(s); mshadow::Tensor<gpu, 2, DType> grad = out_grad[fullc::kOut].get_with_shape<gpu, 2, DType>(Shape2(m, n), s); // backprop CHECK_NE(req[fullc::kWeight], kWriteInplace) << "cannot write weight inplace"; // gradient of weight mshadow::Tensor<gpu, 2, DType> gwmat = in_grad[fullc::kWeight].get<gpu, 2, DType>(s); // Performs fully_connected-inl.h: Assign(gwmat, req[fullc::kWeight], dot(grad.T(), data)); ExpandedDot(s, true, false, req[fullc::kWeight], grad, data, gwmat, param_.cublas_algo_bwd_prec, param_.cublas_algo_bwd_weights.value()); // gradient of bias if (!param_.no_bias) { AddBiasGrad(in_grad[fullc::kBias], grad, req[fullc::kBias], param_.num_hidden, ctx); } // gradient of data // "Output" gradient (an input): B x OF // Weights : OF x IF // Data gradient (an output): B x IF // // Matching C's shape to the Data gradient output, we have m=B and n=IF. What remains is k=OF. // // dot ( m x k , k x n ) -> m x n // dot ( B x OF, OF x IF ) -> B x IF // dot ( OutGradient, Weights ) -> Data Gradient mshadow::Tensor<gpu, 2, DType> gdata = in_grad[fullc::kData].get_with_shape<gpu, 2, DType>(Shape2(m, k), s); // Performs fully_connected-inl.h line: Assign(gdata, req[fullc::kData], dot(grad, wmat)); ExpandedDot(s, false, false, req[fullc::kData], grad, wmat, gdata, param_.cublas_algo_bwd_prec, param_.cublas_algo_bwd_data.value()); } /*! * \brief Returns whether the cublas library supports the fully-connected * operation described by `param`. */ static bool Supports(FullyConnectedParam param, const Context& ctx) { // This operator uses cublasGemmEx(), which is only supported on cuda // compute architectures >= 5.0. The FullyConnectedParam argument // is currently not considered, although this may change in the future. if (ComputeCapabilityMajor(ctx.dev_id) >= 5) return true; // Warn users that have specified a non-default setting for the fine-grained control. if (!param.cublas_off && (param.cublas_algo_fwd || param.cublas_algo_bwd_data || param.cublas_algo_bwd_weights || param.cublas_algo_fwd_prec != -1 || param.cublas_algo_bwd_prec != -1)) { LOG(WARNING) << "Fine-grained FC layer control not possible on this GPU architecture."; } return false; } private: // Return a pointer to the value '1' in the format required by `algo_precision`. // Used typically for the 'alpha' parameter to the GEMM kernel. static const void *one(int32_t algo_precision) { using namespace mxnet::common::cuda; // Default algo precision is that set by DType const void *answer = &CublasType<DType>::one; if (algo_precision != -1) { MSHADOW_REAL_TYPE_SWITCH(algo_precision, CType, { answer = &CublasType<CType>::one; }) } return answer; } // Return a pointer to the value '0' in the format required by `algo_precision`. // Used typically for the 'beta' parameter to the GEMM kernel. static const void *zero(int32_t algo_precision) { using namespace mxnet::common::cuda; // Default algo precision is that set by DType const void *answer = &CublasType<DType>::zero; if (algo_precision != -1) { MSHADOW_REAL_TYPE_SWITCH(algo_precision, CType, { answer = &CublasType<CType>::zero; }) } return answer; } // Returns the matrix multiply parameters m, k, and n of the forward inference operation: // // (m x k) matrix-multiply (k x n) -> (m x n) // // Similar to the code in fully_connected-inl.h, the TBlob shapes are effectively flattened if // they are not 2D. static void GetForwardMKN(const TBlob &data, const TBlob &weights, const TBlob &output, bool flatten, int *m_ptr, int *k_ptr, int *n_ptr) { const TShape& ishape = data.shape_; const TShape& wshape = weights.shape_; const TShape& oshape = output.shape_; int m = flatten ? ishape[0] : ishape.ProdShape(0, ishape.ndim()-1); int k = flatten ? ishape.ProdShape(1, ishape.ndim()) : ishape[ishape.ndim()-1]; int n = wshape[0]; // Weight matrix is transposed in forward inference // Check consistency of input and output shapes int k2 = wshape.ProdShape(1, wshape.ndim()); int m2 = flatten ? oshape[0] : oshape.ProdShape(0, oshape.ndim()-1); int n2 = flatten ? oshape.ProdShape(1, oshape.ndim()) : oshape[oshape.ndim()-1]; CHECK_EQ(m, m2) << "In FullyConnected GEMM, 'data' matrix rows (" << m << ")" << " must match output matrix rows (" << m2 << ")"; CHECK_EQ(k, k2) << "In FullyConnected GEMM, 'data' matrix cols (" << k << ")" << " must match 'weight' matrix rows (" << k2 << ")"; CHECK_EQ(n, n2) << "In FullyConnected GEMM, 'data' matrix cols (" << n << ")" << " must match output matrix cols (" << n2 << ")"; *m_ptr = m; *k_ptr = k; *n_ptr = n; } // Perform the matrix multiplication (a.k.a. 'dot') on the supplied Tensors, // converting between the row-major specification of this routine's interface/Tensors // and the column-major interface of the underlying cuBLAS gemm API. static void ExpandedDot(mshadow::Stream<gpu> *s, bool transposeA, bool transposeB, OpReqType output_request, const mshadow::Tensor<gpu, 2, DType> &A, const mshadow::Tensor<gpu, 2, DType> &B, const mshadow::Tensor<gpu, 2, DType> &C, int32_t algo_precision, int algo) { int m = transposeA ? A.shape_[1] : A.shape_[0]; int k = transposeA ? A.shape_[0] : A.shape_[1]; int n = transposeB ? B.shape_[0] : B.shape_[1]; // Check consistency of input and output shapes by grabbing n, m and k a different way. int k2 = transposeB ? B.shape_[1] : B.shape_[0]; int m2 = C.shape_[0]; int n2 = C.shape_[1]; CHECK_EQ(m, m2) << "In FullyConnected GEMM, 'data' matrix rows (" << m << ")" << " must match output matrix rows (" << m2 << ")"; CHECK_EQ(k, k2) << "In FullyConnected GEMM, 'data' matrix cols (" << k << ")" << " must match 'weight' matrix rows (" << k2 << ")"; CHECK_EQ(n, n2) << "In FullyConnected GEMM, 'data' matrix cols (" << n << ")" << " must match output matrix cols (" << n2 << ")"; // We now juggle the arguments of the matrix multiply to account for the // fact that the data as generated by mxnet is in row-major order, yet the // BLAS gemm kernel assumes they are in column-major order. // // Let .T() represent the transpose operation below. // // If A matrix-multiply B -> C, then B.T() matrix-multiply A.T() -> C.T() // // The ramifications of this are that in order for the gemm kernel to generate // the correct result we need to do 2 things: // // 1. swap the input ordering (so matrix B is the first operand) // 2. swap the dimensions of the matrices. // // The effect of these two steps effectively swaps n and m, leaving k the same. // Keep in mind that any transposition that needs to be done moves with the // input, so the transpose arguments are swapped as well. // In order to operate on submatrices in a "row-major world", one needs the // row-stride, which is the second dimension of the two for each matrix. int lda = B.shape_[1]; int ldb = A.shape_[1]; int ldc = C.shape_[1]; CublasGemm(s, transposeB, transposeA, n, m, k, output_request, B, A, C, lda, ldb, ldc, algo_precision, algo); } // A wrapper for the full-featured matrix multiply kernel cublasGemmEx() available // since CUDA 8 that permits data-type, compute-type and algorithm selection. static void CublasGemm(mshadow::Stream<gpu> *s, bool transposeA, bool transposeB, int m, int n, int k, OpReqType output_request, const mshadow::Tensor<gpu, 2, DType> &A, const mshadow::Tensor<gpu, 2, DType> &B, const mshadow::Tensor<gpu, 2, DType> &C, int lda, int ldb, int ldc, int32_t algo_precision, int algo) { using namespace mxnet::common::cuda; // The default is to have the compute type be the same as the data type, // unless the data type is float16, in which case float32 is chosen. auto compute_precision = CublasType<DType>::kCudaFlag; if (CublasType<DType>::kFlag == mshadow::kFloat16 && algo_precision == -1) { algo_precision = mshadow::kFloat32; } // If the user has overriden this default, change the compute_precision enum // as well as the format of the alpha and beta constants. if (algo_precision != -1) { MSHADOW_REAL_TYPE_SWITCH(algo_precision, CType, { compute_precision = CublasType<CType>::kCudaFlag; }) } const void *alpha = one(algo_precision); const void *beta = zero(algo_precision); switch (output_request) { case kNullOp: break; case kAddTo: // Change beta to point to 1 (the alpha value) rather than 0 to achieve summation. beta = alpha; case kWriteTo: case kWriteInplace: { auto blas_handle = mshadow::Stream<gpu>::GetBlasHandle(s); #if CUDA_VERSION >= 9000 auto handle_math_mode = CUBLAS_DEFAULT_MATH; CUBLAS_CALL(cublasGetMathMode(blas_handle, &handle_math_mode)); // The math mode of the handle needs to be set in sync with the math mode that // is baked into the algo number. Algo numbers at or above CUBLAS_GEMM_DFALT_TENSOR // currently have names that include "TENSOR_OP". auto desired_math_mode = (algo >= CUBLAS_GEMM_DFALT_TENSOR_OP) ? CUBLAS_TENSOR_OP_MATH : CUBLAS_DEFAULT_MATH; if (handle_math_mode != desired_math_mode) CUBLAS_CALL(cublasSetMathMode(blas_handle, desired_math_mode)); #endif auto err = CUBLAS_STATUS_SUCCESS; err = cublasGemmEx(blas_handle, CublasTransposeOp(transposeA), CublasTransposeOp(transposeB), m, n, k, alpha, A.dptr_, CublasType<DType>::kCudaFlag, lda, // A operand B.dptr_, CublasType<DType>::kCudaFlag, ldb, // B operand beta, C.dptr_, CublasType<DType>::kCudaFlag, ldc, // C operand compute_precision, static_cast<cublasGemmAlgo_t>(algo)); CHECK_EQ(err, CUBLAS_STATUS_SUCCESS) << "Cublas gemmEx fail."; #if CUDA_VERSION >= 9000 if (handle_math_mode != desired_math_mode) CUBLAS_CALL(cublasSetMathMode(blas_handle, handle_math_mode)); #endif } break; default: LOG(FATAL) << "not reached"; } } FullyConnectedParam param_; bool verbose_msg_logged; }; // class CuBLASFullyConnectedOp #endif // MXNET_USE_CUDA } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_CUBLAS_FULLY_CONNECTED_INL_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/dual_net/tpu_dual_net.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_DUAL_NET_TPU_DUAL_NET_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_DUAL_NET_TPU_DUAL_NET_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "REDACTEDcontainer/flat_hash_map.h" #include "REDACTEDsynchronization/mutex.h" #include "REDACTEDinference/runner/options.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/factory.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/model.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/random.h" #include "third_party/tensorflow/cc/saved_model/loader.h" #include "third_party/tensorflow/core/framework/graph.pb.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/public/session.h" namespace minigo { // Model that runs inference on tpu. class TpuDualNet : public Model { public: TpuDualNet(const std::string& graph_path, const FeatureDescriptor& feature_desc, const std::string& tpu_name); ~TpuDualNet() override; // Runs inference using TPU with the given inputs and fills the inference // outputs from policy and value tensors. // Args: // inputs: a vector of ModelInput. // outputs: a vector to be filled with outputs. // model_name: path to the inference model's directory. THIS IS UNUSED // since we have it when constructing TpuDualNet. It is here to // override. void RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) override; tensorflow::Status GetModel(); private: tensorflow::Tensor input_; std::vector<tensorflow::Tensor> run_outputs_; size_t batch_capacity_ = 0; const std::string tpu_name_; const std::string graph_path_; tensorflow::SignatureDef signature_def_; tensorflow::DataType input_type_; std::string input_tensor_names_; std::vector<std::string> output_tensor_names_; // output_key is a vector that contains "value_output" and "policy_output". // We use it to track the order output keys get pushed. std::vector<std::string> output_key_; tensorflow::SavedModelBundle saved_model_bundle_; absl::Mutex mutex_; std::unique_ptr<tensorflow::Session> session_; FeatureDescriptor feature_descriptor_; }; // Factory that creates TpuDualNet instance. class TpuDualNetFactory : public ModelFactory { public: TpuDualNetFactory(std::string tpu_name); ~TpuDualNetFactory() override; std::unique_ptr<Model> NewModel(const ModelDefinition& def) override; private: std::unique_ptr<tensorflow::Session> main_session_; std::string tpu_name_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_DUAL_NET_TPU_DUAL_NET_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/async/poll_thread.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/poll_thread.h" #include <utility> namespace minigo { PollThread::PollThread(std::string thread_name, absl::Duration poll_interval, std::function<void()> poll_fn) : Thread(std::move(thread_name)), poll_interval_(poll_interval), poll_fn_(std::move(poll_fn)) {} PollThread::~PollThread() = default; void PollThread::Join() { { absl::MutexLock lock(&mutex_); is_joining_ = true; } Thread::Join(); } void PollThread::Run() { absl::MutexLock lock(&mutex_); for (;;) { poll_fn_(); // AwaitWithTimout blocks until either `poll_interval_` has elapsed or // `is_joining_ == true`. It returns `true` if the polling loop should // exit. if (mutex_.AwaitWithTimeout(absl::Condition(this, &PollThread::IsJoining), poll_interval_)) { break; } } } bool PollThread::IsJoining() const { return is_joining_; } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/norm_convolution.cu<|end_filename|> /* * 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. */ /*! * Copyright (c) 2017 by Contributors * \file norm_convolution.cu * \brief * \author <NAME> */ #include "./norm_convolution-inl.h" #include <vector> #if MXNET_USE_CUDNN == 1 #include "./cudnn/cudnn_norm_convolution-inl.h" #endif // MXNET_USE_CUDNN namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 template<typename DType> static CuDNNNormConvolutionOp<DType>& GetCuDNNNormConvOp( const NormConvolutionParam& param, bool output_stats, const std::vector<mxnet::TShape> &in_shapes, const mxnet::TShape &out_shape, const OpContext& ctx) { #if DMLC_CXX11_THREAD_LOCAL static thread_local std::unordered_map<NormConvSignature, std::shared_ptr<CuDNNNormConvolutionOp<DType> >, OpHash> ops; #else static MX_THREAD_LOCAL std::unordered_map<NormConvSignature, std::shared_ptr<CuDNNNormConvolutionOp<DType> >, OpHash> ops; #endif NormConvSignature key(param); size_t input_ndim = 0; for (auto &s : in_shapes) input_ndim += s.ndim(); key.Reserve(1 /* for output_stats */ + input_ndim /* for primary input data shape */ + out_shape.ndim() /* for primary output data shape */ + 1 /* for dev_id */); key.AddSign(output_stats); key.AddSign(in_shapes); key.AddSign(out_shape); key.AddSign(ctx.run_ctx.ctx.dev_id); auto it = ops.find(key); if (it == ops.end()) { std::shared_ptr<CuDNNNormConvolutionOp<DType>> op( new CuDNNNormConvolutionOp<DType>()); auto ins_ret = ops.insert(std::pair<NormConvSignature, std::shared_ptr<CuDNNNormConvolutionOp<DType>>>(key, op)); CHECK(ins_ret.second); it = ins_ret.first; it->second->Init(param, output_stats, in_shapes, out_shape, ctx); } return *it->second; } #endif template<> void NormConvolutionCompute<gpu>(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const NormConvolutionParam& param = nnvm::get<NormConvolutionParam>(attrs.parsed); int dtype = inputs[norm_conv::kData].type_flag_; mxnet::TShape in_data_shape = inputs[norm_conv::kData].shape_; mxnet::TShape out_data_shape = outputs[norm_conv::kOut].shape_; CHECK_EQ(inputs.size(), static_cast<size_t>(norm_conv::NumInputs(param.no_norm))); #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { if (CuDNNNormConvolutionOp<DType>::Supports(param, in_data_shape, ctx.run_ctx.ctx.dev_id)) { std::vector<mxnet::TShape> in_shapes(inputs.size()); for (size_t i = 0; i < in_shapes.size(); i++) in_shapes[i] = inputs[i].shape_; bool output_stats = CuDNNNormConvolutionOp<DType>::OutputStats(ctx, req); CuDNNNormConvolutionOp<DType> &op = GetCuDNNNormConvOp<DType>(param, output_stats, in_shapes, out_data_shape, ctx); op.Forward(ctx, inputs, req, outputs); } else { LOG(FATAL) << "No fallback impl for unsupported NormConvolution configuration."; } }) #else LOG(FATAL) << "Only cudnn-based NormConvolution supported."; #endif // MXNET_USE_CUDNN } template<> void NormConvolutionGradCompute<gpu>(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const NormConvolutionParam& param = nnvm::get<NormConvolutionParam>(attrs.parsed); size_t num_fwd_inputs = norm_conv::NumInputs(param.no_norm); size_t num_output_gradients = 1; // only dOut gradient needed size_t num_fwd_ios = inputs.size(); size_t num_fwd_outputs = num_fwd_ios - num_fwd_inputs - num_output_gradients; std::vector<TBlob> out_grads(inputs.begin(), inputs.begin() + num_output_gradients); std::vector<TBlob> fwd_out_data(inputs.begin() + num_output_gradients, inputs.begin() + num_output_gradients + num_fwd_outputs); std::vector<TBlob> fwd_in_data(inputs.begin() + num_output_gradients + num_fwd_outputs, inputs.end()); // Remember, for fwd_out_data[kOut], we've swapped in the gradient for the output itself. const TBlob &out_grad = out_grads[norm_conv::kOut]; // Gradient types will be the same as the corresponding output int dtype = out_grad.type_flag_; mxnet::TShape in_data_shape = fwd_in_data[norm_conv::kData].shape_; mxnet::TShape out_data_shape = out_grads[norm_conv::kOut].shape_; #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { if (CuDNNNormConvolutionOp<DType>::Supports(param, in_data_shape, ctx.run_ctx.ctx.dev_id)) { // The Backward() call performs the same function, regardless of 'output_stats', so in that // sense, the setting is arbitrary. However, all configurations of NormConvolution // will have a 'false' version after they have gone through the validation step. Since // we can't call the OutputStats(ctx, req) routine since 'req' refers to the forward outputs, // we just assume 'false' for simplicity: bool output_stats = false; std::vector<mxnet::TShape> in_shapes(fwd_in_data.size()); for (size_t i = 0; i < fwd_in_data.size(); i++) in_shapes[i] = fwd_in_data[i].shape_; CuDNNNormConvolutionOp<DType> &op = GetCuDNNNormConvOp<DType>(param, output_stats, in_shapes, out_data_shape, ctx); op.Backward(ctx, out_grads, fwd_in_data, fwd_out_data, req, outputs); } else { LOG(FATAL) << "No fallback impl for unsupported NormConvolution configuration."; } }) #else LOG(FATAL) << "Only cudnn-based NormConvolution supported."; #endif // MXNET_USE_CUDNN } namespace norm_conv { // Can the function of this convolution op node be handled by norm convolution? bool IsCompatibleConvolution(const nnvm::NodePtr& node, const int& dtype, const TShape& shape, const Context& ctx) { auto param = nnvm::get<ConvolutionParam>(node->attrs.parsed); bool is_compatible = false; #if MXNET_USE_CUDNN == 1 && CUDNN_VERSION >= 7600 MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { // TODO(cfujitsang): add condition if using very specific Convolution parameters // example: cudnn_algo_fwd is_compatible = param.no_bias && CuDNNNormConvolutionOp<DType>::Supports(param, shape, ctx.dev_id); }); #endif // MXNET_USE_CUDNN return is_compatible; } } // namespace norm_conv NNVM_REGISTER_OP(NormConvolution) .set_attr<FCompute>("FCompute<gpu>", NormConvolutionCompute<gpu>); NNVM_REGISTER_OP(_backward_NormConvolution) .set_attr<FCompute>("FCompute<gpu>", NormConvolutionGradCompute<gpu>); } // namespace op } // namespace mxnet <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/tpu_benchmark_main.cc<|end_filename|> #include <cmath> #include <functional> #include <memory> #include <vector> #include "base/commandlineflags.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/str_join.h" #include "REDACTEDstrings/str_replace.h" #include "REDACTEDstrings/str_split.h" #include "REDACTEDsynchronization/mutex.h" #include "REDACTEDtime/clock.h" #include "REDACTEDtime/time.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/poll_thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/sharded_executor.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread_safe_queue.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/model.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/types.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/tf_utils.h" #include "third_party/tracing_framework_bindings_cpp/macros.h" // Inference flags. DEFINE_string(device, "", "ID of the device to run inference on. Can be left empty for " "single GPU machines. For a machine with N GPUs, a device ID " "should be specified in the range [0, N). For TPUs, pass the " "gRPC address for the device ID."); DEFINE_string(model, "", "Path to a minigo model."); DEFINE_int32(parallel_inference, 2, "Number of threads to run inference on."); DEFINE_int32(batch_size, 8, "Batch size for inference."); DEFINE_int64(num_inference, 10, "Run number of inferences for each worker."); namespace { using minigo::Model; using minigo::ModelFactory; using minigo::ModelInput; using minigo::ModelOutput; using minigo::Position; using minigo::Thread; class BenchmarkWorkerThread : public Thread { public: BenchmarkWorkerThread(ModelFactory* model_factory, const std::string& model_path, int64 batch_size, int64 num_inference) : batch_size_(batch_size), num_inference_(num_inference) { model_ = model_factory->NewModel(model_path); } private: void Run() override { // Setup model input and output. ModelInput input; ModelOutput output; input.sym = minigo::symmetry::kIdentity; Position position(minigo::Color::kBlack); input.position_history.push_back(&position); std::vector<const ModelInput*> inputs; std::vector<ModelOutput*> outputs; // The inputs aren't used by any of our test features so we don't need to // initialize them to anything meaningful. for (int i = 0; i < batch_size_; ++i) { inputs.push_back(&input); outputs.push_back(&output); } for (int64 i = 0; i < num_inference_; i++) { model_->RunMany(inputs, &outputs, &model_name_); } } std::string model_name_; std::unique_ptr<Model> model_; int64 batch_size_; int64 num_inference_; }; } // namespace int main(int argc, char* argv[]) { minigo::Init(&argc, &argv); // Start the output threads. std::vector<std::unique_ptr<BenchmarkWorkerThread>> worker_threads; ModelDefinition def; def = LoadModelDefinition(FLAGS_model + ".minigo"); auto* model_factory = GetModelFactory(def, FLAGS_device); worker_threads.reserve(FLAGS_parallel_inference); for (int i = 0; i < FLAGS_parallel_inference; ++i) { worker_threads.push_back(absl::make_unique<BenchmarkWorkerThread>( model_factory.get(), FLAGS_model, FLAGS_batch_size, FLAGS_num_inference)); } for (auto& t : worker_threads) { t->Start(); } for (auto& t : worker_threads) { t->Join(); } return 0; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/include/mxnet/base.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2015 by Contributors * \file base.h * \brief configuration of MXNet as well as basic data structure. */ #ifndef MXNET_BASE_H_ #define MXNET_BASE_H_ #include "dmlc/base.h" #include <string> #include "dmlc/io.h" #include "dmlc/type_traits.h" #include "dmlc/parameter.h" #include "mshadow/tensor.h" // nnvm headers for symbolic construction. #include "nnvm/op.h" #include "nnvm/symbolic.h" #include "libinfo.h" #include "tuple.h" /*! * \brief define compatible keywords in g++ * Used to support g++-4.6 and g++4.7 */ #if DMLC_USE_CXX11 && defined(__GNUC__) && !defined(__clang_version__) #if __GNUC__ == 4 && __GNUC_MINOR__ < 8 #error "Currently we need g++ 4.8 or higher to fully support c++11 features" #define override #define final #endif #endif /*! * \brief define dllexport for Visual Studio */ #ifdef _MSC_VER #ifdef MXNET_EXPORTS #define MXNET_API __declspec(dllexport) #else #define MXNET_API __declspec(dllimport) #endif #else #define MXNET_API #endif /*! * \brief define prediction only */ #ifndef MXNET_PREDICT_ONLY #define MXNET_PREDICT_ONLY 0 #endif /*! \brief major version */ #define MXNET_MAJOR 1 /*! \brief minor version */ #define MXNET_MINOR 6 /*! \brief patch version */ #define MXNET_PATCH 1 /*! \brief mxnet version */ #define MXNET_VERSION (MXNET_MAJOR*10000 + MXNET_MINOR*100 + MXNET_PATCH) /*! \brief helper for making version number */ #define MXNET_MAKE_VERSION(major, minor, patch) ((major)*10000 + (minor)*100 + patch) /*! * \brief define function name as profiler message */ #define PROFILER_MESSAGE_FUNCNAME (__FUNCTION__) /*! \brief namespace of mxnet */ namespace mxnet { /*! \brief mxnet cpu */ typedef mshadow::cpu cpu; /*! \brief mxnet gpu */ typedef mshadow::gpu gpu; /*! \brief index type usually use unsigned */ typedef mshadow::index_t index_t; /*! \brief data type that will be used to store ndarray */ typedef mshadow::default_real_t real_t; /*! \brief operator structure from NNVM */ using Op = nnvm::Op; /*! \brief Context information about the execution environment */ struct Context { /*! \brief Type of device */ enum DeviceType { kCPU = cpu::kDevMask, kGPU = gpu::kDevMask, kCPUPinned = 3, kCPUShared = 5, }; /*! \brief the device type we run the op on */ DeviceType dev_type; /*! \brief device id we are going to run it on */ int32_t dev_id; /*! \brief default constructor */ Context() : dev_type(kCPU), dev_id(0) {} /*! * \brief Get corresponding device mask * \return cpu::kDevMask or gpu::kDevMask */ inline DeviceType dev_mask() const { if (dev_type == kCPUPinned || dev_type == kCPUShared) return kCPU; return dev_type; } /*! * \brief Returns dev_id for kGPU and kCPUPinned, 0 otherwise */ inline int real_dev_id() const { if (dev_type == kCPUPinned || dev_type == kGPU) return dev_id; return 0; } /*! * \brief Comparator, used to enable Context as std::map key. * \param b another context to compare * \return compared result */ inline bool operator<(const Context &b) const; /*! * \brief check if current context equals another one * \param b another context to compare * \return whether dev mask and id are same */ inline bool operator==(const Context &b) const { return dev_type == b.dev_type && dev_id == b.dev_id; } /*! * \brief check if current context not equals another one * \param b another context to compare * \return whether they are not the same */ inline bool operator!=(const Context &b) const { return !(*this == b); } /*! * \brief save the content into binary stream * \param strm the output stream */ inline void Save(dmlc::Stream *strm) const { strm->Write(&dev_type, sizeof(dev_type)); strm->Write(&dev_id, sizeof(dev_id)); } /*! * \brief load the content from binary stream * \param strm the output stream * \return whether the load is successful */ inline bool Load(dmlc::Stream *strm) { if (strm->Read(&dev_type, sizeof(dev_type)) != sizeof(dev_type)) return false; if (strm->Read(&dev_id, sizeof(int32_t)) != sizeof(int32_t)) return false; return true; } /*! \brief the maximal device type */ static const int32_t kMaxDevType = 6; /*! \brief the maximal device index */ static const int32_t kMaxDevID = 16; /*! * \brief Create a new context. * \param dev_type device type. * \param dev_id device id. -1 for current device. */ inline static Context Create(DeviceType dev_type, int32_t dev_id = -1); /*! \return CPU Context */ inline static Context CPU(int32_t dev_id = 0); /*! * Create a GPU context. * \param dev_id the device id. * \return GPU Context. -1 for current GPU. */ inline static Context GPU(int32_t dev_id = -1); /*! * Get the number of GPUs available. * \return The number of GPUs that are available. */ inline static int32_t GetGPUCount(); /*! * Get the GPU streaming multiprocessor (SM) architecture. * \param dev the GPU number to query * \return The GPU SM arch. */ inline static int32_t GetGPUSMArch(int dev); /*! * Is the cuda driver installed and visible to the system. * \return Whether the driver is present. */ inline static bool GPUDriverPresent(); /*! * Get the number of streams that a GPU Worker has available to operations. * \return The number of streams that are available. */ inline static int32_t GetGPUStreamsPerWorker(); /*! * \brief get the free and total available memory on a GPU * \param dev the GPU number to query * \param free_mem pointer to the uint64_t holding free GPU memory * \param total_mem pointer to the uint64_t holding total GPU memory * \return No return value */ inline static void GetGPUMemoryInformation(int dev, uint64_t *free, uint64_t *total); /*! * Create a pinned CPU context. * \param dev_id the device id for corresponding GPU. * \return Pinned CPU context. -1 for current GPU. */ inline static Context CPUPinned(int32_t dev_id = -1); /*! * Create a CPU shared memory context. * \param dev_id dummy device id. * \return CPU shared memory context. */ inline static Context CPUShared(int32_t dev_id = 0); /*! * Create a context from string of the format [cpu|gpu|cpu_pinned](n) * \param str the string pattern * \return Context */ inline static Context FromString(const std::string& str); private: #if MXNET_USE_CUDA static void CudaLibChecks(); #endif #if MXNET_USE_CUDNN static void CuDNNLibChecks(); #endif }; #if MXNET_USE_CUDA /*! \brief Holds an auxiliary mshadow gpu stream that can be synced with a primary stream. */ class GPUAuxStream { public: /*! * \brief constructor. * \param primary_stream gpu stream that is synced with the created auxiliary stream. */ explicit GPUAuxStream(mshadow::Stream<gpu> *primary_stream) : primary_stream_(primary_stream), aux_stream_(primary_stream), gpu_stream_sync_event_(nullptr) { if (Context::GetGPUStreamsPerWorker() >= 2) { // Create auxiliary stream on the same device with the same properties as the primary stream bool primary_has_blas_handle = primary_stream->blas_handle_ownership_ == mshadow::Stream<gpu>::OwnHandle; bool primary_has_dnn_handle = primary_stream->dnn_handle_ownership_ == mshadow::Stream<gpu>::OwnHandle; aux_stream_ = mshadow::NewStream<gpu>(primary_has_blas_handle, primary_has_dnn_handle, primary_stream->dev_id); MSHADOW_CUDA_CALL(cudaEventCreateWithFlags(&gpu_stream_sync_event_, cudaEventDisableTiming)); } } /*! \brief destructor */ ~GPUAuxStream() { // If the aux_stream_ == primary_stream_, then we created no new streams to destroy. if (aux_stream_ != primary_stream_) { MSHADOW_CATCH_ERROR(mshadow::DeleteStream<gpu>(aux_stream_)); MSHADOW_CATCH_ERROR(cudaEventDestroy(gpu_stream_sync_event_)); } } /*! * \brief Makes future aux stream work wait on the completion of existing primary stream work. */ void PreAuxStreamUseSync() { // If the aux_stream_ == primary_stream_, then no synchronization is necessary. if (aux_stream_ != primary_stream_) StreamSync(primary_stream_, aux_stream_, gpu_stream_sync_event_); } /*! * \brief Makes future primary stream work wait on the completion of existing aux stream work. */ void PostAuxStreamUseSync() { // If the aux_stream_ == primary_stream_, then no synchronization is necessary. if (aux_stream_ != primary_stream_) StreamSync(aux_stream_, primary_stream_, gpu_stream_sync_event_); } /*! \brief Getter for created auxiliary stream. */ mshadow::Stream<gpu> *GetStream() { return aux_stream_; } /*! * \brief Make future work enqueued to `s2` wait on completion of current work enqueued to `s1`. * \param s1 stream with work that must be completed before future s2 work can begin. * \param s2 stream whose future work is made to wait on the completion of existing s1 work. * \param event used to pass s1 state to s2. */ static void StreamSync(mshadow::Stream<gpu> *s1, mshadow::Stream<gpu> *s2, cudaEvent_t event) { MSHADOW_CUDA_CALL(cudaEventRecord(event, s1->stream_)); MSHADOW_CUDA_CALL(cudaStreamWaitEvent(s2->stream_, event, 0)); } private: mshadow::Stream<gpu> *primary_stream_; mshadow::Stream<gpu> *aux_stream_; cudaEvent_t gpu_stream_sync_event_; }; /*! * \brief Provides automatic coordination of an auxilary stream with a primary one. * This object, upon construction, prepares an aux stream for use by syncing it with enqueued * primary-stream work. Object destruction will sync again so future primary-stream work * will wait on enqueued aux-stream work. If MXNET_GPU_WORKER_NSTREAMS == 1, then this defaults * simply: the primary stream will equal the aux stream and the syncs will be executed as nops. * See ./src/operator/cudnn/cudnn_convolution-inl.h for a usage example. */ class SyncedGPUAuxStream { public: /*! * \brief constructor. * \param gpu_aux_stream auxilary gpu stream that is managed by this RAII object. */ explicit SyncedGPUAuxStream(GPUAuxStream *gpu_aux_stream) : gpu_aux_stream_(gpu_aux_stream) { gpu_aux_stream_->PreAuxStreamUseSync(); } /*! \brief destructor */ ~SyncedGPUAuxStream() { gpu_aux_stream_->PostAuxStreamUseSync(); } /*! \brief copy constructor deleted to prevent unexpected synchronizations. */ SyncedGPUAuxStream(const SyncedGPUAuxStream&) = delete; /*! \brief copy assignment operator deleted to prevent unexpected synchronizations. */ void operator=(const SyncedGPUAuxStream&) = delete; /*! \brief move constructor permitted as alternative to copying. */ SyncedGPUAuxStream(SyncedGPUAuxStream&&) = default; /*! \brief move assignment operator permitted as alternative to copy assignment. */ SyncedGPUAuxStream& operator=(SyncedGPUAuxStream&&) = default; /*! \brief Getter for underlying mshadow::Stream<gpu>. */ inline mshadow::Stream<gpu>* GetStream() const { return gpu_aux_stream_->GetStream(); } private: GPUAuxStream *gpu_aux_stream_; }; #endif // MXNET_USE_CUDA /*! * \brief execution time context. * The information needed in runtime for actual execution. */ struct RunContext { /*! \brief base Context */ Context ctx; /*! * \brief the stream of the device, can be NULL or Stream<gpu>* in GPU mode */ void *stream; /*! * \brief the auxiliary stream of the device, can be NULL or Stream<gpu>* in GPU mode */ void *aux_stream; /*! * \brief indicator of whether this execution is run in bulk mode */ bool is_bulk; /*! * \brief get mshadow stream from Context * \return the mshadow stream * \tparam xpu the device type of the stream */ template<typename xpu> inline mshadow::Stream<xpu>* get_stream() const { return static_cast<mshadow::Stream<xpu>*>(stream); } #if MXNET_USE_CUDA /*! * \brief get an RAII object that transparently handles the syncing of the auxiliary stream. * \return the aux stream auto-syncing object */ inline SyncedGPUAuxStream get_gpu_aux_stream() const { return SyncedGPUAuxStream(static_cast<GPUAuxStream*>(aux_stream)); } #endif /*! \brief get the base Context from RunContext */ inline const Context& get_ctx() const { return ctx; } }; } // namespace mxnet //! \cond Doxygen_Suppress namespace mxnet { // implementing Context inline bool Context::operator<(const Context &b) const { if (dev_type == b.dev_type) { return dev_id < b.dev_id; } else { return dev_type < b.dev_type; } } inline Context Context::Create(DeviceType dev_type, int32_t dev_id) { Context ctx; ctx.dev_type = dev_type; ctx.dev_id = dev_id < 0 ? 0 : dev_id; if (dev_type & kGPU) { #if MXNET_USE_CUDA CudaLibChecks(); #endif #if MXNET_USE_CUDNN CuDNNLibChecks(); #endif if (dev_id < 0) { #if MXNET_USE_CUDA CHECK_EQ(cudaGetDevice(&ctx.dev_id), cudaSuccess); #else LOG(FATAL) << "Please compile with CUDA enabled for cuda features"; #endif } } return ctx; } inline Context Context::CPU(int32_t dev_id) { return Create(kCPU, dev_id); } inline Context Context::CPUPinned(int32_t dev_id) { return Create(kCPUPinned, dev_id); } inline Context Context::CPUShared(int32_t dev_id) { return Create(kCPUShared, dev_id); } inline Context Context::GPU(int32_t dev_id) { return Create(kGPU, dev_id); } inline bool Context::GPUDriverPresent() { #if MXNET_USE_CUDA int cuda_driver_version = 0; CHECK_EQ(cudaDriverGetVersion(&cuda_driver_version), cudaSuccess); return cuda_driver_version > 0; #else return false; #endif } inline int32_t Context::GetGPUCount() { #if MXNET_USE_CUDA if (!GPUDriverPresent()) { return 0; } int32_t count; cudaError_t e = cudaGetDeviceCount(&count); // TODO(junwu): Remove e == cudaErrorInsufficientDriver // This is skipped for working around wheel build system with older CUDA driver. if (e == cudaErrorNoDevice || e == cudaErrorInsufficientDriver) { return 0; } CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); return count; #else return 0; #endif } inline int32_t Context::GetGPUSMArch(int dev) { #if MXNET_USE_CUDA int32_t compute_capability_major; int32_t compute_capability_minor; cudaError_t e; int curDevice; e = cudaGetDevice(&curDevice); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaSetDevice(dev); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaDeviceGetAttribute(&compute_capability_major, cudaDevAttrComputeCapabilityMajor, dev); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaDeviceGetAttribute(&compute_capability_minor, cudaDevAttrComputeCapabilityMinor, dev); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaSetDevice(curDevice); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); int32_t sm_arch = 10 * compute_capability_major + compute_capability_minor; return sm_arch; #else LOG(FATAL) << "This call is only supported for MXNet built with CUDA support."; return 0; #endif } inline int32_t Context::GetGPUStreamsPerWorker() { // The default number of streams available if the user has not set MXNET_GPU_WORKER_NSTREAMS. const int32_t default_num_streams = 2; // The get_aux_stream() interface can supply one additional stream beyond the standard one. static int32_t num_streams = dmlc::GetEnv("MXNET_GPU_WORKER_NSTREAMS", default_num_streams) >= 2 ? 2 : 1; return num_streams; } inline void Context::GetGPUMemoryInformation(int dev, uint64_t *free_mem, uint64_t *total_mem) { #if MXNET_USE_CUDA size_t memF, memT; cudaError_t e; int curDevice; e = cudaGetDevice(&curDevice); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaSetDevice(dev); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaMemGetInfo(&memF, &memT); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaSetDevice(curDevice); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); *free_mem = static_cast<uint64_t>(memF); *total_mem = static_cast<uint64_t>(memT); #else LOG(FATAL) << "This call is only supported for MXNet built with CUDA support."; #endif } inline Context Context::FromString(const std::string& str) { Context ret; try { const std::string::size_type l = str.find('('); CHECK_NE(l, std::string::npos); const std::string::size_type r = str.find(')'); CHECK_EQ(r, str.length()-1); const std::string type = str.substr(0, l); int id = std::stoi(str.substr(l+1, r-l-1)); if (type == "cpu") { ret = CPU(id); } else if (type == "gpu") { ret = GPU(id); } else if (type == "cpu_pinned") { ret = CPUPinned(id); } else if (type == "cpu_shared") { ret = CPUShared(id); } else { LOG(FATAL) << "Invalid context string " << str; } } catch (...) { LOG(FATAL) << "Invalid context string " << str; } return ret; } inline std::ostream& operator<<(std::ostream &out, const Context &ctx) { if (ctx.dev_type == Context::kCPU) { out << "cpu("; } else if (ctx.dev_type == Context::kGPU) { out << "gpu("; } else if (ctx.dev_type == Context::kCPUPinned) { out << "cpu_pinned("; } else if (ctx.dev_type == Context::kCPUShared) { out << "cpu_shared("; } else { out << "unknown("; } out << ctx.dev_id << ")"; return out; } // describe op registration point #define STRINGIZE_DETAIL(x) #x #define STRINGIZE(x) STRINGIZE_DETAIL(x) #define MXNET_DESCRIBE(...) describe(__VA_ARGS__ "\n\nFrom:" __FILE__ ":" STRINGIZE(__LINE__)) #define ADD_FILELINE "\n\nDefined in " __FILE__ ":L" STRINGIZE(__LINE__) #if MXNET_USE_MKLDNN == 1 constexpr size_t kMKLDNNAlign = 64; #endif } // namespace mxnet namespace std { template<> struct hash<mxnet::Context> { size_t operator()(const mxnet::Context& ctx) const { size_t res = 0; res = dmlc::HashCombine(res, static_cast<size_t>(ctx.dev_type)); res = dmlc::HashCombine(res, static_cast<size_t>(ctx.dev_id)); return res; } }; #if __cplusplus < 201402L && !defined(_MSC_VER) template<typename T, typename... Args> inline std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } #endif } // namespace std #include "./tensor_blob.h" //! \endcond #endif // MXNET_BASE_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/ml_perf/eval_models.cc<|end_filename|> // Copyright 2020 Google LLC // // 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. // Evaluates a directory of models against the target model, as part of the rl // loop. It uses the single-model evaluation class set up in cc/eval.h and // cc/eval.cc. #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/ml_perf/eval_models.h" #include <chrono> // NOLINT #include <cstdint> #include <fstream> #include <iomanip> #include <istream> #include <regex> // NOLINT #include <string> #include <thread> // NOLINT #include <tuple> #include "strings/numbers.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/eval.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/directory_watcher.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/game_utils.h" #include "third_party/tensorflow/core/lib/io/path.h" #include "third_party/tensorflow/core/platform/env.h" ABSL_FLAG(int32_t, start, 0, "Index of first model to evaluate. If not" "specified, evaluate every game"); ABSL_FLAG(int32_t, end, kint32max, "Index of last model to evaluate."); ABSL_FLAG(std::string, timestamp_file, "", "A file records the model name and timestamp"); ABSL_FLAG(int32_t, num_games, 128, "Number of games to run."); ABSL_FLAG(std::string, start_file, "", "File generated at the end of training loop to notify the start of " "the evaluation process. Same as the abort file for selfplay. If not" "specified, evaluation starts immediately"); ABSL_FLAG(std::string, model_dir, "", "Model directory."); ABSL_FLAG(double, target_winrate, 0.5, "Fraction of games that a model must beat the target by."); ABSL_FLAG(std::vector<std::string>, devices, {}, "List of devices to run on."); namespace minigo { const int start_time = absl::ToUnixSeconds(absl::Now()); std::vector<ModelInfoTuple> load_train_times() { std::vector<ModelInfoTuple> models; std::string path = tensorflow::io::JoinPath(absl::GetFlag(FLAGS_timestamp_file)); LOG(INFO) << "About to read file " << path; std::string timestamp_data; const auto& status = ReadFileToString(tensorflow::Env::Default(), path, &timestamp_data); if (!status.ok()) { LOG(ERROR) << "Cannot open file " << path << std::endl; } std::stringstream line_stream(timestamp_data); std::string line; while (std::getline(line_stream, line, '\n')) { if (!line.empty()) { std::regex pattern("(\\s*)(\\S+)(\\s+)(\\S+)"); std::smatch match; std::regex_search(line, match, pattern); std::string timestamp = match[2]; std::string name = match[4]; std::string model_path; model_path = tensorflow::io::JoinPath(absl::GetFlag(FLAGS_model_dir), name); struct ModelInfoTuple model_info = {timestamp, name, model_path}; models.push_back(model_info); } } return models; } void EvaluateModels(std::vector<minigo::ModelInfoTuple> models, int num_games) { int start_point = 0; int num_model = models.size(); while (stoi(models[start_point].name) < absl::GetFlag(FLAGS_start)) { start_point += 1; if (start_point >= num_model) { LOG(ERROR) << "Start point left no model to evaluate."; return; } } std::vector<std::string> devices = absl::GetFlag(FLAGS_devices); int num_devices = devices.size(); std::string eval_model_name; std::string target_model_name; std::string target_path = absl::GetFlag(FLAGS_target_model); std::vector<std::unique_ptr<Evaluator>> evaluators_; evaluators_.reserve(num_devices); for (int i = 0; i < num_devices; i++) { evaluators_.push_back(absl::MakeUnique<Evaluator>()); } bool reset = false; double time_value; for (int j = start_point; j < num_model && stoi(models[j].name) <= absl::GetFlag(FLAGS_end); j++) { LOG(INFO) << ":::MLL " << absl::ToUnixSeconds(absl::Now()) << " eval_start: {\"value\": null, \"metadata\": " << "{\"epoch_num\": " << stoi(models[j].name) << ", " << "\"lineno\": 111, " << "\"file\": \"minigo/ml_perf/eval_models.cc\"}}"; int total_wins = 0; int total_num_games = 0; for (int i = 0; i < num_devices; i++) { int low_end = i * num_games / num_devices; int high_end = (i + 1) * num_games / num_devices; int num_games_to_calculate = high_end - low_end; absl::SetFlag(&FLAGS_eval_model, models[j].model_path); absl::SetFlag(&FLAGS_parallel_games, num_games_to_calculate); absl::SetFlag(&FLAGS_eval_device, devices[i]); absl::SetFlag(&FLAGS_target_device, devices[i]); if (reset) { evaluators_[i]->Reset(); } else { reset = true; } std::vector<std::pair<std::string, WinStats>> win_stats_result = evaluators_[i]->Run(); WinStats eval_stats = win_stats_result[0].second; WinStats target_stats = win_stats_result[1].second; eval_model_name = win_stats_result[0].first; target_model_name = win_stats_result[1].first; int num_games_i = eval_stats.black_wins.total() + eval_stats.white_wins.total() + target_stats.black_wins.total() + target_stats.white_wins.total(); total_wins += eval_stats.black_wins.total() + eval_stats.white_wins.total(); total_num_games += num_games_i; } double win_rate = (double)total_wins / (double)total_num_games; LOG(INFO) << ":::MLL " << absl::ToUnixSeconds(absl::Now()) << " eval_stop: {\"value\": null, \"metadata\": " << "{\"epoch_num\": " << stoi(models[j].name) << ", " << " \"lineno\": 149, " << "\"file\": \"minigo/ml_perf/eval_models.cc\"}}"; if (!strings::safe_strtod(models[j].timestamp, &time_value)) { LOG(ERROR) << "Could not convert time_value to float"; } LOG(INFO) << ":::MLL " << int(start_time + time_value) << " eval_accuracy: {\"value\": " << win_rate << ", \"metadata\": " << "{\"epoch_num\": " << stoi(models[j].name) << ", " << " \"lineno\": 158, " << "\"file\": \"minigo/ml_perf/eval_models.cc\"}}"; LOG(INFO) << "Win rate " << eval_model_name << " vs " << target_model_name << " : " << std::fixed << std::setprecision(3) << win_rate; if (win_rate >= absl::GetFlag(FLAGS_target_winrate)) { LOG(INFO) << "Model " << models[j].name << " beat target after " << models[j].timestamp << " s."; LOG(INFO) << ":::MLL " << int(start_time + time_value) << " run_stop: {\"value\": null, \"metadata\": " << "{\"status\": \"success\"," << " \"lineno\": 173, " << "\"file\": \"minigo/ml_perf/eval_models.cc\"}}"; return; } } double last_time_value; if (!strings::safe_strtod(models.back().timestamp, &last_time_value)) { LOG(ERROR) << "Could not convert time_value to float"; } LOG(INFO) << ":::MLL " << int(start_time + last_time_value) << " run_stop: {\"value\": null, \"metadata\": " << "{\"status\": \"failure\"," << " \"lineno\": 185, " << "\"file\": \"minigo/ml_perf/eval_models.cc\"}}"; } } // namespace minigo int main(int argc, char* argv[]) { minigo::Init(&argc, &argv); minigo::zobrist::Init(absl::GetFlag(FLAGS_seed)); QCHECK(!absl::GetFlag(FLAGS_target_model).empty()) << "FLAGS_target_model not specified! "; QCHECK(!absl::GetFlag(FLAGS_timestamp_file).empty()) << "FLAGS_target_model not specified! "; if (!absl::GetFlag(FLAGS_target_model).empty()) { while (!minigo::file::FileExists(absl::GetFlag(FLAGS_start_file))) { std::this_thread::sleep_for(std::chrono::seconds(1)); } } std::vector<minigo::ModelInfoTuple> models = minigo::load_train_times(); minigo::EvaluateModels(models, absl::GetFlag(FLAGS_num_games)); } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ocl_post_ops.h<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_POST_OPS_H #define OCL_POST_OPS_H DATA_T relu_fwd(DATA_T s, DATA_T alpha) { return s > 0 ? s : s * alpha; } DATA_T relu_bwd(DATA_T dd, DATA_T s, DATA_T alpha) { return s > 0 ? dd : dd * alpha; } DATA_T linear_fwd(DATA_T s, DATA_T alpha, DATA_T beta) { return alpha * s + beta; } DATA_T linear_bwd(DATA_T dd, DATA_T alpha) { return dd * alpha; } DATA_T bounded_relu_fwd(DATA_T s, DATA_T alpha) { s = s > 0 ? s : 0; return s > alpha ? alpha : s; } DATA_T bounded_relu_bwd(DATA_T dd, DATA_T s, DATA_T alpha) { return dd * (0 < s && s < alpha ? 1 : 0); } DATA_T soft_relu_fwd(DATA_T s) { return s < log(DATA_MAX) ? log1p(exp(s)) : s; } DATA_T soft_relu_bwd(DATA_T dd, DATA_T s) { return dd / (1 + exp(-s)); } DATA_T logistic_fwd(DATA_T s) { return 1 / (1 + exp(-s)); } DATA_T logistic_bwd(DATA_T dd, DATA_T s) { DATA_T v = logistic_fwd(s); return dd * v * (1 - v); } DATA_T square_fwd(DATA_T s){ return s*s; } DATA_T square_bwd(DATA_T dd, DATA_T s){ return dd * 2*s; } DATA_T sqrt_fwd(DATA_T s){ return s > 0 ? (sqrt(s)) : 0; } DATA_T sqrt_bwd(DATA_T dd, DATA_T s){ return s > 0 ? dd / (2 * sqrt(s)) : 0; } DATA_T abs_fwd(DATA_T s){ return s > 0 ? s : -s; } DATA_T abs_bwd(DATA_T dd, DATA_T s){ return s > 0 ? dd : s < 0 ? -dd : 0; } DATA_T tanh_fwd(DATA_T s){ return tanh(s); } DATA_T tanh_bwd(DATA_T dd, DATA_T s){ DATA_T e = tanh_fwd(s); return dd * (1 - e) * (1 + e); } DATA_T elu_fwd(DATA_T s, DATA_T alpha){ return s > 0 ? s : alpha * expm1(s); } DATA_T elu_bwd(DATA_T dd, DATA_T s, DATA_T alpha){ return dd * (s > 0 ? 1 : alpha * exp(s)); } DATA_T exp_fwd(DATA_T s) { return exp(s); } DATA_T exp_bwd(DATA_T dd, DATA_T s) { return dd * exp_fwd(s); } DATA_T fwd_eltwise(DATA_T x, DATA_T alpha_, DATA_T beta_) { #ifdef ALG_KIND switch (ALG_KIND) { case RELU: return relu_fwd(x, alpha_); break; case LINEAR: return linear_fwd(x, alpha_, beta_); break; case BOUNDED_RELU: return bounded_relu_fwd(x, alpha_); break; case SOFT_RELU: return soft_relu_fwd(x); break; case LOGISTIC: return logistic_fwd(x); break; case TANH: return tanh_fwd(x); break; case ELU: return elu_fwd(x, alpha_); break; case SQUARE: return square_fwd(x); break; case SQRT: return sqrt_fwd(x); break; case ABS: return abs_fwd(x); break; case EXP: return exp_fwd(x); break; default: return x; break; } #else return x; #endif } DATA_T bwd_eltwise(DATA_T x, DATA_T y, DATA_T alpha_) { #ifdef ALG_KIND switch (ALG_KIND) { case RELU: return relu_bwd(x, y, alpha_); break; case LINEAR: return linear_bwd(x, alpha_); break; case BOUNDED_RELU: return bounded_relu_bwd(x, y, alpha_); break; case SOFT_RELU: return soft_relu_bwd(x, y); break; case LOGISTIC: return logistic_bwd(x, y); break; case TANH: return tanh_bwd(x, y); break; case ELU: return elu_bwd(x, y, alpha_); break; case SQUARE: return square_bwd(x, y); break; case SQRT: return sqrt_bwd(x, y); break; case ABS: return abs_bwd(x, y); break; case EXP: return exp_bwd(x, y); break; default: return x; break; } #else return x; #endif } #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ocl_utils.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <CL/cl_ext.h> #include "ocl/cl_engine.hpp" #include "ocl/ocl_utils.hpp" namespace mkldnn { namespace impl { namespace ocl { namespace ocl_utils { status_t get_ocl_devices( std::vector<cl_device_id> *devices, cl_device_type device_type) { cl_uint num_platforms = 0; cl_int err = clGetPlatformIDs(0, nullptr, &num_platforms); // No platforms - a valid scenario if (err == CL_PLATFORM_NOT_FOUND_KHR) return status::success; OCL_CHECK(err); std::vector<cl_platform_id> platforms(num_platforms); OCL_CHECK(clGetPlatformIDs(num_platforms, &platforms[0], nullptr)); for (size_t i = 0; i < platforms.size(); ++i) { cl_uint num_devices = 0; cl_int err = clGetDeviceIDs( platforms[i], device_type, 0, nullptr, &num_devices); if (!utils::one_of(err, CL_SUCCESS, CL_DEVICE_NOT_FOUND)) { return status::runtime_error; } if (num_devices != 0) { std::vector<cl_device_id> plat_devices; plat_devices.resize(num_devices); OCL_CHECK(clGetDeviceIDs(platforms[i], device_type, num_devices, &plat_devices[0], nullptr)); devices->swap(plat_devices); return status::success; } } // No devices found but still return success return status::success; } } // namespace ocl_utils status_t ocl_jit_t::build(const engine_t *engine) { auto *cl_engine = utils::downcast<const cl_engine_t *>(engine); cl_context ctx = cl_engine->ocl_context(); cl_device_id dev = cl_engine->ocl_device(); cl_int err = CL_SUCCESS; program_ = clCreateProgramWithSource(ctx, 1, &code_, &code_size_, &err); status_t status = ocl_utils::convert_to_mkldnn(err); if (status != status::success) return status; const char *opt_str = options_.data(); err = clBuildProgram(program_, 1, &dev, opt_str, nullptr, nullptr); #ifndef NDEBUG if (err != CL_SUCCESS) { size_t log_length = 0; err = clGetProgramBuildInfo( program_, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &log_length); assert(err == CL_SUCCESS); std::vector<char> log_buf(log_length); err = clGetProgramBuildInfo(program_, dev, CL_PROGRAM_BUILD_LOG, log_length, log_buf.data(), 0); assert(err == CL_SUCCESS); printf("Error during the build of OpenCL program.\nBuild log:\n%s\n", log_buf.data()); } #endif return ocl_utils::convert_to_mkldnn(err); } } // namespace ocl } // namespace impl } // namespace mkldnn <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/bn_activ_fuse_pass.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2019 by Contributors * \file bn_activation_fuse_pass.cc * \brief optimization pass which fuse Activation into BatchNorm * \author <NAME> */ #include <mxnet/base.h> #include <mxnet/operator.h> #include "./exec_pass.h" #include "../operator/nn/activation-inl.h" #include "../operator/nn/batch_norm-inl.h" namespace mxnet { namespace exec { using namespace mxnet::op; namespace { inline bool IsCompatibleActivation(const nnvm::NodePtr& node) { if (node->op() == Op::Get("Activation")) { const auto act_type = nnvm::get<ActivationParam>(node->attrs.parsed).act_type; return act_type == activation::kReLU; } if (node->op() == Op::Get("relu")) { node->attrs.dict["act_type"] = "relu"; } return node->op() == Op::Get("relu"); } inline bool IsCompatibleBN(const nnvm::NodePtr& node, const int& dtype, const TShape& shape, const Context& ctx) { if (node->op() != Op::Get("BatchNorm")) return false; return batchnorm::SupportsFusedActivation(node, dtype, shape, ctx); } } // namespace Graph FuseBNActiv(Graph&& g) { const auto& shape_vec = g.GetAttr<mxnet::ShapeVector>("shape"); const auto& dtype_vec = g.GetAttr<nnvm::DTypeVector>("dtype"); const auto& context_vec = g.GetAttr<ContextVector>("context"); const auto& ig = g.indexed_graph(); const auto ne_counter = GetNodeEntryCount(g); nnvm::NodeEntryMap<nnvm::NodeEntry> entry_map; DFSVisit(g.outputs, [&ne_counter, &entry_map, &ig, &shape_vec, &dtype_vec, &context_vec](const nnvm::NodePtr& n) { if (IsCompatibleActivation(n)) { auto bn = n->inputs[0].node; auto nid = ig.node_id(bn.get()); auto eid = ig.entry_id(nid, 0); if (IsCompatibleBN(bn, dtype_vec[eid], shape_vec[eid], context_vec[nid]) && n->inputs[0].index == 0 && ne_counter.at(n->inputs[0]) == 1) { bn->attrs.dict["act_type"] = n->attrs.dict["act_type"]; bn->attrs.name += "_activ"; bn->op()->attr_parser(&(bn->attrs)); entry_map.insert({nnvm::NodeEntry{n, 0, 0}, nnvm::NodeEntry{bn, 0, 0}}); } } }); g = ReplaceNodeEntries(std::move(g), entry_map); return g; } } // namespace exec } // namespace mxnet <|start_filename|>Google/systems/tpu-v3-1024-TF.json<|end_filename|> { "submitter": "Google", "division": "closed", "status": "research", "system_name": "TPU v3-1024", "number_of_nodes": "64", "host_processors_per_node": "2", "host_processor_model_name": "", "host_processor_core_count": "", "host_processor_vcpu_count": "", "host_processor_frequency": "", "host_processor_caches": "", "host_processor_interconnect": "", "host_memory_capacity": "", "host_storage_type": "", "host_storage_capacity": "", "host_networking": "", "host_networking_topology": "", "host_memory_configuration": "", "accelerators_per_node": "8", "accelerator_model_name": "TPU v3", "accelerator_host_interconnect": "", "accelerator_frequency": "", "accelerator_on-chip_memories": "", "accelerator_memory_configuration": "", "accelerator_memory_capacity": "32 GiB", "accelerator_interconnect": "", "accelerator_interconnect_topology": "2-D toroidal mesh", "cooling": "", "hw_notes": "", "framework": "research-tf", "other_software_stack": "", "operating_system": "", "sw_notes": "" } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/dual_net/lite_dual_net.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/dual_net/lite_dual_net.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/string_view.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" #include "third_party/tensorflow/lite/context.h" #include "third_party/tensorflow/lite/interpreter.h" #include "third_party/tensorflow/lite/kernels/register.h" #include "third_party/tensorflow/lite/model.h" using tflite::ops::builtin::BuiltinOpResolver; namespace minigo { namespace { void Unquantize(const TfLiteQuantizationParams& params, const Tensor<uint8_t>& src, Tensor<float>* dst) { MG_CHECK(src.shape == dst->shape); int size = src.shape.num_elements(); for (int i = 0; i < size; ++i) { dst->data[i] = (src.data[i] - params.zero_point) * params.scale; } } class LiteDualNet : public Model { public: LiteDualNet(const ModelDefinition& def, const FeatureDescriptor& feature_desc); void RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) override; private: void Reserve(int capacity); // The raw model bytes. These bytes must outlive the parsed model, so // `model_bytes_` must be ordered in the list of members before `model_`. // TODO(tommadams): share model bytes between all instances of the same // model. std::string model_bytes_; std::unique_ptr<tflite::FlatBufferModel> model_; std::unique_ptr<tflite::Interpreter> interpreter_; int input_idx_; int policy_idx_; int value_idx_; TfLiteTensor* input_ = nullptr; TfLiteTensor* policy_ = nullptr; TfLiteTensor* value_ = nullptr; std::string graph_path_; int batch_capacity_ = 0; BackedTensor<float> unquantized_policy_; BackedTensor<float> unquantized_value_; }; LiteDualNet::LiteDualNet(const ModelDefinition& def, const FeatureDescriptor& feature_desc) : Model(std::string(file::Stem(def.path)), feature_desc), model_bytes_(def.model_bytes), graph_path_(def.path) { model_ = tflite::FlatBufferModel::BuildFromBuffer(model_bytes_.data(), model_bytes_.size()); MG_CHECK(model_ != nullptr); tflite::ops::builtin::BuiltinOpResolver resolver; tflite::InterpreterBuilder(*model_, resolver)(&interpreter_); MG_CHECK(interpreter_ != nullptr); // Let's just use all the processors we can. interpreter_->SetNumThreads(GetNumLogicalCpus()); const auto& inputs = interpreter_->inputs(); MG_CHECK(inputs.size() == 1); absl::string_view input_name = interpreter_->GetInputName(0); MG_CHECK(input_name == "pos_tensor"); input_idx_ = inputs[0]; // Check that the model matches the board size and feature count. auto* input = interpreter_->tensor(input_idx_); MG_CHECK(input->dims->size == 4); MG_CHECK(input->dims->data[1] == kN); MG_CHECK(input->dims->data[2] == kN); MG_CHECK(input->dims->data[3] == feature_desc.num_planes); const auto& outputs = interpreter_->outputs(); MG_CHECK(outputs.size() == 2); absl::string_view output_0_name = interpreter_->GetOutputName(0); absl::string_view output_1_name = interpreter_->GetOutputName(1); if (output_0_name == "policy_output") { MG_CHECK(output_1_name == "value_output") << output_1_name; policy_idx_ = outputs[0]; value_idx_ = outputs[1]; } else { MG_CHECK(output_1_name == "policy_output") << output_1_name; MG_CHECK(output_0_name == "value_output") << output_0_name; policy_idx_ = outputs[1]; value_idx_ = outputs[0]; } } void LiteDualNet::Reserve(int capacity) { MG_CHECK(capacity > 0); if (capacity == batch_capacity_) { return; } // Resize input tensor to batch size. auto shape = feature_descriptor().GetInputShape(capacity); MG_CHECK(interpreter_->ResizeInputTensor( input_idx_, {shape[0], shape[1], shape[2], shape[3]}) == kTfLiteOk); MG_CHECK(interpreter_->AllocateTensors() == kTfLiteOk); // Get the new inputs and outputs after AllocateTensor(). input_ = interpreter_->tensor(input_idx_); policy_ = interpreter_->tensor(policy_idx_); value_ = interpreter_->tensor(value_idx_); unquantized_policy_.resize({capacity, 1, 1, kNumMoves}); unquantized_value_.resize({capacity, 1, 1, 1}); batch_capacity_ = capacity; } void LiteDualNet::RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) { MG_CHECK(inputs.size() == outputs->size()); Reserve(inputs.size()); Tensor<float> policy, value; const auto& dims = input_->dims->data; switch (input_->type) { case kTfLiteFloat32: { Tensor<float> features({dims[0], dims[1], dims[2], dims[3]}, input_->data.f); feature_descriptor().set_floats(inputs, &features); MG_CHECK(interpreter_->Invoke() == kTfLiteOk); policy = Tensor<float>({batch_capacity_, kNumMoves}, policy_->data.f); value = Tensor<float>({batch_capacity_}, value_->data.f); break; } case kTfLiteUInt8: { Tensor<uint8_t> features({dims[0], dims[1], dims[2], dims[3]}, input_->data.uint8); feature_descriptor().set_bytes(inputs, &features); MG_CHECK(interpreter_->Invoke() == kTfLiteOk); Tensor<uint8_t> quantized_policy({batch_capacity_, kNumMoves}, policy_->data.uint8); Tensor<uint8_t> quantized_value({batch_capacity_}, value_->data.uint8); policy = unquantized_policy_.tensor(); value = unquantized_value_.tensor(); Unquantize(policy_->params, quantized_policy, &policy); Unquantize(value_->params, quantized_value, &value); break; } default: MG_LOG(FATAL) << "Unsupported input type" << input_->type; break; } Model::GetOutputs(inputs, policy, value, absl::MakeSpan(*outputs)); if (model_name != nullptr) { *model_name = graph_path_; } } } // namespace std::unique_ptr<Model> LiteDualNetFactory::NewModel( const ModelDefinition& def) { auto feature_desc = FeatureDescriptor::Create(def.metadata.Get<std::string>("input_features"), def.metadata.Get<std::string>("input_layout")); return absl::make_unique<LiteDualNet>(def, feature_desc); } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/softmax/softmax.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <float.h> #include <math.h> #include "mkldnn.h" #include "src/common/mkldnn_thread.hpp" #include "mkldnn_common.hpp" #include "mkldnn_memory.hpp" #include "softmax/softmax.hpp" namespace softmax { const int64_t global_fill_range = 200; static int init_pd(const prb_t *p, mkldnn_softmax_desc_t &sd, mkldnn_primitive_desc_t &spd, res_t *r) { mkldnn_memory_desc_t data_d; const int ndims = (int)p->dims.size(); DNN_SAFE(mkldnn_memory_desc_init_by_tag( &data_d, ndims, p->dims.data(), p->dt, p->tag), WARN); if (p->dir & FLAG_FWD) { auto prop = p->dir & FLAG_INF ? mkldnn_forward_inference : mkldnn_forward_training; DNN_SAFE(mkldnn_softmax_forward_desc_init(&sd, prop, &data_d, p->axis), WARN); } else { DNN_SAFE(mkldnn_softmax_backward_desc_init(&sd, &data_d, &data_d, p->axis), WARN); } mkldnn_status_t init_status = mkldnn_primitive_desc_create(&spd, &sd, NULL, engine_tgt, NULL); if (init_status == mkldnn_unimplemented) return r->state = UNIMPLEMENTED, OK; else SAFE(init_status, WARN); const char *impl_str = query_impl_info(spd); if (maybe_skip(skip_impl, impl_str)) { print(2, "SKIPPED: mkldnn implementation: %s\n", impl_str); DNN_SAFE(mkldnn_primitive_desc_destroy(spd), WARN); return r->state = SKIPPED, OK; } else { print(5, "mkldnn implementation: %s\n", impl_str); } return OK; } static int compare(const prb_t *p, const dnn_mem_t &fp_mem, const dnn_mem_t &dt_mem, res_t *r) { // FWD // When axis_size is big, significant values will be only in points with the // biggest values are. So we adjust machine epsilon to the amount of such // inputs, which is equally distibuted by fill_data(), thus, dividing // axis_size by global_fill_range gives that number. // When axis_size is small, significant values are coming not only from the // biggest input, but also from some smaller. For this case we estimate the // amount of such number by log2f(axis_size). // TODO: sse41 exp has lower accuracy, so for now we take max(log2(x), 10). // 10 is taken empirically considering it's close to log2 value. // The final criterion picks the max of these numbers. // BWD // We have sum over axis dim, the worst case for error is amount of elements // times machine eps and additional subtract. const float num_significant_values = MAX2(div_up(p->dims[p->axis], global_fill_range), MAX2(log2f(p->dims[p->axis]), 10)); const int f32_mant_digits = 24; const float trh_coeff = (1 << (f32_mant_digits - digits_dt(p->dt))); const float trh = trh_coeff * 1e-7 * (p->dir & FLAG_FWD ? num_significant_values : (p->dims[p->axis] + 1)); const auto nelems = dt_mem.nelems(); r->errors = 0; r->total = nelems; for (int64_t i = 0; i < nelems; i++) { const float dt = dt_mem.get_elem(i); const float fp = fp_mem.get_elem(i); const float diff = fabsf(fp - dt); const float rel_diff = diff / (fabsf(fp) > FLT_MIN ? fabsf(fp) : 1); const bool ok = (fabsf(fp) > 1e-5 ? rel_diff : diff) <= trh; r->errors += !ok; const bool dump = false || (!ok && (r->errors < 10 || verbose >= 10)) || (verbose >= 50 && i < 30) || (verbose >= 99); if (dump) { std::stringstream ss; dims_t dims_idx = off2dims_idx(p->dims, i); ss << dims_idx; std::string ind_str = ss.str(); print(0, "[%4ld][%s] fp:%8g dt:%8g diff:%8g rdiff:%8g\n", (long)i, ind_str.c_str(), fp, dt, diff, rel_diff); } } if (r->errors) r->state = FAILED; if (r->state == UNTESTED) r->state = PASSED; /* optimism */ return r->state == FAILED ? FAIL : OK; } int fill_data_fwd(const prb_t *p, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp) { const auto nelems = mem_fp.nelems(); mkldnn::impl::parallel_nd(nelems, [&](int64_t i) { int64_t mb{0}, c{0}; map_off_to_mb_ic(p, i, mb, c); const float f_min = ((p->axis > 0) ? mb : c) % 2 == 0 ? -global_fill_range : -global_fill_range / 2; const float gen = ((11 * i) + 37) % global_fill_range; const float value = f_min + gen; mem_fp.set_elem(i, value); } ); SAFE(mem_dt.reorder(mem_fp), WARN); return OK; } int fill_data_bwd(const prb_t *p, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp) { const auto nelems = mem_fp.nelems(); // keep all values negative to have sum and sub of same sign, avoiding // cancellation error. mkldnn::impl::parallel_nd(nelems, [&](int64_t i) { const float gen = ((11 * i) + 37) % global_fill_range; const float value = -gen / global_fill_range; mem_fp.set_elem(i, value); } ); SAFE(mem_dt.reorder(mem_fp), WARN); return OK; } int doit(const prb_t *p, res_t *r) { mkldnn_softmax_desc_t sd; mkldnn_primitive_desc_t spd; mkldnn_primitive_t s; SAFE(init_pd(p, sd, spd, r), WARN); if (r->state == SKIPPED || r->state == UNIMPLEMENTED) return OK; DNN_SAFE(mkldnn_primitive_create(&s, spd), WARN); DNN_SAFE(mkldnn_primitive_desc_destroy(spd), CRIT); const auto fp = mkldnn_f32; const auto tag = get_default_tag((int)p->dims.size()); auto &data_desc = sd.data_desc; dnn_mem_t src_fp(data_desc, fp, tag, engine_ref), src_dt(data_desc, engine_tgt); dnn_mem_t dst_fp(data_desc, fp, tag, engine_ref); dnn_mem_t dst_dt; if (!p->inplace) { dst_dt = dnn_mem_t(data_desc, engine_tgt); SAFE(dst_dt.reorder(dst_fp), WARN); } dnn_mem_t d_dst_fp(data_desc, fp, tag, engine_ref), d_dst_dt(data_desc, engine_tgt); dnn_mem_t d_src_fp(data_desc, fp, tag, engine_ref); dnn_mem_t d_src_dt; if (!p->inplace) { d_src_dt = dnn_mem_t(data_desc, engine_tgt); SAFE(d_src_dt.reorder(d_src_fp), WARN); } args_t args; if (p->dir & FLAG_FWD) { SAFE(fill_data_fwd(p, src_dt, src_fp), WARN); args.set(MKLDNN_ARG_SRC, src_dt.m_); args.set(MKLDNN_ARG_DST, p->inplace ? src_dt.m_ : dst_dt.m_); DNN_SAFE(execute_and_wait(s, stream_tgt, args.size(), args), WARN); if (bench_mode & CORR) { compute_ref_fwd(p, src_fp, dst_fp); dnn_mem_t dst(p->inplace ? src_dt : dst_dt, fp, tag, engine_ref); SAFE(compare(p, dst_fp, dst, r), WARN); } } else { SAFE(fill_data_bwd(p, src_dt, src_fp), WARN); SAFE(fill_data_bwd(p, d_dst_dt, d_dst_fp), WARN); args.set(MKLDNN_ARG_DST, src_dt.m_); args.set(MKLDNN_ARG_DIFF_DST, d_dst_dt.m_); args.set(MKLDNN_ARG_DIFF_SRC, p->inplace ? d_dst_dt.m_ : d_src_dt.m_); DNN_SAFE(execute_and_wait(s, stream_tgt, args.size(), args), WARN); if (bench_mode & CORR) { compute_ref_bwd(p, src_fp, d_dst_fp, d_src_fp); dnn_mem_t d_src(p->inplace ? d_dst_dt : d_src_dt, fp, tag, engine_ref); SAFE(compare(p, d_src_fp, d_src, r), WARN); } } measure_perf(r->timer, s, args); DNN_SAFE(mkldnn_primitive_destroy(s), CRIT); return OK; } } <|start_filename|>DellEMC/benchmarks/ssd/implementation/mxnet/tests/horovod_mpi_test.cpp<|end_filename|> #include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <random> #include <vector> #include <mpi.h> #define NWARMUP 1000 #define NTRIALS 10000 int main() { // Initialize MPI with thread support like Horovod int mpi_threads_required = MPI_THREAD_MULTIPLE; int mpi_threads_provided; MPI_Init_thread(nullptr, nullptr, mpi_threads_required, &mpi_threads_provided); int comm_rank, comm_size; MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank); MPI_Comm_size(MPI_COMM_WORLD, &comm_size); // Randomly initialize vector of 2 long long (used for Horovod coordination) std::random_device rd; std::mt19937_64 rng(rd()); std::uniform_int_distribution<long long> dist; std::vector<long long> vec(2); vec[0] = dist(rng); vec[1] = dist(rng); // Warmup if (comm_rank == 0) std::cout << "Running " << NWARMUP << " warmup MPI_Allreduce trials..." << std::endl; for (int i = 0; i < NWARMUP; i++) { int ret_code = MPI_Allreduce(MPI_IN_PLACE, vec.data(), vec.size(), MPI_LONG_LONG_INT, MPI_BAND, MPI_COMM_WORLD); } // Trials if (comm_rank == 0) std::cout << "Running " << NTRIALS << " MPI_Allreduce trials..." << std::endl; double latency_max = 0; double latency_min = 1000000; double duration_ms_trials = 0; MPI_Barrier(MPI_COMM_WORLD); for (int i = 0; i < NTRIALS; i++) { auto tst = std::chrono::high_resolution_clock::now(); int ret_code = MPI_Allreduce(MPI_IN_PLACE, vec.data(), vec.size(), MPI_LONG_LONG_INT, MPI_BAND, MPI_COMM_WORLD); auto tet = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(tet - tst); double duration_trial_ms = duration.count() / 1000000.0; latency_min = std::min(latency_min, duration_trial_ms); latency_max = std::max(latency_max, duration_trial_ms); duration_ms_trials += duration_trial_ms; } double latency_avg = duration_ms_trials / NTRIALS; // Reduce min, max, and average latencies across all workers and trials double latency_min_global, latency_max_global, latency_avg_global; MPI_Reduce(&latency_min, &latency_min_global, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); MPI_Reduce(&latency_max, &latency_max_global, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); MPI_Reduce(&latency_avg, &latency_avg_global, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (comm_rank == 0) { std::cout << "global MIN latency: " << latency_min_global << " ms" << std::endl; std::cout << "global MAX latency: " << latency_max_global << " ms" << std::endl; std::cout << "global AVG latency: " << latency_avg_global / comm_size << " ms" << std::endl; } MPI_Finalize(); } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ocl_executor.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_EXECUTOR_HPP #define OCL_EXECUTOR_HPP #include "ocl/cl_executor.hpp" namespace mkldnn { namespace impl { namespace ocl { struct ocl_stream_t; // Implementation of cl_executor_t for OpenCL struct ocl_executor_t : public cl_executor_t { ocl_executor_t(ocl_stream_t *stream); virtual status_t parallel_for( const cl_nd_range_t &range, const ocl_kernel_t &kernel) override; virtual status_t copy(const memory_storage_t &src, const memory_storage_t &dst, size_t size) override; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/anchor_generator.cu<|end_filename|> /****************************************************************************** * * Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 <torch/extension.h> #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <THC/THCNumerics.cuh> #include <THC/THC.h> #include <cuda.h> #include <vector> __device__ float4 add_boxes(const float4& a, const float4& b) { return float4{a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; } /** * Essentially bolis down to a grid-stride loop * - get the index of the output and backtrack what its values should * be based on the arange that would have been created. * - Easy parallelism - use (BSZ_X, A) as block dimensions to parallelize over * the A anchors used. * - Accesses to global memory are all done via. float4 */ __global__ void generate_anchors_single(const int image_height, const int image_width, const int feature_height, const int feature_width, const float4* anchor_data, // [1, 3, 4] const int stride, const int A, float4 *anchors, const float straddle_thresh, uint8_t* inds_inside) { // size of arange is floor(start - end / step) // in this case, floor((feature{height,width} * stride - 0) / stride) const int len_x = (int)floorf(feature_width); const int len_y = (int)floorf(feature_height); #if 0 if (threadIdx.x == 0 && threadIdx.y == 0 && blockIdx.x == 0) { printf("len_x: %d, len_y: %d\n", len_x, len_y); } #endif // Standard grid-stride loop over output size for (int output_idx = threadIdx.x + blockIdx.x * blockDim.x; output_idx < len_x * len_y; output_idx += gridDim.x * blockDim.x) { // local box is (xp, yp, xp, yp) // where xp = x[output_idx % len(x)] // yp = y[output_idx / len(y)] // and x = (output_idx % len(x)) * step // y = (output_idx / len(y)) * step const float x = (output_idx % len_x) * stride; const float y = (output_idx / len_x) * stride; // This is the basic box float4 box{x, y, x, y}; // parallelize over anchors const int i = threadIdx.y; // for (int i = 0; i < A; ++i) { const float4 a = anchor_data[i]; float4 tmp = add_boxes(box, a); anchors[output_idx * A + i] = tmp; // for each anchor, now check if (straddle_thresh >= 0.f) { inds_inside[output_idx * A + i] = (tmp.x >= -straddle_thresh) & (tmp.y >= -straddle_thresh) & (tmp.z < image_width + straddle_thresh) & (tmp.w < image_height + straddle_thresh); } else { inds_inside[output_idx * A + i] = 1; } } } std::vector<at::Tensor> anchor_generator( std::vector<int64_t> image_shape, // (height, width) std::vector<int64_t> feature_map_size, // (height, width) at::Tensor& cell_anchors, // shape: [1, 3, 4] const int stride, const float straddle_thresh) { // Need to work out some sizes for the kernel const float h_start = 0.; const float h_end = feature_map_size[0] * stride; const int h_elems = (int)std::floor( (h_end - h_start) / stride ); const float w_start = 0., w_end = feature_map_size[1] * stride; const int w_elems = (int)std::floor( (w_end - w_start) / stride ); // If cell anchors are [A, 4] const int A = cell_anchors.size(0); // output anchors are h_elems * w_elems * A * 4 values, so allocate that now. at::Tensor anchors = torch::zeros({h_elems * w_elems * A, 4}, torch::CUDA(at::kFloat)); // also output a bool map of anchors being inside the image at::Tensor inds_inside = torch::zeros({h_elems * w_elems * A}, torch::CUDA(at::kByte)); // CUDA grid is going to be (32, A) * (h_elems * w_elems / 32) const int blockx = 64; dim3 block(blockx, A); dim3 grid((h_elems * w_elems + (blockx - 1)) / blockx); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); generate_anchors_single<<<grid, block, 0, stream>>>( image_shape[0], image_shape[1], feature_map_size[0], feature_map_size[1], reinterpret_cast<float4*>(cell_anchors.data_ptr<float>()), stride, A, reinterpret_cast<float4*>(anchors.data_ptr<float>()), straddle_thresh, inds_inside.data_ptr<uint8_t>()); THCudaCheck(cudaGetLastError()); return {anchors, inds_inside}; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/bfloat16.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <memory> #include "jit_avx512_core_bf16cvt.hpp" #include "bfloat16.hpp" #include "cpu_isa_traits.hpp" namespace mkldnn { namespace impl { using namespace cpu::bf16_support; union float_raw { float fraw; uint16_t iraw[2]; }; bfloat16_t &bfloat16_t::operator=(float f) { assert(cpu::mayiuse(cpu::cpu_isa_t::avx512_core)); jit_call_t p; p.inp = (void *)&f; p.out = (void *)this; static const cpu::jit_avx512_core_cvt_ps_to_bf16_t cvt_one_ps_to_bf16(1); cvt_one_ps_to_bf16.jit_ker(&p); return *this; } bfloat16_t::operator float() const { assert(cpu::mayiuse(cpu::cpu_isa_t::avx512_core)); float_raw r = {0}; r.iraw[1] = raw_bits_; r.iraw[0] = 0; return r.fraw; } void cvt_float_to_bfloat16(bfloat16_t *out, const float *inp, size_t size) { assert(cpu::mayiuse(cpu::cpu_isa_t::avx512_core)); jit_call_t p_; p_.inp = (void *)inp; p_.out = (void *)out; p_.size = size; static const cpu::jit_avx512_core_cvt_ps_to_bf16_t cvt_ps_to_bf16; cvt_ps_to_bf16.jit_ker(&p_); } void cvt_bfloat16_to_float(float *out, const bfloat16_t *inp, size_t size) { assert(cpu::mayiuse(cpu::cpu_isa_t::avx512_core)); jit_call_t p_; p_.inp = (void *)inp; p_.out = (void *)out; p_.size = size; static const cpu::jit_avx512_core_cvt_bf16_to_ps_t cvt_bf16_to_ps; cvt_bf16_to_ps.jit_ker(&p_); } void add_floats_and_cvt_to_bfloat16(bfloat16_t *out, const float *inp0, const float *inp1, size_t size) { assert(cpu::mayiuse(cpu::cpu_isa_t::avx512_core)); jit_call_t p_; p_.inp = (void *)inp0; p_.add = (void *)inp1; p_.out = (void *)out; p_.size = size; static const cpu::jit_avx512_core_add_cvt_ps_to_bf16_t add_cvt_ps_to_bf16; add_cvt_ps_to_bf16.jit_ker(&p_); } } //namespace impl } // namespace mkldnn <|start_filename|>Inspur/benchmarks/dlrm/implementations/implementation_closed/src/gather_gpu.cu<|end_filename|> #include <cuda.h> #include <cuda_fp16.h> #include <cuda_runtime.h> #include <math.h> #include <cassert> #include <iostream> #include <ATen/cuda/CUDAContext.h> #include <torch/extension.h> // For simplicity reason, boundry checks are removed // All the kernels MUST be launched with grid size = batch size and block size = embedding size __global__ void GatherKernel(const float* params, int64_t num_features, int embed_size, int batch_size, int query_nnz, const int64_t* indices, float* ret) { int tid = threadIdx.x, bid = blockIdx.x; extern __shared__ int shmem_indices[]; // each CTA load one row of indices in the mini batch into shared memory for (int i = tid; i < query_nnz; i += blockDim.x) { shmem_indices[i] = indices[query_nnz * bid + i]; } __syncthreads(); #pragma unroll for (int i = 0; i < query_nnz; ++i) { // printf("%d, %d, %d\n", bid, i, shmem_indices[i]); ret[(bid * query_nnz + i) * embed_size + tid] = params[(int64_t)shmem_indices[i] * embed_size + tid]; } } __global__ void OneHotKernel(const float* params, int64_t num_features, int embed_size, int batch_size, const int64_t* indices, float* ret) { int tid = threadIdx.x, bid = blockIdx.x; ret[bid * embed_size + tid] = params[(int64_t)indices[bid] * embed_size + tid]; } // grads is used to update params directly by atomic instead of forming wgrad // Only SGD without momentum and without weight decay is supported __global__ void GatherBackwardFuseSgdKernel(const float* grads, int64_t num_features, int embed_size, int batch_size, int query_nnz, const int64_t* indices, float lr, float* params) { int tid = threadIdx.x, bid = blockIdx.x; extern __shared__ int shmem_indices[]; for (int i = tid; i < query_nnz; i += blockDim.x) { shmem_indices[i] = indices[query_nnz * bid + i]; } __syncthreads(); #pragma unroll for (int i = 0; i < query_nnz; ++i) { atomicAdd(&params[(int64_t)shmem_indices[i] * embed_size + tid], -lr * grads[(bid * query_nnz + i) * embed_size + tid]); } } // Keep the interface and argument name as torch.embedding() // input is indices, and weight is embedding table torch::Tensor gather_gpu_fwd(const torch::Tensor weight, const torch::Tensor indices) { AT_ASSERT(indices.is_cuda()); AT_ASSERT(weight.is_cuda()); AT_ASSERT(indices.scalar_type() == torch::ScalarType::Long); AT_ASSERT(weight.scalar_type() == torch::ScalarType::Float); AT_ASSERT(weight.is_contiguous()); int batch_size = indices.size(0); int query_nnz = 1; if (indices.dim() > 1) { query_nnz = indices.size(1); } // Shared memory size limit. Larger nnz can also be supported by skipping shared memory if necessary TORCH_CHECK(query_nnz <= 12288, "Embedding width must be smaller than 48k"); int num_features = weight.size(0); int embed_size = weight.size(1); // Block dimension limit. Large than 1024 width can be easily supported by letting each block read // from different strides if necessary. TORCH_CHECK(embed_size <= 1024, "Embedding width must be smaller than 1024"); auto outputs = torch::empty(batch_size * query_nnz * embed_size, at::device(at::kCUDA).dtype(at::kFloat)); if (query_nnz != 1) { GatherKernel<<<batch_size, embed_size, query_nnz * sizeof(int), at::cuda::getCurrentCUDAStream()>>>(weight.data_ptr<float>(), num_features, embed_size, batch_size, query_nnz, indices.contiguous().data_ptr<int64_t>(), outputs.data_ptr<float>()); } else { OneHotKernel<<<batch_size, embed_size, 0, at::cuda::getCurrentCUDAStream()>>>( weight.data_ptr<float>(), num_features, embed_size, batch_size, indices.contiguous().data_ptr<int64_t>(), outputs.data_ptr<float>()); } return outputs.reshape({batch_size, query_nnz, embed_size}); } // Because complication of handling sparse tensor, use the native backward function is still faster // TODO(haow): Figure out a way to write out sparse tensor directly to avoid addintional copy which makes // customized implementation slower than Pytorch's own desipte kernels are more efficient torch::Tensor gather_gpu_bwd(const torch::Tensor grad, const torch::Tensor indices, const int num_features) { return at::embedding_sparse_backward(grad, indices, num_features, /*padding_idx=*/-1, /*scale_grad_by_freq=*/false); } // Backward gather with fused plain SGD (no weight decay nor momentum) void gather_gpu_bwd_fuse_sgd(const torch::Tensor grad, const torch::Tensor indices, float lr, torch::Tensor weight) { AT_ASSERT(grad.is_cuda()); AT_ASSERT(indices.is_cuda()); AT_ASSERT(weight.is_cuda()); AT_ASSERT(grad.scalar_type() == torch::ScalarType::Float); AT_ASSERT(indices.scalar_type() == torch::ScalarType::Long); AT_ASSERT(weight.scalar_type() == torch::ScalarType::Float); AT_ASSERT(weight.is_contiguous()); int batch_size = indices.size(0); int query_nnz = 1; if (indices.dim() > 1) { query_nnz = indices.size(1); } int num_features = weight.size(0); int embed_size = weight.size(1); GatherBackwardFuseSgdKernel<<<batch_size, embed_size, query_nnz * sizeof(int), at::cuda::getCurrentCUDAStream()>>>( grad.contiguous().data_ptr<float>(), num_features, embed_size, batch_size, query_nnz, indices.contiguous().data_ptr<int64_t>(), lr, weight.data_ptr<float>()); } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/executor/infer_graph_attr_pass.cc<|end_filename|> /* * 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 infer_graph_attr_pass.cc * \brief infer graph shape, dtype, and storage type */ #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <mxnet/imperative.h> #include "./exec_pass.h" #include "../operator/operator_common.h" #include "../common/exec_utils.h" namespace mxnet { namespace exec { template<typename AttrType, typename FInfer> bool ApplyOpInferAttr(const nnvm::Graph& g, const FInfer& finfer, const NodeAttrs& attrs, const uint32_t nid, std::vector<AttrType>* in_attrs, std::vector<AttrType>* out_attrs, DispatchMode* dispatch_mode) { return finfer(attrs, in_attrs, out_attrs); } template<> bool ApplyOpInferAttr<int, FInferStorageType>(const nnvm::Graph& g, const FInferStorageType& finfer, const NodeAttrs& attrs, const uint32_t nid, std::vector<int>* in_attrs, std::vector<int>* out_attrs, DispatchMode* dispatch_mode) { const DevMaskVector& dev_masks = g.GetAttr<DevMaskVector>("dev_mask"); const bool success = finfer(attrs, dev_masks[nid], dispatch_mode, in_attrs, out_attrs); if (!success) { LOG(FATAL) << "Operator not implemented: " << common::operator_stype_string(attrs, dev_masks[nid], *in_attrs, *out_attrs); } if (*dispatch_mode == DispatchMode::kFComputeFallback) { common::LogStorageFallback(attrs, dev_masks[nid], in_attrs, out_attrs); } return true; } template<typename AttrType, typename IsNone> inline void GetAttrFromForwardNode(const uint32_t nid, const nnvm::IndexedGraph &idx, std::vector<AttrType>* rshape_ptr, std::vector<bool>* inference_finished, IsNone fis_none) { std::vector<AttrType>& rshape = *rshape_ptr; const auto& inode = idx[nid]; // gradient function, used to get node correspondence. static auto& fgrad = Op::GetAttr<nnvm::FGradient>("FGradient"); nnvm::NodePtr fwd_ptr = inode.source->control_deps[0]; const nnvm::IndexedGraph::Node& fnode = idx[inode.control_deps[0]]; // use gradient function to find out the correspondence. std::vector<nnvm::NodeEntry> ograd(fwd_ptr->num_outputs()); for (size_t i = 0; i < ograd.size(); ++i) { ograd[i].index = static_cast<uint32_t>(i); } // input gradient list const std::vector<nnvm::NodeEntry>& igrad = fgrad[fwd_ptr->op()](fwd_ptr, ograd); const nnvm::Node* igrad_node = nullptr; bool all_attrs_known = true; // Input gradient assignement for (size_t i = 0; i < igrad.size(); ++i) { if (igrad[i].node->op() == inode.source->op()) { uint32_t eid = idx.entry_id(nid, igrad[i].index); if (fis_none(rshape[idx.entry_id(fnode.inputs[i])])) { // Need to skip empty forward shape, because it may not be // available now and it is possible to infer the forward // shape in one of the next a few passes all_attrs_known = false; } else { if (fis_none(rshape[eid])) { rshape[eid] = rshape[idx.entry_id(fnode.inputs[i])]; } else { CHECK_EQ(rshape[eid], rshape[idx.entry_id(fnode.inputs[i])]) << "Backward shape inconsistent with the forward shape"; } } if (igrad_node == nullptr) { igrad_node = igrad[i].node.get(); } else { CHECK(igrad_node == igrad[i].node.get()); } } } // out grad entries CHECK(igrad_node != nullptr) << "Cannot find matching backward op for " << inode.source->attrs.name; for (size_t i = 0; i < igrad_node->inputs.size(); ++i) { const nnvm::NodeEntry& e = igrad_node->inputs[i]; if (e.node == nullptr) { uint32_t eid = idx.entry_id(inode.inputs[i]); if (fis_none(rshape[eid])) { rshape[eid] = rshape[idx.entry_id(inode.control_deps[0], e.index)]; } if (fis_none(rshape[eid])) { // If the attr is still unknown all_attrs_known = false; } } } (*inference_finished)[nid] = all_attrs_known; } template<typename FAccessSubgraphType, typename AttrType, typename IsNone> void GetAttrFromFusedNode(uint32_t nid, const nnvm::IndexedGraph& idx, std::vector<AttrType>* rshape_ptr, std::vector<bool>* inference_finished, IsNone fis_none, const std::string& infer_fusion_name) { std::vector<AttrType>& rshape = *rshape_ptr; const auto& inode = idx[nid]; // gradient function, used to get node correspondence. static auto& fgrad = Op::GetAttr<nnvm::FGradient>("FGradient"); nnvm::NodePtr fused_fwd_ptr = inode.source->control_deps[0]; static auto& finfer_fused_shape = Op::GetAttr<FAccessSubgraphType>(infer_fusion_name); auto finfer = finfer_fused_shape.get(fused_fwd_ptr->op(), nullptr); CHECK(finfer != nullptr) << "Operator " << fused_fwd_ptr->attrs.name << " is marked as Fusion but does not allow accessing attributes"; const auto& inferred_attrs = finfer(fused_fwd_ptr->attrs); const auto& fwd_ptr = std::get<0>(inferred_attrs); const auto& input_attrs = std::get<1>(inferred_attrs); const auto& output_attrs = std::get<2>(inferred_attrs); // use gradient function to find out the correspondence. std::vector<nnvm::NodeEntry> ograd(fwd_ptr->num_outputs()); for (size_t i = 0; i < ograd.size(); ++i) { ograd[i].index = static_cast<uint32_t>(i); } // input gradient list const std::vector<nnvm::NodeEntry>& igrad = fgrad[fwd_ptr->op()](fwd_ptr, ograd); const nnvm::Node* igrad_node = nullptr; bool all_attrs_known = true; // Set the attributes of output gradients // using attributes of forward node inputs for (size_t i = 0; i < igrad.size(); ++i) { if (igrad[i].node->op() == inode.source->op()) { uint32_t eid = idx.entry_id(nid, igrad[i].index); if (fis_none(input_attrs[i])) { // Need to skip empty forward shape, because it may not be // available now and it is possible to infer the forward // shape in one of the next a few passes all_attrs_known = false; } else { if (fis_none(rshape[eid])) { rshape[eid] = input_attrs[i]; } else { CHECK_EQ(rshape[eid], input_attrs[i]) << "Backward shape inconsistent with the forward shape"; } } if (igrad_node == nullptr) { igrad_node = igrad[i].node.get(); } else { CHECK(igrad_node == igrad[i].node.get()); } } } // Set the attributes of input gradients // using attributes of forward node outputs CHECK(igrad_node != nullptr) << "Cannot find matching backward op for " << inode.source->attrs.name; for (size_t i = 0; i < igrad_node->inputs.size(); ++i) { const nnvm::NodeEntry& e = igrad_node->inputs[i]; if (e.node == nullptr) { uint32_t eid = idx.entry_id(inode.inputs[i]); if (fis_none(rshape[eid])) { rshape[eid] = output_attrs[e.index]; } if (fis_none(rshape[eid])) { // If the attr is still unknown all_attrs_known = false; } } } (*inference_finished)[nid] = all_attrs_known; } template <typename FProvideSubgraphType, typename AttrType> void ProvideAttrToFusion(const uint32_t nid, const nnvm::IndexedGraph& idx, const std::vector<AttrType>& rshape, const std::string& provide_fusion_name) { const auto& inode = idx[nid]; std::vector<std::vector<AttrType>> in_attrs; std::vector<std::vector<AttrType>> out_attrs; for (const auto& dep_node : inode.source->control_deps) { in_attrs.push_back({}); out_attrs.push_back({}); auto &current_in_attrs = in_attrs.back(); auto &current_out_attrs = out_attrs.back(); uint32_t dep_node_id = idx.node_id(dep_node.get()); for (const auto& e : idx[dep_node_id].inputs) { current_in_attrs.push_back(rshape[idx.entry_id(e)]); } for (size_t i = 0; i < dep_node->num_outputs(); ++i) { current_out_attrs.push_back(rshape[idx.entry_id(dep_node_id, i)]); } } auto provide = Op::GetAttr<FProvideSubgraphType>(provide_fusion_name).get(inode.source->op(), nullptr); CHECK(provide != nullptr) << "Encountered Fusion operator that does not implement providing subgraph attr " << provide_fusion_name << "."; provide(inode.source->attrs, inode.source->control_deps, in_attrs, out_attrs); } /*!\brief * This is a duplicate of the InferAttr function in nnvm with minor modification * to support inferring storage type whose function signature is different from * shape/type inference functions'. The nnvm InferAttr will be deprecated * in the future. Please use interfaces InferShape, InferType, and InferStorageType * to call this function. * * \param ret graph used for attribute inference * \param emmpty_val empty value of the attribute * \param infer_name name of the function used for attribute inference * \param infer_fusion_name name of the function used for accessing attributes in fused nodes * \param input_name name of the attribute in the graph used to store the * input data for attribute inference * \param attr_key_name name of the attribute used for inference for variable nodes * \param attr_name name of the inferred attribute * \param unknown_name name of the attribute storing number of entries * impossible to infer * \param fis_none function returning true for not fully inferred values * \param fdefault default function used for inference if the node does not * provide its own implementation. * \param bwd_identity_assign whether the attributes of forward NDArray and backward * NDArray have to be the same. False only for storage * type inference * \param dispatch_mode_name name of the dispatch mode attribute on the node. Used for * storage type inference * \param default_mode_val default value of the dispatch mode attribute on the node. Used * for storage type inference */ template<typename AttrType, typename FInferType, typename FAccessSubgraphType, typename FProvideSubgraphType, typename IsNone, typename FDefault, typename FNumUnknown> nnvm::Graph InferAttr(nnvm::Graph &&ret, const AttrType empty_val, const char* infer_name, const char* infer_fusion_name, const char* provide_fusion_name, const char* input_name, const char* attr_key_name, const char* attr_name, const char* unknown_name, IsNone fis_none, FNumUnknown fnum_unknown, FDefault fdefault, bool scalars_only, bool bwd_identity_assign, const char* dispatch_mode_name, const DispatchMode default_mode_val = DispatchMode::kUndefined) { using nnvm::IndexedGraph; using nnvm::Op; using AttrVector = std::vector<AttrType>; using NodeAttrVector = std::vector<DispatchMode>; using dmlc::any; const IndexedGraph& idx = ret.indexed_graph(); static auto& finfer_shape = Op::GetAttr<FInferType>(infer_name); static auto& is_backward = Op::GetAttr<nnvm::TIsBackward>("TIsBackward"); // reshape shape vector AttrVector rshape; // vector holding information which operators // finished attribute inference std::vector<bool> inference_finished(idx.num_nodes(), false); // dispatch mode vector DispatchModeVector dispatch_modes; if (ret.attrs.count(attr_name) != 0) { rshape = ret.MoveCopyAttr<AttrVector>(attr_name); } else { rshape.resize(idx.num_node_entries(), empty_val); } if (ret.attrs.count(input_name) != 0) { const AttrVector& shape_args = ret.GetAttr<AttrVector>(input_name); CHECK_LE(shape_args.size(), idx.input_nodes().size()) << "More provided " << attr_name << "s than number of arguments."; for (size_t i = 0; i < shape_args.size(); ++i) { rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i]; } } // get the shape hints std::string shape_hints_key = std::string(attr_name) + "_hints"; if (ret.attrs.count(shape_hints_key)) { nnvm::NodeEntryMap<AttrType> shape_hints = ret.GetAttr<nnvm::NodeEntryMap<AttrType>>(shape_hints_key); for (const auto& kv : shape_hints) { nnvm::NodeEntry e = kv.first; if (idx.exist(e.node.get())) { rshape[idx.entry_id(kv.first)] = kv.second; } } } std::string shape_attr_key; if (ret.attrs.count(attr_key_name) != 0) { shape_attr_key = ret.GetAttr<std::string>(attr_key_name); // erase the provided arguments ret.attrs.erase(attr_key_name); } // limit inference to part of the graph uint32_t node_start = 0, node_end = idx.num_nodes(); if (ret.attrs.count("node_range")) { const auto& range = ret.GetAttr<std::pair<uint32_t, uint32_t> >("node_range"); node_start = range.first; node_end = range.second; CHECK_GE(node_start, 0); CHECK_LE(node_end, idx.num_nodes()); ret.attrs.erase("node_range"); } uint32_t entry_start = 0, entry_end = idx.num_node_entries(); if (ret.attrs.count("entry_range")) { const auto& range = ret.GetAttr<std::pair<uint32_t, uint32_t> >("entry_range"); entry_start = range.first; entry_end = range.second; CHECK_GE(entry_start, 0); CHECK_LE(entry_end, idx.num_node_entries()); ret.attrs.erase("entry_range"); } // populate the node attribute vector if (dispatch_mode_name != nullptr) { if (ret.attrs.count(dispatch_mode_name) != 0) { dispatch_modes = ret.MoveCopyAttr<NodeAttrVector>(dispatch_mode_name); } else { LOG(FATAL) << "Node attribute " << dispatch_mode_name << " does not exist in the graph"; } } // Temp space for shape inference. std::vector<AttrType> ishape, oshape; // inference step function for nid auto infer_step = [&](uint32_t nid, bool last_iter) { if (inference_finished[nid]) return; const auto& inode = idx[nid]; const uint32_t num_inputs = inode.inputs.size(); const uint32_t num_outputs = inode.source->num_outputs(); if (inode.source->is_variable()) { // Variable node. No operator. Only one output entry. CHECK(inode.source->op() == nullptr); CHECK_EQ(num_outputs, 1U); const uint32_t out_ent_id = idx.entry_id(nid, 0); if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) { auto it = inode.source->attrs.dict.find(shape_attr_key); if (it != inode.source->attrs.dict.end()) { std::istringstream is(it->second); CHECK(is >> rshape[out_ent_id]) << "Invalid attribute"; } } if (!fis_none(rshape[out_ent_id])) { inference_finished[nid] = true; } // assign a default value to node attribute if (dispatch_mode_name != nullptr) { op::dispatch_mode_assign(&dispatch_modes[nid], default_mode_val); } } else if (is_backward.get(inode.source->op(), false) && inode.source->control_deps.size() && bwd_identity_assign) { CHECK(dispatch_mode_name == nullptr) << "Backward inference for node attributes is not available"; CHECK_GE(inode.source->control_deps.size(), 1U) << "BackwardOp need to have control_deps to its forward op"; nnvm::NodePtr fwd_ptr = inode.source->control_deps[0]; CHECK(fwd_ptr->op() != nullptr) << "Forward op cannot be a variable"; static auto& is_fusion_helper = Op::GetAttr<exec::TIsFusionHelper>("TIsFusionHelper"); if (!is_fusion_helper.get(fwd_ptr->op(), false)) { GetAttrFromForwardNode(nid, idx, &rshape, &inference_finished, fis_none); } else { GetAttrFromFusedNode<FAccessSubgraphType>(nid, idx, &rshape, &inference_finished, fis_none, infer_fusion_name); } } else { DispatchMode* dispatch_mode = nullptr; // Forward operator inference. ishape.resize(num_inputs, empty_val); for (uint32_t i = 0; i < ishape.size(); ++i) { ishape[i] = rshape[idx.entry_id(inode.inputs[i])]; } oshape.resize(num_outputs, empty_val); for (uint32_t i = 0; i < oshape.size(); ++i) { oshape[i] = rshape[idx.entry_id(nid, i)]; } if (dispatch_mode_name != nullptr) { dispatch_mode = &dispatch_modes[nid]; } auto finfer = finfer_shape.get(inode.source->op(), fdefault); if (finfer != nullptr) { // Call inference function of the operator. try { static auto& is_fusion = Op::GetAttr<exec::TIsFusion>("TIsFusion"); if (is_fusion.get(inode.source->op(), false)) { ProvideAttrToFusion<FProvideSubgraphType>(nid, idx, rshape, provide_fusion_name); } ApplyOpInferAttr(ret, finfer, inode.source->attrs, nid, &ishape, &oshape, dispatch_mode); bool finished = true; for (const auto& attr : ishape) { if (fis_none(attr)) finished = false; } for (const auto& attr : oshape) { if (fis_none(attr)) finished = false; } inference_finished[nid] = finished; } catch (const std::exception& e) { throw dmlc::Error("Error in operator " + inode.source->attrs.name + ": " + e.what()); } } else { // Operator does not provide sttribute inference function, // so we need to test if everything was inferred by other operators bool all_attrs_known = true; for (const auto& attr : ishape) { if (fis_none(attr)) { all_attrs_known = false; } } for (const auto& attr : oshape) { if (fis_none(attr)) { all_attrs_known = false; } } inference_finished[nid] = all_attrs_known; if (!all_attrs_known) { CHECK(!last_iter) << "Attribute " << infer_name << " is not registered by op " << inode.source->op()->name << ". We are not able to complete the inference because of this"; } } // Save to the result map. for (uint32_t i = 0; i < num_inputs; ++i) { rshape[idx.entry_id(inode.inputs[i])] = ishape[i]; } for (uint32_t i = 0; i < num_outputs; ++i) { rshape[idx.entry_id(nid, i)] = oshape[i]; } } }; size_t last_num_unknown; size_t num_unknown_dispatch_mode = dispatch_mode_name ? node_end - node_start : 0; size_t num_unknown_entry_attr = entry_end - entry_start; size_t num_unknown = num_unknown_entry_attr + num_unknown_dispatch_mode; bool last_iter = false; bool do_next_iteration = true; int i = 0; do { if (i % 2 == 0) { for (uint32_t nid = node_start; nid < node_end; ++nid) { infer_step(nid, last_iter); } } else { // backward inference for (uint32_t i = node_end; i != node_start; --i) { infer_step(i - 1, last_iter); } } last_num_unknown = num_unknown; num_unknown = 0; for (size_t j = entry_start; j < entry_end; ++j) { if (fis_none(rshape[j])) { num_unknown += fnum_unknown(rshape[j]); } } if (dispatch_mode_name) { for (size_t i = node_start; i < node_end; i++) { if (dispatch_modes[i] == DispatchMode::kUndefined) ++num_unknown; } } do_next_iteration = num_unknown > 0 && last_num_unknown > num_unknown; if (!do_next_iteration && !last_iter) { // Check if every op agrees that it should be // the end of attribute inference. If not, // perform one final step for (const bool done : inference_finished) { do_next_iteration = do_next_iteration || !done; } last_iter = true; } ++i; } while (do_next_iteration); // set the shapes ret.attrs[attr_name] = std::make_shared<any>(std::move(rshape)); // set the shapes if (dispatch_mode_name) { ret.attrs[dispatch_mode_name] = std::make_shared<any>(std::move(dispatch_modes)); } // number of nodes who knows the shape. ret.attrs[unknown_name] = std::make_shared<any>(num_unknown); return ret; } /*!\brief * This is a version of the InferAttr function specifically for shape inference. * * \param ret graph used for attribute inference * \param emmpty_val empty value of the attribute * \param infer_name name of the function used for attribute inference * \param input_name name of the attribute in the graph used to store the * input data for attribute inference * \param attr_key_name name of the attribute used for inference for variable nodes * \param attr_name name of the inferred attribute * \param unknown_name name of the attribute storing number of entries * impossible to infer * \param fis_none function returning true for not fully inferred values * \param fnum_unknown function returning how many elements are unknown in * partially inferred value of the attribute * \param fdefault default function used for inference if the node does not * provide its own implementation. * \param bwd_identity_assign whether the attributes of forward NDArray and backward * NDArray have to be the same. False only for storage * type inference * \param dispatch_mode_name name of the dispatch mode attribute on the node. Used for * storage type inference * \param default_mode_val default value of the dispatch mode attribute on the node. Used * for storage type inference */ template<typename IsNone, typename FDefault, typename FNumUnknown> nnvm::Graph InferShapeAttr(nnvm::Graph &&ret, const mxnet::TShape empty_val, const char* infer_name, const char* input_name, const char* attr_key_name, const char* attr_name, const char* unknown_name, IsNone fis_none, FNumUnknown fnum_unknown, FDefault fdefault, bool bwd_identity_assign, const char* dispatch_mode_name, const DispatchMode default_mode_val = DispatchMode::kUndefined) { using nnvm::IndexedGraph; using nnvm::Op; using AttrType = mxnet::TShape; using FInferType = mxnet::FInferShape; using AttrVector = std::vector<AttrType>; using NodeAttrVector = std::vector<DispatchMode>; using dmlc::any; const IndexedGraph& idx = ret.indexed_graph(); static auto& finfer_shape = Op::GetAttr<FInferType>(infer_name); static auto& is_backward = Op::GetAttr<nnvm::TIsBackward>("TIsBackward"); // reshape shape vector AttrVector rshape; // vector holding information which operators // finished attribute inference std::vector<bool> inference_finished(idx.num_nodes(), false); // dispatch mode vector DispatchModeVector dispatch_modes; if (ret.attrs.count(attr_name) != 0) { rshape = ret.MoveCopyAttr<AttrVector>(attr_name); } else { rshape.resize(idx.num_node_entries(), empty_val); } if (ret.attrs.count(input_name) != 0) { const AttrVector& shape_args = ret.GetAttr<AttrVector>(input_name); CHECK_LE(shape_args.size(), idx.input_nodes().size()) << "More provided " << attr_name << "s than number of arguments."; for (size_t i = 0; i < shape_args.size(); ++i) { rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i]; } } // get the shape hints std::string shape_hints_key = std::string(attr_name) + "_hints"; if (ret.attrs.count(shape_hints_key)) { nnvm::NodeEntryMap<AttrType> shape_hints = ret.GetAttr<nnvm::NodeEntryMap<AttrType>>(shape_hints_key); for (const auto& kv : shape_hints) { nnvm::NodeEntry e = kv.first; if (idx.exist(e.node.get())) { rshape[idx.entry_id(kv.first)] = kv.second; } } } std::string shape_attr_key; if (ret.attrs.count(attr_key_name) != 0) { shape_attr_key = ret.GetAttr<std::string>(attr_key_name); // erase the provided arguments ret.attrs.erase(attr_key_name); } // limit inference to part of the graph uint32_t node_start = 0, node_end = idx.num_nodes(); if (ret.attrs.count("node_range")) { const auto& range = ret.GetAttr<std::pair<uint32_t, uint32_t> >("node_range"); node_start = range.first; node_end = range.second; CHECK_GE(node_start, 0); CHECK_LE(node_end, idx.num_nodes()); ret.attrs.erase("node_range"); } uint32_t entry_start = 0, entry_end = idx.num_node_entries(); if (ret.attrs.count("entry_range")) { const auto& range = ret.GetAttr<std::pair<uint32_t, uint32_t> >("entry_range"); entry_start = range.first; entry_end = range.second; CHECK_GE(entry_start, 0); CHECK_LE(entry_end, idx.num_node_entries()); ret.attrs.erase("entry_range"); } // populate the node attribute vector if (dispatch_mode_name != nullptr) { if (ret.attrs.count(dispatch_mode_name) != 0) { dispatch_modes = ret.MoveCopyAttr<NodeAttrVector>(dispatch_mode_name); } else { LOG(FATAL) << "Node attribute " << dispatch_mode_name << " does not exist in the graph"; } } // Temp space for shape inference. std::vector<AttrType> ishape, oshape; // whether a shape is dynamic std::vector<int> is_dynamic(rshape.size(), 0); // convert to numpy compatible shape to use operator's infer shape function if (!Imperative::Get()->is_np_shape()) { common::ConvertToNumpyShape(&rshape); } // inference step function for nid auto infer_step = [&](uint32_t nid, bool last_iter) { if (inference_finished[nid]) return; const auto& inode = idx[nid]; const std::string name = inode.source->attrs.name; const uint32_t num_inputs = inode.inputs.size(); const uint32_t num_outputs = inode.source->num_outputs(); if (inode.source->is_variable()) { // Variable node. No operator. Only one output entry. CHECK(inode.source->op() == nullptr); CHECK_EQ(num_outputs, 1U); const uint32_t out_ent_id = idx.entry_id(nid, 0); if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) { auto it = inode.source->attrs.dict.find(shape_attr_key); if (it != inode.source->attrs.dict.end()) { std::istringstream is(it->second); CHECK(is >> rshape[out_ent_id]) << "Invalid attribute"; if (!Imperative::Get()->is_np_shape()) { common::ConvertToNumpyShape(&rshape[out_ent_id]); } } } if (!fis_none(rshape[out_ent_id])) { inference_finished[nid] = true; } // assign a default value to node attribute if (dispatch_mode_name != nullptr) { op::dispatch_mode_assign(&dispatch_modes[nid], default_mode_val); } } else if (is_backward.get(inode.source->op(), false) && inode.source->control_deps.size() && bwd_identity_assign) { CHECK(dispatch_mode_name == nullptr) << "Backward inference for node attributes is not available"; CHECK_GE(inode.source->control_deps.size(), 1U) << "BackwardOp need to have control_deps to its forward op"; nnvm::NodePtr fwd_ptr = inode.source->control_deps[0]; CHECK(fwd_ptr->op() != nullptr) << "Forward op cannot be a variable"; static auto& is_fusion_helper = Op::GetAttr<exec::TIsFusionHelper>("TIsFusionHelper"); if (!is_fusion_helper.get(fwd_ptr->op(), false)) { GetAttrFromForwardNode(nid, idx, &rshape, &inference_finished, fis_none); } else { GetAttrFromFusedNode<exec::FAccessSubgraphShape>(nid, idx, &rshape, &inference_finished, fis_none, "FAccessSubgraphShape"); } } else { DispatchMode* dispatch_mode = nullptr; // Forward operator inference. ishape.resize(num_inputs, empty_val); bool is_input_dynamic_shape = false; for (uint32_t i = 0; i < ishape.size(); ++i) { ishape[i] = rshape[idx.entry_id(inode.inputs[i])]; if (!mxnet::ndim_is_known(ishape[i]) && is_dynamic[idx.entry_id(inode.inputs[i])]) { is_input_dynamic_shape = true; } } oshape.resize(num_outputs, empty_val); for (uint32_t i = 0; i < oshape.size(); ++i) { oshape[i] = rshape[idx.entry_id(nid, i)]; } if (dispatch_mode_name != nullptr) { dispatch_mode = &dispatch_modes[nid]; } auto finfer = finfer_shape.get(inode.source->op(), fdefault); if (finfer == nullptr || is_input_dynamic_shape) { for (uint32_t i = 0; i < oshape.size(); ++i) { if (!mxnet::ndim_is_known(oshape[i].ndim())) { is_dynamic[idx.entry_id(nid, i)] = 1; } } inference_finished[nid] = true; } else { // Call inference function of the operator. try { static auto& is_fusion = Op::GetAttr<exec::TIsFusion>("TIsFusion"); if (is_fusion.get(inode.source->op(), false)) { ProvideAttrToFusion<exec::FProvideSubgraphShape>(nid, idx, rshape, "FProvideSubgraphShape"); } ApplyOpInferAttr(ret, finfer, inode.source->attrs, nid, &ishape, &oshape, dispatch_mode); bool finished = true; for (const auto& attr : ishape) { if (fis_none(attr)) finished = false; } for (const auto& attr : oshape) { if (fis_none(attr)) finished = false; } inference_finished[nid] = finished; } catch (const std::exception& e) { throw dmlc::Error("Error in operator " + inode.source->attrs.name + ": " + e.what()); } } // Save to the result map. for (uint32_t i = 0; i < num_inputs; ++i) { rshape[idx.entry_id(inode.inputs[i])] = ishape[i]; } for (uint32_t i = 0; i < num_outputs; ++i) { rshape[idx.entry_id(nid, i)] = oshape[i]; } } }; size_t last_num_unknown; size_t num_unknown = static_cast<size_t>(-1); // Infinity bool last_iter = false; bool do_next_iteration = true; int i = 0; do { if (i % 2 == 0) { // forward inference for (uint32_t nid = node_start; nid < node_end; ++nid) { infer_step(nid, last_iter); } } else { // backward inference for (uint32_t i = node_end; i != node_start; --i) { infer_step(i - 1, last_iter); } } last_num_unknown = num_unknown; num_unknown = 0; for (size_t j = entry_start; j < entry_end; ++j) { if (fis_none(rshape[j])) { num_unknown += fnum_unknown(rshape[j]); } } if (dispatch_mode_name) { for (size_t i = node_start; i < node_end; i++) { if (dispatch_modes[i] == DispatchMode::kUndefined) { ++num_unknown; } } } do_next_iteration = num_unknown > 0 && last_num_unknown > num_unknown; if (!do_next_iteration && !last_iter) { // Check if every op agrees that it should be // the end of attribute inference. If not, // perform one final step for (const bool done : inference_finished) { do_next_iteration = do_next_iteration || !done; } last_iter = true; } ++i; } while (do_next_iteration); // set the shapes ret.attrs[attr_name] = std::make_shared<any>(std::move(rshape)); // set the shapes if (dispatch_mode_name) { ret.attrs[dispatch_mode_name] = std::make_shared<any>(std::move(dispatch_modes)); } // number of nodes who knows the shape. ret.attrs[unknown_name] = std::make_shared<any>(num_unknown); return ret; } nnvm::Graph InferShape(nnvm::Graph&& graph, mxnet::ShapeVector&& shape_inputs, const std::string& shape_attr_key) { using dmlc::any; if (shape_inputs.size() != 0) { graph.attrs["shape_inputs"] = std::make_shared<any>(std::move(shape_inputs)); } if (shape_attr_key.length() != 0) { graph.attrs["shape_attr_key"] = std::make_shared<any>(shape_attr_key); } return InferShapeAttr( std::move(graph), mxnet::TShape(), "FInferShape", "shape_inputs", "shape_attr_key", "shape", "shape_num_unknown_nodes", [](const mxnet::TShape& s) { return !mxnet::shape_is_known(s); }, [](const mxnet::TShape& s) { if (!mxnet::ndim_is_known(s)) { return static_cast<size_t>(1); } size_t ret = 0; for (const auto& val : s) { if (!mxnet::dim_size_is_known(val)) { ++ret; } } return ret; }, nullptr, true, nullptr); } nnvm::Graph InferType(nnvm::Graph&& graph, nnvm::DTypeVector&& dtype_inputs, const std::string& dtype_attr_key) { using dmlc::any; if (dtype_inputs.size() != 0) { graph.attrs["dtype_inputs"] = std::make_shared<any>(std::move(dtype_inputs)); } if (dtype_attr_key.length() != 0) { graph.attrs["dtype_attr_key"] = std::make_shared<any>(dtype_attr_key); } return InferAttr<int, nnvm::FInferType, exec::FAccessSubgraphType, exec::FProvideSubgraphType>( std::move(graph), -1, "FInferType", "FAccessSubgraphType", "FProvideSubgraphType", "dtype_inputs", "dtype_attr_key", "dtype", "dtype_num_unknown_nodes", [](const int t) { return t == -1; }, [](const int t) { return t == -1 ? 1 : 0; }, common::SameType, true, true, nullptr); } nnvm::Graph InferStorageType(nnvm::Graph&& graph, StorageTypeVector&& storage_type_inputs, const std::string& storage_type_attr_key) { using dmlc::any; if (storage_type_inputs.size() != 0) { graph.attrs["storage_type_inputs"] = std::make_shared<any>(std::move(storage_type_inputs)); } if (storage_type_attr_key.length() != 0) { graph.attrs["storage_type_attr_key"] = std::make_shared<any>(storage_type_attr_key); } // initialize unknown values for dispatch modes if (graph.attrs.count("dispatch_mode") == 0) { DispatchModeVector dispatch_modes(graph.indexed_graph().num_nodes(), DispatchMode::kUndefined); graph.attrs["dispatch_mode"] = std::make_shared<any>(std::move(dispatch_modes)); } // initialize the dev_mask vector from the context vector if (graph.attrs.count("dev_mask") == 0) { CHECK_GT(graph.attrs.count("context"), 0); DevMaskVector dev_masks(graph.indexed_graph().num_nodes()); const ContextVector& vctx = graph.GetAttr<ContextVector>("context"); for (size_t i = 0; i < vctx.size(); i++) dev_masks[i] = vctx[i].dev_mask(); graph.attrs["dev_mask"] = std::make_shared<any>(std::move(dev_masks)); } // for storage type, the backward attr is not necessarily the same as it's correspondence nnvm::Graph ret = InferAttr<int, FInferStorageType, exec::FAccessSubgraphStorageType, exec::FProvideSubgraphStorageType>( std::move(graph), -1, "FInferStorageType", "FAccessSubgraphStorageType", "FProvideSubgraphStorageType", "storage_type_inputs", "storage_type_attr_key", "storage_type", "storage_type_num_unknown_nodes", [](const int t) { return t == -1; }, [](const int t) { return t == -1 ? 1 : 0; }, common::DefaultStorageType, true, false, "dispatch_mode", DispatchMode::kVariable); // log the storage types and dispatch modes of the graph static bool log_verbose = dmlc::GetEnv("MXNET_INFER_STORAGE_TYPE_VERBOSE_LOGGING", false); if (log_verbose) { common::LogInferStorage(ret); } return ret; } } // namespace exec } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/concat/ref_concat.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "src/common/mkldnn_thread.hpp" #include "concat/concat.hpp" namespace concat { void get_sizes(const prb_t *p, int64_t &outer_size, int64_t &inner_size, int64_t &axis_size) { outer_size = inner_size = 1; for (int i = 0; i < p->axis; i++) outer_size *= p->sdims[0][i]; for (int i = p->axis + 1; i < (int)p->sdims[0].size(); i++) inner_size *= p->sdims[0][i]; axis_size = p->axis_size(); } void compute_ref(const prb_t *p, const std::vector<dnn_mem_t> &src, dnn_mem_t &dst) { int64_t outer_size{0}, inner_size{0}, axis_size{0}; get_sizes(p, outer_size, inner_size, axis_size); float *dst_ptr = (float *)dst; mkldnn::impl::parallel_nd(outer_size, inner_size, [&](int64_t ou, int64_t in) { int64_t off_dst = ou * axis_size * inner_size; for (int i_input = 0; i_input < p->n_inputs(); ++i_input) { const float *src_ptr = (const float *)src[i_input]; int64_t i_axis_size = p->sdims[i_input][p->axis]; int64_t off_src = ou * i_axis_size * inner_size; for (int64_t as = 0; as < i_axis_size; ++as) { int64_t idx = as * inner_size + in; dst_ptr[off_dst + idx] = src_ptr[off_src + idx]; } off_dst += i_axis_size * inner_size; // the next input start point } }); } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/s8x8s32/jit_avx512_core_u8_copy_bt_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2018-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_u8.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx512_core_u8_copy_bt_kern::jit_avx512_core_u8_copy_bt_kern(bool s8_case) : jit_generator(nullptr, U8_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rax #define B rdi #define I rax #define A1 rsi #define A2 r10 #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l120; Xbyak::Label l14c; Xbyak::Label l168; Xbyak::Label l178; Xbyak::Label l184; Xbyak::Label l194; Xbyak::Label l20; Xbyak::Label l20c; Xbyak::Label l250; Xbyak::Label l27c; Xbyak::Label l298; Xbyak::Label l2a8; Xbyak::Label l2b4; Xbyak::Label l2c8; Xbyak::Label l34; Xbyak::Label l360; Xbyak::Label l3b4; Xbyak::Label l3e8; Xbyak::Label l400; Xbyak::Label l40e; Xbyak::Label l418; Xbyak::Label l428; Xbyak::Label l4a0; Xbyak::Label l4e8; Xbyak::Label l50c; Xbyak::Label l524; Xbyak::Label l534; Xbyak::Label lcc; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif alignas(16) static unsigned int hbit[] = {0x80808080u, 0x80808080u, 0x80808080u, 0x80808080u}; mov(A1, (size_t)&hbit); movdqu(xmm15, xword[A1]); auto maybe_perform_s8_shift_xmm = [=](Xbyak::Xmm x) { if (s8_case) xorps(x, xmm15); }; auto maybe_perform_s8_shift_r8 = [=](const Xbyak::Reg8 &r) { if (s8_case) xor_(r, (int8_t)0x80); }; auto maybe_perform_s8_shift_r16 = [=](const Xbyak::Reg16 &r) { if (s8_case) xor_(r, (int16_t)0x8080); }; mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); lea(LDA3, ptr[LDA+LDA*2]); sub(A, -128); sub(B, -128); cmp(N, 0x8); jl(l178, T_NEAR); align(4); L(l20); mov(A1, A); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(lcc, T_NEAR); align(4); L(l34); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); movq(xmm2, qword[A1-0x80]); add(A1, LDA); movq(xmm3, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); maybe_perform_s8_shift_xmm(xmm0); maybe_perform_s8_shift_xmm(xmm1); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); movq(xmm2, qword[A1-0x80]); add(A1, LDA); movq(xmm3, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); maybe_perform_s8_shift_xmm(xmm0); maybe_perform_s8_shift_xmm(xmm1); movdqu(xword[B-0x60], xmm0); movdqu(xword[B-0x50], xmm1); sub(B, -64); dec(I); jg(l34, T_NEAR); align(4); L(lcc); test(M, 0x4); jle(l120, T_NEAR); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); movq(xmm2, qword[A1-0x80]); add(A1, LDA); movq(xmm3, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); maybe_perform_s8_shift_xmm(xmm0); maybe_perform_s8_shift_xmm(xmm1); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); sub(B, -32); align(4); L(l120); test(M, 0x2); jle(l14c, T_NEAR); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); maybe_perform_s8_shift_xmm(xmm0); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l14c); test(M, 0x1); jle(l168, T_NEAR); movq(xmm0, qword[A1-0x80]); add(A1, LDA); maybe_perform_s8_shift_xmm(xmm0); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l168); sub(N, 0x8); cmp(N, 0x8); jge(l20, T_NEAR); align(4); L(l178); cmp(N, 0x4); jl(l2a8, T_NEAR); align(4); L(l184); mov(A1, A); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l20c, T_NEAR); align(4); L(l194); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); movd(xmm2, dword[A1-0x80]); add(A1, LDA); movd(xmm3, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); maybe_perform_s8_shift_xmm(xmm0); movdqu(xword[B-0x80], xmm0); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); movd(xmm2, dword[A1-0x80]); add(A1, LDA); movd(xmm3, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); maybe_perform_s8_shift_xmm(xmm0); movdqu(xword[B-0x70], xmm0); sub(B, -32); dec(I); jg(l194, T_NEAR); align(4); L(l20c); test(M, 0x4); jle(l250, T_NEAR); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); movd(xmm2, dword[A1-0x80]); add(A1, LDA); movd(xmm3, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); maybe_perform_s8_shift_xmm(xmm0); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l250); test(M, 0x2); jle(l27c, T_NEAR); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); maybe_perform_s8_shift_xmm(xmm0); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l27c); test(M, 0x1); jle(l298, T_NEAR); movd(xmm0, dword[A1-0x80]); maybe_perform_s8_shift_xmm(xmm0); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l298); sub(N, 0x4); cmp(N, 0x4); jge(l184, T_NEAR); align(4); L(l2a8); cmp(N, 0x2); jl(l40e, T_NEAR); align(4); L(l2b4); mov(A1, A); add(A, 0x2); mov(LDA3, M); sar(LDA3, 0x3); jle(l360, T_NEAR); align(4); L(l2c8); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm2, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm3, eax, 0x0); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm2, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm3, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm4, eax, 0x0); punpcklbw(xmm1, xmm2); punpcklbw(xmm3, xmm4); punpcklwd(xmm1, xmm3); punpcklqdq(xmm0, xmm1); maybe_perform_s8_shift_xmm(xmm0); movdqu(xword[B-0x80], xmm0); sub(B, -16); dec(LDA3); jg(l2c8, T_NEAR); align(4); L(l360); test(M, 0x4); jle(l3b4, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm2, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm3, eax, 0x0); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); maybe_perform_s8_shift_xmm(xmm0); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l3b4); test(M, 0x2); jle(l3e8, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); punpcklbw(xmm0, xmm1); maybe_perform_s8_shift_xmm(xmm0); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l3e8); test(M, 0x1); jle(l400, T_NEAR); mov(ax, word[A1-0x80]); maybe_perform_s8_shift_r16(ax); mov(word[B-0x80], ax); sub(B, -2); align(4); L(l400); sub(N, 0x2); cmp(N, 0x2); jge(l2b4, T_NEAR); align(4); L(l40e); cmp(N, 0x1); jl(l534, T_NEAR); align(4); L(l418); mov(A1, A); add(A, 0x1); mov(LDA3, M); sar(LDA3, 0x3); jle(l4a0, T_NEAR); align(4); L(l428); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x3); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x4); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x5); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x6); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x7); maybe_perform_s8_shift_xmm(xmm0); movq(qword[B-0x80], xmm0); sub(B, -8); dec(LDA3); jg(l428, T_NEAR); align(4); L(l4a0); test(M, 0x4); jle(l4e8, T_NEAR); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x3); maybe_perform_s8_shift_xmm(xmm0); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l4e8); test(M, 0x2); jle(l50c, T_NEAR); mov(al, byte[A1-0x80]); add(A1, LDA); maybe_perform_s8_shift_r8(al); mov(byte[B-0x80], al); mov(al, byte[A1-0x80]); add(A1, LDA); maybe_perform_s8_shift_r8(al); mov(byte[B-0x7f], al); sub(B, -2); align(4); L(l50c); test(M, 0x1); jle(l524, T_NEAR); mov(al, byte[A1-0x80]); maybe_perform_s8_shift_r8(al); mov(byte[B-0x80], al); sub(B, -1); align(4); L(l524); sub(N, 0x1); cmp(N, 0x1); jge(l418, T_NEAR); align(4); L(l534); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/gtp.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 <iostream> #include "base/commandlineflags.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/gtp_client.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/minigui_gtp_client.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/loader.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/zobrist.h" // GTP flags. DEFINE_bool(minigui, false, "Enable Minigui GTP extensions"); // Game options flags. DEFINE_int32( ponder_limit, 0, "If non-zero and in GTP mode, the number times of times to perform tree " "search while waiting for the opponent to play."); DEFINE_bool(courtesy_pass, false, "If true, always pass if the opponent passes."); DEFINE_double(resign_threshold, -0.999, "Resign threshold."); // Tree search flags. DEFINE_int32(num_readouts, 100, "Number of readouts to make during tree search for each move."); DEFINE_int32(virtual_losses, 8, "Number of virtual losses when running tree search."); DEFINE_double(value_init_penalty, 0.0, "New children value initialize penaly.\n" "child's value = parent's value - value_init_penalty * color, " "clamped to [-1, 1].\n" "0 is init-to-parent [default], 2.0 is init-to-loss.\n" "This behaves similiarly to leela's FPU \"First Play Urgency\"."); // Time control flags. DEFINE_double(seconds_per_move, 0, "If non-zero, the number of seconds to spend thinking about each " "move instead of using a fixed number of readouts."); DEFINE_double( time_limit, 0, "If non-zero, the maximum amount of time to spend thinking in a game: we " "spend seconds_per_move thinking for each move for as many moves as " "possible before exponentially decaying the amount of time."); DEFINE_double(decay_factor, 0.98, "If time_limit is non-zero, the decay factor used to shorten the " "amount of time spent thinking as the game progresses."); // Inference flags. DEFINE_string(device, "", "Optional ID of the device to run inference on. For TPUs, pass " "the gRPC address."); DEFINE_string(model, "", "Path to a minigo model."); DEFINE_int32(cache_size_mb, 1024, "Size of the inference cache in MB. Tree reuse in GTP mode is " "disabled, so cache_size_mb should be non-zero for reasonable " "performance. Enabling minigui mode requires an inference cache."); namespace minigo { namespace { void Gtp() { Game::Options game_options; game_options.resign_threshold = FLAGS_resign_threshold; MctsPlayer::Options player_options; player_options.inject_noise = false; player_options.tree.soft_pick_enabled = false; player_options.tree.value_init_penalty = FLAGS_value_init_penalty; player_options.virtual_losses = FLAGS_virtual_losses; player_options.num_readouts = FLAGS_num_readouts; player_options.seconds_per_move = FLAGS_seconds_per_move; player_options.time_limit = FLAGS_time_limit; player_options.decay_factor = FLAGS_decay_factor; GtpClient::Options client_options; client_options.ponder_limit = FLAGS_ponder_limit; client_options.courtesy_pass = FLAGS_courtesy_pass; // Disable tree reuse and rely on the inference cache when running in Minigui // mode: we don't want to pollute the tree when investigating variations. client_options.tree_reuse = !FLAGS_minigui; MG_LOG(INFO) << game_options << " " << player_options; std::shared_ptr<ThreadSafeInferenceCache> inference_cache; if (FLAGS_cache_size_mb > 0) { auto capacity = BasicInferenceCache::CalculateCapacity(FLAGS_cache_size_mb); MG_LOG(INFO) << "Will cache up to " << capacity << " inferences, using roughly " << FLAGS_cache_size_mb << "MB.\n"; inference_cache = std::make_shared<ThreadSafeInferenceCache>(capacity, 1); } else { MG_LOG(WARNING) << "cache_size_mb == 0 results in poor performance in GTP " "mode because tree reuse is disabled."; } std::unique_ptr<GtpClient> client; if (FLAGS_minigui) { client = absl::make_unique<MiniguiGtpClient>( FLAGS_device, std::move(inference_cache), FLAGS_model, game_options, player_options, client_options); } else { client = absl::make_unique<GtpClient>( FLAGS_device, std::move(inference_cache), FLAGS_model, game_options, player_options, client_options); } client->Run(); } } // namespace } // namespace minigo int main(int argc, char* argv[]) { minigo::Init(&argc, &argv); minigo::zobrist::Init(0); minigo::Gtp(); minigo::ShutdownModelFactories(); return 0; } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/jit_sse41_1x1_convolution.cpp<|end_filename|> /******************************************************************************* * Copyright 2017-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mkldnn_types.h" #include "c_types_map.hpp" #include "jit_sse41_1x1_convolution.hpp" #include "utils.hpp" #include "mkldnn_thread.hpp" #include "type_helpers.hpp" namespace mkldnn { namespace impl { namespace cpu { #define data_blk_off(f, n, c, h, w) \ ((ndims == 3) \ ? (f).blk_off(n, c, w) \ : (f).blk_off(n, c, h, w)) using namespace mkldnn::impl::status; using namespace mkldnn::impl::utils; void jit_sse41_1x1_convolution_fwd_t::execute_forward( const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const data_t *, MKLDNN_ARG_SRC); auto weights = CTX_IN_MEM(const data_t *, MKLDNN_ARG_WEIGHTS); auto bias = CTX_IN_MEM(const data_t *, MKLDNN_ARG_BIAS); auto dst = CTX_OUT_MEM(data_t *, MKLDNN_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const auto &jcp = kernel_->jcp; const int ndims = src_d.ndims(); const int work_amount = jcp.mb * jcp.ngroups * jcp.nb_bcast; parallel(0, [&](const int ithr, const int nthr) { // TODO (Roma): remove this restriction assert(jcp.stride_w == 1 && jcp.stride_h == 1); auto par_conv = jit_1x1_conv_call_s(); const int nb_oc = jcp.nb_load; const int nb_ic = jcp.nb_reduce; const int nb_ic_blocking = jcp.nb_reduce_blocking; const int os_block = jcp.bcast_block; int start{0}, end{0}; balance211(work_amount, nthr, ithr, start, end); int iwork = start; while (iwork < end) { int n{0}, g{0}, osb{0}; nd_iterator_init(iwork, n, jcp.mb, g, jcp.ngroups, osb, jcp.nb_bcast); const int bcast_step_rem = jcp.nb_bcast - osb; int bcast_step = bcast_step_rem <= jcp.nb_bcast_blocking_max ? bcast_step_rem : jcp.nb_bcast_blocking; bcast_step = nstl::min<int>(bcast_step, end - iwork); const int os = osb * os_block; const int ow = os % jcp.ow; const int oh = os / jcp.ow; const int iw = nstl::max<int>(ow * jcp.stride_w - jcp.l_pad, 0); const int ih = nstl::max<int>(oh * jcp.stride_h - jcp.t_pad, 0); par_conv.bcast_dim = this_block_size(os, jcp.os, bcast_step * os_block); int ocb = 0; while (ocb < jcp.nb_load) { const int load_step_rem = jcp.nb_load - ocb; const int load_step = load_step_rem < jcp.nb_load_blocking_max ? load_step_rem : jcp.nb_load_blocking; const size_t _ocb = g * nb_oc + ocb; par_conv.load_dim = this_block_size(ocb * jcp.oc_block, jcp.oc, load_step * jcp.oc_block); const size_t dst_off = data_blk_off(dst_d, n, _ocb, oh, ow); par_conv.output_data = &dst[dst_off]; par_conv.bias_data = &bias[_ocb * jcp.oc_block]; for (int icb = 0; icb < nb_ic; icb += nb_ic_blocking) { par_conv.first_last_flag = 0 | (icb == 0) * FLAG_REDUCE_FIRST | (icb + nb_ic_blocking >= nb_ic) * FLAG_REDUCE_LAST; par_conv.reduce_dim = this_block_size(icb * jcp.ic_block, jcp.ic, nb_ic_blocking * jcp.ic_block); const size_t _icb = g * nb_ic + icb; const size_t src_off = data_blk_off(src_d, n, _icb, ih, iw); par_conv.bcast_data = &src[src_off]; par_conv.load_data = &weights[pd()->with_groups() ? weights_d.blk_off(g, ocb, icb) : weights_d.blk_off(ocb, icb)]; kernel_->jit_ker(&par_conv); } ocb += load_step; } iwork += bcast_step; } }); if (pd()->wants_zero_pad_dst()) ctx.memory(MKLDNN_ARG_DST)->zero_pad(); } } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/mcts_tree.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/mcts_tree.h" #include <emmintrin.h> #include <algorithm> #include <cmath> #include <functional> #include <tuple> #include <utility> #include "REDACTEDstrings/str_format.h" #include "REDACTEDtypes/optional.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/algorithm.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" namespace minigo { namespace { // Superko implementation that uses MctsNode::superko_cache. class ZobristHistory : public Position::ZobristHistory { public: explicit ZobristHistory(const MctsNode* node) : node_(node) {} bool HasPositionBeenPlayedBefore(zobrist::Hash stone_hash) const { for (const auto* node = node_; node != nullptr; node = node->parent) { if (node->superko_cache != nullptr) { return node->superko_cache->contains(stone_hash); } else { if (node->position.stone_hash() == stone_hash) { return true; } } } return false; } private: const MctsNode* node_; }; absl::optional<symmetry::Symmetry> CalculateCanonicalSymmetry( const Position& position) { // TODO(tommadams): skip this check if `move` is kPass or on the diagonal. static_assert(symmetry::kIdentity == 0, "kIdentity must be 0"); // When choosing a canonical symmetry, we consider the "best" symmetry to // be the one with the smallest Zobrist hash. The "best" symmetry is only // canonical if its hash value is also unique among the hashes from the // other possible symmetries. auto best_symmetry = symmetry::kIdentity; auto best_hash = position.stone_hash(); bool found_unique_hash = true; std::array<Stone, kN * kN> transformed; for (int i = 1; i < symmetry::kNumSymmetries; ++i) { auto sym = static_cast<symmetry::Symmetry>(i); symmetry::ApplySymmetry<kN, 1>(sym, position.stones().data(), transformed.data()); auto stone_hash = Position::CalculateStoneHash(transformed); if (stone_hash < best_hash) { best_symmetry = sym; best_hash = stone_hash; } else if (stone_hash == best_hash) { found_unique_hash = false; break; } } if (found_unique_hash) { return symmetry::Inverse(best_symmetry); } return absl::nullopt; } constexpr int kSuperKoCacheStride = 8; } // namespace MctsNode::MctsNode(EdgeStats* stats, const Position& position) : parent(nullptr), stats(stats), stats_idx(0), move(Coord::kInvalid), is_expanded(false), has_canonical_symmetry(false), position(position) {} MctsNode::MctsNode(MctsNode* parent, Coord move) : parent(parent), stats(&parent->edges), stats_idx(move), move(move), is_expanded(false), has_canonical_symmetry(parent->has_canonical_symmetry), canonical_symmetry(parent->canonical_symmetry), position(parent->position) { // TODO(tommadams): move this code into the MctsTree and only perform it // only if we are using an inference cache. if (!has_canonical_symmetry) { auto sym = CalculateCanonicalSymmetry(position); if (sym.has_value()) { has_canonical_symmetry = true; canonical_symmetry = sym.value(); } } MG_DCHECK(move >= 0); MG_DCHECK(move < kNumMoves); ZobristHistory zobrist_history(this); position.PlayMove(move, position.to_play(), &zobrist_history); // Insert a cache of ancestor Zobrist hashes at regular depths in the tree. // See the comment for superko_cache in the mcts_node.h for more details. if ((position.n() % kSuperKoCacheStride) == 0) { superko_cache = absl::make_unique<SuperkoCache>(); superko_cache->reserve(position.n() + 1); superko_cache->insert(position.stone_hash()); for (auto* node = parent; node != nullptr; node = node->parent) { if (node->superko_cache != nullptr) { superko_cache->insert(node->superko_cache->begin(), node->superko_cache->end()); break; } superko_cache->insert(node->position.stone_hash()); } } } Coord MctsNode::GetMostVisitedMove(bool restrict_pass_alive) const { // Find the set of moves with the largest N. inline_vector<Coord, kNumMoves> moves; // CalculatePassAliveRegions does not include the kPass point. std::array<Color, kN * kN> out_of_bounds; if (restrict_pass_alive) { out_of_bounds = position.CalculatePassAliveRegions(); } else { for (auto& x : out_of_bounds) { x = Color::kEmpty; } } int best_N = 0; for (int i = 0; i < kNumMoves; ++i) { if ((i != Coord::kPass) && (out_of_bounds[i] != Color::kEmpty)) { continue; } int cn = child_N(i); if (cn >= best_N) { if (cn > best_N) { moves.clear(); best_N = cn; } moves.push_back(i); } } if (moves.empty()) { return Coord::kPass; } // If there's only one move with the largest N, we're done. if (moves.size() == 1) { return moves[0]; } // Otherwise, break tie using the child action score. float to_play = position.to_play() == Color::kBlack ? 1 : -1; float U_common = U_scale() * std::sqrt(1.0f + N()); Coord c = moves[0]; float best_cas = CalculateSingleMoveChildActionScore(to_play, U_common, moves[0]); for (int i = 0; i < moves.size(); ++i) { float cas = CalculateSingleMoveChildActionScore(to_play, U_common, moves[i]); if (cas > best_cas) { best_cas = cas; c = moves[i]; } } return c; } std::vector<Coord> MctsNode::GetMostVisitedPath() const { std::vector<Coord> path; const auto* node = this; while (!node->children.empty()) { Coord c = node->GetMostVisitedMove(); if (node->child_N(c) == 0) { // In cases where nodes have been added to the tree manually (after the // user has played a move, loading an SGF game), it's possible that no // children have been visited. Break before adding a spurious node to the // path. break; } path.push_back(c); auto it = node->children.find(c); if (it == node->children.end()) { // When we reach the move limit, last node will have children with visit // counts but no children. break; } node = it->second.get(); } return path; } std::string MctsNode::GetMostVisitedPathString() const { std::string result; const auto* node = this; for (Coord c : GetMostVisitedPath()) { auto it = node->children.find(c); MG_CHECK(it != node->children.end()); node = it->second.get(); absl::StrAppendFormat(&result, "%s (%d) ==> ", node->move.ToGtp(), node->N()); } absl::StrAppendFormat(&result, "Q: %0.5f", node->Q()); return result; } void MctsNode::PruneChildren(Coord c) { auto child = std::move(children[c]); children.clear(); children[c] = std::move(child); } void MctsNode::ClearChildren() { // I _think_ this is all the state we need to clear... children.clear(); edges = {}; *stats = {}; is_expanded = false; } // Vectorized version of CalculateChildActionScore. void MctsNode::CalculateChildActionScoreSse(PaddedSpan<float> result) const { __m128 to_play = _mm_set_ps1(position.to_play() == Color::kBlack ? 1 : -1); __m128 U_common = _mm_set_ps1(U_scale() * std::sqrt(std::max<float>(1, N() - 1))); // A couple of useful constants. __m128i one = _mm_set1_epi32(1); __m128 one_thousand = _mm_set_ps1(1000); for (int i = 0; i < kNumMoves; i += 4) { // `rcp_N_one = 1 / (1 + child_N(i))` // The division is performed using an approximate reciprocal instruction // that has a maximum relative error of 1.5 * 2^-12. __m128i N = _mm_loadu_si128(reinterpret_cast<const __m128i*>(edges.N.data() + i)); __m128 rcp_N_one = _mm_rcp_ps(_mm_cvtepi32_ps(_mm_add_epi32(one, N))); // `Q = child_W(i) / (1 + child_N(i))` __m128 W = _mm_loadu_ps(edges.W.data() + i); __m128 Q = _mm_mul_ps(W, rcp_N_one); // `U = U_common * child_P(i) / (1 + child_N(i))` __m128 P = _mm_loadu_ps(edges.P.data() + i); __m128 U = _mm_mul_ps(_mm_mul_ps(U_common, P), rcp_N_one); // `legal_bits = position.legal_move(i)` // This requires a few instructions to load the legal move bytes and // shuffle them into each of the four vector slots. __m128i legal_bits = _mm_loadu_si128( reinterpret_cast<const __m128i*>(position.legal_moves().data() + i)); legal_bits = _mm_unpacklo_epi8(legal_bits, _mm_setzero_si128()); legal_bits = _mm_unpacklo_epi16(legal_bits, _mm_setzero_si128()); // `legal = legal_bits == 0 ? 1000 : 0` __m128 legal = _mm_castsi128_ps(_mm_cmpeq_epi32(legal_bits, _mm_setzero_si128())); legal = _mm_and_ps(legal, one_thousand); // `child_action_score[i] = Q * to_play + U - legal` __m128 cas = _mm_sub_ps(_mm_add_ps(_mm_mul_ps(Q, to_play), U), legal); _mm_storeu_ps(result.data() + i, cas); } } std::array<float, kNumMoves> MctsNode::CalculateChildActionScore() const { float to_play = position.to_play() == Color::kBlack ? 1 : -1; float U_common = U_scale() * std::sqrt(std::max<float>(1, N() - 1)); std::array<float, kNumMoves> result; for (int i = 0; i < kNumMoves; ++i) { result[i] = CalculateSingleMoveChildActionScore(to_play, U_common, i); } return result; } MctsNode* MctsNode::MaybeAddChild(Coord c) { auto it = children.find(c); if (it == children.end()) { // TODO(tommadams): Allocate children out of a custom block allocator: we // spend about 5% of our runtme inside MctsNode::PruneChildren freeing // nodes. it = children.emplace(c, absl::make_unique<MctsNode>(this, c)).first; } return it->second.get(); } std::string MctsTree::Stats::ToString() const { return absl::StrFormat( "%d nodes, %d leaf, %.1f average children\n" "%.1f average depth, %d max depth\n", num_nodes, num_leaf_nodes, 1.0f * num_nodes / std::max(1, num_nodes - num_leaf_nodes), 1.0f * depth_sum / num_nodes, max_depth); } std::ostream& operator<<(std::ostream& os, const MctsTree::Options& options) { return os << "value_init_penalty:" << options.value_init_penalty << " policy_softmax_temp:" << options.policy_softmax_temp << " soft_pick_enabled:" << options.soft_pick_enabled << " soft_pick_cutoff:" << options.soft_pick_cutoff; } MctsTree::MctsTree(const Position& position, const Options& options) : game_root_(&game_root_stats_, position), options_(options) { root_ = &game_root_; } MctsNode* MctsTree::SelectLeaf(bool allow_pass) { auto* node = root_; for (;;) { // If a node has never been evaluated, we have no basis to select a child. if (!node->is_expanded) { return node; } PaddedArray<float, kNumMoves> child_action_score; node->CalculateChildActionScoreSse(child_action_score); if (!allow_pass) { child_action_score[Coord::kPass] = -100000; } Coord best_move = ArgMaxSse(child_action_score); if (!node->position.legal_move(best_move)) { best_move = Coord::kPass; } node = node->MaybeAddChild(best_move); } } Coord MctsTree::PickMove(Random* rnd, bool restrict_pass_alive) const { if (options_.soft_pick_enabled && root_->position.n() < options_.soft_pick_cutoff) { return SoftPickMove(rnd); } else { return PickMostVisitedMove(restrict_pass_alive); } } void MctsTree::PlayMove(Coord c) { MG_CHECK(!is_game_over() && is_legal_move(c)) << c << " " << is_game_over() << " " << is_legal_move(c); root_ = root_->MaybeAddChild(c); // Don't need to keep the parent's children around anymore because we'll // never revisit them during normal play. // TODO(tommadams): we should just delete all ancestors. This will require // changes to UndoMove though. root_->parent->PruneChildren(c); } void MctsTree::AddVirtualLoss(MctsNode* leaf) { auto* node = leaf; for (;;) { ++node->num_virtual_losses_applied; node->stats->W[node->stats_idx] += node->position.to_play() == Color::kBlack ? 1 : -1; if (node == root_) { return; } node = node->parent; } } void MctsTree::RevertVirtualLoss(MctsNode* leaf) { auto* node = leaf; for (;;) { --node->num_virtual_losses_applied; node->stats->W[node->stats_idx] -= node->position.to_play() == Color::kBlack ? 1 : -1; if (node == root_) { return; } node = node->parent; } } void MctsTree::IncorporateResults(MctsNode* leaf, absl::Span<const float> move_probabilities, float value) { MG_DCHECK(move_probabilities.size() == kNumMoves); // A finished game should not be going through this code path, it should // directly call BackupValue on the result of the game. MG_DCHECK(!leaf->game_over()); // If the node has already been selected for the next inference batch, we // shouldn't 'expand' it again. if (leaf->is_expanded) { return; } float policy_scalar = 0; for (int i = 0; i < kNumMoves; ++i) { if (leaf->position.legal_move(i)) { policy_scalar += move_probabilities[i]; } } if (policy_scalar > std::numeric_limits<float>::min()) { policy_scalar = 1 / policy_scalar; } // NOTE: Minigo uses value [-1, 1] from black's perspective // Leela uses value [0, 1] from current player's perspective // AlphaGo uses [0, 1] in tree search (see matthew lai's post) // // The initial value of a child's Q is not perfectly understood. // There are a couple of general ideas: // * Init to Parent: // Init a new child to its parent value. // We think of this as saying "The game is probably the same after // *any* move". // * Init to Draw AKA init to zero AKA "position looks even": // Init a new child to 0 for {-1, 1} or 0.5 for LZ. // We tested this in v11, because this is how we interpretted the // original AGZ paper. This doesn't make a lot of sense: The losing // player tends to explore every move before reading a second one // twice. The winning player tends to read only the top policy move // because it has much higher value than any other move. // * Init to Parent minus a constant AKA FPU (Leela's approach): // This outperformed init to parent in eval matches when LZ tested it. // Leela-Zero uses a value around 0.15-0.25 based on policy of explored // children. LCZero uses a much large value 1.25 (they use {-1 to 1}). // * Init to Loss: // Init all children to losing. // We think of this as saying "Only a small number of moves work don't // get distracted" float reduction = options_.value_init_penalty * (leaf->position.to_play() == Color::kBlack ? 1 : -1); float reduced_value = std::min(1.0f, std::max(-1.0f, value - reduction)); leaf->is_expanded = true; for (int i = 0; i < kNumMoves; ++i) { // Zero out illegal moves, and re-normalize move_probabilities. float move_prob = leaf->position.legal_move(i) ? policy_scalar * move_probabilities[i] : 0; leaf->edges.original_P[i] = leaf->edges.P[i] = move_prob; // Note that we accumulate W here, rather than assigning. // When performing tree search normally, we could just assign the value to W // because the result of value head is known before we expand the node. // When running Minigui in study move however, we load the entire game tree // before starting background inference. This means that while background // inferences are being performed, nodes in the tree may already be expanded // and have non-zero W values at the time we need to incorporate a result // for the node from the value head. // TODO(tommadams): Minigui doesn't work this way any more so we can just // assign. leaf->edges.W[i] += reduced_value; } BackupValue(leaf, value); } void MctsTree::IncorporateEndGameResult(MctsNode* leaf, float value) { MG_DCHECK(leaf->game_over()); MG_DCHECK(!leaf->is_expanded); BackupValue(leaf, value); } void MctsTree::BackupValue(MctsNode* leaf, float value) { auto* node = leaf; for (;;) { node->stats->W[node->stats_idx] += value; node->stats->N[node->stats_idx] += 1; if (node == root_) { return; } node = node->parent; } } void MctsTree::InjectNoise(const std::array<float, kNumMoves>& noise, float mix) { MG_CHECK(root_->is_expanded); // NOTE: our interpretation is to only add dirichlet noise to legal moves. // Because dirichlet entries are independent we can simply zero and rescale. float scalar = 0; for (int i = 0; i < kNumMoves; ++i) { if (root_->position.legal_move(i)) { scalar += noise[i]; } } if (scalar > std::numeric_limits<float>::min()) { scalar = 1.0 / scalar; } for (int i = 0; i < kNumMoves; ++i) { float scaled_noise = scalar * (root_->position.legal_move(i) ? noise[i] : 0); root_->edges.P[i] = (1 - mix) * root_->edges.P[i] + mix * scaled_noise; } } void MctsTree::ReshapeFinalVisits(bool restrict_pass_alive) { // Since we aren't actually disallowing *reads* of bensons moves, only their // selection, we get the most visited move regardless of bensons status and // reshape based on its action score. Coord best = root_->GetMostVisitedMove(false); MG_CHECK(root_->edges.N[best] > 0); auto pass_alive_regions = root_->position.CalculatePassAliveRegions(); float U_common = root_->U_scale() * std::sqrt(1.0f + root_->N()); float to_play = root_->position.to_play() == Color::kBlack ? 1 : -1; float best_cas = root_->CalculateSingleMoveChildActionScore(to_play, U_common, uint16_t(best)); bool any = false; // Track if any move has visits after pruning. // We explored this child with uncertainty about its value. Now, after // searching, we change the visit count to reflect how many visits we would // have given it with our newer understanding of its regret relative to our // best move. for (int i = 0; i < kNumMoves; ++i) { // Remove visits in pass alive areas. if (restrict_pass_alive && (i != Coord::kPass) && (pass_alive_regions[i] != Color::kEmpty)) { root_->edges.N[i] = 0; continue; } // Skip the best move; it has the highest action score. if (i == best) { if (root_->edges.N[i] > 0) { any = true; } continue; } // Change N_child to the smallest value that satisfies the inequality // best_cas > Q + (U_scale * P * sqrt(N_parent) / N_child) // Solving for N_child, we get: int new_N = std::max<int>( 0, std::min<int>(root_->child_N(i), -1 * (root_->U_scale() * root_->child_P(i) * std::sqrt(root_->N())) / ((root_->child_Q(i) * to_play) - best_cas))); root_->edges.N[i] = new_N; if (root_->edges.N[i] > 0) { any = true; } } // If all visits were in bensons regions, put a visit on pass. if (!any) { root_->edges.N[Coord::kPass] = 1; } } std::array<float, kNumMoves> MctsTree::CalculateSearchPi() const { std::array<float, kNumMoves> search_pi; if (options_.soft_pick_enabled && root_->position.n() < options_.soft_pick_cutoff) { // Squash counts before normalizing to match softpick behavior in PickMove. for (int i = 0; i < kNumMoves; ++i) { search_pi[i] = std::pow(root_->child_N(i), options_.policy_softmax_temp); } } else { for (int i = 0; i < kNumMoves; ++i) { search_pi[i] = root_->child_N(i); } } // Normalize counts. float sum = 0; for (int i = 0; i < kNumMoves; ++i) { sum += search_pi[i]; } MG_CHECK(sum > 0); for (int i = 0; i < kNumMoves; ++i) { search_pi[i] /= sum; } return search_pi; } MctsTree::Stats MctsTree::CalculateStats() const { Stats stats; std::function<void(const MctsNode&, int)> traverse = [&](const MctsNode& node, int depth) { stats.num_nodes += 1; stats.num_leaf_nodes += node.N() <= 1; stats.max_depth = std::max(depth, stats.max_depth); stats.depth_sum += depth; for (const auto& child : node.children) { traverse(*child.second.get(), depth + 1); } }; traverse(*root_, 0); return stats; } std::string MctsTree::Describe() const { auto sorted_child_info = CalculateRankedChildInfo(); auto result = absl::StrFormat( "%0.4f\n%s\n" "move : action Q U P P-Dir N soft-N p-delta p-rel", root_->Q(), root_->GetMostVisitedPathString()); float child_N_sum = 0; for (const auto& N : root_->edges.N) { child_N_sum += N; } for (int rank = 0; rank < 15; ++rank) { Coord c = sorted_child_info[rank].c; float soft_N = root_->child_N(c) / child_N_sum; float p_delta = soft_N - root_->child_P(c); float p_rel = p_delta / root_->child_P(c); absl::StrAppendFormat( &result, "\n%-5s: % 4.3f % 4.3f %0.3f %0.3f %0.3f %5d %0.4f % 6.5f % 3.2f", c.ToGtp(), sorted_child_info[rank].action_score, root_->child_Q(c), root_->child_U(c), root_->child_P(c), root_->child_original_P(c), root_->child_N(c), soft_N, p_delta, p_rel); } return result; } std::array<MctsTree::ChildInfo, kNumMoves> MctsTree::CalculateRankedChildInfo() const { auto child_action_score = root_->CalculateChildActionScore(); std::array<ChildInfo, kNumMoves> child_info; for (int i = 0; i < kNumMoves; ++i) { child_info[i].c = i; child_info[i].N = root_->child_N(i); child_info[i].P = root_->child_P(i); child_info[i].action_score = child_action_score[i]; } std::sort(child_info.begin(), child_info.end(), [](const ChildInfo& a, const ChildInfo& b) { if (a.N != b.N) { return a.N > b.N; } if (a.P != b.P) { return a.P > b.P; } return a.action_score > b.action_score; }); return child_info; } bool MctsTree::UndoMove() { if (root_ == &game_root_) { return false; } root_ = root_->parent; return true; } Coord MctsTree::PickMostVisitedMove(bool restrict_pass_alive) const { auto c = root_->GetMostVisitedMove(restrict_pass_alive); if (!root_->position.legal_move(c)) { c = Coord::kPass; } return c; } // SoftPickMove is only called for the opening moves of the game, so we don't // bother restricting play in pass-alive territory. Coord MctsTree::SoftPickMove(Random* rnd) const { // Select from the first kN * kN moves (instead of kNumMoves) to avoid // randomly choosing to pass early on in the game. std::array<float, kN * kN> cdf; // For moves before the temperature cutoff, exponentiate the probabilities by // a temperature slightly larger than unity to encourage diversity in early // play and hopefully to move away from 3-3s. for (size_t i = 0; i < cdf.size(); ++i) { cdf[i] = std::pow(root_->child_N(i), options_.policy_softmax_temp); } for (size_t i = 1; i < cdf.size(); ++i) { cdf[i] += cdf[i - 1]; } if (cdf.back() == 0) { // It's actually possible for an early model to put all its reads into pass, // in which case the SearchSorted call below will always return 0. In this // case, we'll just let the model have its way and allow a pass. return Coord::kPass; } Coord c = rnd->SampleCdf(absl::MakeSpan(cdf)); MG_DCHECK(root_->child_N(c) != 0); return c; } } // namespace minigo <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/init.cc<|end_filename|> // Custom init.cc that calls InitGoogle instead of OSS equivalents. #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "base/init_google.h" #include "REDACTEDdebugging/symbolize.h" namespace minigo { void Init(int* pargc, char*** pargv) { InitGoogle((*pargv)[0], pargc, pargv, true); absl::InitializeSymbolizer((*pargv)[0]); } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/cudnn/cudnn_convolution-inl.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2015 by Contributors * \file cudnn_convolution-inl.h * \brief * \author <NAME> */ #ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_CONVOLUTION_INL_H_ #define MXNET_OPERATOR_NN_CUDNN_CUDNN_CONVOLUTION_INL_H_ #include <mxnet/storage.h> #include <algorithm> #include <vector> #include <set> #include <mutex> #include <string> #include <iostream> #include <sstream> #include <iomanip> #include "../convolution-inl.h" #include "./cudnn_algoreg-inl.h" #include "../../../common/cuda_utils.h" namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 // Extent of cudnn_algo_verbose mode: 1 = info on selected algo, 2 = info on all Find() algos. #define ALGO_VERBOSE_LEVEL 1 // Equivalent algo performance threshhold (e.g. 1.01 == 1% performance difference) // Used to prune Tensor Core algos with no appreciable performance benefit. #define ALGO_PERF_THRESHOLD 1.01 /*! * \brief The Operator used to perform convolution using cuDNN kernels. */ template<typename DType> class CuDNNConvolutionOp { STATIC_ASSERT_CUDNN_VERSION_GE(7000); public: CuDNNConvolutionOp() { CUDNN_CALL(cudnnCreateTensorDescriptor(&in_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&out_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&bias_desc_)); CUDNN_CALL(cudnnCreateFilterDescriptor(&filter_desc_)); CUDNN_CALL(cudnnCreateConvolutionDescriptor(&forward_conv_desc_)); CUDNN_CALL(cudnnCreateConvolutionDescriptor(&back_conv_desc_)); CUDNN_CALL(cudnnCreateConvolutionDescriptor(&back_conv_desc_w_)); parallelize_backward_kernels_ = Context::GetGPUStreamsPerWorker() >= 2; } void Init(const ConvolutionParam& param, int forward_compute_type, int backward_compute_type, const mxnet::ShapeVector& in_shape, const mxnet::ShapeVector& out_shape, const RunContext& rctx, bool add_to_weight) { using namespace mshadow; this->param_ = param; // If no local setting for TensorCore use policy, look to global policy. if (!param_.cudnn_tensor_core.has_value()) param_.cudnn_tensor_core = GetEnvAllowTensorCore(); this->add_to_weight_ = add_to_weight; InitBufferForParam(); auto cudnn_forward_compute_type = convertToCuDNNDataType(forward_compute_type); auto cudnn_backward_compute_type = convertToCuDNNDataType(backward_compute_type); // convert MB to words param_.workspace = (param_.workspace << 20) / sizeof(DType); dtype_ = DataType<DType>::kCudnnFlag; auto effective_layout = param_.layout.value(); switch (effective_layout) { // 1D convolutions will be executed as 2D convolutions with a height of 1. case mshadow::kNCW: effective_layout = mshadow::kNCHW; break; case mshadow::kNWC: effective_layout = mshadow::kNHWC; break; case mshadow::kCWN: effective_layout = mshadow::kCHWN; break; default: break; } MSHADOW_LAYOUT_SWITCH(effective_layout, Layout, { format_ = LayoutType<Layout>::kCudnnFlag; }); // Double check to make sure this class supports the operation if (!Supports(param, forward_compute_type, backward_compute_type, rctx.ctx.dev_id)) LOG(FATAL) << "Convolution parameters not supported by cuDNN implementation."; InitDescriptors(in_shape, out_shape, cudnn_forward_compute_type, cudnn_backward_compute_type); if (!param_.cudnn_tune) { param_.cudnn_tune = dmlc::GetEnv("MXNET_CUDNN_AUTOTUNE_DEFAULT", 1); } // In cuDNN_v6, dilated convolution descriptors are compatible with only a // single convolution algorithm. Despite this, we go through the algorithm // selection process, which will return the only algorithm supported. This // approach keeps the treatment of convolution cases uniform and will // naturally respond to more algorithms supporting dilated convolutions in // future cuDNN releases. SelectAlgo(rctx, in_shape, out_shape, cudnn_forward_compute_type, cudnn_backward_compute_type); GetTempSize(rctx); } ~CuDNNConvolutionOp() { CUDNN_CALL(cudnnDestroyTensorDescriptor(in_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(out_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(bias_desc_)); CUDNN_CALL(cudnnDestroyFilterDescriptor(filter_desc_)); CUDNN_CALL(cudnnDestroyConvolutionDescriptor(forward_conv_desc_)); CUDNN_CALL(cudnnDestroyConvolutionDescriptor(back_conv_desc_)); CUDNN_CALL(cudnnDestroyConvolutionDescriptor(back_conv_desc_w_)); } void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data) { using namespace mshadow; size_t expected = param_.no_bias ? 2 : 3; CHECK_EQ(in_data.size(), expected); CHECK_EQ(out_data.size(), 1U); Stream<gpu> *s = ctx.get_stream<gpu>(); Tensor<gpu, 1, DType> workspace = AllocateTempWorkspace(ctx, forward_workspace_byte_); size_t workspace_size = TensorSizeBytes(workspace); // I/O's should have 2 more dims than the kernel dim DType *data_ptr = GetNdPtr(in_data[conv::kData], param_.kernel.ndim() + 2, s); DType *wmat_ptr = GetNdPtr(in_data[conv::kWeight], param_.kernel.ndim() + 2, s); DType *out_ptr = GetNdPtr(out_data[conv::kOut], param_.kernel.ndim() + 2, s); typename DataType<DType>::ScaleType alpha = 1.0f; typename DataType<DType>::ScaleType beta = 0.0f; typename DataType<DType>::ScaleType beta_add = 1.0f; CUDNN_CALL(cudnnConvolutionForward(s->dnn_handle_, &alpha, in_desc_, data_ptr, filter_desc_, wmat_ptr, forward_conv_desc_, forward_algo_.AlgoNumber(), workspace.dptr_, workspace_size, req[conv::kOut] == kAddTo? &beta_add : &beta, out_desc_, out_ptr)); if (!param_.no_bias) { Tensor<gpu, 1, DType> bias = in_data[conv::kBias].get<gpu, 1, DType>(s); CUDNN_CALL(cudnnAddTensor(s->dnn_handle_, &alpha, bias_desc_, bias.dptr_, &beta_add, out_desc_, out_ptr)); } } void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad) { using namespace mshadow; using namespace mshadow::expr; size_t expected = param_.no_bias == 0 ? 3 : 2; CHECK_EQ(out_grad.size(), 1U); CHECK_EQ(in_data.size(), expected); CHECK_EQ(in_grad.size(), expected); Stream<gpu> *s = ctx.get_stream<gpu>(); // RAII object to handle syncing of the underlying auxiliary stream with the primary stream SyncedGPUAuxStream s_dgrad = ctx.get_gpu_aux_stream(); // I/O's should have 2 more dims than the kernel dim DType *grad_ptr = GetNdPtr(out_grad[conv::kOut], param_.kernel.ndim() + 2, s); DType *wmat_ptr = GetNdPtr(in_data[conv::kWeight], param_.kernel.ndim() + 2, s); DType *gwmat_ptr = GetNdPtr(in_grad[conv::kWeight], param_.kernel.ndim() + 2, s); DType *data_ptr = GetNdPtr(in_data[conv::kData], param_.kernel.ndim() + 2, s); DType *gdata_ptr = GetNdPtr(in_grad[conv::kData], param_.kernel.ndim() + 2, s); size_t backward_workspace_byte = parallelize_backward_kernels_ ? back_workspace_byte_dgrad_ + back_workspace_byte_wgrad_ : std::max(back_workspace_byte_dgrad_, back_workspace_byte_wgrad_); Tensor<gpu, 1, DType> workspace = AllocateTempWorkspace(ctx, backward_workspace_byte); size_t workspace_size = TensorSizeBytes(workspace); DType *workspace_dptr_wgrad = workspace.dptr_; DType *workspace_dptr_dgrad = workspace.dptr_; if (parallelize_backward_kernels_) { CHECK_LE(back_workspace_byte_dgrad_ + back_workspace_byte_wgrad_, workspace_size); // Large allocations at some point will be given their own page. Pass this alignment on to // the larger of the two separate dgrad/wgrad workspaces. This probably doesn't matter, but // corresponds more closely to the workspace alignments used during cudnnFind. if (back_workspace_byte_dgrad_ > back_workspace_byte_wgrad_) workspace_dptr_wgrad = workspace.dptr_ + back_workspace_byte_dgrad_ / sizeof(DType); else workspace_dptr_dgrad = workspace.dptr_ + back_workspace_byte_wgrad_ / sizeof(DType); } else { CHECK_LE(back_workspace_byte_dgrad_, workspace_size); CHECK_LE(back_workspace_byte_wgrad_, workspace_size); } typename DataType<DType>::ScaleType alpha = 1.0f; typename DataType<DType>::ScaleType beta = 0.0f; typename DataType<DType>::ScaleType beta_add = 1.0f; if (!param_.no_bias && (req[conv::kBias] != kNullOp)) { Tensor<gpu, 1, DType> gbias = in_grad[conv::kBias].get<gpu, 1, DType>(s); CUDNN_CALL(cudnnConvolutionBackwardBias(s->dnn_handle_, &alpha, out_desc_, grad_ptr, req[conv::kBias] == kAddTo ? &beta_add : &beta, bias_desc_, gbias.dptr_)); } if (req[conv::kWeight] != kNullOp) { if (!ctx.is_cac_gradient_skip) { CHECK_EQ(add_to_weight_, req[conv::kWeight] == kAddTo); CUDNN_CALL(cudnnConvolutionBackwardFilter(s->dnn_handle_, &alpha, in_desc_, data_ptr, out_desc_, grad_ptr, back_conv_desc_w_, back_algo_w_.AlgoNumber(), workspace_dptr_wgrad, back_workspace_byte_wgrad_, req[conv::kWeight] == kAddTo? &beta_add : &beta, filter_desc_, gwmat_ptr)); } } if (req[conv::kData] != kNullOp) { CUDNN_CALL(cudnnConvolutionBackwardData(s_dgrad.GetStream()->dnn_handle_, &alpha, filter_desc_, wmat_ptr, out_desc_, grad_ptr, back_conv_desc_, back_algo_.AlgoNumber(), workspace_dptr_dgrad, back_workspace_byte_dgrad_, req[conv::kData] == kAddTo? &beta_add : &beta, in_desc_, gdata_ptr)); } } /*! * \brief Returns whether the cuDNN library version supports the convolution * operation described by `param`: cuDNN v5 and earlier does not support * dilated convolutions. Dilation only enabled after v6.0.20. */ static bool Supports(ConvolutionParam param, int forward_compute_type, int backward_compute_type, int dev_id) { using namespace mshadow; // NDHWC not supported, NHWC not supported in true fp16 auto layout_val = param.layout.value(); auto true_fp16 = DataType<DType>::kFlag == kFloat16 && (forward_compute_type == kFloat16 || backward_compute_type == kFloat16); if (layout_val == kNDHWC || layout_val == kNWC || layout_val == kNHWC && true_fp16) return false; // Permits graceful fallback to pseudo-fp16 on heterogenous systems if (!SupportsFloat16Compute(dev_id) && (forward_compute_type == kFloat16 || backward_compute_type == kFloat16)) { return false; } return true; } private: /*! * \brief Translate an mxnet datatype to the corresponding cudnnDataType_t. */ cudnnDataType_t convertToCuDNNDataType(int dtype) { cudnnDataType_t converted = CUDNN_DATA_FLOAT; // The following will always assign to `converted` or throw an exception. MSHADOW_REAL_TYPE_SWITCH(dtype, mxDType, { converted = mshadow::DataType<mxDType>::kCudnnFlag; }) return converted; } void InitDescriptors(const mxnet::ShapeVector& in_shape, const mxnet::ShapeVector& out_shape, cudnnDataType_t cudnn_forward_compute_type, cudnnDataType_t cudnn_backward_compute_type) { using namespace mshadow; size_t expected = param_.no_bias ? 2 : 3; CHECK_EQ(in_shape.size(), expected); CHECK_EQ(out_shape.size(), 1U); mxnet::TShape dshape = in_shape[conv::kData]; mxnet::TShape wshape = in_shape[conv::kWeight]; mxnet::TShape oshape = out_shape[conv::kOut]; mxnet::TShape dstride, ostride; if (param_.kernel.ndim() == 1 || param_.kernel.ndim() == 2) { // 1d or 2d conv auto pad = param_.kernel.ndim() == 2 ? param_.pad : mxnet::TShape({0, param_.pad[0]}); auto stride = param_.kernel.ndim() == 2 ? param_.stride : mxnet::TShape({1, param_.stride[0]}); auto dilate = param_.kernel.ndim() == 2 ? param_.dilate : mxnet::TShape({1, param_.dilate[0]}); CUDNN_CALL(cudnnSetConvolution2dDescriptor(forward_conv_desc_, pad[0], pad[1], stride[0], stride[1], dilate[0], dilate[1], CUDNN_CROSS_CORRELATION, cudnn_forward_compute_type)); CUDNN_CALL(cudnnSetConvolution2dDescriptor(back_conv_desc_, pad[0], pad[1], stride[0], stride[1], dilate[0], dilate[1], CUDNN_CROSS_CORRELATION, cudnn_backward_compute_type)); CUDNN_CALL(cudnnSetConvolution2dDescriptor(back_conv_desc_w_, pad[0], pad[1], stride[0], stride[1], dilate[0], dilate[1], CUDNN_CROSS_CORRELATION, cudnn_backward_compute_type)); if (param_.kernel.ndim() == 2) { wshape = ConvertLayout(wshape.get<4>(), param_.layout.value(), kNCHW); dstride = ConvertLayout(Strides<4>(dshape), param_.layout.value(), kNCHW); dshape = ConvertLayout(dshape.get<4>(), param_.layout.value(), kNCHW); ostride = ConvertLayout(Strides<4>(oshape), param_.layout.value(), kNCHW); oshape = ConvertLayout(oshape.get<4>(), param_.layout.value(), kNCHW); } else { wshape = ConvertLayout(wshape.get<3>(), param_.layout.value(), kNCW); wshape = mxnet::TShape({wshape[0], wshape[1], 1, wshape[2]}); dstride = ConvertLayout(Strides<3>(dshape), param_.layout.value(), kNCW); dstride = mxnet::TShape({dstride[0], dstride[1], dstride[1], dstride[2]}); dshape = ConvertLayout(dshape.get<3>(), param_.layout.value(), kNCW); dshape = mxnet::TShape({dshape[0], dshape[1], 1, dshape[2]}); ostride = ConvertLayout(Strides<3>(oshape), param_.layout.value(), kNCW); ostride = mxnet::TShape({ostride[0], ostride[1], ostride[1], ostride[2]}); oshape = ConvertLayout(oshape.get<3>(), param_.layout.value(), kNCW); oshape = mxnet::TShape({oshape[0], oshape[1], 1, oshape[2]}); } CUDNN_CALL(cudnnSetFilter4dDescriptor(filter_desc_, dtype_, format_, wshape[0], wshape[1], wshape[2], wshape[3])); auto kernel_h = wshape[2]; auto kernel_w = wshape[3]; // The 5x5 non-fused Winograd kernel is fast, but because of its reduced numerical // accuracy compared to other algos, users must opt-in to its use. bool exclude_nonfused_winograd_5x5 = !dmlc::GetEnv("MXNET_CUDNN_ENABLE_WINOGRAD_NONFUSED_5X5", false); if (exclude_nonfused_winograd_5x5 && kernel_h == 5 && kernel_w == 5) { excluded_forward_algos_.insert(CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED); excluded_back_algos_.insert(CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED); excluded_back_algos_w_.insert(CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED); } } else if (param_.kernel.ndim() == 3) { // 3d conv CHECK_EQ(param_.layout.value(), kNCDHW) << "CuDNN only support 3D conv with NCDHW layout"; std::vector<int> wshape_buffer(wshape.ndim()); CUDNN_CALL(cudnnSetFilterNdDescriptor(filter_desc_, dtype_, CUDNN_TENSOR_NCHW, static_cast<int>(wshape.ndim()), CastTShapeToIntPtr(wshape, &wshape_buffer))); CUDNN_CALL(cudnnSetConvolutionNdDescriptor(forward_conv_desc_, 3, param_pad_.data(), param_stride_.data(), param_dilate_.data(), CUDNN_CROSS_CORRELATION, cudnn_forward_compute_type)); CUDNN_CALL(cudnnSetConvolutionNdDescriptor(back_conv_desc_, 3, param_pad_.data(), param_stride_.data(), param_dilate_.data(), CUDNN_CROSS_CORRELATION, cudnn_backward_compute_type)); CUDNN_CALL(cudnnSetConvolutionNdDescriptor(back_conv_desc_w_, 3, param_pad_.data(), param_stride_.data(), param_dilate_.data(), CUDNN_CROSS_CORRELATION, cudnn_backward_compute_type)); dstride = ConvertLayout(Strides<5>(dshape), param_.layout.value(), kNCDHW); dshape = ConvertLayout(dshape.get<5>(), param_.layout.value(), kNCDHW); ostride = ConvertLayout(Strides<5>(oshape), param_.layout.value(), kNCDHW); oshape = ConvertLayout(oshape.get<5>(), param_.layout.value(), kNCDHW); } // Set "allow tensor core" flag in convolution descriptors, if available. cudnnMathType_t math_type = param_.cudnn_tensor_core.value() ? CUDNN_TENSOR_OP_MATH : CUDNN_DEFAULT_MATH; #if CUDNN_VERSION >= 7200 if (GetEnvAllowTensorCore() && GetEnvAllowTensorCoreConversion() && (DataType<DType>::kFlag != kFloat16)) math_type = CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION; #endif CUDNN_CALL(cudnnSetConvolutionMathType(forward_conv_desc_, math_type)); CUDNN_CALL(cudnnSetConvolutionMathType(back_conv_desc_, math_type)); CUDNN_CALL(cudnnSetConvolutionMathType(back_conv_desc_w_, math_type)); CUDNN_CALL(cudnnSetConvolutionGroupCount(forward_conv_desc_, param_.num_group)); CUDNN_CALL(cudnnSetConvolutionGroupCount(back_conv_desc_, param_.num_group)); CUDNN_CALL(cudnnSetConvolutionGroupCount(back_conv_desc_w_, param_.num_group)); std::vector<int> dshape_buffer(dshape.ndim()); nnvm::ShapeTypeCast(dshape.begin(), dshape.end(), dshape_buffer.data()); std::vector<int> dstride_buffer(dstride.ndim()); nnvm::ShapeTypeCast(dstride.begin(), dstride.end(), dstride_buffer.data()); CUDNN_CALL(cudnnSetTensorNdDescriptor(in_desc_, dtype_, static_cast<int>(dshape.ndim()), dshape_buffer.data(), dstride_buffer.data())); std::vector<int> oshape_buffer(oshape.ndim()); nnvm::ShapeTypeCast(oshape.begin(), oshape.end(), oshape_buffer.data()); std::vector<int> ostride_buffer(ostride.ndim()); nnvm::ShapeTypeCast(ostride.begin(), ostride.end(), ostride_buffer.data()); CUDNN_CALL(cudnnSetTensorNdDescriptor(out_desc_, dtype_, static_cast<int>(oshape.ndim()), oshape_buffer.data(), ostride_buffer.data())); if (!param_.no_bias) { mxnet::TShape bias = in_shape[conv::kBias]; std::vector<int> bias_shape = {1, static_cast<int>(bias[0]), 1, 1}; std::vector<int> bias_stride = {static_cast<int>(bias[0]), 1, 1, 1}; if (param_.kernel.ndim() == 3) { bias_shape.push_back(1); bias_stride.push_back(1); } CUDNN_CALL(cudnnSetTensorNdDescriptor(bias_desc_, dtype_, static_cast<int>(bias_shape.size()), &bias_shape[0], &bias_stride[0])); } } void CuDNNAlgoSetter(const RunContext& rctx, const mxnet::ShapeVector& in_shape, const mxnet::ShapeVector& out_shape, cudnnDataType_t cudnn_forward_compute_type, cudnnDataType_t cudnn_backward_compute_type, CuDNNAlgo<cudnnConvolutionFwdAlgo_t> *fwd, CuDNNAlgo<cudnnConvolutionBwdDataAlgo_t> *bwd, CuDNNAlgo<cudnnConvolutionBwdFilterAlgo_t> *flt) { // Not in algo registry, must determine via *Get*() or *Find*() mshadow::Stream<gpu> *s = rctx.get_stream<gpu>(); CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle); size_t workspace_byte = static_cast<size_t>(param_.workspace * sizeof(DType)); // Since the function signature of *Get*_v7() matches that of *Find*(), // we can unify the find-vs-get logic by using function pointers. // Forward Algorithm Find/Get() v7 std::vector<cudnnConvolutionFwdAlgoPerf_t> fwd_results(MaxForwardAlgos(s->dnn_handle_)); int actual_fwd_algos = 0; auto fwd_algo_discoverer = param_.cudnn_tune.value() == conv::kOff ? cudnnGetConvolutionForwardAlgorithm_v7 : cudnnFindConvolutionForwardAlgorithm; CUDNN_CALL((*fwd_algo_discoverer)(s->dnn_handle_, in_desc_, filter_desc_, forward_conv_desc_, out_desc_, fwd_results.size(), &actual_fwd_algos, fwd_results.data())); fwd_results.resize(actual_fwd_algos); AlgoFinalSelect<cudnnConvolutionFwdAlgoPerf_t, cudnnConvolutionFwdAlgo_t>(fwd_results, "forward", param_.cudnn_algo_fwd, workspace_byte, fwd, excluded_forward_algos_); // Backprop-to-Filter Algorithm Find/Get() v7 auto max_bwd_filt_algos = MaxBackwardFilterAlgos(s->dnn_handle_); std::vector<cudnnConvolutionBwdFilterAlgoPerf_t> bwd_filt_results(max_bwd_filt_algos); int actual_bwd_filter_algos = 0; // In cudnn v7.1.4, find() returned wgrad algos that could fail for large c if we // were summing into the output (i.e. beta != 0). Get() returned OK algos though. auto bwd_filter_algo_discoverer = param_.cudnn_tune.value() == conv::kOff ? cudnnGetConvolutionBackwardFilterAlgorithm_v7 : cudnnFindConvolutionBackwardFilterAlgorithm; CUDNN_CALL((*bwd_filter_algo_discoverer)(s->dnn_handle_, in_desc_, out_desc_, back_conv_desc_w_, filter_desc_, bwd_filt_results.size(), &actual_bwd_filter_algos, bwd_filt_results.data())); bwd_filt_results.resize(actual_bwd_filter_algos); AlgoFinalSelect<cudnnConvolutionBwdFilterAlgoPerf_t, cudnnConvolutionBwdFilterAlgo_t>(bwd_filt_results, "backprop-to-filter", param_.cudnn_algo_bwd_filter, workspace_byte, flt, excluded_back_algos_w_); // Backprop-to-Data Algorithm Find/Get() v7 auto max_bwd_data_algos = MaxBackwardDataAlgos(s->dnn_handle_); std::vector<cudnnConvolutionBwdDataAlgoPerf_t> bwd_data_results(max_bwd_data_algos); int actual_bwd_data_algos = 0; auto bwd_data_algo_discoverer = param_.cudnn_tune.value() == conv::kOff ? cudnnGetConvolutionBackwardDataAlgorithm_v7 : cudnnFindConvolutionBackwardDataAlgorithm; CUDNN_CALL((*bwd_data_algo_discoverer)(s->dnn_handle_, filter_desc_, out_desc_, back_conv_desc_, in_desc_, bwd_data_results.size(), &actual_bwd_data_algos, bwd_data_results.data())); bwd_data_results.resize(actual_bwd_data_algos); AlgoFinalSelect<cudnnConvolutionBwdDataAlgoPerf_t, cudnnConvolutionBwdDataAlgo_t>(bwd_data_results, "backprop-to-data", param_.cudnn_algo_bwd_data, workspace_byte, bwd, excluded_back_algos_); // Fix for issue #11241 int cudnn_find_issue_max_features = 64 * 1024; if (add_to_weight_ && Features(in_shape[conv::kData]) >= cudnn_find_issue_max_features) { flt->Set(CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1, true); } if (param_.cudnn_algo_verbose) { std::string key = CuDNNConvAlgoReg::Get()->ToString(param_, in_shape, out_shape, dtype_, cudnn_forward_compute_type, cudnn_backward_compute_type, SMArch(rctx.ctx.dev_id)); LOG(INFO) << "Algo selection for convolution: " << key; LOG(INFO) << " forward : " << fwd->AlgoNumber() << TensorCoreStr(rctx.ctx, fwd->IsTensorCoreAlgo()); LOG(INFO) << " backprop-to-data: " << bwd->AlgoNumber() << TensorCoreStr(rctx.ctx, bwd->IsTensorCoreAlgo()); LOG(INFO) << " backprop-to-filter: " << flt->AlgoNumber() << TensorCoreStr(rctx.ctx, flt->IsTensorCoreAlgo()); LOG(INFO) << ""; } } void SelectAlgo(const RunContext& rctx, const mxnet::ShapeVector& in_shape, const mxnet::ShapeVector& out_shape, cudnnDataType_t cudnn_forward_compute_type, cudnnDataType_t cudnn_backward_compute_type) { auto algo_setter = [&](CuDNNAlgo<cudnnConvolutionFwdAlgo_t> *fwd, CuDNNAlgo<cudnnConvolutionBwdDataAlgo_t> *bwd, CuDNNAlgo<cudnnConvolutionBwdFilterAlgo_t> *flt) { if (param_.cudnn_tune.value() == conv::kOff) { // The routine will only be calling cudnnGet, so no need to grab the Storage lock. this->CuDNNAlgoSetter(rctx, in_shape, out_shape, cudnn_forward_compute_type, cudnn_backward_compute_type, fwd, bwd, flt); } else { // One potential problem is that cudnnFind() uses cudaMalloc() to directly allocate // I/O and workspace areas, and these allocations may result in an out-of-memory // error even though the StorageMangager free pool is not empty. Ideally, cudnnFind // would use MXNet's storage allocator for its I/O and workspace areas, instead of using // the area carved out by MXNET_GPU_MEM_POOL_RESERVE. // To get somewhat the same effect as this, we can pre-allocate the areas needed for the // I/Os (possibly triggering a desirable StorageManager::ReleaseAll()), followed by a // DirectFree(), which makes these areas available for cudnn's subsequent cudaMalloc(). // Allocate for x (or dx), w (or dw) and y (or dy). ReserveElements({in_shape[conv::kData].Size(), in_shape[conv::kWeight].Size(), out_shape[conv::kOut].Size()}); // We're about to call cudnnFind so we need to quiet the system by grabbing // the Storage lock. Concurrent cudaMalloc's can disrupt the accurate timing // measurements of the algos, and can prevent the cuda driver's proper freeing // of cudnnFind's internal temporary allocations. Grabbing the lock might also // impede other threads from launching work on the GPU. std::lock_guard<std::mutex> lock(Storage::Get()->GetMutex(Context::kGPU)); this->CuDNNAlgoSetter(rctx, in_shape, out_shape, cudnn_forward_compute_type, cudnn_backward_compute_type, fwd, bwd, flt); } }; CuDNNConvAlgoReg::Get()->FindOrElseRegister(param_, in_shape, out_shape, dtype_, cudnn_forward_compute_type, cudnn_backward_compute_type, SMArch(rctx.ctx.dev_id), add_to_weight_, &forward_algo_, &back_algo_, &back_algo_w_, algo_setter); // If we're allowing Tensor Core variants of the algos to be considered in // *Find*() or *Get*(), but a non-Tensor-Core algo variant is the fastest, // we must change the descriptor to preclude Tensor Core. Simplest is to // once again set the mathType in all cases. CUDNN_CALL(cudnnSetConvolutionMathType(forward_conv_desc_, forward_algo_.MathType())); CUDNN_CALL(cudnnSetConvolutionMathType(back_conv_desc_, back_algo_.MathType())); CUDNN_CALL(cudnnSetConvolutionMathType(back_conv_desc_w_, back_algo_w_.MathType())); } // Convert the `is_tensor_core_algo` flag to a string for verbose-mode output std::string TensorCoreStr(const Context& ctx, bool is_tensor_core_algo) { // GPU's before Volta (sm_70) would not be expected to run Tensor Core algos, // so we don't report whether the algo is/is-not Tensor Core in that case. if (!SupportsTensorCore(ctx.dev_id)) return std::string(""); else if (is_tensor_core_algo) return std::string(" (Tensor Core)"); else return std::string(" (not Tensor Core)"); } std::string FixedFormat(float f, int width, int precision) { std::stringstream ss; ss << std::fixed << std::setprecision(precision) << std::setw(width) << f; return ss.str(); } // Look over the results from *Find*() or *Get*() and pick the fastest algo given possible // workspace constraints and a possible user algo preference. template <typename PerfType, typename AlgoType> void AlgoFinalSelect(const std::vector<PerfType> &perf_results, std::string kernel_name, int32_t algo_preference, size_t workspace_byte, CuDNNAlgo<AlgoType> *algo, const std::set<AlgoType> &excluded_algos) { // Determine the fastest acceptable algo that matches the algo_preference (-1 = any), // regardless of mathType. auto mode = param_.cudnn_tune.value() == conv::kOff ? " get " : " find "; if (param_.cudnn_algo_verbose && ALGO_VERBOSE_LEVEL >= 2) { LOG(INFO) << "Full results of algo" << mode << kernel_name << ":"; for (const auto &result : perf_results) { auto math_type_str = "-"; if (result.mathType == CUDNN_TENSOR_OP_MATH) math_type_str = "+"; LOG(INFO) << " algo: " << result.algo << ", TC" << math_type_str << ", time: " << FixedFormat(result.time, 7, 3) << "ms" << ", wksp = " << result.memory << ", status = " << result.status; } } bool enforce_determinism = dmlc::GetEnv("MXNET_ENFORCE_DETERMINISM", false); for (decltype(perf_results.size()) i = 0; i != perf_results.size(); ++i) { const auto &result = perf_results[i]; bool algo_is_tensor_core = result.mathType == CUDNN_TENSOR_OP_MATH; bool algo_exclusion = param_.cudnn_tensor_core_only && !algo_is_tensor_core || (result.algo != algo_preference) && (excluded_algos.count(result.algo) != 0); if (result.status == CUDNN_STATUS_SUCCESS && (!enforce_determinism || result.determinism == cudnnDeterminism_t::CUDNN_DETERMINISTIC) && (param_.cudnn_tune.value() == conv::kFastest || result.memory <= workspace_byte) && (algo_preference == -1 || algo_preference == result.algo) && !algo_exclusion) { // Fix for a current cuDNNv7 behavior where algos are reported twice // with equivalent performance (both as Tensor Core and not Tensor Core). if ((result.mathType == CUDNN_TENSOR_OP_MATH) && (i != perf_results.size() - 1) && !param_.cudnn_tensor_core_only) { const auto &next_result = perf_results[i+1]; if (next_result.status == CUDNN_STATUS_SUCCESS && next_result.algo == result.algo && next_result.memory == result.memory && next_result.mathType != CUDNN_TENSOR_OP_MATH && next_result.time < ALGO_PERF_THRESHOLD * result.time) { // Skip over this result- it's not really a Tensor Core algo. // Prefer instead the next equivalent non-Tensor Core algo. continue; } } algo->Set(result.algo, algo_is_tensor_core); return; } } if (algo_preference != -1) LOG(FATAL) << "Failed to" << mode << kernel_name << " convolution algorithm " << algo_preference << " with workspace size of " << workspace_byte << " bytes," << " please consider reducing batch/model size or increasing the workspace size"; else LOG(FATAL) << "Failed to" << mode << "any " << kernel_name << " convolution algorithm" << " with workspace size of " << workspace_byte << " bytes," << " please consider reducing batch/model size or increasing the workspace size"; } void GetTempSize(const RunContext& rctx) { mshadow::Stream<gpu> *s = rctx.get_stream<gpu>(); CUDNN_CALL(cudnnGetConvolutionBackwardDataWorkspaceSize(s->dnn_handle_, filter_desc_, out_desc_, back_conv_desc_, in_desc_, back_algo_.AlgoNumber(), &back_workspace_byte_dgrad_)); CUDNN_CALL(cudnnGetConvolutionBackwardFilterWorkspaceSize(s->dnn_handle_, in_desc_, out_desc_, back_conv_desc_w_, filter_desc_, back_algo_w_.AlgoNumber(), &back_workspace_byte_wgrad_)); // cudaMalloc returns addresses that are aligned for large accesses (e.g. to 512 bytes). // Since we only make one allocation and divide it into two parts when we parallelize // the dgrad and wgrad kernels, we round the sizes up to this alignment size so the // dptrs respect this alignment, even if the separate areas are stacked. const size_t dptr_alignment = 512; back_workspace_byte_dgrad_ = RoundToMultiple(back_workspace_byte_dgrad_, dptr_alignment); back_workspace_byte_wgrad_ = RoundToMultiple(back_workspace_byte_wgrad_, dptr_alignment); CUDNN_CALL(cudnnGetConvolutionForwardWorkspaceSize(s->dnn_handle_, in_desc_, filter_desc_, forward_conv_desc_, out_desc_, forward_algo_.AlgoNumber(), &forward_workspace_byte_)); } int *CastTShapeToIntPtr(const mxnet::TShape& s, std::vector<int> *buffer) { buffer->resize(s.ndim()); nnvm::ShapeTypeCast(s.begin(), s.end(), buffer->data()); return buffer->data(); } // Converts a TBlob to a dptr, checking for the expected dim and that it's contiguous. DType *GetNdPtr(const TBlob& tb, int dim, Stream<gpu> *s) { DType *data_ptr = NULL; if (dim == 3) { Tensor<gpu, 3, DType> data = tb.get<gpu, 3, DType>(s); CHECK_EQ(data.CheckContiguous(), true); data_ptr = data.dptr_; } else if (dim == 4) { Tensor<gpu, 4, DType> data = tb.get<gpu, 4, DType>(s); CHECK_EQ(data.CheckContiguous(), true); data_ptr = data.dptr_; } else if (dim == 5) { Tensor<gpu, 5, DType> data = tb.get<gpu, 5, DType>(s); CHECK_EQ(data.CheckContiguous(), true); data_ptr = data.dptr_; } else { LOG(FATAL) << "Unexpected Tensor size " << dim << ", supporting only 3, 4 or 5."; } return data_ptr; } // Converts a mxnet::TShape to a Shape<> of strides. // e.g. {shape[0], shape[1], shape[2]} -> {shape[1]*shape[2], shape[2], 1} template <int dim> inline Shape<dim> Strides(const mxnet::TShape &s) { int ndim = s.ndim(); mxnet::TShape strides(ndim, -1); for (int i = 0; i != ndim; ++i) strides[i] = s.ProdShape(i+1, ndim); return strides.get<dim>(); } void InitBufferForParam() { CastTShapeToIntPtr(param_.stride, &param_stride_); CastTShapeToIntPtr(param_.dilate, &param_dilate_); CastTShapeToIntPtr(param_.pad, &param_pad_); } // Round a value 'x' up to the next multiple of 'multiple' size_t RoundToMultiple(size_t x, size_t multiple) { size_t retVal = ((x + multiple - 1) / multiple) * multiple; return retVal; } // Allocates a 1D Tensor of words with size in bytes >= `size_bytes`. // Always allocates at least one word. mshadow::Tensor<gpu, 1, DType> AllocateTempWorkspace(const OpContext &ctx, size_t size_bytes) { mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); size_t size_words = std::max<size_t>(1, RoundToMultiple(size_bytes, sizeof(DType)) / sizeof(DType)); return ctx.requested[conv::kTempSpace].get_space_typed<gpu, 1, DType>( mshadow::Shape1(size_words), s); } // Returns the size in bytes of the 1D Tensor of words. size_t TensorSizeBytes(const mshadow::Tensor<gpu, 1, DType> &tensor) { return tensor.MSize() * sizeof(DType); } // Given a tensor shape of this operation, return the number of features 'c' int64_t Features(const mxnet::TShape &dshape) { int c = 0; switch (dshape.ndim()) { case 3: c = ConvertLayout(dshape.get<3>(), param_.layout.value(), kNCW)[1]; break; case 4: c = ConvertLayout(dshape.get<4>(), param_.layout.value(), kNCHW)[1]; break; case 5: c = ConvertLayout(dshape.get<5>(), param_.layout.value(), kNCDHW)[1]; break; default: LOG(FATAL) << "Unexpected convolution data dimension " << dshape.ndim(); } return c; } // Make a number of allocations and directly free them, ensuring room for an equivalent set of // cudaMalloc() calls by (say) cudnnFind(). `elements` spec the alloc size in DTypes, not bytes. void ReserveElements(const std::vector<size_t> &elements) { std::vector<Storage::Handle> handles; for (size_t alloc_element : elements) handles.push_back(Storage::Get()->Alloc(alloc_element * sizeof(DType), Context::GPU())); for (auto &handle : handles) Storage::Get()->DirectFree(handle); } // Log that no suitable algo was found that met the workspace constraints, then exit. void LogNoSuitableAlgoAndExit(int num_algos_tried, size_t min_memory_needs, size_t workspace_byte, std::string algo_kind) { LOG(FATAL) << num_algos_tried << " " << algo_kind << " with minimum memory requirement " << min_memory_needs << " bytes have been tried. Workspace size is set to " << workspace_byte << " bytes, please consider reducing the batch/model size, " << "or increasing workspace size."; } std::vector<int> param_stride_; std::vector<int> param_dilate_; std::vector<int> param_pad_; // Temp workspace size in bytes needed for Forward() operation. size_t forward_workspace_byte_; // Temp workspace size in bytes needed for Backward() dgrad (data gradient) operation. size_t back_workspace_byte_dgrad_; // Temp workspace size in bytes needed for Backward() wgrad (weight gradient) operation. size_t back_workspace_byte_wgrad_; cudnnDataType_t dtype_; cudnnTensorDescriptor_t in_desc_; cudnnTensorDescriptor_t out_desc_; cudnnTensorDescriptor_t bias_desc_; cudnnFilterDescriptor_t filter_desc_; // Convolution descriptor for forward inference operation cudnnConvolutionDescriptor_t forward_conv_desc_; // Convolution descriptor for back-prop operations to the data cudnnConvolutionDescriptor_t back_conv_desc_; // Convolution descriptor for back-prop operations to the weights cudnnConvolutionDescriptor_t back_conv_desc_w_; // Should dgrad and wgrad be launched into separate streams bool parallelize_backward_kernels_; // Algorithm for the forward inference operation CuDNNAlgo<cudnnConvolutionFwdAlgo_t> forward_algo_; // Algorithm for the back-prop operation to the data CuDNNAlgo<cudnnConvolutionBwdDataAlgo_t> back_algo_; // Algorithm for the back-prop operation to the weights CuDNNAlgo<cudnnConvolutionBwdFilterAlgo_t> back_algo_w_; cudnnTensorFormat_t format_; ConvolutionParam param_; // Is req[kWeight] == conv::kAddTo ? bool add_to_weight_; // forward algos that should be avoided to work-around possible cuDNN issues. std::set<cudnnConvolutionFwdAlgo_t> excluded_forward_algos_; // dgrad algos that should be avoided to work-around possible cuDNN issues. std::set<cudnnConvolutionBwdDataAlgo_t> excluded_back_algos_; // wgrad algos that should be avoided to work-around possible cuDNN issues. std::set<cudnnConvolutionBwdFilterAlgo_t> excluded_back_algos_w_; }; #endif // __CUDACC__ && CUDNN } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_CUDNN_CUDNN_CONVOLUTION_INL_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/ml_perf/eval_models.h<|end_filename|> // Copyright 2020 Google LLC // // 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. // Evaluates a directory of models against the target model, as part of the rl // loop. It uses the single-model evaluation class set up in cc/eval.h and // cc/eval.cc. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_ML_PERF_EVAL_MODELS_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_ML_PERF_EVAL_MODELS_H_ #include "REDACTEDflags/flag.h" ABSL_DECLARE_FLAG(int32_t, start); ABSL_DECLARE_FLAG(int32_t, end); ABSL_DECLARE_FLAG(std::string, timestamp_file); ABSL_DECLARE_FLAG(int32_t, num_games); ABSL_DECLARE_FLAG(std::string, start_file); ABSL_DECLARE_FLAG(std::string, model_dir); ABSL_DECLARE_FLAG(double, target_winrate); ABSL_DECLARE_FLAG(std::vector<std::string>, devices); namespace minigo { struct ModelInfoTuple { std::string timestamp, name, model_path; }; std::vector<ModelInfoTuple> load_train_times(); void EvaluateModels(std::vector<minigo::ModelInfoTuple> models, int num_games); } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_ML_PERF_EVAL_MODELS_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/concurrent_selfplay.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/concurrent_selfplay.h" // Inference flags. DEFINE_string(device, "", "Optional ID of the device to run inference on. For TPUs, pass " "the gRPC address."); DEFINE_string(model, "", "Path to a minigo model. If passing model_dir/%d.pb," " will play game with the most recent model with the largest" "model name. If using SavedModel api with tpu engine, pass" "model_dir/%d/saved_model.pb"); DEFINE_int32(cache_size_mb, 0, "Size of the inference cache in MB."); DEFINE_int32(cache_shards, 8, "Number of ways to shard the inference cache. The cache uses " "is locked on a per-shard basis, so more shards means less " "contention but each shard is smaller. The number of shards " "is clamped such that it's always <= parallel_games."); // Tree search flags. DEFINE_int32(num_readouts, 104, "Number of readouts to make during tree search for each move."); DEFINE_double(fastplay_frequency, 0.0, "The fraction of moves that should use a lower number of " "playouts, aka 'playout cap oscillation'.\nIf this is set, " "'fastplay_readouts' should also be set."); DEFINE_int32(fastplay_readouts, 20, "The number of readouts to perform on a 'low readout' move, " "aka 'playout cap oscillation'.\nIf this is set, " "'fastplay_frequency' should be nonzero."); DEFINE_int32(virtual_losses, 8, "Number of virtual losses when running tree search."); DEFINE_double(dirichlet_alpha, 0.03, "Alpha value for Dirichlet noise."); DEFINE_double(noise_mix, 0.25, "The amount of noise to mix into the root."); DEFINE_double(value_init_penalty, 2.0, "New children value initialization penalty.\n" "Child value = parent's value - penalty * color, clamped to " "[-1, 1]. Penalty should be in [0.0, 2.0].\n" "0 is init-to-parent, 2.0 is init-to-loss [default].\n" "This behaves similiarly to Leela's FPU \"First Play Urgency\"."); DEFINE_bool(target_pruning, false, "If true, subtract visits from all moves that weren't the best " "move until the uncertainty level compensates."); DEFINE_double(policy_softmax_temp, 0.98, "For soft-picked moves, the probabilities are exponentiated by " "policy_softmax_temp to encourage diversity in early play.\n"); DEFINE_bool(allow_pass, true, "If false, pass moves will only be read and played if there is no " "other legal alternative."); DEFINE_int32(restrict_pass_alive_play_threshold, 4, "If the opponent has passed at least " "restrict_pass_alive_play_threshold pass moves in a row, playing " "moves in pass-alive territory of either player is disallowed."); // Threading flags. DEFINE_int32(selfplay_threads, 3, "Number of threads to run batches of selfplay games on."); DEFINE_int32(parallel_search, 3, "Number of threads to run tree search on."); DEFINE_int32(parallel_inference, 2, "Number of threads to run inference on."); DEFINE_int32(concurrent_games_per_thread, 1, "Number of games to play concurrently on each selfplay thread. " "Inferences from a thread's concurrent games are batched up and " "evaluated together. Increasing concurrent_games_per_thread can " "help improve GPU or TPU utilization, especially for small " "models."); // Game flags. DEFINE_uint64(seed, 0, "Random seed. Use default value of 0 to use a time-based seed. " "This seed is used to control the moves played, not whether a " "game has resignation disabled or is a holdout."); DEFINE_double(min_resign_threshold, -1.0, "Each game's resign threshold is picked randomly from the range " "[min_resign_threshold, max_resign_threshold)"); DEFINE_double(max_resign_threshold, -0.8, "Each game's resign threshold is picked randomly from the range " "[min_resign_threshold, max_resign_threshold)"); DEFINE_double(disable_resign_pct, 0.1, "Fraction of games to disable resignation for."); DEFINE_int32(num_games, 0, "Total number of games to play. Only one of run_forever and " "num_games must be set."); DEFINE_bool(run_forever, false, "Whether to run forever. Only one of run_forever and num_games " "must be set."); DEFINE_string(abort_file, "", "If non-empty, specifies a path to a file whose presence is " "checked for periodically when run_forever=true. If the file " "exists the selfplay process will abort immediately."); // Output flags. DEFINE_double(holdout_pct, 0.03, "Fraction of games to hold out for validation."); DEFINE_string(output_dir, "", "Output directory. If empty, no examples are written. If " "output_dir contains the substring \"$MODEL\", the name of " "the last models used for inference when playing a game will " "be substituded in the path."); DEFINE_string(holdout_dir, "", "Holdout directory. If empty, no examples are written. If " "holdout_dir contains the substring \"$MODEL\", the name of " "the last models used for inference when playing a game will " "be substituded in the path."); DEFINE_string(sgf_dir, "", "Directory to write output SGFs to. If sgf_dir contains the " "substring \"$MODEL\", the name of the last models used for " "inference when playing a game will be substituded in the " "path."); DEFINE_string(wtf_trace, "/tmp/minigo.wtf-trace", "Output path for WTF traces."); DEFINE_bool(verbose, true, "Whether to log progress."); DEFINE_int32(output_threads, 1, "Number of threads write training examples on."); namespace minigo { Selfplayer::Selfplayer() : rnd_(FLAGS_seed, Random::kUniqueStream), executor_(FLAGS_parallel_search) { absl::MutexLock lock(&mutex_); ParseFlags(); } SelfplayGame::SelfplayGame(int game_id, const Options& options, std::unique_ptr<Game> game, std::unique_ptr<MctsTree> tree) : options_(options), game_(std::move(game)), tree_(std::move(tree)), use_ansi_colors_(FdSupportsAnsiColors(fileno(stderr))), start_time_(absl::Now()), rnd_(FLAGS_seed, Random::kUniqueStream), inference_symmetry_mix_(rnd_.UniformUint64()), game_id_(game_id) { target_readouts_ = options_.num_readouts; } SelfplayGame::SelectLeavesStats SelfplayGame::SelectLeaves( InferenceCache* cache, std::vector<Inference>* inferences) { // We can only inject noise if the root is expanded. If it isn't expanded // yet, the next call to SelectLeaf must by definition select the root (and // break out of the loop below). We'll then inject the noise on the subsequent // call to SelectLeaves. if (inject_noise_before_next_read_ && tree_->root()->is_expanded) { inject_noise_before_next_read_ = false; InjectNoise(); } const auto* root = tree_->root(); SelectLeavesStats stats; do { auto* leaf = tree_->SelectLeaf(options_.allow_pass); if (leaf == nullptr) { break; } stats.num_nodes_selected += leaf->position.n() - root->position.n(); if (leaf->game_over()) { float value = leaf->position.CalculateScore(game_->options().komi) > 0 ? 1 : -1; tree_->IncorporateEndGameResult(leaf, value); stats.num_game_over_leaves += 1; continue; } if (MaybeQueueInference(leaf, cache, inferences)) { stats.num_leaves_queued += 1; } else { stats.num_cache_hits += 1; } if (leaf == root) { if (!fastplay_) { inject_noise_before_next_read_ = true; } break; } } while (stats.num_leaves_queued < options_.num_virtual_losses && tree_->root()->N() < target_readouts_); return stats; } void SelfplayGame::ProcessInferences(const std::string& model_name, absl::Span<const Inference> inferences) { if (!model_name.empty()) { if (models_used_.empty() || model_name != models_used_.back()) { models_used_.push_back(model_name); } } for (const auto& inference : inferences) { tree_->IncorporateResults(inference.leaf, inference.output.policy, inference.output.value); tree_->RevertVirtualLoss(inference.leaf); } } bool SelfplayGame::MaybePlayMove() { // Check if this game's tree search has performed enough reads that it // should now play a move. if (tree_->root()->N() < target_readouts_) { return false; } // Handle resignation. if (ShouldResign()) { game_->SetGameOverBecauseOfResign(OtherColor(tree_->to_play())); } else { // Restrict playing in pass-alive territory once the opponent has passed // `restrict_pass_alive_play_threshold` times in a row. int num_opponent_passes = num_consecutive_passes_[tree_->to_play() == Color::kBlack ? 1 : 0]; bool restrict_pass_alive_moves = num_opponent_passes >= options_.restrict_pass_alive_play_threshold; Coord c = tree_->PickMove(&rnd_, restrict_pass_alive_moves); if (options_.verbose) { const auto& position = tree_->root()->position; MG_LOG(INFO) << position.ToPrettyString(use_ansi_colors_); MG_LOG(INFO) << "Move: " << position.n() << " Captures X: " << position.num_captures()[0] << " O: " << position.num_captures()[1]; if (!fastplay_) { MG_LOG(INFO) << tree_->Describe(); } MG_LOG(INFO) << absl::StreamFormat("Q: %0.5f", tree_->root()->Q()); MG_LOG(INFO) << "Played >> " << tree_->to_play() << "[" << c << "]"; } std::string model_str; if (!models_used_.empty()) { model_str = absl::StrCat("model: ", models_used_.back(), "\n"); } if (options_.target_pruning && !fastplay_) { tree_->ReshapeFinalVisits(restrict_pass_alive_moves); } if (!fastplay_ && c != Coord::kResign) { auto search_pi = tree_->CalculateSearchPi(); game_->AddTrainableMove(tree_->to_play(), c, tree_->root()->position, std::move(model_str), tree_->root()->Q(), tree_->root()->N(), search_pi); } else { game_->AddNonTrainableMove(tree_->to_play(), c, tree_->root()->position, std::move(model_str), tree_->root()->Q(), tree_->root()->N()); } // Update the number of consecutive passes. // The number of consecutive passes latches when it hits // `restrict_pass_alive_play_threshold`. int& num_passes = num_consecutive_passes_[tree_->to_play() == Color::kBlack ? 0 : 1]; if (num_passes < options_.restrict_pass_alive_play_threshold) { if (c == Coord::kPass) { num_passes += 1; } else { num_passes = 0; } } tree_->PlayMove(c); // If the whole board is pass-alive, play pass moves to end the game. if (tree_->root()->position.n() >= kMinPassAliveMoves && tree_->root()->position.CalculateWholeBoardPassAlive()) { while (!tree_->is_game_over()) { tree_->PlayMove(Coord::kPass); } } // TODO(tommadams): move game over logic out of MctsTree and into Game. if (tree_->is_game_over()) { game_->SetGameOverBecauseOfPasses( tree_->CalculateScore(game_->options().komi)); } } if (!game_->game_over()) { fastplay_ = ShouldFastplay(); inject_noise_before_next_read_ = !fastplay_; int num_readouts = fastplay_ ? options_.fastplay_readouts : options_.num_readouts; target_readouts_ = tree_->root()->N() + num_readouts; if (!fastplay_) { if (options_.fastplay_frequency > 0) { tree_->ClearSubtrees(); } } } else { duration_ = absl::Now() - start_time_; } return true; } bool SelfplayGame::ShouldFastplay() { return options_.fastplay_frequency > 0 && rnd_() < options_.fastplay_frequency; } bool SelfplayGame::ShouldResign() const { return game_->options().resign_enabled && tree_->root()->Q_perspective() < game_->options().resign_threshold; } void SelfplayGame::InjectNoise() { tree_->InjectNoise(rnd_.Dirichlet<kNumMoves>(options_.dirichlet_alpha), options_.noise_mix); } symmetry::Symmetry SelfplayGame::GetInferenceSymmetry( const MctsNode* node) const { uint64_t bits = Random::MixBits(node->position.stone_hash() * Random::kLargePrime + inference_symmetry_mix_); return static_cast<symmetry::Symmetry>(bits % symmetry::kNumSymmetries); } bool SelfplayGame::MaybeQueueInference(MctsNode* leaf, InferenceCache* cache, std::vector<Inference>* inferences) { ModelOutput cached_output; auto inference_sym = GetInferenceSymmetry(leaf); auto cache_key = InferenceCache::Key(leaf->move, leaf->canonical_symmetry, leaf->position); if (cache->TryGet(cache_key, leaf->canonical_symmetry, inference_sym, &cached_output)) { tree_->IncorporateResults(leaf, cached_output.policy, cached_output.value); return false; } inferences->emplace_back(); auto& inference = inferences->back(); inference.cache_key = cache_key; inference.input.sym = inference_sym; inference.leaf = leaf; // TODO(tommadams): add a method to FeatureDescriptor that returns the // required position history size. auto* node = leaf; for (int i = 0; i < inference.input.position_history.capacity(); ++i) { inference.input.position_history.push_back(&node->position); node = node->parent; if (node == nullptr) { break; } } tree_->AddVirtualLoss(leaf); return true; } void Selfplayer::Run() { // Create the inference cache. std::shared_ptr<InferenceCache> inference_cache; if (FLAGS_cache_size_mb > 0) { auto capacity = BasicInferenceCache::CalculateCapacity(FLAGS_cache_size_mb); MG_LOG(INFO) << "Will cache up to " << capacity << " inferences, using roughly " << FLAGS_cache_size_mb << "MB.\n"; inference_cache = std::make_shared<ThreadSafeInferenceCache>( capacity, FLAGS_cache_shards); } else { inference_cache = std::make_shared<NullInferenceCache>(); } if (FLAGS_run_forever) { // Note that we don't ever have to worry about joining this thread because // it's only ever created when selfplay runs forever and when it comes time // to terminate the process, CheckAbortFile will call abort(). abort_file_watcher_ = absl::make_unique<PollThread>( "AbortWatcher", absl::Seconds(5), std::bind(&Selfplayer::CheckAbortFile, this)); abort_file_watcher_->Start(); } // Load the models. auto feature_descriptor = InitializeModels(); // Initialize the selfplay threads. std::vector<std::unique_ptr<SelfplayThread>> selfplay_threads; { absl::MutexLock lock(&mutex_); selfplay_threads.reserve(FLAGS_selfplay_threads); for (int i = 0; i < FLAGS_selfplay_threads; ++i) { selfplay_threads.push_back( absl::make_unique<SelfplayThread>(i, this, inference_cache)); } } // Start the output threads. std::vector<std::unique_ptr<OutputThread>> output_threads; output_threads.reserve(FLAGS_output_threads); for (int i = 0; i < FLAGS_output_threads; ++i) { output_threads.push_back( absl::make_unique<OutputThread>(i, feature_descriptor, &output_queue_)); } for (auto& t : output_threads) { t->Start(); } #ifdef WTF_ENABLE // Save WTF in the background periodically. wtf_saver_ = absl::make_unique<WtfSaver>(FLAGS_wtf_trace, absl::Seconds(5)); #endif // WTF_ENABLE // Run the selfplay threads. for (auto& t : selfplay_threads) { t->Start(); } for (auto& t : selfplay_threads) { t->Join(); } // Stop the output threads by pushing one null game onto the output queue // for each thread, causing the treads to exit when the pop them off. for (size_t i = 0; i < output_threads.size(); ++i) { output_queue_.Push(nullptr); } for (auto& t : output_threads) { t->Join(); } MG_CHECK(output_queue_.empty()); if (FLAGS_cache_size_mb > 0) { MG_LOG(INFO) << "Inference cache stats: " << inference_cache->GetStats(); } { absl::MutexLock lock(&mutex_); MG_LOG(INFO) << FormatWinStatsTable({{latest_model_name_, win_stats_}}); } } std::unique_ptr<SelfplayGame> Selfplayer::StartNewGame(bool verbose) { WTF_SCOPE0("StartNewGame"); Game::Options game_options; MctsTree::Options tree_options; SelfplayGame::Options selfplay_options; std::string player_name; int game_id; { absl::MutexLock lock(&mutex_); if (!FLAGS_run_forever && num_games_remaining_ == 0) { return nullptr; } if (!FLAGS_run_forever) { num_games_remaining_ -= 1; } player_name = latest_model_name_; game_id = next_game_id_++; game_options.resign_threshold = -rnd_.Uniform(std::fabs(FLAGS_min_resign_threshold), std::fabs(FLAGS_max_resign_threshold)); game_options.resign_enabled = rnd_() >= FLAGS_disable_resign_pct; tree_options = tree_options_; selfplay_options.num_virtual_losses = FLAGS_virtual_losses; selfplay_options.num_readouts = FLAGS_num_readouts; selfplay_options.fastplay_readouts = FLAGS_fastplay_readouts; selfplay_options.fastplay_frequency = FLAGS_fastplay_frequency; selfplay_options.noise_mix = FLAGS_noise_mix; selfplay_options.dirichlet_alpha = FLAGS_dirichlet_alpha; selfplay_options.is_holdout = rnd_() < FLAGS_holdout_pct; selfplay_options.target_pruning = FLAGS_target_pruning; selfplay_options.verbose = verbose; selfplay_options.allow_pass = FLAGS_allow_pass; selfplay_options.restrict_pass_alive_play_threshold = FLAGS_restrict_pass_alive_play_threshold; } auto game = absl::make_unique<Game>(player_name, player_name, game_options); auto tree = absl::make_unique<MctsTree>(Position(Color::kBlack), tree_options); return absl::make_unique<SelfplayGame>(game_id, selfplay_options, std::move(game), std::move(tree)); } void Selfplayer::EndGame(std::unique_ptr<SelfplayGame> selfplay_game) { { absl::MutexLock lock(&mutex_); win_stats_.Update(*selfplay_game->game()); } output_queue_.Push(std::move(selfplay_game)); } void Selfplayer::ExecuteSharded(std::function<void(int, int)> fn) { executor_.Execute(std::move(fn)); } std::unique_ptr<Model> Selfplayer::AcquireModel() { return models_.Pop(); } void Selfplayer::ReleaseModel(std::unique_ptr<Model> model) { if (model->name() == latest_model_name_) { models_.Push(std::move(model)); } } void Selfplayer::ParseFlags() { // Check that exactly one of (run_forever and num_games) is set. if (FLAGS_run_forever) { MG_CHECK(FLAGS_num_games == 0) << "num_games must not be set if run_forever is true"; } else { MG_CHECK(FLAGS_num_games > 0) << "num_games must be set if run_forever is false"; } MG_CHECK(!FLAGS_model.empty()); // Clamp num_concurrent_games_per_thread to avoid a situation where a single // thread ends up playing considerably more games than the others. if (!FLAGS_run_forever) { auto max_concurrent_games_per_thread = (FLAGS_num_games + FLAGS_selfplay_threads - 1) / FLAGS_selfplay_threads; FLAGS_concurrent_games_per_thread = std::min( max_concurrent_games_per_thread, FLAGS_concurrent_games_per_thread); } tree_options_.value_init_penalty = FLAGS_value_init_penalty; tree_options_.policy_softmax_temp = FLAGS_policy_softmax_temp; tree_options_.soft_pick_enabled = true; num_games_remaining_ = FLAGS_num_games; } FeatureDescriptor Selfplayer::InitializeModels() { if (FLAGS_model.find("%d") != std::string::npos) { using namespace std::placeholders; // NOLINT directory_watcher_ = absl::make_unique<DirectoryWatcher>( FLAGS_model, absl::Seconds(5), std::bind(&Selfplayer::CreateModels, this, _1)); MG_LOG(INFO) << "Waiting for model to match pattern " << FLAGS_model; } else { CreateModels(FLAGS_model); } // Get the feature descriptor from the first model loaded. // TODO(tommadams): instead of this, specify the model features explicitly on // the command line and pass them in to ModelFactory::NewModel, checking that // the models input shape matches the expected number of features. auto model = models_.Pop(); auto feature_descriptor = model->feature_descriptor(); models_.Push(std::move(model)); return feature_descriptor; } void Selfplayer::CreateModels(const std::string& path) { MG_LOG(INFO) << "Loading model " << path; ModelDefinition def; auto* env = tensorflow::Env::Default(); if (FLAGS_model.find("saved_model.pb") != std::string::npos) { while (!env->FileExists(path + ".minigo").ok()) { absl::SleepFor(absl::Milliseconds(10)); } def = LoadModelDefinition(path + ".minigo"); } else { def = LoadModelDefinition(path); } auto* factory = GetModelFactory(def, FLAGS_device); auto model = factory->NewModel(def); { absl::MutexLock lock(&mutex_); latest_model_name_ = model->name(); } models_.Push(std::move(model)); for (int i = 1; i < FLAGS_parallel_inference; ++i) { models_.Push(factory->NewModel(def)); } } void Selfplayer::CheckAbortFile() { if (file::FileExists(FLAGS_abort_file)) { LOG(INFO) << "Exiting because " << FLAGS_abort_file << " was found"; std::exit(0); } } SelfplayThread::SelfplayThread(int thread_id, Selfplayer* selfplayer, std::shared_ptr<InferenceCache> cache) : Thread(absl::StrCat("Selfplay:", thread_id)), selfplayer_(selfplayer), cache_(std::move(cache)), thread_id_(thread_id) { selfplay_games_.resize(FLAGS_concurrent_games_per_thread); } void SelfplayThread::Run() { WTF_THREAD_ENABLE("SelfplayThread"); searches_.resize(FLAGS_parallel_search); while (!selfplay_games_.empty()) { StartNewGames(); SelectLeaves(); auto model_name = RunInferences(); ProcessInferences(model_name); PlayMoves(); } MG_LOG(INFO) << "SelfplayThread " << thread_id_ << " played " << num_games_finished_ << " games"; } void SelfplayThread::StartNewGames() { WTF_SCOPE0("StartNewGames"); for (size_t i = 0; i < selfplay_games_.size();) { if (selfplay_games_[i] == nullptr) { // The i'th element is null, either start a new game, or remove the // element from the `selfplay_games_` array. bool verbose = FLAGS_verbose && thread_id_ == 0 && i == 0; auto selfplay_game = selfplayer_->StartNewGame(verbose); if (selfplay_game == nullptr) { // There are no more games to play remove the empty i'th slot from the // array. To do this without having to shuffle all the elements down, // we move the last element into position i and pop off the back. After // doing this, go round the loop again without incrementing i (otherwise // we'd skip over the newly moved element). selfplay_games_[i] = std::move(selfplay_games_.back()); selfplay_games_.pop_back(); continue; } else { selfplay_games_[i] = std::move(selfplay_game); } } // We didn't remove an element from the array, iterate as normal. i += 1; } } void SelfplayThread::SelectLeaves() { WTF_SCOPE("SelectLeaves: games", size_t)(selfplay_games_.size()); std::atomic<size_t> game_idx(0); selfplayer_->ExecuteSharded([this, &game_idx](int shard_idx, int num_shards) { WTF_SCOPE0("SelectLeaf"); MG_CHECK(static_cast<size_t>(num_shards) == searches_.size()); SelfplayGame::SelectLeavesStats total_stats; auto& search = searches_[shard_idx]; search.Clear(); for (;;) { auto i = game_idx.fetch_add(1); if (i >= selfplay_games_.size()) { break; } TreeSearch::InferenceSpan span; span.selfplay_game = selfplay_games_[i].get(); span.pos = search.inferences.size(); auto stats = span.selfplay_game->SelectLeaves(cache_.get(), &search.inferences); span.len = stats.num_leaves_queued; if (span.len > 0) { search.inference_spans.push_back(span); } total_stats += stats; } WTF_APPEND_SCOPE("leaves, nodes, cache_hits, game_over", int, int, int, int) (total_stats.num_leaves_queued, total_stats.num_nodes_selected, total_stats.num_cache_hits, total_stats.num_game_over_leaves); }); } std::string SelfplayThread::RunInferences() { WTF_SCOPE0("RunInferences"); // TODO(tommadams): stop allocating theses temporary vectors. std::vector<const ModelInput*> input_ptrs; std::vector<ModelOutput*> output_ptrs; for (auto& s : searches_) { for (auto& x : s.inferences) { input_ptrs.push_back(&x.input); output_ptrs.push_back(&x.output); } } if (input_ptrs.empty()) { return {}; } std::string model_name; auto model = selfplayer_->AcquireModel(); model->RunMany(input_ptrs, &output_ptrs, nullptr); model_name = model->name(); selfplayer_->ReleaseModel(std::move(model)); return model_name; } void SelfplayThread::ProcessInferences(const std::string& model_name) { { WTF_SCOPE0("UpdateCache"); for (auto& s : searches_) { for (auto& inference : s.inferences) { cache_->Merge(inference.cache_key, inference.leaf->canonical_symmetry, inference.input.sym, &inference.output); } } } { WTF_SCOPE0("ProcessInferences"); for (auto& s : searches_) { for (const auto& span : s.inference_spans) { span.selfplay_game->ProcessInferences( model_name, absl::MakeSpan(s.inferences).subspan(span.pos, span.len)); } } } } void SelfplayThread::PlayMoves() { WTF_SCOPE0("PlayMoves"); for (auto& selfplay_game : selfplay_games_) { if (!selfplay_game->MaybePlayMove()) { continue; } if (selfplay_game->options().verbose && FLAGS_cache_size_mb > 0) { MG_LOG(INFO) << "Inference cache stats: " << cache_->GetStats(); } if (selfplay_game->game()->game_over()) { selfplayer_->EndGame(std::move(selfplay_game)); num_games_finished_ += 1; selfplay_game = nullptr; } } } OutputThread::OutputThread( int thread_id, FeatureDescriptor feature_descriptor, ThreadSafeQueue<std::unique_ptr<SelfplayGame>>* output_queue) : Thread(absl::StrCat("Output:", thread_id)), output_queue_(output_queue), output_dir_(FLAGS_output_dir), holdout_dir_(FLAGS_holdout_dir), sgf_dir_(FLAGS_sgf_dir), feature_descriptor_(std::move(feature_descriptor)) {} void OutputThread::Run() { for (;;) { auto selfplay_game = output_queue_->Pop(); if (selfplay_game == nullptr) { break; } WriteOutputs(std::move(selfplay_game)); } } void OutputThread::WriteOutputs(std::unique_ptr<SelfplayGame> selfplay_game) { auto now = absl::Now(); auto output_name = GetOutputName(selfplay_game->game_id()); auto* game = selfplay_game->game(); if (FLAGS_verbose) { LogEndGameInfo(*game, selfplay_game->duration()); } // Take the player name from the last model used to play a move. This is // done because the ml_perf RL loop waits for a certain number of games to // be played by a model before training a new one. By assigned a game to // the last model used to play a move rather than the first, training waits // for less time and so we produce new models more quickly. const auto& models_used = selfplay_game->models_used(); const auto& player_name = !models_used.empty() ? models_used.back() : game->black_name(); if (!sgf_dir_.empty()) { WriteSgf(GetOutputDir(now, player_name, file::JoinPath(sgf_dir_, "clean")), output_name, *game, false); WriteSgf(GetOutputDir(now, player_name, file::JoinPath(sgf_dir_, "full")), output_name, *game, true); } const auto& example_dir = selfplay_game->options().is_holdout ? holdout_dir_ : output_dir_; if (!example_dir.empty()) { tf_utils::WriteGameExamples(GetOutputDir(now, player_name, example_dir), output_name, feature_descriptor_, *game); } } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/pool/bench_pool.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <float.h> #include <math.h> #include <sstream> #include "mkldnn.h" #include "mkldnn_common.hpp" #include "mkldnn_memory.hpp" #include "parser.hpp" #include "pool/pool.hpp" namespace pool { std::vector<dir_t> dir {FWD_D}; std::vector<const dt_conf_t *> cfg {conf_f32}; std::vector<mkldnn_format_tag_t> tag {mkldnn_nchw}; std::vector<alg_t> alg {MAX}; std::vector<int64_t> mb {0}; const char *skip_impl = ""; bool allow_unimpl = false; const char *perf_template_csv = "perf,%engine%,%name%,%dir%,%cfg%,%tag%,%alg%,%DESC%,%-time%,%0time%"; const char *perf_template_def = "perf,%engine%,%name%,%desc%,%-time%,%0time%"; const char *perf_template = perf_template_def; void reset_parameters() { dir = {FWD_D}; cfg = {conf_f32}; mb = {0}; tag = {mkldnn_nchw}; alg = {MAX}; skip_impl = ""; allow_unimpl = false; } void check_correctness(const desc_t *c) { for (const auto &i_dir: dir) for (const auto &i_cfg: cfg) for (const auto &i_tag: tag) for (const auto &i_alg: alg) for (const auto &i_mb: mb) { const prb_t p(*c, i_dir, i_cfg, i_tag, i_alg, i_mb); std::stringstream ss; ss << p; const std::string cpp_pstr = ss.str(); const char *pstr = cpp_pstr.c_str(); print(1, "run: %s\n", pstr); res_t res{}; const int status = doit(&p, &res); bool want_perf_report = false; parse_result(res, want_perf_report, allow_unimpl, status, pstr); if (want_perf_report && bench_mode & PERF) { perf_report_t pr(perf_template); pr.report(&p, &res, pstr); } benchdnn_stat.tests++; } } int bench(int argc, char **argv) { using namespace parser; for (; argc > 0; --argc, ++argv) { if (parse_bench_settings(argv[0])); else if (parse_batch(bench, argv[0])); else if (parse_tag(tag, argv[0])); else if (parse_mb(mb, argv[0])); else if (parse_dir(dir, argv[0])); else if (parse_vector_option(cfg, str2cfg, argv[0], "cfg")); else if (parse_vector_option(alg, str2alg, argv[0], "alg")); else if (parse_skip_impl(skip_impl, argv[0])); else if (parse_allow_unimpl(allow_unimpl, argv[0])); else if (parse_perf_template(perf_template, perf_template_def, perf_template_csv, argv[0])); else if (parse_reset(reset_parameters, argv[0])); else { catch_unknown_options(argv[0], "pool"); desc_t c; SAFE_V(str2desc(&c, argv[0])); check_correctness(&c); } } return parse_last_argument(); } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/ml_perf/watcher_and_sampler.cc<|end_filename|> #include <filesystem> #include <fstream> #include <ostream> #include <string> #include <utility> #include <vector> #include "REDACTEDflags/flag.h" #include "REDACTEDflags/marshalling.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/poll_thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/sample_records.h" #include "third_party/tensorflow/core/lib/io/path.h" #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/platform/file_system.h" ABSL_FLAG(int32_t, num_games, 4096, "Number of games to wait for."); ABSL_FLAG(int32_t, window_size, 5, "Maximum number of recent selfplay rounds to train on."); ABSL_FLAG(int32_t, iterations, 43, "number of rl_loop iterations to run."); ABSL_FLAG(std::string, golden_chunk_dir, "", "Training example directory."); ABSL_FLAG(std::string, selfplay_dir, "", "Path to selfplay_dir."); ABSL_FLAG(double, train_filter, 0.3, "Fraction of selfplay games to pass to training."); namespace minigo { namespace fs = std::filesystem; std::vector<std::string> ListSelfplayDirs(std::string path) { std::vector<std::string> matched_entries; TF_CHECK_OK(tensorflow::Env::Default()->GetChildren(path, &matched_entries)); std::sort(matched_entries.begin(), matched_entries.end(), std::greater<std::string>()); return matched_entries; } void WaitForTrainingExamples(int model_num, int num_games, std::string selfplay_dir) { bool first_time_around = true; std::string selfplay_model_name = absl::StrCat( std::string(6 - std::to_string(model_num).length(), '0'), model_num); fs::path selfplay_model_dir = fs::path(selfplay_dir) / selfplay_model_name; fs::path pattern = selfplay_model_dir / "*/*/*.tfrecord.zz"; std::vector<std::string> matched_output_files; int counter = 0; while (true) { counter += 1; if (first_time_around) { LOG(INFO) << "Waiting for " << num_games << " games in " << selfplay_model_dir; LOG(INFO) << "Pattern as: " << pattern; first_time_around = false; } auto* env = tensorflow::Env::Default(); if (env->FileExists(selfplay_model_dir).ok()) { TF_CHECK_OK(tensorflow::Env::Default()->GetMatchingPaths( pattern, &matched_output_files)); if (matched_output_files.size() >= absl::GetFlag(FLAGS_num_games)) { break; } } if ((counter % 100) == 0) { LOG(INFO) << " Waiting for " + std::to_string(num_games) + " games in " << selfplay_model_dir << ". Found " << std::to_string(matched_output_files.size()); } absl::SleepFor(absl::Milliseconds(50)); } LOG(INFO) << "Done waiting. "; } void SampleTrainingExamples(std::string selfplay_dir, int window_size, std::string golden_chunk_dir, int num_games, double train_filter, int files_per_pattern) { // Set flags for sample_records.cc absl::SetFlag(&FLAGS_num_read_threads, 16); absl::SetFlag(&FLAGS_num_write_threads, 16); absl::SetFlag(&FLAGS_sample_frac, train_filter); absl::SetFlag(&FLAGS_seed, 0); absl::SetFlag(&FLAGS_shuffle, true); absl::SetFlag(&FLAGS_compression, 1); std::vector<std::string> selfplay_model_names = ListSelfplayDirs(selfplay_dir); if (window_size > selfplay_model_names.size()) { window_size = selfplay_model_names.size(); } selfplay_model_names.resize(window_size); std::vector<std::string> src_patterns; src_patterns.reserve(window_size); for (const std::string& model_name : selfplay_model_names) { src_patterns.push_back( (fs::path(tensorflow::io::JoinPath(selfplay_dir, model_name))) / "*/*/*.tfrecord.zz"); } int train_model_num = std::stoi(selfplay_model_names[0]) + 1; std::string train_model_name = absl::StrCat( std::string(6 - std::to_string(train_model_num).length(), '0'), train_model_num); std::vector<std::string> src_paths; int num_src_patterns = src_patterns.size(); LOG(INFO) << "num_src_patterns is: " << num_src_patterns; for (int i = 0; i < num_src_patterns; ++i) { const auto& pattern = src_patterns[i]; std::vector<std::string> paths; TF_CHECK_OK(tensorflow::Env::Default()->GetMatchingPaths(pattern, &paths)); LOG(INFO) << pattern << " matched " << paths.size() << " files"; if (files_per_pattern > 0) { MG_CHECK(static_cast<int>(paths.size()) >= files_per_pattern) << "require " << files_per_pattern << " files per pattern, " << pattern << " matched only " << paths.size(); minigo::Random rnd(absl::GetFlag(FLAGS_seed), minigo::Random::kUniqueStream); rnd.Shuffle(&paths); paths.resize(files_per_pattern); } for (auto& path : paths) { src_paths.push_back(std::move(path)); } } std::string chunk_file_name = "{" + train_model_name + "}.tfrecord.zz"; // std::string dst_path = tensorflow::io::JoinPath(golden_chunk_dir, chunk_file_name); // absl::SetFlag(&FLAGS_dst, dst_path); size_t num_records = minigo::Run(src_paths, FLAGS_dst); // Now, gather chunk_paths and num_examples info std::string chunk_pattern = fs::path(golden_chunk_dir) / absl::StrCat("{", train_model_name, "}-*-of-*.tfrecord.zz"); std::vector<std::string> chunk_paths; TF_CHECK_OK(tensorflow::Env::Default()->GetMatchingPaths(chunk_pattern, &chunk_paths)); std::sort(chunk_paths.begin(), chunk_paths.end()); QCHECK_EQ(chunk_paths.size(), absl::GetFlag(FLAGS_num_write_threads)); chunk_paths.push_back(std::to_string(num_records)); // Write to golden_chunk_list.txt std::string file_name = fs::path(golden_chunk_dir) / absl::StrCat(train_model_name, "-golden_chunk_list.txt"); tensorflow::Status status; std::unique_ptr<tensorflow::WritableFile> file; status = tensorflow::Env::Default()->NewWritableFile(file_name, &file); if (!status.ok()) { LOG(ERROR) << "error opening " << file_name << " for write: " << status; } std::string concat_tfrecords; for (const auto& piece : chunk_paths) { concat_tfrecords += (piece + '\n'); } status = file->Append({concat_tfrecords.data(), concat_tfrecords.size()}); if (!status.ok()) { LOG(ERROR) << "error writing to " << file_name << ": " << status; } status = file->Close(); if (!status.ok()) { LOG(ERROR) << "error closing " << file_name << ": " << status; } } } // namespace minigo int main(int argc, char* argv[]) { minigo::Init(&argc, &argv); // List model dirs under selfplay dir in reverse order std::vector<std::string> model_names = minigo::ListSelfplayDirs(absl::GetFlag(FLAGS_selfplay_dir)); if (model_names.empty()) { LOG(ERROR) << "Watcher couldn\'t find any selfplay games under " << absl::GetFlag(FLAGS_selfplay_dir) << "Either bootstrap.sh or " << "init_from_checkpoint.sh must be run before the train loop is" << "started"; } int model_num = std::stoi(model_names[0]); while (model_num < absl::GetFlag(FLAGS_iterations)) { minigo::WaitForTrainingExamples(model_num, absl::GetFlag(FLAGS_num_games), absl::GetFlag(FLAGS_selfplay_dir)); minigo::SampleTrainingExamples( absl::GetFlag(FLAGS_selfplay_dir), absl::GetFlag(FLAGS_window_size), absl::GetFlag(FLAGS_golden_chunk_dir), absl::GetFlag(FLAGS_num_games), absl::GetFlag(FLAGS_train_filter), absl::GetFlag(FLAGS_num_games)); ++model_num; } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/bf16/jit_avx512_core_s16_copy_an_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_s16.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx512_core_s16_copy_an_kern::jit_avx512_core_s16_copy_an_kern() : jit_generator(nullptr, S16_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rax #define B rdi #define I rax #define A1 rsi #define A2 r10 #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l1e8; Xbyak::Label l24; Xbyak::Label l2c8; Xbyak::Label l2fc; Xbyak::Label l30c; Xbyak::Label l318; Xbyak::Label l32c; Xbyak::Label l38; Xbyak::Label l44c; Xbyak::Label l4e8; Xbyak::Label l510; Xbyak::Label l520; Xbyak::Label l52c; Xbyak::Label l540; Xbyak::Label l5dc; Xbyak::Label l630; Xbyak::Label l658; Xbyak::Label l668; Xbyak::Label l674; Xbyak::Label l688; Xbyak::Label l730; Xbyak::Label l78c; Xbyak::Label l7c0; Xbyak::Label l7dc; Xbyak::Label l7ec; Xbyak::Label l7f8; Xbyak::Label l808; Xbyak::Label l884; Xbyak::Label l8cc; Xbyak::Label l8f8; Xbyak::Label l914; Xbyak::Label l924; Xbyak::Label l930; Xbyak::Label l940; Xbyak::Label l9b8; Xbyak::Label l9fc; Xbyak::Label la28; Xbyak::Label la44; Xbyak::Label la52; Xbyak::Label la5c; Xbyak::Label la6c; Xbyak::Label lae4; Xbyak::Label lb2c; Xbyak::Label lb5c; Xbyak::Label lb74; Xbyak::Label lb84; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); shl(LDA, 1); lea(LDA3, ptr[LDA+LDA*2]); sub(A, -128); sub(B, -128); cmp(N, 0x30); jl(l30c, T_NEAR); align(4); L(l24); mov(A1, A); add(A, 0x60); mov(I, M); sar(I, 0x2); jle(l1e8, T_NEAR); align(4); L(l38); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); vmovdqu(xmm0, xword[A1-0x40]); vmovdqu(xmm1, xword[A1+LDA*1-0x40]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B], ymm2); vmovdqu(xmm0, xword[A1-0x30]); vmovdqu(xmm1, xword[A1+LDA*1-0x30]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x20], ymm2); lea(A1, ptr[A1+LDA*2]); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x40], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x80], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0xa0], ymm2); vmovdqu(xmm0, xword[A1-0x40]); vmovdqu(xmm1, xword[A1+LDA*1-0x40]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0xc0], ymm2); vmovdqu(xmm0, xword[A1-0x30]); vmovdqu(xmm1, xword[A1+LDA*1-0x30]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0xe0], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -384); dec(I); jg(l38, T_NEAR); align(4); L(l1e8); test(M, 0x2); jle(l2c8, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); vmovdqu(xmm0, xword[A1-0x40]); vmovdqu(xmm1, xword[A1+LDA*1-0x40]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B], ymm2); vmovdqu(xmm0, xword[A1-0x30]); vmovdqu(xmm1, xword[A1+LDA*1-0x30]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x20], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -192); align(4); L(l2c8); test(M, 0x1); jle(l2fc, T_NEAR); vmovdqu(ymm0, yword[A1-0x80]); vmovdqu(ymm1, yword[A1-0x60]); vmovdqu(ymm2, yword[A1-0x40]); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm1); vmovdqu(yword[B-0x40], ymm2); sub(B, -96); align(4); L(l2fc); sub(N, 0x30); cmp(N, 0x30); jge(l24, T_NEAR); align(4); L(l30c); cmp(N, 0x20); jl(l520, T_NEAR); align(4); L(l318); mov(A1, A); add(A, 0x40); mov(I, M); sar(I, 0x2); jle(l44c, T_NEAR); align(4); L(l32c); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); lea(A1, ptr[A1+LDA*2]); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x20], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B+0x60], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -256); dec(I); jg(l32c, T_NEAR); align(4); L(l44c); test(M, 0x2); jle(l4e8, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x60]); vmovdqu(xmm1, xword[A1+LDA*1-0x60]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x50]); vmovdqu(xmm1, xword[A1+LDA*1-0x50]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -128); align(4); L(l4e8); test(M, 0x1); jle(l510, T_NEAR); vmovdqu(ymm0, yword[A1-0x80]); vmovdqu(ymm1, yword[A1-0x60]); add(A1, LDA); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm1); sub(B, -64); align(4); L(l510); sub(N, 0x20); cmp(N, 0x20); jge(l318, T_NEAR); align(4); L(l520); cmp(N, 0x10); jl(l668, T_NEAR); align(4); L(l52c); mov(A1, A); add(A, 0x20); mov(I, M); sar(I, 0x2); jle(l5dc, T_NEAR); align(4); L(l540); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); lea(A1, ptr[A1+LDA*2]); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x40], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x20], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -128); dec(I); jg(l540, T_NEAR); align(4); L(l5dc); test(M, 0x2); jle(l630, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1+LDA*1-0x80]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm2); vmovdqu(xmm0, xword[A1-0x70]); vmovdqu(xmm1, xword[A1+LDA*1-0x70]); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm2, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x60], ymm2); lea(A1, ptr[A1+LDA*2]); sub(B, -64); align(4); L(l630); test(M, 0x1); jle(l658, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xmm1, xword[A1-0x70]); vmovdqu(xword[B-0x80], xmm0); vmovdqu(xword[B-0x70], xmm1); sub(B, -32); align(4); L(l658); sub(N, 0x10); cmp(N, 0x10); jge(l52c, T_NEAR); align(4); L(l668); cmp(N, 0x8); jl(l7ec, T_NEAR); align(4); L(l674); mov(A1, A); add(A, 0x10); mov(I, M); sar(I, 0x3); jle(l730, T_NEAR); align(4); L(l688); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm2); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x40], ymm0); vmovdqu(yword[B-0x20], ymm2); sub(B, -128); dec(I); jg(l688, T_NEAR); align(4); L(l730); test(M, 0x4); jle(l78c, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm2, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm3, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm4, xmm0, xmm1); vpunpckhwd(xmm5, xmm0, xmm1); vperm2f128(ymm0, ymm4, ymm5, 0x20); vpunpcklwd(xmm4, xmm2, xmm3); vpunpckhwd(xmm5, xmm2, xmm3); vperm2f128(ymm2, ymm4, ymm5, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovdqu(yword[B-0x60], ymm2); sub(B, -64); align(4); L(l78c); test(M, 0x2); jle(l7c0, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); add(A1, LDA); vmovdqu(xmm1, xword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm2, xmm0, xmm1); vpunpckhwd(xmm3, xmm0, xmm1); vperm2f128(ymm0, ymm2, ymm3, 0x20); vmovdqu(yword[B-0x80], ymm0); sub(B, -32); align(4); L(l7c0); test(M, 0x1); jle(l7dc, T_NEAR); vmovdqu(xmm0, xword[A1-0x80]); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l7dc); sub(N, 0x8); cmp(N, 0x8); jge(l674, T_NEAR); align(4); L(l7ec); cmp(N, 0x4); jl(l924, T_NEAR); align(4); L(l7f8); mov(A1, A); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(l884, T_NEAR); align(4); L(l808); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vperm2f128(ymm0, ymm0, ymm2, 0x20); vmovdqu(yword[B-0x80], ymm0); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vperm2f128(ymm0, ymm0, ymm2, 0x20); vmovdqu(yword[B-0x60], ymm0); sub(B, -64); dec(I); jg(l808, T_NEAR); align(4); L(l884); test(M, 0x4); jle(l8cc, T_NEAR); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vmovq(xmm2, qword[A1-0x80]); add(A1, LDA); vmovq(xmm3, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vmovdqu(xword[B-0x80], xmm0); vmovdqu(xword[B-0x70], xmm2); sub(B, -32); align(4); L(l8cc); test(M, 0x2); jle(l8f8, T_NEAR); vmovq(xmm0, qword[A1-0x80]); add(A1, LDA); vmovq(xmm1, qword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l8f8); test(M, 0x1); jle(l914, T_NEAR); vmovq(xmm0, qword[A1-0x80]); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l914); sub(N, 0x4); cmp(N, 0x4); jge(l7f8, T_NEAR); align(4); L(l924); cmp(N, 0x2); jl(la52, T_NEAR); align(4); L(l930); mov(A1, A); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l9b8, T_NEAR); align(4); L(l940); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x70], xmm0); sub(B, -32); dec(I); jg(l940, T_NEAR); align(4); L(l9b8); test(M, 0x4); jle(l9fc, T_NEAR); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vmovd(xmm2, dword[A1-0x80]); add(A1, LDA); vmovd(xmm3, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vpunpcklwd(xmm2, xmm2, xmm3); vpunpcklqdq(xmm0, xmm0, xmm2); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l9fc); test(M, 0x2); jle(la28, T_NEAR); vmovd(xmm0, dword[A1-0x80]); add(A1, LDA); vmovd(xmm1, dword[A1-0x80]); add(A1, LDA); vpunpcklwd(xmm0, xmm0, xmm1); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(la28); test(M, 0x1); jle(la44, T_NEAR); vmovd(xmm0, dword[A1-0x80]); vmovd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(la44); sub(N, 0x2); cmp(N, 0x2); jge(l930, T_NEAR); align(4); L(la52); cmp(N, 0x1); jl(lb84, T_NEAR); align(4); L(la5c); mov(A1, A); add(A, 0x2); mov(LDA3, M); sar(LDA3, 0x3); jle(lae4, T_NEAR); align(4); L(la6c); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x3); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x4); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x5); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x6); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x7); vmovdqu(xword[B-0x80], xmm0); sub(B, -16); dec(LDA3); jg(la6c, T_NEAR); align(4); L(lae4); test(M, 0x4); jle(lb2c, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x2); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x3); vmovq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(lb2c); test(M, 0x2); jle(lb5c, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); vpinsrw(xmm0, xmm0, eax, 0x1); vmovd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(lb5c); test(M, 0x1); jle(lb74, T_NEAR); mov(ax, word[A1-0x80]); mov(word[B-0x80], ax); sub(B, -2); align(4); L(lb74); sub(N, 0x1); cmp(N, 0x1); jge(la5c, T_NEAR); align(4); L(lb84); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/engine/threaded_engine.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2015 by Contributors * \file threaded_engine.cc * \brief implements base threaded engine. * \author <NAME> */ #include <dmlc/logging.h> #include <cassert> #include <algorithm> #include <condition_variable> #include <mutex> #include <utility> #include "./threaded_engine.h" #include "../common/cuda_utils.h" #include "../common/nvtx.h" namespace mxnet { namespace engine { #if ENGINE_DEBUG std::atomic<std::size_t> OprBlock::counter{0}; std::atomic<std::size_t> VersionedVarBlock::counter{0}; std::atomic<std::size_t> ThreadedVar::counter{0}; std::atomic<std::size_t> ThreadedOpr::counter{0}; #endif // ENGINE_DEBUG ThreadedVar::ThreadedVar(VersionedVarBlock* head) : head_{head} { #if ENGINE_DEBUG LOG(INFO) << __func__ << " " << ++counter; #endif // ENGINE_DEBUG } inline void ThreadedVar::AppendReadDependency(OprBlock* opr_block) { std::lock_guard<std::mutex> lock{mutex_}; if (pending_write_ == nullptr) { // invariant: is_ready_to_read() CHECK_GE(num_pending_reads_, 0); // STATE CHANGE ++num_pending_reads_; // decrease wait counter opr_block->decr_wait(); } else { auto&& new_var_block = VersionedVarBlock::New(); assert(head_->next == nullptr); assert(head_->trigger == nullptr); assert(head_->write == false); // append things to next. head_->next = new_var_block; head_->trigger = opr_block; head_ = new_var_block; } } inline void ThreadedVar::AppendWriteDependency(OprBlock* opr_block) { auto&& new_var_block = VersionedVarBlock::New(); std::lock_guard<std::mutex> lock{mutex_}; // invariant. assert(head_->next == nullptr); assert(head_->trigger == nullptr); assert(head_->write == false); // attach to head. head_->next = new_var_block; head_->trigger = opr_block; head_->write = true; // check if it is ready to write if (pending_write_ == nullptr) { // invariant: is_ready_to_read() pending_write_ = head_; CHECK_GE(num_pending_reads_, 0); if (num_pending_reads_ == 0) { // STATE CHANGE opr_block->decr_wait(); num_pending_reads_ = kWriteTriggered; } } else { CHECK_NE(num_pending_reads_, 0); } head_ = new_var_block; } template <typename Dispatcher> inline void ThreadedVar::CompleteReadDependency(Dispatcher dispatcher) { OprBlock *trigger = nullptr; { // this is lock scope std::lock_guard<std::mutex> lock{mutex_}; CHECK_GT(num_pending_reads_, 0); if (--num_pending_reads_ == 0) { if (pending_write_ != nullptr) { // STATE CHANGE trigger = pending_write_->trigger; num_pending_reads_ = kWriteTriggered; } } } if (trigger != nullptr && trigger->decr_wait() == 0) { dispatcher(trigger); } } template <typename Dispatcher> inline bool ThreadedVar::CompleteWriteDependency(Dispatcher dispatcher) { // this is lock scope VersionedVarBlock *old_pending_write, *end_of_read_chain; OprBlock* trigger_write = nullptr; { std::lock_guard<std::mutex> lock{mutex_}; // invariants assert(head_->next == nullptr); assert(pending_write_ != nullptr); CHECK_EQ(num_pending_reads_, kWriteTriggered); // increment version number ++version_; // really delete if (to_delete_) { VersionedVarBlock *head = pending_write_->next; VersionedVarBlock::Delete(pending_write_); assert(head_ == head); VersionedVarBlock::Delete(head); return true; } // detach pending write old_pending_write = pending_write_; // search for chains to trigger end_of_read_chain = old_pending_write->next; // reset to 0 pending reads num_pending_reads_ = 0; while (end_of_read_chain != head_ && end_of_read_chain->write == false) { ++num_pending_reads_; end_of_read_chain = end_of_read_chain->next; } if (end_of_read_chain == head_) { pending_write_ = nullptr; } else { // check if there is pending reads, if not trigger write assert(end_of_read_chain->write == true); pending_write_ = end_of_read_chain; if (num_pending_reads_ == 0) { // mark write as already activated in this var num_pending_reads_ = kWriteTriggered; trigger_write = end_of_read_chain->trigger; } } } // This is outside of lock scope // Be very carful, pending_write_ and num_pending_reads_ // can change now, do not rely on these two variables. // The linked list \in [old_pending_write, end_of_read_chain) // is already detached from this Var. // So it is safe to modify these VersionedVarBlock *cur_head = old_pending_write->next; VersionedVarBlock::Delete(old_pending_write); // dispatch all the events while (cur_head != end_of_read_chain) { if (cur_head->trigger->decr_wait() == 0) { dispatcher(cur_head->trigger); } auto prev = cur_head; cur_head = cur_head->next; assert(cur_head != nullptr); VersionedVarBlock::Delete(prev); } if (trigger_write != nullptr && trigger_write->decr_wait() == 0) { dispatcher(trigger_write); } return false; } inline void ThreadedVar::SetToDelete() { std::lock_guard<std::mutex> lock{mutex_}; to_delete_ = true; } inline bool ThreadedVar::ready_to_read() { std::lock_guard<std::mutex> lock{mutex_}; return this->is_ready_to_read(); } inline size_t ThreadedVar::version() { std::lock_guard<std::mutex> lock{mutex_}; return this->version_; } // implementation of threaded engine ThreadedVar* ThreadedEngine::NewVariable() { return ThreadedVar::New(VersionedVarBlock::New()); } ThreadedOpr* ThreadedEngine::NewOperator( ThreadedEngine::AsyncFn fn, std::vector<VarHandle> const& const_vars, std::vector<VarHandle> const& mutable_vars, FnProperty prop, const char* opr_name, bool wait) { auto ret = ThreadedOpr::New(); ret->opr_name = opr_name; ret->fn = std::move(fn); ret->prop = prop; ret->const_vars.resize(const_vars.size()); ret->mutable_vars.resize(mutable_vars.size()); ret->wait = wait; std::transform(const_vars.begin(), const_vars.end(), ret->const_vars.begin(), ThreadedVar::CastFromBase); std::transform(mutable_vars.begin(), mutable_vars.end(), ret->mutable_vars.begin(), ThreadedVar::CastFromBase); if (ENGINE_DEBUG != 0) { CheckDuplicate(const_vars, mutable_vars); } return ret; } void ThreadedEngine::CheckDuplicate(std::vector<VarHandle> const& const_vars, std::vector<VarHandle> const& mutable_vars) { // Check for duplicates. auto use = const_vars; auto mutate = mutable_vars; const size_t use_size = use.size(); const size_t mutate_size = mutate.size(); std::sort(use.begin(), use.end()); std::sort(mutate.begin(), mutate.end()); for (std::size_t i = 0; i < use_size; ++i) { if (i != 0 && use.at(i) == use.at(i - 1)) { LOG(FATAL) << "duplicate items found in `const_vars`"; } } for (std::size_t i = 0; i < mutate_size; ++i) { if (i != 0 && mutate.at(i) == mutate.at(i - 1)) { LOG(FATAL) << "duplicate items found in `mutable_vars`"; } } std::size_t j = 0; for (std::size_t i = 0; i < use_size; ++i) { while (j < mutate_size && mutate.at(j) < use.at(i)) { ++j; } if (j == mutate_size) { break; } if (mutate.at(j) == use.at(i)) { LOG(FATAL) << "duplicate items found between `const_vars` and `mutable_vars`"; } } } void ThreadedEngine::DeleteOperator(OprHandle op) { ThreadedOpr* threaded_opr = ThreadedOpr::CastFromBase(op); std::vector<VarHandle> deps; deps.reserve(threaded_opr->const_vars.size() + threaded_opr->mutable_vars.size()); deps.insert(deps.end(), threaded_opr->const_vars.begin(), threaded_opr->const_vars.end()); deps.insert(deps.end(), threaded_opr->mutable_vars.begin(), threaded_opr->mutable_vars.end()); this->PushAsync([threaded_opr](RunContext, CallbackOnComplete on_complete) { ThreadedOpr::Delete(threaded_opr); on_complete(); }, Context::CPU(), {}, deps, FnProperty::kDeleteVar, 0, "DeleteOperator"); } void ThreadedEngine::Push(OprHandle op, Context exec_ctx, int priority, bool profiling) { BulkFlush(); ThreadedOpr* threaded_opr = ThreadedOpr::CastFromBase(op); if (profiling) { threaded_opr->opr_name = profiler::CustomOpProfiler::Get()->GenerateDisplayName(threaded_opr->opr_name); } OprBlock* opr_block = OprBlock::New(); opr_block->opr = threaded_opr; opr_block->wait.store(static_cast<int>( threaded_opr->const_vars.size() + threaded_opr->mutable_vars.size() + 1)); opr_block->ctx = exec_ctx; opr_block->priority = priority; opr_block->profiling = profiling; ++pending_; // Add read dependencies. for (auto&& i : threaded_opr->const_vars) { i->AppendReadDependency(opr_block); } // Add write dependencies. for (auto&& i : threaded_opr->mutable_vars) { i->AppendWriteDependency(opr_block); } if (opr_block->decr_wait() == 0) { this->PushToExecute(opr_block, true); } } void ThreadedEngine::PushAsync(AsyncFn fn, Context exec_ctx, std::vector<VarHandle> const& const_vars, std::vector<VarHandle> const& mutable_vars, FnProperty prop, int priority, const char* opr_name, bool wait) { #if MXNET_USE_CUDA if (exec_ctx.dev_mask() == gpu::kDevMask) { if (device_count_ < 0) { int tmp = -1; cudaGetDeviceCount(&tmp); device_count_ = tmp; CHECK_GT(device_count_, 0) << "GPU usage requires at least 1 GPU"; } CHECK_LT(exec_ctx.dev_id, device_count_) << "Invalid GPU Id: " << exec_ctx.dev_id << ", Valid device id should be less than device_count: " << device_count_; } #endif const bool profiling = profiler_->IsProfiling(profiler::Profiler::kImperative); ThreadedOpr *opr = NewOperator(std::move(fn), const_vars, mutable_vars, prop, opr_name, wait); opr->temporary = true; Push(opr, exec_ctx, priority, profiling); } void ThreadedEngine::PushSync(SyncFn exec_fn, Context exec_ctx, std::vector<VarHandle> const& const_vars, std::vector<VarHandle> const& mutable_vars, FnProperty prop, int priority, const char* opr_name) { if (!bulk_size() || prop != FnProperty::kNormal || priority) { this->PushAsync([exec_fn](RunContext ctx, CallbackOnComplete on_complete) { exec_fn(ctx); on_complete(); }, exec_ctx, const_vars, mutable_vars, prop, priority, opr_name); return; } const BulkStatus& bulk_status = *BulkStatusStore::Get(); if (bulk_status.count && exec_ctx != bulk_status.ctx) BulkFlush(); BulkAppend(exec_fn, exec_ctx, const_vars, mutable_vars, opr_name); } void ThreadedEngine::DeleteVariable(SyncFn delete_fn, Context exec_ctx, VarHandle var) { ThreadedVar* threaded_var = ThreadedVar::CastFromBase(var); this->PushAsync([delete_fn, threaded_var](RunContext ctx, CallbackOnComplete on_complete) { // Mark variable as orphan, // so during `ThreadedEngine::OnComplete` it could be recycled. threaded_var->SetToDelete(); delete_fn(ctx); on_complete(); }, exec_ctx, {}, {var}, FnProperty::kDeleteVar, 0, "DeleteVariable"); } void ThreadedEngine::WaitForVar(VarHandle var) { BulkFlush(); ThreadedVar* threaded_var = ThreadedVar::CastFromBase(var); if (threaded_var->ready_to_read()) { ThrowException(threaded_var); return; } if (engine_info_) { LOG(INFO) << "Wait for " << threaded_var; debug_wait_var_ = threaded_var; } std::atomic<bool> done{false}; this->PushAsync([this, &done](RunContext, CallbackOnComplete on_complete) { if (engine_info_) { LOG(INFO) << "Sync is executed"; } { std::unique_lock<std::mutex> lock{finished_m_}; done.store(true); } finished_cv_.notify_all(); if (engine_info_) { LOG(INFO) << "Sync is notified"; } on_complete(); }, Context::CPU(), {var}, {}, FnProperty::kNormal, 0, "WaitForVar", true); { std::unique_lock<std::mutex> lock{finished_m_}; finished_cv_.wait(lock, [this, &done]() { return done.load() || kill_.load(); }); } ThrowException(threaded_var); } void ThreadedEngine::WaitForAll() { BulkFlush(); std::unique_lock<std::mutex> lock{finished_m_}; finished_cv_.wait(lock, [this]() { return pending_.load() == 0 || kill_.load(); }); std::exception_ptr exception_to_rethrow = nullptr; if (!global_exception_refs_.empty()) { // iterate through all exception refs for (const auto& global_exception_ref : global_exception_refs_) { // the first exception will be saved to be rethrown later if (*global_exception_ref != nullptr && exception_to_rethrow == nullptr) { exception_to_rethrow = *global_exception_ref; } // clear exceptions, WaitToRead following WaitForAll shouldn't throw *global_exception_ref = nullptr; } // A waitall following a waitall shouldn't throw any exceptions global_exception_refs_.clear(); if (exception_to_rethrow != nullptr) { std::rethrow_exception(exception_to_rethrow); } } } inline void ThreadedEngine::OnComplete(ThreadedOpr* threaded_opr) { bool is_temporary_opr = threaded_opr->temporary; // Mark complete for read variables for (auto&& i : threaded_opr->const_vars) { i->CompleteReadDependency( [this](OprBlock* opr) { this->PushToExecute(opr, false); }); } // Mark complete for write variables. for (auto&& i : threaded_opr->mutable_vars) { if (threaded_opr->opr_exception && *threaded_opr->opr_exception) { i->var_exception = threaded_opr->opr_exception; // add current operator exceptions to global exceptions if not already // added AddToGlobalExceptions(threaded_opr->opr_exception); } const bool debug_info = (engine_info_ && debug_wait_var_ == i); if (debug_info) { LOG(INFO) << "Complete write dep for " << i; } const bool to_delete = i->CompleteWriteDependency([this, debug_info](OprBlock* opr) { if (debug_info) { LOG(INFO) << "PushToExecute " << opr; debug_push_opr_ = opr; } this->PushToExecute(opr, false); if (debug_info) { LOG(INFO) << "Fin PushToExecute " << opr; } }); if (to_delete) { ThreadedVar::Delete(i); } } // The function been pushed from `ThreadedEngine::DeleteOperator` // could execute right after we mark all vars as complete, so if // threaded_opr is not temporary, its value is not reliable // anymore start from here. int npending = 0; { std::unique_lock<std::mutex> lock{finished_m_}; npending = --pending_; } CHECK_GE(npending, 0); if (npending == 0) { // no need to grab lock when notify. finished_cv_.notify_all(); } // delete operator if it is temperory if (is_temporary_opr) { ThreadedOpr::Delete(threaded_opr); } } inline void ThreadedEngine::ThrowException(ThreadedVar* threaded_var) { if (threaded_var->var_exception && *threaded_var->var_exception) { std::exception_ptr tmp = *threaded_var->var_exception; *threaded_var->var_exception = nullptr; std::rethrow_exception(tmp); } return; } void ThreadedEngine::Throw(VarHandle var) { ThreadedVar *threaded_var = ThreadedVar::CastFromBase(var); ThrowException(threaded_var); } void ThreadedEngine::OnCompleteStatic(Engine *engine, void *opr_block_, const dmlc::Error* error) { OprBlock *opr_block = static_cast<OprBlock*>(opr_block_); ThreadedOpr *threaded_opr = opr_block->opr; if (error != nullptr) { auto ex_p = std::make_exception_ptr(*error); threaded_opr->opr_exception = std::make_shared<std::exception_ptr>(ex_p); } if (opr_block->profiling && threaded_opr->opr_name) { // record operator end timestamp opr_block->opr_profile->stop(); } static_cast<ThreadedEngine*>(engine)->OnComplete(threaded_opr); OprBlock::Delete(opr_block); } } // namespace engine } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_avx_f32_copy_an_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_f32.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx_f32_copy_an_kern::jit_avx_f32_copy_an_kern() : jit_generator(nullptr, F32_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rsi #define B rdi #define I rax #define A1 r10 #define A2 rsi #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l10cc; Xbyak::Label l116c; Xbyak::Label l11c0; Xbyak::Label l11f0; Xbyak::Label l1200; Xbyak::Label l1224; Xbyak::Label l12c4; Xbyak::Label l1318; Xbyak::Label l134c; Xbyak::Label l136c; Xbyak::Label l1370; Xbyak::Label l1394; Xbyak::Label l1430; Xbyak::Label l1484; Xbyak::Label l14b8; Xbyak::Label l14d8; Xbyak::Label l14dc; Xbyak::Label l1500; Xbyak::Label l159c; Xbyak::Label l15f0; Xbyak::Label l1624; Xbyak::Label l1644; Xbyak::Label l1648; Xbyak::Label l166c; Xbyak::Label l168; Xbyak::Label l1708; Xbyak::Label l175c; Xbyak::Label l1790; Xbyak::Label l17b0; Xbyak::Label l17b4; Xbyak::Label l1e4; Xbyak::Label l228; Xbyak::Label l250; Xbyak::Label l260; Xbyak::Label l280; Xbyak::Label l2fc; Xbyak::Label l340; Xbyak::Label l36c; Xbyak::Label l388; Xbyak::Label l38c; Xbyak::Label l3ac; Xbyak::Label l424; Xbyak::Label l468; Xbyak::Label l494; Xbyak::Label l4b0; Xbyak::Label l4b4; Xbyak::Label l4d4; Xbyak::Label l54; Xbyak::Label l54c; Xbyak::Label l590; Xbyak::Label l5bc; Xbyak::Label l5d8; Xbyak::Label l5dc; Xbyak::Label l5fc; Xbyak::Label l674; Xbyak::Label l6b8; Xbyak::Label l6c; Xbyak::Label l6e4; Xbyak::Label l700; Xbyak::Label l704; Xbyak::Label l70c; Xbyak::Label l728; Xbyak::Label l740; Xbyak::Label l87c; Xbyak::Label l91c; Xbyak::Label l970; Xbyak::Label l9a0; Xbyak::Label l9b0; Xbyak::Label l9d4; Xbyak::Label la74; Xbyak::Label lac8; Xbyak::Label lafc; Xbyak::Label lb1c; Xbyak::Label lb20; Xbyak::Label lb44; Xbyak::Label lbe0; Xbyak::Label lc34; Xbyak::Label lc68; Xbyak::Label lc88; Xbyak::Label lc8c; Xbyak::Label lcb0; Xbyak::Label ld4c; Xbyak::Label lda0; Xbyak::Label ldd4; Xbyak::Label ldf4; Xbyak::Label ldf8; Xbyak::Label le1c; Xbyak::Label leb8; Xbyak::Label lf0c; Xbyak::Label lf40; Xbyak::Label lf60; Xbyak::Label lf64; Xbyak::Label lf6c; Xbyak::Label lf78; Xbyak::Label lf90; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); sub(A, -128); sub(B, -128); shl(LDA, 0x2); lea(LDA3, ptr[LDA+LDA*2]); vbroadcastss(ymm6, dword[ALPHA]); vpcmpeqb(xmm3, xmm3, xmm3); vpsrld(xmm3, xmm3, 0x17); vpslld(xmm3, xmm3, 0x19); vpsrld(xmm3, xmm3, 0x2); vpcmpeqb(xmm4, xmm4, xmm4); vpslld(xmm4, xmm4, 0x1f); vperm2f128(ymm4, ymm4, ymm4, 0x20); vucomiss(xmm6, xmm3); jne(l70c, T_NEAR); cmp(N, 0x10); jl(l260, T_NEAR); align(4); L(l54); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x40); mov(I, M); sar(I, 0x3); jle(l168, T_NEAR); align(4); L(l6c); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x60]); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x60]); vmovups(yword[B+0x60], ymm0); vmovups(ymm0, yword[A2-0x80]); vmovups(yword[B+0x80], ymm0); vmovups(ymm0, yword[A2-0x60]); vmovups(yword[B+0xa0], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x80]); vmovups(yword[B+0xc0], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x60]); vmovups(yword[B+0xe0], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x80]); vmovups(yword[B+0x100], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x60]); vmovups(yword[B+0x120], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x80]); vmovups(yword[B+0x140], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x60]); vmovups(yword[B+0x160], ymm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -512); dec(I); jg(l6c, T_NEAR); align(4); L(l168); test(M, 0x4); jle(l1e4, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x60]); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x60]); vmovups(yword[B+0x60], ymm0); lea(A1, ptr[A1+LDA*4]); sub(B, -256); align(4); L(l1e4); test(M, 0x2); jle(l228, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vmovups(yword[B-0x20], ymm0); lea(A1, ptr[A1+LDA*2]); sub(B, -128); align(4); L(l228); test(M, 0x1); jle(l250, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmovups(yword[B-0x60], ymm0); sub(B, -64); align(4); L(l250); sub(N, 0x10); cmp(N, 0x10); jge(l54, T_NEAR); align(4); L(l260); cmp(N, 0x8); jl(l38c, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x20); mov(I, M); sar(I, 0x3); jle(l2fc, T_NEAR); align(4); L(l280); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A2-0x80]); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x80]); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x80]); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x80]); vmovups(yword[B+0x60], ymm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -256); dec(I); jg(l280, T_NEAR); align(4); L(l2fc); test(M, 0x4); jle(l340, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmovups(yword[B-0x20], ymm0); lea(A1, ptr[A1+LDA*4]); sub(B, -128); align(4); L(l340); test(M, 0x2); jle(l36c, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmovups(yword[B-0x60], ymm0); lea(A1, ptr[A1+LDA*2]); sub(B, -64); align(4); L(l36c); test(M, 0x1); jle(l388, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmovups(yword[B-0x80], ymm0); sub(B, -32); align(4); L(l388); sub(N, 0x8); align(4); L(l38c); cmp(N, 0x4); jl(l4b4, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x10); mov(I, M); sar(I, 0x3); jle(l424, T_NEAR); align(4); L(l3ac); vmovups(xmm0, xword[A1-0x80]); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vmovups(xword[B-0x70], xmm0); vmovups(xmm0, xword[A1+LDA*2-0x80]); vmovups(xword[B-0x60], xmm0); vmovups(xmm0, xword[A1+LDA3*1-0x80]); vmovups(xword[B-0x50], xmm0); vmovups(xmm0, xword[A2-0x80]); vmovups(xword[B-0x40], xmm0); vmovups(xmm0, xword[A2+LDA*1-0x80]); vmovups(xword[B-0x30], xmm0); vmovups(xmm0, xword[A2+LDA*2-0x80]); vmovups(xword[B-0x20], xmm0); vmovups(xmm0, xword[A2+LDA3*1-0x80]); vmovups(xword[B-0x10], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -128); dec(I); jg(l3ac, T_NEAR); align(4); L(l424); test(M, 0x4); jle(l468, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vmovups(xword[B-0x70], xmm0); vmovups(xmm0, xword[A1+LDA*2-0x80]); vmovups(xword[B-0x60], xmm0); vmovups(xmm0, xword[A1+LDA3*1-0x80]); vmovups(xword[B-0x50], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -64); align(4); L(l468); test(M, 0x2); jle(l494, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vmovups(xword[B-0x70], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -32); align(4); L(l494); test(M, 0x1); jle(l4b0, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vmovups(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l4b0); sub(N, 0x4); align(4); L(l4b4); cmp(N, 0x2); jl(l5dc, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(l54c, T_NEAR); align(4); L(l4d4); vmovsd(xmm0, qword[A1-0x80]); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vmovlps(qword[B-0x78], xmm0); vmovsd(xmm0, qword[A1+LDA*2-0x80]); vmovlps(qword[B-0x70], xmm0); vmovsd(xmm0, qword[A1+LDA3*1-0x80]); vmovlps(qword[B-0x68], xmm0); vmovsd(xmm0, qword[A2-0x80]); vmovlps(qword[B-0x60], xmm0); vmovsd(xmm0, qword[A2+LDA*1-0x80]); vmovlps(qword[B-0x58], xmm0); vmovsd(xmm0, qword[A2+LDA*2-0x80]); vmovlps(qword[B-0x50], xmm0); vmovsd(xmm0, qword[A2+LDA3*1-0x80]); vmovlps(qword[B-0x48], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -64); dec(I); jg(l4d4, T_NEAR); align(4); L(l54c); test(M, 0x4); jle(l590, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vmovlps(qword[B-0x78], xmm0); vmovsd(xmm0, qword[A1+LDA*2-0x80]); vmovlps(qword[B-0x70], xmm0); vmovsd(xmm0, qword[A1+LDA3*1-0x80]); vmovlps(qword[B-0x68], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -32); align(4); L(l590); test(M, 0x2); jle(l5bc, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vmovlps(qword[B-0x78], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -16); align(4); L(l5bc); test(M, 0x1); jle(l5d8, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vmovlps(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l5d8); sub(N, 0x2); align(4); L(l5dc); cmp(N, 0x1); jl(l704, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l674, T_NEAR); align(4); L(l5fc); vmovss(xmm0, dword[A1-0x80]); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vmovss(dword[B-0x7c], xmm0); vmovss(xmm0, dword[A1+LDA*2-0x80]); vmovss(dword[B-0x78], xmm0); vmovss(xmm0, dword[A1+LDA3*1-0x80]); vmovss(dword[B-0x74], xmm0); vmovss(xmm0, dword[A2-0x80]); vmovss(dword[B-0x70], xmm0); vmovss(xmm0, dword[A2+LDA*1-0x80]); vmovss(dword[B-0x6c], xmm0); vmovss(xmm0, dword[A2+LDA*2-0x80]); vmovss(dword[B-0x68], xmm0); vmovss(xmm0, dword[A2+LDA3*1-0x80]); vmovss(dword[B-0x64], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -32); dec(I); jg(l5fc, T_NEAR); align(4); L(l674); test(M, 0x4); jle(l6b8, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vmovss(dword[B-0x7c], xmm0); vmovss(xmm0, dword[A1+LDA*2-0x80]); vmovss(dword[B-0x78], xmm0); vmovss(xmm0, dword[A1+LDA3*1-0x80]); vmovss(dword[B-0x74], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -16); align(4); L(l6b8); test(M, 0x2); jle(l6e4, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vmovss(dword[B-0x7c], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -8); align(4); L(l6e4); test(M, 0x1); jle(l700, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vmovss(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l700); sub(N, 0x1); align(4); L(l704); jmp(l17b4, T_NEAR); align(4); L(l70c); vxorps(xmm3, xmm3, xmm4); vucomiss(xmm6, xmm3); jne(lf6c, T_NEAR); vmovaps(ymm6, ymm4); cmp(N, 0x10); jl(l9b0, T_NEAR); align(4); L(l728); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x40); mov(I, M); sar(I, 0x3); jle(l87c, T_NEAR); align(4); L(l740); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x60], ymm0); vmovups(ymm0, yword[A2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x80], ymm0); vmovups(ymm0, yword[A2-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0xa0], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0xc0], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0xe0], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x100], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x120], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x140], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x160], ymm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -512); dec(I); jg(l740, T_NEAR); align(4); L(l87c); test(M, 0x4); jle(l91c, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x60], ymm0); lea(A1, ptr[A1+LDA*4]); sub(B, -256); align(4); L(l91c); test(M, 0x2); jle(l970, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); lea(A1, ptr[A1+LDA*2]); sub(B, -128); align(4); L(l970); test(M, 0x1); jle(l9a0, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); sub(B, -64); align(4); L(l9a0); sub(N, 0x10); cmp(N, 0x10); jge(l728, T_NEAR); align(4); L(l9b0); cmp(N, 0x8); jl(lb20, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x20); mov(I, M); sar(I, 0x3); jle(la74, T_NEAR); align(4); L(l9d4); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B+0x60], ymm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -256); dec(I); jg(l9d4, T_NEAR); align(4); L(la74); test(M, 0x4); jle(lac8, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); lea(A1, ptr[A1+LDA*4]); sub(B, -128); align(4); L(lac8); test(M, 0x2); jle(lafc, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); lea(A1, ptr[A1+LDA*2]); sub(B, -64); align(4); L(lafc); test(M, 0x1); jle(lb1c, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vxorps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); sub(B, -32); align(4); L(lb1c); sub(N, 0x8); align(4); L(lb20); cmp(N, 0x4); jl(lc8c, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x10); mov(I, M); sar(I, 0x3); jle(lbe0, T_NEAR); align(4); L(lb44); vmovups(xmm0, xword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x70], xmm0); vmovups(xmm0, xword[A1+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x60], xmm0); vmovups(xmm0, xword[A1+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x50], xmm0); vmovups(xmm0, xword[A2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x40], xmm0); vmovups(xmm0, xword[A2+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x30], xmm0); vmovups(xmm0, xword[A2+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x20], xmm0); vmovups(xmm0, xword[A2+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x10], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -128); dec(I); jg(lb44, T_NEAR); align(4); L(lbe0); test(M, 0x4); jle(lc34, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x70], xmm0); vmovups(xmm0, xword[A1+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x60], xmm0); vmovups(xmm0, xword[A1+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x50], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -64); align(4); L(lc34); test(M, 0x2); jle(lc68, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x70], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -32); align(4); L(lc68); test(M, 0x1); jle(lc88, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); sub(B, -16); align(4); L(lc88); sub(N, 0x4); align(4); L(lc8c); cmp(N, 0x2); jl(ldf8, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(ld4c, T_NEAR); align(4); L(lcb0); vmovsd(xmm0, qword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x78], xmm0); vmovsd(xmm0, qword[A1+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x70], xmm0); vmovsd(xmm0, qword[A1+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x68], xmm0); vmovsd(xmm0, qword[A2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x60], xmm0); vmovsd(xmm0, qword[A2+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x58], xmm0); vmovsd(xmm0, qword[A2+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x50], xmm0); vmovsd(xmm0, qword[A2+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x48], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -64); dec(I); jg(lcb0, T_NEAR); align(4); L(ld4c); test(M, 0x4); jle(lda0, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x78], xmm0); vmovsd(xmm0, qword[A1+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x70], xmm0); vmovsd(xmm0, qword[A1+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x68], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -32); align(4); L(lda0); test(M, 0x2); jle(ldd4, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x78], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -16); align(4); L(ldd4); test(M, 0x1); jle(ldf4, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); sub(B, -8); align(4); L(ldf4); sub(N, 0x2); align(4); L(ldf8); cmp(N, 0x1); jl(lf64, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(leb8, T_NEAR); align(4); L(le1c); vmovss(xmm0, dword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x7c], xmm0); vmovss(xmm0, dword[A1+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x78], xmm0); vmovss(xmm0, dword[A1+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x74], xmm0); vmovss(xmm0, dword[A2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x70], xmm0); vmovss(xmm0, dword[A2+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x6c], xmm0); vmovss(xmm0, dword[A2+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x68], xmm0); vmovss(xmm0, dword[A2+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x64], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -32); dec(I); jg(le1c, T_NEAR); align(4); L(leb8); test(M, 0x4); jle(lf0c, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x7c], xmm0); vmovss(xmm0, dword[A1+LDA*2-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x78], xmm0); vmovss(xmm0, dword[A1+LDA3*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x74], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -16); align(4); L(lf0c); test(M, 0x2); jle(lf40, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x7c], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -8); align(4); L(lf40); test(M, 0x1); jle(lf60, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); sub(B, -4); align(4); L(lf60); sub(N, 0x1); align(4); L(lf64); jmp(l17b4, T_NEAR); align(4); L(lf6c); cmp(N, 0x10); jl(l1200, T_NEAR); align(4); L(lf78); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x40); mov(I, M); sar(I, 0x3); jle(l10cc, T_NEAR); align(4); L(lf90); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x60], ymm0); vmovups(ymm0, yword[A2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x80], ymm0); vmovups(ymm0, yword[A2-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0xa0], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0xc0], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0xe0], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x100], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x120], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x140], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x160], ymm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -512); dec(I); jg(lf90, T_NEAR); align(4); L(l10cc); test(M, 0x4); jle(l116c, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x60], ymm0); lea(A1, ptr[A1+LDA*4]); sub(B, -256); align(4); L(l116c); test(M, 0x2); jle(l11c0, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); lea(A1, ptr[A1+LDA*2]); sub(B, -128); align(4); L(l11c0); test(M, 0x1); jle(l11f0, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1-0x60]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); sub(B, -64); align(4); L(l11f0); sub(N, 0x10); cmp(N, 0x10); jge(lf78, T_NEAR); align(4); L(l1200); cmp(N, 0x8); jl(l1370, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x20); mov(I, M); sar(I, 0x3); jle(l12c4, T_NEAR); align(4); L(l1224); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); vmovups(ymm0, yword[A2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B], ymm0); vmovups(ymm0, yword[A2+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x20], ymm0); vmovups(ymm0, yword[A2+LDA*2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x40], ymm0); vmovups(ymm0, yword[A2+LDA3*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B+0x60], ymm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -256); dec(I); jg(l1224, T_NEAR); align(4); L(l12c4); test(M, 0x4); jle(l1318, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); vmovups(ymm0, yword[A1+LDA*2-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x40], ymm0); vmovups(ymm0, yword[A1+LDA3*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x20], ymm0); lea(A1, ptr[A1+LDA*4]); sub(B, -128); align(4); L(l1318); test(M, 0x2); jle(l134c, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); vmovups(ymm0, yword[A1+LDA*1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x60], ymm0); lea(A1, ptr[A1+LDA*2]); sub(B, -64); align(4); L(l134c); test(M, 0x1); jle(l136c, T_NEAR); vmovups(ymm0, yword[A1-0x80]); vmulps(ymm0, ymm6, ymm0); vmovups(yword[B-0x80], ymm0); sub(B, -32); align(4); L(l136c); sub(N, 0x8); align(4); L(l1370); cmp(N, 0x4); jl(l14dc, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x10); mov(I, M); sar(I, 0x3); jle(l1430, T_NEAR); align(4); L(l1394); vmovups(xmm0, xword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x70], xmm0); vmovups(xmm0, xword[A1+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x60], xmm0); vmovups(xmm0, xword[A1+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x50], xmm0); vmovups(xmm0, xword[A2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x40], xmm0); vmovups(xmm0, xword[A2+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x30], xmm0); vmovups(xmm0, xword[A2+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x20], xmm0); vmovups(xmm0, xword[A2+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x10], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -128); dec(I); jg(l1394, T_NEAR); align(4); L(l1430); test(M, 0x4); jle(l1484, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x70], xmm0); vmovups(xmm0, xword[A1+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x60], xmm0); vmovups(xmm0, xword[A1+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x50], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -64); align(4); L(l1484); test(M, 0x2); jle(l14b8, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); vmovups(xmm0, xword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x70], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -32); align(4); L(l14b8); test(M, 0x1); jle(l14d8, T_NEAR); vmovups(xmm0, xword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l14d8); sub(N, 0x4); align(4); L(l14dc); cmp(N, 0x2); jl(l1648, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(l159c, T_NEAR); align(4); L(l1500); vmovsd(xmm0, qword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x78], xmm0); vmovsd(xmm0, qword[A1+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x70], xmm0); vmovsd(xmm0, qword[A1+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x68], xmm0); vmovsd(xmm0, qword[A2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x60], xmm0); vmovsd(xmm0, qword[A2+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x58], xmm0); vmovsd(xmm0, qword[A2+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x50], xmm0); vmovsd(xmm0, qword[A2+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x48], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -64); dec(I); jg(l1500, T_NEAR); align(4); L(l159c); test(M, 0x4); jle(l15f0, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x78], xmm0); vmovsd(xmm0, qword[A1+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x70], xmm0); vmovsd(xmm0, qword[A1+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x68], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -32); align(4); L(l15f0); test(M, 0x2); jle(l1624, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); vmovsd(xmm0, qword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x78], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -16); align(4); L(l1624); test(M, 0x1); jle(l1644, T_NEAR); vmovsd(xmm0, qword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l1644); sub(N, 0x2); align(4); L(l1648); cmp(N, 0x1); jl(l17b4, T_NEAR); mov(A1, A); lea(A2, ptr[A1+LDA*4]); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l1708, T_NEAR); align(4); L(l166c); vmovss(xmm0, dword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x7c], xmm0); vmovss(xmm0, dword[A1+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x78], xmm0); vmovss(xmm0, dword[A1+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x74], xmm0); vmovss(xmm0, dword[A2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x70], xmm0); vmovss(xmm0, dword[A2+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x6c], xmm0); vmovss(xmm0, dword[A2+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x68], xmm0); vmovss(xmm0, dword[A2+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x64], xmm0); lea(A1, ptr[A1+LDA*8]); lea(A2, ptr[A2+LDA*8]); sub(B, -32); dec(I); jg(l166c, T_NEAR); align(4); L(l1708); test(M, 0x4); jle(l175c, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x7c], xmm0); vmovss(xmm0, dword[A1+LDA*2-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x78], xmm0); vmovss(xmm0, dword[A1+LDA3*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x74], xmm0); lea(A1, ptr[A1+LDA*4]); sub(B, -16); align(4); L(l175c); test(M, 0x2); jle(l1790, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); vmovss(xmm0, dword[A1+LDA*1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x7c], xmm0); lea(A1, ptr[A1+LDA*2]); sub(B, -8); align(4); L(l1790); test(M, 0x1); jle(l17b0, T_NEAR); vmovss(xmm0, dword[A1-0x80]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l17b0); sub(N, 0x1); align(4); L(l17b4); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/zobrist.h<|end_filename|> // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ZOBRIST_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ZOBRIST_H_ #include <algorithm> #include <array> #include <cstdint> #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/color.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/coord.h" namespace minigo { namespace zobrist { using Hash = uint64_t; namespace internal { extern Hash kBlackToPlayHash; extern Hash kOpponentPassedHash; extern std::array<std::array<Hash, 3>, kNumMoves> kMoveHashes; extern std::array<Hash, kN * kN> kIllegalEmptyPointHashes; } // namespace internal // Non-zero when it's black's turn. inline Hash ToPlayHash(Color color) { return color == Color::kBlack ? internal::kBlackToPlayHash : 0; } // Hash set when the previous move was a pass. inline Hash OpponentPassedHash() { return internal::kOpponentPassedHash; } // Hashes for moves by black and white. inline Hash MoveHash(Coord c, Color color) { return internal::kMoveHashes[c][static_cast<int>(color)]; } // Hashes used for empty points that can't be played because of things like // self-capture, ko or positional superko. inline Hash IllegalEmptyPointHash(Coord c) { return internal::kIllegalEmptyPointHashes[c]; } void Init(uint64_t seed); } // namespace zobrist } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ZOBRIST_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/mkldnn_common.cpp<|end_filename|> /******************************************************************************* * Copyright 2017-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <assert.h> #include "mkldnn.h" #include "mkldnn_common.hpp" // Engine kind used to run MKL-DNN primitives for testing mkldnn_engine_kind_t engine_tgt_kind = mkldnn_cpu; // Engine used for reference benchdnn computations mkldnn_engine_t engine_ref; // Engine used to run MKL-DNN primitives for testing mkldnn_engine_t engine_tgt; // Stream for reference engine mkldnn_stream_t stream_ref; // Stream for target engine mkldnn_stream_t stream_tgt; <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/model/factory.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_FACTORY_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_FACTORY_H_ #include <memory> #include <ostream> #include <string> #include <utility> #include "REDACTEDcontainer/flat_hash_map.h" #include "REDACTEDstrings/string_view.h" #include "REDACTEDtypes/variant.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/model.h" namespace minigo { using ModelProperty = absl::variant<std::string, bool, int64_t, uint64_t, float>; // Although the metadata is stored in the Minigo file as JSON, it is // converted on load to a simpler representation to avoid pulling an entire // JSON library into this header (at the time of writing the nlohmann::json // header is more than 22,000 lines). class ModelMetadata { public: // Explicit setters to avoid hard to interpret template compiler errors. void Set(absl::string_view key, const char* value) { impl_[key] = std::string(value); } void Set(absl::string_view key, absl::string_view value) { impl_[key] = std::string(value); } void Set(absl::string_view key, std::string value) { impl_[key] = std::move(value); } void Set(absl::string_view key, bool value) { impl_[key] = value; } void Set(absl::string_view key, int64_t value) { impl_[key] = value; } void Set(absl::string_view key, uint64_t value) { impl_[key] = value; } void Set(absl::string_view key, float value) { impl_[key] = value; } bool Has(absl::string_view key) const { return impl_.contains(key); } template <typename T> const T& Get(absl::string_view key) const { const auto& prop = impl_.at(key); MG_DCHECK(absl::holds_alternative<T>(prop)) << DebugString(); return absl::get<T>(prop); } template <typename T> bool TryGet(absl::string_view key, T* value) const { auto it = impl_.find(key); if (it == impl_.end()) { return false; } if (!absl::holds_alternative<T>(it->second)) { return false; } *value = absl::get<T>(it->second); return true; } std::string DebugString() const; private: absl::flat_hash_map<std::string, ModelProperty> impl_; }; struct ModelDefinition { std::string path; ModelMetadata metadata; std::string model_bytes; }; // Factory that creates Model instances. // All implementations are required to be thread safe. class ModelFactory { public: virtual ~ModelFactory(); // Create a single model. virtual std::unique_ptr<Model> NewModel(const ModelDefinition& def) = 0; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_MODEL_FACTORY_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/dual_net/random_dual_net.cc<|end_filename|> // Copyright 2019 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/dual_net/random_dual_net.h" #include <cmath> #include <vector> #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/numbers.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/str_split.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" namespace minigo { RandomDualNet::RandomDualNet(std::string name, const FeatureDescriptor& feature_desc, uint64_t seed, float policy_stddev, float value_stddev) : Model(std::move(name), feature_desc), rnd_(seed, Random::kUniqueStream), policy_stddev_(policy_stddev), value_stddev_(value_stddev) {} void RandomDualNet::RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) { for (auto* output : *outputs) { rnd_.NormalDistribution(0.5, policy_stddev_, &output->policy); for (auto& p : output->policy) { p = std::exp(p); } float sum = 0; for (auto p : output->policy) { sum += p; } for (auto& p : output->policy) { p /= sum; } do { output->value = rnd_.NormalDistribution(0, value_stddev_); } while (output->value < -1 || output->value > 1); } if (model_name != nullptr) { *model_name = name(); } } std::unique_ptr<Model> RandomDualNetFactory::NewModel( const ModelDefinition& def) { const auto& metadata = def.metadata; uint64_t seed = metadata.Get<uint64_t>("seed"); float policy_stddev = metadata.Get<float>("policy_stddev"); float value_stddev = metadata.Get<float>("value_stddev"); auto name = absl::StrCat("rnd:", seed, ":", policy_stddev, ":", value_stddev); auto feature_desc = FeatureDescriptor::Create(metadata.Get<std::string>("input_features"), metadata.Get<std::string>("input_layout")); return absl::make_unique<RandomDualNet>(name, feature_desc, seed, policy_stddev, value_stddev); } } // namespace minigo <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/rnn/ref_rnn.cpp<|end_filename|> /******************************************************************************* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <stdlib.h> #include "src/common/mkldnn_thread.hpp" #include "rnn/rnn.hpp" #include "rnn/rnn_aux.hpp" namespace rnn { #define min(a, b) ((a < b) ? a : b) #define max(a, b) ((a > b) ? a : b) #define xstr(a) str(a) #define str(a) #a #define AOC array_offset_calculator void lstm_activation(int64_t dic, int64_t n_gates, int64_t batch, // float a[batch][n_gates * wc] float *a) { AOC<float> pa(a, batch, n_gates, dic); mkldnn::impl::parallel_nd(batch, [&](int64_t ib) { for (int64_t ih = 0; ih < dic; ih++) { pa(ib, 0, ih) = logistic(pa(ib, 0, ih)); pa(ib, 1, ih) = logistic(pa(ib, 1, ih)); pa(ib, 2, ih) = tanhf(pa(ib, 2, ih)); pa(ib, 3, ih) = logistic(pa(ib, 3, ih)); for (int64_t ig = 0; ig < 4; ig++) { print(80, "activation 1 a[" IFMT "][" IFMT "][" IFMT "] = %.7f\n", ib, ig, ih, pa(ib, ig, ih)); } } }); } float activation(activation_t f, float x, bool is_fwd = true) { float result = 0; switch (f) { case RELU: result = is_fwd ? relu(x) : drelu(x); break; case LOGISTIC: result = is_fwd ? logistic(x) : x_m_square(x); break; case TANH: result = is_fwd ? tanhf(x) : one_m_square(x); break; default: assert(!"unknown activation"); } return result; } void rnn_fwd(activation_t f, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *dst_iter_h_, float *gates_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *src_layer_, const float *src_iter_h_) { AOC<float> dst_iter_h(dst_iter_h_, batch, n_gates, wc); AOC<const float> bias(bias_, n_gates, dic); AOC<float> gates(gates_, batch, n_gates, dic); gemm("C", "N", "N", batch, n_gates * dic, slc, 1.0, src_layer_, wc, weights_layer_, n_gates * dic, 0.0, gates_, n_gates * dic); gemm("C", "N", "N", batch, n_gates * dic, sic, 1.0, src_iter_h_, wc, weights_iter_h_, n_gates * dic, 1.0, gates_, n_gates * dic); for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates; j++) for (int64_t k = 0; k < dic; k++) { const auto tmp = activation(f, gates(i, j, k) + bias(j, k)); gates(i, j, k) = tmp; dst_iter_h(i, j, k) = tmp; } } void gru_fwd(int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *dst_iter_h_, float *gates_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *src_layer_, const float *src_iter_h_) { AOC<const float> src_iter_h(src_iter_h_, batch, wc); AOC<const float> weights_layer(weights_layer_, slc, n_gates, dic); AOC<const float> weights_iter_h(weights_iter_h_, sic, n_gates, dic); AOC<const float> bias(bias_, n_gates, dic); AOC<float> gates(gates_, batch, n_gates, dic); AOC<float> h_dst(dst_iter_h_, batch, wc); gemm("C", "N", "N", batch, n_gates * dic, slc, 1.0, src_layer_, wc, weights_layer_, n_gates * dic, 0.0, gates_, n_gates * dic); gemm("C", "N", "N", batch, (n_gates - 1) * dic, sic, 1.0, src_iter_h_, wc, weights_iter_h_, n_gates * dic, 1.0, gates_, n_gates * dic); for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates - 1; j++) for (int64_t k = 0; k < dic; k++) { gates(i, j, k) = logistic(gates(i, j, k) + bias(j, k)); } for (int64_t i = 0; i < batch; i++) for (int64_t k = 0; k < dic; k++) { h_dst(i, k) = src_iter_h(i, k) * gates(i, 1, k); } gemm("C", "N", "N", batch, dic, sic, 1.0, dst_iter_h_, wc, &(weights_iter_h(0, 2, 0)), n_gates * dic, 1.0, &(gates(0, 2, 0)), n_gates * dic); for (int64_t i = 0; i < batch; i++) for (int64_t k = 0; k < dic; k++) { gates(i, 2, k) = tanhf(gates(i, 2, k) + bias(2, k)); } for (int64_t i = 0; i < batch; i++) for (int64_t k = 0; k < dic; k++) { h_dst(i, k) = (float) ((double) gates(i, 0, k) * src_iter_h(i, k) + (1.0 - (double) gates(i, 0, k)) * gates(i, 2, k)); } } void gru_lbr_fwd(int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *dst_iter_h_, float *gates_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *src_layer_, const float *src_iter_h_, float *ws_local_) { AOC<const float> src_iter_h(src_iter_h_, batch, wc); AOC<const float> weights_layer(weights_layer_, slc, n_gates, dic); AOC<const float> weights_iter_h(weights_iter_h_, sic, n_gates, dic); AOC<const float> bias(bias_, n_gates + 1, dic); AOC<float> gates(gates_, batch, n_gates, dic); AOC<float> h_dst(dst_iter_h_, batch, wc); AOC<float> tmp_ws(ws_local_, batch, n_gates, dic); gemm("C", "N", "N", batch, n_gates * dic, slc, 1.0, src_layer_, wc, weights_layer_, n_gates * dic, 0.0, gates_, n_gates * dic); gemm("C", "N", "N", batch, n_gates * dic, sic, 1.0, src_iter_h_, wc, weights_iter_h_, n_gates * dic, 0.0, ws_local_, n_gates * dic); for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates - 1; j++) for (int64_t k = 0; k < dic; k++) { gates(i, j, k) = logistic(gates(i, j, k) + tmp_ws(i, j, k) + bias(j, k)); } for (int64_t i = 0; i < batch; i++) for (int64_t k = 0; k < dic; k++) { gates(i, 2, k) = tanhf(gates(i, 2, k) + gates(i, 1, k) * (tmp_ws(i, 2, k) + bias(3, k)) + bias(2, k)); } for (int64_t i = 0; i < batch; i++) for (int64_t k = 0; k < dic; k++) { h_dst(i, k) = gates(i, 0, k) * src_iter_h(i, k) + (1 - gates(i, 0, k)) * gates(i, 2, k); } } // w = [weights_layer | weights_iter] : with order f, i , o, \bar(c) void lstm_fwd(const prb_t *p, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *dst_iter_h_, float *c_dst_, float *gates_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *src_layer_, const float *src_iter_h_, const float *src_iter_c_) { AOC<float> h_dst(dst_iter_h_, batch, wc); AOC<float> c_dst(c_dst_, batch, wc); AOC<const float> bias(bias_, n_gates, dic); AOC<const float> src_iter_c(src_iter_c_, batch, wc); AOC<float> gates(gates_, batch, n_gates, dic); const int64_t ohi = 0; const int64_t ohf = 1; const int64_t ohc = 2; const int64_t oho = 3; gemm("C", "N", "N", batch, n_gates * dic, slc, 1.0, src_layer_, wc, weights_layer_, n_gates * dic, 0.0, gates_, n_gates * dic); gemm("C", "N", "N", batch, n_gates * dic, sic, 1.0, src_iter_h_, wc, weights_iter_h_, n_gates * dic, 1.0, gates_, n_gates * dic); auto maybe_deq_w = [&](float g, int64_t oc) { if (p->cfg == conf_f32 || p->cfg == conf_f16) return g; float scale = 1.; if (p->scale_policy == PER_OC) scale = p->wei_oc_scales[oc]; else if (p->scale_policy == COMMON) scale = p->wei_scale; scale *= p->data_scale; return g / scale; }; // add bias for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates; j++) for (int64_t k = 0; k < dic; k++) { gates(i, j, k) = maybe_deq_w(gates(i, j, k), j * dic + k) + bias(j, k); } // run the eltwise lstm_activation(dic, n_gates, batch, gates_); auto maybe_q_d = [&](float h) { if (p->cfg == conf_f32 || p->cfg == conf_f16) return h; float fp = p->data_scale * h; fp = mxcsr_round(fp); if (fp + p->data_shift > p->cfg[input].max) fp = p->cfg[input].max - p->data_shift; if (fp + p->data_shift < p->cfg[input].min) fp = p->cfg[input].min - p->data_shift; return fp; }; // compute C_t_l and H_t_l for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < dic; j++) { float tmp = gates(i, ohf, j) * src_iter_c(i, j) + gates(i, ohi, j) * gates(i, ohc, j); c_dst(i, j) = tmp; h_dst(i, j) = maybe_q_d(gates(i, oho, j) * tanhf(tmp)); } } void rnn_cell_fwd(const prb_t *p, alg_t alg, activation_t f, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *dst_iter_h, float *dst_iter_c, float *gates, const float *weights_layer, const float *weights_iter, const float *bias, const float *src_layer, const float *src_iter_h, const float *src_iter_c, float *ws_local_) { switch (alg) { case VANILLA_GRU: gru_fwd(sic, slc, dic, wc, batch, n_gates, dst_iter_h, gates, weights_layer, weights_iter, bias, src_layer, src_iter_h); break; case LBR_GRU: gru_lbr_fwd(sic, slc, dic, wc, batch, n_gates, dst_iter_h, gates, weights_layer, weights_iter, bias, src_layer, src_iter_h, ws_local_); break; case VANILLA_LSTM: lstm_fwd(p, sic, slc, dic, wc, batch, n_gates, dst_iter_h, dst_iter_c, gates, weights_layer, weights_iter, bias, src_layer, src_iter_h, src_iter_c); break; case VANILLA_RNN: rnn_fwd(f, sic, slc, dic, wc, batch, n_gates, dst_iter_h, gates, weights_layer, weights_iter, bias, src_layer, src_iter_h); break; default: break; } } void copy(int64_t dimc, int64_t dimr, int64_t ld_src, int64_t ld_dst, const float *src_, float *dst_, rnn_action_t action = action_copy) { AOC<const float> src(src_, dimc, ld_src); AOC<float> dst(dst_, dimc, ld_dst); mkldnn::impl::parallel_nd(dimc, [&](int64_t i) { for (int64_t j = 0; j < dimr; j++) { dst(i, j) = action == action_sum ? dst(i, j) + src(i, j) : src(i, j); } }); } void shift(int64_t dimc, int64_t dimr, int64_t ld_src, float *src_, float shift, bool round = false, const prb_t *p = nullptr) { AOC<float> src(src_, dimc, ld_src); mkldnn::impl::parallel_nd(dimc, [&](int64_t i) { for (int64_t j = 0; j < dimr; j++) { float fp = src(i, j) + shift; if (round) { fp = mxcsr_round(fp); if (fp > UINT8_MAX) fp = UINT8_MAX; if (fp < 0) fp = 0; } src(i, j) = fp; } }); } void scale(int64_t dimc, int64_t dimr, int64_t ld_src, float *src_, float scale, bool round = false, const prb_t *p = nullptr) { AOC<float> src(src_, dimc, ld_src); mkldnn::impl::parallel_nd(dimc, [&](int64_t i) { for (int64_t j = 0; j < dimr; j++) { float fp = src(i, j) * scale; if (round) fp = mxcsr_round(fp); src(i, j) = fp; } }); } /* lstm example: * fwd: ws keeps {h, c} for every cell */ void copy_init_fwd(const prb_t *p, alg_t alg, int64_t sic, int64_t slc, int64_t dic, int64_t dlc, int64_t wc, int64_t batch, int64_t n_layer, int64_t n_iter, int64_t n_dir, int64_t n_states, float *ws_, const float *src_layer_, const float *firstit_states_, const float *firstit_c_states_, rnn_iter_direction_t iter_dir, rnn_layer_direction_t lay_dir, int64_t dir_val) { AOC<float> ws(ws_, n_layer + 2, n_dir, n_iter + 2, n_states, batch * wc); AOC<const float> src_layer(src_layer_, n_iter, batch * slc); AOC<const float> firstit_states( firstit_states_, n_layer, n_dir, batch * sic); AOC<const float> firstit_c_states( firstit_c_states_, n_layer, n_dir, batch * dic); int64_t lay_dest = (lay_dir == bottom2top) ? 0 : n_layer + 1; int64_t it_dest = (iter_dir == left2right) ? 0 : n_iter + 1; bool is_int8 = p->cfg[input].dt == mkldnn_u8; // Copy input for (int64_t it = 0; it < n_iter; it++) { copy(batch, slc, slc, wc, &src_layer(it, 0), &ws(lay_dest, dir_val, it + 1, H, 0)); if (p->cfg[input].dt == mkldnn_u8) // shift u8 input to s8 to avoid compensation in gemm shift(batch, slc, wc, &ws(lay_dest, dir_val, it + 1, H, 0), -1. * p->data_shift); } // Copy states for (int64_t lay = 0; lay < n_layer; lay++) { copy(batch, sic, sic, wc, &firstit_states(lay, dir_val, 0), &ws(lay + 1, dir_val, it_dest, H, 0)); if (p->cfg[states].dt == mkldnn_u8) shift(batch, sic, wc, &ws(lay + 1, dir_val, it_dest, H, 0), -1. * p->data_shift); else if (p->cfg[states].dt == mkldnn_f32 && is_int8) { // quantize to s8 scale(batch, sic, wc, &ws(lay + 1, dir_val, it_dest, H, 0), p->data_scale, true, p); } if (alg == VANILLA_LSTM) { copy(batch, dic, dic, wc, &firstit_c_states(lay, dir_val, 0), &ws(lay + 1, dir_val, it_dest, C, 0)); } } } /* lstm example: * bwd: wsb keeps {dh, dc, dx} for every cell */ void copy_init_bwd(alg_t alg, int64_t sic, int64_t slc, int64_t dic, int64_t dlc, int64_t wc, int64_t batch, int64_t n_layer, int64_t n_iter, int64_t n_dir, int64_t n_states, float *ws_, const float *src_layer_, const float *firstit_states_, const float *firstit_c_states_, rnn_iter_direction_t iter_dir, rnn_layer_direction_t lay_dir, int64_t dir_val, bool is_concat = false) { AOC<float> ws( ws_, n_layer + 2, n_dir, n_iter + 2, n_states + 1, batch * wc); auto c_stride = is_concat ? 2 * dlc : dlc; AOC<const float> src_layer(src_layer_, n_iter, batch * c_stride); AOC<const float> firstit_states( firstit_states_, n_layer, n_dir, batch * dic); AOC<const float> firstit_c_states( firstit_c_states_, n_layer, n_dir, batch * dic); int64_t lay_dest = (lay_dir == bottom2top) ? 0 : n_layer + 1; int64_t it_dest = (iter_dir == left2right) ? 0 : n_iter + 1; for (int64_t it = 0; it < n_iter; it++) copy(batch, dic, c_stride, wc, &src_layer(it, dir_val * is_concat * dlc), &ws(lay_dest, dir_val, it + 1, n_states, 0)); for (int64_t lay = 0; lay < n_layer; lay++) { copy(batch, dic, dic, wc, &firstit_states(lay, dir_val, 0), &ws(lay + 1, dir_val, it_dest, H, 0)); if (alg == VANILLA_LSTM) { copy(batch, dic, dic, wc, &firstit_c_states(lay, dir_val, 0), &ws(lay + 1, dir_val, it_dest, C, 0)); } } } void copy_res_fwd(const prb_t *p, alg_t alg, int64_t sic, int64_t slc, int64_t dic, int64_t dlc, int64_t wc, int64_t batch, int64_t n_layer, int64_t n_iter, int64_t n_dir, int64_t n_states, float *lastit_states_, float *lastit_c_states_, float *lastlay_states_, const float *ws_, rnn_iter_direction_t iter_dir, rnn_layer_direction_t lay_dir, int64_t dir_val, rnn_action_t action, bool is_concat = false) { int64_t lastlay_c = is_concat ? 2 * dlc : dlc; AOC<float> lastit_states( lastit_states_, n_layer, n_dir, batch, dic); AOC<float> lastit_c_states( lastit_c_states_, n_layer, n_dir, batch, dic); AOC<float> lastlay_states(lastlay_states_, n_iter, batch, lastlay_c); AOC<const float> ws( ws_, n_layer + 2, n_dir, n_iter + 2, n_states, batch, wc); // Copy states layer for (int64_t it = 0; it < n_iter; it++) { for (int64_t nb = 0; nb < batch; nb++) { auto from = &ws(n_layer, dir_val, it + 1, H, nb, 0); auto to = &lastlay_states( it, nb, action == action_concat ? dlc : 0); copy(1, dlc, wc, lastlay_c, from, to, action); if (p->cfg[dst_last_layer].dt == mkldnn_u8) { // shift s8 internal ws to u8 shift(1, dlc, lastlay_c, to, p->data_shift); } else { // dequantize to f32 scale(1, dlc, lastlay_c, to, 1. / p->data_scale); } } } int64_t it_source = (iter_dir == left2right) ? n_iter : 1; // Copy states iteration for (int64_t lay = 0; lay < n_layer; lay++) { if (alg == VANILLA_LSTM) { copy(batch, dic, wc, dic, &ws(lay + 1, dir_val, it_source, C, 0, 0), &lastit_c_states(lay, dir_val, 0, 0)); } copy(batch, dic, wc, dic, &ws(lay + 1, dir_val, it_source, H, 0, 0), &lastit_states(lay, dir_val, 0, 0)); if (p->cfg[dst_last_iteration].dt == mkldnn_u8) { // shift s8 internal ws to u8 shift(batch, dic, dic, &lastit_states(lay, dir_val, 0, 0), p->data_shift); } else { // dequantize to f32 scale(batch, dic, dic, &lastit_states(lay, dir_val, 0, 0), 1. / p->data_scale); } } } void copy_res_bwd(alg_t alg, int64_t sic, int64_t slc, int64_t dic, int64_t dlc, int64_t wc, int64_t batch, int64_t n_layer, int64_t n_iter, int64_t n_dir, int64_t n_states, float *lastit_states_, float *lastit_c_states_, float *lastlay_states_, const float *ws_, rnn_iter_direction_t iter_dir, rnn_layer_direction_t lay_dir, int64_t dir_val, rnn_action_t action) { AOC<float> lastit_states( lastit_states_, n_layer, n_dir, batch, sic); AOC<float> lastit_c_states( lastit_c_states_, n_layer, n_dir, batch, dic); AOC<float> lastlay_states(lastlay_states_, n_iter, batch, slc); AOC<const float> ws( ws_, n_layer + 2, n_dir, n_iter + 2, n_states + 1, batch, wc); for (int64_t it = 0; it < n_iter; it++) { for (int64_t nb = 0; nb < batch; nb++) { // copy H to last layer states auto from = &ws(1, dir_val, it + 1, n_states, nb, 0); auto to = &lastlay_states(it, nb, 0); copy(1, slc, wc, slc, from, to, action); } } int64_t it_source = (iter_dir == left2right) ? n_iter : 1; for (int64_t lay = 0; lay < n_layer; lay++) { if (alg == VANILLA_LSTM) { copy(batch, dic, wc, dic, &ws(lay + 1, dir_val, it_source, C, 0, 0), &lastit_c_states(lay, dir_val, 0, 0)); } copy(batch, sic, wc, sic, &ws(lay + 1, dir_val, it_source, H, 0, 0), &lastit_states(lay, dir_val, 0, 0)); } } void rnn_linear_fwd(const prb_t *p, mkldnn_rnn_direction_t direction, const float *src_iter_, const float *src_iter_c_, const float *src_layer_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, float *dst_iter_, float *dst_iter_c_, float *dst_layer_, float *ws_, float *gates_) { const alg_t alg = p->alg; const int64_t sic = p->sic; const int64_t slc = p->slc; const int64_t dic = p->dic; const int64_t dlc = p->dlc; const int64_t wc = max(sic, max(slc, dic)); bool is_lbr = p->alg == LBR_GRU; bool is_concat = direction == mkldnn_bidirectional_concat; const int64_t batch = p->mb; const int64_t n_gates = p->n_gates(); const int64_t n_states = p->n_states(); const int64_t n_layer = p->n_layer; const int64_t n_iter = p->n_iter; const int64_t n_dir = p->n_directions(); activation_t f = p->activation; AOC<const float> bias(bias_, n_layer, n_dir, (n_gates + is_lbr) * dic); AOC<const float> weights_layer( weights_layer_, n_layer, n_dir, n_gates * dic, slc); AOC<const float> weights_iter( weights_iter_h_, n_layer, n_dir, n_gates * dic, sic); AOC<float> ws(ws_, n_layer + 2, n_dir, n_iter + 2, n_states, batch, wc); AOC<float> gates(gates_, n_layer, n_dir, n_iter, batch, n_gates, dic); int64_t ws_local_size = is_lbr * batch * n_gates * dic; float *ws_local_ = new float[ws_local_size]; auto process_direction = [&](rnn_iter_direction_t iter_dir, rnn_layer_direction_t lay_dir, int64_t dir_val, rnn_action_t action) { // we first need to copy the initial states and input into ws // it simplifies the logic in the following code print(80, "rnn_linear_fwd: call copy_init dir_val = " IFMT "\n", dir_val); copy_init_fwd(p, alg, sic, slc, dic, dlc, wc, batch, n_layer, n_iter, n_dir, n_states, ws_, src_layer_, src_iter_, src_iter_c_, iter_dir, lay_dir, dir_val); // We run the grid of computation for (int64_t il = 0; il < n_layer; il++) { for (int64_t it = 0; it < n_iter; it++) { print(80, "==== layer = " IFMT " iter = " IFMT " ===\n", il, it); int64_t iter = (iter_dir == left2right) ? it + 1 : n_iter - it; int64_t prev_iter = (iter_dir == left2right) ? iter - 1 : iter + 1; int64_t lay = il + 1; rnn_cell_fwd(p, alg, f, sic, slc, dic, wc, batch, n_gates, &ws(lay, dir_val, iter, H, 0, 0), &ws(lay, dir_val, iter, C, 0, 0), &gates(lay - 1, dir_val, iter - 1, 0, 0, 0), &weights_layer(lay - 1, dir_val, 0, 0), &weights_iter(lay - 1, dir_val, 0, 0), &bias(lay - 1, dir_val, 0), &ws(lay - 1, dir_val, iter, H, 0, 0), &ws(lay, dir_val, prev_iter, H, 0, 0), &ws(lay, dir_val, prev_iter, C, 0, 0), ws_local_); } } // Finally we copy the results to the result buffers copy_res_fwd(p, alg, sic, slc, dic, dlc, wc, batch, n_layer, n_iter, n_dir, n_states, dst_iter_, dst_iter_c_, dst_layer_, ws_, iter_dir, lay_dir, dir_val, action, is_concat); }; switch (direction) { case mkldnn_unidirectional_left2right: process_direction(left2right, bottom2top, 0, action_copy); break; case mkldnn_unidirectional_right2left: process_direction(right2left, bottom2top, 0, action_copy); break; case mkldnn_bidirectional_sum: process_direction(left2right, bottom2top, 0, action_copy); process_direction(right2left, bottom2top, 1, action_sum); break; case mkldnn_bidirectional_concat: process_direction(left2right, bottom2top, 0, action_copy); process_direction(right2left, bottom2top, 1, action_concat); break; default: assert("unknown direction"); break; } delete[] ws_local_; } void compute_ref_fwd(const prb_t *p, dnn_mem_t &src_layer_m, dnn_mem_t &src_iter_m, dnn_mem_t &src_iter_c_m, dnn_mem_t &weights_src_layer_m, dnn_mem_t &weights_src_iter_m, dnn_mem_t &bias_m, dnn_mem_t &dst_last_layer_m, dnn_mem_t &dst_last_iteration_m, dnn_mem_t &dst_c_last_iteration_m, mkldnn_rnn_direction_t direction) { assert(direction == mkldnn_unidirectional_left2right || direction == mkldnn_unidirectional_right2left || direction == mkldnn_bidirectional_sum || direction == mkldnn_bidirectional_concat); const int64_t wc = max(p->sic, max(p->slc, p->dic)); int64_t ws_size = (p->n_layer + 2) * p->n_directions() * (p->n_iter + 2) * p->n_states() * p->mb * wc; auto *ws = new float[ws_size]; int64_t gates_size = p->n_layer * p->n_directions() * p->n_iter * p->mb * p->n_gates() * p->dic; auto *gates = new float[gates_size]; rnn_linear_fwd(p, direction, (float *)src_iter_m, (float *)src_iter_c_m, (float *)src_layer_m, (float *)weights_src_layer_m, (float *)weights_src_iter_m, (float *)bias_m, (float *)dst_last_iteration_m, (float *)dst_c_last_iteration_m, (float *)dst_last_layer_m, ws, gates); delete[] ws; delete[] gates; } // ============================================================================= // ================ BACKWARD =================================================== // ============================================================================= void rnn_bwd(alg_t alg, activation_t f, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *diff_src_layer_, float *diff_src_iter_, float *diff_weights_layer_, float *diff_weights_iter_h_, float *diff_bias_, float *b_gates_, const float *src_layer_, const float *src_iter_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *dst_iter_h_, const float *gates_, const float *diff_dst_layer_, const float *diff_dst_iter_h_) { AOC<const float> diff_dst_layer(diff_dst_layer_, batch, wc); AOC<const float> diff_dst_iter_h(diff_dst_iter_h_, batch, wc); AOC<const float> gates(gates_, batch, n_gates, dic); AOC<float> b_gates(b_gates_, batch, n_gates, dic); for (int64_t b = 0; b < batch; ++b) for (int64_t h = 0; h < dic; ++h) { const float g = gates(b, 0, h); const float dd = diff_dst_layer(b, h) + diff_dst_iter_h(b, h); b_gates(b, 0, h) = activation(f, g, false) * dd; } gemm("C", "T", "N", sic, n_gates * dic, batch, 1.0, src_iter_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_iter_h_, n_gates * dic); gemm("C", "T", "N", slc, n_gates * dic, batch, 1.0, src_layer_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_layer_, n_gates * dic); for (int64_t b = 0; b < batch; ++b) copy(n_gates, dic, dic, dic, &b_gates(b, 0, 0), diff_bias_, action_sum); gemm("C", "N", "T", batch, slc, n_gates * dic, 1.0, b_gates_, n_gates * dic, weights_layer_, n_gates * dic, 0.0, diff_src_layer_, wc); gemm("C", "N", "T", batch, sic, n_gates * dic, 1.0, b_gates_, n_gates * dic, weights_iter_h_, n_gates * dic, 0.0, diff_src_iter_, wc); } void lstm_bwd(alg_t alg, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *diff_src_layer_, float *diff_src_iter_h_, float *diff_src_iter_c_, float *diff_weights_layer_, float *diff_weights_iter_h_, float *diff_bias_, float *b_gates_, const float *src_layer_, const float *src_iter_h_, const float *src_iter_c_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *dst_iter_h_, const float *dst_iter_c_, const float *gates_, const float *diff_dst_layer_, const float *diff_dst_iter_h_, const float *diff_dst_iter_c_) { // TODO: check sic and slc as last dimension in arrays and cycles // input AOC<const float> diff_dst_layer(diff_dst_layer_, batch, wc); AOC<const float> diff_dst_iter_c(diff_dst_iter_c_, batch, wc); AOC<const float> diff_dst_iter_h(diff_dst_iter_h_, batch, wc); AOC<const float> src_iter_c(src_iter_c_, batch, wc); AOC<const float> dst_iter_h(dst_iter_h_, batch, wc); AOC<const float> dst_iter_c(dst_iter_c_, batch, wc); AOC<const float> gates(gates_, batch, n_gates, dic); AOC<float> diff_src_iter_c(diff_src_iter_c_, batch, wc); AOC<float> b_gates(b_gates_, batch, n_gates, dic); const int64_t ohi = 0; const int64_t ohf = 1; const int64_t ohc = 2; const int64_t oho = 3; for (int64_t ib = 0; ib < batch; ib++) for (int64_t ih = 0; ih < dic; ih++) { print(80, "rnn_single_bwd: ib = " IFMT " ih = " IFMT "\n", ib, ih); float ho = gates(ib, oho, ih); float hf = gates(ib, ohf, ih); float hc = gates(ib, ohc, ih); float hi = gates(ib, ohi, ih); float dh = diff_dst_layer(ib, ih) + diff_dst_iter_h(ib, ih); float c = dst_iter_c(ib, ih); float dho = tanhf(c) * dh; b_gates(ib, oho, ih) = x_m_square(ho) * dho; float dc_next = diff_dst_iter_c(ib, ih); float dc = ho * dh * dtanhf(c) + dc_next; diff_src_iter_c(ib, ih) = hf * dc; float c_old = src_iter_c(ib, ih); float dhf = c_old * dc; b_gates(ib, ohf, ih) = x_m_square(hf) * dhf; float dhi = hc * dc; b_gates(ib, ohi, ih) = x_m_square(hi) * dhi; float dhc = hi * dc; b_gates(ib, ohc, ih) = one_m_square(hc) * dhc; } gemm("C", "T", "N", sic, n_gates * dic, batch, 1.0, src_iter_h_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_iter_h_, n_gates * dic); gemm("C", "T", "N", slc, n_gates * dic, batch, 1.0, src_layer_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_layer_, n_gates * dic); gemm("C", "N", "T", batch, sic, n_gates * dic, 1.0, b_gates_, n_gates * dic, weights_iter_h_, n_gates * dic, 0.0, diff_src_iter_h_, wc); gemm("C", "N", "T", batch, slc, n_gates * dic, 1.0, b_gates_, n_gates * dic, weights_layer_, n_gates * dic, 0.0, diff_src_layer_, wc); for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates; j++) for (int64_t k = 0; k < dic; k++) diff_bias_[j * dic + k] += b_gates(i, j, k); } void gru_bwd(alg_t alg, activation_t f, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *diff_src_layer_, float *diff_src_iter_, float *diff_weights_layer_, float *diff_weights_iter_h_, float *diff_bias_, float *b_gates_, const float *src_layer_, const float *src_iter_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *dst_iter_h_, const float *gates_, const float *diff_dst_layer_, const float *diff_dst_iter_h_, float *ws_local_) { AOC<const float> src_iter(src_iter_, batch, wc); AOC<const float> diff_dst_layer(diff_dst_layer_, batch, wc); AOC<const float> diff_dst_iter_h(diff_dst_iter_h_, batch, wc); AOC<const float> gates(gates_, batch, n_gates, dic); AOC<const float> weights_layer(weights_layer_, slc, n_gates, dic); AOC<const float> weights_iter_h(weights_iter_h_, sic, n_gates, dic); AOC<float> diff_src_iter(diff_src_iter_, batch, wc); AOC<float> diff_weights_iter_h(diff_weights_iter_h_, sic, n_gates, dic); AOC<float> b_gates(b_gates_, batch, n_gates, dic); float *dhr_ = ws_local_; float *hr_ = ws_local_ + batch * wc; AOC<float> dhr(dhr_, batch, wc); AOC<float> hr(hr_, batch, wc); // dc = (1 - u) * dh; dc^ = one_m_square(c) * dc; // du = (h - u) * dh; du^ = x_m_square(u) * du; // dhr = Wc dc^; // dr = h * dhr; dr^ = x_m_square(r) * dr; const int64_t ohu = 0; const int64_t ohr = 1; const int64_t ohc = 2; for (int64_t ib = 0; ib < batch; ib++) for (int64_t ih = 0; ih < dic; ih++) { float h = src_iter(ib, ih); float c = gates(ib, ohc, ih); float u = gates(ib, ohu, ih); float dh = diff_dst_layer(ib, ih) + diff_dst_iter_h(ib, ih); float du = (h - c) * dh; float dc = (1.0f - u) * dh; b_gates(ib, ohu, ih) = x_m_square(u) * du; b_gates(ib, ohc, ih) = one_m_square(c) * dc; diff_src_iter(ib, ih) = dh * u; } gemm("C", "N", "T", batch, sic, dic, 1.0, &(b_gates(0, 2, 0)), n_gates * dic, &(weights_iter_h(0, 2, 0)), n_gates * dic, 0.0, dhr_, wc); for (int64_t ib = 0; ib < batch; ib++) for (int64_t ih = 0; ih < dic; ih++) { float h = src_iter(ib, ih); float r = gates(ib, ohr, ih); float dr = h * dhr(ib, ih); hr(ib, ih) = h * r; diff_src_iter(ib, ih) += dhr(ib, ih) * r; b_gates(ib, ohr, ih) = x_m_square(r) * dr; } // dWx += xdu^ | xdr^ | xdc^ // dWh += hdu^ | ddr^ | (h * r)dc^ gemm("C", "T", "N", sic, (n_gates - 1) * dic, batch, 1.0, src_iter_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_iter_h_, n_gates * dic); gemm("C", "T", "N", sic, dic, batch, 1.0, hr_, wc, &(b_gates(0, 2, 0)), n_gates * dic, 1.0, &(diff_weights_iter_h(0, 2, 0)), n_gates * dic); gemm("C", "T", "N", slc, n_gates * dic, batch, 1.0, src_layer_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_layer_, n_gates * dic); // dx_next = Wxudu^ + Wxrdr^ + Wxcdc^ // dh_next = dh * u + Whudu^ + Whzdz^ + r * Whcdc^ gemm("C", "N", "T", batch, sic, (n_gates - 1)* dic, 1.0, b_gates_, n_gates * dic, weights_iter_h_, n_gates * dic, 1.0, diff_src_iter_, wc); gemm("C", "N", "T", batch, slc, n_gates * dic, 1.0, b_gates_, n_gates * dic, weights_layer_, n_gates * dic, 0.0, diff_src_layer_, wc); for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates; j++) for (int64_t k = 0; k < dic; k++) diff_bias_[j * dic + k] += b_gates(i, j, k); } void gru_lbr_bwd(alg_t alg, activation_t f, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *diff_src_layer_, float *diff_src_iter_, float *diff_weights_layer_, float *diff_weights_iter_h_, float *diff_bias_, float *b_gates_, const float *src_layer_, const float *src_iter_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, const float *dst_iter_h_, const float *gates_, const float *diff_dst_layer_, const float *diff_dst_iter_h_, float *ws_local_) { AOC<const float> src_iter(src_iter_, batch, wc); AOC<const float> diff_dst_layer(diff_dst_layer_, batch, wc); AOC<const float> diff_dst_iter_h(diff_dst_iter_h_, batch, wc); AOC<const float> gates(gates_, batch, n_gates, dic); AOC<const float> weights_layer(weights_layer_, slc, n_gates, dic); AOC<const float> weights_iter_h(weights_iter_h_, sic, n_gates, dic); AOC<const float> bias(bias_, n_gates + 1, dic); AOC<float> diff_src_iter(diff_src_iter_, batch, wc); AOC<float> diff_weights_iter_h(diff_weights_iter_h_, dic, n_gates, sic); AOC<float> b_gates(b_gates_, batch, n_gates, dic); float *Wh_b_ = ws_local_; float *b_gates_r_ = ws_local_ + dic * batch; AOC<float> Wh_b(Wh_b_, batch, dic); AOC<float> b_gates_r(b_gates_r_, batch, n_gates, dic); for (int64_t ib = 0; ib < batch; ib++) for (int64_t ih = 0; ih < dic; ih++) Wh_b(ib, ih) = bias(3, ih); gemm("C", "N", "N", batch, dic, sic, 1.0, src_iter_, wc, &weights_iter_h(0, 2, 0), n_gates * dic, 1.0, Wh_b_, dic); // dc = (1 - u) * dh; dc^ = one_m_square(c) * dc; // du = (h - c) * dh; du^ = x_m_square(u) * du; // dr = (Wh + b) * dc^; dr^ = x_m_square(r) * dr; const int64_t ohu = 0; const int64_t ohr = 1; const int64_t ohc = 2; for (int64_t ib = 0; ib < batch; ib++) for (int64_t ih = 0; ih < dic; ih++) { float h = src_iter(ib, ih); float dh = diff_dst_layer(ib, ih) + diff_dst_iter_h(ib, ih); float u = gates(ib, ohu, ih); float r = gates(ib, ohr, ih); float c = gates(ib, ohc, ih); float du = (h - c) * dh; float dc = (1.0f - u) * dh; b_gates(ib, ohu, ih) = x_m_square(u) * du; b_gates(ib, ohc, ih) = one_m_square(c) * dc; float dr = Wh_b(ib, ih) * b_gates(ib, ohc, ih); b_gates(ib, ohr, ih) = x_m_square(r) * dr; b_gates_r(ib, ohu, ih) = b_gates(ib, ohu, ih); b_gates_r(ib, ohr, ih) = b_gates(ib, ohr, ih); b_gates_r(ib, ohc, ih) = b_gates(ib, ohc, ih) * r; diff_src_iter(ib, ih) = dh * u; } gemm("C", "T", "N", sic, n_gates * dic, batch, 1.0, src_iter_, wc, b_gates_r_, n_gates * dic, 1.0, diff_weights_iter_h_, n_gates * dic); gemm("C", "T", "N", slc, n_gates * dic, batch, 1.0, src_layer_, wc, b_gates_, n_gates * dic, 1.0, diff_weights_layer_, n_gates * dic); gemm("C", "N", "T", batch, slc, n_gates * dic, 1.0, b_gates_, n_gates * dic, weights_layer_, n_gates * dic, 0.0, diff_src_layer_, wc); gemm("C", "N", "T", batch, sic, n_gates * dic, 1.0, b_gates_r_, n_gates * dic, weights_iter_h_, n_gates * dic, 1.0, diff_src_iter_, wc); for (int64_t i = 0; i < batch; i++) for (int64_t j = 0; j < n_gates; j++) for (int64_t k = 0; k < dic; k++) diff_bias_[j * dic + k] += b_gates(i, j, k); for (int64_t i = 0; i < batch; i++) for (int64_t k = 0; k < dic; k++) diff_bias_[3 * dic + k] += b_gates_r(i, 2, k); } void rnn_cell_bwd(alg_t alg, activation_t f, int64_t sic, int64_t slc, int64_t dic, int64_t wc, int64_t batch, int64_t n_gates, float *diff_src_layer, float *diff_src_iter_h, float *diff_src_iter_c, float *diff_weights_layer, float *diff_weights_iter, float *diff_bias, float *b_gates, const float *src_layer, const float *src_iter_h, const float *src_iter_c, const float *weights_layer, const float *weights_iter, const float *bias, const float *dst_iter_h, const float *dst_iter_c, const float *gates, const float *diff_dst_layer, const float *diff_dst_iter_h, const float *diff_dst_iter_c, float *ws_local_) { switch (alg) { case VANILLA_LSTM: lstm_bwd(alg, sic, slc, dic, wc, batch, n_gates, diff_src_layer, diff_src_iter_h, diff_src_iter_c, diff_weights_layer, diff_weights_iter, diff_bias, b_gates, src_layer, src_iter_h, src_iter_c, weights_layer, weights_iter, bias, dst_iter_h, dst_iter_c, gates, diff_dst_layer, diff_dst_iter_h, diff_dst_iter_c); break; case VANILLA_RNN: rnn_bwd(alg, f, sic, slc, dic, wc, batch, n_gates, diff_src_layer, diff_src_iter_h, diff_weights_layer, diff_weights_iter, diff_bias, b_gates, src_layer, src_iter_h, weights_layer, weights_iter, bias, dst_iter_h, gates, diff_dst_layer, diff_dst_iter_h); break; case VANILLA_GRU: gru_bwd(alg, f, sic, slc, dic, wc, batch, n_gates, diff_src_layer, diff_src_iter_h, diff_weights_layer, diff_weights_iter, diff_bias, b_gates, src_layer, src_iter_h, weights_layer, weights_iter, bias, dst_iter_h, gates, diff_dst_layer, diff_dst_iter_h, ws_local_); break; case LBR_GRU: gru_lbr_bwd(alg, f, sic, slc, dic, wc, batch, n_gates, diff_src_layer, diff_src_iter_h, diff_weights_layer, diff_weights_iter, diff_bias, b_gates, src_layer, src_iter_h, weights_layer, weights_iter, bias, dst_iter_h, gates, diff_dst_layer, diff_dst_iter_h, ws_local_); default: break; } } void rnn_linear_bwd(const prb_t *p, mkldnn_rnn_direction_t direction, const float *diff_dst_iter_, const float *diff_dst_iter_c_, const float *diff_dst_layer_, const float *weights_layer_, const float *weights_iter_h_, const float *bias_, float *diff_src_iter_, float *diff_src_iter_c_, float *diff_src_layer_, float *diff_weights_layer_, float *diff_weights_iter_h_, float *diff_bias_, float *ws_, const float *gates_) { const alg_t alg = p->alg; const int64_t sic = p->sic; const int64_t slc = p->slc; const int64_t dic = p->dic; const int64_t dlc = p->dlc; const int64_t wc = max(sic, max(slc, dic)); bool is_lbr = p->alg == LBR_GRU; const int64_t batch = p->mb; const int64_t n_gates = p->n_gates(); const int64_t n_states = p->n_states(); const int64_t n_layer = p->n_layer; const int64_t n_iter = p->n_iter; const int64_t n_dir = p->n_directions(); activation_t f = p->activation; const int64_t X = n_states; AOC<const float> bias(bias_, n_layer, n_dir, n_gates + is_lbr, dic); AOC<float> diff_bias(diff_bias_, n_layer, n_dir, n_gates + is_lbr, dic); AOC<const float> weights_layer( weights_layer_, n_layer, n_dir, n_gates * dic, slc); AOC<const float> weights_iter( weights_iter_h_, n_layer, n_dir, n_gates * dic, sic); AOC<float> diff_weights_layer( diff_weights_layer_, n_layer, n_dir, n_gates * dic, slc); AOC<float> diff_weights_iter( diff_weights_iter_h_, n_layer, n_dir, n_gates * dic, sic); auto *b_gates = new float[batch * n_gates * dic]; AOC<float> ws(ws_, n_layer + 2, n_dir, n_iter + 2, n_states, batch, wc); AOC<const float> gates(gates_, n_layer, n_dir, n_iter, batch, n_gates, dic); int64_t wsb_size = (n_layer + 2) * n_dir * (n_iter + 2) * (n_states + 1) * batch * wc; auto *wsb_ = new float[wsb_size]; init_buffer(wsb_, wsb_size, 0.); // ??!! Temporary. For debug. // n_states + 1 -- H, C, X AOC<float> wsb( wsb_, n_layer + 2, n_dir, n_iter + 2, n_states + 1, batch, wc); int64_t ws_local_size; switch (p->alg) { case LBR_GRU: ws_local_size = batch * (n_gates + 1) * dic; break; case VANILLA_GRU: ws_local_size = 2 * batch * wc; break; default: ws_local_size = 0; } float *ws_local_ = new float[ws_local_size]; auto process_direction = [&](rnn_iter_direction_t iter_dir, rnn_layer_direction_t lay_dir, int64_t dir_val, rnn_action_t action) { // we first need to copy the initial states and input into ws // it simplifies the logic in the following code copy_init_bwd(alg, sic, slc, dic, dlc, wc, batch, n_layer, n_iter, n_dir, n_states, wsb_, diff_dst_layer_, diff_dst_iter_, diff_dst_iter_c_, iter_dir, lay_dir, dir_val, direction == mkldnn_bidirectional_concat); // We run the grid of computation for (int64_t j = n_layer - 1; j >= 0; j--) { for (int64_t i = 0; i < n_iter; i++) { int64_t iter = (iter_dir == left2right) ? i + 1 : n_iter - i; int64_t prev_iter = (iter_dir == left2right) ? iter - 1 : iter + 1; int64_t lay = j + 1; int64_t prev_lay = lay + 1; int64_t ws_iter = (iter_dir == left2right) ? iter : iter; int64_t ws_prev_iter = (iter_dir == left2right) ? iter + 1 : iter - 1; rnn_cell_bwd(alg, f, sic, slc, dic, wc, batch, n_gates, &wsb(lay, dir_val, iter, X, 0, 0), &wsb(lay, dir_val, iter, H, 0, 0), &wsb(lay, dir_val, iter, C, 0, 0), &diff_weights_layer(lay - 1, dir_val, 0, 0), &diff_weights_iter(lay - 1, dir_val, 0, 0), &diff_bias(lay - 1, dir_val, 0, 0), b_gates, &ws(lay - 1, dir_val, ws_iter, H, 0, 0), &ws(lay, dir_val, ws_prev_iter, H, 0, 0), &ws(lay, dir_val, ws_prev_iter, C, 0, 0), &weights_layer(lay - 1, dir_val, 0, 0), &weights_iter(lay - 1, dir_val, 0, 0), &bias(lay - 1, dir_val, 0, 0), &ws(lay, dir_val, ws_iter, H, 0, 0), &ws(lay, dir_val, ws_iter, C, 0, 0), &gates(lay - 1, dir_val, ws_iter - 1, 0, 0, 0), &wsb(prev_lay, dir_val, iter, X, 0, 0), &wsb(lay, dir_val, prev_iter, H, 0, 0), &wsb(lay, dir_val, prev_iter, C, 0, 0), ws_local_); } } // Finally we copy the results to the result buffers copy_res_bwd(alg, sic, slc, dic, dlc, wc, batch, n_layer, n_iter, n_dir, n_states, diff_src_iter_, diff_src_iter_c_, diff_src_layer_, wsb_, iter_dir, lay_dir, dir_val, action); }; switch (direction) { case mkldnn_unidirectional_left2right: process_direction(right2left, top2bottom, 0, action_copy); break; case mkldnn_unidirectional_right2left: process_direction(left2right, top2bottom, 0, action_copy); break; case mkldnn_bidirectional_sum: process_direction(right2left, top2bottom, 0, action_copy); process_direction(left2right, top2bottom, 1, action_sum); break; case mkldnn_bidirectional_concat: process_direction(right2left, top2bottom, 0, action_copy); process_direction(left2right, top2bottom, 1, action_sum); break; default: assert("unknown direction"); break; } delete[] wsb_; delete[] b_gates; delete[] ws_local_; } void compute_ref_bwd(const prb_t *p, dnn_mem_t &input_m, dnn_mem_t &states_m, dnn_mem_t &c_states_m, dnn_mem_t &diff_last_layer_m, dnn_mem_t &diff_last_iteration_m, dnn_mem_t &diff_c_last_iteration_m, dnn_mem_t &weights_input_m, dnn_mem_t &weights_states_m, dnn_mem_t &bias_m, dnn_mem_t &dst_last_layer_m, dnn_mem_t &dst_last_iteration_m, dnn_mem_t &dst_c_last_iteration_m, dnn_mem_t &dst_diff_input_m, dnn_mem_t &dst_diff_states_m, dnn_mem_t &dst_diff_c_states_m, dnn_mem_t &dst_diff_weights_input_m, dnn_mem_t &dst_diff_weights_states_m, dnn_mem_t &dst_diff_bias_m, mkldnn_rnn_direction_t direction) { // !! TODO: add support of strides assert(direction == mkldnn_unidirectional_left2right || direction == mkldnn_unidirectional_right2left || direction == mkldnn_bidirectional_sum || direction == mkldnn_bidirectional_concat); assert(p->dlc == p->dic); int64_t wc = max(p->sic, max(p->slc, p->dic)); int64_t ws_size = (p->n_layer + 2) * p->n_directions() * (p->n_iter + 2) * p->n_states() * p->mb * wc; auto *ws = new float[ws_size]; init_buffer(ws, ws_size, -55.); // ??!! Temporary. For debug. int64_t gates_size = p->n_layer * p->n_directions() * p->n_iter * p->mb * p->n_gates() * p->dic; auto *gates = new float[gates_size]; rnn_linear_fwd(p, direction, (float *)states_m, (float *)c_states_m, (float *)input_m, (float *)weights_input_m, (float *)weights_states_m, (float *)bias_m, (float *)dst_last_iteration_m, (float *)dst_c_last_iteration_m, (float *)dst_last_layer_m, ws, gates); rnn_linear_bwd(p, direction, (float *)diff_last_iteration_m, (float *)diff_c_last_iteration_m, (float *)diff_last_layer_m, (float *)weights_input_m, (float *)weights_states_m, (float *)bias_m, (float *)dst_diff_states_m, (float *)dst_diff_c_states_m, (float *)dst_diff_input_m, (float *)dst_diff_weights_input_m, (float *)dst_diff_weights_states_m, (float *)dst_diff_bias_m, ws, gates); delete[] ws; delete[] gates; } } // namespace rnn <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/dual_net/tpu_dual_net.cc<|end_filename|> // Copyright 2018 Google LLC // // 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/dual_net/tpu_dual_net.h" #include <algorithm> #include <cstddef> #include <memory> #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/match.h" #include "REDACTEDstrings/numbers.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/string_view.h" #include "REDACTEDstrings/strip.h" #include "REDACTEDtypes/span.h" #include "REDACTEDinference/runner/options.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "third_party/tensorflow/cc/saved_model/signature_constants.h" #include "third_party/tensorflow/cc/saved_model/tag_constants.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/types.proto.h" #include "third_party/tensorflow/core/lib/core/errors.h" #include "third_party/tensorflow/core/lib/core/status.h" #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/platform/logging.h" #include "third_party/tensorflow/core/platform/protobuf.h" #include "third_party/tensorflow/core/protobuf/config.proto.h" #include "third_party/tensorflow/core/public/session.h" #include "third_party/tensorflow/core/public/session_options.h" #include "third_party/tracing_framework_bindings_cpp/macros.h" namespace minigo { namespace { // A GraphDef containing the ops required to initialize and shutdown a TPU. // This proto was generated from the script oneoffs/generate_tpu_graph_def.py. constexpr auto kTpuOpsGraphDef = R"( node { name: "ConfigureDistributedTPU" op: "ConfigureDistributedTPU" device: "/device:TPU_SYSTEM:0" attr { key: "embedding_config" value { s: "" } } attr { key: "is_global_init" value { b: false } } attr { key: "tpu_embedding_config" value { s: "" } } } node { name: "ShutdownDistributedTPU" op: "ShutdownDistributedTPU" device: "/device:TPU_SYSTEM:0" } library { } )"; std::unique_ptr<tensorflow::Session> CreateSession( const tensorflow::GraphDef& graph_def, const std::string& tpu_name) { // The following check is commented out since we are running the script on // REDACTED TPU instead of cloud TPU for now. // Make sure tpu_name is a gRPC address of cloud TPU. // MG_CHECK(absl::StartsWith(tpu_name, "grpc://")); tensorflow::SessionOptions options; options.target = tpu_name; options.config.set_allow_soft_placement(true); options.config.set_log_device_placement(true); std::unique_ptr<tensorflow::Session> session(tensorflow::NewSession(options)); TF_CHECK_OK(session->Create(graph_def)); return session; } } // namespace TpuDualNet::TpuDualNet(const std::string& graph_path, const FeatureDescriptor& feature_desc, const std::string& tpu_name) : Model(std::string(file::Stem(graph_path)), feature_desc), tpu_name_(tpu_name), graph_path_(graph_path), feature_descriptor_(feature_desc) { TF_CHECK_OK(GetModel()); } TpuDualNet::~TpuDualNet() { absl::MutexLock lock(&mutex_); LOG(INFO) << "Shutting down TPU for TpuDualNet" << std::endl; saved_model_bundle_.session.reset(); } void TpuDualNet::RunMany(const std::vector<const ModelInput*>& inputs, std::vector<ModelOutput*>* outputs, std::string* model_name) { auto input_size = static_cast<int>(inputs.size()); MG_CHECK(input_size > 0); switch (feature_descriptor_.layout) { case FeatureDescriptor::Layout::kNhwc: input_ = tensorflow::Tensor(input_type_, tensorflow::TensorShape({ static_cast<int>(input_size), kN, kN, feature_descriptor().num_planes, })); break; case FeatureDescriptor::Layout::kNchw: input_ = tensorflow::Tensor(input_type_, tensorflow::TensorShape({ static_cast<int>(input_size), feature_descriptor().num_planes, kN, kN, })); break; } batch_capacity_ = input_size; WTF_SCOPE("TpuDualNet::Run: inputs, capacity", size_t, size_t) (input_size, batch_capacity_); { WTF_SCOPE("SetFeatures: inputs", size_t)(input_size); if (input_type_ == tensorflow::DT_FLOAT) { Tensor<float> features(feature_descriptor_.GetInputShape(input_size), input_.flat<float>().data()); feature_descriptor().set_floats(inputs, &features); } else { static_assert(sizeof(bool) == sizeof(uint8_t), "bool must be 1 byte"); Tensor<uint8_t> features( feature_descriptor_.GetInputShape(input_size), reinterpret_cast<uint8_t*>(input_.flat<bool>().data())); feature_descriptor().set_bytes(inputs, &features); } } // Run the model. { WTF_SCOPE("Session::Run: inputs, capacity", size_t, size_t) (inputs.size(), batch_capacity_); run_outputs_.clear(); TF_CHECK_OK(session_->Run({{input_tensor_names_, input_}}, output_tensor_names_, {}, &run_outputs_)); } // Copy the policy and value out of the output tensors. { WTF_SCOPE("GetOutputs: outputs", size_t)(run_outputs_.size()); const auto& tensor_0 = run_outputs_[0].flat<float>(); const auto& tensor_1 = run_outputs_[1].flat<float>(); Tensor<float> policy; Tensor<float> value; if (output_key_[0] == "policy_output") { policy = Tensor<float>({input_size, kNumMoves}, tensor_0.data()); value = Tensor<float>({input_size}, tensor_1.data()); } else { MG_CHECK(output_key_[1] == "policy_output"); policy = Tensor<float>({input_size, kNumMoves}, tensor_1.data()); value = Tensor<float>({input_size}, tensor_0.data()); } Model::GetOutputs(inputs, policy, value, outputs); } if (model_name != nullptr) { *model_name = graph_path_; } } TpuDualNetFactory::TpuDualNetFactory(std::string tpu_name) : tpu_name_(std::move(tpu_name)) { // Create a session containing ops for initializing & shutting down a TPU. tensorflow::GraphDef graph_def; ::tensorflow::protobuf::TextFormat::ParseFromString(kTpuOpsGraphDef, &graph_def); main_session_ = CreateSession(graph_def, tpu_name_); MG_LOG(INFO) << "Initializing TPU " << tpu_name_; TF_CHECK_OK(main_session_->Run({}, {}, {"ConfigureDistributedTPU"}, nullptr)); } TpuDualNetFactory::~TpuDualNetFactory() { MG_LOG(INFO) << "Shutting down TPU " << tpu_name_; TF_CHECK_OK(main_session_->Run({}, {}, {"ShutdownDistributedTPU"}, nullptr)); MG_LOG(INFO) << "Closing main session"; TF_CHECK_OK(main_session_->Close()); } tensorflow::Status TpuDualNet::GetModel() { absl::MutexLock lock(&mutex_); tensorflow::RunOptions run_options; std::unordered_set<std::string> tags = {tensorflow::kSavedModelTagServe, tensorflow::kSavedModelTagTpu}; tensorflow::SessionOptions session_options; session_options.target = tpu_name_; session_options.config.set_allow_soft_placement(true); session_options.config.set_log_device_placement(true); TF_CHECK_OK(tensorflow::LoadSavedModel( session_options, run_options, graph_path_, tags, &saved_model_bundle_)); // Get names of input and output tensors from signature. auto iter = saved_model_bundle_.meta_graph_def.signature_def().find( tensorflow::kDefaultServingSignatureDefKey); if (iter == saved_model_bundle_.meta_graph_def.signature_def().end()) { LOG(ERROR) << tensorflow::errors::InvalidArgument( absl::StrCat("Could not find SignatureDef with key: serving_default")); } signature_def_ = iter->second; for (const auto& input : signature_def_.inputs()) { input_tensor_names_ = input.second.name(); input_type_ = input.second.dtype(); } for (const auto& output : signature_def_.outputs()) { output_tensor_names_.push_back(output.second.name()); output_key_.push_back(output.first); } session_ = std::move(saved_model_bundle_.session); return tensorflow::Status::OK(); } std::unique_ptr<Model> TpuDualNetFactory::NewModel(const ModelDefinition& def) { // const std::string& descriptor) { MG_CHECK(def.metadata.Get<std::string>("engine") == "tpu"); auto feature_desc = FeatureDescriptor::Create(def.metadata.Get<std::string>("input_features"), def.metadata.Get<std::string>("input_layout")); // strip the .minigo at the end to use the savedmodel api std::string model_path = def.path; auto it = model_path.find(".minigo"); if (it != std::string::npos) { model_path.erase(model_path.size() - 7); } return absl::make_unique<TpuDualNet>(model_path, feature_desc, tpu_name_); } } // namespace minigo <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/lingvo/core/ops/tokenizer_op_headers.h<|end_filename|> /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef LINGVO_CORE_OPS_TOKENIZER_OP_HEADERS_H_ #define LINGVO_CORE_OPS_TOKENIZER_OP_HEADERS_H_ #include <algorithm> #include <string> #include <unordered_map> #include <vector> #include "third_party/tensorflow/core/framework/op_kernel.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/tensor_shape.h" #include "third_party/tensorflow/core/lib/strings/str_util.h" #include "third_party/tensorflow/core/platform/env.h" namespace tensorflow { namespace babelfish { namespace { template <typename TokenizerClass> class LabelToTokenIdOp : public OpKernel { public: explicit LabelToTokenIdOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("append_eos", &append_eos_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("maxlen", &maxlen_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("pad_to_maxlen", &pad_to_maxlen_)); } void Compute(OpKernelContext* ctx) override { const Tensor& labels = ctx->input(0); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(labels.shape()), errors::InvalidArgument("labels must be a vector, but get ", labels.shape().DebugString())); const int batch = labels.NumElements(); auto Tlabels = labels.flat<tstring>(); Tensor token_ids(DT_INT32, TensorShape({batch, maxlen_})); auto Ttoken_ids = token_ids.matrix<int32>(); Ttoken_ids.setZero(); // Sanity Tensor target_ids(DT_INT32, TensorShape({batch, maxlen_})); auto Ttarget_ids = target_ids.matrix<int32>(); Ttarget_ids.setZero(); // Sanity Tensor paddings(DT_FLOAT, TensorShape({batch, maxlen_})); auto Tpaddings = paddings.matrix<float>(); Tpaddings.setZero(); // Sanity int actual_maxlen = pad_to_maxlen_ ? maxlen_ : 0; for (int i = 0; i < batch; ++i) { VLOG(1) << i << " " << Tlabels(i); std::vector<int32> ids = TokenizerClass::StringToIds(Tlabels(i)); if (ids.size() + 1 > maxlen_) { LOG(WARNING) << "Too long target " << ids.size() << " " << Tlabels(i); ids.resize(maxlen_ - 1); } const int id_size = ids.size(); const int32 kSOS = 1; const int32 kEOS = 2; Ttoken_ids(i, 0) = kSOS; for (int j = 0; j < id_size; ++j) { Ttoken_ids(i, j + 1) = ids[j]; Ttarget_ids(i, j) = ids[j]; Tpaddings(i, j) = 0.0; // padding = false } Ttarget_ids(i, id_size) = kEOS; Tpaddings(i, id_size) = append_eos_ ? 0.0 : 1.0; actual_maxlen = std::max(actual_maxlen, id_size + 1); for (int j = id_size + 1; j < maxlen_; ++j) { Ttoken_ids(i, j) = kEOS; Ttarget_ids(i, j) = kEOS; Tpaddings(i, j) = 1.0; // padding = true } } Tensor out_token_ids(DT_INT32, TensorShape({batch, actual_maxlen})); Tensor out_target_ids(DT_INT32, TensorShape({batch, actual_maxlen})); Tensor out_paddings(DT_FLOAT, TensorShape({batch, actual_maxlen})); typedef const Eigen::DSizes<Eigen::DenseIndex, 2> DSize2; out_token_ids.matrix<int32>() = Ttoken_ids.slice(DSize2{0, 0}, DSize2{batch, actual_maxlen}); out_target_ids.matrix<int32>() = Ttarget_ids.slice(DSize2{0, 0}, DSize2{batch, actual_maxlen}); out_paddings.matrix<float>() = Tpaddings.slice(DSize2{0, 0}, DSize2{batch, actual_maxlen}); OP_REQUIRES_OK(ctx, ctx->set_output("token_ids", out_token_ids)); OP_REQUIRES_OK(ctx, ctx->set_output("target_ids", out_target_ids)); OP_REQUIRES_OK(ctx, ctx->set_output("paddings", out_paddings)); } private: bool append_eos_ = true; int maxlen_ = 0; bool pad_to_maxlen_ = true; }; template <typename TokenizerClass> class IdToTokenOp : public OpKernel { public: explicit IdToTokenOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { const Tensor& ids = ctx->input(0); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(ids.shape()), errors::InvalidArgument("token_ids must be a matrix, but get ", ids.shape().DebugString())); const Tensor& seq_lens = ctx->input(1); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(seq_lens.shape()), errors::InvalidArgument("seq_lens must be a vector, but get ", seq_lens.shape().DebugString())); const int batch = seq_lens.NumElements(); OP_REQUIRES(ctx, batch == ids.dim_size(0), errors::InvalidArgument( "batch size has to match between token_ids and seq_lens. ", ids.shape().DebugString(), " vs. ", seq_lens.shape().DebugString())); Tensor* out; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({batch}), &out)); const auto& t_ids = ids.matrix<int32>(); const auto& t_seq_lens = seq_lens.vec<int32>(); auto t_out = out->template vec<tstring>(); for (int i = 0; i < batch; ++i) { const int len_i = std::max(0, t_seq_lens(i)); std::vector<int32> ids_i(len_i); for (int j = 0; j < len_i; ++j) { ids_i[j] = t_ids(i, j); } std::vector<string> labels = TokenizerClass::IdToStrings(ids_i); t_out(i) = TokenizerClass::JoinLabels(labels); } } }; } // namespace } // namespace babelfish } // namespace tensorflow #endif // LINGVO_CORE_OPS_TOKENIZER_OP_HEADERS_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ocl_engine.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_ENGINE_HPP #define OCL_ENGINE_HPP #include "mkldnn.h" #include "common/c_types_map.hpp" #include "common/engine.hpp" #include "common/stream.hpp" #include "common/utils.hpp" #include "ocl/cl_device_info.hpp" #include "ocl/cl_engine.hpp" #include "ocl/ocl_utils.hpp" namespace mkldnn { namespace impl { namespace ocl { class ocl_engine_t : public cl_engine_t { public: static status_t get_ocl_devices(std::vector<cl_device_id> *devices); ocl_engine_t(cl_device_id adevice) : cl_engine_t(engine_kind::gpu, backend_kind::ocl, cl_device_info_t(adevice)) , device_(adevice) , context_(nullptr) , is_user_context_(false) {} ocl_engine_t(cl_device_id adevice, cl_context acontext) : cl_engine_t(engine_kind::gpu, backend_kind::ocl, cl_device_info_t(adevice)) , device_(adevice) , context_(acontext) , is_user_context_(true) {} virtual ~ocl_engine_t() override { if (context_) { clReleaseContext(context_); } } status_t init(); virtual status_t create_memory_storage(memory_storage_t **storage, unsigned flags, size_t size, void *handle) override; virtual status_t create_stream(stream_t **stream, unsigned flags) override; status_t create_stream(stream_t **stream, cl_command_queue queue); virtual const concat_primitive_desc_create_f * get_concat_implementation_list() const override; virtual const reorder_primitive_desc_create_f * get_reorder_implementation_list() const override; virtual const sum_primitive_desc_create_f * get_sum_implementation_list() const override; virtual const primitive_desc_create_f * get_implementation_list() const override; cl_device_id device() const { return device_; } cl_context context() const { return context_; } virtual cl_device_id ocl_device() const override { return device(); } virtual cl_context ocl_context() const override { return context(); } stream_t *service_stream() const { return service_stream_.get(); } private: cl_device_id device_; cl_context context_; bool is_user_context_; std::unique_ptr<stream_t> service_stream_; }; class ocl_engine_factory_t : public engine_factory_t { public: virtual size_t count() const override { std::vector<cl_device_id> ocl_devices; status_t status = ocl_utils::get_ocl_devices(&ocl_devices, CL_DEVICE_TYPE_GPU); if (status != status::success) return status; return ocl_devices.size(); } virtual status_t engine_create( engine_t **engine, size_t index) const override { status_t status; std::vector<cl_device_id> ocl_devices; status = ocl_utils::get_ocl_devices(&ocl_devices, CL_DEVICE_TYPE_GPU); if (status != status::success) return status; if (index >= ocl_devices.size()) return status::invalid_arguments; auto *ocl_engine = new ocl_engine_t(ocl_devices[index]); if (!ocl_engine) return status::out_of_memory; status = ocl_engine->init(); if (status != status::success) { delete ocl_engine; return status; } *engine = ocl_engine; return status::success; } status_t engine_create( engine_t **engine, cl_device_id device, cl_context context) { auto *ocl_engine = new ocl_engine_t(device, context); if (!ocl_engine) return status::out_of_memory; status_t status = ocl_engine->init(); if (status != status::success) { delete ocl_engine; return status; } *engine = ocl_engine; return status::success; } }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/eltwise/ref_eltwise.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "src/common/mkldnn_thread.hpp" #include "eltwise/eltwise.hpp" namespace eltwise { void compute_ref_fwd(const prb_t *p, const dnn_mem_t &src, dnn_mem_t &dst) { const float *src_ptr = (const float *)src; float *dst_ptr = (float *)dst; const auto nelems = src.nelems(); mkldnn::impl::parallel_nd(nelems, [&](int64_t i) { dst_ptr[i] = compute_eltwise_fwd(p->alg, src_ptr[i], 1.0, p->alpha, p->beta); }); } void compute_ref_bwd(const prb_t *p, const dnn_mem_t &src, const dnn_mem_t &diff_dst, dnn_mem_t &diff_src) { const float *src_ptr = (const float *)src; const float *d_dst_ptr = (const float *)diff_dst; float *d_src_ptr = (float *)diff_src; const auto nelems = src.nelems(); mkldnn::impl::parallel_nd(nelems, [&](int64_t i) { d_src_ptr[i] = compute_eltwise_bwd( p->alg, d_dst_ptr[i], src_ptr[i], p->alpha, p->beta); }); } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/normalized_convolution.cc<|end_filename|> /* * 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. */ /*! * Copyright (c) 2017 by Contributors * \file normalized_convolution.cc * \brief * \author <NAME> */ #include "./normalized_convolution-inl.h" #include "../elemwise_op_common.h" #include "../operator_common.h" #if MXNET_USE_NNPACK == 1 #include "../nnpack/nnpack_pooling-inl.h" #endif // MXNET_USE_NNPACK namespace mxnet { namespace op { DMLC_REGISTER_PARAMETER(NormalizedConvolutionParam); static inline index_t AddPad(index_t dsize, index_t pad) { return dsize + 2 * pad; } static inline std::vector<std::string> ListArguments(const NormalizedConvolutionParam& param_) { if (!param_.no_equiv_scale_bias) { return {"data", "equiv_scale", "equiv_bias", "mean", "var", "weight"}; } else { return {"data", "weight"}; } } static bool NormalizedConvolutionShape(const nnvm::NodeAttrs& attrs, std::vector<TShape> *in_shape, std::vector<TShape> *out_shape) { using namespace mshadow; const NormalizedConvolutionParam& param_ = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); if (!param_.no_equiv_scale_bias) { CHECK_EQ(in_shape->size(), static_cast<size_t>(normalized_conv::kNumInputs)) << "Input:[data, equiv_scale, equiv_bias, mean, var, gamma, beta, weight]"; } else { CHECK_EQ(in_shape->size(), static_cast<size_t>(normalized_conv::kNumInputsNoEquivScaleBias)) << "Input:[data, weight]"; } int weight_idx = normalized_conv::WeightIdx(param_.no_equiv_scale_bias); out_shape->resize(normalized_conv::kNumOutputs, TShape()); const TShape &dshp = (*in_shape)[normalized_conv::kData]; if (dshp.ndim() == 0) return false; SHAPE_ASSIGN_CHECK(*out_shape, normalized_conv::kSum, Shape1(param_.num_filter)); SHAPE_ASSIGN_CHECK(*out_shape, normalized_conv::kSumOfSquares, Shape1(param_.num_filter)); if (param_.kernel.ndim() == 1) { // 1d conv CHECK_EQ(dshp.ndim(), 3U) << "Input data should be 3D in batch-num_filter-x"; Shape<3> dshape = ConvertLayout(dshp.get<3>(), param_.layout.value(), kNCW); Shape<3> wshape = Shape3(param_.num_filter / param_.num_group, dshape[1] / param_.num_group, param_.kernel[0]); wshape = ConvertLayout(wshape, kNCW, param_.layout.value()); wshape[0] *= param_.num_group; SHAPE_ASSIGN_CHECK(*in_shape, weight_idx, wshape); if (!param_.no_equiv_scale_bias) { SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kEquivScale, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kEquivBias, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kMean, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kVar, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kGamma, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kBeta, Shape1(dshape[1])); } const index_t dilated_ksize_x = param_.DilatedKernelSize(0); CHECK_EQ(dshape[1] % param_.num_group, 0U) \ << "input num_filter must divide group size"; CHECK_EQ(param_.num_filter % param_.num_group, 0U) \ << "output num_filter must divide group size"; CHECK_GT(param_.kernel.Size(), 0U) \ << "incorrect kernel size: " << param_.kernel; CHECK_GT(param_.stride.Size(), 0U) \ << "incorrect stride size: " << param_.stride; CHECK_GT(param_.dilate.Size(), 0U) \ << "incorrect dilate size: " << param_.dilate; Shape<3> oshape; oshape[0] = dshape[0]; oshape[1] = param_.num_filter; oshape[2] = dshape[2] ? (AddPad(dshape[2], param_.pad[0]) - dilated_ksize_x) / param_.stride[0] + 1 : 0; SHAPE_ASSIGN_CHECK(*out_shape, 0, ConvertLayout(oshape, kNCW, param_.layout.value())); // Perform incomplete shape inference. Fill in the missing values in data shape. // 1) We can always fill in the batch_size. // 2) We can back-calculate the input height/width if the corresponding stride is 1. oshape = ConvertLayout((*out_shape)[0].get<3>(), param_.layout.value(), kNCW); dshape[0] = oshape[0]; if (oshape[2] && param_.stride[0] == 1) { dshape[2] = oshape[2] + dilated_ksize_x - 1 - 2 * param_.pad[0]; } SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kData, ConvertLayout(dshape, kNCW, param_.layout.value())); // Check whether the kernel sizes are valid if (dshape[2] != 0) { CHECK_LE(dilated_ksize_x, AddPad(dshape[2], param_.pad[0])) << "kernel size exceed input"; } return true; } else if (param_.kernel.ndim() == 2) { // 2d conv CHECK_EQ(dshp.ndim(), 4U) \ << "Input data should be 4D in batch-num_filter-y-x"; Shape<4> dshape = ConvertLayout(dshp.get<4>(), param_.layout.value(), kNCHW); Shape<4> wshape = Shape4(param_.num_filter / param_.num_group, dshape[1] / param_.num_group, param_.kernel[0], param_.kernel[1]); wshape = ConvertLayout(wshape, kNCHW, param_.layout.value()); wshape[0] *= param_.num_group; SHAPE_ASSIGN_CHECK(*in_shape, weight_idx, wshape); if (!param_.no_equiv_scale_bias) { SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kEquivScale, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kEquivBias, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kMean, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kVar, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kGamma, Shape1(dshape[1])); SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kBeta, Shape1(dshape[1])); } const index_t dilated_ksize_y = param_.DilatedKernelSize(0); const index_t dilated_ksize_x = param_.DilatedKernelSize(1); CHECK_EQ(dshape[1] % param_.num_group, 0U) \ << "input num_filter must divide group size"; CHECK_EQ(param_.num_filter % param_.num_group, 0U) \ << "output num_filter must divide group size"; CHECK_GT(param_.kernel.Size(), 0U) \ << "incorrect kernel size: " << param_.kernel; CHECK_GT(param_.stride.Size(), 0U) \ << "incorrect stride size: " << param_.stride; CHECK_GT(param_.dilate.Size(), 0U) \ << "incorrect dilate size: " << param_.dilate; Shape<4> oshape; oshape[0] = dshape[0]; oshape[1] = param_.num_filter; oshape[2] = dshape[2] ? (AddPad(dshape[2], param_.pad[0]) - dilated_ksize_y) / param_.stride[0] + 1 : 0; oshape[3] = dshape[3] ? (AddPad(dshape[3], param_.pad[1]) - dilated_ksize_x) / param_.stride[1] + 1 : 0; SHAPE_ASSIGN_CHECK(*out_shape, 0, ConvertLayout(oshape, kNCHW, param_.layout.value())); // Perform incomplete shape inference. Fill in the missing values in data shape. // 1) We can always fill in the batch_size. // 2) We can back-calculate the input height/width if the corresponding stride is 1. oshape = ConvertLayout((*out_shape)[0].get<4>(), param_.layout.value(), kNCHW); dshape[0] = oshape[0]; if (oshape[2] && param_.stride[0] == 1) { dshape[2] = oshape[2] + dilated_ksize_y - 1 - 2 * param_.pad[0]; } if (oshape[3] && param_.stride[1] == 1) { dshape[3] = oshape[3] + dilated_ksize_x - 1 - 2 * param_.pad[1]; } SHAPE_ASSIGN_CHECK(*in_shape, normalized_conv::kData, ConvertLayout(dshape, kNCHW, param_.layout.value())); // Check whether the kernel sizes are valid if (dshape[2] != 0) { CHECK_LE(dilated_ksize_y, AddPad(dshape[2], param_.pad[0])) << "kernel size exceed input"; } if (dshape[3] != 0) { CHECK_LE(dilated_ksize_x, AddPad(dshape[3], param_.pad[1])) << "kernel size exceed input"; } return true; } else if (param_.kernel.ndim() == 3) { LOG(FATAL) << "3D NormalizedConvolution not supported."; return true; } else { LOG(FATAL) << "Unknown normalizedConvolution type"; return false; } } static bool NormalizedConvolutionType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_type, std::vector<int> *out_type) { const NormalizedConvolutionParam& param_ = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); CHECK_GE(in_type->size(), 1U); int dtype = (*in_type)[0]; CHECK_NE(dtype, -1) << "First input must have specified type"; // For float16 input type, the equiv_scale, equiv_bias, weights and output are also float16, // but the mean and var inputs, and the sum and sum_of_squares outputs are stored in float32. int dtype_statistics; MSHADOW_REAL_TYPE_SWITCH_EX(dtype, DTypeX, AccRealX, { dtype_statistics = mshadow::DataType<AccRealX>::kFlag; }); // Default expected input dtype matches that of the 1st (i.e. data) input. std::vector<int> input_types(in_type->size(), dtype); // However the 'mean', 'var', 'gamma' and 'beta' inputs, if present, may have increased precision. if (!param_.no_equiv_scale_bias) { input_types[normalized_conv::kMean] = dtype_statistics; input_types[normalized_conv::kVar] = dtype_statistics; input_types[normalized_conv::kGamma] = dtype_statistics; input_types[normalized_conv::kBeta] = dtype_statistics; } for (size_t i = 0; i < in_type->size(); ++i) { int expected_type = input_types[i]; if ((*in_type)[i] == -1) { (*in_type)[i] = expected_type; } else { UNIFORM_TYPE_CHECK((*in_type)[i], expected_type, ListArguments(param_)[i]); } } out_type->clear(); // 1st data output is of type 'dtype', rest are of greater precision 'dtype_statistics' out_type->push_back(dtype); while (out_type->size() < static_cast<size_t>(normalized_conv::kNumOutputs)) out_type->push_back(dtype_statistics); return true; } void NormalizedConvolutionParamParser(nnvm::NodeAttrs* attrs) { using namespace mshadow; NormalizedConvolutionParam param_; try { param_.Init(attrs->dict); } catch (const dmlc::ParamError& e) { std::ostringstream os; os << e.what(); os << ", in operator " << attrs->op->name << "(" << "name=\"" << attrs->name << "\""; for (const auto& k : attrs->dict) { os << ", " << k.first << "=\"" << k.second << "\""; } os << ")"; throw dmlc::ParamError(os.str()); } if (param_.kernel.ndim() == 1) { param_.layout = param_.layout? param_.layout.value() : mshadow::kNCW; if (param_.stride.ndim() == 0) param_.stride = Shape1(1); if (param_.dilate.ndim() == 0) param_.dilate = Shape1(1); if (param_.pad.ndim() == 0) param_.pad = Shape1(0); } else if (param_.kernel.ndim() == 2) { param_.layout = param_.layout ? param_.layout.value() : mshadow::kNCHW; if (param_.stride.ndim() == 0) param_.stride = Shape2(1, 1); if (param_.dilate.ndim() == 0) param_.dilate = Shape2(1, 1); if (param_.pad.ndim() == 0) param_.pad = Shape2(0, 0); } else { CHECK_EQ(param_.kernel.ndim(), 3U) << param_.kernel.ndim() << "3D NormalizedConvolution not supported"; param_.layout = param_.layout ? param_.layout.value(): mshadow::kNCDHW; if (param_.stride.ndim() == 0) param_.stride = Shape3(1, 1, 1); if (param_.dilate.ndim() == 0) param_.dilate = Shape3(1, 1, 1); if (param_.pad.ndim() == 0) param_.pad = Shape3(0, 0, 0); } CHECK_EQ(param_.kernel.ndim(), param_.stride.ndim()) << "Stride must have the same number of dimensions with kernel_size," << "but kernel_size is set to " << param_.kernel << " while stride is " << param_.stride; CHECK_EQ(param_.kernel.ndim(), param_.dilate.ndim()) << "Dilate must have the same number of dimensions with kernel_size," << "but kernel_size is set to " << param_.kernel << " while dilate is " << param_.dilate; CHECK_EQ(param_.kernel.ndim(), param_.pad.ndim()) << "Padding must have the same number of dimensions with kernel_size," << "but kernel_size is set to " << param_.kernel << " while padding is " << param_.pad; attrs->parsed = std::move(param_); } struct NormalizedConvolutionGrad { const char *op_name; std::vector<nnvm::NodeEntry> operator()(const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) const { const NormalizedConvolutionParam& param_ = nnvm::get<NormalizedConvolutionParam>(n->attrs.parsed); size_t num_fwd_inputs = n->inputs.size(); size_t num_fwd_outputs = n->num_outputs(); if (!param_.no_equiv_scale_bias) { CHECK_EQ(num_fwd_inputs, static_cast<size_t>(normalized_conv::kNumInputs)) << "Input:[data, equiv_scale, equiv_bias, mean, var, gamma, beta, weight]"; } else { CHECK_EQ(num_fwd_inputs, static_cast<size_t>(normalized_conv::kNumInputsNoEquivScaleBias)) << "Input:[data, weight]"; } std::vector<nnvm::NodeEntry> heads; // We copy the outputs and the inputs of the forward node to the inputs of the backward node, // with the one *important* exception that the first backward input is the gradient of the first // output, not the output itself. The benefit is that vectors of the forward node output- // and input-shapes are easily obtained, as is useful for operator instance lookup and init. std::vector<nnvm::NodeEntry> out_data(num_fwd_outputs); for (uint32_t i = 0; i < out_data.size(); ++i) { out_data[i] = nnvm::NodeEntry{n, i, 0}; } // The one data output gradient, the remainder of the outputs, and all forward node inputs // are inputs of the backward node. heads.reserve(num_fwd_outputs + num_fwd_inputs); CHECK_GT(ograds.size(), normalized_conv::kData) << "Not enough gradients of NormalizedConvolution node."; // Copy all outputs of forward node to the backward node, but use the gradient of the primary // output, instead of the output itself. Rest are copied to have shape info readily available. for (uint32_t i = 0; i < num_fwd_outputs; ++i) { heads.push_back((i == normalized_conv::kOut) ? ograds[i] : out_data[i]); } // Copy all inputs of forward node to backward node for (uint32_t i = 0; i < num_fwd_inputs; ++i) { heads.push_back(n->inputs[i]); } nnvm::NodePtr gnode = nnvm::Node::Create(); gnode->inputs = std::move(heads); gnode->control_deps.emplace_back(n); gnode->attrs = n->attrs; gnode->attrs.op = nnvm::Op::Get("_backward_NormalizedConvolution"); gnode->attrs.name = n->attrs.name + "_backward"; std::vector<nnvm::NodeEntry> in_grad(num_fwd_inputs); for (uint32_t i = 0; i < num_fwd_inputs; ++i) { in_grad[i] = nnvm::NodeEntry{gnode, i, 0}; } return in_grad; } }; NNVM_REGISTER_OP(NormalizedConvolution) .describe(R"code(Compute *N*-D normalizedConvolution on *(N+2)*-D input. ******** Documentation not yet correct for this fused normalized convolution!! ************* In the 2-D normalizedConvolution, given input data with shape *(batch_size, channel, height, width)*, the output is computed by .. math:: out[n,i,:,:] = bias[i] + \sum_{j=0}^{channel} data[n,j,:,:] \star weight[i,j,:,:] where :math:`\star` is the 2-D cross-correlation operator. For general 2-D normalizedConvolution, the shapes are - **data**: *(batch_size, channel, height, width)* - **weight**: *(num_filter, channel, kernel[0], kernel[1])* - **bias**: *(num_filter,)* - **out**: *(batch_size, num_filter, out_height, out_width)*. Define:: f(x,k,p,s,d) = floor((x+2*p-d*(k-1)-1)/s)+1 then we have:: out_height=f(height, kernel[0], pad[0], stride[0], dilate[0]) out_width=f(width, kernel[1], pad[1], stride[1], dilate[1]) If ``no_bias`` is set to be true, then the ``bias`` term is ignored. The default data ``layout`` is *NCHW*, namely *(batch_size, channel, height, width)*. We can choose other layouts such as *NWC*. If ``num_group`` is larger than 1, denoted by *g*, then split the input ``data`` evenly into *g* parts along the channel axis, and also evenly split ``weight`` along the first dimension. Next compute the normalizedConvolution on the *i*-th part of the data with the *i*-th weight part. The output is obtained by concatenating all the *g* results. 1-D normalizedConvolution does not have *height* dimension but only *width* in space. - **data**: *(batch_size, channel, width)* - **weight**: *(num_filter, channel, kernel[0])* - **bias**: *(num_filter,)* - **out**: *(batch_size, num_filter, out_width)*. 3-D normalizedConvolution adds an additional *depth* dimension besides *height* and *width*. The shapes are - **data**: *(batch_size, channel, depth, height, width)* - **weight**: *(num_filter, channel, kernel[0], kernel[1], kernel[2])* - **bias**: *(num_filter,)* - **out**: *(batch_size, num_filter, out_depth, out_height, out_width)*. Both ``weight`` and ``bias`` are learnable parameters. )code" ADD_FILELINE) .set_num_inputs([](const NodeAttrs& attrs) { const NormalizedConvolutionParam& params = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); return normalized_conv::NumInputs(params.no_equiv_scale_bias); }) .set_num_outputs(normalized_conv::kNumOutputs) .set_attr_parser(NormalizedConvolutionParamParser) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { const NormalizedConvolutionParam& params = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); if (params.no_equiv_scale_bias) return std::vector<std::string>{"data", "weight"}; else return std::vector<std::string>{"data", "equiv_scale", "equiv_bias", "mean", "var", "gamma", "beta", "weight"}; }) .set_attr<nnvm::FListOutputNames>("FListOutputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"output", "sum", "sum_squares"}; }) .set_attr<mxnet::FInferShape>("FInferShape", NormalizedConvolutionShape) .set_attr<nnvm::FInferType>("FInferType", NormalizedConvolutionType) .set_attr<FCompute>("FCompute<cpu>", NormalizedConvolutionCompute<cpu>) .set_attr<nnvm::FGradient>("FGradient", NormalizedConvolutionGrad{"_backward_NormalizedConvolution"}) .set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) { return std::vector<ResourceRequest>{ResourceRequest::kTempSpace}; }) .add_argument("data", "NDArray-or-Symbol", "Input data to the NormalizedConvolutionOp.") .add_argument("equiv_scale", "NDArray-or-Symbol", "equivalent scale array") .add_argument("equiv_bias", "NDArray-or-Symbol", "equivalent bias array") .add_argument("mean", "NDArray-or-Symbol", "mean array") .add_argument("var", "NDArray-or-Symbol", "array describing variance (actually an inverse std dev)") .add_argument("gamma", "NDArray-or-Symbol", "gamma array (also known as 'scale')") .add_argument("beta", "NDArray-or-Symbol", "beta array (also known as 'bias')") .add_argument("weight", "NDArray-or-Symbol", "Weight matrix.") .add_arguments(NormalizedConvolutionParam::__FIELDS__()); NNVM_REGISTER_OP(_backward_NormalizedConvolution) .set_num_inputs([](const NodeAttrs& attrs) { const NormalizedConvolutionParam& params = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); return normalized_conv::NumInputs(params.no_equiv_scale_bias) + normalized_conv::kNumOutputs; }) .set_num_outputs([](const NodeAttrs& attrs) { const NormalizedConvolutionParam& params = nnvm::get<NormalizedConvolutionParam>(attrs.parsed); // The outputs of the backward node are the fwd-node input gradients, so one per fwd node input. return normalized_conv::NumInputs(params.no_equiv_scale_bias); }) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) { return std::vector<ResourceRequest>{ResourceRequest::kTempSpace}; }) .set_attr_parser(NormalizedConvolutionParamParser) .set_attr<FCompute>("FCompute<cpu>", NormalizedConvolutionGradCompute<cpu>); } // namespace op } // namespace mxnet <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/jit_ref_shuffle_kernel.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef JIT_REF_SHUFFLE_KERNEL_HPP #define JIT_REF_SHUFFLE_KERNEL_HPP #include "common/c_types_map.hpp" #include "common/memory.hpp" #include "ocl/jit_primitive_conf.hpp" #include "ocl_shuffle_pd.hpp" namespace mkldnn { namespace impl { namespace ocl { struct jit_ref_shuffle_kernel { jit_ref_shuffle_kernel(jit_shuffle_conf_t ajshfl) : jshfl(ajshfl){} ~jit_ref_shuffle_kernel(){} static status_t init_conf(const shuffle_pd_t *pd, jit_shuffle_conf_t &jshfl, jit_offsets &jit_off, const memory_desc_wrapper &src_md, const memory_desc_wrapper &dst_md, const memory_desc_wrapper &diff_src_md, const memory_desc_wrapper &diff_dst_md) { const bool is_fwd = pd->is_fwd(); const memory_desc_wrapper &input_md = is_fwd ? src_md : diff_dst_md; jshfl.data_type = input_md.data_type(); const int axis = pd->axis(); jshfl.axis = axis; const int axis_size = pd->axis_size(); const int group_size = pd->group_size(); jshfl.transpose_row = is_fwd ? group_size : axis_size / group_size; jshfl.transpose_col = is_fwd ? axis_size / group_size : group_size; jshfl.axis_size = axis_size; jshfl.group_size = group_size; auto dims = pd->desc()->data_desc.dims; auto ndims = pd->desc()->data_desc.ndims; const size_t outer_size = utils::array_product(dims, axis); const size_t inner_size = utils::array_product(dims + axis + 1, ndims - axis - 1); const size_t dim = axis_size * inner_size; jshfl.outer_size = outer_size; jshfl.inner_size = inner_size; jshfl.dim = dim; jshfl.ndims = ndims; jshfl.gws_d[0] = nstl::max(size_t(1), inner_size); jshfl.gws_d[1] = nstl::max(1, axis_size); jshfl.gws_d[2] = nstl::max(size_t(1), outer_size); set_offsets(input_md, jit_off.src_off); return status::success; } static status_t init_const_def(ocl_jit_t &jit, const jit_shuffle_conf_t &jshfl, const jit_offsets &jit_off) { jit.set_data_type(jshfl.data_type); jit.define_int("NDIMS", jshfl.ndims); jit.define_int("AXIS", jshfl.axis); jit.define_int("AXIS_SIZE", jshfl.axis_size); jit.define_int("GROUP_SIZE", jshfl.group_size); jit.define_int("TRANSPOSE_ROW", jshfl.transpose_row); jit.define_int("TRANSPOSE_COL", jshfl.transpose_col); jit.define_int("INNER_SIZE", jshfl.inner_size); jit.define_int("OUTER_SIZE", jshfl.outer_size); def_offsets(jit_off.src_off, jit, "SRC", jshfl.ndims); return status::success; } jit_shuffle_conf_t jshfl; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif // JIT_REF_SHUFFLE_KERNEL_HPP <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/gtests/api/test_stream.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mkldnn_test_common.hpp" #include "gtest/gtest.h" #include "mkldnn.h" namespace mkldnn { TEST(stream_test_c, WaitNullStream) { mkldnn_stream_t stream = nullptr; mkldnn_status_t status = mkldnn_stream_wait(stream); ASSERT_EQ(status, mkldnn_invalid_arguments); } TEST(stream_test_c, Wait) { mkldnn_engine_t engine; MKLDNN_CHECK(mkldnn_engine_create(&engine, mkldnn_cpu, 0)); mkldnn_stream_t stream; MKLDNN_CHECK( mkldnn_stream_create(&stream, engine, mkldnn_stream_default_flags)); MKLDNN_CHECK(mkldnn_stream_wait(stream)); MKLDNN_CHECK(mkldnn_stream_destroy(stream)); MKLDNN_CHECK(mkldnn_engine_destroy(engine)); } TEST(stream_test_cpp, Wait) { engine eng(engine::kind::cpu, 0); stream s(eng); s.wait(); } } // namespace mkldnn <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ocl_reorder_pd.hpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_REORDER_PD_HPP #define OCL_REORDER_PD_HPP #include "common/c_types_map.hpp" #include "common/reorder_pd.hpp" #include "common/utils.hpp" #include "ocl/ocl_engine.hpp" namespace mkldnn { namespace impl { namespace ocl { struct ocl_reorder_pd_t : public reorder_pd_t { using reorder_pd_t::reorder_pd_t; status_t init() { bool args_ok = true && attr()->has_default_values(); if (!args_ok) return status::unimplemented; return status::success; } }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/common/primitive.hpp<|end_filename|> /******************************************************************************* * Copyright 2016-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef PRIMITIVE_HPP #define PRIMITIVE_HPP #include <assert.h> #include "mkldnn.h" #include "c_types_map.hpp" #include "nstl.hpp" #include "primitive_desc.hpp" #include "primitive_exec_types.hpp" /** \brief A pure virtual primitive class * * Primitive contains links to its inputs & outputs, though it does not track * their readiness on execution step. * * @remark @b Rational. * Dependencies are essential through-out the whole MKL-DNN library, so it * makes sense to include them on the very low level. On the other hand, * tracking them should be a task for corresponding essence, like scheduler, * stream or whatever. Primitive itself should know nothing about the * environment it is running in. * * @note * To make user experience better we should provide API which allows * achieving the best (or good enough) performance when creating primitives * in natural order: i.e. from bottom to top for forward pass and from top to * bottom for backward pass. Please consider restriction [1] in Level 0. */ struct mkldnn_primitive: public mkldnn::impl::c_compatible { mkldnn_primitive(const mkldnn::impl::primitive_desc_t *pd) : pd_(pd->clone()) {} virtual ~mkldnn_primitive() { delete pd_; } virtual mkldnn::impl::status_t init() { return mkldnn::impl::status::success; } /** returns primitive's engine */ mkldnn::impl::engine_t *engine() const { return pd_->engine(); } /** returns primitive's inputs */ const mkldnn::impl::primitive_desc_t *pd() const { return pd_; } /** returns primitive's kind */ mkldnn::impl::primitive_kind_t kind() const { return pd_->kind(); } /** executes primitive with execution context @p ctx */ virtual mkldnn::impl::status_t execute(const mkldnn::impl::exec_ctx_t &ctx) const = 0; protected: const mkldnn::impl::primitive_desc_t *pd_; private: mkldnn_primitive() = delete; MKLDNN_DISALLOW_COPY_AND_ASSIGN(mkldnn_primitive); }; #endif // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/async/thread.h<|end_filename|> // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_THREAD_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_THREAD_H_ #include <functional> #include <string> #include <thread> // NOLINT #include "REDACTEDsynchronization/mutex.h" namespace minigo { class Thread { public: virtual ~Thread(); Thread() = default; explicit Thread(std::string name); Thread(Thread&&) = default; Thread& operator=(Thread&&) = default; std::thread::native_handle_type handle() { return impl_.native_handle(); } virtual void Start(); virtual void Join(); private: virtual void Run() = 0; std::string name_; std::thread impl_; }; class LambdaThread : public Thread { public: template <typename T> explicit LambdaThread(T closure) : closure_(std::move(closure)) {} template <typename T> LambdaThread(std::string name, T closure) : Thread(std::move(name)), closure_(std::move(closure)) {} LambdaThread(LambdaThread&&) = default; LambdaThread& operator=(LambdaThread&&) = default; private: void Run() override; std::function<void()> closure_; }; // A thread whose `Start` method blocks until the thread is running and has // called `SignalStarted` at least once. // This can be useful to serialize the order in which threads start. class BlockingStartThread : public Thread { public: BlockingStartThread() = default; explicit BlockingStartThread(std::string name) : Thread(std::move(name)) {} void Start() override { Thread::Start(); absl::MutexLock lock(&mutex_); while (!started_) { cond_var_.Wait(&mutex_); } } protected: void SignalStarted() { absl::MutexLock lock(&mutex_); started_ = true; cond_var_.Signal(); } private: absl::Mutex mutex_; absl::CondVar cond_var_; bool started_ = false; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_ASYNC_THREAD_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/tensor/amp_cast.cc<|end_filename|> /* * 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 amp_cast.cc * \brief Casts used by AMP */ #include "./amp_cast.h" namespace mxnet { namespace op { static mshadow::LayoutFlag MCastChangeLayout(nnvm::NodeAttrs* attrs, const mshadow::LayoutFlag targetLayout, std::vector<nnvm::TShape>* inpTransposes, std::vector<nnvm::TShape>* outTransposes) { auto n_inps = attrs->op->get_num_inputs(*attrs); auto n_outs = attrs->op->get_num_outputs(*attrs); CHECK_EQ(n_inps, n_outs) << "This operator should have the same number inputs and outputs"; inpTransposes->resize(n_inps); outTransposes->resize(n_outs); int valid = -1; for (size_t i = 0; i < outTransposes->size(); i++) { if (inpTransposes->at(i).ndim() > 0 && outTransposes->at(i).ndim() > 0) { bool accept = inpTransposes->at(i).ndim() == outTransposes->at(i).ndim(); auto ndim = std::min(inpTransposes->at(i).ndim(), outTransposes->at(i).ndim()); for (size_t j = 0; j < ndim; j++) accept *= inpTransposes->at(i)[j] == common::ReverseTransposeAxes(outTransposes->at(i))[j]; if (!accept) { inpTransposes->clear(); outTransposes->clear(); return mshadow::kUNKNOWN; } } else if (inpTransposes->at(i).ndim() > 0) { outTransposes->at(i) = common::ReverseTransposeAxes(inpTransposes->at(i)); } else if (outTransposes->at(i).ndim() > 0) { inpTransposes->at(i) = common::ReverseTransposeAxes(outTransposes->at(i)); } else { continue; } valid = i; } if (valid < 0) { inpTransposes->clear(); outTransposes->clear(); return mshadow::kUNKNOWN; } return common::Transpose(targetLayout, outTransposes->at(valid)); } DMLC_REGISTER_PARAMETER(AMPCastParam); DMLC_REGISTER_PARAMETER(AMPMultiCastParam); NNVM_REGISTER_OP(amp_cast) .describe(R"code(Cast function between low precision float/FP32 used by AMP. It casts only between low precision float/FP32 and does not do anything for other types. )code" ADD_FILELINE) .set_attr_parser(ParamParser<AMPCastParam>) .set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<1, 1>) .set_attr<nnvm::FInferType>("FInferType", AMPCastType) .set_attr<mxnet::alm::FChangeLayout>("FChangeLayout", ElemwiseChangeLayout) .set_attr<nnvm::FInplaceOption>("FInplaceOption", [](const NodeAttrs& attrs){ return std::vector<std::pair<int, int> >{{0, 0}}; }) .set_attr<nnvm::FInplaceIdentity>("FInplaceIdentity", [](const NodeAttrs& attrs){ return std::vector<bool>{true}; }) .set_attr<FCompute>("FCompute<cpu>", AMPCastCompute<cpu>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseNone{"_backward_amp_cast"}) .add_argument("data", "NDArray-or-Symbol", "The input.") .add_arguments(AMPCastParam::__FIELDS__()); NNVM_REGISTER_OP(_backward_amp_cast) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_attr<nnvm::FInplaceOption>("FInplaceOption", [](const NodeAttrs& attrs){ return std::vector<std::pair<int, int> >{{0, 0}}; }) .set_attr<nnvm::FInplaceIdentity>("FInplaceIdentity", [](const NodeAttrs& attrs){ return std::vector<bool>{true}; }) .set_attr<FCompute>("FCompute<cpu>", AMPCastCompute<cpu>); NNVM_REGISTER_OP(amp_multicast) .describe(R"code(Cast function used by AMP, that casts its inputs to the common widest type. It casts only between low precision float/FP32 and does not do anything for other types. )code" ADD_FILELINE) .set_num_inputs([](const nnvm::NodeAttrs& attrs) { const AMPMultiCastParam& param = dmlc::get<AMPMultiCastParam>(attrs.parsed); return static_cast<uint32_t>(param.num_outputs); }) .set_num_outputs([](const nnvm::NodeAttrs& attrs) { const AMPMultiCastParam& param = dmlc::get<AMPMultiCastParam>(attrs.parsed); return static_cast<uint32_t>(param.num_outputs); }) .set_attr_parser(ParamParser<AMPMultiCastParam>) .set_attr<mxnet::FInferShape>("FInferShape", AMPMultiCastShape) .set_attr<nnvm::FInferType>("FInferType", AMPMultiCastType) .set_attr<mxnet::alm::FChangeLayout>("FChangeLayout", MCastChangeLayout) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { uint32_t num_args = dmlc::get<AMPMultiCastParam>(attrs.parsed).num_outputs; std::vector<std::string> ret; for (uint32_t i = 0; i < num_args; ++i) { ret.push_back(std::string("data_") + std::to_string(i)); } return ret; }) .set_attr<nnvm::FInplaceOption>("FInplaceOption", [](const NodeAttrs& attrs){ int num_args = dmlc::get<AMPMultiCastParam>(attrs.parsed).num_outputs; std::vector<std::pair<int, int>> ret; for (int i = 0; i < num_args; ++i) { ret.emplace_back(i, i); } return ret; }) .set_attr<nnvm::FInplaceIdentity>("FInplaceIdentity", [](const NodeAttrs& attrs){ int num_args = dmlc::get<AMPMultiCastParam>(attrs.parsed).num_outputs; return std::vector<bool>(num_args, true); }) .set_attr<FCompute>("FCompute<cpu>", AMPMultiCastCompute<cpu>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseNone{"_backward_amp_multicast"}) .add_argument("data", "NDArray-or-Symbol[]", "Weights") .add_arguments(AMPMultiCastParam::__FIELDS__()); NNVM_REGISTER_OP(_backward_amp_multicast) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_num_inputs([](const nnvm::NodeAttrs& attrs) { const AMPMultiCastParam& param = dmlc::get<AMPMultiCastParam>(attrs.parsed); return static_cast<uint32_t>(param.num_outputs); }) .set_num_outputs([](const nnvm::NodeAttrs& attrs) { const AMPMultiCastParam& param = dmlc::get<AMPMultiCastParam>(attrs.parsed); return static_cast<uint32_t>(param.num_outputs); }) .set_attr_parser(ParamParser<AMPMultiCastParam>) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { uint32_t num_args = dmlc::get<AMPMultiCastParam>(attrs.parsed).num_outputs; std::vector<std::string> ret; for (uint32_t i = 0; i < num_args; ++i) { ret.push_back(std::string("grad_") + std::to_string(i)); } return ret; }) .set_attr<nnvm::FInplaceOption>("FInplaceOption", [](const NodeAttrs& attrs){ int num_args = dmlc::get<AMPMultiCastParam>(attrs.parsed).num_outputs; std::vector<std::pair<int, int>> ret; for (int i = 0; i < num_args; ++i) { ret.emplace_back(i, i); } return ret; }) .set_attr<nnvm::FInplaceIdentity>("FInplaceIdentity", [](const NodeAttrs& attrs){ int num_args = dmlc::get<AMPMultiCastParam>(attrs.parsed).num_outputs; return std::vector<bool>(num_args, true); }) .set_attr<FCompute>("FCompute<cpu>", AMPMultiCastCompute<cpu>) .add_argument("grad", "NDArray-or-Symbol[]", "Gradients") .add_arguments(AMPMultiCastParam::__FIELDS__()); } // namespace op } // namespace mxnet <|start_filename|>Google/benchmarks/resnet/implementations/resnet-cloud-TF2.0-tpu-v3-32/docker/Dockerfile<|end_filename|> # Docker for MLPerf v0.7 Cloud GPU Resnet submission # Based on tf-hightly-gpu (at 20200624) & the 20200620 pip packages FROM ubuntu:18.04 as base ARG DEBIAN_FRONTEND="noninteractive" RUN apt-get update && apt-get install -y --no-install-recommends dialog apt-utils RUN apt-get update && \ apt-get install -y --no-install-recommends gnupg2 curl ca-certificates && \ curl -fsSL https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub | apt-key add - && \ echo "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/cuda.list && \ echo "deb https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/nvidia-ml.list && \ apt-get purge --autoremove -y curl && \ rm -rf /var/lib/apt/lists/* ENV CUDA_VERSION=10.1.243 ENV CUDA_PKG_VERSION=10-1=10.1.243-1 RUN apt-get update && \ apt-get install -y --no-install-recommends cuda-cudart-$CUDA_PKG_VERSION cuda-compat-10-1 && \ ln -s cuda-10.1 /usr/local/cuda && \ rm -rf /var/lib/apt/lists/* RUN echo "/usr/local/nvidia/lib" >> /etc/ld.so.conf.d/nvidia.conf && \ echo "/usr/local/nvidia/lib64" >> /etc/ld.so.conf.d/nvidia.conf ENV PATH=/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin ENV LD_LIBRARY_PATH=/usr/local/nvidia/lib:/usr/local/nvidia/lib64 ENV NVIDIA_VISIBLE_DEVICES=all ENV NVIDIA_DRIVER_CAPABILITIES=compute,utility ENV NVIDIA_REQUIRE_CUDA=cuda>=10.1 brand=tesla,driver>=384,driver<385 brand=tesla,driver>=396,driver<397 brand=tesla,driver>=410,driver<411 ARG ARCH ARG CUDA=10.1 ARG CUDNN=7.6.4.38-1 ARG CUDNN_MAJOR_VERSION=7 ARG LIB_DIR_PREFIX=x86_64 ARG LIBNVINFER=6.0.1-1 ARG LIBNVINFER_MAJOR_VERSION=6 ARG LIB_DIR_PREFIX=x86_64 RUN ["/bin/bash", "-c", "apt-get update && apt-get install -y --no-install-recommends \ build-essential \ cuda-command-line-tools-${CUDA/./-} \ libcublas10=10.2.1.243-1 \ cuda-nvrtc-${CUDA/./-} \ cuda-cufft-${CUDA/./-} \ cuda-curand-${CUDA/./-} \ cuda-cusolver-${CUDA/./-} \ cuda-cusparse-${CUDA/./-} \ curl \ libcudnn7=${CUDNN}+cuda${CUDA} \ libfreetype6-dev \ libhdf5-serial-dev \ libzmq3-dev \ pkg-config \ software-properties-common \ unzip"] RUN ["/bin/bash", "-c", "[[ \"${ARCH}\" = \"ppc64le\" ]] || { \ apt-get update && \ apt-get install -y --no-install-recommends \ libnvinfer${LIBNVINFER_MAJOR_VERSION}=${LIBNVINFER}+cuda${CUDA} \ libnvinfer-plugin${LIBNVINFER_MAJOR_VERSION}=${LIBNVINFER}+cuda${CUDA} && \ apt-get clean && \ rm -rf /var/lib/apt/lists/*; }"] ENV LD_LIBRARY_PATH=/usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64 RUN ["/bin/bash", "-c", "ln -s /usr/local/cuda/lib64/stubs/libcuda.so /usr/local/cuda/lib64/stubs/libcuda.so.1 && \ echo \"/usr/local/cuda/lib64/stubs\" > /etc/ld.so.conf.d/z-cuda-stubs.conf && \ ldconfig"] ENV LANG=C.UTF-8 RUN ["/bin/bash", "-c", "apt-get update && apt-get install -y python3 python3-pip"] RUN ["/bin/bash", "-c", "python3 -m pip --no-cache-dir install --upgrade pip setuptools"] RUN ["/bin/bash", "-c", "ln -s $(which python3) /usr/local/bin/python"] ARG TF_PACKAGE=tf-nightly-gpu ARG TF_PACKAGE_VERSION=2.3.0.dev20200620 RUN ["/bin/bash", "-c", "python3 -m pip install --no-cache-dir \ ${TF_PACKAGE}${TF_PACKAGE_VERSION:+==${TF_PACKAGE_VERSION}} \ tf-estimator-nightly==2.3.0.dev2020062001 \ tb-nightly==2.3.0a20200620 \ tensorflow-model-optimization==0.3.0"] RUN ["/bin/bash", "-c", "apt-get update && apt-get install -y vim nano"] <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/jit_uni_dw_conv_kernel_f32.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "c_types_map.hpp" #include "nstl.hpp" #include "type_helpers.hpp" #include "utils.hpp" #include "memory.hpp" #include "jit_uni_dw_conv_kernel_f32.hpp" #define GET_OFF(field) offsetof(jit_conv_call_s, field) namespace mkldnn { namespace impl { namespace cpu { using namespace mkldnn::impl::prop_kind; using namespace mkldnn::impl::memory_tracking::names; using namespace mkldnn::impl::utils; using namespace Xbyak; template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::load_src(int ur_ch_blocks, int ur_w) { int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { for (int ow = 0; ow < ur_w; ow++) { Vmm vmm_acc = get_acc_reg(i*ur_ch_blocks*ur_w + ch*ur_w + ow); int b_off = ch*jcp.ch_block + i*4; if (this->jcp.with_bias) uni_vmovups(vmm_acc, vmmword[reg_bias + b_off*sizeof(float)]); else uni_vpxor(vmm_acc, vmm_acc, vmm_acc); int o_off = ch*jcp.oh*jcp.ow*jcp.ch_block + ow*jcp.ch_block + i*4; if (this->jcp.with_sum) uni_vaddps(vmm_acc, vmm_acc, vmmword[reg_output + o_off*sizeof(float)]); } } } } template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::apply_filter( int ur_ch_blocks, int ur_w) { int ch_blk = jcp.ch_block; int dilate_h = jcp.dilate_h + 1; int dilate_w = jcp.dilate_w + 1; int stride_w = jcp.stride_w; Label iter_exit_label; cmp(reg_kh, 0); je(iter_exit_label, T_NEAR); cmp(reg_kw, 0); je(iter_exit_label, T_NEAR); mov(iter_kh, reg_kh); Label kh_label; L(kh_label); { mov(iter_kw, reg_kw); mov(aux1_reg_input, aux_reg_input); mov(aux1_reg_kernel, aux_reg_kernel); Label kw_label; L(kw_label); { int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { int ker_off = ch*jcp.kh*jcp.kw*ch_blk + i*4; Vmm vmm_ker = get_ker_reg(0); uni_vmovups(vmm_ker, ptr[aux1_reg_kernel + ker_off*sizeof(float)]); for (int ow = 0; ow < ur_w; ow++) { int inp_off = ch*jcp.ih*jcp.iw*ch_blk + ow*stride_w*ch_blk + i*4; Vmm vmm_src = get_src_reg(0); uni_vmovups(vmm_src, ptr[aux1_reg_input + inp_off*sizeof(float)]); Vmm vmm_acc = get_acc_reg(i*ur_ch_blocks*ur_w + ch*ur_w + ow); uni_vfmadd231ps(vmm_acc, vmm_src, vmm_ker); } } } add(aux1_reg_kernel, ch_blk*sizeof(float)); add(aux1_reg_input, ch_blk*dilate_w*sizeof(float)); dec(iter_kw); cmp(iter_kw, 0); jg(kw_label, T_NEAR); } add(aux_reg_kernel, jcp.kw*ch_blk*sizeof(float)); add(aux_reg_input, jcp.iw*ch_blk*dilate_h*sizeof(float)); dec(iter_kh); cmp(iter_kh, 0); jg(kh_label, T_NEAR); } L(iter_exit_label); } template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::apply_filter_unrolled( int ur_ch_blocks, int ur_w) { int ch_blk = jcp.ch_block; int dilate_h = jcp.dilate_h + 1; int dilate_w = jcp.dilate_w + 1; int stride_w = jcp.stride_w; Label iter_exit_label; cmp(reg_kh, 0); je(iter_exit_label, T_NEAR); mov(iter_kh, reg_kh); Label kh_label; L(kh_label); { int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { for (int kw = 0; kw < jcp.kw; kw++) { int ker_off = ch*jcp.kh*jcp.kw*ch_blk + kw*ch_blk + i*4; Vmm vmm_ker = get_ker_reg(0); uni_vmovups(vmm_ker, ptr[aux_reg_kernel + ker_off*sizeof(float)]); for (int ow = 0; ow < ur_w; ow++) { int inp_off = ch*jcp.ih*jcp.iw*ch_blk + ow*stride_w*ch_blk + kw*ch_blk*dilate_w + i*4; Vmm vmm_src = get_src_reg(0); uni_vmovups(vmm_src, ptr[aux_reg_input + inp_off*sizeof(float)]); Vmm vmm_acc = get_acc_reg(i*ur_ch_blocks*ur_w + ch*ur_w + ow); uni_vfmadd231ps(vmm_acc, vmm_src, vmm_ker); } } } } add(aux_reg_kernel, jcp.kw*ch_blk*sizeof(float)); add(aux_reg_input, jcp.iw*ch_blk*dilate_h*sizeof(float)); dec(iter_kh); cmp(iter_kh, 0); jg(kh_label, T_NEAR); } L(iter_exit_label); } template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::apply_activation( int ur_ch_blocks, int ur_w) { if (this->jcp.with_eltwise) { int repeats = isa == sse41 ? 2 : 1; eltwise_injector_->compute_vector_range(4, repeats * ur_w * ur_ch_blocks + 4); } } template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::store_dst( int ur_ch_blocks, int ur_w) { int ch_blk = jcp.ch_block; int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { for (int ow = 0; ow < ur_w; ow++) { int o_off = ch*jcp.oh*jcp.ow*ch_blk + ow*ch_blk + i*4; Vmm vmm_dst = get_acc_reg(i*ur_ch_blocks*ur_w + ch*ur_w + ow); uni_vmovups(vmmword[reg_output + o_off*sizeof(float)], vmm_dst); } } } } template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::loop_body(int ur_ch_blocks) { Label unrolled_w_label; Label tail_w_label; Label exit_label; L(unrolled_w_label); { int ur_w = jcp.ur_w; cmp(reg_ur_w, ur_w); jl(tail_w_label, T_NEAR); mov(aux_reg_input, reg_input); mov(aux_reg_kernel, reg_kernel); load_src(ur_ch_blocks, ur_w); apply_filter_unrolled(ur_ch_blocks, ur_w); apply_activation(ur_ch_blocks, ur_w); store_dst(ur_ch_blocks, ur_w); add(reg_input, sizeof(float) * ur_w * jcp.ch_block * jcp.stride_w); add(reg_output, sizeof(float) * ur_w * jcp.ch_block); sub(reg_ur_w, ur_w); jmp(unrolled_w_label); } L(tail_w_label); { int ur_w = 1; cmp(reg_ur_w, ur_w); jl(exit_label, T_NEAR); mov(aux_reg_input, reg_input); mov(aux_reg_kernel, reg_kernel); load_src(ur_ch_blocks, ur_w); apply_filter(ur_ch_blocks, ur_w); apply_activation(ur_ch_blocks, ur_w); store_dst(ur_ch_blocks, ur_w); add(reg_input, sizeof(float) * ur_w * jcp.ch_block * jcp.stride_w); add(reg_output, sizeof(float) * ur_w * jcp.ch_block); sub(reg_ur_w, ur_w); jmp(tail_w_label); } L(exit_label); } template <cpu_isa_t isa> void jit_uni_dw_conv_fwd_kernel_f32<isa>::generate() { this->preamble(); mov(reg_input, ptr[this->param1 + GET_OFF(src)]); mov(reg_output, ptr[this->param1 + GET_OFF(dst)]); mov(reg_kernel, ptr[this->param1 + GET_OFF(filt)]); if (jcp.with_bias) mov(reg_bias, ptr[this->param1 + GET_OFF(bias)]); mov(reg_kh, ptr[this->param1 + GET_OFF(kh_padding)]); mov(reg_kw, ptr[this->param1 + GET_OFF(kw_padding)]); mov(reg_ch_blocks, ptr[this->param1 + GET_OFF(ch_blocks)]); mov(reg_ur_w, ptr[this->param1 + GET_OFF(ur_w)]); Label ch_blocks_tail_label; Label exit_label; int ch_blocks_tail = jcp.nb_ch % jcp.nb_ch_blocking; cmp(reg_ch_blocks, jcp.nb_ch_blocking); jne(ch_blocks_tail ? ch_blocks_tail_label : exit_label, T_NEAR); loop_body(jcp.nb_ch_blocking); // channel main loop if (ch_blocks_tail) { L(ch_blocks_tail_label); cmp(reg_ch_blocks, ch_blocks_tail); jne(exit_label, T_NEAR); loop_body(ch_blocks_tail); // channel tail loop } L(exit_label); this->postamble(); if (jcp.with_eltwise) eltwise_injector_->prepare_table(); } template struct jit_uni_dw_conv_fwd_kernel_f32<avx512_common>; template struct jit_uni_dw_conv_fwd_kernel_f32<avx2>; template struct jit_uni_dw_conv_fwd_kernel_f32<sse41>; template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_data_kernel_f32<isa>::load_ddst( int ur_ch_blocks, int ur_str_w) { int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { for (int w = 0; w < ur_str_w; w++) { Vmm vmm_acc = get_acc_reg(i*ur_ch_blocks*ur_str_w + ch*ur_str_w + w); uni_vpxor(vmm_acc, vmm_acc, vmm_acc); } } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_data_kernel_f32<isa>::apply_filter( int ur_ch_blocks, int ur_str_w) { int kw = jcp.kw; int kh = jcp.kh; int ow = jcp.ow; int oh = jcp.oh; int ch_blk = jcp.ch_block; int stride_h = jcp.stride_h; int stride_w = jcp.stride_w; Label iter_exit_label; cmp(reg_kh, 0); je(iter_exit_label, T_NEAR); cmp(reg_kw, 0); je(iter_exit_label, T_NEAR); mov(iter_kh, reg_kh); Label kh_label; L(kh_label); { mov(aux1_reg_ddst, aux_reg_ddst); mov(aux1_reg_kernel, aux_reg_kernel); mov(iter_kw, reg_kw); Label kw_label; L(kw_label); { int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { int ker_off = ch*kh*kw*ch_blk + i*4; Vmm vmm_ker = get_ker_reg(0); uni_vmovups(vmm_ker, ptr[aux1_reg_kernel + ker_off*sizeof(float)]); for (int w = 0; w < ur_str_w; w++) { int ddst_off = (ch*oh*ow + w)*ch_blk + i*4; Vmm vmm_src = get_src_reg(0); uni_vmovups(vmm_src, ptr[aux1_reg_ddst + ddst_off*sizeof(float)]); Vmm vmm_acc = get_acc_reg(i*ur_ch_blocks*ur_str_w + ch*ur_str_w + w); uni_vfmadd231ps(vmm_acc, vmm_src, vmm_ker); } } } add(aux1_reg_kernel, ch_blk*stride_w*sizeof(float)); sub(aux1_reg_ddst, ch_blk*sizeof(float)); sub(iter_kw, stride_w); cmp(iter_kw, 0); jg(kw_label, T_NEAR); } add(aux_reg_kernel, kw*ch_blk*stride_h*sizeof(float)); sub(aux_reg_ddst, ow*ch_blk*sizeof(float)); sub(iter_kh, stride_h); cmp(iter_kh, 0); jg(kh_label, T_NEAR); } L(iter_exit_label); } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_data_kernel_f32<isa>::store_dsrc( int ur_ch_blocks, int ur_str_w) { int ch_blk = jcp.ch_block; int iw = jcp.iw; int ih = jcp.ih; int stride_w = jcp.stride_w; int repeats = isa == sse41 ? 2 : 1; for (int i = 0; i < repeats; i++) { for (int ch = 0; ch < ur_ch_blocks; ch++) { for (int w = 0; w < ur_str_w; w++) { int dsrc_off = (ch*ih*iw + w*stride_w)*ch_blk + i*4; Vmm vmm_acc = get_acc_reg(i*ur_ch_blocks*ur_str_w + ch*ur_str_w + w); uni_vmovups(ptr[reg_dsrc + dsrc_off*sizeof(float)], vmm_acc); } } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_data_kernel_f32<isa>::loop_body( int ur_ch_blocks) { Label unrolled_w_label; Label tail_w_label; Label exit_label; L(unrolled_w_label); { int ur_w = jcp.ur_w; cmp(reg_ur_str_w, ur_w); jl(tail_w_label, T_NEAR); mov(aux_reg_ddst, reg_ddst); mov(aux_reg_kernel, reg_kernel); load_ddst(ur_ch_blocks, ur_w); apply_filter(ur_ch_blocks, ur_w); store_dsrc(ur_ch_blocks, ur_w); add(reg_dsrc, sizeof(float) * ur_w * jcp.ch_block * jcp.stride_w); add(reg_ddst, sizeof(float) * ur_w * jcp.ch_block); sub(reg_ur_str_w, ur_w); jmp(unrolled_w_label); } L(tail_w_label); { int ur_w = 1; cmp(reg_ur_str_w, ur_w); jl(exit_label, T_NEAR); mov(aux_reg_ddst, reg_ddst); mov(aux_reg_kernel, reg_kernel); load_ddst(ur_ch_blocks, ur_w); apply_filter(ur_ch_blocks, ur_w); store_dsrc(ur_ch_blocks, ur_w); add(reg_dsrc, sizeof(float) * ur_w * jcp.ch_block * jcp.stride_w); add(reg_ddst, sizeof(float) * ur_w * jcp.ch_block); sub(reg_ur_str_w, ur_w); jmp(tail_w_label); } L(exit_label); } template <cpu_isa_t isa> void jit_uni_dw_conv_bwd_data_kernel_f32<isa>::generate() { preamble(); mov(reg_dsrc, ptr[this->param1 + GET_OFF(src)]); mov(reg_ddst, ptr[this->param1 + GET_OFF(dst)]); mov(reg_kernel, ptr[this->param1 + GET_OFF(filt)]); mov(reg_kh, ptr[this->param1 + GET_OFF(kh_padding)]); mov(reg_kw, ptr[this->param1 + GET_OFF(kw_padding)]); mov(reg_ch_blocks, ptr[this->param1 + GET_OFF(ch_blocks)]); mov(reg_ur_str_w, ptr[this->param1 + GET_OFF(ur_str_w)]); Label ch_blocks_tail_label; Label exit_label; int ch_blocks_tail = jcp.nb_ch % jcp.nb_ch_blocking; cmp(reg_ch_blocks, jcp.nb_ch_blocking); jne(ch_blocks_tail ? ch_blocks_tail_label : exit_label, T_NEAR); loop_body(jcp.nb_ch_blocking); // channel main loop if (ch_blocks_tail) { L(ch_blocks_tail_label); cmp(reg_ch_blocks, ch_blocks_tail); jne(exit_label, T_NEAR); loop_body(ch_blocks_tail); // channel tail loop } L(exit_label); this->postamble(); } template struct jit_uni_dw_conv_bwd_data_kernel_f32<avx512_common>; template struct jit_uni_dw_conv_bwd_data_kernel_f32<avx2>; template struct jit_uni_dw_conv_bwd_data_kernel_f32<sse41>; template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::zero_filter() { for (int r = 0; r < reg_repeats; ++r) { for (int i = 0; i < jcp.kw; ++i) { Vmm vmm_acc = get_acc_reg(r * jcp.kw + i); uni_vpxor(vmm_acc, vmm_acc, vmm_acc); } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::load_filter() { for (int r = 0; r < reg_repeats; ++r) { const int reg_set = r * jcp.kw; for (int i = 0; i < jcp.kw; ++i) { int off_filter = (reg_set + i) * simd_w; Vmm vmm_acc = get_acc_reg(reg_set + i); uni_vmovups(vmm_acc, vmmword[reg_tmp_filter + off_filter * sizeof(float)]); } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::zero_bias() { for (int r = 0; r < reg_repeats; ++r) { Vmm vmm_bias = get_bias_reg(r); uni_vpxor(vmm_bias, vmm_bias, vmm_bias); } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::load_bias() { for (int r = 0; r < reg_repeats; ++r) { Vmm vmm_bias = get_bias_reg(r); uni_vmovups( vmm_bias, vmmword[reg_bias_baddr + r * simd_w * sizeof(float)]); } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_ow_step_unroll( int unroll_w, int l_pad, int pad_offset, int ow_block) { const int iw_block = ow_block * jcp.stride_w; const int right_border = jcp.iw - iw_block; const int r_pad = jcp.r_pad; const int cascade_input = nstl::min(jcp.stride_w, jcp.kw); /* preamble count for number of cascaded LOAD + FMA operation */ const int input_overlap = nstl::max(jcp.kw - l_pad, 0); const bool is_last_block = (unroll_w + ow_block == jcp.ow); /* LOAD initial input registers, then cascade LOADs and FMAs*/ for (int r = 0; r < reg_repeats; ++r) { for (int i_ur = 0; i_ur < unroll_w; ++i_ur) { int off_output = (i_ur * reg_repeats + r) * simd_w; Vmm vmm_output = get_output_reg(r); uni_vmovups(vmm_output, ptr[reg_tmp_output + off_output * sizeof(float)]); if (i_ur == 0) { for (int c = 0; c < input_overlap; ++c) { int off_input = ((c - pad_offset) * reg_repeats + r) * simd_w; if (off_input < 0 && unroll_w == jcp.ow) continue; const bool over_steps_bdry = true && is_last_block && (c - pad_offset + r_pad > right_border); if (over_steps_bdry) continue; Vmm vmm_input = get_input_reg((c % jcp.kw) * reg_repeats + r); uni_vmovups(vmm_input, ptr[reg_tmp_input + off_input * sizeof(float)]); } } else { for (int c = 0; c < cascade_input; ++c) { int overlap = (i_ur - 1) * jcp.stride_w + input_overlap; int off_input = ((overlap + c - pad_offset) * reg_repeats + r) * simd_w; if (off_input < 0 || overlap + c + l_pad > right_border) continue; const bool over_steps_bdry = true && is_last_block && (overlap + c - pad_offset + r_pad > right_border); if (over_steps_bdry) continue; Vmm vmm_input = get_input_reg( ((overlap + c) % jcp.kw) * reg_repeats + r); uni_vmovups(vmm_input, ptr[reg_tmp_input + off_input * sizeof(float)]); } } for (int i_kw = 0; i_kw < jcp.kw; ++i_kw) { int io_overlap = i_kw + (i_ur * jcp.stride_w); /* Don't apply FMAs that fall into the padded region */ if (io_overlap - l_pad < 0 || io_overlap - jcp.l_pad >= right_border) continue; const bool over_steps_bdry = true && is_last_block && (io_overlap - jcp.l_pad + jcp.r_pad > right_border); if (over_steps_bdry) continue; Vmm vmm_input = get_input_reg( ((io_overlap - l_pad) % jcp.kw) * reg_repeats + r); Vmm vmm_acc = get_acc_reg(i_kw * reg_repeats + r); Vmm vmm_aux = isa == sse41 ? get_aux_reg() : vmm_input; if (isa == sse41) uni_vmovups(vmm_aux, vmm_input); uni_vfmadd231ps(vmm_acc, vmm_aux, vmm_output); } } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_bias_step_unroll( const int unroll_w) { for (int r = 0; r < reg_repeats; ++r) { for (int i = 0; i < unroll_w; ++i) { Vmm vmm_bias = get_bias_reg(r); int off_output = (i * reg_repeats + r) * simd_w; if (isa == sse41) { /* Need to support unaligned address loads for SSE41 */ Vmm vmm_output = get_output_reg(1 + r); uni_vmovups(vmm_output, ptr[reg_tmp_output + off_output * sizeof(float)]); uni_vaddps(vmm_bias, vmm_bias, vmm_output); } else { uni_vaddps(vmm_bias, vmm_bias, vmmword[reg_tmp_output + off_output * sizeof(float)]); } } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::store_filter() { for (int r = 0; r < reg_repeats; ++r) { const int reg_set = r * jcp.kw; for (int i = 0; i < jcp.kw; ++i) { int off_filter = (i + reg_set) * simd_w; Vmm vmm_acc = get_acc_reg(i + reg_set); uni_vmovups(vmmword[reg_tmp_filter + off_filter * sizeof(float)], vmm_acc); } } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::store_bias() { for (int r = 0; r < reg_repeats; ++r) { Vmm vmm_bias = get_bias_reg(r); uni_vmovups( vmmword[reg_bias_baddr + r * simd_w * sizeof(float)], vmm_bias); } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_bias_loop( const int block_size) { Label oh_label; Label ow_blk_label; const int unroll_w = nstl::min(block_size, jcp.ow); const int unroll_w_trips = jcp.ow / unroll_w; const int tail_w = jcp.ow > block_size ? jcp.ow % block_size : 0; const int ch_offset = jcp.ch_block; mov(reg_oh, ptr[this->param1 + offsetof(jit_dw_conv_call_s, oh_index)]); mov(reg_oh_worksize, ptr[this->param1 + offsetof(jit_dw_conv_call_s, oh_count)]); mov(reg_tmp_output, reg_output_baddr); L(oh_label); { mov(reg_iter_ow_blk, unroll_w_trips); L(ow_blk_label); { compute_bias_step_unroll(unroll_w); add(reg_tmp_output, unroll_w * ch_offset * sizeof(float)); dec(reg_iter_ow_blk); cmp(reg_iter_ow_blk, 0); jg(ow_blk_label, T_NEAR); } if (tail_w > 0) { compute_bias_step_unroll(tail_w); add(reg_tmp_output, tail_w * ch_offset * sizeof(float)); } inc(reg_oh); cmp(reg_oh, reg_oh_worksize); jl(oh_label, T_NEAR); } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_zero_filter() { const int ch_offset = jcp.ch_block; Label kh_loop_label, skip_zeroing_label; mov(reg_exec_flags, ptr[this->param1 + offsetof(jit_dw_conv_call_s, exec_flags)]); and_(reg_exec_flags, FLAG_ZERO_FILTER); test(reg_exec_flags, reg_exec_flags); je(skip_zeroing_label); zero_filter(); mov(reg_tmp_filter, reg_filter_baddr); mov(reg_kh, jcp.kh); L(kh_loop_label); { store_filter(); add(reg_tmp_filter, jcp.kw * ch_offset * sizeof(float)); dec(reg_kh); cmp(reg_kh, 0); jg(kh_loop_label); } /* Comeback pointers */ sub(reg_tmp_filter, jcp.kh * jcp.kw * ch_offset * sizeof(float)); L(skip_zeroing_label); } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_h_step( int unroll_w, int l_pad, int pad_offset, int ow_block) { const int ch_offset = jcp.ch_block; Label kh_loop_label, skip_loop_label; cmp(reg_kh_count, 0); je(skip_loop_label, T_NEAR); mov(reg_kh, reg_kh_count); L(kh_loop_label); { load_filter(); compute_ow_step_unroll(unroll_w, l_pad, pad_offset, ow_block); store_filter(); add(reg_tmp_filter, jcp.kw * ch_offset * sizeof(float)); add(reg_tmp_input, jcp.iw * ch_offset * sizeof(float)); dec(reg_kh); cmp(reg_kh, 0); jg(kh_loop_label); } /* Comeback pointers */ Label kh_comeback_label; mov(reg_kh, reg_kh_count); L(kh_comeback_label); { sub(reg_tmp_input, jcp.iw * ch_offset * sizeof(float)); sub(reg_tmp_filter, jcp.kw * ch_offset * sizeof(float)); dec(reg_kh); cmp(reg_kh, 0); jg(kh_comeback_label, T_NEAR); } L(skip_loop_label); } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_h_loop( int unroll_w, int l_pad, int pad_offset, int ow_block) { // last index of output that is not influenced by right padding const size_t io_overlap = jcp.oh - 1 - utils::div_up(jcp.b_pad, jcp.stride_h); const int ch_offset = jcp.ch_block; const int t_overlap_off = jcp.t_pad % jcp.stride_h == 0 ? jcp.stride_h : 1; const int b_overlap_off = jcp.b_pad % jcp.stride_h == 0 ? jcp.stride_h : 1; Label tpad_loop_label, h_loop_label, skip_tpad_label, skip_bpad_label; mov(reg_oh, ptr[this->param1 + offsetof(jit_dw_conv_call_s, oh_index)]); mov(reg_oh_worksize, ptr[this->param1 + offsetof(jit_dw_conv_call_s, oh_count)]); mov(reg_kh_count, ptr[this->param1 + offsetof(jit_dw_conv_call_s, kh_count)]); mov(reg_tmp_output, reg_output_baddr); mov(reg_tmp_input, reg_input_baddr); mov(reg_tmp_filter, reg_filter_baddr); L(h_loop_label); { compute_h_step(unroll_w, l_pad, pad_offset, ow_block); add(reg_tmp_output, jcp.ow * ch_offset * sizeof(float)); /* If within the top_pad region */ if (jcp.t_pad > 0) { /* Skip t_pad area if no longer in initial h_block */ cmp(reg_oh, jcp.t_pad); jg(skip_tpad_label, T_NEAR); cmp(reg_kh_count, jcp.kh); jge(skip_tpad_label, T_NEAR); add(reg_kh_count, t_overlap_off); sub(reg_tmp_filter, t_overlap_off * jcp.kw * ch_offset * sizeof(float)); /* kernel has moved beyond padding (adjust for stride effects) */ if (jcp.t_pad % jcp.stride_h != 0) { int inp_corr = jcp.stride_h - jcp.t_pad % jcp.stride_h; add(reg_tmp_input, inp_corr * jcp.iw * ch_offset * sizeof(float)); } jmp(tpad_loop_label, T_NEAR); } L(skip_tpad_label); cmp(reg_oh, io_overlap); jl(skip_bpad_label, T_NEAR); sub(reg_kh_count, b_overlap_off); L(skip_bpad_label); add(reg_tmp_input, jcp.stride_h * jcp.iw * ch_offset * sizeof(float)); L(tpad_loop_label); inc(reg_oh); cmp(reg_oh, reg_oh_worksize); jl(h_loop_label, T_NEAR); } } template <cpu_isa_t isa> inline void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::compute_ow_block_unroll() { const int ch_offset = jcp.ch_block; int ow = jcp.ow; int pad_offset = 0; int l_pad = jcp.l_pad; int r_pad = jcp.r_pad; /* Is this strictly defined by: * -code-size (?) * -address size (?) */ const int max_unroll_w = 30; const int block_size = 15; int unroll_w_tail = 0; int unroll_w = 0; int unroll_w_trips = 0; const bool do_unroll_w = jcp.ow > max_unroll_w; if (do_unroll_w) { unroll_w = nstl::min(block_size, jcp.ow); unroll_w_trips = ow / unroll_w; /* calculate tail */ unroll_w_tail = ow % unroll_w; /* Perform some rebalancing if tail too small*/ if ((unroll_w_tail == 0 && r_pad != 0) || (r_pad > 0 && r_pad >= unroll_w_tail)) { if (unroll_w_trips > 1) { unroll_w_tail += unroll_w; unroll_w_trips--; } else { /* Idealy, this case shouldn't happen */ unroll_w_tail += (unroll_w - unroll_w / 2); unroll_w = unroll_w / 2; } } } else { unroll_w_tail = jcp.ow; } if (jcp.with_bias) { Label skip_load_bias; mov(reg_bias_baddr, ptr[this->param1 + offsetof(jit_dw_conv_call_s, bias)]); zero_bias(); mov(reg_exec_flags, ptr[this->param1 + offsetof(jit_dw_conv_call_s, exec_flags)]); and_(reg_exec_flags, FLAG_ZERO_BIAS); test(reg_exec_flags, reg_exec_flags); jne(skip_load_bias); load_bias(); L(skip_load_bias); compute_bias_loop(block_size); store_bias(); } /* Pass filter address, then offset for h_padding. */ compute_zero_filter(); mov(reg_kh_offset, ptr[this->param1 + offsetof(jit_dw_conv_call_s, filter_pad_off)]); add(reg_filter_baddr, reg_kh_offset); /* compute left padded block */ if (l_pad && do_unroll_w) { compute_h_loop(unroll_w, l_pad, 0, 0); add(reg_output_baddr, unroll_w * ch_offset * sizeof(float)); add(reg_input_baddr, unroll_w * jcp.stride_w * ch_offset * sizeof(float)); unroll_w_trips--; pad_offset = l_pad; l_pad = 0; } /* compute middle block */ Label ow_blk_label; /* Insert loop for 'ow' block when middle block needs to execute more * than once */ bool do_ow_blk_loop = unroll_w_trips > 1; if (do_ow_blk_loop) { mov(reg_iter_ow_blk, unroll_w_trips); L(ow_blk_label); } if (unroll_w_trips > 0) { compute_h_loop(unroll_w, l_pad, pad_offset, 0); add(reg_output_baddr, unroll_w * ch_offset * sizeof(float)); add(reg_input_baddr, unroll_w * jcp.stride_w * ch_offset * sizeof(float)); } if (do_ow_blk_loop) { dec(reg_iter_ow_blk); cmp(reg_iter_ow_blk, 0); jg(ow_blk_label, T_NEAR); } /* compute right padded block */ if (unroll_w_tail) { compute_h_loop(unroll_w_tail, l_pad, pad_offset, jcp.ow - unroll_w_tail); } } template <cpu_isa_t isa> void jit_uni_dw_conv_bwd_weights_kernel_f32<isa>::generate() { preamble(); mov(reg_input_baddr, ptr[this->param1 + offsetof(jit_dw_conv_call_s, input)]); mov(reg_output_baddr, ptr[this->param1 + offsetof(jit_dw_conv_call_s, output)]); mov(reg_filter_baddr, ptr[this->param1 + offsetof(jit_dw_conv_call_s, filter)]); compute_ow_block_unroll(); this->postamble(); } template struct jit_uni_dw_conv_bwd_weights_kernel_f32<avx512_common>; template struct jit_uni_dw_conv_bwd_weights_kernel_f32<avx2>; template struct jit_uni_dw_conv_bwd_weights_kernel_f32<sse41>; } } } <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/eval.h<|end_filename|> // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_EVAL_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_EVAL_H_ #include <stdio.h> #include <atomic> #include <cmath> #include <functional> #include <iostream> #include <memory> #include <string> #include <thread> // NOLINT #include <utility> #include <vector> #include "base/commandlineflags.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/str_format.h" #include "REDACTEDstrings/str_split.h" #include "REDACTEDtime/clock.h" #include "REDACTEDtime/time.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/constants.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/game.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/game_utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/mcts_player.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/batching_model.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/loader.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/model.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/random.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/tf_utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/zobrist.h" // Game options flags. ABSL_DECLARE_FLAG(bool, resign_enabled); ABSL_DECLARE_FLAG(double, resign_threshold); ABSL_DECLARE_FLAG(uint64, seed); // Tree search flags. ABSL_DECLARE_FLAG(int32, virtual_losses); ABSL_DECLARE_FLAG(double, value_init_penalty); // Inference flags. ABSL_DECLARE_FLAG(std::string, eval_model); ABSL_DECLARE_FLAG(std::string, eval_device); ABSL_DECLARE_FLAG(int32, num_eval_readouts); ABSL_DECLARE_FLAG(std::string, target_model); ABSL_DECLARE_FLAG(std::string, target_device); ABSL_DECLARE_FLAG(int32, num_target_readouts); ABSL_DECLARE_FLAG(int32, parallel_games); // Output flags. ABSL_DECLARE_FLAG(std::string, output_bigtable); ABSL_DECLARE_FLAG(std::string, sgf_dir); ABSL_DECLARE_FLAG(std::string, bigtable_tag); ABSL_DECLARE_FLAG(bool, verbose); namespace minigo { class Evaluator { class EvaluatedModel { public: EvaluatedModel(BatchingModelFactory* batcher, const std::string& path, const MctsPlayer::Options& player_options) : batcher_(batcher), path_(path), player_options_(player_options) {} std::string name() { absl::MutexLock lock(&mutex_); if (name_.empty()) { // The model's name is lazily initialized the first time we create a // instance. Make sure it's valid. NewModelImpl(); } return name_; } WinStats GetWinStats() const { absl::MutexLock lock(&mutex_); return win_stats_; } void UpdateWinStats(const Game& game) { absl::MutexLock lock(&mutex_); win_stats_.Update(game); } std::unique_ptr<Model> NewModel() { absl::MutexLock lock(&mutex_); return NewModelImpl(); } const MctsPlayer::Options& player_options() const { return player_options_; } private: std::unique_ptr<Model> NewModelImpl() EXCLUSIVE_LOCKS_REQUIRED(&mutex_) { auto model = batcher_->NewModel(path_); if (name_.empty()) { name_ = model->name(); } return model; } mutable absl::Mutex mutex_; BatchingModelFactory* batcher_ GUARDED_BY(&mutex_); const std::string path_; std::string name_ GUARDED_BY(&mutex_); WinStats win_stats_ GUARDED_BY(&mutex_); MctsPlayer::Options player_options_; }; public: Evaluator(); void Reset(); std::vector<std::pair<std::string, WinStats>> Run(); private: void ThreadRun(int thread_id, EvaluatedModel* black_model, EvaluatedModel* white_model); Game::Options game_options_; std::vector<std::thread> threads_; std::atomic<size_t> game_id_{0}; std::vector<std::unique_ptr<BatchingModelFactory>> batchers_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_EVAL_H_ <|start_filename|>Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/concurrent_selfplay.h<|end_filename|> #ifndef MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_CONCURRENT_SELFPLAY_H_ #define MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_CONCURRENT_SELFPLAY_H_ // Copyright 2019 Google LLC // // 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 <cmath> #include <functional> #include <memory> #include <vector> #include "base/commandlineflags.h" #include "REDACTEDmemory/memory.h" #include "REDACTEDstrings/str_cat.h" #include "REDACTEDstrings/str_join.h" #include "REDACTEDstrings/str_replace.h" #include "REDACTEDstrings/str_split.h" #include "REDACTEDsynchronization/mutex.h" #include "REDACTEDtime/clock.h" #include "REDACTEDtime/time.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/poll_thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/sharded_executor.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/async/thread_safe_queue.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/directory_watcher.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/path.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/file/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/game.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/game_utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/init.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/mcts_tree.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/inference_cache.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/loader.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/platform/utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/random.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/tf_utils.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/wtf_saver.h" #include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/zobrist.h" #include "third_party/tensorflow/core/lib/io/path.h" #include "third_party/tensorflow/core/platform/env.h" #include "third_party/tensorflow/core/platform/file_system.h" #include "third_party/tracing_framework_bindings_cpp/macros.h" // Plays multiple selfplay games. // There are several important classes in this binary: // - `SelfplayGame` : holds the state for a single game, most importantly an // `MctsTree` and a `Game`. The `SelfplayGame` is responsible for selecting // leaves in the MCTS tree to run inference on, propagating inference // results back up the tree, and playing moves. // - `SelfplayThread` : owns multiple `SelfplayGame` instances and uses them // to play games concurrently. See SelfplayThread::Run for the sequence of // operations performed when playing games. Tree search is carried out in // batches on multiple threads in parallel. // - `Selfplayer` : owns multiple `SelfplayThread` instances, which lets the // binary perform tree search on multiple threads. // - `OutputThread` : responsible for writing SGF & training examples to // storage. After a game finished, its `SelfplayThread` hands the // `SelfplayGame` instance back to the `Selfplayer`, which pushes it onto // an output queue for `OutputThread` to consume. // Inference flags. DECLARE_string(engine); DECLARE_string(device); DECLARE_string(model); DECLARE_int32(cache_size_mb); DECLARE_int32(cache_shards); // Tree search flags. DECLARE_int32(num_readouts); DECLARE_double(fastplay_frequency); DECLARE_int32(fastplay_readouts); DECLARE_int32(virtual_losses); DECLARE_double(dirichlet_alpha); DECLARE_double(noise_mix); DECLARE_double(value_init_penalty); DECLARE_bool(target_pruning); DECLARE_double(policy_softmax_temp); DECLARE_bool(allow_pass); DECLARE_int32(restrict_pass_alive_play_threshold); // Threading flags. DECLARE_int32(selfplay_threads); DECLARE_int32(parallel_search); DECLARE_int32(parallel_inference); DECLARE_int32(concurrent_games_per_thread); // Game flags. DECLARE_uint64(seed); DECLARE_double(min_resign_threshold); DECLARE_double(max_resign_threshold); DECLARE_double(disable_resign_pct); DECLARE_int32(num_games); DECLARE_bool(run_forever); DECLARE_string(abort_file); // Output flags. DECLARE_double(holdout_pct); DECLARE_string(output_dir); DECLARE_string(holdout_dir); DECLARE_string(sgf_dir); DECLARE_string(wtf_trace); DECLARE_bool(verbose); DECLARE_int32(output_threads); namespace minigo { inline std::string GetOutputDir(absl::Time now, const std::string& model_name, const std::string& root_dir) { auto sub_dirs = absl::FormatTime("%Y-%m-%d-%H", now, absl::UTCTimeZone()); auto clean_model_name = absl::StrReplaceAll(model_name, {{":", "_"}, {"/", "_"}, {".", "_"}}); std::string processed_root_dir = absl::StrReplaceAll(root_dir, {{"$MODEL", clean_model_name}}); return file::JoinPath(processed_root_dir, sub_dirs); } // Information required to run a single inference. struct Inference { InferenceCache::Key cache_key; MctsNode* leaf; ModelInput input; ModelOutput output; }; // Holds all the state for a single selfplay game. // Each `SelfplayThread` plays multiple games in parallel, calling // `SelectLeaves`, `ProcessInferences` and `MaybePlayMove` sequentially. class SelfplayGame { public: struct Options { // Number of virtual losses. int num_virtual_losses; // Number of positions to read normally. int num_readouts; // Number of positions to read if playout cap oscillations determines that // this should be a "fast" play. int fastplay_readouts; // Frequency that a move should be a "fast" play. float fastplay_frequency; // Alpha value for Dirichlet noise. float dirichlet_alpha; // Fraction of noise to mix into the root node before performing reads. // Noise is not injected for "fast" plays. float noise_mix; // True if this game's data should be written to the `holdout_dir` instead // of the `output_dir`. bool is_holdout; // If true, subtract visits from all moves that weren't the best move until // the uncertainty level compensates. bool target_pruning; // If true, perform verbose logging. Usually restricted to just the first // `SelfplayGame` of the first `SelfplayThread`. bool verbose; // If false, pass is only read and played if there are no other legal // alternatives. bool allow_pass; // Disallow playing in pass-alive territory once the number of passes played // during a game is at least `restrict_pass_alive_play_threshold`. int restrict_pass_alive_play_threshold; }; // Stats about the nodes visited during SelectLeaves. struct SelectLeavesStats { int num_leaves_queued = 0; int num_nodes_selected = 0; int num_cache_hits = 0; int num_game_over_leaves = 0; SelectLeavesStats& operator+=(const SelectLeavesStats& other) { num_leaves_queued += other.num_leaves_queued; num_nodes_selected += other.num_nodes_selected; num_cache_hits += other.num_cache_hits; num_game_over_leaves += other.num_game_over_leaves; return *this; } }; SelfplayGame(int game_id, const Options& options, std::unique_ptr<Game> game, std::unique_ptr<MctsTree> tree); int game_id() const { return game_id_; } Game* game() { return game_.get(); } const Game* game() const { return game_.get(); } const MctsTree* tree() const { return tree_.get(); } absl::Duration duration() const { return duration_; } const Options& options() const { return options_; } const std::vector<std::string>& models_used() const { return models_used_; } // Selects leaves to perform inference on. // Returns the number of leaves selected. It is possible that no leaves will // be selected if all desired leaves are already in the inference cache. SelectLeavesStats SelectLeaves(InferenceCache* cache, std::vector<Inference>* inferences); // Processes the inferences selected by `SelectedLeaves` that were evaluated // by the SelfplayThread. void ProcessInferences(const std::string& model_name, absl::Span<const Inference> inferences); // Plays a move if the necessary number of nodes have been read. // Returns true if `MaybePlayMove` actually played a move. // Returns false if the `SeflplayGame` needs to read more positions before it // can play a move. bool MaybePlayMove(); private: // Randomly choose whether or not to fast play. bool ShouldFastplay(); // Returns true if the predicted win rate is below `resign_threshold`. bool ShouldResign() const; // Injects noise into the root. void InjectNoise(); // Returns the symmetry that should be when performing inference on this // node's position. symmetry::Symmetry GetInferenceSymmetry(const MctsNode* node) const; // Looks the `leaf` up in the inference cache: // - if found: propagates the cached inference result back up the tree. // - if not found: appends an element to `inferences` to perform inference // on `leaf`. // Returns true in an inference was queued. bool MaybeQueueInference(MctsNode* leaf, InferenceCache* cache, std::vector<Inference>* inferences); const Options options_; int target_readouts_; std::unique_ptr<Game> game_; std::unique_ptr<MctsTree> tree_; const bool use_ansi_colors_; const absl::Time start_time_; absl::Duration duration_; std::vector<std::string> models_used_; Random rnd_; const uint64_t inference_symmetry_mix_; // We need to wait until the root is expanded by the first call to // SelectLeaves in the game before injecting noise. bool inject_noise_before_next_read_ = false; // We don't allow fast play for the opening move: fast play relies to some // degree on tree reuse from earlier reads but the tree is empty at the start // of the game. bool fastplay_ = false; // Number of consecutive passes played by black and white respectively. // Used to determine when to disallow playing in pass-alive territory. // `num_consecutive_passes_` latches once it reaches // `restrict_pass_alive_play_threshold` is is not reset to 0 when a non-pass // move is played. int num_consecutive_passes_[2] = {0, 0}; const int game_id_; }; // The main application class. // Manages multiple SelfplayThread objects. // Each SelfplayThread plays multiple games concurrently, each one is // represented by a SelfplayGame. // The Selfplayer also has a OutputThread, which writes the results of completed // games to disk. class Selfplayer { public: Selfplayer(); void Run() LOCKS_EXCLUDED(&mutex_); std::unique_ptr<SelfplayGame> StartNewGame(bool verbose) LOCKS_EXCLUDED(&mutex_); void EndGame(std::unique_ptr<SelfplayGame> selfplay_game) LOCKS_EXCLUDED(&mutex_); // Exectutes `fn` on `parallel_search` threads in parallel on a shared // `ShardedExecutor`. // Concurrent calls to `ExecuteSharded` are executed sequentially, unless // `parallel_search == 1`. This blocking property can be used to pipeline // CPU tree search and GPU inference. void ExecuteSharded(std::function<void(int, int)> fn); // Grabs a model from a pool. If `selfplay_threads > parallel_inference`, // `AcquireModel` may block if a model isn't immediately available. std::unique_ptr<Model> AcquireModel(); // Gives a previously acquired model back to the pool. void ReleaseModel(std::unique_ptr<Model> model); private: void ParseFlags() EXCLUSIVE_LOCKS_REQUIRED(&mutex_); FeatureDescriptor InitializeModels(); void CreateModels(const std::string& path); void CheckAbortFile(); mutable absl::Mutex mutex_; MctsTree::Options tree_options_ GUARDED_BY(&mutex_); int num_games_remaining_ GUARDED_BY(&mutex_) = 0; Random rnd_ GUARDED_BY(&mutex_); WinStats win_stats_ GUARDED_BY(&mutex_); ThreadSafeQueue<std::unique_ptr<SelfplayGame>> output_queue_; ShardedExecutor executor_; ThreadSafeQueue<std::unique_ptr<Model>> models_; // The latest path that matches the model pattern. std::string latest_model_name_ GUARDED_BY(&mutex_); int next_game_id_ GUARDED_BY(&mutex_) = 1; std::unique_ptr<DirectoryWatcher> directory_watcher_; std::unique_ptr<PollThread> abort_file_watcher_; std::unique_ptr<WtfSaver> wtf_saver_; }; // Plays multiple games concurrently using `SelfplayGame` instances. class SelfplayThread : public Thread { public: SelfplayThread(int thread_id, Selfplayer* selfplayer, std::shared_ptr<InferenceCache> cache); private: void Run() override; // Starts new games playing. void StartNewGames(); // Selects leaves to perform inference on for all currently playing games. // The selected leaves are stored in `inferences_` and `inference_spans_` // maps contents of `inferences_` back to the `SelfplayGames` that they // came from. void SelectLeaves(); // Runs inference on the leaves selected by `SelectLeaves`. // Runs the name of the model that ran the inferences. std::string RunInferences(); // Calls `SelfplayGame::ProcessInferences` for all inferences performed. void ProcessInferences(const std::string& model); // Plays moves on all games that have performed sufficient reads. void PlayMoves(); struct TreeSearch { // Holds the span of inferences requested for a single `SelfplayGame`: // `pos` and `len` index into the `inferences` array. struct InferenceSpan { SelfplayGame* selfplay_game; size_t pos; size_t len; }; void Clear() { inferences.clear(); inference_spans.clear(); } std::vector<Inference> inferences; std::vector<InferenceSpan> inference_spans; }; Selfplayer* selfplayer_; int num_virtual_losses_ = 8; std::vector<std::unique_ptr<SelfplayGame>> selfplay_games_; std::unique_ptr<Model> model_; std::shared_ptr<InferenceCache> cache_; std::vector<TreeSearch> searches_; int num_games_finished_ = 0; const int thread_id_; }; // Writes SGFs and training examples for completed games to disk. class OutputThread : public Thread { public: OutputThread(int thread_id, FeatureDescriptor feature_descriptor, ThreadSafeQueue<std::unique_ptr<SelfplayGame>>* output_queue); private: void Run() override; void WriteOutputs(std::unique_ptr<SelfplayGame> selfplay_game); ThreadSafeQueue<std::unique_ptr<SelfplayGame>>* output_queue_; const std::string output_dir_; const std::string holdout_dir_; const std::string sgf_dir_; const FeatureDescriptor feature_descriptor_; }; } // namespace minigo #endif // MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_MINIGO_CC_CONCURRENT_SELFPLAY_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/cudnn/cudnn_norm_convolution-inl.h<|end_filename|> /* * 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. */ /*! * Copyright (c) 2015 by Contributors * \file cudnn_norm_convolution-inl.h * \brief * \author <NAME> */ #ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_NORM_CONVOLUTION_INL_H_ #define MXNET_OPERATOR_NN_CUDNN_CUDNN_NORM_CONVOLUTION_INL_H_ #include <mxnet/storage.h> #include <algorithm> #include <vector> #include <mutex> #include <string> #include <iostream> #include <sstream> #include <iomanip> #include <type_traits> #include "../convolution-inl.h" #include "../norm_convolution-inl.h" #include "../../../common/cuda_utils.h" #include "nhwc_batch_norm-inl.h" #include "cudnn_common_op.h" namespace mxnet { namespace op { #if MXNET_USE_CUDNN == 1 /*! * \brief The Operator used to perform normalized convolution using cuDNN kernels. */ template<typename DType> class CuDNNNormConvolutionOp { public: CuDNNNormConvolutionOp() #if CUDNN_VERSION >= 7600 : fwd_op_(CUDNN_FUSED_SCALE_BIAS_ACTIVATION_CONV_BNSTATS), bwd_wgrad_op_(CUDNN_FUSED_SCALE_BIAS_ACTIVATION_WGRAD), fnlz_train_op_(CUDNN_FUSED_BN_FINALIZE_STATISTICS_TRAINING), fnlz_inference_op_(CUDNN_FUSED_BN_FINALIZE_STATISTICS_INFERENCE) #endif { CUDNN_CALL(cudnnCreateTensorDescriptor(&in_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&equiv_scale_bias_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&out_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&in_stats_desc_)); CUDNN_CALL(cudnnCreateTensorDescriptor(&out_stats_desc_)); CUDNN_CALL(cudnnCreateFilterDescriptor(&filter_desc_)); CUDNN_CALL(cudnnCreateConvolutionDescriptor(&conv_desc_)); CUDNN_CALL(cudnnCreateActivationDescriptor(&activation_desc_)); parallelize_backward_kernels_ = Context::GetGPUStreamsPerWorker() >= 2; } ~CuDNNNormConvolutionOp() { CUDNN_CALL(cudnnDestroyTensorDescriptor(in_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(equiv_scale_bias_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(out_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(in_stats_desc_)); CUDNN_CALL(cudnnDestroyTensorDescriptor(out_stats_desc_)); CUDNN_CALL(cudnnDestroyFilterDescriptor(filter_desc_)); CUDNN_CALL(cudnnDestroyConvolutionDescriptor(conv_desc_)); CUDNN_CALL(cudnnDestroyActivationDescriptor(activation_desc_)); if (init_feature_vector_constants_) { init_feature_vector_constants_ = false; // We're probably at program exit, bypass the conventional approach of // mxnet::Storage::Get()->DirectFree(zeros_feature_vector_hdl_); CUDA_CALL(cudaFree(zeros_feature_vector_hdl_.dptr)); CUDA_CALL(cudaFree(ones_feature_vector_hdl_.dptr)); } } void Init(const NormConvolutionParam& param, bool output_stats, const std::vector<TShape>& in_shapes, const TShape& out_shape, const OpContext& ctx) { #if CUDNN_VERSION < 7600 LOG(FATAL) << "cuDNN version 7.6 or later is required."; #else using namespace mshadow; this->param_ = param; this->fwd_op_plan_output_stats_ = output_stats; InitBufferForParam(); auto cudnn_fwd_compute_type = convertToCuDNNDataType(mshadow::kFloat32); dtype_ = DataType<DType>::kCudnnFlag; // For float16 input type beta, gamma, mean, and average are stored in float32. // For other input types, these parameters have the same type as input dtype_param_ = (dtype_ == CUDNN_DATA_HALF) ? kFloat32 : DataType<DType>::kFlag; auto effective_layout = param_.layout.value(); switch (effective_layout) { // 1D normalizedConvolutions will be executed as 2D normalizedConvolutions with a height of 1. case mshadow::kNCW: effective_layout = mshadow::kNCHW; break; case mshadow::kNWC: effective_layout = mshadow::kNHWC; break; case mshadow::kCWN: effective_layout = mshadow::kCHWN; break; default: break; } MSHADOW_LAYOUT_SWITCH(effective_layout, Layout, { format_ = LayoutType<Layout>::kCudnnFlag; }); // Double check to make sure this class supports the operation if (!Supports(param, in_shapes[norm_conv::kData], ctx.run_ctx.ctx.dev_id)) LOG(FATAL) << "Unexpected unsupported use of NormConvolution op."; InitDescriptors(in_shapes, out_shape, cudnn_fwd_compute_type, output_stats, ctx); // Have cuDNN make a 'plan' for the fused op, returning the temp workspace size required. GetTempSize(ctx); // Create an equivalent BatchNormParam for the held instance of the NhwcBatchNormOp // Not needed for Backward bn_param_.eps = 0.0; // Not needed for Backward since running mean/var are updated by forward kernel. bn_param_.momentum = 0.f; // Finalize kernel can respond to fix_gamma = true bn_param_.fix_gamma = false; // use_global_stats will only be true for inference-only graphs where backward is not needed bn_param_.use_global_stats = false; // Should have no effect on NHWCBatchNorm::Backward() bn_param_.output_mean_var = true; // NormConvolution only supported for NHWC layouts CHECK_EQ(effective_layout, mshadow::kNHWC); bn_param_.axis = 3; // Only cudnn NormConvolution is implemented bn_param_.cudnn_off = false; // Copy act_type value from NormalizeConvolutionParam -> BatchNormParam if (param_.act_type.has_value()) bn_param_.act_type = param_.act_type; bn_param_.bn_group = 1; bn_param_.xbuf_ptr = 0U; if (!param_.no_norm) { int in_features = static_cast<int>(Features(in_shapes[norm_conv::kData])); FinalizeInit(param_, Shape1(in_features), ctx); } #endif // CUDNN_VERSION >= 7600 } void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data) { using namespace mshadow; size_t expected_inputs = norm_conv::NumInputs(param_.no_norm); size_t expected_outputs = norm_conv::NumOutputs(param_.no_norm); CHECK_EQ(in_data.size(), expected_inputs); CHECK_EQ(out_data.size(), expected_outputs); CHECK_EQ(req.size(), expected_outputs); // Finalize checks if (!param_.no_norm) { CHECK(req[norm_conv::kEquivScale] == kWriteTo || req[norm_conv::kEquivScale] == kNullOp); CHECK(req[norm_conv::kEquivBias] == kWriteTo || req[norm_conv::kEquivBias] == kNullOp); } // All inputs (except for the data and weight) should have // a shape equal to the one used to init the op for (size_t i = 0; i != in_data.size(); ++i) { if (i == static_cast<size_t>(norm_conv::kData) || i == static_cast<size_t>(norm_conv::WeightIdx(param_.no_norm))) continue; CHECK_EQ(in_data[i].shape_, init_shape_); } // All outputs (except for the first 3) should have a shape equal to the one used to init the op for (size_t i = 3; i != out_data.size(); ++i) { CHECK_EQ(out_data[i].shape_, init_shape_); } if (!param_.no_norm) FinalizeForward(ctx, in_data, req, out_data); Stream<gpu> *s = ctx.get_stream<gpu>(); Tensor<gpu, 1, DType> workspace = AllocateTempWorkspace(ctx, fwd_workspace_byte_); size_t workspace_size = TensorSizeBytes(workspace); // I/O's should have 2 more dims than the kernel dim int weight_idx = norm_conv::WeightIdx(param_.no_norm); DType *data_ptr = GetNdPtr(in_data[norm_conv::kData], param_.kernel.ndim() + 2, s); DType *wmat_ptr = GetNdPtr(in_data[weight_idx], param_.kernel.ndim() + 2, s); int in_features = static_cast<int>(Features(in_data[norm_conv::kData].shape_)); DType *equiv_scale_ptr = nullptr; DType *equiv_bias_ptr = nullptr; if (fprop_eq_scale_bias_ptr_type_ != CUDNN_PTR_NULL) { if (param_.no_norm) { equiv_scale_ptr = static_cast<DType *>(ones_feature_vector_hdl_.dptr); equiv_bias_ptr = static_cast<DType *>(zeros_feature_vector_hdl_.dptr); } else { equiv_scale_ptr = out_data[norm_conv::kEquivScale].get_with_shape<gpu, 1, DType>( Shape1(in_features), s).dptr_; equiv_bias_ptr = out_data[norm_conv::kEquivBias].get_with_shape<gpu, 1, DType>( Shape1(in_features), s).dptr_; } } DType *out_ptr = GetNdPtr(out_data[norm_conv::kOut], param_.kernel.ndim() + 2, s); // Make sure the op's present need for output_stats corresponds to the assumed need at the time // the 'plan' was made. bool needed_output_stats = CuDNNNormConvolutionOp::OutputStats(ctx, req); CHECK_EQ(needed_output_stats, fwd_op_plan_output_stats_) << "Improper instance lookup for CuDNNNormConvolutionOp: improper 'output_stats' bool."; int out_features = static_cast<int>(Features(out_data[norm_conv::kOut].shape_)); // No implementations of this op exist with DType = double, so output stats pointers // will always be float. float *sum_ptr = nullptr; float *sum_of_squares_ptr = nullptr; if (fwd_op_plan_output_stats_) { sum_ptr = out_data[norm_conv::kOutSum].get_with_shape<gpu, 1, float>( Shape1(out_features), s).dptr_; sum_of_squares_ptr = out_data[norm_conv::kOutSumOfSquares].get_with_shape<gpu, 1, float>( Shape1(out_features), s).dptr_; } CHECK_EQ(req[norm_conv::kOut], kWriteTo) << "In norm-conv output, expecting simple write of output, not add-to or inplace write."; #if CUDNN_VERSION < 7600 LOG(FATAL) << "cuDNN version 7.6 or later is required."; #else // This operator does not support output blending as specified by alpha or beta. // Set data input pointers in op instance fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_XDATA, data_ptr); fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_WDATA, wmat_ptr); fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQSCALE, equiv_scale_ptr); fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQBIAS, equiv_bias_ptr); // Set workspace input pointer in op instance fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_WORKSPACE, workspace.dptr_); fwd_op_.SetOpVariantParamAttrPtr(CUDNN_SCALAR_SIZE_T_WORKSPACE_SIZE_IN_BYTES, &workspace_size); // Set data output pointers in op instance fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_YDATA, out_ptr); fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_YSUM, sum_ptr); fwd_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_YSQSUM, sum_of_squares_ptr); // Launch forward operation fwd_op_.Execute(s->dnn_handle_); #endif // CUDNN_VERSION < 7600 } void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &fwd_in_data, const std::vector<TBlob> &fwd_out_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad) { using namespace mshadow; size_t expected_inputs = norm_conv::NumInputs(param_.no_norm); CHECK_EQ(fwd_in_data.size(), expected_inputs); // We expect to see an in_grad tensor for all inputs, // except the moving_mean and moving_var 'aux inputs'. CHECK_EQ(in_grad.size(), norm_conv::NumNonAuxInputs(param_.no_norm)); Stream<gpu> *s = ctx.get_stream<gpu>(); // RAII object to handle syncing of the underlying auxiliary stream with the primary stream SyncedGPUAuxStream s_wgrad = ctx.get_gpu_aux_stream(); size_t dgrad_kernels_workspace_offset_byte = parallelize_backward_kernels_ ? bwd_wgrad_workspace_byte_ : 0; // The temp space bytes requested to cover the kernels called directly by this routine (the // wgrad and conv-dgrag). The nhwc_bn_op.Backward() will also request a workspace to cover // the bn-dgrad (+ potentially the wgrad if parallelize_backward_kernels_ is true). size_t backward_workspace_byte = parallelize_backward_kernels_ ? bwd_wgrad_workspace_byte_ + bwd_dgrad_conv_workspace_byte_ : std::max(bwd_wgrad_workspace_byte_, bwd_dgrad_conv_workspace_byte_); Tensor<gpu, 1, DType> workspace = AllocateTempWorkspace(ctx, backward_workspace_byte); size_t workspace_size = TensorSizeBytes(workspace); // I/O's should have 2 more dims than the kernel dim int input_weight_idx = norm_conv::WeightIdx(param_.no_norm); int ingrad_weight_idx = norm_conv::BwdInGradIdx(input_weight_idx); // Ptr to the forward operation data input DType *data_ptr = GetNdPtr(fwd_in_data[norm_conv::kData], param_.kernel.ndim() + 2, s); // Ptr to the incoming gradient of the forward operation data output 'Y' (an input here) DType *y_grad_ptr = GetNdPtr(out_grad[norm_conv::kOut], param_.kernel.ndim() + 2, s); // Ptr to the outgoing gradient of the forward operation weight input (an output here) DType *wgt_grad_ptr = GetNdPtr(in_grad[ingrad_weight_idx], param_.kernel.ndim() + 2, s); int in_features = static_cast<int>(Features(fwd_in_data[norm_conv::kData].shape_)); DType *equiv_scale_ptr = nullptr; DType *equiv_bias_ptr = nullptr; if (wgrad_eq_scale_bias_ptr_type_ != CUDNN_PTR_NULL) { if (param_.no_norm) { equiv_scale_ptr = static_cast<DType *>(ones_feature_vector_hdl_.dptr); equiv_bias_ptr = static_cast<DType *>(zeros_feature_vector_hdl_.dptr); } else { equiv_scale_ptr = fwd_out_data[norm_conv::kBwdEquivScale].get_with_shape<gpu, 1, DType>( Shape1(in_features), s).dptr_; equiv_bias_ptr = fwd_out_data[norm_conv::kBwdEquivBias].get_with_shape<gpu, 1, DType>( Shape1(in_features), s).dptr_; } } #if CUDNN_VERSION < 7600 LOG(FATAL) << "cuDNN version 7.6 or later is required."; #else // WGRAD // This operator does not support output blending as specified by alpha or beta. // Set data input pointers in op instance bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_XDATA, data_ptr); bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_DYDATA, y_grad_ptr); // Here we supply equiv_scale and equiv_bias ptrs, though perhaps statically-initted ones bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQSCALE, equiv_scale_ptr); bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQBIAS, equiv_bias_ptr); // Set workspace input pointer in op instance bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_WORKSPACE, workspace.dptr_); bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_SCALAR_SIZE_T_WORKSPACE_SIZE_IN_BYTES, &workspace_size); // Set data output pointers in op instance bwd_wgrad_op_.SetOpVariantParamAttrPtr(CUDNN_PTR_DWDATA, wgt_grad_ptr); // Launch backward wgrad operation into the alternate stream (if enabled) bwd_wgrad_op_.Execute(s_wgrad.GetStream()->dnn_handle_); // DGRAD - convolution dgrad followed optionally by batchnorm dgrad if (req[conv::kData] != kNullOp) { // First: convolution dgrad typename DataType<DType>::ScaleType alpha = 1.0f; typename DataType<DType>::ScaleType beta = 0.0f; typename DataType<DType>::ScaleType beta_add = 1.0f; bool only_conv_dgrad_present = param_.no_norm && !param_.act_type.has_value(); typename DataType<DType>::ScaleType conv_dgrad_beta = (only_conv_dgrad_present && (req[norm_conv::kData] == kAddTo)) ? beta_add : beta; if (!only_conv_dgrad_present && (req[norm_conv::kData] == kAddTo)) LOG(FATAL) << "NormConvolution dgrad output summation not supported " "when applying stats (needs extra conv dgrad buffer not yet allocated)."; // Ptr to the forward operation weight input DType *wmat_ptr = GetNdPtr(fwd_in_data[input_weight_idx], param_.kernel.ndim() + 2, s); // Ptr to the outgoing gradient of the forward operation data input (an output here) DType *x_grad_ptr = GetNdPtr(in_grad[norm_conv::kData], param_.kernel.ndim() + 2, s); DType *dgrad_workspace_ptr = workspace.dptr_ + dgrad_kernels_workspace_offset_byte / sizeof(DType); size_t dgrad_workspace_byte = workspace_size - dgrad_kernels_workspace_offset_byte; // Launch conv dgrad into the primary stream, although with an offsetted workspace // pointer if dual-stream is enabled. CUDNN_CALL(cudnnConvolutionBackwardData(s->dnn_handle_, &alpha, filter_desc_, wmat_ptr, out_desc_, y_grad_ptr, conv_desc_, back_conv_dgrad_algo_, dgrad_workspace_ptr, dgrad_workspace_byte, &conv_dgrad_beta, in_desc_, x_grad_ptr)); // Second (if needed): batchnorm dgrad if (!only_conv_dgrad_present) { // The following unusual case is not typically found (e.g. in Resnet). if (param_.no_norm) LOG(FATAL) << "Relu activation with no_norm not yet supported."; // Prepare inputs of NHWCBatchnorm::Backward() // Note that the 1st input is the same as the 1st output, i.e. the Batchnorm // is operating 'in place' on the gradient as output by the convolution dgrad. TBlob not_used; std::vector<TBlob> bn_bwd_inputs{in_grad[norm_conv::kData], fwd_out_data[norm_conv::kBwdSavedMean], fwd_out_data[norm_conv::kBwdSavedInvStdDev], fwd_in_data[norm_conv::kData], fwd_in_data[norm_conv::kGamma], fwd_in_data[norm_conv::kBeta], not_used, not_used}; std::vector<OpReqType> bn_bwd_req{req[norm_conv::kData], req[norm_conv::BwdInGradIdx(norm_conv::kGamma)], req[norm_conv::BwdInGradIdx(norm_conv::kBeta)]}; std::vector<TBlob> bn_bwd_outputs{in_grad[norm_conv::kData], in_grad[norm_conv::BwdInGradIdx(norm_conv::kGamma)], in_grad[norm_conv::BwdInGradIdx(norm_conv::kBeta)]}; // This function will ask for a temp workspace and will get the same pointer // (as long as the workspace does not to be increased). This all works fine because // at this point the wgrad, conv-dgad and this bn-dgrad are all using the same stream. // The Init call is made prior to each Backward(), a historical result of transitioning // from a symbolic to a gluon (imperative) op style. nhwc_bn_op.Init(bn_param_); // Launch batchnorm backward into the primary stream. This will launch a kernel with // an offsetted workspace pointer if dual-stream is enabled. nhwc_bn_op.Backward(ctx, bn_bwd_inputs, bn_bwd_req, bn_bwd_outputs, dgrad_kernels_workspace_offset_byte); } } #endif // CUDNN_VERSION < 7600 } /*! * \brief Returns whether the norm convolution operation described by `param` * is supported. */ template <typename SupportedConvParam> static bool Supports(const SupportedConvParam &param, const TShape& in_data_shape, int dev_id) { using namespace mshadow; static_assert(std::is_same<SupportedConvParam, ConvolutionParam>::value || std::is_same<SupportedConvParam, NormConvolutionParam>::value, "Unsupported template specialization of NormConvolution::Supports()"); // Need cuDNN version >= 7.6 if (CUDNN_VERSION < 7600) return false; // Only Volta GPU arch (70) specifically supported. Not earlier arches or Turing (75). if (SMArch(dev_id) != 70) return false; // Only kNHWC and kNWC format supported auto layout_val = param.layout.value(); if (layout_val != kNWC && layout_val != kNHWC) return false; // Only 2D convolution supported if (param.kernel.ndim() != 2) return false; // Only 1x1 with no stride, or strided 3x3 supported if (!(param.kernel == TShape{3, 3}) && !(param.kernel == TShape{1, 1} && param.stride == TShape{1, 1})) return false; // No dilation supported if (param.dilate != TShape{1, 1}) return false; // No grouped convolution supported if (param.num_group != 1) return false; // Must have a multiple of 32 input features 'c' (assumes N..C layout). if (in_data_shape[in_data_shape.ndim()-1] % 32 != 0) return false; // Must have a multiple of 32 output features (== number of filters 'k') if (param.num_filter % 32 != 0) return false; // Op parameters are supported, assuming datatype is float16 return DataType<DType>::kFlag == kFloat16; } // Does the operator need to emit valid 'sum' and 'sum_of_squares' tensors? static bool OutputStats(const OpContext &ctx, const std::vector<OpReqType> &req) { // In processing validation samples on the training graph, req[] values // are equal to kWriteOp, but the outputs are not needed. // ctx.is_train == false identifies this case. return ctx.is_train && (NeedsOutput(norm_conv::kOutSum, req) || NeedsOutput(norm_conv::kOutSumOfSquares, req)); } private: static bool NeedsOutput(size_t output_index, const std::vector<OpReqType> &req) { return (req.size() > output_index) && (req[output_index] != kNullOp); } // Converts a TBlob to a 1D dptr of the specifed size, checking for that it's contiguous. DType *Get1dPtr(const TBlob &tb, int size, mshadow::Stream<gpu> *s) { mshadow::Tensor<gpu, 1, DType> data = tb.get<gpu, 1, DType>(s); CHECK_EQ(data.CheckContiguous(), true); return data.dptr_; } /*! * \brief Translate an mxnet datatype to the corresponding cudnnDataType_t. */ cudnnDataType_t convertToCuDNNDataType(int dtype) { cudnnDataType_t converted = CUDNN_DATA_FLOAT; // The following will always assign to `converted` or throw an exception. MSHADOW_REAL_TYPE_SWITCH(dtype, mxDType, { converted = mshadow::DataType<mxDType>::kCudnnFlag; }) return converted; } void FinalizeInit(const NormConvolutionParam &param, const TShape shape, const OpContext &ctx) { CHECK_GE(param.eps, CUDNN_BN_MIN_EPSILON) << "CuDNN requires eps to be no less than " << CUDNN_BN_MIN_EPSILON; FinalizeInitDescriptors(shape); #if CUDNN_VERSION >= 7600 // Set up the 'Const Param Pack' for the BNForwardFinalizeStatisticsTraining op // Describe pointer alignments fnlz_train_op_.SetOpConstParamAttr({CUDNN_PARAM_YSUM_PLACEHOLDER, CUDNN_PARAM_YSQSUM_PLACEHOLDER, CUDNN_PARAM_BN_SCALE_PLACEHOLDER, CUDNN_PARAM_BN_BIAS_PLACEHOLDER, CUDNN_PARAM_BN_SAVED_MEAN_PLACEHOLDER, CUDNN_PARAM_BN_SAVED_INVSTD_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_MEAN_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_VAR_PLACEHOLDER, CUDNN_PARAM_BN_EQSCALE_PLACEHOLDER, CUDNN_PARAM_BN_EQBIAS_PLACEHOLDER}, CUDNN_PTR_ELEM_ALIGNED); // Set the I/O descriptors // sum and sum_squares input descriptor (typically fp32). Also // scale, bias, running_mean and running_var input descriptors, as well as the // saved_mean and saved_inv_std output descriptor (typically fp32) fnlz_train_op_.SetOpConstParamDesc({CUDNN_PARAM_YSTATS_DESC, CUDNN_PARAM_BN_SCALEBIAS_MEANVAR_DESC}, in_stats_desc_); // equiv_scale and equiv_bias output descriptor (typically fp16) fnlz_train_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_EQSCALEBIAS_DESC, equiv_scale_bias_desc_); // Set up the 'Const Param Pack' for the BNForwardFinalizeStatisticsInference op fnlz_inference_op_.SetOpConstParamAttr({CUDNN_PARAM_BN_SCALE_PLACEHOLDER, CUDNN_PARAM_BN_BIAS_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_MEAN_PLACEHOLDER, CUDNN_PARAM_BN_RUNNING_VAR_PLACEHOLDER, CUDNN_PARAM_BN_EQSCALE_PLACEHOLDER, CUDNN_PARAM_BN_EQBIAS_PLACEHOLDER}, CUDNN_PTR_ELEM_ALIGNED); // Set the I/O descriptors // scale, bias, running_mean and running_var input descriptors, as well as the // saved_mean and saved_inv_std output descriptor (typically fp32) fnlz_inference_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_SCALEBIAS_MEANVAR_DESC, in_stats_desc_); // equiv_scale and equiv_bias output descriptor (typically fp16) fnlz_inference_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_EQSCALEBIAS_DESC, equiv_scale_bias_desc_); // Perform some actions identically on both train and inference ops. mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); for (auto op : {&fnlz_train_op_, &fnlz_inference_op_}) { // Set the mode parameter in the ops, can't be CUDNN_BATCHNORM_PER_ACTIVATION. op->SetOpConstParamAttr(CUDNN_PARAM_BN_MODE, CUDNN_BATCHNORM_SPATIAL); // Check workspace size, also creates 'plan'. size_t workspace_size_bytes = op->GetWorkspaceSizeInBytes(s->dnn_handle_); CHECK_EQ(workspace_size_bytes, 0U) << "Unexpected non-zero workspace size for CuDNNBNStatsFinalize op."; op->SetOpVariantParamAttrPtr(CUDNN_PTR_WORKSPACE, static_cast<void *>(nullptr)); op->SetOpVariantParamAttrPtr(CUDNN_PTR_WORKSPACE, &workspace_size_bytes); } #endif } void FinalizeForward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data) { using namespace mshadow; using namespace mshadow::expr; int in_features = in_data[norm_conv::kInSum].shape_[0]; auto in_feature_shape = Shape1(in_features); Stream<gpu> *s = ctx.get_stream<gpu>(); DType *equiv_scale = Get1dPtr(out_data[norm_conv::kEquivScale], in_features, s); DType *equiv_bias = Get1dPtr(out_data[norm_conv::kEquivBias], in_features, s); #if CUDNN_VERSION < 7600 LOG(FATAL) << "cuDNN version 7.6 or later is required."; #else MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, { Tensor<gpu, 1, DTypeParam> sum = in_data[norm_conv::kInSum] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); Tensor<gpu, 1, DTypeParam> sum_squares = in_data[norm_conv::kInSumOfSquares] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); Tensor<gpu, 1, DTypeParam> gamma = in_data[norm_conv::kGamma] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); Tensor<gpu, 1, DTypeParam> beta = in_data[norm_conv::kBeta] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); Tensor<gpu, 1, DTypeParam> moving_mean = in_data[norm_conv::kMovingMean] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); Tensor<gpu, 1, DTypeParam> moving_inv_var = in_data[norm_conv::kMovingVar] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); if (param_.fix_gamma) gamma = 1.f; auto &op = ctx.is_train ? fnlz_train_op_ : fnlz_inference_op_; // The prep needed for the train_op_ is a superset of that needed for the inference_op_. // Start here with the common prep needed for the inference_op_: // Set data pointers in the 'variant param pack' op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_SCALE, gamma.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_BIAS, beta.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_RUNNING_MEAN, moving_mean.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_RUNNING_VAR, moving_inv_var.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQSCALE, equiv_scale); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_EQBIAS, equiv_bias); // Set some additional light-weight parameters in the 'variant param pack' op.SetOpVariantParamAttrPtr<double>(CUDNN_SCALAR_DOUBLE_BN_EPSILON, &param_.eps); // Now add additional prep needed only for train_op_: if (ctx.is_train) { Tensor<gpu, 1, DTypeParam> save_mean = out_data[norm_conv::kSavedMean] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); Tensor<gpu, 1, DTypeParam> save_inv_var = out_data[norm_conv::kSavedInvStdDev] .get_with_shape<gpu, 1, DTypeParam>(in_feature_shape, s); // Set data pointers in the 'variant param pack' op.SetOpVariantParamAttrPtr(CUDNN_PTR_YSUM, sum.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_YSQSUM, sum_squares.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_SAVED_MEAN, save_mean.dptr_); op.SetOpVariantParamAttrPtr(CUDNN_PTR_BN_SAVED_INVSTD, save_inv_var.dptr_); // Set some additional light-weight parameters in the 'variant param pack' int64_t elem_count = in_data[norm_conv::kData].shape_.Size() / in_features; double avg_factor = 1.0 - param_.momentum; op.SetOpVariantParamAttrPtr(CUDNN_SCALAR_INT64_T_BN_ACCUMULATION_COUNT, &elem_count); op.SetOpVariantParamAttrPtr(CUDNN_SCALAR_DOUBLE_BN_EXP_AVG_FACTOR, &avg_factor); } // Finally, launch op op.Execute(s->dnn_handle_); }) #endif // CUDNN_VERSION >= 7600 } void FinalizeInitDescriptors(const TShape &shape) { using namespace mshadow; init_shape_ = shape; CHECK_EQ(init_shape_.ndim(), 1) << "Expecting 1D 'sum' input."; int c = init_shape_[0]; cudnnTensorFormat_t format = CUDNN_TENSOR_NHWC; MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, { CUDNN_CALL(cudnnSetTensor4dDescriptor(in_stats_desc_, format, DataType<DTypeParam>::kCudnnFlag, 1, c, 1, 1)); }) } void InitDescriptors(const std::vector<TShape>& in_shapes, const TShape& out_shape, cudnnDataType_t cudnn_fwd_compute_type, bool output_stats, const OpContext& ctx) { using namespace mshadow; size_t expected_inputs = norm_conv::NumInputs(param_.no_norm); CHECK_EQ(in_shapes.size(), expected_inputs); TShape dshape = in_shapes[norm_conv::kData]; int weight_idx = norm_conv::WeightIdx(param_.no_norm); TShape wshape = in_shapes[weight_idx]; TShape oshape = out_shape; TShape dstride, ostride; #if CUDNN_VERSION < 7600 LOG(FATAL) << "cuDNN version 7.6 or later is required."; #else bool no_activation = !param_.act_type.has_value(); // We'll need normconv fprop if we're doing a normalization, activation, or outputting stats. bool fused_normconv_fprop_needed = !param_.no_norm || !no_activation || output_stats; // We only supply a null pointer if we think cuDNN can then fall back to the conventional fprop. fprop_eq_scale_bias_ptr_type_ = fused_normconv_fprop_needed ? CUDNN_PTR_16B_ALIGNED : CUDNN_PTR_NULL; // We'll need normconv wgrad if we're doing a normalization or activation. bool fused_normconv_wgrad_needed = !param_.no_norm || !no_activation; // We only supply a null pointer if we think cuDNN can then fall back to the conventional wgrad. wgrad_eq_scale_bias_ptr_type_ = fused_normconv_wgrad_needed ? CUDNN_PTR_16B_ALIGNED : CUDNN_PTR_NULL; auto stats_ptr_type = output_stats ? CUDNN_PTR_16B_ALIGNED : CUDNN_PTR_NULL; // Describe i/o tensor pointer alignment for forward fused op fwd_op_.SetOpConstParamAttr({CUDNN_PARAM_XDATA_PLACEHOLDER, CUDNN_PARAM_WDATA_PLACEHOLDER, CUDNN_PARAM_YDATA_PLACEHOLDER}, CUDNN_PTR_16B_ALIGNED); fwd_op_.SetOpConstParamAttr({CUDNN_PARAM_BN_EQSCALE_PLACEHOLDER, CUDNN_PARAM_BN_EQBIAS_PLACEHOLDER}, fprop_eq_scale_bias_ptr_type_); fwd_op_.SetOpConstParamAttr({CUDNN_PARAM_YSUM_PLACEHOLDER, CUDNN_PARAM_YSQSUM_PLACEHOLDER}, stats_ptr_type); // Describe i/o tensor pointer alignment for backward wgrad fused op bwd_wgrad_op_.SetOpConstParamAttr({CUDNN_PARAM_DYDATA_PLACEHOLDER, CUDNN_PARAM_XDATA_PLACEHOLDER, CUDNN_PARAM_DWDATA_PLACEHOLDER}, CUDNN_PTR_16B_ALIGNED); bwd_wgrad_op_.SetOpConstParamAttr({CUDNN_PARAM_BN_EQSCALE_PLACEHOLDER, CUDNN_PARAM_BN_EQBIAS_PLACEHOLDER}, wgrad_eq_scale_bias_ptr_type_); if (param_.kernel.ndim() == 1 || param_.kernel.ndim() == 2) { // 1d or 2d conv auto pad = param_.kernel.ndim() == 2 ? param_.pad : TShape({0, param_.pad[0]}); auto stride = param_.kernel.ndim() == 2 ? param_.stride : TShape({1, param_.stride[0]}); auto dilate = param_.kernel.ndim() == 2 ? param_.dilate : TShape({1, param_.dilate[0]}); CUDNN_CALL(cudnnSetConvolution2dDescriptor(conv_desc_, pad[0], pad[1], stride[0], stride[1], dilate[0], dilate[1], CUDNN_CROSS_CORRELATION, cudnn_fwd_compute_type)); if (param_.kernel.ndim() == 2) { wshape = ConvertLayout(wshape.get<4>(), param_.layout.value(), kNCHW); dstride = ConvertLayout(Strides<4>(dshape), param_.layout.value(), kNCHW); dshape = ConvertLayout(dshape.get<4>(), param_.layout.value(), kNCHW); ostride = ConvertLayout(Strides<4>(oshape), param_.layout.value(), kNCHW); oshape = ConvertLayout(oshape.get<4>(), param_.layout.value(), kNCHW); } else { wshape = ConvertLayout(wshape.get<3>(), param_.layout.value(), kNCW); wshape = TShape({wshape[0], wshape[1], 1, wshape[2]}); dstride = ConvertLayout(Strides<3>(dshape), param_.layout.value(), kNCW); dstride = TShape({dstride[0], dstride[1], dstride[1], dstride[2]}); dshape = ConvertLayout(dshape.get<3>(), param_.layout.value(), kNCW); dshape = TShape({dshape[0], dshape[1], 1, dshape[2]}); ostride = ConvertLayout(Strides<3>(oshape), param_.layout.value(), kNCW); ostride = TShape({ostride[0], ostride[1], ostride[1], ostride[2]}); oshape = ConvertLayout(oshape.get<3>(), param_.layout.value(), kNCW); oshape = TShape({oshape[0], oshape[1], 1, oshape[2]}); } CUDNN_CALL(cudnnSetFilter4dDescriptor(filter_desc_, dtype_, format_, wshape[0], wshape[1], wshape[2], wshape[3])); } else if (param_.kernel.ndim() == 3) { LOG(FATAL) << "3D NormConvolution not supported."; } cudnnMathType_t math_type = CUDNN_TENSOR_OP_MATH; if (GetEnvAllowTensorCore() && GetEnvAllowTensorCoreConversion() && (DataType<DType>::kFlag != kFloat16)) math_type = CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION; CUDNN_CALL(cudnnSetConvolutionMathType(conv_desc_, math_type)); CUDNN_CALL(cudnnSetConvolutionGroupCount(conv_desc_, param_.num_group)); std::vector<int> dshape_buffer(dshape.ndim()); nnvm::ShapeTypeCast(dshape.begin(), dshape.end(), dshape_buffer.data()); std::vector<int> dstride_buffer(dstride.ndim()); nnvm::ShapeTypeCast(dstride.begin(), dstride.end(), dstride_buffer.data()); CUDNN_CALL(cudnnSetTensorNdDescriptor(in_desc_, dtype_, static_cast<int>(dshape.ndim()), dshape_buffer.data(), dstride_buffer.data())); std::vector<int> oshape_buffer(oshape.ndim()); nnvm::ShapeTypeCast(oshape.begin(), oshape.end(), oshape_buffer.data()); std::vector<int> ostride_buffer(ostride.ndim()); nnvm::ShapeTypeCast(ostride.begin(), ostride.end(), ostride_buffer.data()); CUDNN_CALL(cudnnSetTensorNdDescriptor(out_desc_, dtype_, static_cast<int>(oshape.ndim()), oshape_buffer.data(), ostride_buffer.data())); // Always set scale/bias descriptors int in_features = static_cast<int>(Features(in_shapes[norm_conv::kData])); TShape equiv_scale_bias_shape = TShape({in_features}); std::vector<int> equiv_scale_shape = {1, static_cast<int>(in_features), 1, 1}; std::vector<int> equiv_scale_stride = {static_cast<int>(in_features), 1, 1, 1}; CUDNN_CALL(cudnnSetTensorNdDescriptor(equiv_scale_bias_desc_, dtype_, static_cast<int>(equiv_scale_shape.size()), &equiv_scale_shape[0], &equiv_scale_stride[0])); fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_EQSCALEBIAS_DESC, equiv_scale_bias_desc_); bwd_wgrad_op_.SetOpConstParamDesc(CUDNN_PARAM_BN_EQSCALEBIAS_DESC, equiv_scale_bias_desc_); if (!param_.no_norm) { CHECK_EQ(equiv_scale_bias_shape, in_shapes[norm_conv::kInSum]) << "Expecting equal equivalent-scale and sum input tensor shapes."; CHECK_EQ(equiv_scale_bias_shape, in_shapes[norm_conv::kInSumOfSquares]) << "Expecting equal equivalent-scale and sum_squares input tensor shapes."; CHECK_EQ(equiv_scale_bias_shape, in_shapes[norm_conv::kMovingMean]) << "Expecting equal equivalent-scale and saved-mean input tensor shapes."; CHECK_EQ(equiv_scale_bias_shape, in_shapes[norm_conv::kMovingVar]) << "Expecting equal equivalent-scale and saved-inv-stddev input tensor shapes."; CHECK_EQ(equiv_scale_bias_shape, in_shapes[norm_conv::kGamma]) << "Expecting equal equivalent-scale and gamma input tensor shapes."; CHECK_EQ(equiv_scale_bias_shape, in_shapes[norm_conv::kBeta]) << "Expecting equal equivalent-scale and beta input tensor shapes."; } if (output_stats) { // Replace with checks at every Forward()? // TShape sum_shape = out_shape[norm_conv::kOutSum]; // TShape sum_of_squares_shape = out_shape[norm_conv::kOutSumOfSquares]; // CHECK_EQ(sum_shape, sum_of_squares_shape) << // "Expecting equal sum and sum_of_squares output tensor shapes."; int output_features = static_cast<int>(Features(out_shape)); std::vector<int> stats_shape = {1, output_features, 1, 1}; std::vector<int> stats_stride = {output_features, 1, 1, 1}; // Stats are output in the same precision as the forward compute (i.e. float32) CUDNN_CALL(cudnnSetTensorNdDescriptor(out_stats_desc_, cudnn_fwd_compute_type, static_cast<int>(stats_shape.size()), &stats_shape[0], &stats_stride[0])); fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_YSTATS_DESC, out_stats_desc_); } // Here's where the standard convolution does a 'SelectAlgo', which may run cudnnFind() // Not available yet for the NormConvolution operation. // If we're allowing Tensor Core variants of the algos to be considered in // Copied temporarily from 'SelectAlgo': probably not needed // *Find*() or *Get*(), but a non-Tensor-Core algo variant is the fastest, // we must change the descriptor to preclude Tensor Core. Simplest is to // once again set the mathType in all cases. CUDNN_CALL(cudnnSetConvolutionMathType(conv_desc_, CUDNN_TENSOR_OP_MATH)); // Set activation descriptor, default is no activation cudnnActivationMode_t mode = CUDNN_ACTIVATION_IDENTITY; if (param_.act_type.has_value()) { CHECK_EQ(param_.act_type.value(), activation::kReLU) << "Only relu activation supported in normalized convolution."; mode = CUDNN_ACTIVATION_RELU; } auto nan_prop = CUDNN_NOT_PROPAGATE_NAN; double dummy_clip = 0.0; CUDNN_CALL(cudnnSetActivationDescriptor(activation_desc_, mode, nan_prop, dummy_clip)); // Currently, the only way to turn off activation is to not set the descriptor if (mode != CUDNN_ACTIVATION_IDENTITY) { fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_ACTIVATION_DESC, activation_desc_); bwd_wgrad_op_.SetOpConstParamDesc(CUDNN_PARAM_ACTIVATION_DESC, activation_desc_); } // Set desc pointers fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_XDESC, in_desc_); bwd_wgrad_op_.SetOpConstParamDesc(CUDNN_PARAM_XDESC, in_desc_); // FusedOp does not accept CUDNN_BATCHNORM_PER_ACTIVATION fwd_op_.SetOpConstParamAttr(CUDNN_PARAM_BN_MODE, CUDNN_BATCHNORM_SPATIAL); bwd_wgrad_op_.SetOpConstParamAttr(CUDNN_PARAM_BN_MODE, CUDNN_BATCHNORM_SPATIAL); // The Cudnn Convolution op provides parameters for controlling math precision // separately for forward and backward, and so there are separate forward and backward conv // descriptors. However, NormConvolution does not have these extra parameters, so the // same descriptor can be used for both. fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_CONV_DESC, conv_desc_); bwd_wgrad_op_.SetOpConstParamDesc(CUDNN_PARAM_CONV_DESC, conv_desc_); // W desc for forward == dW desc for backward wgrad fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_WDESC, filter_desc_); bwd_wgrad_op_.SetOpConstParamDesc(CUDNN_PARAM_DWDESC, filter_desc_); // Y desc for forward == dY desc for backward wgrad fwd_op_.SetOpConstParamDesc(CUDNN_PARAM_YDESC, out_desc_); bwd_wgrad_op_.SetOpConstParamDesc(CUDNN_PARAM_DYDESC, out_desc_); #endif // CUDNN_VERSION < 7600 // Set up 0.f and 1.f constant vectors if we're running in no-apply mode if ((fprop_eq_scale_bias_ptr_type_ != CUDNN_PTR_NULL || wgrad_eq_scale_bias_ptr_type_ != CUDNN_PTR_NULL) && param_.no_norm && !init_feature_vector_constants_) { size_t equiv_scale_bytes = in_features * sizeof(DType); Stream<gpu> *s = ctx.get_stream<gpu>(); zeros_feature_vector_hdl_ = mxnet::Storage::Get()->Alloc(equiv_scale_bytes, Context::GPU()); // Zero the read-only zeros_feature_vector_hdl_ area once. CUDA_CALL(cudaMemsetAsync(zeros_feature_vector_hdl_.dptr, 0, equiv_scale_bytes, mshadow::Stream<gpu>::GetStream(s))); ones_feature_vector_hdl_ = mxnet::Storage::Get()->Alloc(equiv_scale_bytes, Context::GPU()); // Setting this up as 1's is a little tricky. Not sure if the cuMemsetD32Async would // have endian issues. TBlob ones_tblob(ones_feature_vector_hdl_.dptr, equiv_scale_bias_shape, gpu::kDevMask, DataType<DType>::kFlag, ctx.run_ctx.ctx.dev_id); auto ones_tensor = ones_tblob.get_with_shape<gpu, 1, DType>(Shape1(in_features), s); // Now init the ones tensor ones_tensor = 1.f; init_feature_vector_constants_ = true; } } void GetTempSize(const OpContext& ctx) { mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); // Make op plan for forward op and set forward workspace size fwd_workspace_byte_ = fwd_op_.GetWorkspaceSizeInBytes(s->dnn_handle_); // Make op plan for backward wgrad op and set backward wgrad workspace size bwd_wgrad_workspace_byte_ = bwd_wgrad_op_.GetWorkspaceSizeInBytes(s->dnn_handle_); // Get workspace for backward dgrad- convolution requirement CUDNN_CALL(cudnnGetConvolutionBackwardDataWorkspaceSize(s->dnn_handle_, filter_desc_, out_desc_, conv_desc_, in_desc_, back_conv_dgrad_algo_, &bwd_dgrad_conv_workspace_byte_)); // cudaMalloc returns addresses that are aligned for large accesses (e.g. to 512 bytes). // Since we may make one allocation and divide it into two parts when we parallelize // the dgrad and wgrad kernels, we round the size of the wgrad tempspace up to this // alignment size so the temp space dptrs for the dgrad kernels will respect this alignment // when stacked on top of the wgrad temp area. const size_t dptr_alignment = 512; bwd_wgrad_workspace_byte_ = RoundToMultiple(bwd_wgrad_workspace_byte_, dptr_alignment); } int *CastTShapeToIntPtr(const TShape& s, std::vector<int> *buffer) { buffer->resize(s.ndim()); nnvm::ShapeTypeCast(s.begin(), s.end(), buffer->data()); return buffer->data(); } // Converts a TBlob to a dptr, checking for the expected dim and that it's contiguous. DType *GetNdPtr(const TBlob& tb, int dim, Stream<gpu> *s) { DType *data_ptr = NULL; if (dim == 3) { Tensor<gpu, 3, DType> data = tb.get<gpu, 3, DType>(s); CHECK_EQ(data.CheckContiguous(), true); data_ptr = data.dptr_; } else if (dim == 4) { Tensor<gpu, 4, DType> data = tb.get<gpu, 4, DType>(s); CHECK_EQ(data.CheckContiguous(), true); data_ptr = data.dptr_; } else if (dim == 5) { Tensor<gpu, 5, DType> data = tb.get<gpu, 5, DType>(s); CHECK_EQ(data.CheckContiguous(), true); data_ptr = data.dptr_; } else { LOG(FATAL) << "Unexpected Tensor size " << dim << ", supporting only 3, 4 or 5."; } return data_ptr; } // Converts a TShape to a Shape<> of strides. // e.g. {shape[0], shape[1], shape[2]} -> {shape[1]*shape[2], shape[2], 1} template <int dim> inline Shape<dim> Strides(const TShape &s) { uint32_t ndim = s.ndim(); TShape strides(ndim, -1); for (uint32_t i = 0; i != ndim; ++i) strides[i] = s.ProdShape(i+1, ndim); return strides.get<dim>(); } void InitBufferForParam() { CastTShapeToIntPtr(param_.stride, &param_stride_); CastTShapeToIntPtr(param_.dilate, &param_dilate_); CastTShapeToIntPtr(param_.pad, &param_pad_); } // Round a value 'x' up to the next multiple of 'multiple' size_t RoundToMultiple(size_t x, size_t multiple) { size_t retVal = ((x + multiple - 1) / multiple) * multiple; return retVal; } // Allocates a 1D Tensor of words with size in bytes >= `size_bytes`. // Always allocates at least one word. mshadow::Tensor<gpu, 1, DType> AllocateTempWorkspace(const OpContext &ctx, size_t size_bytes) { mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); size_t size_words = std::max<size_t>(1, RoundToMultiple(size_bytes, sizeof(DType)) / sizeof(DType)); return ctx.requested[norm_conv::kTempSpace].get_space_typed<gpu, 1, DType>( mshadow::Shape1(size_words), s); } // Returns the size in bytes of the 1D Tensor of words. size_t TensorSizeBytes(const mshadow::Tensor<gpu, 1, DType> &tensor) { return tensor.MSize() * sizeof(DType); } // Given a tensor shape of this operation, return the number of features 'c' int64_t Features(const TShape &dshape) { int c = 0; switch (dshape.ndim()) { case 3: c = ConvertLayout(dshape.get<3>(), param_.layout.value(), kNCW)[1]; break; case 4: c = ConvertLayout(dshape.get<4>(), param_.layout.value(), kNCHW)[1]; break; case 5: c = ConvertLayout(dshape.get<5>(), param_.layout.value(), kNCDHW)[1]; break; default: LOG(FATAL) << "Unexpected convolution data dimension " << dshape.ndim(); } return c; } std::vector<int> param_stride_; std::vector<int> param_dilate_; std::vector<int> param_pad_; // Temp workspace size in bytes needed for Forward() operation. size_t fwd_workspace_byte_; // Temp workspace size in bytes needed for Backward() wgrad operation. size_t bwd_wgrad_workspace_byte_; // Temp workspace size in bytes needed for Backward() dgrad operation (conv portion). size_t bwd_dgrad_conv_workspace_byte_; // The hardwired backward dgrad convolution algo cudnnConvolutionBwdDataAlgo_t back_conv_dgrad_algo_ = CUDNN_CONVOLUTION_BWD_DATA_ALGO_1; // Should dgrad and wgrad be launched into separate streams bool parallelize_backward_kernels_; cudnnDataType_t dtype_; cudnnTensorDescriptor_t in_desc_; cudnnTensorDescriptor_t equiv_scale_bias_desc_; cudnnFilterDescriptor_t filter_desc_; cudnnTensorDescriptor_t out_desc_; cudnnTensorDescriptor_t in_stats_desc_; cudnnTensorDescriptor_t out_stats_desc_; // Convolution descriptor for forward and backward operation (same math type used in both) cudnnConvolutionDescriptor_t conv_desc_; cudnnTensorFormat_t format_; NormConvolutionParam param_; // The assumption of the fwd_op plan as to whether sum and sum_of_squares outputs are populated. bool fwd_op_plan_output_stats_; // A cached copy of the fwd_op plan ptr placeholder for equiv_stats and equiv_bias. cudnnFusedOpsPointerPlaceHolder_t fprop_eq_scale_bias_ptr_type_; // A cached copy of the bwd_op plan ptr placeholder for equiv_stats and equiv_bias. cudnnFusedOpsPointerPlaceHolder_t wgrad_eq_scale_bias_ptr_type_; // An instance of the equivalent Batchnorm operation, suitable for calling Backward() on. NhwcBatchNormOp<DType> nhwc_bn_op; // The BatchNormParam associated with the NHWCBatchNormOp instance BatchNormParam bn_param_; bool init_feature_vector_constants_ = false; mxnet::Storage::Handle zeros_feature_vector_hdl_; mxnet::Storage::Handle ones_feature_vector_hdl_; // Specifies activation parameters: relu cudnnActivationDescriptor_t activation_desc_; // data members to support finalize function int dtype_param_; // The shape used to init the in_stats_desc of the finalize op TShape init_shape_; #if CUDNN_VERSION >= 7600 // New normalized convolution forward fused-op CuDNNCommonOp fwd_op_; // New normalized convolution backward wgrad fused-op CuDNNCommonOp bwd_wgrad_op_; // New 'fused op' for BN stats finalize forward (training mode) CuDNNCommonOp fnlz_train_op_; // New 'fused op' for BN stats finalize forward (inference mode) CuDNNCommonOp fnlz_inference_op_; #endif }; #endif // __CUDACC__ && CUDNN } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_CUDNN_CUDNN_NORM_CONVOLUTION_INL_H_ <|start_filename|>Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-512/util/roc_metrics/roc_metrics.h<|end_filename|> #ifndef _THIRD_PARTY_MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_UTIL_ROC_METRICS_ROC_METRICS_H_ #define _THIRD_PARTY_MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_UTIL_ROC_METRICS_ROC_METRICS_H_ #include <Python.h> #include <vector> #include "REDACTEDtypes/span.h" #include "third_party/py/numpy/core/include/numpy/arrayobject.h" namespace rocmetrics { // Computes ROC-based metrics for single-class binary classifiers. struct PredictElem { float score; int target; }; struct RocData { std::vector<int> tps; std::vector<int> fps; }; class RocMetrics { public: // Create an RocMetrics object with predictions py_scores and targets // py_objects are numpy array objects. explicit RocMetrics(PyObject* py_scores, PyObject* py_targets); // RocMetrics is designed to be used in a roughly singleton fashion. RocMetrics(const RocMetrics& other) = delete; RocMetrics& operator=(const RocMetrics& other) = delete; // Computes the area under the ROC curve. float ComputeRocAuc(); // Computes the raw ROC vectors: TPS and FPS. These can be normalized to TPR // and FPR via element-wise division with the final value, vec.back(). // The algorithm is a combination of a cumulative sum on the targets, a // filtering operation, and an averaging of duplicated score contributions. RocData BinaryRoc() const; private: // Container for the full set of predictions and targets. std::vector<PredictElem> full_data_; }; } // namespace rocmetrics #endif // _THIRD_PARTY_MLPERF_SUBMISSIONS_TRAINING_V0_7_MODELS_PROD_UTIL_ROC_METRICS_ROC_METRICS_H_ <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/gtests/ocl/api/test_stream.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mkldnn_test_common.hpp" #include "gtest/gtest.h" #include "mkldnn.h" #include <CL/cl.h> #include <memory> namespace mkldnn { class ocl_stream_test_c : public ::testing::Test { protected: virtual void SetUp() { if (!find_ocl_device(CL_DEVICE_TYPE_GPU)) { return; } MKLDNN_CHECK(mkldnn_engine_create(&eng, mkldnn_gpu, 0)); MKLDNN_CHECK(mkldnn_engine_get_ocl_context(eng, &ocl_ctx)); MKLDNN_CHECK(mkldnn_engine_get_ocl_device(eng, &ocl_dev)); } virtual void TearDown() { if (eng) { MKLDNN_CHECK(mkldnn_engine_destroy(eng)); } } mkldnn_engine_t eng = nullptr; cl_context ocl_ctx = nullptr; cl_device_id ocl_dev = nullptr; }; class ocl_stream_test_cpp : public ::testing::Test { protected: virtual void SetUp() { if (!find_ocl_device(CL_DEVICE_TYPE_GPU)) { return; } eng = engine(engine::kind::gpu, 0); ocl_ctx = eng.get_ocl_context(); ocl_dev = eng.get_ocl_device(); } engine eng; cl_context ocl_ctx = nullptr; cl_device_id ocl_dev = nullptr; }; TEST_F(ocl_stream_test_c, CreateC) { SKIP_IF(!find_ocl_device(CL_DEVICE_TYPE_GPU), "OpenCL GPU devices not found."); mkldnn_stream_t stream; MKLDNN_CHECK( mkldnn_stream_create(&stream, eng, mkldnn_stream_default_flags)); cl_command_queue ocl_queue; MKLDNN_CHECK(mkldnn_stream_get_ocl_command_queue(stream, &ocl_queue)); cl_device_id ocl_queue_dev; cl_context ocl_queue_ctx; OCL_CHECK(clGetCommandQueueInfo(ocl_queue, CL_QUEUE_DEVICE, sizeof(ocl_queue_dev), &ocl_queue_dev, nullptr)); OCL_CHECK(clGetCommandQueueInfo(ocl_queue, CL_QUEUE_CONTEXT, sizeof(ocl_queue_ctx), &ocl_queue_ctx, nullptr)); ASSERT_EQ(ocl_dev, ocl_queue_dev); ASSERT_EQ(ocl_ctx, ocl_queue_ctx); MKLDNN_CHECK(mkldnn_stream_destroy(stream)); } TEST_F(ocl_stream_test_cpp, CreateCpp) { SKIP_IF(!find_ocl_device(CL_DEVICE_TYPE_GPU), "OpenCL GPU devices not found."); stream s(eng); cl_command_queue ocl_queue = s.get_ocl_command_queue(); cl_device_id ocl_queue_dev; cl_context ocl_queue_ctx; OCL_CHECK(clGetCommandQueueInfo(ocl_queue, CL_QUEUE_DEVICE, sizeof(ocl_queue_dev), &ocl_queue_dev, nullptr)); OCL_CHECK(clGetCommandQueueInfo(ocl_queue, CL_QUEUE_CONTEXT, sizeof(ocl_queue_ctx), &ocl_queue_ctx, nullptr)); ASSERT_EQ(ocl_dev, ocl_queue_dev); ASSERT_EQ(ocl_ctx, ocl_queue_ctx); } TEST_F(ocl_stream_test_c, BasicInteropC) { SKIP_IF(!find_ocl_device(CL_DEVICE_TYPE_GPU), "OpenCL GPU devices not found."); cl_int err; cl_command_queue interop_ocl_queue = clCreateCommandQueue(ocl_ctx, ocl_dev, 0, &err); OCL_CHECK(err); mkldnn_stream_t stream; MKLDNN_CHECK(mkldnn_stream_create_ocl(&stream, eng, interop_ocl_queue)); cl_command_queue ocl_queue; MKLDNN_CHECK(mkldnn_stream_get_ocl_command_queue(stream, &ocl_queue)); ASSERT_EQ(ocl_queue, interop_ocl_queue); cl_uint ref_count; OCL_CHECK(clGetCommandQueueInfo(interop_ocl_queue, CL_QUEUE_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, nullptr)); int i_ref_count = int(ref_count); ASSERT_EQ(i_ref_count, 2); MKLDNN_CHECK(mkldnn_stream_destroy(stream)); OCL_CHECK(clGetCommandQueueInfo(interop_ocl_queue, CL_QUEUE_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, nullptr)); i_ref_count = int(ref_count); ASSERT_EQ(i_ref_count, 1); OCL_CHECK(clReleaseCommandQueue(interop_ocl_queue)); } TEST_F(ocl_stream_test_cpp, BasicInteropC) { SKIP_IF(!find_ocl_device(CL_DEVICE_TYPE_GPU), "OpenCL GPU devices not found."); cl_int err; cl_command_queue interop_ocl_queue = clCreateCommandQueue(ocl_ctx, ocl_dev, 0, &err); OCL_CHECK(err); { stream s(eng, interop_ocl_queue); cl_uint ref_count; OCL_CHECK(clGetCommandQueueInfo(interop_ocl_queue, CL_QUEUE_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, nullptr)); int i_ref_count = int(ref_count); ASSERT_EQ(i_ref_count, 2); cl_command_queue ocl_queue = s.get_ocl_command_queue(); ASSERT_EQ(ocl_queue, interop_ocl_queue); } cl_uint ref_count; OCL_CHECK(clGetCommandQueueInfo(interop_ocl_queue, CL_QUEUE_REFERENCE_COUNT, sizeof(cl_uint), &ref_count, nullptr)); int i_ref_count = int(ref_count); ASSERT_EQ(i_ref_count, 1); OCL_CHECK(clReleaseCommandQueue(interop_ocl_queue)); } TEST_F(ocl_stream_test_c, InteropIncompatibleQueueC) { SKIP_IF(!find_ocl_device(CL_DEVICE_TYPE_GPU), "OpenCL GPU devices not found."); cl_device_id cpu_ocl_dev = find_ocl_device(CL_DEVICE_TYPE_CPU); SKIP_IF(!cpu_ocl_dev, "OpenCL CPU devices not found."); cl_int err; cl_context cpu_ocl_ctx = clCreateContext(nullptr, 1, &cpu_ocl_dev, nullptr, nullptr, &err); OCL_CHECK(err); cl_command_queue cpu_ocl_queue = clCreateCommandQueue(cpu_ocl_ctx, cpu_ocl_dev, 0, &err); OCL_CHECK(err); mkldnn_stream_t stream; mkldnn_status_t status = mkldnn_stream_create_ocl(&stream, eng, cpu_ocl_queue); ASSERT_EQ(status, mkldnn_invalid_arguments); OCL_CHECK(clReleaseCommandQueue(cpu_ocl_queue)); } TEST_F(ocl_stream_test_cpp, InteropIncompatibleQueueCpp) { SKIP_IF(!find_ocl_device(CL_DEVICE_TYPE_GPU), "OpenCL GPU devices not found."); cl_device_id cpu_ocl_dev = find_ocl_device(CL_DEVICE_TYPE_CPU); SKIP_IF(!cpu_ocl_dev, "OpenCL CPU devices not found."); cl_int err; cl_context cpu_ocl_ctx = clCreateContext(nullptr, 1, &cpu_ocl_dev, nullptr, nullptr, &err); OCL_CHECK(err); cl_command_queue cpu_ocl_queue = clCreateCommandQueue(cpu_ocl_ctx, cpu_ocl_dev, 0, &err); OCL_CHECK(err); catch_expected_failures([&] { stream s(eng, cpu_ocl_queue); }, true, mkldnn_invalid_arguments); OCL_CHECK(clReleaseCommandQueue(cpu_ocl_queue)); } } // namespace mkldnn <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/s8x8s32/jit_avx512_core_u8_copy_an_kern.cpp<|end_filename|> /******************************************************************************* * Copyright 2018-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common_u8.hpp" #include "jit_generator.hpp" namespace mkldnn { namespace impl { namespace cpu { jit_avx512_core_u8_copy_an_kern::jit_avx512_core_u8_copy_an_kern() : jit_generator(nullptr, U8_COPY_KERNEL_CODE_SIZE) { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rax #define B rdi #define I rax #define A1 rsi #define A2 r10 #define LDA3 r11 #define ARG_ALPHA 40+stacksize+rsp #define ARG_B 48+stacksize+rsp #endif inLocalLabel(); { Xbyak::Label l170; Xbyak::Label l1f0; Xbyak::Label l20; Xbyak::Label l224; Xbyak::Label l234; Xbyak::Label l240; Xbyak::Label l254; Xbyak::Label l32c; Xbyak::Label l34; Xbyak::Label l388; Xbyak::Label l3b0; Xbyak::Label l3c0; Xbyak::Label l3cc; Xbyak::Label l3dc; Xbyak::Label l454; Xbyak::Label l48c; Xbyak::Label l4a8; Xbyak::Label l4b8; Xbyak::Label l4c4; Xbyak::Label l4d8; Xbyak::Label l570; Xbyak::Label l5c4; Xbyak::Label l5f0; Xbyak::Label l60c; Xbyak::Label l61c; Xbyak::Label l628; Xbyak::Label l638; Xbyak::Label l6b0; Xbyak::Label l6f4; Xbyak::Label l720; Xbyak::Label l73c; Xbyak::Label l74c; Xbyak::Label l758; Xbyak::Label l76c; Xbyak::Label l804; Xbyak::Label l858; Xbyak::Label l88c; Xbyak::Label l8a4; Xbyak::Label l8b2; Xbyak::Label l8bc; Xbyak::Label l8cc; Xbyak::Label l944; Xbyak::Label l98c; Xbyak::Label l9b0; Xbyak::Label l9c8; Xbyak::Label l9d8; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); lea(LDA3, ptr[LDA+LDA*2]); sub(A, -128); sub(B, -128); cmp(N, 0x30); jl(l234, T_NEAR); align(4); L(l20); mov(A1, A); add(A, 0x30); mov(I, M); sar(I, 0x2); jle(l170, T_NEAR); align(4); L(l34); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1+LDA*1-0x80]); movdqu(xmm2, xword[A1+LDA*2-0x80]); movdqu(xmm3, xword[A1+LDA3*1-0x80]); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm4, xmm1); movdqa(xmm5, xmm2); punpcklbw(xmm2, xmm3); punpckhbw(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqa(xmm2, xmm4); punpcklwd(xmm4, xmm5); punpckhwd(xmm2, xmm5); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); movdqu(xword[B-0x60], xmm4); movdqu(xword[B-0x50], xmm2); movdqu(xmm0, xword[A1-0x70]); movdqu(xmm1, xword[A1+LDA*1-0x70]); movdqu(xmm2, xword[A1+LDA*2-0x70]); movdqu(xmm3, xword[A1+LDA3*1-0x70]); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm4, xmm1); movdqa(xmm5, xmm2); punpcklbw(xmm2, xmm3); punpckhbw(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqa(xmm2, xmm4); punpcklwd(xmm4, xmm5); punpckhwd(xmm2, xmm5); movdqu(xword[B-0x40], xmm0); movdqu(xword[B-0x30], xmm1); movdqu(xword[B-0x20], xmm4); movdqu(xword[B-0x10], xmm2); movdqu(xmm0, xword[A1-0x60]); movdqu(xmm1, xword[A1+LDA*1-0x60]); movdqu(xmm2, xword[A1+LDA*2-0x60]); movdqu(xmm3, xword[A1+LDA3*1-0x60]); lea(A1, ptr[A1+LDA*4]); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm4, xmm1); movdqa(xmm5, xmm2); punpcklbw(xmm2, xmm3); punpckhbw(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqa(xmm2, xmm4); punpcklwd(xmm4, xmm5); punpckhwd(xmm2, xmm5); movdqu(xword[B], xmm0); movdqu(xword[B+0x10], xmm1); movdqu(xword[B+0x20], xmm4); movdqu(xword[B+0x30], xmm2); sub(B, -192); dec(I); jg(l34, T_NEAR); align(4); L(l170); test(M, 0x2); jle(l1f0, T_NEAR); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1-0x70]); movdqu(xmm2, xword[A1-0x60]); add(A1, LDA); movdqu(xmm3, xword[A1-0x80]); movdqu(xmm4, xword[A1-0x70]); movdqu(xmm5, xword[A1-0x60]); add(A1, LDA); movdqa(xmm6, xmm0); punpcklbw(xmm0, xmm3); punpckhbw(xmm6, xmm3); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm6); movdqa(xmm6, xmm1); punpcklbw(xmm1, xmm4); punpckhbw(xmm6, xmm4); movdqu(xword[B-0x60], xmm1); movdqu(xword[B-0x50], xmm6); movdqa(xmm6, xmm2); punpcklbw(xmm2, xmm5); punpckhbw(xmm6, xmm5); movdqu(xword[B-0x40], xmm2); movdqu(xword[B-0x30], xmm6); sub(B, -96); align(4); L(l1f0); test(M, 0x1); jle(l224, T_NEAR); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1-0x70]); movdqu(xmm2, xword[A1-0x60]); add(A1, LDA); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); movdqu(xword[B-0x60], xmm2); sub(B, -48); align(4); L(l224); sub(N, 0x30); cmp(N, 0x30); jge(l20, T_NEAR); align(4); L(l234); cmp(N, 0x20); jl(l3c0, T_NEAR); align(4); L(l240); mov(A1, A); add(A, 0x20); mov(I, M); sar(I, 0x2); jle(l32c, T_NEAR); align(4); L(l254); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1+LDA*1-0x80]); movdqu(xmm2, xword[A1+LDA*2-0x80]); movdqu(xmm3, xword[A1+LDA3*1-0x80]); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm4, xmm1); movdqa(xmm5, xmm2); punpcklbw(xmm2, xmm3); punpckhbw(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqa(xmm2, xmm4); punpcklwd(xmm4, xmm5); punpckhwd(xmm2, xmm5); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); movdqu(xword[B-0x60], xmm4); movdqu(xword[B-0x50], xmm2); movdqu(xmm0, xword[A1-0x70]); movdqu(xmm1, xword[A1+LDA*1-0x70]); movdqu(xmm2, xword[A1+LDA*2-0x70]); movdqu(xmm3, xword[A1+LDA3*1-0x70]); lea(A1, ptr[A1+LDA*4]); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm4, xmm1); movdqa(xmm5, xmm2); punpcklbw(xmm2, xmm3); punpckhbw(xmm5, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqa(xmm2, xmm4); punpcklwd(xmm4, xmm5); punpckhwd(xmm2, xmm5); movdqu(xword[B-0x40], xmm0); movdqu(xword[B-0x30], xmm1); movdqu(xword[B-0x20], xmm4); movdqu(xword[B-0x10], xmm2); sub(B, -128); dec(I); jg(l254, T_NEAR); align(4); L(l32c); test(M, 0x2); jle(l388, T_NEAR); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1-0x70]); add(A1, LDA); movdqu(xmm2, xword[A1-0x80]); movdqu(xmm3, xword[A1-0x70]); add(A1, LDA); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm2); punpckhbw(xmm4, xmm2); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm4); movdqa(xmm4, xmm1); punpcklbw(xmm1, xmm3); punpckhbw(xmm4, xmm3); movdqu(xword[B-0x60], xmm1); movdqu(xword[B-0x50], xmm4); sub(B, -64); align(4); L(l388); test(M, 0x1); jle(l3b0, T_NEAR); movdqu(xmm0, xword[A1-0x80]); movdqu(xmm1, xword[A1-0x70]); add(A1, LDA); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); sub(B, -32); align(4); L(l3b0); sub(N, 0x20); cmp(N, 0x20); jge(l240, T_NEAR); align(4); L(l3c0); cmp(N, 0x10); jl(l4b8, T_NEAR); align(4); L(l3cc); mov(A1, A); add(A, 0x10); mov(I, M); sar(I, 0x2); jle(l454, T_NEAR); align(4); L(l3dc); movdqu(xmm0, xword[A1-0x80]); add(A1, LDA); movdqu(xmm1, xword[A1-0x80]); add(A1, LDA); movdqu(xmm2, xword[A1-0x80]); add(A1, LDA); movdqu(xmm3, xword[A1-0x80]); add(A1, LDA); movdqa(xmm4, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm4, xmm1); movdqa(xmm1, xmm2); punpcklbw(xmm2, xmm3); punpckhbw(xmm1, xmm3); movdqa(xmm3, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm3, xmm2); movdqa(xmm2, xmm4); punpcklwd(xmm4, xmm1); punpckhwd(xmm2, xmm1); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm3); movdqu(xword[B-0x60], xmm4); movdqu(xword[B-0x50], xmm2); sub(B, -64); dec(I); jg(l3dc, T_NEAR); align(4); L(l454); test(M, 0x2); jle(l48c, T_NEAR); movdqu(xmm0, xword[A1-0x80]); add(A1, LDA); movdqu(xmm1, xword[A1-0x80]); add(A1, LDA); movdqa(xmm2, xmm0); punpcklbw(xmm0, xmm1); punpckhbw(xmm2, xmm1); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm2); sub(B, -32); align(4); L(l48c); test(M, 0x1); jle(l4a8, T_NEAR); movdqu(xmm0, xword[A1-0x80]); add(A1, LDA); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l4a8); sub(N, 0x10); cmp(N, 0x10); jge(l3cc, T_NEAR); align(4); L(l4b8); cmp(N, 0x8); jl(l61c, T_NEAR); align(4); L(l4c4); mov(A1, A); add(A, 0x8); mov(I, M); sar(I, 0x3); jle(l570, T_NEAR); align(4); L(l4d8); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); movq(xmm2, qword[A1-0x80]); add(A1, LDA); movq(xmm3, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); movq(xmm2, qword[A1-0x80]); add(A1, LDA); movq(xmm3, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqu(xword[B-0x60], xmm0); movdqu(xword[B-0x50], xmm1); sub(B, -64); dec(I); jg(l4d8, T_NEAR); align(4); L(l570); test(M, 0x4); jle(l5c4, T_NEAR); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); movq(xmm2, qword[A1-0x80]); add(A1, LDA); movq(xmm3, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); movdqa(xmm1, xmm0); punpcklwd(xmm0, xmm2); punpckhwd(xmm1, xmm2); movdqu(xword[B-0x80], xmm0); movdqu(xword[B-0x70], xmm1); sub(B, -32); align(4); L(l5c4); test(M, 0x2); jle(l5f0, T_NEAR); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(xmm1, qword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l5f0); test(M, 0x1); jle(l60c, T_NEAR); movq(xmm0, qword[A1-0x80]); add(A1, LDA); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l60c); sub(N, 0x8); cmp(N, 0x8); jge(l4c4, T_NEAR); align(4); L(l61c); cmp(N, 0x4); jl(l74c, T_NEAR); align(4); L(l628); mov(A1, A); add(A, 0x4); mov(I, M); sar(I, 0x3); jle(l6b0, T_NEAR); align(4); L(l638); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); movd(xmm2, dword[A1-0x80]); add(A1, LDA); movd(xmm3, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); movdqu(xword[B-0x80], xmm0); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); movd(xmm2, dword[A1-0x80]); add(A1, LDA); movd(xmm3, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); movdqu(xword[B-0x70], xmm0); sub(B, -32); dec(I); jg(l638, T_NEAR); align(4); L(l6b0); test(M, 0x4); jle(l6f4, T_NEAR); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); movd(xmm2, dword[A1-0x80]); add(A1, LDA); movd(xmm3, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); movdqu(xword[B-0x80], xmm0); sub(B, -16); align(4); L(l6f4); test(M, 0x2); jle(l720, T_NEAR); movd(xmm0, dword[A1-0x80]); add(A1, LDA); movd(xmm1, dword[A1-0x80]); add(A1, LDA); punpcklbw(xmm0, xmm1); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l720); test(M, 0x1); jle(l73c, T_NEAR); movd(xmm0, dword[A1-0x80]); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l73c); sub(N, 0x4); cmp(N, 0x4); jge(l628, T_NEAR); align(4); L(l74c); cmp(N, 0x2); jl(l8b2, T_NEAR); align(4); L(l758); mov(A1, A); add(A, 0x2); mov(LDA3, M); sar(LDA3, 0x3); jle(l804, T_NEAR); align(4); L(l76c); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm2, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm3, eax, 0x0); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm2, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm3, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm4, eax, 0x0); punpcklbw(xmm1, xmm2); punpcklbw(xmm3, xmm4); punpcklwd(xmm1, xmm3); punpcklqdq(xmm0, xmm1); movdqu(xword[B-0x80], xmm0); sub(B, -16); dec(LDA3); jg(l76c, T_NEAR); align(4); L(l804); test(M, 0x4); jle(l858, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm2, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm3, eax, 0x0); punpcklbw(xmm0, xmm1); punpcklbw(xmm2, xmm3); punpcklwd(xmm0, xmm2); movq(qword[B-0x80], xmm0); sub(B, -8); align(4); L(l858); test(M, 0x2); jle(l88c, T_NEAR); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm0, eax, 0x0); mov(ax, word[A1-0x80]); add(A1, LDA); pinsrw(xmm1, eax, 0x0); punpcklbw(xmm0, xmm1); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l88c); test(M, 0x1); jle(l8a4, T_NEAR); mov(ax, word[A1-0x80]); mov(word[B-0x80], ax); sub(B, -2); align(4); L(l8a4); sub(N, 0x2); cmp(N, 0x2); jge(l758, T_NEAR); align(4); L(l8b2); cmp(N, 0x1); jl(l9d8, T_NEAR); align(4); L(l8bc); mov(A1, A); add(A, 0x1); mov(LDA3, M); sar(LDA3, 0x3); jle(l944, T_NEAR); align(4); L(l8cc); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x3); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x4); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x5); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x6); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x7); movq(qword[B-0x80], xmm0); sub(B, -8); dec(LDA3); jg(l8cc, T_NEAR); align(4); L(l944); test(M, 0x4); jle(l98c, T_NEAR); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x0); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x1); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x2); mov(al, byte[A1-0x80]); add(A1, LDA); pinsrb(xmm0, eax, 0x3); movd(dword[B-0x80], xmm0); sub(B, -4); align(4); L(l98c); test(M, 0x2); jle(l9b0, T_NEAR); mov(al, byte[A1-0x80]); add(A1, LDA); mov(byte[B-0x80], al); mov(al, byte[A1-0x80]); add(A1, LDA); mov(byte[B-0x7f], al); sub(B, -2); align(4); L(l9b0); test(M, 0x1); jle(l9c8, T_NEAR); mov(al, byte[A1-0x80]); mov(byte[B-0x80], al); sub(B, -1); align(4); L(l9c8); sub(N, 0x1); cmp(N, 0x1); jge(l8bc, T_NEAR); align(4); L(l9d8); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } } } <|start_filename|>Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/tests/benchdnn/concat/concat.cpp<|end_filename|> /******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include "mkldnn.h" #include "src/common/mkldnn_thread.hpp" #include "mkldnn_common.hpp" #include "mkldnn_memory.hpp" #include "concat/concat.hpp" namespace concat { static int init_pd(const prb_t *p, mkldnn_primitive_desc_t &cpd, res_t *r) { std::vector<mkldnn_memory_desc_t> src_d; src_d.resize(p->n_inputs()); mkldnn_memory_desc_t dst_d; const int ndims = (int)p->ddims.size(); for (int i_input = 0; i_input < p->n_inputs(); ++i_input) { const dims_t &i_sdims = p->sdims[i_input]; DNN_SAFE(mkldnn_memory_desc_init_by_tag(&src_d[i_input], ndims, i_sdims.data(), p->sdt, p->stag[i_input]), WARN); } if (p->dtag != mkldnn_format_tag_undef) { DNN_SAFE(mkldnn_memory_desc_init_by_tag( &dst_d, ndims, p->ddims.data(), p->ddt, p->dtag), WARN); } mkldnn_status_t init_status = mkldnn_concat_primitive_desc_create(&cpd, p->dtag != mkldnn_format_tag_undef ? &dst_d : NULL, p->n_inputs(), p->axis, src_d.data(), NULL, engine_tgt); if (init_status == mkldnn_unimplemented) return r->state = UNIMPLEMENTED, OK; else SAFE(init_status, WARN); const char *impl_str = query_impl_info(cpd); print(5, "mkldnn implementation: %s\n", impl_str); return OK; } static int compare(const prb_t *p, const mkldnn_data_type_t dst_data_type, const dnn_mem_t &fp_mem, const dnn_mem_t &dt_mem, res_t *r) { const auto nelems = dt_mem.nelems(); r->errors = 0; r->total = nelems; for (int64_t i = 0; i < nelems; i++) { const float dt = dt_mem.get_elem(i); const float fp0 = fp_mem.get_elem(i); const float fp = maybe_saturate(dst_data_type, fp0); const bool ok = dt == fp; // expect exact answer due to int values r->errors += !ok; const bool dump = false || (!ok && (r->errors < 10 || verbose >= 10)) || (verbose >= 50 && i < 30) || (verbose >= 99); if (dump) { std::stringstream ss; dims_t ddims_idx = off2dims_idx(p->ddims, i); ss << ddims_idx; std::string ind_str = ss.str(); print(0, "[%4ld][%s] fp0:%8g fp:%8g dt:%8g\n", (long)i, ind_str.c_str(), fp0, fp, dt); } } if (r->errors) r->state = FAILED; if (r->state == UNTESTED) r->state = PASSED; /* optimism */ return r->state == FAILED ? FAIL : OK; } int fill_src(const prb_t *p, int input_idx, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp) { auto get_range = [](const mkldnn_data_type_t dt) { if (dt == mkldnn_s8 || dt == mkldnn_u8) return 256; else if (dt == mkldnn_bf16 || dt == mkldnn_f16) return 128; return 1024; }; const auto nelems = mem_fp.nelems(); const int range = get_range(p->sdt); const int f_min = p->sdt == mkldnn_u8 ? 0 : -range / 2; mkldnn::impl::parallel_nd(nelems, [&](int64_t i) { const float gen = ((97 * i) - 17 * input_idx + 101) % range; const float value = f_min + gen; mem_fp.set_elem(i, maybe_saturate(p->sdt, value)); } ); SAFE(mem_dt.reorder(mem_fp), WARN); return OK; } int doit(const prb_t *p, res_t *r) { mkldnn_primitive_desc_t cpd; mkldnn_primitive_t c; SAFE(init_pd(p, cpd, r), WARN); if (r->state == SKIPPED || r->state == UNIMPLEMENTED) return OK; DNN_SAFE(mkldnn_primitive_create(&c, cpd), WARN); const auto q = [=](mkldnn_query_t query, int index = 0) { return *mkldnn_primitive_desc_query_md(cpd, query, index); }; const auto fp = mkldnn_f32; const auto tag = get_default_tag((int)p->sdims[0].size()); const auto dst_dt_d = q(mkldnn_query_dst_md); const auto dst_data_type = dst_dt_d.data_type; // needed for deduced dst dnn_mem_t dst_fp(dst_dt_d, fp, tag, engine_ref), dst_dt(dst_dt_d, engine_tgt); args_t args; args.set(MKLDNN_ARG_DST, dst_dt.m_); std::vector<dnn_mem_t> src_fp, src_dt; src_fp.reserve(p->n_inputs()); src_dt.reserve(p->n_inputs()); for (int i_input = 0; i_input < p->n_inputs(); ++i_input) { const auto src_dt_d = q(mkldnn_query_src_md, i_input); src_fp.emplace_back(src_dt_d, fp, tag, engine_ref); src_dt.emplace_back(src_dt_d, engine_tgt); SAFE(fill_src(p, i_input, src_dt[i_input], src_fp[i_input]), WARN); args.set(MKLDNN_ARG_MULTIPLE_SRC + i_input, src_dt[i_input].m_); } DNN_SAFE(execute_and_wait(c, stream_tgt, args.size(), args), WARN); if (bench_mode & CORR) { compute_ref(p, src_fp, dst_fp); dnn_mem_t dst(dst_dt, fp, tag, engine_ref); SAFE(compare(p, dst_data_type, dst_fp, dst, r), WARN); } measure_perf(r->timer, c, args); DNN_SAFE(mkldnn_primitive_desc_destroy(cpd), CRIT); DNN_SAFE(mkldnn_primitive_destroy(c), CRIT); return OK; } }
goswamig/training_results_v0.7
<|start_filename|>Makefile<|end_filename|> DESTDIR ?= /usr/local MANPAGE_DIR = doc/man # We are linking libraries written in C which may have suboptimal security # histories. Prefer dynamic linking so security updates need not require a # recompile. DYNAMIC ?= 1 ifeq ($(DYNAMIC),1) LIBGIT2_SYS_USE_PKG_CONFIG ?= 1 PKG_CONFIG_ALL_DYNAMIC ?= 1 export LIBGIT2_SYS_USE_PKG_CONFIG export PKG_CONFIG_ALL_DYNAMIC endif # Test configuration. GROUPS := stretch buster stable nightly CRATES := core bin lfs DOCKER_FILES := $(patsubst %,test/Dockerfile.%,$(GROUPS)) DOCKER_STAMPS := $(patsubst %,test/Dockerfile.%.stamp,$(GROUPS)) CI_TARGETS := $(patsubst %,ci-%,$(GROUPS)) PACKAGE_TARGETS := $(patsubst %,package-%,$(CRATES)) INCLUDES := $(wildcard test/include/*.erb) MANPAGES := $(patsubst %.adoc,%.1,$(wildcard doc/man/*.adoc)) SRC := $(shell find . -name '*.rs') Makefile Cargo.toml all: cargo build --release test: cargo test install: all for i in target/release/git-*; do \ [ -x "$$i" ] || continue; \ install -m 755 "$$i" "$(DESTDIR)/bin/$$(basename "$$i")"; \ done %.md: %.adoc asciidoctor -o $@+ -b docbook5 $^ pandoc -f docbook -t commonmark -o $@ $@+ $(RM) $@+ %.1: %.adoc asciidoctor -b manpage -a compat-mode -o $@ $^ doc: $(MANPAGES) clean: cargo clean rm -fr target tmp for i in "$(DOCKER_STAMPS)"; \ do \ [ ! -f "$$i" ] || docker image rm -f "$$i"; \ done rm -f $(DOCKER_FILES) $(DOCKER_STAMPS) rm -fr tmp rm -fr *.md *.md+ scutiger-*/*.md scutiger-*/*.md+ rm -fr doc/man/*.1 linkage: tmp set -e; \ for i in target/release/git-*; \ do \ echo $$i | grep -vF '.d' || continue; \ lfile=tmp/$$(basename $$i)-linkage; \ ldd $$i | tee $$lfile; \ echo Ensuring libssl is absent; \ grep -qsv libssl $$lfile; \ echo Looking for libgit2; \ grep -qs libgit2 $$lfile; \ echo Looking for libz; \ grep -qs libz $$lfile; \ echo Looking for libpcre2; \ grep -qs libpcre2 $$lfile; \ done tmp: [ -d tmp ] || mkdir tmp # We do not require both of these commands here since nightly Rust may be # missing one or more of these. When run under CI, they should be present for # stable Rust and catch any issues. # # Note if we're using rustup, cargo-clippy may exist in the PATH even if clippy # isn't installed, but it may be a wrapper that just fails when invoked. Check # that it can successfully print help output to check if we really have clippy. # The same goes for rustfmt. lint: if command -v cargo-clippy && cargo-clippy --help >/dev/null 2>&1; \ then \ $(MAKE) clippy; \ fi if command -v rustfmt && rustfmt --help >/dev/null 2>&1; \ then \ $(MAKE) fmt; \ fi package: $(PACKAGE_TARGETS) package-%: scutiger-% scutiger-%/README.md (cd "$<" && cargo package --allow-dirty) ci: $(CI_TARGETS) ci-%: test/Dockerfile.%.stamp docker run --rm \ -e CARGO_NET_GIT_FETCH_WITH_CLI=true \ $$(cat "$<") \ sh -c 'cd /usr/src/scutiger && make test-full' test-full: make all make doc make test make lint test/Dockerfile.%.stamp: test/Dockerfile.% $(SRC) docker build --iidfile="$@" -f "$<" . test/Dockerfile.%: test/Dockerfile.%.erb $(INCLUDES) test/template "$<" >"$@" clippy: rm -rf target @# We exclude these lints here instead of in the file because Rust 1.24 @# doesn't support excluding clippy warnings. Similarly, it doesn't support @# the syntax these lints suggest. cargo clippy -- \ -A clippy::range-plus-one \ -A clippy::needless-lifetimes \ -A clippy::unknown-clippy-lints \ -D warnings fmt: if rustfmt --help | grep -qse --check; \ then \ rustfmt --check $$(find . -name '*.rs' | grep -v '^./target'); \ else \ rustfmt --write-mode diff $$(find . -name '*.rs' | grep -v '^./target'); \ fi .PHONY: all lint ci clean doc clippy fmt linkage test
bk2204/scutiger
<|start_filename|>src/benchmark/SerializationBenchmarks/Program.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="Program.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Akka.Actor; using Akka.Configuration; using Akka.Serialization; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using Newtonsoft.Json; namespace SerializationBenchmarks { class Program { static void Main(string[] args) { BenchmarkRunner.Run<JsonSerializerTests>(); } } public class TestSer { public int Id { get; set; } public string someStr { get; set; } public string someStr2 { get; set; } public string someStr3 { get; set; } public Guid IDK { get; set; } } [MemoryDiagnoser] public class JsonSerializerTests { public JsonSerializerTests() { _sys_noPool = ActorSystem.Create("bench-serialization-json-nopool",ConfigurationFactory.ParseString(@" akka.actor {{ serialization-settings {{ json {{ use-pooled-string-builder = false }} }} }}")); _sys_pool = ActorSystem.Create("bench-serialization-json-pool"); _noPoolSer = _sys_noPool.Serialization.FindSerializerForType(typeof(object)); _poolSer = _sys_pool.Serialization.FindSerializerForType(typeof(object)); } private static TestSer testObj = new TestSer() { Id = 124, someStr = "412tgieoargj4a9349u2u-03jf3290rjf2390ja209fj1099u42n0f92qm93df3m-032jfq-102", someStr2 = "412tgieoargj4a9349u2u-03jf3290rjf2390ja209fj1099u42n0f92qm93df3m-032jfq-102", someStr3 = new string(Enumerable.Repeat('l',512).ToArray()), IDK = Guid.Empty }; private ActorSystem _sys_noPool; private ActorSystem _sys_pool; private Serializer _noPoolSer; private Serializer _poolSer; private const int _numIters = 10000; [Benchmark] public void Pooling() { for (int i = 0; i < _numIters; i++) { _poolSer.ToBinary(testObj); } } [Benchmark] public void NoPooling() { for (int i = 0; i < _numIters; i++) { _noPoolSer.ToBinary(testObj); } } [Benchmark] public void Pooling_MultiTasks() { Task.WaitAll(Enumerable.Repeat(0, 10) .Select((l) => Task.Run(Pooling)).ToArray()); } [Benchmark] public void NoPooling_MultiTasks() { Task.WaitAll(Enumerable.Repeat(0, 10) .Select((l) => Task.Run(NoPooling)).ToArray()); } } //[MemoryDiagnoser] public class SerializationTests { private ActorSystem _sys; private Serializer _ser; public SerializationTests() { _sys = ActorSystem.Create("bench-serialization",ConfigurationFactory.ParseString(@" akka.actor {{ serializers {{ hyperion = ""Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion"" }} serialization-bindings {{ ""System.Object"" = hyperion }} }}")); _ser = _sys.Serialization.FindSerializerForType(typeof(MyType)); } public static MyType payload => new MyType() { SomeInt = 1, SomeStr = "lol" }; [Benchmark] public void Serialization_WithTransport_NoState() { DoSer_NoState(payload); } //Noninlining here because we don't want //Jitter to inline and possibly remove the capture of 2 variables //we want to simulate in this benchmark [MethodImpl(MethodImplOptions.NoInlining)] private void DoSer_NoState(MyType thisPayload) { var res = Akka.Serialization.Serialization.WithTransport( _sys.Serialization.System, () => { return _ser.ToBinary(thisPayload); }); } //Noinlining here to be fair, since we are noinling on other. [MethodImpl(MethodImplOptions.NoInlining)] private void DoSer_State(MyType thisPayload) { var res = Akka.Serialization.Serialization.WithTransport( _sys.Serialization.System,(_ser,thisPayload), (inp) => { var (serializer, myType) = inp; return serializer.ToBinary(myType); }); } [Benchmark] public void Serialization_WithTransport_State() { DoSer_State(payload); } } public class MyType { public string SomeStr { get; set; } public int SomeInt { get; set; } } } <|start_filename|>src/core/Akka.Tests/IO/TestUtils.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="TestUtils.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System.Net; namespace Akka.Tests.IO { public static class TestUtils { public static bool Is(this EndPoint ep1, EndPoint ep2) { return ep1 is IPEndPoint ip1 && ep2 is IPEndPoint ip2 && ip1.Port == ip2.Port && ip1.Address.MapToIPv4().Equals(ip2.Address.MapToIPv4()); } } } <|start_filename|>src/core/Akka/IO/SocketEventArgsPool.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="SocketEventArgsPool.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Actor; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Runtime.CompilerServices; using Akka.Annotations; using Akka.IO.Buffers; using Akka.Util; namespace Akka.IO { public interface ISocketEventArgsPool { SocketAsyncEventArgs Acquire(IActorRef actor); void Release(SocketAsyncEventArgs e); BufferPoolInfo BufferPoolInfo { get; } } // This class __does not__ pool and reuse SocketAsyncEventArgs anymore. Reusing SocketAsyncEventArgs with // multiple Socket instances is dangerous because SocketAsyncEventArgs is not a simple struct or POCO, // it actually held internal states that can wreak havoc if being used in another socket instance. // It is impossible to clear a SocketAsyncEventArgs object and the hassle of trying to handle every single // edge case outweigh the speed and memory gain of pooling the instances. internal class PreallocatedSocketEventAgrsPool : ISocketEventArgsPool { // Byte buffer pool is moved here to reduce the chance that a memory segment got mis-managed // and not released properly. We only need to worry about acquiring and releasing SocketAsyncEventArgs // and not worry about having to check to see if we need to rent or release any buffer. // // There is no reason why users or developers would need to touch memory management code because it is // very specific for providing byte buffers for SocketAsyncEventArgs private readonly IBufferPool _bufferPool; private readonly EventHandler<SocketAsyncEventArgs> _onComplete; public PreallocatedSocketEventAgrsPool(int initSize, IBufferPool bufferPool, EventHandler<SocketAsyncEventArgs> onComplete) { _bufferPool = bufferPool; _onComplete = onComplete; } public SocketAsyncEventArgs Acquire(IActorRef actor) { var buffer = _bufferPool.Rent(); var e = new SocketAsyncEventArgs(); e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); e.UserToken = actor; e.Completed += _onComplete; return e; } public void Release(SocketAsyncEventArgs e) { if (e.Buffer != null) { _bufferPool.Release(new ArraySegment<byte>(e.Buffer, e.Offset, e.Count)); } if (e.BufferList != null) { foreach (var segment in e.BufferList) { _bufferPool.Release(segment); } } e.Dispose(); } public BufferPoolInfo BufferPoolInfo => _bufferPool.Diagnostics(); } internal static class SocketAsyncEventArgsExtensions { public static void SetBuffer(this SocketAsyncEventArgs args, ByteString data) { if (data.IsCompact) { var buffer = data.Buffers[0]; if (args.BufferList != null) { // BufferList property setter is not simple member association operation, // but the getter is. Therefore we first check if we need to clear buffer list // and only do so if necessary. args.BufferList = null; } args.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); } else { if (RuntimeDetector.IsMono) { // Mono doesn't support BufferList - falback to compacting ByteString var compacted = data.Compact(); var buffer = compacted.Buffers[0]; args.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); } else { args.SetBuffer(null, 0, 0); args.BufferList = data.Buffers; } } } public static void SetBuffer(this SocketAsyncEventArgs args, IEnumerable<ByteString> dataCollection) { if (RuntimeDetector.IsMono) { // Mono doesn't support BufferList - falback to compacting ByteString var dataList = dataCollection.ToList(); var totalSize = dataList.SelectMany(d => d.Buffers).Sum(d => d.Count); var bytes = new byte[totalSize]; var position = 0; foreach (var byteString in dataList) { var copied = byteString.CopyTo(bytes, position, byteString.Count); position += copied; } args.SetBuffer(bytes, 0, bytes.Length); } else { args.SetBuffer(null, 0, 0); args.BufferList = dataCollection.SelectMany(d => d.Buffers).ToList(); } } } } <|start_filename|>src/core/Akka/Serialization/NewtonSoftJsonSerializer.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="NewtonSoftJsonSerializer.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Akka.Actor; using Akka.Configuration; using Akka.Util; using Microsoft.Extensions.ObjectPool; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Akka.Serialization { /// <summary> /// A typed settings for a <see cref="NewtonSoftJsonSerializer"/> class. /// </summary> public sealed class NewtonSoftJsonSerializerSettings { /// <summary> /// A default instance of <see cref="NewtonSoftJsonSerializerSettings"/> used when no custom configuration has been provided. /// </summary> public static readonly NewtonSoftJsonSerializerSettings Default = new NewtonSoftJsonSerializerSettings( encodeTypeNames: true, preserveObjectReferences: true, converters: Enumerable.Empty<Type>(), usePooledStringBuilder:true, stringBuilderMinSize:2048, stringBuilderMaxSize:32768); /// <summary> /// Creates a new instance of the <see cref="NewtonSoftJsonSerializerSettings"/> based on a provided <paramref name="config"/>. /// Config may define several key-values: /// <ul> /// <li>`encode-type-names` (boolean) mapped to <see cref="EncodeTypeNames"/></li> /// <li>`preserve-object-references` (boolean) mapped to <see cref="PreserveObjectReferences"/></li> /// <li>`converters` (type list) mapped to <see cref="Converters"/>. They must implement <see cref="JsonConverter"/> and define either default constructor or constructor taking <see cref="ExtendedActorSystem"/> as its only parameter.</li> /// </ul> /// </summary> /// <exception cref="ArgumentNullException">Raised when no <paramref name="config"/> was provided.</exception> /// <exception cref="ArgumentException">Raised when types defined in `converters` list didn't inherit <see cref="JsonConverter"/>.</exception> public static NewtonSoftJsonSerializerSettings Create(Config config) { if (config.IsNullOrEmpty()) throw ConfigurationException.NullOrEmptyConfig<NewtonSoftJsonSerializerSettings>(); return new NewtonSoftJsonSerializerSettings( encodeTypeNames: config.GetBoolean("encode-type-names", true), preserveObjectReferences: config.GetBoolean( "preserve-object-references", true), converters: GetConverterTypes(config), usePooledStringBuilder: config.GetBoolean("use-pooled-string-builder", true), stringBuilderMinSize:config.GetInt("pooled-string-builder-minsize", 2048), stringBuilderMaxSize: config.GetInt("pooled-string-builder-maxsize", 32768) ); } private static IEnumerable<Type> GetConverterTypes(Config config) { var converterNames = config.GetStringList("converters", new string[] { }); if (converterNames != null) foreach (var converterName in converterNames) { var type = Type.GetType(converterName, true); if (!typeof(JsonConverter).IsAssignableFrom(type)) throw new ArgumentException($"Type {type} doesn't inherit from a {typeof(JsonConverter)}."); yield return type; } } /// <summary> /// When true, serializer will encode a type names into serialized json $type field. This must be true /// if <see cref="NewtonSoftJsonSerializer"/> is a default serializer in order to support polymorphic /// deserialization. /// </summary> public bool EncodeTypeNames { get; } /// <summary> /// When true, serializer will track a reference dependencies in serialized object graph. This must be /// true if <see cref="NewtonSoftJsonSerializer"/>. /// </summary> public bool PreserveObjectReferences { get; } /// <summary> /// A collection of an additional converter types to be applied to a <see cref="NewtonSoftJsonSerializer"/>. /// Converters must inherit from <see cref="JsonConverter"/> class and implement a default constructor. /// </summary> public IEnumerable<Type> Converters { get; } /// <summary> /// The Starting size used for Pooled StringBuilders, if <see cref="UsePooledStringBuilder"/> is -true- /// </summary> public int StringBuilderMinSize { get; } /// <summary> /// The Max Retained size for Pooled StringBuilders, if <see cref="UsePooledStringBuilder"/> is -true- /// </summary> public int StringBuilderMaxSize { get; } /// <summary> /// If -true-, Stringbuilders are pooled and reused for serialization to lower memory pressure. /// </summary> public bool UsePooledStringBuilder { get; } /// <summary> /// Creates a new instance of the <see cref="NewtonSoftJsonSerializerSettings"/>. /// </summary> /// <param name="encodeTypeNames">Determines if a special `$type` field should be emitted into serialized JSON. Must be true if corresponding serializer is used as default.</param> /// <param name="preserveObjectReferences">Determines if object references should be tracked within serialized object graph. Must be true if corresponding serialize is used as default.</param> /// <param name="converters">A list of types implementing a <see cref="JsonConverter"/> to support custom types serialization.</param> /// <param name="usePooledStringBuilder">Determines if string builders will be used from a pool to lower memory usage</param> /// <param name="stringBuilderMinSize">Starting size used for pooled string builders if enabled</param> /// <param name="stringBuilderMaxSize">Max retained size used for pooled string builders if enabled</param> public NewtonSoftJsonSerializerSettings(bool encodeTypeNames, bool preserveObjectReferences, IEnumerable<Type> converters, bool usePooledStringBuilder, int stringBuilderMinSize, int stringBuilderMaxSize) { if (converters == null) throw new ArgumentNullException(nameof(converters), $"{nameof(NewtonSoftJsonSerializerSettings)} requires a sequence of converters."); EncodeTypeNames = encodeTypeNames; PreserveObjectReferences = preserveObjectReferences; Converters = converters; UsePooledStringBuilder = usePooledStringBuilder; StringBuilderMinSize = stringBuilderMinSize; StringBuilderMaxSize = stringBuilderMaxSize; } } /// <summary> /// This is a special <see cref="Serializer"/> that serializes and deserializes javascript objects only. /// These objects need to be in the JavaScript Object Notation (JSON) format. /// </summary> public class NewtonSoftJsonSerializer : Serializer { private readonly JsonSerializer _serializer; private readonly ObjectPool<StringBuilder> _sbPool; /// <summary> /// TBD /// </summary> public JsonSerializerSettings Settings { get; } /// <summary> /// TBD /// </summary> public object Serializer { get { return _serializer; } } /// <summary> /// Initializes a new instance of the <see cref="NewtonSoftJsonSerializer" /> class. /// </summary> /// <param name="system">The actor system to associate with this serializer. </param> public NewtonSoftJsonSerializer(ExtendedActorSystem system) : this(system, NewtonSoftJsonSerializerSettings.Default) { } public NewtonSoftJsonSerializer(ExtendedActorSystem system, Config config) : this(system, NewtonSoftJsonSerializerSettings.Create(config)) { } public NewtonSoftJsonSerializer(ExtendedActorSystem system, NewtonSoftJsonSerializerSettings settings) : base(system) { if (settings.UsePooledStringBuilder) { _sbPool = new DefaultObjectPoolProvider() .CreateStringBuilderPool(settings.StringBuilderMinSize,settings.StringBuilderMaxSize); } Settings = new JsonSerializerSettings { PreserveReferencesHandling = settings.PreserveObjectReferences ? PreserveReferencesHandling.Objects : PreserveReferencesHandling.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, TypeNameHandling = settings.EncodeTypeNames ? TypeNameHandling.All : TypeNameHandling.None, }; if (system != null) { var settingsSetup = system.Settings.Setup.Get<NewtonSoftJsonSerializerSetup>() .GetOrElse(NewtonSoftJsonSerializerSetup.Create(s => {})); settingsSetup.ApplySettings(Settings); } var converters = settings.Converters .Select(type => CreateConverter(type, system)) .ToList(); converters.Add(new SurrogateConverter(this)); converters.Add(new DiscriminatedUnionConverter()); foreach (var converter in converters) { Settings.Converters.Add(converter); } Settings.ObjectCreationHandling = ObjectCreationHandling.Replace; //important: if reuse, the serializer will overwrite properties in default references, e.g. Props.DefaultDeploy or Props.noArgs Settings.ContractResolver = new AkkaContractResolver(); _serializer = JsonSerializer.Create(Settings); } private static JsonConverter CreateConverter(Type converterType, ExtendedActorSystem actorSystem) { var ctor = converterType.GetConstructors() .FirstOrDefault(c => { var parameters = c.GetParameters(); return parameters.Length == 1 && parameters[0].ParameterType == typeof(ExtendedActorSystem); }); return ctor == null ? (JsonConverter)Activator.CreateInstance(converterType) : (JsonConverter)Activator.CreateInstance(converterType, actorSystem); } internal class AkkaContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var prop = base.CreateProperty(member, memberSerialization); if (!prop.Writable) { var property = member as PropertyInfo; if (property != null) { var hasPrivateSetter = property.GetSetMethod(true) != null; prop.Writable = hasPrivateSetter; } } return prop; } } /// <summary> /// Returns whether this serializer needs a manifest in the fromBinary method /// </summary> public override bool IncludeManifest => false; /// <summary> /// Serializes the given object into a byte array /// </summary> /// <param name="obj">The object to serialize </param> /// <returns>A byte array containing the serialized object</returns> public override byte[] ToBinary(object obj) { if (_sbPool != null) { return toBinary_PooledBuilder(obj); } else { return toBinary_NewBuilder(obj); } } private byte[] toBinary_NewBuilder(object obj) { string data = JsonConvert.SerializeObject(obj, Formatting.None, Settings); byte[] bytes = Encoding.UTF8.GetBytes(data); return bytes; } private byte[] toBinary_PooledBuilder(object obj) { //Don't try to opt with //StringBuilder sb = _sbPool.Get() //Or removing null check //Both are necessary to avoid leaking on thread aborts etc StringBuilder sb = null; try { sb = _sbPool.Get(); using (var tw = new StringWriter(sb, CultureInfo.InvariantCulture)) { var ser = JsonSerializer.CreateDefault(Settings); ser.Formatting = Formatting.None; using (var jw = new JsonTextWriter(tw)) { ser.Serialize(jw, obj); } return Encoding.UTF8.GetBytes(tw.ToString()); } } finally { if (sb != null) { _sbPool.Return(sb); } } } /// <summary> /// Deserializes a byte array into an object of type <paramref name="type"/>. /// </summary> /// <param name="bytes">The array containing the serialized object</param> /// <param name="type">The type of object contained in the array</param> /// <returns>The object contained in the array</returns> public override object FromBinary(byte[] bytes, Type type) { string data = Encoding.UTF8.GetString(bytes); object res = JsonConvert.DeserializeObject(data, Settings); return TranslateSurrogate(res, this, type); } private static object TranslateSurrogate(object deserializedValue, NewtonSoftJsonSerializer parent, Type type) { var j = deserializedValue as JObject; if (j != null) { //The JObject represents a special akka.net wrapper for primitives (int,float,decimal) to preserve correct type when deserializing if (j["$"] != null) { var value = j["$"].Value<string>(); return GetValue(value); } //The JObject is not of our concern, let Json.NET deserialize it. return j.ToObject(type, parent._serializer); } var surrogate = deserializedValue as ISurrogate; //The deserialized object is a surrogate, unwrap it if (surrogate != null) { return surrogate.FromSurrogate(parent.system); } return deserializedValue; } private static object GetValue(string V) { var t = V.Substring(0, 1); var v = V.Substring(1); if (t == "I") return int.Parse(v, NumberFormatInfo.InvariantInfo); if (t == "F") return float.Parse(v, NumberFormatInfo.InvariantInfo); if (t == "M") return decimal.Parse(v, NumberFormatInfo.InvariantInfo); throw new NotSupportedException(); } /// <summary> /// TBD /// </summary> internal class SurrogateConverter : JsonConverter { private readonly NewtonSoftJsonSerializer _parent; /// <summary> /// TBD /// </summary> /// <param name="parent">TBD</param> public SurrogateConverter(NewtonSoftJsonSerializer parent) { _parent = parent; } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns><c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.</returns> public override bool CanConvert(Type objectType) { if (objectType == typeof(int) || objectType == typeof(float) || objectType == typeof(decimal)) return true; if (typeof(ISurrogated).IsAssignableFrom(objectType)) return true; if (objectType == typeof(object)) return true; return false; } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return DeserializeFromReader(reader, serializer, objectType); } private object DeserializeFromReader(JsonReader reader, JsonSerializer serializer, Type objectType) { var surrogate = serializer.Deserialize(reader); return TranslateSurrogate(surrogate, _parent, objectType); } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is int || value is decimal || value is float) { writer.WriteStartObject(); writer.WritePropertyName("$"); writer.WriteValue(GetString(value)); writer.WriteEndObject(); } else { var value1 = value as ISurrogated; if (value1 != null) { var surrogated = value1; var surrogate = surrogated.ToSurrogate(_parent.system); serializer.Serialize(writer, surrogate); } else { serializer.Serialize(writer, value); } } } private object GetString(object value) { if (value is int) return "I" + ((int)value).ToString(NumberFormatInfo.InvariantInfo); if (value is float) return "F" + ((float)value).ToString(NumberFormatInfo.InvariantInfo); if (value is decimal) return "M" + ((decimal)value).ToString(NumberFormatInfo.InvariantInfo); throw new NotSupportedException(); } } } } <|start_filename|>src/examples/Cluster/ClusterSharding/ShoppingCart/Customers.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="Customers.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using Akka.Actor; using Akka.Cluster.Sharding; using Akka.Persistence; namespace ShoppingCart { #region ActorClass public class Customer : ReceiveActor { public sealed class PurchaseItem { public readonly string ItemName; public PurchaseItem(string itemName) { ItemName = itemName; } } private readonly List<string> _purchasedItems = new List<string>(); public Customer(string persistenceId) { Receive<PurchaseItem>(purchase => { _purchasedItems.Add(purchase.ItemName); var name = Uri.UnescapeDataString(Self.Path.Name); Console.WriteLine( @$"'{name}' purchased '{purchase.ItemName}'. All items: [{string.Join(", ", _purchasedItems)}] --------------------------"); }); } } #endregion } <|start_filename|>src/core/Akka.Streams/Implementation/AsyncEnumerable.cs<|end_filename|> // //----------------------------------------------------------------------- // // <copyright file="AsyncEnumerable.cs" company="Akka.NET Project"> // // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // // </copyright> // //----------------------------------------------------------------------- using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Akka.Configuration.Hocon; namespace Akka.Streams.Dsl { /// <summary> /// Used to treat an <see cref="IRunnableGraph{TMat}"/> of <see cref="ISinkQueue{T}"/> /// as an <see cref="IAsyncEnumerable{T}"/> /// </summary> /// <typeparam name="T"></typeparam> public sealed class StreamsAsyncEnumerableRerunnable<T,TMat> : IAsyncEnumerable<T> { private static readonly Sink<T, ISinkQueue<T>> defaultSinkqueue = Sink.Queue<T>(); private readonly Source<T, TMat> _source; private readonly IMaterializer _materializer; private readonly Sink<T, ISinkQueue<T>> thisSinkQueue; //private readonly IRunnableGraph<(UniqueKillSwitch, ISinkQueue<T>)> _graph; public StreamsAsyncEnumerableRerunnable(Source<T,TMat> source, IMaterializer materializer) { _source = source; _materializer = materializer; thisSinkQueue = defaultSinkqueue; } public StreamsAsyncEnumerableRerunnable(Source<T, TMat> source, IMaterializer materializer, int minBuf, int maxBuf):this(source, materializer) { thisSinkQueue = defaultSinkqueue.WithAttributes( Attributes.CreateInputBuffer(minBuf, maxBuf)); } public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return new SinkQueueAsyncEnumerator<T>(_source .Via(cancellationToken.AsFlow<T>(cancelGracefully: true)) .ViaMaterialized(KillSwitches.Single<T>(), Keep.Right) .ToMaterialized(thisSinkQueue, Keep.Both) .Run(_materializer), cancellationToken); } } /// <summary> /// Wraps a Sink Queue and Killswitch around <see cref="IAsyncEnumerator{T}"/> /// </summary> /// <typeparam name="T"></typeparam> public sealed class SinkQueueAsyncEnumerator<T> : IAsyncEnumerator<T> { private ISinkQueue<T> _sinkQueue; private IKillSwitch _killSwitch; private CancellationToken _token; public SinkQueueAsyncEnumerator((UniqueKillSwitch killSwitch,ISinkQueue<T> sinkQueue) queueAndSwitch, CancellationToken token) { _sinkQueue = queueAndSwitch.sinkQueue; _killSwitch = queueAndSwitch.killSwitch; _token = token; } public async ValueTask DisposeAsync() { //If we are disposing, let's shut down the stream //so that we don't have data hanging around. _killSwitch.Shutdown(); _killSwitch = null; _sinkQueue = null; } public async ValueTask<bool> MoveNextAsync() { _token.ThrowIfCancellationRequested(); var opt = await _sinkQueue.PullAsync(); if (opt.HasValue) { Current = opt.Value; return true; } else { return false; } } public T Current { get; private set; } } } <|start_filename|>src/contrib/cluster/Akka.DistributedData.Tests/LightningDb/LmdbDurableStoreSpec.cs<|end_filename|> // //----------------------------------------------------------------------- // // <copyright file="LmdbSpec.cs" company="Akka.NET Project"> // // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // // </copyright> // //----------------------------------------------------------------------- using System.IO; using Akka.Actor; using Akka.Configuration; using Akka.DistributedData.Durable; using Akka.DistributedData.LightningDB; using Xunit; using Xunit.Abstractions; namespace Akka.DistributedData.Tests.LightningDb { public class LmdbDurableStoreSpec { private const string DDataDir = "thisdir"; private readonly ITestOutputHelper _output; private static readonly Config BaseConfig = ConfigurationFactory.ParseString($@" akka.actor {{ provider=""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" }} akka.remote.dot-netty.tcp.port = 0 akka.cluster.distributed-data.durable.lmdb {{ dir = {DDataDir} map-size = 100 MiB write-behind-interval = off }}").WithFallback(DistributedData.DefaultConfig()) .WithFallback(TestKit.Xunit2.TestKit.DefaultConfig); public LmdbDurableStoreSpec(ITestOutputHelper output) { _output = output; } [Fact] public void Lmdb_should_not_throw_when_opening_existing_directory() { if(Directory.Exists(DDataDir)) { var di = new DirectoryInfo(DDataDir); di.Delete(true); } Directory.CreateDirectory(DDataDir); var testKit = new TestKit.Xunit2.TestKit(BaseConfig, nameof(LmdbDurableStoreSpec), _output); var probe = testKit.CreateTestProbe(); var config = testKit.Sys.Settings.Config.GetConfig("akka.cluster.distributed-data.durable"); var lmdb = testKit.Sys.ActorOf(LmdbDurableStore.Props(config)); lmdb.Tell(LoadAll.Instance, probe.Ref); probe.ExpectMsg<LoadAllCompleted>(); } } } <|start_filename|>src/examples/Cluster/ClusterSharding/ShoppingCart/start.cmd<|end_filename|> dotnet publish -c Release docker build -t shopping-cart:latest . docker-compose up <|start_filename|>src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Program.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="Program.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.Bootstrap.Docker; using Akka.Cluster; using Akka.Cluster.Sharding; using Akka.Cluster.Tools.Singleton; using Akka.Configuration; using Akka.Persistence.Sqlite; using Akka.Util; namespace ClusterSharding.Node { using ClusterSharding = Akka.Cluster.Sharding.ClusterSharding; public static class Program { public static async Task Main(string[] args) { #region Console shutdown setup var exitEvent = new ManualResetEvent(false); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitEvent.Set(); }; AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { exitEvent.Set(); }; #endregion var config = ConfigurationFactory.ParseString(await File.ReadAllTextAsync("app.conf")) .BootstrapFromDocker() .WithFallback(ClusterSingletonManager.DefaultConfig()) .WithFallback(SqlitePersistence.DefaultConfiguration()); var system = ActorSystem.Create("sharded-cluster-system", config); var sharding = ClusterSharding.Get(system); var shardRegion = await sharding.StartAsync( typeName: "customer", entityPropsFactory: e => Props.Create(() => new Customer(e)), settings: ClusterShardingSettings.Create(system), messageExtractor: new MessageExtractor(10)); var cluster = Cluster.Get(system); cluster.RegisterOnMemberUp(() => { ProduceMessages(system, shardRegion); }); exitEvent.WaitOne(); await system.Terminate(); } private static void ProduceMessages(ActorSystem system, IActorRef shardRegion) { var customers = new[] { "Yoda", "Obi-Wan", "<NAME>", "<NAME>", "<NAME>", "R2D2", "<NAME>", "Chewbacca", "Jabba" }; var items = new[] { "Yoghurt", "Fruits", "Lightsaber", "Fluffy toy", "Dreamcatcher", "Candies", "Cigars", "Chicken nuggets", "French fries" }; system.Scheduler.Advanced.ScheduleRepeatedly(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(3), () => { var customer = PickRandom(customers); var item = PickRandom(items); var message = new ShardEnvelope(customer, new Customer.PurchaseItem(item)); shardRegion.Tell(message); }); } private static T PickRandom<T>(T[] items) => items[ThreadLocalRandom.Current.Next(items.Length)]; } } <|start_filename|>src/core/Akka/IO/UdpListener.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="UdpListener.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Net.Sockets; using Akka.Actor; using Akka.Annotations; using Akka.Dispatch; using Akka.Event; using Akka.Util.Internal; namespace Akka.IO { using static Udp; using ByteBuffer = ArraySegment<byte>; /// <summary> /// INTERNAL API /// </summary> [InternalApi] internal class UdpListener : WithUdpSend, IRequiresMessageQueue<IUnboundedMessageQueueSemantics> { private readonly IActorRef _bindCommander; private readonly Bind _bind; protected readonly ILoggingAdapter Log = Context.GetLogger(); public UdpListener(UdpExt udp, IActorRef bindCommander, Bind bind) { Udp = udp; _bindCommander = bindCommander; _bind = bind; Context.Watch(bind.Handler); // sign death pact Socket = (bind.Options.OfType<Inet.DatagramChannelCreator>().FirstOrDefault() ?? new Inet.DatagramChannelCreator()).Create(bind.LocalAddress.AddressFamily); Socket.Blocking = false; try { foreach (var option in bind.Options) { option.BeforeDatagramBind(Socket); } Socket.Bind(bind.LocalAddress); var ret = Socket.LocalEndPoint; if (ret == null) throw new ArgumentException($"bound to unknown SocketAddress [{Socket.LocalEndPoint}]"); Log.Debug("Successfully bound to [{0}]", ret); bind.Options.OfType<Inet.SocketOptionV2>().ForEach(x => x.AfterBind(Socket)); ReceiveAsync(); } catch (Exception e) { bindCommander.Tell(new CommandFailed(bind)); Log.Error(e, "Failed to bind UDP channel to endpoint [{0}]", bind.LocalAddress); Context.Stop(Self); } } protected sealed override Socket Socket { get; } /// <summary> /// TBD /// </summary> protected sealed override UdpExt Udp { get; } protected override void PreStart() { _bindCommander.Tell(new Bound(Socket.LocalEndPoint)); Context.Become(m => ReadHandlers(m) || SendHandlers(m)); } protected override bool Receive(object message) { throw new NotSupportedException(); } private bool ReadHandlers(object message) { switch (message) { case SuspendReading _: // TODO: What should we do here - we cant cancel a pending ReceiveAsync return true; case ResumeReading _: ReceiveAsync(); return true; case SocketReceived received: DoReceive(received, _bind.Handler); return true; case Unbind _: Log.Debug("Unbinding endpoint [{0}]", _bind.LocalAddress); try { Socket.Dispose(); Sender.Tell(Unbound.Instance); Log.Debug("Unbound endpoint [{0}], stopping listener", _bind.LocalAddress); } finally { Context.Stop(Self); } return true; } return false; } private void DoReceive(SocketReceived e, IActorRef handler) { if(e.IsIcmpError) { Log.Debug("Ignoring client connection reset."); ReceiveAsync(); return; } if (e.SocketError != SocketError.Success) throw new SocketException((int)e.SocketError); handler.Tell(new Received(e.Data, e.RemoteEndPoint)); ReceiveAsync(); } /// <summary> /// TBD /// </summary> protected override void PostStop() { if (Socket.Connected) { Log.Debug("Closing DatagramChannel after being stopped"); try { Socket.Dispose(); } catch (Exception e) { Log.Debug("Error closing DatagramChannel: {0}", e); } } } private void ReceiveAsync() { var e = Udp.SocketEventArgsPool.Acquire(Self); e.RemoteEndPoint = Socket.LocalEndPoint; if (!Socket.ReceiveFromAsync(e)) { Self.Tell(new SocketReceived(e)); Udp.SocketEventArgsPool.Release(e); } } } } <|start_filename|>src/examples/Cluster/ClusterSharding/ShoppingCart/Program.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="Program.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.Bootstrap.Docker; using Akka.Cluster; using Akka.Cluster.Sharding; using Akka.Configuration; using Akka.Util; namespace ShoppingCart { public static class Program { private const string FrontEndRole = "frontend"; private const string BackEndRole = "backend"; public static async Task<int> Main(string[] args) { #region Console shutdown setup var exitEvent = new ManualResetEvent(false); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitEvent.Set(); }; AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { exitEvent.Set(); }; #endregion // We will create a single node with the role "frontend" and three nodes with the role "backend" // using docker containers and docker-compose // Frontend will periodically send a purchase order to the backend nodes #region RoleSetup var role = Environment.GetEnvironmentVariable("IS_FRONTEND") == "true" ? FrontEndRole : BackEndRole; var config = ConfigurationFactory.ParseString(@$" # We need to tell Akka to provide us cluster enabled actors akka.actor.provider = cluster # This tells Akka which role this node belongs to akka.cluster.roles=[{role}] # This tells Akka to wait for at least 4 nodes joining the cluster # before signaling that it is up and ready akka.cluster.min-nr-of-members = 4") .BootstrapFromDocker(); var system = ActorSystem.Create("shopping-cart", config); #endregion #region StartSharding // Starts and initialize cluster sharding var sharding = ClusterSharding.Get(system); #endregion #region StartShardRegion switch (role) { case FrontEndRole: // Depending on the role, we will start a shard or a shard proxy var shardRegionProxy = await sharding.StartProxyAsync( typeName: "customer", role: BackEndRole, messageExtractor: new MessageExtractor(10)); // Register a callback for the "cluster is up" event var cluster = Cluster.Get(system); cluster.RegisterOnMemberUp(() => { ProduceMessages(system, shardRegionProxy); }); break; case BackEndRole: // Depending on the role, we will start a shard or a shard proxy await sharding.StartAsync( typeName: "customer", entityPropsFactory: e => Props.Create(() => new Customer(e)), // .WithRole is important because we're dedicating a specific node role for // the actors to be instantiated in; in this case, we're instantiating only // in the "backend" roled nodes. settings: ClusterShardingSettings.Create(system).WithRole(BackEndRole), messageExtractor: new MessageExtractor(10)); break; } #endregion exitEvent.WaitOne(); await system.Terminate(); return 0; } #region StartSendingMessage private static void ProduceMessages(ActorSystem system, IActorRef shardRegionProxy) { var customers = new[] { "Yoda", "Obi-Wan", "<NAME>", "<NAME>", "<NAME>", "R2D2", "<NAME>", "Chewbacca", "Jabba" }; var items = new[] { "Yoghurt", "Fruits", "Lightsaber", "Fluffy toy", "Dreamcatcher", "Candies", "Cigars", "Chicken nuggets", "French fries" }; // Start a timer that periodically sends messages to the shard system.Scheduler.Advanced .ScheduleRepeatedly(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(3), () => { var customer = PickRandom(customers); var item = PickRandom(items); // A shard message needs to be wrapped inside an envelope so the system knows which // shard and actor it should route the message to. var message = new ShardEnvelope(customer, new Customer.PurchaseItem(item)); shardRegionProxy.Tell(message); }); } #endregion private static T PickRandom<T>(T[] items) => items[ThreadLocalRandom.Current.Next(items.Length)]; } } <|start_filename|>src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Dockerfile<|end_filename|> FROM mcr.microsoft.com/dotnet/core/runtime:3.1 COPY ["./bin/Release/netcoreapp3.1/publish", "."] ENTRYPOINT ["dotnet", "ClusterSharding.Node.dll"] <|start_filename|>src/core/Akka.Tests/IO/UdpIntegrationSpec.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="UdpIntegrationSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using Akka.Actor; using Akka.IO; using Akka.IO.Buffers; using Akka.TestKit; using Xunit; using Xunit.Abstractions; using FluentAssertions; using FluentAssertions.Extensions; namespace Akka.Tests.IO { public class UdpIntegrationSpec : AkkaSpec { public UdpIntegrationSpec(ITestOutputHelper output) : base(@" akka.actor.serialize-creators = on akka.actor.serialize-messages = on akka.io.udp.max-channels = unlimited akka.io.udp.nr-of-selectors = 1 akka.io.udp.buffer-pool = ""akka.io.udp.direct-buffer-pool"" akka.io.udp.nr-of-selectors = 1 # This comes out to be about 1.6 Mib maximum total buffer size akka.io.udp.direct-buffer-pool.buffer-size = 512 akka.io.udp.direct-buffer-pool.buffers-per-segment = 32 akka.io.udp.direct-buffer-pool.buffer-pool-limit = 100 # akka.io.udp.trace-logging = true akka.loglevel = DEBUG", output) { } private (IActorRef, IPEndPoint) BindUdp(IActorRef handler) { var commander = CreateTestProbe(); commander.Send(Sys.Udp(), new Udp.Bind(handler, new IPEndPoint(IPAddress.Loopback, 0))); IPEndPoint localEndpoint = null; commander.ExpectMsg<Udp.Bound>(x => localEndpoint = (IPEndPoint)x.LocalAddress); return (commander.Sender, localEndpoint); } private IActorRef SimpleSender() { var commander = CreateTestProbe(); commander.Send(Udp.Instance.Apply(Sys).Manager, Udp.SimpleSender.Instance); commander.ExpectMsg<Udp.SimpleSenderReady>(TimeSpan.FromSeconds(10)); return commander.Sender; } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_be_able_to_send_without_binding() { var (_, localEndpoint) = BindUdp(TestActor); var data = ByteString.FromString("To infinity and beyond!"); SimpleSender().Tell(Udp.Send.Create(data, localEndpoint)); ExpectMsg<Udp.Received>(x => x.Data.ShouldBe(data)); } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_be_able_to_send_multipart_ByteString_without_binding() { var (_, localEndpoint) = BindUdp(TestActor); var data = ByteString.FromString("This ") + ByteString.FromString("is ") + ByteString.FromString("multiline ") + ByteString.FromString(" string!"); SimpleSender().Tell(Udp.Send.Create(data, localEndpoint)); ExpectMsg<Udp.Received>(x => x.Data.ShouldBe(data)); } [Fact] public void BugFix_UDP_fire_and_forget_must_handle_batch_writes_when_bound() { var (server, serverLocalEndpoint) = BindUdp(TestActor); var (client, clientLocalEndpoint) = BindUdp(TestActor); var data = ByteString.FromString("Fly little packet!"); // queue 3 writes client.Tell(Udp.Send.Create(data, serverLocalEndpoint)); client.Tell(Udp.Send.Create(data, serverLocalEndpoint)); client.Tell(Udp.Send.Create(data, serverLocalEndpoint)); var raw = ReceiveN(3); var msgs = raw.Cast<Udp.Received>(); msgs.Sum(x => x.Data.Count).Should().Be(data.Count*3); ExpectNoMsg(100.Milliseconds()); // repeat in the other direction server.Tell(Udp.Send.Create(data, clientLocalEndpoint)); server.Tell(Udp.Send.Create(data, clientLocalEndpoint)); server.Tell(Udp.Send.Create(data, clientLocalEndpoint)); raw = ReceiveN(3); msgs = raw.Cast<Udp.Received>(); msgs.Sum(x => x.Data.Count).Should().Be(data.Count * 3); } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_be_able_to_send_several_packet_back_and_forth_with_binding() { var serverProbe = CreateTestProbe(); var clientProbe = CreateTestProbe(); var (server, serverLocalEndpoint) = BindUdp(serverProbe); var (client, clientLocalEndpoint) = BindUdp(clientProbe); void CheckSendingToClient(int iteration) { server.Tell(Udp.Send.Create(ByteString.FromString(iteration.ToString()), clientLocalEndpoint)); clientProbe.ExpectMsg<Udp.Received>(x => { x.Data.ToString().ShouldBe(iteration.ToString()); x.Sender.Is(serverLocalEndpoint).ShouldBeTrue($"Client sender {x.Sender} was expected to be {serverLocalEndpoint}"); }, hint: $"sending to client failed in {iteration} iteration"); } void CheckSendingToServer(int iteration) { client.Tell(Udp.Send.Create(ByteString.FromString(iteration.ToString()), serverLocalEndpoint)); serverProbe.ExpectMsg<Udp.Received>(x => { x.Data.ToString().ShouldBe(iteration.ToString()); x.Sender.Is(clientLocalEndpoint).ShouldBeTrue($"Server sender {x.Sender} was expected to be {clientLocalEndpoint}"); }, hint: $"sending to client failed in {iteration} iteration"); } const int iterations = 20; for (int i = 1; i <= iterations; i++) CheckSendingToServer(i); for (int i = 1; i <= iterations; i++) CheckSendingToClient(i); for (int i = 1; i <= iterations; i++) { if (i % 2 == 0) CheckSendingToServer(i); else CheckSendingToClient(i); } } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_be_able_to_send_several_packets_in_a_row() { var (server, serverLocalEndpoint) = BindUdp(TestActor); var (client, clientLocalEndpoint) = BindUdp(TestActor); void CheckSendingToClient(ByteString expected) { ExpectMsg<Udp.Received>(x => { x.Data.ShouldBe(expected); x.Sender.Is(serverLocalEndpoint).ShouldBeTrue($"{x.Sender} was expected to be {serverLocalEndpoint}"); }); } void CheckSendingToServer(ByteString expected) { ExpectMsg<Udp.Received>(x => { x.Data.ShouldBe(expected); x.Sender.Is(clientLocalEndpoint).ShouldBeTrue($"{x.Sender} was expected to be {clientLocalEndpoint}"); }); } var data = new[] { ByteString.FromString("a"), ByteString.FromString("bb"), ByteString.FromString("ccc"), ByteString.FromString("dddd"), ByteString.FromString("eeeee"), ByteString.FromString("ffffff"), ByteString.FromString("ggggggg"), ByteString.FromString("hhhhhhhh"), ByteString.FromString("iiiiiiiii"), ByteString.FromString("jjjjjjjjjj") }; var iterations = data.Length; for (int i = 0; i < iterations; i++) client.Tell(Udp.Send.Create(data[i], serverLocalEndpoint)); for (int i = 0; i < iterations; i++) CheckSendingToServer(data[i]); for (int i = 0; i < iterations; i++) server.Tell(Udp.Send.Create(data[i], clientLocalEndpoint)); for (int i = 0; i < iterations; i++) CheckSendingToClient(data[i]); } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_not_leak_memory() { const int batchCount = 2000; const int batchSize = 100; var udp = Udp.Instance.Apply(Sys); var poolInfo = udp.SocketEventArgsPool.BufferPoolInfo; poolInfo.Type.Should().Be(typeof(DirectBufferPool)); poolInfo.Free.Should().Be(poolInfo.TotalSize); poolInfo.Used.Should().Be(0); var serverProbe = CreateTestProbe(); var (server, _) = BindUdp(serverProbe); var clientProbe = CreateTestProbe(); var (client, clientLocalEndpoint) = BindUdp(clientProbe); var data = ByteString.FromString("Fly little packet!"); // send a lot of packets through, the byte buffer pool should not leak anything for (var n = 0; n < batchCount; ++n) { for (var i = 0; i < batchSize; i++) server.Tell(Udp.Send.Create(data, clientLocalEndpoint)); var msgs = clientProbe.ReceiveN(batchSize); var receives = msgs.Cast<Udp.Received>(); receives.Sum(r => r.Data.Count).Should().Be(data.Count * batchSize); } // stop all connections so all receives are stopped and all pending SocketAsyncEventArgs are collected server.Tell(Udp.Unbind.Instance, serverProbe); serverProbe.ExpectMsg<Udp.Unbound>(); client.Tell(Udp.Unbind.Instance, clientProbe); clientProbe.ExpectMsg<Udp.Unbound>(); // wait for all SocketAsyncEventArgs to be released Thread.Sleep(1000); poolInfo = udp.SocketEventArgsPool.BufferPoolInfo; poolInfo.Type.Should().Be(typeof(DirectBufferPool)); poolInfo.Free.Should().Be(poolInfo.TotalSize); poolInfo.Used.Should().Be(0); } [Fact] public void The_UDP_Fire_and_Forget_SimpleSender_implementation_must_not_leak_memory() { const int batchCount = 2000; const int batchSize = 100; var udp = Udp.Instance.Apply(Sys); var poolInfo = udp.SocketEventArgsPool.BufferPoolInfo; poolInfo.Type.Should().Be(typeof(DirectBufferPool)); poolInfo.Free.Should().Be(poolInfo.TotalSize); poolInfo.Used.Should().Be(0); var serverProbe = CreateTestProbe(); var (server, serverLocalEndpoint) = BindUdp(serverProbe); var sender = SimpleSender(); var data = ByteString.FromString("Fly little packet!"); // send a lot of packets through, the byte buffer pool should not leak anything for (var n = 0; n < batchCount; ++n) { for (int i = 0; i < batchSize; i++) sender.Tell(Udp.Send.Create(data, serverLocalEndpoint)); var msgs = serverProbe.ReceiveN(batchSize); var receives = msgs.Cast<Udp.Received>(); receives.Sum(r => r.Data.Count).Should().Be(data.Count * batchSize); } // stop all connections so all receives are stopped and all pending SocketAsyncEventArgs are collected server.Tell(Udp.Unbind.Instance, serverProbe); serverProbe.ExpectMsg<Udp.Unbound>(); // wait for all SocketAsyncEventArgs to be released Thread.Sleep(1000); poolInfo = udp.SocketEventArgsPool.BufferPoolInfo; poolInfo.Type.Should().Be(typeof(DirectBufferPool)); poolInfo.Free.Should().Be(poolInfo.TotalSize); poolInfo.Used.Should().Be(0); } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_call_SocketOption_beforeBind_method_before_bind() { var commander = CreateTestProbe(); var assertOption = new AssertBeforeBind(); commander.Send( Udp.Instance.Apply(Sys).Manager, new Udp.Bind(TestActor, new IPEndPoint(IPAddress.Loopback, 0), options: new[] {assertOption})); commander.ExpectMsg<Udp.Bound>(); Assert.Equal(1, assertOption.BeforeCalled); } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_call_SocketOption_afterConnect_method_after_binding() { var commander = CreateTestProbe(); var assertOption = new AssertAfterChannelBind(); commander.Send( Udp.Instance.Apply(Sys).Manager, new Udp.Bind(TestActor, new IPEndPoint(IPAddress.Loopback, 0), options: new[] { assertOption })); commander.ExpectMsg<Udp.Bound>(); Assert.Equal(1, assertOption.AfterCalled); } [Fact] public void The_UDP_Fire_and_Forget_implementation_must_call_DatagramChannelCreator_create_method_when_opening_channel() { var commander = CreateTestProbe(); var assertOption = new AssertOpenDatagramChannel(); commander.Send( Udp.Instance.Apply(Sys).Manager, new Udp.Bind( TestActor, new IPEndPoint(IPAddress.Loopback, 0), options: new[] { assertOption })); commander.ExpectMsg<Udp.Bound>(); Assert.Equal(1, assertOption.OpenCalled); } class AssertBeforeBind : Inet.SocketOption { public int BeforeCalled { get; private set; } public override void BeforeDatagramBind(Socket ds) { Assert.True(!ds.IsBound); BeforeCalled += 1; } } class AssertAfterChannelBind : Inet.SocketOptionV2 { public int AfterCalled { get; set; } public override void AfterBind(Socket s) { Assert.True(s.IsBound); AfterCalled += 1; } } class AssertOpenDatagramChannel : Inet.DatagramChannelCreator { public int OpenCalled { get; set; } public override Socket Create() { OpenCalled += 1; return base.Create(); } public override Socket Create(AddressFamily addressFamily) { OpenCalled += 1; return base.Create(addressFamily); } } } } <|start_filename|>src/examples/Cluster/ClusterSharding/ShoppingCart/MessageExtractor.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="MessageExtractor.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Cluster.Sharding; namespace ShoppingCart { #region ExtractorClass public sealed class ShardEnvelope { public string EntityId { get; } public object Payload { get; } public ShardEnvelope(string entityId, object payload) { EntityId = entityId; Payload = payload; } } public sealed class MessageExtractor : HashCodeMessageExtractor { public MessageExtractor(int maxNumberOfShards) : base(maxNumberOfShards) { } public override string EntityId(object message) => message switch { ShardRegion.StartEntity start => start.EntityId, ShardEnvelope e => e.EntityId, _ => null }; public override object EntityMessage(object message) => message switch { ShardEnvelope e => e.Payload, _ => message }; } #endregion } <|start_filename|>src/core/Akka.Tests/IO/TestSocketOption.cs<|end_filename|> // //----------------------------------------------------------------------- // // <copyright file="TestSocketOption.cs" company="Akka.NET Project"> // // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // // </copyright> // //----------------------------------------------------------------------- using System; using System.Net.Sockets; using Akka.IO; namespace Akka.Tests.IO { internal class TestSocketOption : Inet.SocketOptionV2 { private readonly Action<Socket> _callback; public TestSocketOption(Action<Socket> callback) { _callback = callback; } public override void AfterBind(Socket s) => _callback(s); public override void AfterConnect(Socket s) => _callback(s); } } <|start_filename|>src/core/Akka/Serialization/SerializerErrorCode.cs<|end_filename|> // //----------------------------------------------------------------------- // // <copyright file="ErrorCodes.cs" company="Akka.NET Project"> // // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // // </copyright> // //----------------------------------------------------------------------- using System.Collections.Generic; using System.Text; namespace Akka.Serialization { internal class SerializerErrorCode { public static readonly Dictionary<int, SerializerErrorCode> ErrorCodes = new Dictionary<int, SerializerErrorCode> { [1] = new SerializerErrorCode(1, "Akka.Serialization.NewtonSoftJsonSerializer, Akka", "ConfigurationFactory.Default()", "ActorSystem.Create()"), [2] = new SerializerErrorCode(2, "Akka.Remote.Serialization.ProtobufSerializer, Akka.Remote", "RemoteConfigFactory.Default()", null), [3] = new SerializerErrorCode(3, "Akka.Remote.Serialization.DaemonMsgCreateSerializer, Akka.Remote", "RemoteConfigFactory.Default()", null), [4] = new SerializerErrorCode(4, "Akka.Serialization.ByteArraySerializer, Akka", "ConfigurationFactory.Default()", "ActorSystem.Create()"), [5] = new SerializerErrorCode(5, "Akka.Cluster.Serialization.ClusterMessageSerializer, Akka.Cluster", "ClusterConfigFactory.Default()", "ClusterSharding.Get()"), [6] = new SerializerErrorCode(6, "Akka.Remote.Serialization.MessageContainerSerializer, Akka.Remote", "RemoteConfigFactory.Default()", null), [7] = new SerializerErrorCode(7, "Akka.Persistence.Serialization.PersistenceMessageSerializer, Akka.Persistence", "Persistence.DefaultConfig()", "Persistence.Instance.Apply()"), [8] = new SerializerErrorCode(8, "Akka.Persistence.Serialization.PersistenceSnapshotSerializer, Akka.Persistence", "Persistence.DefaultConfig()", "Persistence.Instance.Apply()"), [10] = new SerializerErrorCode(10, "Akka.Cluster.Metrics.Serialization.ClusterMetricsMessageSerializer, Akka.Cluster.Metrics", "ClusterMetrics.DefaultConfig()", "ClusterMetrics.Get()"), [11] = new SerializerErrorCode(11, "Akka.DistributedData.Serialization.ReplicatedDataSerializer, Akka.DistributedData", "DistributedData.DefaultConfig() or ClusterSharding.DefaultConfig()", "ClusterSharding.Get(), DistributedData.Get()"), [12] = new SerializerErrorCode(12, "Akka.DistributedData.Serialization.ReplicatorMessageSerializer, Akka.DistributedData", "DistributedData.DefaultConfig() or ClusterSharding.DefaultConfig()", "ClusterSharding.Get(), DistributedData.Get()"), [13] = new SerializerErrorCode(13, "Akka.Cluster.Sharding.Serialization.ClusterShardingMessageSerializer, Akka.Cluster.Sharding", "ClusterSharding.DefaultConfig()", "ClusterSharding.Get()"), [14] = new SerializerErrorCode(14, "Akka.Cluster.Tools.Singleton.Serialization.ClusterSingletonMessageSerializer, Akka.Cluster.Tools", "DistributedPubSub.DefaultConfig(), ClusterSingletonProxy.DefaultConfig(), or ClusterSingletonManager.DefaultConfig()", "DistributedPubSub.Get(), ClusterSharding.Get()"), [15] = new SerializerErrorCode(15, "Akka.Cluster.Tools.Client.Serialization.ClusterClientMessageSerializer, Akka.Cluster.Tools", "ClusterClientReceptionist.DefaultConfig()", "ClusterClientReceptionist.Get()"), [16] = new SerializerErrorCode(16, "Akka.Remote.Serialization.MiscMessageSerializer, Akka.Remote", "RemoteConfigFactory.Default()", null), [17] = new SerializerErrorCode(17, "Akka.Remote.Serialization.PrimitiveSerializers, Akka.Remote", "RemoteConfigFactory.Default()", null), [22] = new SerializerErrorCode(22, "Akka.Remote.Serialization.SystemMessageSerializer, Akka.Remote", "RemoteConfigFactory.Default()", null), [30] = new SerializerErrorCode(30, "Akka.Streams.Serialization.StreamRefSerializer, Akka.Streams", "ActorMaterializer.DefaultConfig()", "ActorSystem.Materializer()"), [48] = new SerializerErrorCode(48, "Akka.Persistence.Redis.Serialization.PersistentSnapshotSerializer, Akka.Persistence.Redis", "RedisPersistence.DefaultConfig()", "RedisPersistence.Get()"), }; public static string GetErrorForSerializerId(int id) => ErrorCodes.TryGetValue(id, out var err) ? err.ToString() : id > 100 ? $"Serializer Id [{id}] is not one of the internal Akka.NET serializer. Please contact your plugin provider for more information." : $"Could not find any internal Akka.NET serializer with Id [{id}]. Please create an issue in our GitHub at [https://github.com/akkadotnet/akka.net]."; private SerializerErrorCode(int id, string fqcn, string directAccess, string injector) { Id = id; Fqcn = fqcn; DirectAccess = directAccess; Injector = injector; } public int Id { get; } public string Fqcn { get; } public string DirectAccess { get; } public string Injector { get; } public override string ToString() { var sb = new StringBuilder($"Serializer Id [{Id}] is used to instantiate [{Fqcn}]. ") .Append($"You can add it by adding a fallback to your ActorSystem configuration by using [{DirectAccess}]."); if (Injector != null) sb.Append($" It is also automatically injected into your configuration when you call [{Injector}]."); return sb.ToString(); } } } <|start_filename|>src/examples/Cluster/ClusterSharding/ClusterSharding.Node/start.cmd<|end_filename|> dotnet publish -c Release docker build -t cluster-sharding:latest . docker-compose up <|start_filename|>src/core/Akka.Streams.Tests/Dsl/QueueSinkSpec.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="QueueSinkSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Akka.Actor; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.Streams.Util; using Akka.TestKit; using Akka.Util; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class QueueSinkSpec : AkkaSpec { private readonly ActorMaterializer _materializer; private readonly TimeSpan _pause = TimeSpan.FromMilliseconds(300); private static TestException TestException() { return new TestException("boom"); } public QueueSinkSpec(ITestOutputHelper output) : base(output) { _materializer = Sys.Materializer(); } [Fact] public void QueueSink_should_send_the_elements_as_result_of_future() { this.AssertAllStagesStopped(() => { var expected = new List<Option<int>> { new Option<int>(1), new Option<int>(2), new Option<int>(3), new Option<int>() }; var queue = Source.From(expected.Where(o => o.HasValue).Select(o => o.Value)) .RunWith(Sink.Queue<int>(), _materializer); expected.ForEach(v => { queue.PullAsync().PipeTo(TestActor); ExpectMsg(v); }); }, _materializer); } [Fact] public void QueueSink_should_allow_to_have_only_one_future_waiting_for_result_in_each_point_in_time() { this.AssertAllStagesStopped(() => { var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer); var sub = probe.ExpectSubscription(); var future = queue.PullAsync(); var future2 = queue.PullAsync(); future2.Invoking(t => t.Wait(RemainingOrDefault)).Should().Throw<IllegalStateException>(); sub.SendNext(1); future.PipeTo(TestActor); ExpectMsg(new Option<int>(1)); sub.SendComplete(); queue.PullAsync(); }, _materializer); } [Fact] public void QueueSink_should_wait_for_next_element_from_upstream() { this.AssertAllStagesStopped(() => { var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer); var sub = probe.ExpectSubscription(); queue.PullAsync().PipeTo(TestActor); ExpectNoMsg(_pause); sub.SendNext(1); ExpectMsg(new Option<int>(1)); sub.SendComplete(); queue.PullAsync(); }, _materializer); } [Fact] public void QueueSink_should_fail_future_on_stream_failure() { this.AssertAllStagesStopped(() => { var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer); var sub = probe.ExpectSubscription(); queue.PullAsync().PipeTo(TestActor); ExpectNoMsg(_pause); sub.SendError(TestException()); ExpectMsg<Status.Failure>( f => f.Cause.Equals(TestException())); }, _materializer); } [Fact] public void QueueSink_should_fail_future_when_stream_failed() { this.AssertAllStagesStopped(() => { var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer); var sub = probe.ExpectSubscription(); sub.SendError(TestException()); queue.Invoking(q => q.PullAsync().Wait(RemainingOrDefault)) .Should().Throw<TestException>(); }, _materializer); } [Fact] public void QueueSink_should_timeout_future_when_stream_cannot_provide_data() { this.AssertAllStagesStopped(() => { var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer); var sub = probe.ExpectSubscription(); queue.PullAsync().PipeTo(TestActor); ExpectNoMsg(_pause); sub.SendNext(1); ExpectMsg(new Option<int>(1)); sub.SendComplete(); queue.PullAsync(); }, _materializer); } [Fact] public void QueueSink_should_fail_pull_future_when_stream_is_completed() { this.AssertAllStagesStopped(() => { var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer); var sub = probe.ExpectSubscription(); queue.PullAsync().PipeTo(TestActor); sub.SendNext(1); ExpectMsg(new Option<int>(1)); sub.SendComplete(); var result = queue.PullAsync().Result; result.Should().Be(Option<int>.None); var exception = Record.ExceptionAsync(async () => await queue.PullAsync()).Result; exception.Should().BeOfType<StreamDetachedException>(); }, _materializer); } [Fact] public void QueueSink_should_keep_on_sending_even_after_the_buffer_has_been_full() { this.AssertAllStagesStopped(() => { const int bufferSize = 16; const int streamElementCount = bufferSize + 4; var sink = Sink.Queue<int>().WithAttributes(Attributes.CreateInputBuffer(bufferSize, bufferSize)); var tuple = Source.From(Enumerable.Range(1, streamElementCount)) .AlsoToMaterialized( Flow.Create<int>().Take(bufferSize).WatchTermination(Keep.Right).To(Sink.Ignore<int>()), Keep.Right) .ToMaterialized(sink, Keep.Both) .Run(_materializer); var probe = tuple.Item1; var queue = tuple.Item2; probe.Wait(TimeSpan.FromMilliseconds(300)).Should().BeTrue(); for (var i = 1; i <= streamElementCount; i++) { queue.PullAsync().PipeTo(TestActor); ExpectMsg(new Option<int>(i)); } queue.PullAsync().PipeTo(TestActor); ExpectMsg(Option<int>.None); }, _materializer); } [Fact] public void QueueSink_should_work_with_one_element_buffer() { this.AssertAllStagesStopped(() => { var sink = Sink.Queue<int>().WithAttributes(Attributes.CreateInputBuffer(1, 1)); var probe = this.CreateManualPublisherProbe<int>(); var queue = Source.FromPublisher(probe).RunWith(sink, _materializer); var sub = probe.ExpectSubscription(); queue.PullAsync().PipeTo(TestActor); sub.SendNext(1); // should pull next element ExpectMsg(new Option<int>(1)); queue.PullAsync().PipeTo(TestActor); ExpectNoMsg(); // element requested but buffer empty sub.SendNext(2); ExpectMsg(new Option<int>(2)); sub.SendComplete(); var future = queue.PullAsync(); future.Wait(_pause).Should().BeTrue(); future.Result.Should().Be(Option<int>.None); }, _materializer); } [Fact] public void QueueSink_should_fail_to_materialize_with_zero_sized_input_buffer() { Source.Single(1) .Invoking( s => s.RunWith(Sink.Queue<int>().WithAttributes(Attributes.CreateInputBuffer(0, 0)), _materializer)) .Should().Throw<ArgumentException>(); } } } <|start_filename|>src/core/Akka/IO/UdpConnectedManager.cs<|end_filename|> //----------------------------------------------------------------------- // <copyright file="UdpConnectedManager.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; using Akka.Annotations; namespace Akka.IO { using ByteBuffer = ArraySegment<byte>; /// <summary> /// INTERNAL API /// </summary> [InternalApi] class UdpConnectedManager : ActorBase { private readonly UdpConnectedExt _udpConn; /// <summary> /// TBD /// </summary> /// <param name="udpConn">TBD</param> public UdpConnectedManager(UdpConnectedExt udpConn) { _udpConn = udpConn; } protected override bool Receive(object message) { switch (message) { case UdpConnected.Connect connect: { var commander = Sender; // NOTE: Aaronontheweb (9/1/2017) this should probably be the Handler... Context.ActorOf(Props.Create(() => new UdpConnection(_udpConn, commander, connect))); return true; } default: throw new ArgumentException($"The supplied message type [{message.GetType()}] is invalid. Only Connect messages are supported.", nameof(message)); } } } } <|start_filename|>src/examples/Cluster/ClusterSharding/ShoppingCart/Dockerfile<|end_filename|> FROM mcr.microsoft.com/dotnet/core/runtime:3.1 COPY ["./bin/Release/netcoreapp3.1/publish", "."] ENTRYPOINT ["dotnet", "ShoppingCart.dll"]
EgoPingvina/akka.net
<|start_filename|>MMM-Glance.js<|end_filename|> /********************************* Magic Mirror Module: MMM-Glance By eouia MIT Licensed *********************************/ Module.register("MMM-Glance", { defaults: { defaultGlancingTime : 10000, alias: {} }, start: function() { this.status = {} this.alias = {} this.glancing = false this.timer = null this.defaultAlias = { "news" : "newsfeed", "weather" : "currentweather", "forecast" : "weatherforecast", "hello" : "helloworld", "test" : ["clock", "newsfeed"] } }, getTranslations: function() { return { en: "translations/en.json", } }, getCommands: function(register) { if (register.constructor.name == 'TelegramBotCommandRegister') { register.add({ command: "glanceables", description: this.translate("CMD_GLANCENAMES_DESCRIPTION"), callback: "cmd_glancenames" }) register.add({ command: "glance", description: this.translate("CMD_GLANCE_DESCRIPTION"), args_pattern: [/.*/], args_mapping: ["name"], callback: "cmd_glanceon" }) register.add({ command: "glanceoff", description: this.translate("CMD_GLANCEOFF_DESCRIPTION"), callback: "cmd_glanceoff" }) } if (register.constructor.name == 'AssistantCommandRegister') { register.add({ command: this.translate("CMD_ASSTNT_GLANCEABLENAMES"), description: this.translate("CMD_GLANCENAMES_DESCRIPTION"), callback: "cmd_glancenames" }) register.add({ //command: "glance :name", command: this.translate("CMD_ASSTNT_GLANCE"), description: this.translate("CMD_ASSTNT_GLANCE_DESCRIPTION"), callback: "cmd_glanceon" }) register.add({ command: this.translate("CMD_ASSTNT_GLANCEOFF"), description: this.translate("CMD_GLANCEOFF_DESCRIPTION"), callback: "cmd_glanceoff" }) } }, cmd_glanceon: function(command, handler) { if (handler.args) { var ret = this.glanceOn(handler.args.name) if (ret) { handler.reply("TEXT", this.translate("CMD_GLANCE_SUCCESS")) } else { handler.reply("TEXT", this.translate("CMD_GLANCE_IMPOSSIBLE"), handler.args.name) } } else { handler.reply("TEXT", this.translate("CMD_GLANCE_NO_ARGS")) } }, cmd_glanceoff: function(command, handler) { this.glanceOff() handler.reply("TEXT", this.translate("CMD_GLANCE_SUCCESS")) }, cmd_glancenames: function(command, handler) { var text="" text = Object.keys(this.alias).join() handler.reply("TEXT", text) }, initialize: function() { var self = this MM.getModules().enumerate(function(m) { if(m.data.position) { self.alias[m.name] = m.name } }) this.alias = Object.assign({}, this.alias, this.defaultAlias, this.config.alias) }, glanceOn : function (call, time) { var filter = [] var self = this if (!time) { time = this.config.defaultGlancingTime } if (Object.keys(this.alias).indexOf(call) >= 0) { var modules = this.alias[call] if (Array.isArray(modules)) { filter = modules } else { filter.push(modules) } } else { return false } if (!this.glancing) { MM.getModules().enumerate(function(m) { if (m.data.position) { self.status[m.name] = m.hidden } }) } MM.getModules().enumerate(function(m) { if(Object.values(filter).indexOf(m.name) >= 0) { matched = 1 } }) if (matched == 0) { return false } else { clearTimeout(this.timer) this.timer = null MM.getModules().enumerate(function(m) { if (Object.values(filter).indexOf(m.name) >= 0) { m.show(0) } else { m.hide(0) } }) this.glancing = true this.sendNotification('GLANCE_STARTED', {modules:filter, time:time}) this.timer = setTimeout(function(){ self.glanceOff() }, time) return true } }, glanceOff: function() { this.glancing = false if (this.timer) { clearTimeout(this.timer) this.timer = null var self = this MM.getModules().enumerate(function(m) { if (typeof self.status[m.name] !== 'undefined') { if (self.status[m.name]) { m.hide(0) } else { m.show(0) } } }) this.status = {} this.sendNotification('GLANCE_ENDED') return true } return false }, notificationReceived: function(notification, payload, sender) { switch(notification) { case 'DOM_OBJECTS_CREATED': this.initialize() break case 'GLANCE_ON': this.glanceOn(payload.name, payload.time) break case 'GLANCE_OFF': this.glanceOff() break } }, })
eouia/MMM-Glance
<|start_filename|>public/dist/Parsley.js-2.6.0/test/unit/form.js<|end_filename|> import $ from 'jquery'; import ParsleyForm from '../../src/parsley/form'; import Parsley from '../../src/parsley'; describe('ParsleyForm', () => { it('should be a function', () => { expect(ParsleyForm).to.be.a('function'); }); it('should bind parsleyFields children', () => { $('body').append( '<form id="element">' + '<input id="field1" type="text"/>' + '<div id="field2"></div>' + '<textarea id="field2"></textarea>' + '</form>'); var parsleyForm = $('#element').parsley(); expect(parsleyForm.fields.length).to.be(2); }); it('should bind parsleyFields children, and not excluded ones', () => { $('body').append( '<form id="element">' + '<input id="field1" type="text"/>' + '<div id="field2"></div>' + '<textarea id="field2"></textarea>' + '<div data-parsley-validate></div>' + // ParsleyForm, not a valid child '<input id="field3" disabled />' + // Disabled, excluded buy custom options below '<input id="field-excluded" data-parsley-excluded="true" />' + // Disabled, excluded buy custom options below '<input type="submit"/>' + // Excluded field, not valid '</form>'); var parsleyForm = $('#element').parsley({excluded: '[disabled], input[type=button], input[type=submit], input[type=reset]'}); expect(parsleyForm.fields.length).to.be(2); }); it('should properly bind options for form and children fields', () => { $('body').append( '<form id="element" data-parsley-trigger="change">' + '<input id="field1" type="text" data-parsley-required="true" />' + '<div id="field2"></div>' + '<textarea id="field3" data-parsley-notblank="true"></textarea>' + '</form>'); var parsleyForm = $('#element').parsley(); expect(parsleyForm.fields.length).to.be(2); expect($('#field1').parsley().options.trigger).to.be('change'); expect($('#field1').parsley().options.required).to.eql(true); expect($('#field1').parsley().options.notblank).to.be(undefined); expect($('#field3').parsley().options.notblank).to.eql(true); expect($('#field3').parsley().options.required).to.be(undefined); }); it('should properly store validation state after `validate()`', () => { $('body').append( '<form id="element" data-parsley-trigger="change">' + '<input id="field1" type="text" data-parsley-required="true" />' + '<div id="field2"></div>' + '<textarea id="field3" data-parsley-notblank="true"></textarea>' + '</form>'); var parsleyForm = $('#element').parsley(); parsleyForm.validate(); expect(parsleyForm.validationResult).to.be(false); $('#field1').val('foo'); $('#field3').val('foo'); expect(parsleyForm.validate()).to.be(true); }); it('should handle group validation', () => { $('body').append( '<form id="element">' + '<input id="field1" type="text" data-parsley-group="foo" data-parsley-required="true" />' + '<div id="field2"></div>' + '<textarea id="field3" data-parsley-required="true"></textarea>' + '</form>'); var parsleyForm = $('#element').parsley(); expect(parsleyForm.isValid()).to.be(false); $('#field1').val('value'); expect(parsleyForm.isValid()).to.be(false); expect(parsleyForm.isValid({group: 'foo'})).to.be(true); $('#field3').attr('data-parsley-group', 'bar'); expectWarning(() => { expect(parsleyForm.isValid('bar')).to.be(false); }); }); it('should handle group validation with controls with multiple group names', () => { $('body').append( '<form id="element">' + '<input id="field1" type="text" data-parsley-group=\'["foo", "bar"]\' data-parsley-required="true" />' + '<input id="field2" type="text" data-parsley-group=\'["bar", "baz"]\' data-parsley-required="true" />' + '<textarea id="field3" data-parsley-group=\'["baz", "qux"]\' data-parsley-required="true"></textarea>' + '</form>'); var parsleyForm = $('#element').parsley(); expect(parsleyForm.isValid()).to.be(false); $('#field1').val('value'); $('#field2').val('value'); expect(parsleyForm.isValid()).to.be(false); // group name only on one required field, with value expect(parsleyForm.isValid('foo')).to.be(true); // group name on multiple required fields, all with values expect(parsleyForm.isValid('bar')).to.be(true); // group name on multiple required fields, one missing a value expect(parsleyForm.isValid('baz')).to.be(false); // group name on single required field, without value expect(parsleyForm.isValid('qux')).to.be(false); }); it('should send submit button values, even for async validations', () => { var deferred = null; window.Parsley.addValidator('custom', () => { deferred = $.Deferred(); return deferred.promise(); }); $('body').append( '<form id="element">' + '<input id="field1" type="text" name="nick" data-parsley-custom data-parsley-required />' + '<div id="field2" name="comment"></div>' + '<input type="submit" name="foo" value="bar" />' + '<input type="submit" name="foo" value="other" />' + '<button name="foo" value="but">ok</button>' + '</form>'); var parsleyForm = $('#element').parsley(); $('#element input:last').click(); // Form should not be submitted at this point, coz field is required expect(deferred).to.be(null); $('#field1').val('something'); var values = []; $('#element').on('submit', evt => { expect(evt.parsley).to.be(true); values.push($('form input[type!=submit][name="foo"]').val()); evt.preventDefault(); }); $('#element button').click(); expect(values).to.eql([]); deferred.resolve(); expect(values).to.eql(['but']); $('#element input[value="other"]').click(); deferred.resolve(); expect(values).to.eql(['but', 'other']); $('#element').submit(); // Similar to pressing 'enter' deferred.resolve(); expect(values).to.eql(['but', 'other', 'bar']); window.Parsley.removeValidator('custom'); }); it('should not validate when triggered by a button with formnovalidate', () => { var $form = $('<form id="element"><input type="string" required /><input type="submit" formnovalidate /><form>').appendTo($('body')); $form.on('submit', e => { e.preventDefault(); }); var callbacks = []; $.each(['validate', 'error', 'success', 'validated', 'submit'], (i, cb) => { $form.parsley().on('form:' + cb, () => { callbacks.push(cb); }); }); $form.parsley(); $form.find('input[type=submit]').click(); expect(callbacks.join()).to.be(''); }); it('should have a force option for validate and isValid methods', () => { $('body').append( '<form id="element">' + '<input id="field1" type="email" />' + '<input id="field3" data-parsley-notblank="true" />' + '</form>'); expect($('#element').parsley().isValid()).to.be(true); expect($('#element').parsley().isValid({force: true})).to.be(false); expect($('#element').parsley().validate()).to.be(true); expectWarning(() => { expect($('#element').parsley().validate(undefined, true)).to.be(false); }); }); it('should properly bind dynamically added fields', () => { $('body').append('<form id="element" data-parsley-trigger="change"></form>'); $('#element').append('<input type="email" id="email" required />'); var fieldInstance = $('#email').psly(); expect(fieldInstance.__class__).to.be('ParsleyField'); var formInstance = $('#element').psly(); // form corectly have its field, and field have finaly its parent form expect(formInstance.fields[0].$element.attr('id')).to.be('email'); expect(fieldInstance.parent.__class__).to.be('ParsleyForm'); }); it('should fire the right callbacks in the right order', () => { var $form = $('<form id="element"><input type="string" required /><form>').appendTo($('body')); $form.on('submit', e => { e.preventDefault(); }); var callbacks = []; $.each(['validate', 'error', 'success', 'validated', 'submit'], (i, cb) => { $form.parsley().on('form:' + cb, () => { callbacks.push(cb); }); }); $form.parsley(); $form.submit(); $form.find('input').val('Hello'); $form.submit(); expect(callbacks.join()).to.be('validate,error,validated,validate,success,validated,submit'); }); it('should fire "form:validate.parsley" to give the opportunity for changes before validation occurs', () => { var $form = $('<form id="element"><input type="string" required /><form>').appendTo($('body')); $form.parsley().on('form:validate', function () { this.$element.find('input').remove(); }); expect($form.parsley().validate()).to.be(true); }); it('should stop event propagation on form submit', done => { $('body').append('<form id="element"><input type="text" required/></form>'); var parsleyInstance = $('#element').parsley() .on('form:validated', () => { done(); }); $('#element').on('submit', () => { // It sould never pass here! expect(true).to.be(false); }) .submit(); }); it('should have the validationResult be changeable', () => { var submitted = false; $('<form id="element"></form>') .appendTo('body') .parsley() .on('form:success', form => { form.validationResult = false; }) .on('form:error', form => { form.validationResult = true; }) .on('form:submit', form => { submitted = true; return false; }); $('#element').submit(); expect(submitted).to.be(false); $('#element').append('<input required>').submit(); expect(submitted).to.be(true); }); it('should fire form:submit.event and be interruptable when validated', done => { $('<form id="element"></form>') .appendTo('body') .parsley() .on('form:submit', () => { done(); return false; }); $('#element').submit(); }); it('should deprecate interruptions with submitEvent.preventDefault()', () => { expectWarning(() => { $('<form id="element"></form>') .appendTo('body') .parsley() .on('form:validate', (form) => { form.submitEvent.preventDefault(); }) .on('form:submit', (form) => { throw new Error('Form should not have been submitted'); }); $('#element').submit(); }); }); it('should fire field:reset event if fields are removed or excluded', () => { var parsleyInstance; var steps = []; var step = 'init'; var parsleyForm = $('<form id="element"><input type="text" required></form>') .appendTo('body') .parsley() .on('field:reset', function () { steps.push('form: ' + step); expect(this).to.be(parsleyInstance); }) ; parsleyInstance = $('#element input').parsley() .on('field:reset', function () { steps.push('field: ' + step); expect(this).to.be(parsleyInstance); }); parsleyForm.validate(); parsleyForm.validate(); parsleyForm.options.excluded = '[required]'; step = 'excluded'; parsleyForm.validate(); parsleyForm.validate(); parsleyForm.options.excluded = ''; step = 'not excluded'; parsleyForm.validate(); parsleyForm.validate(); var $i = $('#element input').detach(); step = 'detached'; parsleyForm.validate(); parsleyForm.validate(); $i.appendTo('form'); step = 'reattached'; parsleyForm.validate(); parsleyForm.validate(); $i.remove(); step = 'removed'; parsleyForm.validate(); parsleyForm.validate(); expect(steps).to.eql(['field: excluded', 'form: excluded', 'field: detached', 'form: detached', 'field: removed', 'form: removed']); }); it('should handle validators returning promises', done => { var called = 0; var shouldSubmit = false; var form = $('<form id="element"><input data-parsley-custom value="x"/></form>') .appendTo('body') .parsley(); var deferred; window.Parsley.addValidator('custom', () => { called++; deferred = $.Deferred(); return deferred.promise(); }); $('#element').on('submit', evt => { evt.preventDefault(); expect(evt.parsley).to.be(true); // Sanity check expect(shouldSubmit).to.be(true); window.Parsley.removeValidator('custom'); done(); }); $('#element').submit(); expect(called).to.eql(1); deferred.reject(); var promise = form.whenValidate(); expect(called).to.eql(2); expect(promise.state()).to.eql('pending'); deferred.reject(); expect(promise.state()).to.eql('rejected'); $('#element').submit(); expect(called).to.eql(3); shouldSubmit = true; deferred.resolve(); }); it('should handle priority correctly', () => { var calls = []; var form = $('<form id="element"><input value="0" data-parsley-custom1 data-parsley-custom2 data-parsley-custom3 data-parsley-custom4/></form>') .appendTo('body') .parsley() .on('form:submit', evt => { return false; }); for (const i of [1, 2, 3, 4]) window.Parsley.addValidator(`custom${i}`, { priority: i <= 2 ? 100 : 10 - i, validateNumber: function(value, requirement) { calls.push(i); return value > i; } }); $('#element').submit(); $('#element input').val('3'); $('#element').submit(); $('#element input').val('5'); $('#element').submit(); expect(calls).to.eql([2, 1, 2, 1, 3, 2, 1, 3, 4]); for (const i of [1, 2, 3, 4]) window.Parsley.removeValidator(`custom${i}`); }); afterEach(() => { $('#element').remove(); }); }); <|start_filename|>public/dist/Parsley.js-2.6.0/doc/annotated-source/remote.html<|end_filename|> <!DOCTYPE html> <html> <head> <title>remote.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <ul id="jump_to"> <li> <a class="large" href="javascript:void(0);">Jump To &hellip;</a> <a class="small" href="javascript:void(0);">+</a> <div id="jump_wrapper"> <div id="jump_page"><a class="source" href="../index.html"><<< back to documentation</a> <a class="source" href="abstract.html"> abstract.js </a> <a class="source" href="defaults.html"> defaults.js </a> <a class="source" href="factory.html"> factory.js </a> <a class="source" href="field.html"> field.js </a> <a class="source" href="form.html"> form.js </a> <a class="source" href="main.html"> main.js </a> <a class="source" href="multiple.html"> multiple.js </a> <a class="source" href="pubsub.html"> pubsub.js </a> <a class="source" href="remote.html"> remote.js </a> <a class="source" href="ui.html"> ui.js </a> <a class="source" href="utils.html"> utils.js </a> <a class="source" href="validator.html"> validator.js </a> <a class="source" href="validator_registry.html"> validator_registry.js </a> </div> </li> </ul> <ul class="sections"> <li id="title"> <div class="annotation"> <h1>remote.js</h1> </div> </li> <li id="section-1"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-1">&#182;</a> </div> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">import</span> $ <span class="hljs-keyword">from</span> <span class="hljs-string">'jquery'</span>; <span class="hljs-keyword">import</span> Parsley <span class="hljs-keyword">from</span> <span class="hljs-string">'./main'</span>; $.extend(<span class="hljs-literal">true</span>, Parsley, { asyncValidators: { <span class="hljs-string">'default'</span>: { fn: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">xhr</span>) </span>{</pre></div></div> </li> <li id="section-2"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-2">&#182;</a> </div> <p>By default, only status 2xx are deemed successful. Note: we use status instead of state() because responses with status 200 but invalid messages (e.g. an empty body for content type set to JSON) will result in state() === ‘rejected’.</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">return</span> xhr.status &gt;= <span class="hljs-number">200</span> &amp;&amp; xhr.status &lt; <span class="hljs-number">300</span>; }, url: <span class="hljs-literal">false</span> }, reverse: { fn: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">xhr</span>) </span>{</pre></div></div> </li> <li id="section-3"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-3">&#182;</a> </div> <p>If reverse option is set, a failing ajax request is considered successful</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">return</span> xhr.status &lt; <span class="hljs-number">200</span> || xhr.status &gt;= <span class="hljs-number">300</span>; }, url: <span class="hljs-literal">false</span> } }, addAsyncValidator: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">name, fn, url, options</span>) </span>{ Parsley.asyncValidators[name] = { fn: fn, url: url || <span class="hljs-literal">false</span>, options: options || {} }; <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>; } }); Parsley.addValidator(<span class="hljs-string">'remote'</span>, { requirementType: { <span class="hljs-string">''</span>: <span class="hljs-string">'string'</span>, <span class="hljs-string">'validator'</span>: <span class="hljs-string">'string'</span>, <span class="hljs-string">'reverse'</span>: <span class="hljs-string">'boolean'</span>, <span class="hljs-string">'options'</span>: <span class="hljs-string">'object'</span> }, validateString: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value, url, options, instance</span>) </span>{ <span class="hljs-keyword">var</span> data = {}; <span class="hljs-keyword">var</span> ajaxOptions; <span class="hljs-keyword">var</span> csr; <span class="hljs-keyword">var</span> validator = options.validator || (<span class="hljs-literal">true</span> === options.reverse ? <span class="hljs-string">'reverse'</span> : <span class="hljs-string">'default'</span>); <span class="hljs-keyword">if</span> (<span class="hljs-string">'undefined'</span> === <span class="hljs-keyword">typeof</span> Parsley.asyncValidators[validator]) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Calling an undefined async validator: `'</span> + validator + <span class="hljs-string">'`'</span>); url = Parsley.asyncValidators[validator].url || url;</pre></div></div> </li> <li id="section-4"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-4">&#182;</a> </div> <p>Fill current value</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> (url.indexOf(<span class="hljs-string">'{value}'</span>) &gt; <span class="hljs-number">-1</span>) { url = url.replace(<span class="hljs-string">'{value}'</span>, <span class="hljs-built_in">encodeURIComponent</span>(value)); } <span class="hljs-keyword">else</span> { data[instance.$element.attr(<span class="hljs-string">'name'</span>) || instance.$element.attr(<span class="hljs-string">'id'</span>)] = value; }</pre></div></div> </li> <li id="section-5"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-5">&#182;</a> </div> <p>Merge options passed in from the function with the ones in the attribute</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">var</span> remoteOptions = $.extend(<span class="hljs-literal">true</span>, options.options || {} , Parsley.asyncValidators[validator].options);</pre></div></div> </li> <li id="section-6"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-6">&#182;</a> </div> <p>All <code>$.ajax(options)</code> could be overridden or extended directly from DOM in <code>data-parsley-remote-options</code></p> </div> <div class="content"><div class='highlight'><pre> ajaxOptions = $.extend(<span class="hljs-literal">true</span>, {}, { url: url, data: data, type: <span class="hljs-string">'GET'</span> }, remoteOptions);</pre></div></div> </li> <li id="section-7"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-7">&#182;</a> </div> <p>Generate store key based on ajax options</p> </div> <div class="content"><div class='highlight'><pre> instance.trigger(<span class="hljs-string">'field:ajaxoptions'</span>, instance, ajaxOptions); csr = $.param(ajaxOptions);</pre></div></div> </li> <li id="section-8"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-8">&#182;</a> </div> <p>Initialise querry cache</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> (<span class="hljs-string">'undefined'</span> === <span class="hljs-keyword">typeof</span> Parsley._remoteCache) Parsley._remoteCache = {};</pre></div></div> </li> <li id="section-9"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-9">&#182;</a> </div> <p>Try to retrieve stored xhr</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">var</span> xhr = Parsley._remoteCache[csr] = Parsley._remoteCache[csr] || $.ajax(ajaxOptions); <span class="hljs-keyword">var</span> handleXhr = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">var</span> result = Parsley.asyncValidators[validator].fn.call(instance, xhr, url, options); <span class="hljs-keyword">if</span> (!result) <span class="hljs-comment">// Map falsy results to rejected promise</span> result = $.Deferred().reject(); <span class="hljs-keyword">return</span> $.when(result); }; <span class="hljs-keyword">return</span> xhr.then(handleXhr, handleXhr); }, priority: <span class="hljs-number">-1</span> }); Parsley.on(<span class="hljs-string">'form:submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ Parsley._remoteCache = {}; }); <span class="hljs-built_in">window</span>.ParsleyExtend.addAsyncValidator = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ ParsleyUtils.warnOnce(<span class="hljs-string">'Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`'</span>); <span class="hljs-keyword">return</span> Parsley.addAsyncValidator(...arguments); };</pre></div></div> </li> </ul> </div> <script type="text/javascript">var _gaq=_gaq||[];_gaq.push(["_setAccount","UA-37229467-1"]);_gaq.push(["_trackPageview"]);(function(){var e=document.createElement("script");e.type="text/javascript";e.async=true;e.src=("https:"==document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})();</script></body> </html> <|start_filename|>public/dist/Parsley.js-2.6.0/doc/annotated-source/main.html<|end_filename|> <!DOCTYPE html> <html> <head> <title>main.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <ul id="jump_to"> <li> <a class="large" href="javascript:void(0);">Jump To &hellip;</a> <a class="small" href="javascript:void(0);">+</a> <div id="jump_wrapper"> <div id="jump_page"><a class="source" href="../index.html"><<< back to documentation</a> <a class="source" href="abstract.html"> abstract.js </a> <a class="source" href="defaults.html"> defaults.js </a> <a class="source" href="factory.html"> factory.js </a> <a class="source" href="field.html"> field.js </a> <a class="source" href="form.html"> form.js </a> <a class="source" href="main.html"> main.js </a> <a class="source" href="multiple.html"> multiple.js </a> <a class="source" href="pubsub.html"> pubsub.js </a> <a class="source" href="remote.html"> remote.js </a> <a class="source" href="ui.html"> ui.js </a> <a class="source" href="utils.html"> utils.js </a> <a class="source" href="validator.html"> validator.js </a> <a class="source" href="validator_registry.html"> validator_registry.js </a> </div> </li> </ul> <ul class="sections"> <li id="title"> <div class="annotation"> <h1>main.js</h1> </div> </li> <li id="section-1"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-1">&#182;</a> </div> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">import</span> $ <span class="hljs-keyword">from</span> <span class="hljs-string">'jquery'</span>; <span class="hljs-keyword">import</span> ParsleyUtils <span class="hljs-keyword">from</span> <span class="hljs-string">'./utils'</span>; <span class="hljs-keyword">import</span> ParsleyDefaults <span class="hljs-keyword">from</span> <span class="hljs-string">'./defaults'</span>; <span class="hljs-keyword">import</span> ParsleyAbstract <span class="hljs-keyword">from</span> <span class="hljs-string">'./abstract'</span>; <span class="hljs-keyword">import</span> ParsleyValidatorRegistry <span class="hljs-keyword">from</span> <span class="hljs-string">'./validator_registry'</span>; <span class="hljs-keyword">import</span> ParsleyUI <span class="hljs-keyword">from</span> <span class="hljs-string">'./ui'</span>; <span class="hljs-keyword">import</span> ParsleyForm <span class="hljs-keyword">from</span> <span class="hljs-string">'./form'</span>; <span class="hljs-keyword">import</span> ParsleyField <span class="hljs-keyword">from</span> <span class="hljs-string">'./field'</span>; <span class="hljs-keyword">import</span> ParsleyMultiple <span class="hljs-keyword">from</span> <span class="hljs-string">'./multiple'</span>; <span class="hljs-keyword">import</span> ParsleyFactory <span class="hljs-keyword">from</span> <span class="hljs-string">'./factory'</span>; <span class="hljs-keyword">var</span> vernums = $.fn.jquery.split(<span class="hljs-string">'.'</span>); <span class="hljs-keyword">if</span> (<span class="hljs-built_in">parseInt</span>(vernums[<span class="hljs-number">0</span>]) &lt;= <span class="hljs-number">1</span> &amp;&amp; <span class="hljs-built_in">parseInt</span>(vernums[<span class="hljs-number">1</span>]) &lt; <span class="hljs-number">8</span>) { <span class="hljs-keyword">throw</span> <span class="hljs-string">"The loaded version of jQuery is too old. Please upgrade to 1.8.x or better."</span>; } <span class="hljs-keyword">if</span> (!vernums.forEach) { ParsleyUtils.warn(<span class="hljs-string">'Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim'</span>); }</pre></div></div> </li> <li id="section-2"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-2">&#182;</a> </div> <p>Inherit <code>on</code>, <code>off</code> &amp; <code>trigger</code> to Parsley:</p> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">var</span> Parsley = $.extend(<span class="hljs-keyword">new</span> ParsleyAbstract(), { $element: $(<span class="hljs-built_in">document</span>), actualizeOptions: <span class="hljs-literal">null</span>, _resetOptions: <span class="hljs-literal">null</span>, Factory: ParsleyFactory, version: <span class="hljs-string">'@@version'</span> });</pre></div></div> </li> <li id="section-3"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-3">&#182;</a> </div> <p>Supplement ParsleyField and Form with ParsleyAbstract This way, the constructors will have access to those methods</p> </div> <div class="content"><div class='highlight'><pre>$.extend(ParsleyField.prototype, ParsleyUI.Field, ParsleyAbstract.prototype); $.extend(ParsleyForm.prototype, ParsleyUI.Form, ParsleyAbstract.prototype);</pre></div></div> </li> <li id="section-4"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-4">&#182;</a> </div> <p>Inherit actualizeOptions and _resetOptions:</p> </div> <div class="content"><div class='highlight'><pre>$.extend(ParsleyFactory.prototype, ParsleyAbstract.prototype);</pre></div></div> </li> <li id="section-5"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-5">&#182;</a> </div> <h3 id="jquery-api">jQuery API</h3> <p><code>$(&#39;.elem&#39;).parsley(options)</code> or <code>$(&#39;.elem&#39;).psly(options)</code></p> </div> <div class="content"><div class='highlight'><pre>$.fn.parsley = $.fn.psly = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">options</span>) </span>{ <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.length &gt; <span class="hljs-number">1</span>) { <span class="hljs-keyword">var</span> instances = []; <span class="hljs-keyword">this</span>.each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ instances.push($(<span class="hljs-keyword">this</span>).parsley(options)); }); <span class="hljs-keyword">return</span> instances; }</pre></div></div> </li> <li id="section-6"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-6">&#182;</a> </div> <p>Return undefined if applied to non existing DOM element</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> (!$(<span class="hljs-keyword">this</span>).length) { ParsleyUtils.warn(<span class="hljs-string">'You must bind Parsley on an existing element.'</span>); <span class="hljs-keyword">return</span>; } <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ParsleyFactory(<span class="hljs-keyword">this</span>, options); };</pre></div></div> </li> <li id="section-7"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-7">&#182;</a> </div> <h3 id="parsleyfield-and-parsleyform-extension">ParsleyField and ParsleyForm extension</h3> <p>Ensure the extension is now defined if it wasn’t previously</p> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">if</span> (<span class="hljs-string">'undefined'</span> === <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span>.ParsleyExtend) <span class="hljs-built_in">window</span>.ParsleyExtend = {};</pre></div></div> </li> <li id="section-8"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-8">&#182;</a> </div> <h3 id="parsley-config">Parsley config</h3> <p>Inherit from ParsleyDefault, and copy over any existing values</p> </div> <div class="content"><div class='highlight'><pre>Parsley.options = $.extend(ParsleyUtils.objectCreate(ParsleyDefaults), <span class="hljs-built_in">window</span>.ParsleyConfig); <span class="hljs-built_in">window</span>.ParsleyConfig = Parsley.options; <span class="hljs-comment">// Old way of accessing global options</span></pre></div></div> </li> <li id="section-9"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-9">&#182;</a> </div> <h3 id="globals">Globals</h3> </div> <div class="content"><div class='highlight'><pre><span class="hljs-built_in">window</span>.Parsley = <span class="hljs-built_in">window</span>.psly = Parsley; <span class="hljs-built_in">window</span>.ParsleyUtils = ParsleyUtils;</pre></div></div> </li> <li id="section-10"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-10">&#182;</a> </div> <h3 id="define-methods-that-forward-to-the-registry-and-deprecate-all-access-except-through-window-parsley">Define methods that forward to the registry, and deprecate all access except through window.Parsley</h3> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">var</span> registry = <span class="hljs-built_in">window</span>.Parsley._validatorRegistry = <span class="hljs-keyword">new</span> ParsleyValidatorRegistry(<span class="hljs-built_in">window</span>.ParsleyConfig.validators, <span class="hljs-built_in">window</span>.ParsleyConfig.i18n); <span class="hljs-built_in">window</span>.ParsleyValidator = {}; $.each(<span class="hljs-string">'setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator'</span>.split(<span class="hljs-string">' '</span>), <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">i, method</span>) </span>{ <span class="hljs-built_in">window</span>.Parsley[method] = $.proxy(registry, method); <span class="hljs-built_in">window</span>.ParsleyValidator[method] = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ ParsleyUtils.warnOnce(<span class="hljs-string">`Accessing the method '<span class="hljs-subst">${method}</span>' through ParsleyValidator is deprecated. Simply call 'window.Parsley.<span class="hljs-subst">${method}</span>(...)'`</span>); <span class="hljs-keyword">return</span> <span class="hljs-built_in">window</span>.Parsley[method](...arguments); }; });</pre></div></div> </li> <li id="section-11"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-11">&#182;</a> </div> <h3 id="parsleyui">ParsleyUI</h3> <p>Deprecated global object</p> </div> <div class="content"><div class='highlight'><pre><span class="hljs-built_in">window</span>.Parsley.UI = ParsleyUI; <span class="hljs-built_in">window</span>.ParsleyUI = { removeError: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">instance, name, doNotUpdateClass</span>) </span>{ <span class="hljs-keyword">var</span> updateClass = <span class="hljs-literal">true</span> !== doNotUpdateClass; ParsleyUtils.warnOnce(<span class="hljs-string">`Accessing ParsleyUI is deprecated. Call 'removeError' on the instance directly. Please comment in issue 1073 as to your need to call this method.`</span>); <span class="hljs-keyword">return</span> instance.removeError(name, {updateClass}); }, getErrorsMessages: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">instance</span>) </span>{ ParsleyUtils.warnOnce(<span class="hljs-string">`Accessing ParsleyUI is deprecated. Call 'getErrorsMessages' on the instance directly.`</span>); <span class="hljs-keyword">return</span> instance.getErrorsMessages(); } }; $.each(<span class="hljs-string">'addError updateError'</span>.split(<span class="hljs-string">' '</span>), <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">i, method</span>) </span>{ <span class="hljs-built_in">window</span>.ParsleyUI[method] = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">instance, name, message, assert, doNotUpdateClass</span>) </span>{ <span class="hljs-keyword">var</span> updateClass = <span class="hljs-literal">true</span> !== doNotUpdateClass; ParsleyUtils.warnOnce(<span class="hljs-string">`Accessing ParsleyUI is deprecated. Call '<span class="hljs-subst">${method}</span>' on the instance directly. Please comment in issue 1073 as to your need to call this method.`</span>); <span class="hljs-keyword">return</span> instance[method](name, {message, assert, updateClass}); }; });</pre></div></div> </li> <li id="section-12"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-12">&#182;</a> </div> <h3 id="parsley-auto-binding">PARSLEY auto-binding</h3> <p>Prevent it by setting <code>ParsleyConfig.autoBind</code> to <code>false</code></p> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">if</span> (<span class="hljs-literal">false</span> !== <span class="hljs-built_in">window</span>.ParsleyConfig.autoBind) { $(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{</pre></div></div> </li> <li id="section-13"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-13">&#182;</a> </div> <p>Works only on <code>data-parsley-validate</code>.</p> </div> <div class="content"><div class='highlight'><pre> <span class="hljs-keyword">if</span> ($(<span class="hljs-string">'[data-parsley-validate]'</span>).length) $(<span class="hljs-string">'[data-parsley-validate]'</span>).parsley(); }); } <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Parsley;</pre></div></div> </li> </ul> </div> <script type="text/javascript">var _gaq=_gaq||[];_gaq.push(["_setAccount","UA-37229467-1"]);_gaq.push(["_trackPageview"]);(function(){var e=document.createElement("script");e.type="text/javascript";e.async=true;e.src=("https:"==document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})();</script></body> </html>
yogamadness/bpmweb
<|start_filename|>canarygen_awscreds.cmd<|end_filename|> @echo off REM Test script to generate AWS creds REM Requires curl and jq. Customize name/path to EXEs below. set curl=curl set jq=jq-win64.exe REM Grab the date and time for creating unique files for /f "tokens=1,2,3,4 delims=/ " %%a in ('date /t') do set currdate=%%d%%c%%b for /f "tokens=1,2,3,4 delims=.:" %%a in ("%time%") do set currtime=%%a%%b%%c REM Set this variable to your API token set token=<KEY> REM Customize this variable to match your console URL set console=ab123456.canary.tools ECHO Using console %console% REM Token memo set tokenmemo=\"Consider any AWS creds from %USERNAME% on %COMPUTERNAME% compromised\" REM Base URL set baseurl="https://$console/api/v1/canarytoken/create?auth_token=%token%&memo=%tokenmemo%&kind=aws-id&aws_id_username=%USERNAME%" REM Run the jewels ECHO Creating token. One moment... %curl% -s -X POST https://%console%/api/v1/canarytoken/create -d "auth_token=%token%&memo=%tokenmemo%&kind=aws-id" | %jq% -r ".canarytoken.renders.\"aws-id\"" > awscreds_%currdate%%currtime%.txt ECHO New AWS Credentials Canarytoken written to file awscreds_%currdate%%currtime%.txt pause
szepeviktor/canary-utils
<|start_filename|>hawk-core/src/main/java/com/wealdtech/hawk/guice/HawkServerConfigurationModule.java<|end_filename|> package com.wealdtech.hawk.guice; import com.google.inject.AbstractModule; import com.wealdtech.hawk.HawkServerConfiguration; /** * Make Hawk configuration available to Guice */ public class HawkServerConfigurationModule extends AbstractModule { private final HawkServerConfiguration configuration; public HawkServerConfigurationModule(final HawkServerConfiguration configuration) { super(); this.configuration = configuration; } @Override protected void configure() { binder().bind(HawkServerConfiguration.class).toInstance(this.configuration); } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/config/ApplicationModule.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.wealdtech.DataError; import com.wealdtech.configuration.ConfigurationSource; import com.wealdtech.jetty.config.JettyServerConfiguration; public class ApplicationModule extends AbstractModule { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModule.class); @Override protected void configure() { try { // Bind configuration information final JettyServerConfiguration configuration = new ConfigurationSource<JettyServerConfiguration>().getConfiguration("config-test.json", JettyServerConfiguration.class); bind(JettyServerConfiguration.class).toInstance(configuration); } catch (DataError de) { LOGGER.error("Failed to initialize properties: {}", de.getLocalizedMessage(), de); } } } <|start_filename|>hawk-server-jersey/src/main/java/com/wealdtech/hawk/jersey/HawkAuthenticationFilter.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk.jersey; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import com.google.common.base.Optional; import com.google.inject.Inject; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerRequestFilter; import com.wealdtech.DataError; import com.wealdtech.ServerError; import com.wealdtech.jersey.auth.Authenticator; import com.wealdtech.jersey.exceptions.InternalServerException; import com.wealdtech.jersey.exceptions.UnauthorizedException; /** * Authentication filter using the Hawk protocol. * @param <T> */ public class HawkAuthenticationFilter<T> implements ContainerRequestFilter { private final transient Authenticator<T> authenticator; @Context private transient HttpServletRequest servletrequest; @Inject public HawkAuthenticationFilter(final Authenticator<T> authenticator) { this.authenticator = authenticator; } @Override public ContainerRequest filter(final ContainerRequest request) { Optional<T> result; try { result = authenticator.authenticate(request); } catch (DataError de) { // A data error means that the authentication attempt failed due to bad data throw new UnauthorizedException(de); } catch (ServerError se) { // A server error means that the authentication attempt failed due to a server problem throw new InternalServerException(se); } // At this point authentication is complete and we can check the result if (!result.isPresent()) { // No result returned; authentication did not result in a valid principal throw new UnauthorizedException("Unknown or invalid authentication", "Authentication failed"); } // At this point the request has been authenticated successfully. // Store the object returned form the authenticator so that it can be // accessed by resources, providers etc. this.servletrequest.setAttribute("com.wealdtech.authenticatedprincipal", result.get()); return request; } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/resources/HelloWorldResource.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.resources; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import test.com.wealdtech.hawk.model.ExampleUser; /** * Simple resource for testing Hawk authentication and * authenticated user injection. */ @Path("helloworld") public class HelloWorldResource { @Context ExampleUser authenticatedUser; @GET @Produces("text/plain") public String getHelloWorld() { if (this.authenticatedUser == null) { return "Hello world"; } else { return "Hello " + this.authenticatedUser.getName(); } } @POST @Produces("text/plain") public String getHelloWorldPost() { if (this.authenticatedUser == null) { return "Hello world"; } else { return "Hello " + this.authenticatedUser.getName(); } } } <|start_filename|>hawk-core/src/test/java/test/com/wealdtech/hawk/HawkServerTest.java<|end_filename|> /* * Copyright 2012 - 2014 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk; import com.google.common.io.BaseEncoding; import com.wealdtech.DataError; import com.wealdtech.hawk.*; import com.wealdtech.hawk.Hawk.PayloadValidation; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.HttpURLConnection; import java.net.URI; import static org.testng.Assert.*; public class HawkServerTest { private HawkCredentials testcredentials1, testcredentials2; private HawkClient testclient; private URI validuri1, validuri2; private static final String BASEBEWITURI = "http://localhost:18234/helloworld"; // Helper private HttpURLConnection connect(final URI uri, final String authorizationHeader, final String body) throws Exception { final HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); connection.setRequestMethod("GET"); if (authorizationHeader != null) { connection.setRequestProperty("Authorization", authorizationHeader); } if (body != null) { connection.setDoOutput(true); } connection.setDoInput(true); connection.connect(); if (body != null) { connection.getOutputStream().write(body.getBytes()); } return connection; } @BeforeClass public void setUp() throws Exception { this.testcredentials1 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.testcredentials2 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.testclient = new HawkClient.Builder().credentials(this.testcredentials1).build(); this.validuri1 = new URI("http://localhost:18234/testpath/subpath?param1=val1&param2=val2"); this.validuri2 = new URI("http://localhost:18234/v1/usergroups/"); } @Test public void testModel() throws Exception { // Test a default server final HawkServer server1 = new HawkServer.Builder().build(); server1.toString(); server1.hashCode(); assertEquals(server1, server1); assertNotEquals(null, server1); assertNotEquals(server1, null); // Test a copied server HawkServer server2 = new HawkServer.Builder(server1) .configuration(new HawkServerConfiguration.Builder() .payloadValidation(PayloadValidation.MANDATORY) .build()) .build(); server2.toString(); server2.hashCode(); assertEquals(server2, server2); assertNotEquals(null, server2); assertNotEquals(server2, null); assertNotEquals(server1, server2); } @Test public void testConfigurationModel() throws Exception { // Test the default configuration final HawkServerConfiguration configuration1 = new HawkServerConfiguration.Builder().build(); configuration1.toString(); configuration1.hashCode(); assertEquals(configuration1, configuration1); assertNotEquals(configuration1, null); assertNotEquals(null, configuration1); // Test a copied configuration final HawkServerConfiguration configuration2 = new HawkServerConfiguration.Builder(configuration1) .bewitAllowed(false) .nonceCacheSize(500L) .payloadValidation(PayloadValidation.MANDATORY) .timestampSkew(30L) .build(); configuration2.toString(); configuration2.hashCode(); assertEquals(configuration2, configuration2); assertNotEquals(configuration2, null); assertNotEquals(null, configuration2); assertNotEquals(configuration2, configuration1); } @Test public void testValidation() throws Exception { // Ensure that invalid timeskew is caught try { new HawkServerConfiguration.Builder().timestampSkew(-5L).build(); fail("Created Hawk server configuration with invalid timestamp skew"); } catch (DataError de) { // Good } // Ensure that invalid nonce cache size is caught try { new HawkServerConfiguration.Builder().nonceCacheSize(-5L).build(); fail("Created Hawk server configuration with invalid nonce cache"); } catch (DataError de) { // Good } } @Test public void testSkewConfiguration() throws Exception { // Ensure that timeout is working HawkServerConfiguration configuration = new HawkServerConfiguration.Builder() .timestampSkew(1L) .build(); SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, configuration); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); Thread.sleep(2000L); try { final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testDuplicateConfiguration() throws Exception { // Ensure that duplicating the configuration works final HawkServerConfiguration configuration = new HawkServerConfiguration.Builder() .timestampSkew(123L) .build(); final HawkServerConfiguration copy = new HawkServerConfiguration.Builder(configuration).build(); assertEquals(configuration, copy); } @Test public void testMissingAuthorizationHeader() throws Exception { // Ensure that a missing authorization header is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { final HttpURLConnection connection = connect(this.validuri1, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testAuthorizationHeader() throws Exception { // Test correct implementation final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 200); } finally { server.stop(); } } @Test public void testAuthorizationHeader2() throws Exception { // Test correct implementation with body final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); final String body = "Body of request"; final String hash = Hawk.calculateMac(this.testcredentials1, body); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "post", hash, null, null, null); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, body); assertEquals(connection.getResponseCode(), 200); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader1() throws Exception { // Ensure that an authorization header with the wrong header is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("Hawk", "Eagle"); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader2() throws Exception { // Ensure that an authorization header without a nonce is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("nonce=", "invalid="); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader3() throws Exception { // Ensure that an authorization header without a timestamp is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("ts=", "invalid="); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader4() throws Exception { // Ensure that an authorization header without a mac is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("mac=", "invalid="); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader5() throws Exception { // Ensure that an authorization header without an id is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("id=", "invalid="); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader6() throws Exception { // Ensure that an authorization header with an invalid mac is caught SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri2, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("mac=\"", "mac=\"x"); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader7() throws Exception { // Ensure that bad body hashes are caught final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); final String body = "Body of request"; final String hash = Hawk.calculateMac(this.testcredentials1, "Some other text"); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "post", hash, null, null, null); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, body); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader8() throws Exception { // Ensure that invalid timestamps are caught final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); authorizationHeader = authorizationHeader.replace("ts=\"", "ts=\"x"); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader9() throws Exception { // Ensure that a blank Hawk authorization header is caught final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { String authorizationHeader = "Hawk"; final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader10() throws Exception { // Ensure that if payload hash is required that this is enforced final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, new HawkServerConfiguration.Builder().payloadValidation(PayloadValidation.MANDATORY).build()); final String body = "Body text"; try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, body); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidAuthorizationHeader11() throws Exception { // Ensure that if payload hash is required that this is enforced, but not if there is no body final SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, new HawkServerConfiguration.Builder().payloadValidation(PayloadValidation.MANDATORY).build()); try { String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); final HttpURLConnection connection = connect(this.validuri1, authorizationHeader, null); assertEquals(connection.getResponseCode(), 200); } finally { server.stop(); } } @Test public void testBewit() throws Exception { // Test a valid bewit SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { final String bewit = Hawk.generateBewit(this.testcredentials1, new URI(BASEBEWITURI), 600L, null); URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 200); } finally { server.stop(); } } @Test public void testExpiredBewit() throws Exception { // Test an expired bewit SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { final String bewit = Hawk.generateBewit(this.testcredentials1, new URI(BASEBEWITURI), 1L, null); URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); Thread.sleep(2000); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidBewit1() throws Exception { // Test an invalid bewit due to mismatched URIs SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); try { final String bewit = Hawk.generateBewit(this.testcredentials1, this.validuri1, 120L, null); URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidBewit2() throws Exception { // Test an invalid bewit due to missing Key ID SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); // Calculate expiry from ttl and current time Long expiry = System.currentTimeMillis() / 1000L + 120L; final String mac = Hawk.calculateMAC(this.testcredentials1, Hawk.AuthType.BEWIT, expiry, new URI(BASEBEWITURI), null, null, null, null, null, null); final StringBuffer sb = new StringBuffer(256); sb.append('\\'); sb.append(String.valueOf(expiry)); sb.append('\\'); sb.append(mac); sb.append('\\'); final String bewit = BaseEncoding.base64().encode(sb.toString().getBytes()); try { URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidBewit3() throws Exception { // Test an invalid bewit due to missing expiry SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); // Calculate expiry from ttl and current time Long expiry = System.currentTimeMillis() / 1000L + 120L; final String mac = Hawk.calculateMAC(this.testcredentials1, Hawk.AuthType.BEWIT, expiry, new URI(BASEBEWITURI), null, null, null, null, null, null); final StringBuffer sb = new StringBuffer(256); sb.append(this.testcredentials1.getKeyId()); sb.append('\\'); sb.append('\\'); sb.append(mac); sb.append('\\'); final String bewit = BaseEncoding.base64().encode(sb.toString().getBytes()); try { URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidBewit4() throws Exception { // Test an invalid bewit due to missing mac SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); // Calculate expiry from ttl and current time Long expiry = System.currentTimeMillis() / 1000L + 120L; // final String mac = Hawk.calculateMAC(this.testcredentials1, Hawk.AuthType.BEWIT, expiry, new URI(BASEBEWITURI), null, null, null, null); final StringBuffer sb = new StringBuffer(256); sb.append(this.testcredentials1.getKeyId()); sb.append('\\'); sb.append(String.valueOf(expiry)); sb.append('\\'); sb.append('\\'); final String bewit = BaseEncoding.base64().encode(sb.toString().getBytes()); try { URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } @Test public void testInvalidBewit5() throws Exception { // Test an invalid bewit due to malforation SimpleHttpServer server = new SimpleHttpServer(this.testcredentials1, null); // Calculate expiry from ttl and current time Long expiry = System.currentTimeMillis() / 1000L + 120L; final String mac = Hawk.calculateMAC(this.testcredentials1, Hawk.AuthType.BEWIT, expiry, new URI(BASEBEWITURI), null, null, null, null, null, null); final StringBuffer sb = new StringBuffer(256); sb.append(this.testcredentials1.getKeyId()); sb.append('\\'); sb.append(String.valueOf(expiry)); sb.append('\\'); sb.append(mac); final String bewit = BaseEncoding.base64().encode(sb.toString().getBytes()); try { URI testUri = new URI(BASEBEWITURI + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, null, null); assertEquals(connection.getResponseCode(), 401); } finally { server.stop(); } } } <|start_filename|>hawk-core/src/test/resources/clientconfig-test3.json<|end_filename|> // Invalid configuration for a Hawk client { "pathprefix": "/", "payloadvalidation": "invalid" } <|start_filename|>hawk-server-jersey/src/main/java/com/wealdtech/hawk/jersey/HawkAuthenticator.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk.jersey; import static com.wealdtech.Preconditions.*; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.List; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.common.io.CharStreams; import com.google.inject.Inject; import com.sun.jersey.spi.container.ContainerRequest; import com.wealdtech.DataError; import com.wealdtech.hawk.Hawk; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.hawk.HawkServer; import com.wealdtech.jersey.auth.Authenticator; import com.wealdtech.jersey.auth.PrincipalProvider; /** * Authenticate a request using Hawk. */ public class HawkAuthenticator<T extends HawkCredentialsProvider> implements Authenticator<T> { private final transient HawkServer server; private final transient PrincipalProvider<T, String> provider; /** * Create a new authenticator for Hawk. * @param server a the Hawk server * @param provider a provider for Hawk credentials */ @Inject public HawkAuthenticator(final HawkServer server, final PrincipalProvider<T, String> provider) { this.server = server; this.provider = provider; } @Override public boolean canAuthenticate(final ContainerRequest request) { boolean result = false; try { server.splitAuthorizationHeader(request.getHeaderValue(ContainerRequest.AUTHORIZATION)); result = true; } catch (DataError de) { // Means we can't authenticate using Hawk } return result; } /** * Authenticate a request. * <p>Authentication can be with an authentication header or a query string, so * decide which it is and handle it appropriately. * @param request the HTTP request * @return the authenticated principal, or <code>Optional.absent()</code> if the request was not authenticated * @throws DataError if there is a problem with the data that prevents the authentication attempt */ @Override public Optional<T> authenticate(final ContainerRequest request) { if (request.getQueryParameters().containsKey("bewit")) { return authenticateFromBewit(request); } else { return authenticateFromHeader(request); } } /** * Authenticate a request from a bewit. * @param request the HTTP request * @return the authenticated principal, or <code>Optional.absent()</code> if the request was not authenticated * @throws DataError if there is a problem with the data that prevents the authentication attempt */ private Optional<T> authenticateFromBewit(final ContainerRequest request) { checkState((request.getMethod().equals("GET")), "HTTP method %s not supported with bewit", request.getMethod()); final String bewit = server.extractBewit(request.getRequestUri()); final ImmutableMap<String, String> bewitFields = server.splitBewit(bewit); final Optional<T> principal = provider.getFromKey(bewitFields.get("id")); if (!principal.isPresent()) { // Could not find the principal, reject this authentication request return Optional.absent(); } final HawkCredentials credentials = principal.get().getHawkCredentials(bewitFields.get("id")); this.server.authenticate(credentials, request.getRequestUri()); return principal; } /** * Authenticate a request from an authentication header. * @param request the HTTP request * @return the authenticated principal, or <code>Optional.absent()</code> if the request was not authenticated * @throws DataError if there is a problem with the data that prevents the authentication attempt */ private Optional<T> authenticateFromHeader(final ContainerRequest request) { final ImmutableMap<String, String> authorizationHeaders = server.splitAuthorizationHeader(request.getHeaderValue(ContainerRequest.AUTHORIZATION)); checkNotNull(authorizationHeaders.get("id"), "Missing required Hawk authorization header \"id\""); checkNotNull(authorizationHeaders.get("ts"), "Missing required Hawk authorization header \"ts\""); checkNotNull(authorizationHeaders.get("mac"), "Missing required Hawk authorization header \"mac\""); checkNotNull(authorizationHeaders.get("nonce"), "Missing required Hawk authorization header \"nonce\""); String hash = null; final URI uri = request.getRequestUri(); final String method = request.getMethod(); final Optional<T> principal = provider.getFromKey(authorizationHeaders.get("id")); if (!principal.isPresent()) { // Could not find the principal, reject this authentication request return Optional.absent(); } final HawkCredentials credentials = principal.get().getHawkCredentials(authorizationHeaders.get("id")); if (authorizationHeaders.get("hash") != null) { try { List<String> contentTypes = request.getRequestHeader(ContainerRequest.CONTENT_TYPE); if ((contentTypes == null) || (contentTypes.size() == 0)) { throw new DataError.Bad("Missing content type header for body verification"); } hash = Hawk.calculateBodyMac(credentials, contentTypes.get(0), CharStreams.toString(new InputStreamReader(request.getEntityInputStream(), "UTF-8"))); } catch (IOException ioe) { throw new DataError.Bad("Failed to read the message body to calculate hash", ioe); } } final boolean hasBody = request.getHeaderValue(ContainerRequest.CONTENT_LENGTH) != null ? true : false; this.server.authenticate(credentials, uri, method, authorizationHeaders, hash, hasBody); return principal; } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/service/ExampleUserService.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.service; import java.util.List; import java.util.Map; import test.com.wealdtech.hawk.model.ExampleUser; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.wealdtech.DataError; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.hawk.jersey.HawkPrincipalProvider; /** * Example service to provide a user definition given a key. * <p>In this case, the key is the Hawk key ID as passed in * by every the Hawk-authenticated request. */ public class ExampleUserService extends HawkPrincipalProvider<ExampleUser> { private transient final Map<String, ExampleUser> usermap; public ExampleUserService() throws DataError { this.usermap = Maps.newHashMap(); HawkCredentials user1HawkCredentials1 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); HawkCredentials user1HawkCredentials2 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); List<HawkCredentials> user1HawkCredentials = Lists.newArrayList(user1HawkCredentials1, user1HawkCredentials2); ExampleUser user1 = new ExampleUser("Steve", user1HawkCredentials); this.usermap.put(user1HawkCredentials1.getKeyId(), user1); this.usermap.put(user1HawkCredentials2.getKeyId(), user1); HawkCredentials user2HawkCredentials1 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); List<HawkCredentials> user2HawkCredentials = Lists.newArrayList(user2HawkCredentials1); ExampleUser user2 = new ExampleUser("John", user2HawkCredentials); this.usermap.put(user2HawkCredentials1.getKeyId(), user2); } /** * Simple lookup of a local map to find an ExampleUser given a * Hawk key ID. In any real-world situation this method would * be expected to query some sort of persistent datastore. * @param hawkKeyId the ID of the Hawk key that identifies the user * @return An Optional, containing the ExampleUser if they were found */ @Override public Optional<ExampleUser> getFromKey(final String hawkKeyId) { return Optional.fromNullable(this.usermap.get(hawkKeyId)); } } <|start_filename|>hawk-core/src/main/java/com/wealdtech/hawk/HawkClient.java<|end_filename|> /* * Copyright 2012 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk; import static com.wealdtech.Preconditions.*; import java.net.URI; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; import com.google.inject.Inject; import com.wealdtech.DataError; import com.wealdtech.utils.StringUtils; public final class HawkClient implements Comparable<HawkClient> { private final HawkClientConfiguration configuration; private final HawkCredentials credentials; private long mTimeSkew; @Inject private HawkClient(final HawkClientConfiguration configuration, final HawkCredentials credentials) { if (configuration == null) { this.configuration = new HawkClientConfiguration(); } else { this.configuration = configuration; } this.credentials = credentials; validate(); } private void validate() { checkNotNull(this.configuration, "The client configuration is required"); checkNotNull(this.credentials, "The credentials are required"); } /** * Adjust the client to handle clock skew from server clock. * <p> * Calculate the time-skew between the client and server, for any future * request.<br> * This can handle clock skew in either the client or the server, or * any timezone mis-configuration.<br> * Just call this method any time (or any number of times) after receiving * a response from the server.<br> * This can be either successful or error response. * <p> * Example: * <pre> * * URLConnection conn; * ... * //send request, receive anything. * if ( conn.getDate()!=0 ) hawkClient.setServerDate(conn.getDate()); * </pre> * @param date the current server date, as was received from the server. */ public void setServerDate(long date) { mTimeSkew = date - System.currentTimeMillis(); } /** * Generate the value for the Hawk authorization header. * * @param uri the URI for the request * @param method the request for the method * @param hash a hash of the request's payload, or <code>null</code> if payload authentication is not required * @param ext extra data, or <code>null</code> if none * @param app application ID, or <code>null</code> if none * @param dlg delegator, or <code>null</code> if none * @return The value for the Hawk authorization header. * @throws DataError If there is a problem with the data passed in which makes it impossible to generate a valid authorization header */ public String generateAuthorizationHeader(final URI uri, final String method, final String hash, final String ext, final String app, final String dlg) { long timestamp = (System.currentTimeMillis() + mTimeSkew) / Hawk.MILLISECONDS_IN_SECONDS; final String nonce = StringUtils.generateRandomString(6); final String mac = Hawk.calculateMAC(this.credentials, Hawk.AuthType.HEADER, timestamp, uri, nonce, method, hash, ext, app, dlg); final StringBuilder sb = new StringBuilder(1024); sb.append("Hawk id=\""); sb.append(this.credentials.getKeyId()); sb.append("\", ts=\""); sb.append(timestamp); sb.append("\", nonce=\""); sb.append(nonce); if (hash != null) { sb.append("\", hash=\""); sb.append(hash); } if ((ext != null) && (!"".equals(ext))) { sb.append("\", ext=\""); sb.append(ext); } sb.append("\", mac=\""); sb.append(mac); sb.append('"'); return sb.toString(); } public boolean isValidFor(final String path) { return ((this.configuration.getPathPrefix() == null) || ((path == null) || (path.startsWith(this.configuration.getPathPrefix())))); } // Standard object methods follow @Override public String toString() { return Objects.toStringHelper(this) .add("configuration", this.configuration) .add("credentials", this.credentials) .toString(); } @Override public boolean equals(final Object that) { return (that instanceof HawkClient) && (this.compareTo((HawkClient)that) == 0); } @Override public int hashCode() { return Objects.hashCode(this.configuration, this.credentials); } @Override public int compareTo(final HawkClient that) { return ComparisonChain.start() .compare(this.configuration, that.configuration) .compare(this.credentials, that.credentials) .result(); } public static class Builder { private HawkClientConfiguration configuration; private HawkCredentials credentials; /** * Generate a new builder. */ public Builder() { } /** * Generate build with all values set from a prior object. * @param prior the prior object */ public Builder(final HawkClient prior) { this.configuration = prior.configuration; this.credentials = prior.credentials; } /** * Override the existing configuration. * @param configuration the new configuration * @return The builder */ public Builder configuration(final HawkClientConfiguration configuration) { this.configuration = configuration; return this; } /** * Override the existing credentials. * @param credentials the new credentials * @return The builder */ public Builder credentials(final HawkCredentials credentials) { this.credentials = credentials; return this; } /** * Build the client * @return a new client */ public HawkClient build() { return new HawkClient(this.configuration, this.credentials); } } } <|start_filename|>hawk-core/src/main/java/com/wealdtech/hawk/Hawk.java<|end_filename|> /* * Copyright 2012, 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk; import static com.wealdtech.Preconditions.*; import java.io.UnsupportedEncodingException; import java.net.URI; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Strings; import com.google.common.io.BaseEncoding; import com.wealdtech.DataError; import com.wealdtech.ServerError; import com.wealdtech.hawk.HawkCredentials.Algorithm; /** * The Hawk class provides helper methods for calculating the MAC, required by * both clients and servers. */ public class Hawk { public static final String HAWKVERSION = "1"; protected static final long MILLISECONDS_IN_SECONDS = 1000L; private static final int DEFAULT_HTTP_PORT = 80; private static final int DEFAULT_HTTPS_PORT = 443; /** * Calculate and return a MAC. The MAC is used to sign the method and * parameters passed as part of a request. It forms the basis to allow the * server to verify that the request has not been tampered with. * <p> * Note that there is no validation of the parameters except to confirm that * mandatory parameters are not null. * * @param credentials * Hawk credentials of the requestor * @param authType * The type of the MAC to calculate * @param timestamp * timestamp of the request * @param uri * URI of the request, including query parameters if appropriate * @param nonce * nonce a random string used to uniquely identify the request * @param method * the HTTP method of the request * @param hash * a hash of the request's payload, or <code>null</code> if payload * authentication is not required * @param ext * optional extra data, as supplied by the requestor to differentiate * the request if required * @param app * application ID, used for Oz * @param dlg * delegator, used for Oz * @return the MAC * @throws DataError * if there is an issue with the data that prevents creation of the * MAC */ public static String calculateMAC(final HawkCredentials credentials, final AuthType authType, final Long timestamp, final URI uri, final String nonce, final String method, final String hash, final String ext, final String app, final String dlg) { // Check that required parameters are present checkNotNull(credentials, "Credentials are required but not supplied"); checkNotNull(timestamp, "Timestamp is required but not supplied"); checkNotNull(uri, "URI is required but not supplied"); checkNotNull(authType, "Authentication type is required but not supplied"); if (authType.equals(AuthType.HEADER)) { // Additional parameters for core authentications checkNotNull(nonce, "Nonce is required but not supplied"); checkNotNull(method, "Method is required but not supplied"); } final StringBuilder sb = new StringBuilder(1024); sb.append("hawk."); sb.append(HAWKVERSION); sb.append('.'); sb.append(authType.toString()); sb.append('\n'); sb.append(timestamp); sb.append('\n'); if (authType.equals(AuthType.HEADER)) { sb.append(nonce); } sb.append('\n'); if (authType.equals(AuthType.BEWIT)) { sb.append("GET"); } else { sb.append(method.toUpperCase(Locale.ENGLISH)); } sb.append('\n'); sb.append(uri.getRawPath()); if (uri.getQuery() != null) { sb.append('?'); sb.append(uri.getRawQuery()); } sb.append('\n'); sb.append(uri.getHost().toLowerCase(Locale.ENGLISH)); sb.append('\n'); sb.append(getPort(uri)); sb.append('\n'); if ((authType.equals(AuthType.HEADER)) && (hash != null)) { sb.append(hash); } sb.append('\n'); sb.append(Strings.nullToEmpty(ext).replace("\\", "\\\\").replace("\n", "\\n")); sb.append('\n'); if (app != null) { sb.append(app); sb.append('\n'); sb.append(Strings.nullToEmpty(dlg)); sb.append('\n'); } return calculateMac(credentials, sb.toString()); } /** * Obtain the port of a URI. * @param uri the URI * @return The port. */ private static int getPort(final URI uri) { int port = uri.getPort(); if (port == -1) { // Default port if ("http".equals(uri.getScheme())) { port = DEFAULT_HTTP_PORT; } else if ("https".equals(uri.getScheme())) { port = DEFAULT_HTTPS_PORT; } else { throw new DataError.Bad("Unknown URI scheme \"" + uri.getScheme() + "\""); } } return port; } public static String calculateTSMac(final long curtime) { final HawkCredentials credentials = new HawkCredentials.Builder() .keyId("dummy") .key("dummy") .algorithm(Algorithm.SHA256) .build(); return calculateMac(credentials, String.valueOf(curtime)); } /** * Generate the MAC for a body with a specific content-type * * @param credentials * Hawk credentials of the requestor * @param contentType * the MIME content type * @param body * the body * @return the MAC * @throws DataError * if there is an issue with the data that prevents creation of the * MAC */ public static String calculateBodyMac(final HawkCredentials credentials, final String contentType, final String body) { // Check that required parameters are present checkNotNull(contentType, "Content type is required but not supplied"); checkNotNull(body, "Body is required but not supplied"); final StringBuilder sb = new StringBuilder(1024); sb.append("hawk."); sb.append(HAWKVERSION); sb.append(".payload\n"); if (contentType.indexOf(';') != -1) { sb.append(contentType.substring(0, contentType.indexOf(';')).toLowerCase(Locale.ENGLISH)); } else { sb.append(contentType.toLowerCase(Locale.ENGLISH)); } sb.append('\n'); sb.append(body); sb.append('\n'); return calculateMac(credentials, sb.toString()); } /** * Internal method to generate the MAC given the compiled string to sign * * @param credentials * Hawk credentials of the requestor * @param text * the compiled string * @return the MAC * @throws DataError * if there is an issue with the data that prevents creation of the * MAC */ public static String calculateMac(final HawkCredentials credentials, final String text) { try { Mac mac = Mac.getInstance(credentials.getJavaAlgorithm()); try { mac.init(new SecretKeySpec(credentials.getKey().getBytes("UTF-8"), credentials.getJavaAlgorithm())); return BaseEncoding.base64().encode(mac.doFinal(text.getBytes("UTF-8"))); } catch (UnsupportedEncodingException uee) { throw new ServerError("Unable to encode with UTF-8", uee); } catch (InvalidKeyException e) { throw new DataError.Bad("Invalid key", e); } } catch (NoSuchAlgorithmException nsae) { throw new DataError.Bad("Unknown encryption algorithm", nsae); } } /** * Calculate and return a bewit. The bewit is used to allow access to a resource * when passed to a suitable Hawk server. * * @param credentials * Hawk credentials of the requestor * @param uri * URI of the request, including query parameters if appropriate * @param ttl * the time to live for the bewit, in seconds * @param ext * optional extra data, as supplied by the requestor to differentiate * the request if required * @return the MAC * @throws DataError * if there is an issue with the data that prevents creation of the * MAC */ public static String generateBewit(final HawkCredentials credentials, final URI uri, final Long ttl, final String ext) { checkNotNull(credentials, "Credentials are required but not supplied"); checkNotNull(uri, "URI is required but not supplied"); checkNotNull(ttl, "TTL is required but not supplied"); checkState((ttl > 0), "TTL must be a positive value"); // Calculate expiry from ttl and current time Long expiry = System.currentTimeMillis() / MILLISECONDS_IN_SECONDS + ttl; final String mac = Hawk.calculateMAC(credentials, Hawk.AuthType.BEWIT, expiry, uri, null, null, null, ext, null, null); final StringBuffer sb = new StringBuffer(256); sb.append(credentials.getKeyId()); sb.append('\\'); sb.append(String.valueOf(expiry)); sb.append('\\'); sb.append(mac); sb.append('\\'); if (ext != null) { sb.append(ext); } return BaseEncoding.base64().encode(sb.toString().getBytes()); } public enum AuthType { /** * Authentication via an Authentication HTTP header */ HEADER, /** * Authentication via a bewit query parameter */ BEWIT; @Override @JsonValue public String toString() { return super.toString().toLowerCase(Locale.ENGLISH); } @JsonCreator public static AuthType parse(final String authType) { try { return valueOf(authType.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException iae) { // N.B. we don't pass the iae as the cause of this exception because // this happens during invocation, and in that case the enum handler // will report the root cause exception rather than the one we throw. throw new DataError.Bad("Hawk authentication type \"" + authType + "\" is invalid"); } } } public enum PayloadValidation { /** * Never validate the payload regardless of if there is a payload hash present */ NEVER, /** * Validate if there is a payload hash present, continue if not */ IFPRESENT, /** * Validate if there is a payload hash present, fail if not */ MANDATORY; @Override @JsonValue public String toString() { return super.toString().toLowerCase(Locale.ENGLISH).replaceAll("_", "-"); } @JsonCreator public static PayloadValidation parse(final String payloadValidation) { try { return valueOf(payloadValidation.toUpperCase(Locale.ENGLISH).replaceAll("-", "_")); } catch (IllegalArgumentException iae) { // N.B. we don't pass the iae as the cause of this exception because // this happens during invocation, and in that case the enum handler // will report the root cause exception rather than the one we throw. throw new DataError.Bad("Hawk algorithm \"" + payloadValidation + "\" is invalid"); } } } } <|start_filename|>hawk-client-jersey/src/test/java/test/com/wealdtech/hawk/jersey/TestHawkClient.java<|end_filename|> /* * Copyright 2012 - 2014 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.jersey; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.wealdtech.hawk.HawkClient; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.hawk.jersey.HawkAuthorizationFilter; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import javax.ws.rs.core.MediaType; import static org.testng.Assert.fail; public class TestHawkClient { private transient Client client; private transient HawkClient hawkClient; private static transient final String URL = "http://localhost:8080/helloworld"; @BeforeClass public void setUp() throws Exception { final HawkCredentials hawkCredentials = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.hawkClient = new HawkClient.Builder().credentials(hawkCredentials).build(); final ClientConfig clientconfig = new DefaultClientConfig(); this.client = Client.create(clientconfig); this.client.addFilter(new HawkAuthorizationFilter(this.hawkClient)); } @Test public void testBasic() { final WebResource resource = this.client.resource(URL); try { final String result = resource.accept(MediaType.TEXT_PLAIN).get(String.class); System.out.println("Result is " + result); } catch (UniformInterfaceException uie) { fail(uie.getResponse().getStatusInfo().getReasonPhrase()); } } } <|start_filename|>hawk-core/src/test/java/test/com/wealdtech/hawk/HawkClientTest.java<|end_filename|> /* * Copyright 2012 - 2014 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk; import com.wealdtech.DataError; import com.wealdtech.configuration.ConfigurationSource; import com.wealdtech.hawk.Hawk.PayloadValidation; import com.wealdtech.hawk.HawkClient; import com.wealdtech.hawk.HawkClientConfiguration; import com.wealdtech.hawk.HawkCredentials; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.HttpURLConnection; import java.net.URI; import static org.testng.Assert.*; public class HawkClientTest { private SimpleHttpServer server; private HawkCredentials testCredentials1, testCredentials2; private URI validUri1; // Helper private HttpURLConnection connect(final URI uri, final String authorizationHeader) throws Exception { final HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", authorizationHeader); connection.setDoOutput(true); connection.connect(); return connection; } @BeforeClass public void setUp() throws Exception { this.testCredentials1 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.server = new SimpleHttpServer(this.testCredentials1, null); this.testCredentials2 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.validUri1 = new URI("http://localhost:18234/testpath/subpath?param1=val1&param2=val2"); } @AfterClass public void tearDown() throws Exception { this.server.stop(); } @Test public void testModel() throws Exception { final HawkClient testClient = new HawkClient.Builder().credentials(this.testCredentials1).build(); testClient.toString(); testClient.hashCode(); assertEquals(testClient, testClient); assertNotEquals(testClient, null); assertNotEquals(null, testClient); final HawkClient testClient2 = new HawkClient.Builder(testClient).credentials(this.testCredentials2).build(); testClient2.toString(); testClient2.hashCode(); assertEquals(testClient2, testClient2); assertNotEquals(testClient2, testClient); } @Test public void testValidRequest() throws Exception { final HawkClient testClient = new HawkClient.Builder().credentials(this.testCredentials1).build(); final String authorizationHeader = testClient.generateAuthorizationHeader(this.validUri1, "get", null, null, null, null); final HttpURLConnection connection = connect(this.validUri1, authorizationHeader); assertEquals(connection.getResponseCode(), 200); } @Test public void testBlankExt() throws Exception { // Test with blank EXT data final HawkClient testClient = new HawkClient.Builder().credentials(this.testCredentials1).build(); final String authorizationHeader = testClient.generateAuthorizationHeader(this.validUri1, "get", null, "", null, null); final HttpURLConnection connection = connect(this.validUri1, authorizationHeader); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidExt() throws Exception { // Test with EXT data final HawkClient testClient = new HawkClient.Builder().credentials(this.testCredentials1).build(); final String authorizationHeader = testClient.generateAuthorizationHeader(this.validUri1, "get", null, "some data", null, null); final HttpURLConnection connection = connect(this.validUri1, authorizationHeader); assertEquals(connection.getResponseCode(), 200); } @Test public void testIncorrectMethod() throws Exception { // Mismatch of HTTP method final HawkClient testClient = new HawkClient.Builder().credentials(this.testCredentials1).build(); final String authorizationHeader = testClient.generateAuthorizationHeader(this.validUri1, "post", null, null, null, null); final HttpURLConnection connection = connect(this.validUri1, authorizationHeader); assertEquals(connection.getResponseCode(), 401); } @Test public void testDuplicateNonce() throws Exception { // Attempt repeat requests final HawkClient testClient = new HawkClient.Builder().credentials(this.testCredentials1).build(); final String authorizationHeader = testClient.generateAuthorizationHeader(this.validUri1, "get", null, null, null, null); final HttpURLConnection connection = connect(this.validUri1, authorizationHeader); assertEquals(connection.getResponseCode(), 200); final HttpURLConnection connection2 = connect(this.validUri1, authorizationHeader); assertEquals(connection2.getResponseCode(), 401); } @Test public void testPrefix() throws Exception { // Check client path prefix final HawkClient testClient1 = new HawkClient.Builder().credentials(this.testCredentials1).build(); assertTrue(testClient1.isValidFor("/test/test2")); assertTrue(testClient1.isValidFor(null)); HawkClientConfiguration clientConfiguration = new HawkClientConfiguration.Builder() .pathPrefix("/foo") .build(); final HawkClient testClient2 = new HawkClient.Builder() .credentials(this.testCredentials1) .configuration(clientConfiguration) .build(); assertTrue(testClient2.isValidFor("/foo")); assertFalse(testClient2.isValidFor("/test/test2")); clientConfiguration = new HawkClientConfiguration.Builder(clientConfiguration) .pathPrefix("/test/") .build(); final HawkClient testClient3 = new HawkClient.Builder() .credentials(this.testCredentials1) .configuration(clientConfiguration) .build(); assertTrue(testClient3.isValidFor("/test/test2")); assertFalse(testClient3.isValidFor("/testtest2")); } @Test public void testConfigurationModel() throws Exception { // Test default configuration final HawkClientConfiguration configuration1 = new HawkClientConfiguration(); assertNotNull(configuration1); configuration1.toString(); configuration1.hashCode(); assertEquals(configuration1, configuration1); assertNotEquals(null, configuration1); assertNotEquals(configuration1, null); // Test non-default configuration final HawkClientConfiguration configuration2 = new HawkClientConfiguration.Builder(configuration1) .payloadValidation(PayloadValidation.MANDATORY) .pathPrefix("/test") .build(); assertNotNull(configuration2); configuration2.toString(); configuration2.hashCode(); assertEquals(configuration2, configuration2); assertNotEquals(null, configuration2); assertNotEquals(configuration2, null); assertNotEquals(configuration2, configuration1); } @Test public void testConfiguration() throws Exception { // Test obtaining the configuration from a valid configuration source final HawkClientConfiguration configuration = new ConfigurationSource<HawkClientConfiguration>().getConfiguration("clientconfig-test1.json", HawkClientConfiguration.class); assertNotNull(configuration); configuration.toString(); configuration.hashCode(); assertEquals(configuration, configuration); assertNotEquals(null, configuration); assertNotEquals(configuration, null); } @Test public void testInvalidConfiguration1() throws Exception { // Test obtaining the configuration with an invalid path prefix try { new ConfigurationSource<HawkClientConfiguration>().getConfiguration("clientconfig-test2.json", HawkClientConfiguration.class); fail("Obtained invalid client configuration"); } catch (DataError de) { // Good } } @Test public void testInvalidConfiguration2() throws Exception { // Test obtaining the configuration with an invalid payload validation try { new ConfigurationSource<HawkClientConfiguration>().getConfiguration("clientconfig-test3.json", HawkClientConfiguration.class); fail("Obtained invalid client configuration"); } catch (DataError de) { // Good } } } <|start_filename|>hawk-core/src/main/java/com/wealdtech/hawk/HawkServerConfiguration.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; import com.google.inject.Inject; import com.wealdtech.hawk.Hawk.PayloadValidation; import static com.wealdtech.Preconditions.*; /** * Configuration for a Hawk server. The Hawk server has a number of * configuration parameters. These are as follows: * <ul> * <li>ntpServer: the name of an NTP server to send to the client in the case of * a bad request. Defaults to <code>pool.ntp.org</code></li> * <li>timestampSkew: the maximum difference between client and server * timestamps, in seconds, for a request to be considered valid. Defaults to <code>60</code></li> * <li>bewitAllowed: if authentication of URLs using bewits is allowed. Defaults to <code>true</code></li> * <li>payloadValidation: how to handle payload validation. Defaults to <code>IFPRESENT</code></li> * <li>nonceCacheSize: the maximum number of nonces to hold in cache. Defaults to <code>10000</code></li> * </ul> * This is configured as a standard Jackson object and can be realized as part * of a ConfigurationSource. */ public final class HawkServerConfiguration implements Comparable<HawkServerConfiguration> { private long timestampSkew = 60L; private boolean bewitAllowed = true; private PayloadValidation payloadValidation = PayloadValidation.IFPRESENT; private long nonceCacheSize = 10000L; /** * Inject a default configuration if none supplied elsewhere */ @Inject private HawkServerConfiguration() { this(null, null, null, null); } /** * Create a configuration with specified values for all options. * Used by builders and ConfigurationSource. * * @param timestampSkew * the maximum number of seconds of skew to allow between client and * server, or <code>null</code> for the default * @param bewitAllowed * whether or not to allow bewits, or <code>null</code> for the default * @param payloadValidation * how to validate against payloads, or <code>null</code> for the default * @param nonceCacheSize * the maximum number of nonces to hold in cache, or <code>null</code> for the default */ @JsonCreator private HawkServerConfiguration(@JsonProperty("timestampskew") final Long timestampSkew, @JsonProperty("bewitallowed") final Boolean bewitAllowed, @JsonProperty("payloadvalidation") final PayloadValidation payloadValidation, @JsonProperty("noncecachesize") final Long nonceCacheSize) { if (timestampSkew != null) { this.timestampSkew = timestampSkew; } if (bewitAllowed != null) { this.bewitAllowed = bewitAllowed; } if (payloadValidation != null) { this.payloadValidation = payloadValidation; } if (nonceCacheSize != null) { this.nonceCacheSize = nonceCacheSize; } validate(); } private void validate() { checkNotNull(this.timestampSkew, "The timestamp skew is required"); checkArgument((this.timestampSkew >= 0), "The timestamp may not be negative"); checkNotNull(this.bewitAllowed, "Allowance of bewits is required"); checkNotNull(this.payloadValidation, "Payload validation setting is required"); checkNotNull(this.nonceCacheSize, "The nonce cache size is required"); checkArgument((this.nonceCacheSize >= 0), "The nonce cache size may not be negative"); } public Long getTimestampSkew() { return this.timestampSkew; } public Boolean isBewitAllowed() { return this.bewitAllowed; } public PayloadValidation getPayloadValidation() { return this.payloadValidation; } public Long getNonceCacheSize() { return this.nonceCacheSize; } // Standard object methods follow @Override public String toString() { return Objects.toStringHelper(this) .add("timestampSkew", this.getTimestampSkew()) .add("bewitAllowed", this.isBewitAllowed()) .add("payloadValidation", this.getPayloadValidation()) .add("nonceCacheSize", this.getNonceCacheSize()) .toString(); } @Override public boolean equals(final Object that) { return (that instanceof HawkServerConfiguration) && (this.compareTo((HawkServerConfiguration)that) == 0); } @Override public int hashCode() { return Objects.hashCode(this.getTimestampSkew(), this.isBewitAllowed(), this.getPayloadValidation(), this.getNonceCacheSize()); } @Override public int compareTo(final HawkServerConfiguration that) { return ComparisonChain.start() .compare(this.getTimestampSkew(), that.getTimestampSkew()) .compare(this.isBewitAllowed(), that.isBewitAllowed()) .compare(this.getPayloadValidation(), that.getPayloadValidation()) .compare(this.getNonceCacheSize(), that.getNonceCacheSize()) .result(); } public static class Builder { private Long timestampSkew; private Boolean bewitAllowed; private PayloadValidation payloadValidation; private Long nonceCacheSize; /** * Generate a new builder. */ public Builder() { } /** * Generate build with all values set from a prior object. * @param prior the prior object */ public Builder(final HawkServerConfiguration prior) { this.timestampSkew = prior.timestampSkew; this.bewitAllowed = prior.bewitAllowed; this.payloadValidation = prior.payloadValidation; this.nonceCacheSize = prior.nonceCacheSize; } /** * Override the existing timestamp skew. * @param timestampSkew the new timestamp skew * @return The builder */ public Builder timestampSkew(final Long timestampSkew) { this.timestampSkew = timestampSkew; return this; } /** * Override the existing allowance of bewits. * @param bewitAllowed if bewits are allowed * @return The builder */ public Builder bewitAllowed(final Boolean bewitAllowed) { this.bewitAllowed = bewitAllowed; return this; } /** * Override the existing handling of payload validation. * @param payloadValidation * @return The builder */ public Builder payloadValidation(final PayloadValidation payloadValidation) { this.payloadValidation = payloadValidation; return this; } /** * Override the existing nonce cache size. * @param nonceCacheSize the new nonce cache size * @return The builder */ public Builder nonceCacheSize(final Long nonceCacheSize) { this.nonceCacheSize = nonceCacheSize; return this; } /** * Create a new Hawk server configuration from the defaults * and overrides provided. * @return The Hawk server configuration * @throws com.wealdtech.DataError If the data provided is invalid for a Hawk server configuration */ public HawkServerConfiguration build() { return new HawkServerConfiguration(this.timestampSkew, this.bewitAllowed, this.payloadValidation, this.nonceCacheSize); } } } <|start_filename|>hawk-core/src/main/java/com/wealdtech/hawk/HawkServer.java<|end_filename|> /* * Copyright 2012 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk; import static com.wealdtech.Preconditions.*; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Objects; import com.google.common.base.Splitter; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.BaseEncoding; import com.google.inject.Inject; import com.wealdtech.DataError; import com.wealdtech.ServerError; import com.wealdtech.hawk.Hawk.PayloadValidation; /** * The Hawk server. Note that this is not an HTTP server in itself, but provides * the backbone of any Hawk implementation within an HTTP server. */ public final class HawkServer implements Comparable<HawkServer> { private static final Splitter WHITESPACESPLITTER = Splitter.onPattern("\\s+").limit(2); private static final Pattern FIELDPATTERN = Pattern.compile("([^=]*)\\s*=\\s*\"([^\"]*)[,\"\\s]*"); private static final Pattern BEWITPATTERN = Pattern.compile("bewit=([^&]*)"); private static final Splitter BEWITSPLITTER = Splitter.on('\\'); private static final String BEWITREMOVEALMATCH = "bewit=[^&]*"; private static final String HEADER_MAC = "mac"; private static final String HEADER_TS = "ts"; private static final String HEADER_NONCE = "nonce"; private static final String HEADER_ID = "id"; private static final String HEADER_EXPIRY = "expiry"; private static final String HEADER_EXT = "ext"; private static final String HEADER_APP = "app"; private static final String HEADER_DLG = "dlg"; private static final int BEWIT_FIELDS = 4; private static final int BEWIT_FIELD_ID = 0; private static final int BEWIT_FIELD_EXPIRY = 1; private static final int BEWIT_FIELD_MAC = 2; private static final int BEWIT_FIELD_EXT = 3; private final HawkServerConfiguration configuration; private LoadingCache<String, Boolean> nonces; /** * Create an instance of the Hawk server with custom configuration. * * @param configuration * the specific configuration */ @Inject private HawkServer(final HawkServerConfiguration configuration) { if (configuration == null) { this.configuration = new HawkServerConfiguration.Builder().build(); } else { this.configuration = configuration; } initializeCache(); } private void initializeCache() { this.nonces = CacheBuilder.newBuilder() .expireAfterWrite(this.configuration.getTimestampSkew() * 2, TimeUnit.SECONDS) .maximumSize(this.configuration.getNonceCacheSize()) .build(new CacheLoader<String, Boolean>() { @Override public Boolean load(String key) { return false; } }); } /** * Authenticate a request using Hawk. * @param credentials the Hawk credentials against which to authenticate * @param uri the URI of the request * @param method the method of the request * @param authorizationHeaders the Hawk authentication headers * @param hash the hash of the body, if available * @param hasBody <code>true</code> if the request has a body, <code>false</code> if not */ public void authenticate(final HawkCredentials credentials, final URI uri, final String method, final ImmutableMap<String, String> authorizationHeaders, final String hash, final boolean hasBody) { // Ensure that the required fields are present checkNotNull(authorizationHeaders.get(HEADER_TS), "The timestamp was not supplied"); checkNotNull(authorizationHeaders.get(HEADER_NONCE), "The nonce was not supplied"); checkNotNull(authorizationHeaders.get(HEADER_ID), "The id was not supplied"); checkNotNull(authorizationHeaders.get(HEADER_MAC), "The mac was not supplied"); if ((this.configuration.getPayloadValidation().equals(PayloadValidation.MANDATORY)) && (hasBody)) { checkNotNull(authorizationHeaders.get("hash"), "The payload hash was not supplied"); checkNotNull(hash, "The payload hash could not be calculated"); } // Ensure that the timestamp passed in is within suitable bounds confirmTimestampWithinBounds(authorizationHeaders.get(HEADER_TS)); // Ensure that this is not a replay of a previous request confirmUniqueNonce(authorizationHeaders.get(HEADER_NONCE) + authorizationHeaders.get(HEADER_TS) + authorizationHeaders.get(HEADER_ID)); // Ensure that the MAC is correct final String mac = Hawk.calculateMAC(credentials, Hawk.AuthType.HEADER, Long.valueOf(authorizationHeaders.get(HEADER_TS)), uri, authorizationHeaders.get(HEADER_NONCE), method, hash, authorizationHeaders.get(HEADER_EXT), authorizationHeaders.get(HEADER_APP), authorizationHeaders.get(HEADER_DLG)); if (!timeConstantEquals(mac, authorizationHeaders.get(HEADER_MAC))) { throw new DataError.Authentication("The MAC in the request does not match the server-calculated MAC"); } } /** * Authenticate a request using a Hawk bewit. * @param credentials the Hawk credentials against which to authenticate * @param uri the URI of the request */ public void authenticate(final HawkCredentials credentials, final URI uri) { final String bewit = extractBewit(uri); final ImmutableMap<String, String> bewitFields = splitBewit(bewit); checkNotNull(bewitFields.get(HEADER_ID), "ID missing from bewit"); checkNotNull(bewitFields.get(HEADER_EXPIRY), "Expiry missing from bewit"); checkNotNull(bewitFields.get(HEADER_MAC), "MAC missing from bewit"); checkState((credentials.getKeyId().equals(bewitFields.get(HEADER_ID))), "The id in the bewit is not recognised"); final Long expiry = Long.parseLong(bewitFields.get(HEADER_EXPIRY)); final URI strippedUri = stripBewit(uri); final String calculatedMac = Hawk.calculateMAC(credentials, Hawk.AuthType.BEWIT, expiry, strippedUri, null, null, null, bewitFields.get(HEADER_EXT), null, null); if (!timeConstantEquals(calculatedMac, bewitFields.get(HEADER_MAC))) { throw new DataError.Authentication("The MAC in the request does not match the server-calculated MAC"); } } // Strip the bewit query parameter from a URI private URI stripBewit(final URI uri) { String uristr = uri.toString().replaceAll(BEWITREMOVEALMATCH, ""); // If the bewit was the first parameter... uristr = uristr.replaceAll("\\?&", "?"); // If the bewit was the only parameter... uristr = uristr.replaceAll("\\?$", ""); // If the bewit was a middle parameter... uristr = uristr.replaceAll("&&", "&"); // If the bewit was the last parameter... uristr = uristr.replaceAll("&$", ""); try { return new URI(uristr); } catch (URISyntaxException use) { throw new ServerError("Failed to remove bewit from query string", use); } } // Confirm that the request nonce has not already been seen within the allowable time period private void confirmUniqueNonce(final String nonce) { checkState(!this.nonces.getUnchecked(nonce), "The nonce supplied is the same as one seen previously"); this.nonces.put(nonce, true); } // Confirm that the request timestamp is within an acceptable range of current time private void confirmTimestampWithinBounds(final String ts) { Long timestamp; try { timestamp = Long.valueOf(ts); } catch (Exception e) { throw new DataError.Bad("The timestamp is in the wrong format; we expect seconds since the epoch", e); } long now = System.currentTimeMillis() / Hawk.MILLISECONDS_IN_SECONDS; checkState((Math.abs(now - timestamp) <= configuration.getTimestampSkew()), "The timestamp is too far from the current time to be acceptable"); } /** * Generate text for a WWW-Authenticate header after a failed authentication. * <p> * Note that this generates the header's contents, and not the header itself. * * @return text suitable for placement in a WWW-Authenticate header */ public String generateAuthenticateHeader() { long curTime = System.currentTimeMillis() / Hawk.MILLISECONDS_IN_SECONDS; StringBuilder sb = new StringBuilder(64); sb.append("Hawk ts=\""); sb.append(String.valueOf(curTime)); sb.append("\" tsm=\""); sb.append(Hawk.calculateTSMac(curTime)); sb.append('"'); return sb.toString(); } // Avoid any weakness through fast-path comparison of strings private static boolean timeConstantEquals(final String first, final String second) { if ((first == null) || (second == null)) { // null always returns false return false; } if (first.length() != second.length()) { return false; } int res = 0; int l = first.length(); for (int i = 0; i < l; i++) { if (first.charAt(i) != second.charAt(i)) { res++; } } return (res == 0); } /* * Split an authorization header into individual fields. * @param authorizationheader the Hawk authorization header * @return A map of authorization parameters * @throws DataError If the authorization header is invalid in some way */ public ImmutableMap<String, String> splitAuthorizationHeader(final String authorizationheader) { checkNotNull(authorizationheader, "No authorization header"); List<String> headerfields = Lists.newArrayList(WHITESPACESPLITTER.split(authorizationheader)); checkState((headerfields.size() == 2), "The authorization header does not contain the expected number of fields"); checkState(("hawk".equals(headerfields.get(0).toLowerCase(Locale.ENGLISH))), "The authorization header is not a Hawk authorization header"); Map<String, String> fields = new HashMap<>(); Matcher m = FIELDPATTERN.matcher(headerfields.get(1)); while (m.find()) { String key = m.group(1); String value = m.group(2); fields.put(key, value); } return ImmutableMap.copyOf(fields); } /** * Split a base64-encoded bewit into individual fields. * @param bewit the base64-encoded bewit * @return A map of bewit parameters * @throws DataError If the bewit is invalid in some way */ public ImmutableMap<String, String> splitBewit(final String bewit) { checkNotNull(bewit, "No bewit"); final String decodedBewit = new String(BaseEncoding.base64().decode(bewit)); List<String> bewitfields = Lists.newArrayList(BEWITSPLITTER.split(decodedBewit)); checkState((bewitfields.size() == BEWIT_FIELDS), "The bewit did not contain the correct number of values"); long expiry; try { expiry = Long.parseLong(bewitfields.get(1)); } catch (NumberFormatException nfe) { throw new DataError.Bad("Timestamp is invalid", nfe); } checkState((System.currentTimeMillis() / Hawk.MILLISECONDS_IN_SECONDS <= expiry), "The bewit has expired"); Map<String, String> bewitMap = Maps.newHashMap(); bewitMap.put(HEADER_ID, bewitfields.get(BEWIT_FIELD_ID)); bewitMap.put(HEADER_EXPIRY, bewitfields.get(BEWIT_FIELD_EXPIRY)); bewitMap.put(HEADER_MAC, bewitfields.get(BEWIT_FIELD_MAC)); bewitMap.put(HEADER_EXT, bewitfields.get(BEWIT_FIELD_EXT)); return ImmutableMap.copyOf(bewitMap); } /** * Extract a bewit from a URI. * @param uri the URI from which to pull the bewit * @return The bewit * @throws DataError if there is an issue with the data that prevents obtaining the bewit */ public String extractBewit(final URI uri) { checkNotNull(uri, "URI is required but not supplied"); final String uristr = uri.toString(); Matcher m = BEWITPATTERN.matcher(uristr); checkState(m.find(), "The query string did not contain a bewit"); return m.group(1); } // Standard object methods follow @Override public String toString() { return Objects.toStringHelper(this) .add("configuration", this.configuration) .toString(); } @Override public boolean equals(final Object that) { return (that instanceof HawkServer) && (this.compareTo((HawkServer)that) == 0); } @Override public int hashCode() { return Objects.hashCode(this.configuration); } @Override public int compareTo(final HawkServer that) { return ComparisonChain.start() .compare(this.configuration, that.configuration) .result(); } public static class Builder { private HawkServerConfiguration configuration; /** * Generate a new builder. */ public Builder() { } /** * Generate build with all values set from a prior object. * @param prior the prior object */ public Builder(final HawkServer prior) { this.configuration = prior.configuration; } /** * Override the existing configuration. * @param configuration the new configuration * @return The builder */ public Builder configuration(final HawkServerConfiguration configuration) { this.configuration = configuration; return this; } /** * Build the server * @return a new server */ public HawkServer build() { return new HawkServer(this.configuration); } } } <|start_filename|>hawk-core/src/main/java/com/wealdtech/hawk/HawkClientConfiguration.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Ordering; import com.wealdtech.configuration.Configuration; import com.wealdtech.hawk.Hawk.PayloadValidation; import static com.wealdtech.Preconditions.*; /** * Configuration for a Hawk client. The Hawk client has a number of * configuration parameters. These are as follows: * <ul> * <li>pathPrefix: the path prefix for which the client should add authentication. Defaults to <code>null</code> for everything</li> * <li>payloadValidation: if payload validation should take place. Defaults to <code>NEVER</code></li> * </ul> * This is configured as a standard Jackson object and can be realized as part * of a ConfigurationSource. */ public class HawkClientConfiguration implements Configuration, Comparable<HawkClientConfiguration> { private String pathPrefix = null; private PayloadValidation payloadValidation = PayloadValidation.NEVER; /** * Create a client configuration with default values */ public HawkClientConfiguration() { // 0-configuration } /** * Create a configuration with specified values for all options. * Note that this should not be called directly, and the Builder should be * used for instantiation. * * @param pathPrefix * which requests to authenticate, or <code>null</code> for the default * @param payloadValidation * how to validate against payloads, or <code>null</code> for the default */ @JsonCreator private HawkClientConfiguration(@JsonProperty("pathprefix") final String pathPrefix, @JsonProperty("payloadvalidation") final PayloadValidation payloadValidation) { if (pathPrefix != null) { this.pathPrefix = pathPrefix; } if (payloadValidation != null) { this.payloadValidation = payloadValidation; } validate(); } private void validate() { checkNotNull(this.payloadValidation, "Payload validation setting is required"); checkArgument(this.pathPrefix == null || this.pathPrefix.startsWith("/"), "Path prefix must start with \"/\" if present"); } public String getPathPrefix() { return this.pathPrefix; } public PayloadValidation getPayloadValidation() { return this.payloadValidation; } // Standard object methods follow @Override public String toString() { return Objects.toStringHelper(this) .add("pathPrefix", this.getPathPrefix()) .add("payloadValidation", this.getPayloadValidation()) .toString(); } @Override public boolean equals(final Object that) { return (that instanceof HawkClientConfiguration) && (this.compareTo((HawkClientConfiguration)that) == 0); } @Override public int hashCode() { return Objects.hashCode(this.getPathPrefix(), this.getPayloadValidation()); } @Override public int compareTo(final HawkClientConfiguration that) { return ComparisonChain.start() .compare(this.getPathPrefix(), that.getPathPrefix(), Ordering.<String>natural().nullsFirst()) .compare(this.getPayloadValidation(), that.getPayloadValidation()) .result(); } public static class Builder { private String pathPrefix; private PayloadValidation payloadValidation; /** * Generate a new builder. */ public Builder() { } /** * Generate build with all values set from a prior configuration. * @param prior the prior configuration */ public Builder(final HawkClientConfiguration prior) { this.pathPrefix = prior.pathPrefix; this.payloadValidation = prior.payloadValidation; } /** * Override the default path prefix * @param pathPrefix the new path prefix value * @return The builder */ public Builder pathPrefix(final String pathPrefix) { this.pathPrefix = pathPrefix; return this; } /** * Override the default handling of payload validation. * @param payloadValidation the new payload validation value * @return The builder */ public Builder payloadValidation(final PayloadValidation payloadValidation) { this.payloadValidation = payloadValidation; return this; } /** * Create a new Hawk client configuration from the defaults * and overrides provided. * @return The Hawk client configuration * @throws com.wealdtech.DataError If the data provided is invalid for a Hawk client configuration */ public HawkClientConfiguration build() { return new HawkClientConfiguration(this.pathPrefix, this.payloadValidation); } } } <|start_filename|>hawk-core/src/test/java/test/com/wealdtech/hawk/HawkTest.java<|end_filename|> /* * Copyright 2012, 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk; import static org.testng.Assert.*; import java.net.URI; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.wealdtech.DataError; import com.wealdtech.hawk.Hawk; import com.wealdtech.hawk.Hawk.AuthType; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.hawk.HawkCredentials.Algorithm; public class HawkTest { private HawkCredentials testhc1; private URI testuri1, testuri2, testuri3; @BeforeClass public void setUp() throws Exception { this.testhc1 = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.testuri1 = new URI("http://www.example.com/test/path"); this.testuri2 = new URI("https://www.example.com/test/path/two?one=1&two=two"); this.testuri3 = new URI("https://www.example.com/test?param=&lt;&gt;&pound;%54%65%73%74"); } @Test public void testMAC() throws Exception { String testmac1 = Hawk.calculateMAC(this.testhc1, Hawk.AuthType.HEADER, 12345L, this.testuri1, "testnonce", "GET", null, null, null, null); assertEquals(testmac1, "ST9uc4f43RcEx72niTPaj/3nADfjazou/wNODvi/SvM="); } @Test public void testHttpsMAC() throws Exception { String testmac1 = Hawk.calculateMAC(this.testhc1, Hawk.AuthType.HEADER, 54321L, this.testuri2, "testnonce", "POST", null, null, null, null); assertEquals(testmac1, "afBpC1ZwH+s35f/OwKBoPLfrGQsQzEaKLpNM2ZG15Iw="); } @Test public void testExtDataMAC() throws Exception { String testmac1 = Hawk.calculateMAC(this.testhc1, Hawk.AuthType.HEADER, 12345L, this.testuri1, "testnonce", "GET", null, "Extra data", null, null); assertEquals(testmac1, "ucCVBEnEMDICl5efmmgo4MnnObG2rStZq6a1o8yHPD8="); } @Test public void testOzMAC() throws Exception { String testmac1 = Hawk.calculateMAC(this.testhc1, Hawk.AuthType.HEADER, 12345L, this.testuri1, "testnonce", "GET", null, "Extra data", "12345", "54321"); assertEquals(testmac1, "bH7bZlofGKZUW6oNLF8scxXfCwYiNmijELwGJPGI3Gs="); } @Test public void testRaw() throws Exception { String testmac1 = Hawk.calculateMAC(this.testhc1, Hawk.AuthType.HEADER, 12345L, this.testuri3, "testnonce", "GET", null, null, null, null); assertEquals(testmac1, "sbrKX3RkGZdLarMQEU6fmuBcFSlyVuTsOjBSeoeUp2I="); } @Test public void testCorrectMethod() throws Exception { // Ensure that we are using the right method final HawkCredentials testCredentials = new HawkCredentials.Builder().keyId("test").key("mysecretkey").algorithm(Algorithm.SHA256).build(); String testmac1 = Hawk.calculateMac(testCredentials, "myvalue"); assertEquals(testmac1, "C+QQeDUXTqKSPM4ZibEgFlPsXhJcSdU2sT48/fbeJtk="); } @Test public void testBodyMac() throws Exception { // Ensure that the body MAC gives the correct result final HawkCredentials testCredentials = new HawkCredentials.Builder().keyId("test").key("mysecretkey").algorithm(Algorithm.SHA256).build(); final String contentType = "text/plain; charset=utf-8"; String testmac1 = Hawk.calculateBodyMac(testCredentials, contentType, "Text body"); assertEquals(testmac1, "w1rO8cxeoTwVmO1Weffal3VCYHBTcIxpjgQUZx01mRU="); } @Test public void testBewitValidation1() throws Exception { try { Hawk.generateBewit(this.testhc1, this.testuri1, -1L, null); fail("Bewit generated with negative TTL"); } catch (DataError de) { // Good } } @Test public void testBewitValidation2() throws Exception { Hawk.generateBewit(this.testhc1, this.testuri1, 240L, "extdata"); } @Test public void testBadScheme() throws Exception { URI invalidSchemeUri= new URI("ftp://www.example.com/file"); try { Hawk.calculateMAC(this.testhc1, Hawk.AuthType.HEADER, 12345L, invalidSchemeUri, "testnonce", "GET", null, null, null, null); fail("MAC calculated with invalid scheme"); } catch (DataError de) { // Good } } @Test public void testValidAuthType() throws Exception { AuthType.parse("header"); } @Test public void testInvalidAuthType() throws Exception { try { AuthType.parse("invalid"); fail("AuthType accepted invalid value"); } catch (DataError de) { // Good } } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/jersey/guice/HawkServletModule.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.jersey.guice; import java.util.HashMap; import java.util.List; import java.util.Map; import test.com.wealdtech.hawk.jersey.HawkExampleUserAuthenticationFilter; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.ObjectArrays; import com.google.inject.servlet.ServletModule; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import com.wealdtech.hawk.jersey.HawkUnauthorizedFilter; import com.wealdtech.jersey.filters.BodyPrefetchFilter; import com.wealdtech.jersey.filters.ServerHeaderFilter; /** * A Guice module to configure a Jetty server with servlets */ public class HawkServletModule extends ServletModule { private String packages; /** * Create a Jersey servlet module with a list of packages to * check for resources and the like. * @param packages a list of packages */ public HawkServletModule(final String... packages) { super(); setPackages(packages); } @Override protected void configureServlets() { final Map<String, String> params = new HashMap<String, String>(); params.put(PackagesResourceConfig.PROPERTY_PACKAGES, this.packages); // Add the authentication filter to requests and the unauthorized filter to responses final String requestFilters = joinClassNames(BodyPrefetchFilter.class, HawkExampleUserAuthenticationFilter.class); final String responseFilters = joinClassNames(HawkUnauthorizedFilter.class, ServerHeaderFilter.class); params.put(PackagesResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, requestFilters); params.put(PackagesResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, responseFilters); serve("/*").with(GuiceContainer.class, params); } /** * Set the list of packages that we will search for providers and the like * @param additionalPackages The packages above and beyond our standard list */ private void setPackages(final String... additionalPackages) { String[] packagesList = ObjectArrays.concat("com.wealdtech.jersey", additionalPackages); packagesList = ObjectArrays.concat("com.yammer.metrics", packagesList); this.packages = Joiner.on(',').skipNulls().join(packagesList); } /** * Convert a varargs of clases in to a comma-separated string of class names */ private String joinClassNames(final Class<?>... clazz) { Function<Class<?>, String> classToName = new Function<Class<?>, String>() { @Override public String apply(Class<?> klazz) { return klazz.getName(); } }; List<String> names = Lists.transform(Lists.newArrayList(clazz), classToName); return Joiner.on(',').skipNulls().join(names); } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/HawkJerseyServerTest.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk; import static org.testng.Assert.*; import java.net.HttpURLConnection; import java.net.URI; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import test.com.wealdtech.hawk.config.ApplicationModule; import test.com.wealdtech.hawk.jersey.guice.HawkConfigurationModule; import test.com.wealdtech.hawk.jersey.guice.HawkServletModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.wealdtech.hawk.Hawk; import com.wealdtech.hawk.Hawk.PayloadValidation; import com.wealdtech.hawk.HawkClient; import com.wealdtech.hawk.HawkClientConfiguration; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.jetty.JettyServer; public class HawkJerseyServerTest { private HawkCredentials goodCredentials; private URI validuri1, validuri2; private JettyServer webserver; // Helper private HttpURLConnection connect(final URI uri, final String method, final String authorizationHeader, String contentType, final String body) throws Exception { final HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); connection.setRequestMethod(method); if (authorizationHeader != null) { connection.setRequestProperty("Authorization", authorizationHeader); } if (body != null) { connection.setRequestProperty("Content-Type", contentType); connection.setDoOutput(true); } connection.setDoInput(true); connection.connect(); if (body != null) { connection.getOutputStream().write(body.getBytes()); } return connection; } @BeforeClass public void setUp() throws Exception { this.goodCredentials = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); this.validuri1 = new URI("http://localhost:8080/helloworld"); this.validuri2 = new URI("http://localhost:8080/helloworld?one=one&two=two"); // Create an injector with our basic configuration final Injector injector = Guice.createInjector(new ApplicationModule(), new HawkConfigurationModule(), new HawkServletModule("test.com.wealdtech.hawk.providers", "test.com.wealdtech.hawk.resources")); this.webserver = injector.getInstance(JettyServer.class); webserver.start(); } @AfterClass public void tearDown() throws Exception { this.webserver.stop(); } @Test public void testValidAuth() throws Exception { // Test valid authentication with a GET request final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidAuth2() throws Exception { // Test valid authentication with a POST request final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "post", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "POST", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidAuth3() throws Exception { // Test valid authentication with a POST request and body final HawkClientConfiguration configuration = new HawkClientConfiguration.Builder().payloadValidation(PayloadValidation.MANDATORY).build(); final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).configuration(configuration).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "post", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "POST", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidAuth4() throws Exception { // Test valid authentication with body hash final HawkClientConfiguration configuration = new HawkClientConfiguration.Builder().payloadValidation(PayloadValidation.MANDATORY).build(); final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).configuration(configuration).build(); final String body = "Test body"; final String hash = Hawk.calculateBodyMac(this.goodCredentials, "text/plain", body); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "post", hash, null, null, null); HttpURLConnection connection = connect(this.validuri1, "POST", authorizationHeader, "Text/Plain", body); assertEquals(connection.getResponseCode(), 200); } @Test public void testReplayProtection() throws Exception { // Test catching a replay of an older request final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 200); connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testSkewProtection() throws Exception { // Test catching an anachronistic request final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); Thread.sleep(61000L); HttpURLConnection connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testFailedAuth() throws Exception { // Test failed auth due to bad MAC final HawkCredentials badCredentials = new HawkCredentials.Builder(this.goodCredentials) .key("bad") .build(); final HawkClient testclient = new HawkClient.Builder().credentials(badCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testInvalidAuth1() throws Exception { // Test authentication with unknown key ID final HawkCredentials badCredentials = new HawkCredentials.Builder(this.goodCredentials) .keyId("unknown") .build(); final HawkClient testclient = new HawkClient.Builder().credentials(badCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testInvalidAuth2() throws Exception { // Test authentication with differing algorithms final HawkCredentials badCredentials = new HawkCredentials.Builder(this.goodCredentials) .algorithm(HawkCredentials.Algorithm.SHA1) .build(); final HawkClient testclient = new HawkClient.Builder().credentials(badCredentials).build(); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "get", null, null, null, null); HttpURLConnection connection = connect(this.validuri1, "GET", authorizationHeader, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testInvalidAuth3() throws Exception { // Test authentication with incorrect body hash final HawkClientConfiguration configuration = new HawkClientConfiguration.Builder().payloadValidation(PayloadValidation.MANDATORY).build(); final HawkClient testclient = new HawkClient.Builder().credentials(this.goodCredentials).configuration(configuration).build(); final String body = "Test body"; final String hash = Hawk.calculateMac(this.goodCredentials, "bad body"); final String authorizationHeader = testclient.generateAuthorizationHeader(this.validuri1, "put", hash, null, null, null); HttpURLConnection connection = connect(this.validuri1, "PUT", authorizationHeader, null, body); assertEquals(connection.getResponseCode(), 401); } @Test public void testValidBewit1() throws Exception { // Test a valid bewit with a simple request final String bewit = Hawk.generateBewit(this.goodCredentials, this.validuri1, 600L, null); URI testUri = new URI(this.validuri1.toString() + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidBewit2() throws Exception { // Test a valid bewit appending to an existing query string final String bewit = Hawk.generateBewit(this.goodCredentials, this.validuri2, 600L, null); URI testUri = new URI(this.validuri2.toString() + "&bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidBewit3() throws Exception { // Test a valid bewit in the middle of a query string final URI validuri = new URI(this.validuri2.toString() + "&three=three"); final String bewit = Hawk.generateBewit(this.goodCredentials, validuri, 600L, null); URI testUri = new URI(this.validuri2.toString() + "&bewit=" + bewit + "&three=three"); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testValidBewit4() throws Exception { // Test a valid bewit with extra data final String bewit = Hawk.generateBewit(this.goodCredentials, this.validuri1, 600L, "extra"); URI testUri = new URI(this.validuri1.toString() + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 200); } @Test public void testInvalidBewit1() throws Exception { // Test an invalid bewit due to using the PUT method final String bewit = Hawk.generateBewit(this.goodCredentials, this.validuri1, 600L, null); URI testUri = new URI(this.validuri1.toString() + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "PUT", null, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testInvalidBewit2() throws Exception { // Test an invalid bewit due to bad bewit final HawkCredentials badCredentials = new HawkCredentials.Builder(this.goodCredentials) .key("bad") .build(); final String bewit = Hawk.generateBewit(badCredentials, this.validuri1, 600L, null); URI testUri = new URI(this.validuri1.toString() + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testInvalidBewit3() throws Exception { // Test an invalid bewit due to expiry final String bewit = Hawk.generateBewit(this.goodCredentials, this.validuri1, 1L, null); Thread.sleep(2000L); URI testUri = new URI(this.validuri1.toString() + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 401); } @Test public void testInvalidBewit4() throws Exception { // Test a valid bewit that doesn't exist on the server final HawkCredentials otherCredentials = new HawkCredentials.Builder(this.goodCredentials).keyId("someoneelse").build(); final String bewit = Hawk.generateBewit(otherCredentials, this.validuri1, 600L, null); URI testUri = new URI(this.validuri1.toString() + "?bewit=" + bewit); final HttpURLConnection connection = connect(testUri, "GET", null, null, null); assertEquals(connection.getResponseCode(), 401); } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/model/ExampleUser.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.model; import java.util.List; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.hawk.jersey.HawkCredentialsProvider; /** * A simple example user class for testing Hawk. * <p>This class implements <code>HawkCredentialsProvider</code>, * which allows us to use it in authenticators. */ public class ExampleUser implements HawkCredentialsProvider { private final String name; private final List<HawkCredentials> hawkCredentials; public ExampleUser(final String name, final List<HawkCredentials> hawkCredentials) { this.name = name; this.hawkCredentials = hawkCredentials; } public String getName() { return this.name; } @Override public HawkCredentials getHawkCredentials(final String keyId) { for (HawkCredentials credentials : this.hawkCredentials) { if (credentials.getKeyId().equals(keyId)) { return credentials; } } return null; } } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/jersey/HawkExampleUserAuthenticationFilter.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.jersey; import test.com.wealdtech.hawk.model.ExampleUser; import com.google.inject.Inject; import com.wealdtech.hawk.jersey.HawkAuthenticationFilter; import com.wealdtech.jersey.auth.Authenticator; /** * A filter to intercept all incoming requests and authenticate them using Hawk. */ public class HawkExampleUserAuthenticationFilter extends HawkAuthenticationFilter<ExampleUser> { /** * Set up the filter with a suitable authenticator * @param authenticator An authenticator */ @Inject public HawkExampleUserAuthenticationFilter(final Authenticator<ExampleUser> authenticator) { super(authenticator); } } <|start_filename|>hawk-server-jersey/src/main/java/com/wealdtech/hawk/jersey/HawkUnauthorizedFilter.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk.jersey; import javax.ws.rs.core.Response.Status; import com.google.inject.Inject; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; import com.wealdtech.hawk.HawkServer; /** * Response filter providing a WWW-Authenticate header * for unauthorized requests with the server's current * time as well as an NTP server for time synchronization, * as per the Hawk specification. */ public class HawkUnauthorizedFilter implements ContainerResponseFilter { private final transient HawkServer server; @Inject public HawkUnauthorizedFilter(final HawkServer server) { this.server = server; } @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { if (response.getStatus() == Status.UNAUTHORIZED.getStatusCode()) { response.getHttpHeaders().add("WWW-Authenticate", this.server.generateAuthenticateHeader()); } return response; } } <|start_filename|>hawk-core/src/test/java/test/com/wealdtech/hawk/SimpleHttpServer.java<|end_filename|> /* * Copyright 2012 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import com.google.common.collect.ImmutableMap; import com.google.common.io.CharStreams; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import com.wealdtech.DataError; import com.wealdtech.ServerError; import com.wealdtech.hawk.Hawk; import com.wealdtech.hawk.HawkCredentials; import com.wealdtech.hawk.HawkServer; import com.wealdtech.hawk.HawkServerConfiguration; /** * Simple HTTP server that does nothing other than check the Hawk authentication * parameters and return any empty response with appropriate response code. */ public class SimpleHttpServer { private final HttpServer server; public SimpleHttpServer(final HawkCredentials credentials, final HawkServerConfiguration configuration) throws Exception { InetSocketAddress addr = new InetSocketAddress(18234); this.server = HttpServer.create(addr, 0); this.server.createContext("/", new AuthenticateHandler(credentials, configuration)); this.server.setExecutor(Executors.newCachedThreadPool()); this.server.start(); } public void stop() { this.server.stop(0); } // A handler that does nothing other than authentication private class AuthenticateHandler implements HttpHandler { private transient final HawkServer server; private transient final HawkCredentials credentials; public AuthenticateHandler(final HawkCredentials credentials, final HawkServerConfiguration configuration) { this.credentials = credentials; this.server = new HawkServer.Builder().configuration(configuration).build(); } @Override public void handle(final HttpExchange exchange) throws IOException { if (exchange.getRequestURI().toString().contains("bewit=")) { handleAuthenticationBewit(exchange); } else { handleAuthenticationHeader(exchange); } } private void handleAuthenticationBewit(final HttpExchange exchange) throws IOException { if (!exchange.getRequestMethod().equals("GET")) { System.out.println("Not authenticated: HTTP method " + exchange.getRequestMethod() + " not supported with bewit"); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(401, 0); } URI uri = null; try { uri = new URI(exchange.getRequestURI().getScheme() + "://" + exchange.getRequestHeaders().getFirst("Host") + exchange.getRequestURI()); } catch (URISyntaxException use) { System.out.println("Not authenticated: " + use.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(401, 0); } try { server.authenticate(this.credentials, uri); System.out.println("Authenticated by bewit"); exchange.sendResponseHeaders(200, 0); } catch (DataError de) { System.out.println("Not authenticated: " + de.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(401, 0); } catch (ServerError se) { System.out.println("Not authenticated: " + se.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(500, 0); } } private void handleAuthenticationHeader(final HttpExchange exchange) throws IOException { // Obtain parameters available from the request URI uri = null; try { uri = new URI(exchange.getRequestURI().getScheme() + "://" + exchange.getRequestHeaders().getFirst("Host") + exchange.getRequestURI()); } catch (URISyntaxException use) { System.out.println("Not authenticated: " + use.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(401, 0); } ImmutableMap<String, String> authorizationHeaders = ImmutableMap.of(); try { authorizationHeaders = this.server.splitAuthorizationHeader(exchange.getRequestHeaders().getFirst("Authorization")); } catch (DataError de) { System.out.println("Not authenticated: " + de.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(401, 0); } String hash = null; if (authorizationHeaders.get("hash") != null) { // Need to calculate hash of the body hash = Hawk.calculateMac(this.credentials, CharStreams.toString(new InputStreamReader(exchange.getRequestBody(), "UTF-8"))); } // Need to know if there is a body present // TODO what happens if the client fakes this information boolean hasBody = exchange.getRequestHeaders().getFirst("Content-Length") != null ? true : false; try { server.authenticate(this.credentials, uri, exchange.getRequestMethod(), authorizationHeaders, hash, hasBody); System.out.println("Authenticated by header"); exchange.sendResponseHeaders(200, 0); } catch (DataError de) { System.out.println("Not authenticated: " + de.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(401, 0); } catch (ServerError se) { System.out.println("Not authenticated: " + se.getLocalizedMessage()); addAuthenticateHeader(exchange); exchange.sendResponseHeaders(500, 0); } } private void addAuthenticateHeader(final HttpExchange exchange) { Map<String, List<String>> responseheaders = exchange.getResponseHeaders(); String authenticate = server.generateAuthenticateHeader(); List<String> authenticateheader = new ArrayList<>(); authenticateheader.add(authenticate); responseheaders.put("WWW-Authenticate", authenticateheader); } } public static void main(String[] args) { try { HawkCredentials credentials = new HawkCredentials.Builder() .keyId("<KEY>") .key("<KEY>") .algorithm(HawkCredentials.Algorithm.SHA256) .build(); new SimpleHttpServer(credentials, null); while (true) { Thread.sleep(60000); } } catch (Exception e) { // Shutdown } } } <|start_filename|>hawk-client-jersey/src/main/java/com/wealdtech/hawk/jersey/HawkAuthorizationFilter.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wealdtech.hawk.jersey; import com.google.common.net.HttpHeaders; import com.google.inject.Inject; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import com.wealdtech.hawk.HawkClient; import java.net.URI; import static com.wealdtech.Preconditions.checkNotNull; /** * Request filter providing an Authorization header * for requests to Hawk applications. */ public class HawkAuthorizationFilter extends ClientFilter { private final transient HawkClient client; @Inject public HawkAuthorizationFilter(final HawkClient client) { checkNotNull(client, "Hawk authorization filter requires a hawk client"); this.client = client; } @Override public ClientResponse handle(final ClientRequest cr) { if ((!cr.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) && (client.isValidFor(cr.getURI().getRawPath()))) { final URI uri = cr.getURI(); final String method = cr.getMethod(); cr.getHeaders().add(HttpHeaders.AUTHORIZATION, this.client.generateAuthorizationHeader(uri, method, null, null, null, null)); } return getNext().handle(cr);} } <|start_filename|>hawk-server-jersey/src/test/java/test/com/wealdtech/hawk/jersey/guice/HawkConfigurationModule.java<|end_filename|> /* * Copyright 2013 Weald Technology Trading Limited * * 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 test.com.wealdtech.hawk.jersey.guice; import test.com.wealdtech.hawk.model.ExampleUser; import test.com.wealdtech.hawk.service.ExampleUserService; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.servlet.ServletModule; import com.wealdtech.hawk.jersey.HawkAuthenticator; import com.wealdtech.jersey.auth.Authenticator; import com.wealdtech.jersey.auth.PrincipalProvider; /** * A Guice module to configure Hawk authentication with the ExampleUser as the * underlying principal. */ public class HawkConfigurationModule extends ServletModule { @Override public void configureServlets() { bind(new TypeLiteral<Authenticator<ExampleUser>>(){}).to(new TypeLiteral<HawkAuthenticator<ExampleUser>>(){}).in(Singleton.class); bind(new TypeLiteral<PrincipalProvider<ExampleUser, String>>(){}).to(ExampleUserService.class); } }
forkerknights/hawk
<|start_filename|>services/els-verify/src/main/java/app/coronawarn/datadonation/services/els/otp/ElsOtpRedemptionRequest.java<|end_filename|> package app.coronawarn.datadonation.services.els.otp; import javax.validation.constraints.Pattern; public class ElsOtpRedemptionRequest { /** * UUID. */ @Pattern(regexp = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}") private String otp; public String getOtp() { return otp; } public void setOtp(String otp) { this.otp = otp; } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/FailedAttestationTimestampValidation.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class FailedAttestationTimestampValidation extends RuntimeException { private static final long serialVersionUID = -8531642585453016232L; public FailedAttestationTimestampValidation() { super("JWS payload timestamp not in validity range"); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/logging/PpacLogger.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.logging; import app.coronawarn.datadonation.common.config.SecurityLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class PpacLogger implements SecurityLogger { static final Logger logger = LoggerFactory.getLogger(PpacLogger.class); @Override public void error(final Exception e) { logger.error(e.getMessage(), e); } @Override public void securityWarn(final Exception e) { logger.warn(SECURITY, e.getMessage()); } void success(final String os, final String endpoint) { logger.info("Successful {} ({}) verification", os, endpoint); } @Override public void successAndroid(final String endpoint) { success("Android", endpoint); } @Override public void successIos(final String endpoint) { success("iOS", endpoint); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/client/domain/PerDeviceValidationRequest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.client.domain; import com.fasterxml.jackson.annotation.JsonProperty; public class PerDeviceValidationRequest { @JsonProperty("device_token") String deviceToken; @JsonProperty("transaction_id") String transactionId; Long timestamp; public PerDeviceValidationRequest() { //empty constructor } /** * Create a new instance of an validation request that can be used to verify a device against the Apple Device API. * * @param deviceToken the device token used for validation. * @param transactionId a valid transaction id for this request. * @param timestamp a valid timestamp for this request. */ public PerDeviceValidationRequest(String deviceToken, String transactionId, Long timestamp) { this.deviceToken = deviceToken; this.transactionId = transactionId; this.timestamp = timestamp; } public String getDeviceToken() { return deviceToken; } public void setDeviceToken(String deviceToken) { this.deviceToken = deviceToken; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } } <|start_filename|>services/retention/src/main/java/app/coronawarn/datadonation/services/retention/config/RetentionConfiguration.java<|end_filename|> package app.coronawarn.datadonation.services.retention.config; import javax.validation.constraints.Min; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; @ConfigurationProperties(prefix = "services.retention") @Validated public class RetentionConfiguration { @Min(0) private Integer apiTokenRetentionDays; @Min(0) private Integer deviceTokenRetentionHours; @Min(0) private Integer otpRetentionDays; @Min(0) private Integer elsOtpRetentionDays; @Min(0) private Integer exposureRiskMetadataRetentionDays; @Min(0) private Integer exposureWindowRetentionDays; @Min(0) private Integer keyMetadataWithClientRetentionDays; @Min(0) private Integer keyMetadataWithUserRetentionDays; @Min(0) private Integer testResultMetadataRetentionDays; @Min(0) private Integer saltRetentionHours; @Min(0) private Integer clientMetadataRetentionDays; @Min(0) private Integer userMetadataRetentionDays; @Min(0) private Integer summarizedExposureWindowRetentionDays; @Min(0) private Integer exposureWindowAtTestRegistrationRetentionDays; @Min(0) private Integer scanInstanceAtTestRegistrationRetentionDays; @Min(0) private Integer exposureWindowTestResultRetentionDays; public Integer getTestResultMetadataRetentionDays() { return testResultMetadataRetentionDays; } public void setTestResultMetadataRetentionDays(Integer testResultMetadataRetentionDays) { this.testResultMetadataRetentionDays = testResultMetadataRetentionDays; } public Integer getSaltRetentionHours() { return saltRetentionHours; } public void setSaltRetentionHours(Integer saltRetentionHours) { this.saltRetentionHours = saltRetentionHours; } public Integer getKeyMetadataWithUserRetentionDays() { return keyMetadataWithUserRetentionDays; } public void setKeyMetadataWithUserRetentionDays(Integer keyMetadataWithUserRetentionDays) { this.keyMetadataWithUserRetentionDays = keyMetadataWithUserRetentionDays; } public Integer getExposureWindowRetentionDays() { return exposureWindowRetentionDays; } public void setExposureWindowRetentionDays(Integer exposureWindowRetentionDays) { this.exposureWindowRetentionDays = exposureWindowRetentionDays; } public Integer getKeyMetadataWithClientRetentionDays() { return keyMetadataWithClientRetentionDays; } public void setKeyMetadataWithClientRetentionDays(Integer keyMetadataWithClientRetentionDays) { this.keyMetadataWithClientRetentionDays = keyMetadataWithClientRetentionDays; } public Integer getApiTokenRetentionDays() { return apiTokenRetentionDays; } public void setApiTokenRetentionDays(Integer apiTokenRetentionDays) { this.apiTokenRetentionDays = apiTokenRetentionDays; } public Integer getDeviceTokenRetentionHours() { return deviceTokenRetentionHours; } public void setDeviceTokenRetentionHours(Integer deviceTokenRetentionHours) { this.deviceTokenRetentionHours = deviceTokenRetentionHours; } public Integer getOtpRetentionDays() { return otpRetentionDays; } public void setOtpRetentionDays(Integer otpRetentionDays) { this.otpRetentionDays = otpRetentionDays; } public Integer getExposureRiskMetadataRetentionDays() { return exposureRiskMetadataRetentionDays; } public void setExposureRiskMetadataRetentionDays(Integer exposureRiskMetadataRetentionDays) { this.exposureRiskMetadataRetentionDays = exposureRiskMetadataRetentionDays; } public Integer getClientMetadataRetentionDays() { return clientMetadataRetentionDays; } public void setClientMetadataRetentionDays(Integer clientMetadataRetentionDays) { this.clientMetadataRetentionDays = clientMetadataRetentionDays; } public Integer getElsOtpRetentionDays() { return elsOtpRetentionDays; } public void setElsOtpRetentionDays(Integer elsOtpRetentionDays) { this.elsOtpRetentionDays = elsOtpRetentionDays; } public Integer getUserMetadataRetentionDays() { return userMetadataRetentionDays; } public void setUserMetadataRetentionDays(Integer userMetadataRetentionDays) { this.userMetadataRetentionDays = userMetadataRetentionDays; } public Integer getSummarizedExposureWindowRetentionDays() { return summarizedExposureWindowRetentionDays; } public void setSummarizedExposureWindowRetentionDays(Integer summarizedExposureWindowRetentionDays) { this.summarizedExposureWindowRetentionDays = summarizedExposureWindowRetentionDays; } public Integer getExposureWindowAtTestRegistrationRetentionDays() { return exposureWindowAtTestRegistrationRetentionDays; } public void setExposureWindowAtTestRegistrationRetentionDays(Integer exposureWindowAtTestRegistrationRetentionDays) { this.exposureWindowAtTestRegistrationRetentionDays = exposureWindowAtTestRegistrationRetentionDays; } public Integer getScanInstanceAtTestRegistrationRetentionDays() { return scanInstanceAtTestRegistrationRetentionDays; } public void setScanInstanceAtTestRegistrationRetentionDays(Integer scanInstanceAtTestRegistrationRetentionDays) { this.scanInstanceAtTestRegistrationRetentionDays = scanInstanceAtTestRegistrationRetentionDays; } public Integer getExposureWindowTestResultRetentionDays() { return exposureWindowTestResultRetentionDays; } public void setExposureWindowTestResultRetentionDays(Integer exposureWindowTestResultRetentionDays) { this.exposureWindowTestResultRetentionDays = exposureWindowTestResultRetentionDays; } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/persistence/repository/metrics/ClientMetadataRepositoryTest.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.common.persistence.domain.metrics.ClientMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.ClientMetadataDetails; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import java.time.LocalDate; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class ClientMetadataRepositoryTest { @Autowired private ClientMetadataRepository clientMetadataRepository; @AfterEach void tearDown() { clientMetadataRepository.deleteAll(); } @Test void clientMetadataShouldBePersistedCorrectly() { CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(1, 1, 1); ClientMetadataDetails clientMetadataDetails = new ClientMetadataDetails(cwaVersionMetadata, "abc", 2, 2, 3, 1l, 2l); ClientMetadata clientMetadata = new ClientMetadata(null, clientMetadataDetails, new TechnicalMetadata(LocalDate.now(), true, true, false, false)); clientMetadataRepository.save(clientMetadata); ClientMetadata loadedEntity = clientMetadataRepository.findAll().iterator().next(); ClientMetadataDetails loadedCMD = loadedEntity.getClientMetadataDetails(); assertEquals(loadedCMD, clientMetadata.getClientMetadataDetails()); assertEquals(loadedEntity.getTechnicalMetadata(), clientMetadata.getTechnicalMetadata()); assertNotNull(loadedEntity.getId()); assertEquals(clientMetadataDetails.getAndroidApiLevel(), loadedCMD.getAndroidApiLevel()); assertEquals(clientMetadataDetails.getAndroidEnfVersion(), loadedCMD.getAndroidEnfVersion()); assertEquals(clientMetadataDetails.getAppConfigEtag(), loadedCMD.getAppConfigEtag()); assertEquals(clientMetadataDetails.getCwaVersion().getCwaVersionMajor(), loadedCMD.getCwaVersion().getCwaVersionMajor()); assertEquals(clientMetadataDetails.getCwaVersion().getCwaVersionMinor(), loadedCMD.getCwaVersion().getCwaVersionMinor()); assertEquals(clientMetadataDetails.getCwaVersion().getCwaVersionPatch(), loadedCMD.getCwaVersion().getCwaVersionPatch()); assertEquals(clientMetadataDetails.getIosVersionMajor(), loadedCMD.getIosVersionMajor()); assertEquals(clientMetadataDetails.getIosVersionMinor(), loadedCMD.getIosVersionMinor()); assertEquals(clientMetadataDetails.getIosVersionPatch(), loadedCMD.getIosVersionPatch()); } @Test void clientMetadataShouldBePersistedCorrectlyMax() { CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(1, 1, 1); ClientMetadataDetails clientMetadataDetails = new ClientMetadataDetails(cwaVersionMetadata, "abc", 2, 2, 3, 2l * Integer.MAX_VALUE, 2l * Integer.MAX_VALUE); ClientMetadata clientMetadata = new ClientMetadata(null, clientMetadataDetails, new TechnicalMetadata(LocalDate.now(), true, true, false, false)); clientMetadataRepository.save(clientMetadata); ClientMetadata loadedEntity = clientMetadataRepository.findAll().iterator().next(); ClientMetadataDetails loadedCMD = loadedEntity.getClientMetadataDetails(); assertEquals(loadedCMD, clientMetadata.getClientMetadataDetails()); assertEquals(loadedEntity.getTechnicalMetadata(), clientMetadata.getTechnicalMetadata()); assertNotNull(loadedEntity.getId()); assertEquals(clientMetadataDetails.getAndroidApiLevel(), loadedCMD.getAndroidApiLevel()); assertEquals(clientMetadataDetails.getAndroidEnfVersion(), loadedCMD.getAndroidEnfVersion()); assertEquals(clientMetadataDetails.getAppConfigEtag(), loadedCMD.getAppConfigEtag()); assertEquals(clientMetadataDetails.getCwaVersion().getCwaVersionMajor(), loadedCMD.getCwaVersion().getCwaVersionMajor()); assertEquals(clientMetadataDetails.getCwaVersion().getCwaVersionMinor(), loadedCMD.getCwaVersion().getCwaVersionMinor()); assertEquals(clientMetadataDetails.getCwaVersion().getCwaVersionPatch(), loadedCMD.getCwaVersion().getCwaVersionPatch()); assertEquals(clientMetadataDetails.getIosVersionMajor(), loadedCMD.getIosVersionMajor()); assertEquals(clientMetadataDetails.getIosVersionMinor(), loadedCMD.getIosVersionMinor()); assertEquals(clientMetadataDetails.getIosVersionPatch(), loadedCMD.getIosVersionPatch()); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/DeviceTokenSyntaxError.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class DeviceTokenSyntaxError extends RuntimeException { public DeviceTokenSyntaxError(final Throwable cause) { super("Device token is badly formatted ", cause); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/FailedAttestationHostnameValidation.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public final class FailedAttestationHostnameValidation extends RuntimeException { private static final long serialVersionUID = -8531642585453016232L; public FailedAttestationHostnameValidation(String message, Throwable e) { super(message, e); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/MissingMandatoryAuthenticationFields.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class MissingMandatoryAuthenticationFields extends RuntimeException { private static final long serialVersionUID = 6711968113382365103L; public MissingMandatoryAuthenticationFields(String message) { super(message); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/apitoken/ProdApiTokenService.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.apitoken; import app.coronawarn.datadonation.common.persistence.repository.ApiTokenRepository; import app.coronawarn.datadonation.services.ppac.ios.client.IosDeviceApiClient; import app.coronawarn.datadonation.services.ppac.ios.verification.JwtProvider; import app.coronawarn.datadonation.services.ppac.ios.verification.PpacIosScenarioRepository; import app.coronawarn.datadonation.services.ppac.ios.verification.apitoken.authentication.ApiTokenAuthenticationStrategy; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.ExternalServiceError; import app.coronawarn.datadonation.services.ppac.ios.verification.scenario.ratelimit.PpacIosRateLimitStrategy; import feign.FeignException; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("!loadtest") public class ProdApiTokenService extends ApiTokenService { public ProdApiTokenService(ApiTokenRepository apiTokenRepository, IosDeviceApiClient iosDeviceApiClient, JwtProvider jwtProvider, ApiTokenAuthenticationStrategy apiTokenAuthenticationStrategy, PpacIosRateLimitStrategy iosScenarioValidator, PpacIosScenarioRepository ppacIosScenarioRepository) { super(apiTokenRepository, iosDeviceApiClient, jwtProvider, apiTokenAuthenticationStrategy, iosScenarioValidator, ppacIosScenarioRepository); } @Override protected void treatApiClientErrors(FeignException e) { throw new ExternalServiceError(e); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/devicetoken/ProdDeviceTokenRedemptionStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.devicetoken; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.DeviceTokenRedeemed; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.InternalServerError; import org.springframework.context.annotation.Profile; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Component; @Component @Profile("!loadtest") public class ProdDeviceTokenRedemptionStrategy implements DeviceTokenRedemptionStrategy { /** * How to handle exceptions during OTP redemption. * * @param e in case of {@link DuplicateKeyException} a {@link DeviceTokenRedeemed} is thrown. * @throws InternalServerError if given {@link Exception} is <code>not</code> an instance of * {@link DuplicateKeyException}. */ @Override public void redeem(Exception e) throws InternalServerError { if (e.getCause() instanceof DuplicateKeyException) { throw new DeviceTokenRedeemed(e); } throw new InternalServerError(e); } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/persistence/repository/metrics/KeySubmissionMetadataWithUserMetadataRepositoryTest.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithUserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails; import java.time.LocalDate; import java.time.ZoneId; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class KeySubmissionMetadataWithUserMetadataRepositoryTest { @Autowired private KeySubmissionMetadataWithUserMetadataRepository keySubmissionMetadataUserMetadataRepository; @AfterEach void tearDown() { keySubmissionMetadataUserMetadataRepository.deleteAll(); } @Test void keySubmissionWithUserMetadataShouldBePersistedCorrectly() { LocalDate justADate = LocalDate.now(ZoneId.of("UTC")); UserMetadataDetails userMetadata = new UserMetadataDetails(1, 2, 3); CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(1, 1, 1); TechnicalMetadata technicalMetadata = new TechnicalMetadata(justADate, true, false, true, false); KeySubmissionMetadataWithUserMetadata keySubmissionMetadata = new KeySubmissionMetadataWithUserMetadata(null, true, false, true, false, 1, 2, 3, 4, null, null, userMetadata, technicalMetadata, cwaVersionMetadata); keySubmissionMetadataUserMetadataRepository.save(keySubmissionMetadata); KeySubmissionMetadataWithUserMetadata loadedEntity = keySubmissionMetadataUserMetadataRepository.findAll().iterator().next(); assertEquals(loadedEntity.getDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(), keySubmissionMetadata.getDaysSinceMostRecentDateAtRiskLevelAtTestRegistration()); assertEquals(loadedEntity.getHoursSinceHighRiskWarningAtTestRegistration(), keySubmissionMetadata.getHoursSinceHighRiskWarningAtTestRegistration()); assertEquals(loadedEntity.getHoursSinceReceptionOfTestResult(), keySubmissionMetadata.getHoursSinceReceptionOfTestResult()); assertEquals(loadedEntity.getSubmitted(), keySubmissionMetadata.getSubmitted()); assertEquals(loadedEntity.getSubmittedAfterSymptomFlow(), keySubmissionMetadata.getSubmittedAfterSymptomFlow()); assertEquals(loadedEntity.getSubmittedWithTeletan(), keySubmissionMetadata.getSubmittedWithTeletan()); assertEquals(loadedEntity.getSubmittedAfterRapidAntigenTest(), keySubmissionMetadata.getSubmittedAfterRapidAntigenTest()); assertEquals(loadedEntity.getTechnicalMetadata(), keySubmissionMetadata.getTechnicalMetadata()); assertEquals(loadedEntity.getUserMetadata(), keySubmissionMetadata.getUserMetadata()); assertNotNull(loadedEntity.getId()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionMajor(), cwaVersionMetadata.getCwaVersionMajor()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionMinor(), cwaVersionMetadata.getCwaVersionMinor()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionPatch(), cwaVersionMetadata.getCwaVersionPatch()); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/controller/AndroidApiErrorHandler.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.controller; import static app.coronawarn.datadonation.services.ppac.commons.web.DataSubmissionResponse.of; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.APK_CERTIFICATE_MISMATCH; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.APK_PACKAGE_NAME_MISMATCH; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.ATTESTATION_EXPIRED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.BASIC_INTEGRITY_REQUIRED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.CTS_PROFILE_MATCH_REQUIRED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.EVALUATION_TYPE_BASIC_REQUIRED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.EVALUATION_TYPE_HARDWARE_BACKED_REQUIRED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.FAILED_ATTESTATION_HOSTNAME_VALIDATION; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.JWS_SIGNATURE_VERIFICATION_FAILED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.MISSING_MANDATORY_AUTHENTICATION_FIELDS; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.NONCE_MISMATCH; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.SALT_REDEEMED; import static java.util.Map.entry; import static java.util.Map.ofEntries; import app.coronawarn.datadonation.common.config.SecurityLogger; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.ApkCertificateDigestsNotAllowed; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.ApkPackageNameNotAllowed; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.BasicEvaluationTypeNotPresent; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.BasicIntegrityIsRequired; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.CtsProfileMatchRequired; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.FailedAttestationHostnameValidation; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.FailedAttestationTimestampValidation; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.FailedJwsParsing; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.FailedSignatureVerification; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.HardwareBackedEvaluationTypeNotPresent; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.MissingMandatoryAuthenticationFields; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.NonceCalculationError; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.NonceCouldNotBeVerified; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.SaltNotValidAnymore; import app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode; import java.util.Map; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE) public class AndroidApiErrorHandler extends ResponseEntityExceptionHandler { private SecurityLogger securityLogger; public AndroidApiErrorHandler(SecurityLogger securityLogger) { this.securityLogger = securityLogger; } /** * Mapping of business logic exceptions to codes delivered to the client. */ private static final Map<Class<? extends RuntimeException>, PpacErrorCode> ERROR_CODES = ofEntries( entry(FailedJwsParsing.class, JWS_SIGNATURE_VERIFICATION_FAILED), entry(FailedSignatureVerification.class, JWS_SIGNATURE_VERIFICATION_FAILED), entry(FailedAttestationHostnameValidation.class, FAILED_ATTESTATION_HOSTNAME_VALIDATION), entry(SaltNotValidAnymore.class, SALT_REDEEMED), entry(FailedAttestationTimestampValidation.class, ATTESTATION_EXPIRED), entry(NonceCouldNotBeVerified.class, NONCE_MISMATCH), entry(ApkPackageNameNotAllowed.class, APK_PACKAGE_NAME_MISMATCH), entry(ApkCertificateDigestsNotAllowed.class, APK_CERTIFICATE_MISMATCH), entry(BasicIntegrityIsRequired.class, BASIC_INTEGRITY_REQUIRED), entry(CtsProfileMatchRequired.class, CTS_PROFILE_MATCH_REQUIRED), entry(BasicEvaluationTypeNotPresent.class, EVALUATION_TYPE_BASIC_REQUIRED), entry(MissingMandatoryAuthenticationFields.class, MISSING_MANDATORY_AUTHENTICATION_FIELDS), entry(HardwareBackedEvaluationTypeNotPresent.class, EVALUATION_TYPE_HARDWARE_BACKED_REQUIRED)); @ExceptionHandler(value = { FailedJwsParsing.class, FailedSignatureVerification.class }) protected ResponseEntity<Object> handleAuthenticationErrors(RuntimeException runtimeException, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(runtimeException); errorCode.secureLog(securityLogger, runtimeException); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(of(errorCode)); } @ExceptionHandler(value = { FailedAttestationTimestampValidation.class, FailedAttestationHostnameValidation.class, ApkPackageNameNotAllowed.class, ApkCertificateDigestsNotAllowed.class, NonceCouldNotBeVerified.class, SaltNotValidAnymore.class, BasicIntegrityIsRequired.class, CtsProfileMatchRequired.class, BasicEvaluationTypeNotPresent.class, HardwareBackedEvaluationTypeNotPresent.class }) protected ResponseEntity<Object> handleForbiddenErrors(RuntimeException runtimeException, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(runtimeException); errorCode.secureLog(securityLogger, runtimeException); return ResponseEntity.status(HttpStatus.FORBIDDEN).body(of(errorCode)); } @ExceptionHandler(value = MissingMandatoryAuthenticationFields.class) protected ResponseEntity<Object> handleMissingInformationOrBadRequests(RuntimeException runtimeException, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(runtimeException); errorCode.secureLog(securityLogger, runtimeException); return ResponseEntity.badRequest().body(of(errorCode)); } @ExceptionHandler(value = NonceCalculationError.class) protected ResponseEntity<Object> handleInternalServerErrors(RuntimeException runtimeException, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(runtimeException); errorCode.secureLog(securityLogger, runtimeException); return new ResponseEntity<>(PpacErrorCode.INTERNAL_SERVER_ERROR, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } private PpacErrorCode getErrorCode(RuntimeException runtimeException) { return ERROR_CODES.getOrDefault(runtimeException.getClass(), PpacErrorCode.UNKNOWN); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/client/domain/PerDeviceDataUpdateRequest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.client.domain; import com.fasterxml.jackson.annotation.JsonProperty; public class PerDeviceDataUpdateRequest { @JsonProperty("device_token") private String deviceToken; @JsonProperty("transaction_id") private String transactionId; private Long timestamp; private boolean bit0; private boolean bit1; public PerDeviceDataUpdateRequest() { // empty constructor } /** * Create a new instance of an update request against the Apple Device Check API to update per-device data. * * @param deviceToken the device token to identify the per-device data. * @param transactionId a valid transaction id for this request. * @param timestamp a valid timestamp for this request. * @param bit0 the first of an total of 2 bits * @param bit1 the second of an total of 2 bits. */ public PerDeviceDataUpdateRequest( String deviceToken, String transactionId, Long timestamp, boolean bit0, boolean bit1) { this.deviceToken = deviceToken; this.transactionId = transactionId; this.timestamp = timestamp; this.bit0 = bit0; this.bit1 = bit1; } public String getDeviceToken() { return deviceToken; } public void setDeviceToken(String deviceToken) { this.deviceToken = deviceToken; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public boolean isBit0() { return bit0; } public void setBit0(boolean bit0) { this.bit0 = bit0; } public boolean isBit1() { return bit1; } public void setBit1(boolean bit1) { this.bit1 = bit1; } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/domain/ElsOneTimePassword.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.domain; import javax.validation.constraints.Size; public class ElsOneTimePassword extends OneTimePassword { /** * No argument constructor. */ public ElsOneTimePassword() { } /** * Constructs the {@link ElsOneTimePassword}. * * @param password The otp to store. */ public ElsOneTimePassword(@Size(min = 36, max = 36) String password) { super(password); } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/config/UrlConstantsTest.java<|end_filename|> package app.coronawarn.datadonation.common.config; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class UrlConstantsTest { /** * Test API version path. */ @Test void testAPIVersionPath() { assertEquals("/version/v1", UrlConstants.V1); } /** * Relevant for iOS mobile devices. */ @Test void testIOSAPIPaths() { assertEquals("/version/v1/ios", UrlConstants.IOS); // iOSController - RequestMapping assertEquals("/version/v1/ios/dat", UrlConstants.IOS + UrlConstants.DATA); // iOSController - PostMapping assertEquals("/version/v1/ios/otp", UrlConstants.IOS + UrlConstants.OTP); // iOSController - PostMapping assertEquals("/version/v1/ios/els", UrlConstants.IOS + UrlConstants.LOG); // iOSController - PostMapping } /** * Relevant for Android mobile devices. */ @Test void testAndroidAPIPaths() { assertEquals("/version/v1/android", UrlConstants.ANDROID); // AndroidController - RequestMapping assertEquals("/version/v1/android/dat", UrlConstants.ANDROID + UrlConstants.DATA); // AndroidController - PostMapping assertEquals("/version/v1/android/otp", UrlConstants.ANDROID + UrlConstants.OTP); // AndroidController - PostMapping assertEquals("/version/v1/android/els", UrlConstants.ANDROID + UrlConstants.LOG); // AndroidController - PostMapping } /** * Relevant for RKI survey system, EDUS hosted under https://survey.data.coronawarn.app */ @Test void testOTPAPIPaths() { assertEquals("/version/v1", UrlConstants.SURVEY); // OTPController - RequestMapping assertEquals("/version/v1/otp", UrlConstants.SURVEY + UrlConstants.OTP); // OTPController - PostMapping } @Test void testElsAPIPaths() { assertEquals("/version/v1", UrlConstants.SURVEY); // OTPController - RequestMapping assertEquals("/version/v1/els", UrlConstants.SURVEY + UrlConstants.LOG); // OTPController - PostMapping } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/HardwareBackedEvaluationTypeNotPresent.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class HardwareBackedEvaluationTypeNotPresent extends RuntimeException { private static final long serialVersionUID = -1834500566508031768L; public HardwareBackedEvaluationTypeNotPresent() { super("Evaluation Type HARDWARE_BACKED not found in Android attestation response"); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/commons/PpaDataRequestValidationFailed.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.commons; public class PpaDataRequestValidationFailed extends RuntimeException { private static final long serialVersionUID = -1558962815012631670L; public PpaDataRequestValidationFailed(String message) { super(message); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/NonceCalculationError.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class NonceCalculationError extends RuntimeException { private static final long serialVersionUID = -8400452065767821216L; public NonceCalculationError(Exception cause) { super("Could not recaculate nonce. ", cause); } public NonceCalculationError(String message) { super(message); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/domain/DeviceToken.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.domain; import org.springframework.data.annotation.Id; public class DeviceToken { @Id private Long id; private byte[] deviceTokenHash; Long createdAt; public DeviceToken() { } public DeviceToken(byte[] deviceTokenHash, Long createdAt) { this.deviceTokenHash = deviceTokenHash; this.createdAt = createdAt; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public byte[] getDeviceTokenHash() { return deviceTokenHash; } public void setDeviceTokenHash(byte[] deviceTokenHash) { this.deviceTokenHash = deviceTokenHash; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/TestApplication.java<|end_filename|> package app.coronawarn.datadonation.common; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; @SpringBootApplication @Configuration public class TestApplication { } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/devicetoken/LoadTestDeviceTokenRedemptionStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.devicetoken; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("loadtest") public class LoadTestDeviceTokenRedemptionStrategy implements DeviceTokenRedemptionStrategy { @Override public void redeem(Exception e) { // do nothing here } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/testdata/JwsGenerationUtil.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.testdata; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.json.webtoken.JsonWebToken; import com.google.api.client.util.Lists; import com.google.api.client.util.StringUtils; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.commons.codec.binary.Base64; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; public class JwsGenerationUtil { public static JsonWebSignature createJsonWebSignature(Map<String, Serializable> payloadValues) { try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); X509Certificate certificate = getTestCertificate(); List<String> certificates = Lists.newArrayList(); certificates.add(Base64.encodeBase64String(Objects.requireNonNull(certificate).getEncoded())); header.setX509Certificates(certificates); JsonWebToken.Payload payload = new JsonWebToken.Payload(); payloadValues.forEach(payload::set); //RSAPublicKey publicKey = getPublicKey(); String signedJWSString = JsonWebSignature.signUsingRsaSha256(getPrivateKey(), GsonFactory.getDefaultInstance(), header, payload); int firstDot = signedJWSString.indexOf('.'); int secondDot = signedJWSString.indexOf('.', firstDot + 1); byte[] signatureBytes = Base64.decodeBase64(signedJWSString.substring(secondDot + 1)); byte[] signedContentBytes = StringUtils.getBytesUtf8(signedJWSString.substring(0, secondDot)); return new JsonWebSignature(header, payload, signatureBytes, signedContentBytes); } catch (Exception ex) { return null; } } public static String createCompactSerializedJws(Map<String, Serializable> payloadValues) { try { JsonWebSignature jws = createJsonWebSignature(payloadValues); GsonFactory gsonFactory = GsonFactory.getDefaultInstance(); String content = Base64.encodeBase64URLSafeString(gsonFactory.toByteArray(Objects.requireNonNull(jws).getHeader())) + "." + Base64.encodeBase64URLSafeString(gsonFactory.toByteArray(jws.getPayload())); return content + "." + Base64.encodeBase64URLSafeString(jws.getSignatureBytes()); } catch (Exception ex) { return null; } } public static X509Certificate getTestCertificate() { try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CertificateFactory cf = CertificateFactory.getInstance("X509", "BC"); InputStream is = JwsGenerationUtil.class.getResourceAsStream("/certificates/test.cert"); X509Certificate certificate = (X509Certificate) cf.generateCertificate(is); is.close(); return certificate; } catch (IOException | CertificateException | NoSuchProviderException e) { e.printStackTrace(); } return null; } private static PrivateKey getPrivateKey() { try { URL url = JwsGenerationUtil.class.getResource("/certificates/test.key"); PEMParser pemParser = new PEMParser(new FileReader((url.getPath()))); Object object; object = pemParser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); // Unencrypted key - no password needed PrivateKeyInfo pki = (PrivateKeyInfo) object; return converter.getPrivateKey(pki); } catch (IOException e) { e.printStackTrace(); } return null; } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/repository/OneTimePasswordRepository.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository; import app.coronawarn.datadonation.common.persistence.domain.OneTimePassword; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; /** * <code>created_at</code> time in <strong>seconds</strong> since epoch. */ @Repository public interface OneTimePasswordRepository extends CrudRepository<OneTimePassword, String> { @Modifying @Query("delete from one_time_password where expiration_timestamp < :threshold or redemption_timestamp < :threshold") void deleteOlderThan(@Param("threshold") long threshold); @Query("select count(*) from one_time_password where expiration_timestamp < :threshold " + "or redemption_timestamp < :threshold") int countOlderThan(@Param("threshold") long threshold); @Modifying @Query("insert into one_time_password (password, redemption_timestamp, expiration_timestamp) " + "values(:password, :redemptionTimestamp, :expirationTimestamp)") void insert(@Param("password") String password, @Param("redemptionTimestamp") Long redemptionTimestamp, @Param("expirationTimestamp") Long expirationTimestamp ); } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/ApiTokenAlreadyUsed.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class ApiTokenAlreadyUsed extends RuntimeException { public ApiTokenAlreadyUsed(String perDeviceDataLastUpdated) { super("PPAC failed due to API Token already issued this month: " + perDeviceDataLastUpdated); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/AbstractOtpService.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; import app.coronawarn.datadonation.common.persistence.domain.OneTimePassword; import app.coronawarn.datadonation.common.utils.TimeUtils; import java.time.ZoneOffset; import java.time.ZonedDateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.repository.CrudRepository; public abstract class AbstractOtpService<T extends OneTimePassword> { private final Logger logger = LoggerFactory.getLogger(AbstractOtpService.class); private final CrudRepository<T, String> otpRepository; /** * Constructs the OtpService. * * @param otpRepository The OTP Repository. */ protected AbstractOtpService(CrudRepository<T, String> otpRepository) { this.otpRepository = otpRepository; } /** * Save a new OneTimePassword or any of it's subtypes and return the expiration time. * * @return the expiration time. */ public ZonedDateTime createOtp(T otp, int validityInHours) { if (!otp.isNew()) { throw new OtpStatusException("OTP to create must be new."); } ZonedDateTime expirationTime = ZonedDateTime.now(ZoneOffset.UTC).plusHours(validityInHours); otp.setExpirationTimestamp(expirationTime.toEpochSecond()); otp.setPassword(otp.getPassword().toLowerCase()); otpRepository.save(otp); return expirationTime; } /** * Redeems the OTP object, if it has state {@link OtpState#VALID}. This means that the redemption timestamp is set to * the current timestamp. * * @param otp The OTP to redeem. * @return The {@link OtpState} of the OTP before redemption. */ public OtpState redeemOtp(T otp) { OtpState state = getOtpStatus(otp); if (state.equals(OtpState.VALID)) { otp.setRedemptionTimestamp(TimeUtils.getEpochSecondsForNow()); otp.setPassword(otp.getPassword().toLowerCase()); otpRepository.save(otp); return getOtpStatus(otp); } return state; } /** * Fetches and returns the {@link OneTimePassword} or any of it's subtypes with the provided password from the * repository. * * @param password The password/ID of the OTP. * @return The {@link OneTimePassword} from the repository (if present) or any of it's subtypes. * @throws OtpNotFoundException if no OTP was found. */ public T getOtp(String password) { var otp = otpRepository.findById(password.toLowerCase()); if (otp.isPresent()) { return otp.get(); } else { throw new OtpNotFoundException(password); } } /** * Calculates and returns the {@link OtpState} of the provided OTP. * * @param otp The OTP. * @return The {@link OtpState} of the provided OTP. */ public OtpState getOtpStatus(T otp) { ZonedDateTime expirationTime = TimeUtils.getZonedDateTimeFor(otp.getExpirationTimestamp()); boolean isExpired = expirationTime.isBefore(ZonedDateTime.now(ZoneOffset.UTC)); if (otp.getRedemptionTimestamp() != null) { logger.info("OTP '{}' already redeemed", otp); return OtpState.REDEEMED; } if (isExpired) { logger.info("OTP '{}' already expired", otp); return OtpState.EXPIRED; } logger.debug("OTP is valid"); return OtpState.VALID; } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/ApkPackageNameNotAllowed.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class ApkPackageNameNotAllowed extends RuntimeException { private static final long serialVersionUID = 8772200600466947124L; public ApkPackageNameNotAllowed(String apkPackageName) { super("APK package not allowed: " + apkPackageName); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/ApkCertificateDigestsNotAllowed.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class ApkCertificateDigestsNotAllowed extends RuntimeException { private static final long serialVersionUID = 7913843985526360886L; public ApkCertificateDigestsNotAllowed() { super("APK Certificate Digest Sha256 received which is not part of allowed list"); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/DeviceTokenInvalid.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class DeviceTokenInvalid extends RuntimeException { public DeviceTokenInvalid() { super("PPAC failed due to invalid device token!"); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/OtpNotFoundException.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; @SuppressWarnings("serial") public class OtpNotFoundException extends RuntimeException { public OtpNotFoundException(final String otp) { // it's save to be logged, since it's coming from OtpRedemptionRequest#otp super("OTP '" + otp + "' not found"); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/OtpService.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; import app.coronawarn.datadonation.common.persistence.domain.OneTimePassword; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Service; @Service public class OtpService extends AbstractOtpService<OneTimePassword> { /** * Constructs the OtpService. * * @param otpRepository The OTP Repository. */ protected OtpService(CrudRepository<OneTimePassword, String> otpRepository) { super(otpRepository); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/salt/SaltVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.salt; public interface SaltVerificationStrategy { void validateSalt(String saltString); } <|start_filename|>services/els-verify/src/test/java/app/coronawarn/datadonation/services/els/otp/GenerateElsOtpControllerTest.java<|end_filename|> package app.coronawarn.datadonation.services.els.otp; import static org.assertj.core.api.Assertions.assertThat; import app.coronawarn.datadonation.common.persistence.service.OtpTestGenerationResponse; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("generate-els") @DirtiesContext class GenerateElsOtpControllerTest { @Autowired GenerateElsOtpController generateElsOtpController; @Test void testElsOtpsAreCreated() { int numberOfInvocations = 15; int validityInHours = 5; List<OtpTestGenerationResponse> responses = generateElsOtpController .generateElsOtp(numberOfInvocations, validityInHours) .getBody(); assert responses != null; assertThat(responses.size()).isEqualTo(numberOfInvocations); for (OtpTestGenerationResponse response : responses) { assertThat(ZonedDateTime.now(ZoneOffset.UTC).plusHours(validityInHours)) .isEqualToIgnoringSeconds(response.getExpirationDate()); } } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/commons/web/CommonApiErrorHandler.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.commons.web; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.INTERNAL_SERVER_ERROR; import app.coronawarn.datadonation.common.config.SecurityLogger; import app.coronawarn.datadonation.common.persistence.errors.MetricsDataCouldNotBeStored; import app.coronawarn.datadonation.services.ppac.commons.PpaDataRequestValidationFailed; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.InternalServerError; import app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode; import java.util.Map; import javax.validation.ConstraintViolationException; import org.apache.catalina.connector.ClientAbortException; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @Order(Ordered.LOWEST_PRECEDENCE) public class CommonApiErrorHandler extends ResponseEntityExceptionHandler { private SecurityLogger securityLogger; public CommonApiErrorHandler(SecurityLogger securityLogger) { this.securityLogger = securityLogger; } private static final Map<Class<? extends RuntimeException>, PpacErrorCode> ERROR_CODES = Map.of( MetricsDataCouldNotBeStored.class, PpacErrorCode.METRICS_DATA_NOT_VALID, PpaDataRequestValidationFailed.class, PpacErrorCode.METRICS_DATA_NOT_VALID, InternalServerError.class, INTERNAL_SERVER_ERROR); @ExceptionHandler(value = { InternalServerError.class }) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) protected void handleWrappedInternalErrors(RuntimeException e, WebRequest webRequest) { getErrorCode(e).secureLog(securityLogger, e); } @ExceptionHandler(value = { MetricsDataCouldNotBeStored.class, PpaDataRequestValidationFailed.class }) @ResponseStatus(HttpStatus.BAD_REQUEST) protected void handleBadRequest(RuntimeException e, WebRequest webRequest) { getErrorCode(e).secureLog(securityLogger, e); } @ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Void handleOtpCreationError(ConstraintViolationException e) { securityLogger.securityWarn(e); return null; } @ExceptionHandler(ClientAbortException.class) @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE) public Object exceptionHandler(ClientAbortException exc) { return null; //socket is closed, cannot return any response } private PpacErrorCode getErrorCode(RuntimeException runtimeException) { return ERROR_CODES.getOrDefault(runtimeException.getClass(), PpacErrorCode.UNKNOWN); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/repository/metrics/ScanInstanceRepository.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import app.coronawarn.datadonation.common.persistence.domain.metrics.ScanInstance; import java.time.LocalDate; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; public interface ScanInstanceRepository extends CrudRepository<ScanInstance, Long> { @Query("select count(*) from scan_instance where submitted_at < :threshold") int countOlderThan(@Param("threshold") LocalDate threshold); @Modifying @Query("delete from scan_instance where submitted_at < :threshold") void deleteOlderThan(@Param("threshold") LocalDate threshold); } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/persistence/repository/metrics/UserMetadataRepositoryTest.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.UserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails; import java.time.LocalDate; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class UserMetadataRepositoryTest { @Autowired private UserMetadataRepository userMetadataRepository; @AfterEach void tearDown() { userMetadataRepository.deleteAll(); } @Test void userMetadataShouldBePersistedCorrectly() { UserMetadata userMetadata = new UserMetadata(null, new UserMetadataDetails(1, 2, 2), new TechnicalMetadata(LocalDate.now(), true, true, false, false)); userMetadataRepository.save(userMetadata); UserMetadata loadedEntity = userMetadataRepository.findAll().iterator().next(); assertEquals(loadedEntity.getUserMetadataDetails(), userMetadata.getUserMetadataDetails()); assertEquals(loadedEntity.getTechnicalMetadata(), userMetadata.getTechnicalMetadata()); assertNotNull(loadedEntity.getId()); } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/validation/ObjectWithDateMember.java<|end_filename|> package app.coronawarn.datadonation.common.validation; import java.time.LocalDate; public class ObjectWithDateMember { /** * from = "1970-01-01", till = "2000-01-01". */ @DateInRange(from = "1970-01-01", till = "2000-01-01") LocalDate dateToBeValidated; /** * from = "", till = "". */ @DateInRange LocalDate dateToBeValidatedNull; /** * from = "1970-01-01", till = "". */ @DateInRange(from = "1970-01-01", message = "Date must be after {from}") LocalDate dateToBeValidatedFrom; /** * from = "", till = "2000-01-01". */ @DateInRange(till = "2000-01-01", message = "Date must be before {till}") LocalDate dateToBeValidatedTill; public void setDateToBeValidated(final LocalDate dateToBeValidated) { this.dateToBeValidated = dateToBeValidated; } public void setDateToBeValidatedFrom(final LocalDate dateToBeValidatedFrom) { this.dateToBeValidatedFrom = dateToBeValidatedFrom; } public void setDateToBeValidatedNull(final LocalDate dateToBeValidatedNull) { this.dateToBeValidatedNull = dateToBeValidatedNull; } public void setDateToBeValidatedTill(final LocalDate dateToBeValidatedTill) { this.dateToBeValidatedTill = dateToBeValidatedTill; } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/FailedSignatureVerification.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public final class FailedSignatureVerification extends RuntimeException { private static final long serialVersionUID = 5078963545906035590L; public FailedSignatureVerification(String message) { super(message); } public FailedSignatureVerification(String message, Throwable e) { super(message, e); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/client/domain/PerDeviceDataQueryRequest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.client.domain; import com.fasterxml.jackson.annotation.JsonProperty; public class PerDeviceDataQueryRequest { @JsonProperty("device_token") private String deviceToken; @JsonProperty("transaction_id") private String transactionId; private Long timestamp; public PerDeviceDataQueryRequest() { // empty constructor } /** * Create a new instance of an query request to retrieve per-device data for a given device token. * * @param deviceToken the device token as identification. * @param transactionId a valid transaction id for this request. * @param timestamp a valid timestamp for this request. */ public PerDeviceDataQueryRequest(String deviceToken, String transactionId, Long timestamp) { this.deviceToken = deviceToken; this.transactionId = transactionId; this.timestamp = timestamp; } public String getDeviceToken() { return deviceToken; } public void setDeviceToken(String deviceToken) { this.deviceToken = deviceToken; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/errors/MetricsDataCouldNotBeStored.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.errors; public class MetricsDataCouldNotBeStored extends RuntimeException { private static final long serialVersionUID = 2136916612923338677L; public MetricsDataCouldNotBeStored(String message) { super(message); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/client/IosDeviceApiClient.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.client; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import app.coronawarn.datadonation.services.ppac.ios.client.domain.PerDeviceDataQueryRequest; import app.coronawarn.datadonation.services.ppac.ios.client.domain.PerDeviceDataUpdateRequest; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @FeignClient(name = "deviceApi", url = "${ppac.ios.device-api-url}") public interface IosDeviceApiClient { @PostMapping(value = "/query_two_bits") ResponseEntity<String> queryDeviceData(@RequestHeader(AUTHORIZATION) final String jwt, @RequestBody PerDeviceDataQueryRequest queryRequest); @PostMapping(value = "/update_two_bits") ResponseEntity<Void> updatePerDeviceData(@RequestHeader(AUTHORIZATION) final String jwt, @RequestBody PerDeviceDataUpdateRequest updateRequest); } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/controller/validation/EdusOneTimePasswordRequestAndroidValidator.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.controller.validation; import app.coronawarn.datadonation.common.protocols.internal.ppdd.EDUSOneTimePasswordRequestAndroid; import app.coronawarn.datadonation.services.ppac.commons.validation.UuidConstraintValidator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.stereotype.Component; @Component public class EdusOneTimePasswordRequestAndroidValidator extends UuidConstraintValidator implements ConstraintValidator<ValidEdusOneTimePasswordRequestAndroid, EDUSOneTimePasswordRequestAndroid> { @Override public boolean isValid(final EDUSOneTimePasswordRequestAndroid requestBody, final ConstraintValidatorContext context) { return super.isValid(requestBody.getPayload().getOtp(), context); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/JwtProvider.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Instant; import java.util.Base64; import java.util.Date; import java.util.Optional; import org.springframework.stereotype.Component; @Component public class JwtProvider { private final PpacConfiguration ppacConfiguration; private static final String BEARER_PREFIX = "Bearer "; private static final String KEY_ID = "kid"; private static final String ELLIPTIC_CURVE = "EC"; public JwtProvider(PpacConfiguration ppacConfiguration) { this.ppacConfiguration = ppacConfiguration; } /** * Generate a valid jwt to query the Device API. * * @return an valid Json Web Token as Authorization Header (Bearer jwt). */ public String generateJwt() { String ppacIosJwtKeyId = this.ppacConfiguration.getIos().getPpacIosJwtKeyId(); String ppacIosJwtTeamId = this.ppacConfiguration.getIos().getPpacIosJwtTeamId(); String secretKeyString = this.ppacConfiguration.getIos().getPpacIosJwtSigningKey(); PrivateKey pk = buildPrivateKey(secretKeyString).orElseThrow(RuntimeException::new); return BEARER_PREFIX + Jwts .builder() .setHeaderParam(KEY_ID, ppacIosJwtKeyId) .setIssuer(ppacIosJwtTeamId) .setIssuedAt(Date.from(Instant.now())) .signWith(pk, SignatureAlgorithm.ES256) .compact(); } private Optional<PrivateKey> buildPrivateKey(String pk8) { byte[] pk8EncodedBytes = convertToPkcs8(pk8); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pk8EncodedBytes); try { KeyFactory kf = KeyFactory.getInstance(ELLIPTIC_CURVE); return Optional.of(kf.generatePrivate(keySpec)); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { return Optional.empty(); } } private byte[] convertToPkcs8(String pk8) { pk8 = pk8.replace("-----BEGIN PRIVATE KEY-----", ""); pk8 = pk8.replace("-----END PRIVATE KEY-----", ""); pk8 = pk8.replaceAll("\\s+", ""); return Base64.getDecoder().decode(pk8); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/DeviceTokenRedeemed.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class DeviceTokenRedeemed extends RuntimeException { public DeviceTokenRedeemed(final Throwable cause) { super("PPAC failed due to redeemed device token", cause); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/ApiTokenExpired.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class ApiTokenExpired extends RuntimeException { public ApiTokenExpired() { super("PPAC failed due to expired api token."); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/commons/validation/UuidConstraintValidator.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.commons.validation; import java.util.UUID; import javax.validation.ConstraintValidatorContext; public abstract class UuidConstraintValidator { private void addViolation(final ConstraintValidatorContext validatorContext) { validatorContext.buildConstraintViolationWithTemplate("OTP must be a valid UUID v4 String.") .addConstraintViolation(); } private boolean checkIsValidUuid(final String uuid, final ConstraintValidatorContext constraintValidatorContext) { boolean isUuid = false; try { UUID.fromString(uuid); isUuid = true; } catch (final IllegalArgumentException e) { addViolation(constraintValidatorContext); } return isUuid; } protected boolean isValid(final String uuid, final ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); return checkIsValidUuid(uuid, context); } } <|start_filename|>services/edus/src/test/java/app/coronawarn/datadonation/services/edus/otp/GenerateOtpControllerTest.java<|end_filename|> package app.coronawarn.datadonation.services.edus.otp; import static org.assertj.core.api.Assertions.assertThat; import app.coronawarn.datadonation.common.persistence.service.OtpTestGenerationResponse; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("generate-otp") @DirtiesContext class GenerateOtpControllerTest { @Autowired GenerateOtpController generateOtpController; @Test void testOtpsAreCreated() { int numberOfInvocations = 15; int validityInHours = 5; List<OtpTestGenerationResponse> responses = generateOtpController.generateOtp(numberOfInvocations, validityInHours) .getBody(); assert responses != null; assertThat(responses.size()).isEqualTo(numberOfInvocations); for (OtpTestGenerationResponse response : responses) { assertThat(ZonedDateTime.now(ZoneOffset.UTC).plusHours(validityInHours)) .isEqualToIgnoringSeconds(response.getExpirationDate()); } } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/NonceCouldNotBeVerified.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class NonceCouldNotBeVerified extends RuntimeException { private static final long serialVersionUID = -288077614896557469L; public NonceCouldNotBeVerified(String message) { super(message); } public NonceCouldNotBeVerified(String message, Exception cause) { super(message, cause); } } <|start_filename|>services/retention/src/main/java/app/coronawarn/datadonation/services/retention/runner/RetentionPolicy.java<|end_filename|> package app.coronawarn.datadonation.services.retention.runner; import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.HOURS; import app.coronawarn.datadonation.common.persistence.repository.ApiTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.DeviceTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.ElsOneTimePasswordRepository; import app.coronawarn.datadonation.common.persistence.repository.OneTimePasswordRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ClientMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureRiskMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowTestResultsRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowsAtTestRegistrationRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.KeySubmissionMetadataWithClientMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.KeySubmissionMetadataWithUserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ScanInstanceRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ScanInstancesAtTestRegistrationRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.SummarizedExposureWindowsWithUserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.TestResultMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.UserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.ppac.android.SaltRepository; import app.coronawarn.datadonation.services.retention.Application; import app.coronawarn.datadonation.services.retention.config.RetentionConfiguration; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.temporal.TemporalUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(1) public class RetentionPolicy implements ApplicationRunner { static long subtractRetentionPeriodFromNowToEpochMilli(final TemporalUnit temporalUnit, final Integer retentionPeriod) { return Instant.now().truncatedTo(temporalUnit).minus(retentionPeriod, temporalUnit).toEpochMilli(); } static long subtractRetentionPeriodFromNowToSeconds(final TemporalUnit temporalUnit, final Integer retentionPeriod) { return Instant.now().truncatedTo(temporalUnit).minus(retentionPeriod, temporalUnit).getEpochSecond(); } /** * Calculates the date to be used for the deletion. * * @param retentionDays how many days back in time you want to travel? * @return TODAY - retentionDays */ static LocalDate threshold(final Integer retentionDays) { return Instant.now().atOffset(ZoneOffset.UTC).toLocalDate().minusDays(retentionDays); } private final Logger logger = LoggerFactory.getLogger(getClass()); private final ExposureRiskMetadataRepository exposureRiskMetadataRepository; private final ExposureWindowRepository exposureWindowRepository; private final ScanInstanceRepository scanInstanceRepository; private final KeySubmissionMetadataWithClientMetadataRepository keySubmissionMetadataWithClientMetadataRepository; private final KeySubmissionMetadataWithUserMetadataRepository keySubmissionMetadataWithUserMetadataRepository; private final TestResultMetadataRepository testResultMetadataRepository; private final DeviceTokenRepository deviceTokenRepository; private final OneTimePasswordRepository oneTimePasswordRepository; private final ElsOneTimePasswordRepository elsOneTimePasswordRepository; private final RetentionConfiguration retentionConfiguration; private final ApplicationContext appContext; private final SaltRepository saltRepository; private final ApiTokenRepository apiTokenRepository; private final ClientMetadataRepository clientMetadataRepository; private final UserMetadataRepository userMetadataRepository; private final SummarizedExposureWindowsWithUserMetadataRepository summarizedExposureWindowsWithUserMetadataRepo; private final ExposureWindowTestResultsRepository exposureWindowTestResultsRepository; private final ScanInstancesAtTestRegistrationRepository scanInstancesAtTestRegistrationRepository; private final ExposureWindowsAtTestRegistrationRepository exposureWindowsAtTestRegistrationRepository; /** * Creates a new {@link RetentionPolicy}. */ @Autowired public RetentionPolicy(final ApiTokenRepository apiTokenRepository, final ExposureRiskMetadataRepository exposureRiskMetadataRepository, final ExposureWindowRepository exposureWindowRepository, final ScanInstanceRepository scanInstanceRepository, final KeySubmissionMetadataWithClientMetadataRepository keySubmissionMetadataWithClientMetadataRepository, final KeySubmissionMetadataWithUserMetadataRepository keySubmissionMetadataWithUserMetadataRepository, final TestResultMetadataRepository testResultMetadataRepository, final DeviceTokenRepository deviceTokenRepository, final OneTimePasswordRepository oneTimePasswordRepository, final ElsOneTimePasswordRepository elsOneTimePasswordRepository, final RetentionConfiguration retentionConfiguration, final ApplicationContext appContext, final SaltRepository saltRepository, final ClientMetadataRepository clientMetadataRepository, final UserMetadataRepository userMetadataRepository, final SummarizedExposureWindowsWithUserMetadataRepository summarizedExposureWindowsWithUserMetadataRepo, final ExposureWindowTestResultsRepository exposureWindowTestResultsRepository, final ScanInstancesAtTestRegistrationRepository scanInstancesAtTestRegistrationRepository, final ExposureWindowsAtTestRegistrationRepository exposureWindowsAtTestRegistrationRepository) { this.exposureRiskMetadataRepository = exposureRiskMetadataRepository; this.scanInstanceRepository = scanInstanceRepository; this.exposureWindowRepository = exposureWindowRepository; this.keySubmissionMetadataWithClientMetadataRepository = keySubmissionMetadataWithClientMetadataRepository; this.keySubmissionMetadataWithUserMetadataRepository = keySubmissionMetadataWithUserMetadataRepository; this.testResultMetadataRepository = testResultMetadataRepository; this.deviceTokenRepository = deviceTokenRepository; this.oneTimePasswordRepository = oneTimePasswordRepository; this.elsOneTimePasswordRepository = elsOneTimePasswordRepository; this.retentionConfiguration = retentionConfiguration; this.appContext = appContext; this.saltRepository = saltRepository; this.apiTokenRepository = apiTokenRepository; this.clientMetadataRepository = clientMetadataRepository; this.userMetadataRepository = userMetadataRepository; this.summarizedExposureWindowsWithUserMetadataRepo = summarizedExposureWindowsWithUserMetadataRepo; this.exposureWindowTestResultsRepository = exposureWindowTestResultsRepository; this.scanInstancesAtTestRegistrationRepository = scanInstancesAtTestRegistrationRepository; this.exposureWindowsAtTestRegistrationRepository = exposureWindowsAtTestRegistrationRepository; } private void deleteClientMetadata() { final LocalDate date = threshold(retentionConfiguration.getClientMetadataRetentionDays()); logDeletionInDays(clientMetadataRepository.countOlderThan(date), retentionConfiguration.getClientMetadataRetentionDays(), "client metadata"); clientMetadataRepository.deleteOlderThan(date); } private void deleteKeySubmissionMetadataWithClient() { final LocalDate date = threshold(retentionConfiguration.getKeyMetadataWithClientRetentionDays()); logDeletionInDays(keySubmissionMetadataWithClientMetadataRepository.countOlderThan(date), retentionConfiguration.getKeyMetadataWithClientRetentionDays(), "key submission metadata with client"); keySubmissionMetadataWithClientMetadataRepository.deleteOlderThan(date); } private void deleteKeySubmissionMetadataWithUser() { final LocalDate date = threshold(retentionConfiguration.getKeyMetadataWithUserRetentionDays()); logDeletionInDays(keySubmissionMetadataWithUserMetadataRepository.countOlderThan(date), retentionConfiguration.getKeyMetadataWithUserRetentionDays(), "key submission metadata with user"); keySubmissionMetadataWithUserMetadataRepository.deleteOlderThan(date); } private void deleteOutdatedApiTokens() { final long apiTokenThreshold = subtractRetentionPeriodFromNowToSeconds(DAYS, retentionConfiguration.getApiTokenRetentionDays()); logDeletionInDays(apiTokenRepository.countOlderThan(apiTokenThreshold), retentionConfiguration.getApiTokenRetentionDays(), "API tokens"); apiTokenRepository.deleteOlderThan(apiTokenThreshold); } private void deleteOutdatedDeviceTokens() { final long deviceTokenThreshold = subtractRetentionPeriodFromNowToEpochMilli(HOURS, retentionConfiguration.getDeviceTokenRetentionHours()); logDeletionInHours(deviceTokenRepository.countOlderThan(deviceTokenThreshold), retentionConfiguration.getDeviceTokenRetentionHours(), "device tokens"); deviceTokenRepository.deleteOlderThan(deviceTokenThreshold); } private void deleteOutdatedElsTokens() { final long elsOtpThreshold = subtractRetentionPeriodFromNowToSeconds(DAYS, retentionConfiguration.getElsOtpRetentionDays()); logDeletionInDays(elsOneTimePasswordRepository.countOlderThan(elsOtpThreshold), retentionConfiguration.getElsOtpRetentionDays(), "els-verify tokens"); elsOneTimePasswordRepository.deleteOlderThan(elsOtpThreshold); } private void deleteOutdatedExposureRiskMetadata() { final LocalDate date = threshold(retentionConfiguration.getExposureRiskMetadataRetentionDays()); logDeletionInDays(exposureRiskMetadataRepository.countOlderThan(date), retentionConfiguration.getExposureRiskMetadataRetentionDays(), "exposure risk metadata"); exposureRiskMetadataRepository.deleteOlderThan(date); } private void deleteOutdatedExposureWindows() { final LocalDate date = threshold(retentionConfiguration.getExposureWindowRetentionDays()); logDeletionInDays(exposureWindowRepository.countOlderThan(date), retentionConfiguration.getExposureWindowRetentionDays(), "exposure windows"); exposureWindowRepository.deleteOlderThan(date); } private void deleteOutdatedOneTimePasswords() { final long otpThreshold = subtractRetentionPeriodFromNowToSeconds(DAYS, retentionConfiguration.getOtpRetentionDays()); logDeletionInDays(oneTimePasswordRepository.countOlderThan(otpThreshold), retentionConfiguration.getOtpRetentionDays(), "one time passwords"); oneTimePasswordRepository.deleteOlderThan(otpThreshold); } private void deleteOutdatedSalt() { final long saltThreshold = subtractRetentionPeriodFromNowToEpochMilli(HOURS, retentionConfiguration.getSaltRetentionHours()); logDeletionInHours(saltRepository.countOlderThan(saltThreshold), retentionConfiguration.getSaltRetentionHours(), "salts"); saltRepository.deleteOlderThan(saltThreshold); } private void deleteOutdatedScanInstance() { final LocalDate date = threshold(retentionConfiguration.getExposureWindowRetentionDays()); logDeletionInDays(scanInstanceRepository.countOlderThan(date), retentionConfiguration.getExposureWindowRetentionDays(), "scan instance"); scanInstanceRepository.deleteOlderThan(date); } private void deleteTestResultsMetadata() { final LocalDate date = threshold(retentionConfiguration.getTestResultMetadataRetentionDays()); logDeletionInDays(testResultMetadataRepository.countOlderThan(date), retentionConfiguration.getTestResultMetadataRetentionDays(), "test results metadata"); testResultMetadataRepository.deleteOlderThan(date); } private void deleteUserMetaData() { final LocalDate date = threshold(retentionConfiguration.getUserMetadataRetentionDays()); logDeletionInDays(userMetadataRepository.countOlderThan(date), retentionConfiguration.getUserMetadataRetentionDays(), "user metadata"); userMetadataRepository.deleteOlderThan(date); } private void deleteSummarizedExposureWindowsWithUserMetadata() { final LocalDate date = threshold(retentionConfiguration.getSummarizedExposureWindowRetentionDays()); logDeletionInDays(summarizedExposureWindowsWithUserMetadataRepo.countOlderThan(date), retentionConfiguration.getSummarizedExposureWindowRetentionDays(), "summarized exposure windows"); summarizedExposureWindowsWithUserMetadataRepo.deleteOlderThan(date); } private void deleteExposureWindowsTestResult() { final LocalDate date = threshold(retentionConfiguration.getExposureWindowTestResultRetentionDays()); logDeletionInDays(exposureWindowTestResultsRepository.countOlderThan(date), retentionConfiguration.getExposureWindowTestResultRetentionDays(), "exposure window test result"); exposureWindowTestResultsRepository.deleteOlderThan(date); } private void deleteExposureWindowAtTestRegistration() { final LocalDate date = threshold(retentionConfiguration.getExposureWindowAtTestRegistrationRetentionDays()); logDeletionInDays(exposureWindowsAtTestRegistrationRepository.countOlderThan(date), retentionConfiguration.getExposureWindowAtTestRegistrationRetentionDays(), "exposure window at test registration"); exposureWindowsAtTestRegistrationRepository.deleteOlderThan(date); } private void deleteScanInstanceAtTestRegistration() { final LocalDate date = threshold(retentionConfiguration.getScanInstanceAtTestRegistrationRetentionDays()); logDeletionInDays(scanInstancesAtTestRegistrationRepository.countOlderThan(date), retentionConfiguration.getScanInstanceAtTestRegistrationRetentionDays(), "scan instance at test registration"); scanInstancesAtTestRegistrationRepository.deleteOlderThan(date); } private void logDeletionInDays(final int dataAmount, final int retentionDays, final String dataName) { logger.info("Deleting {} {} that are older than {} day(s) ago.", dataAmount, dataName, retentionDays); } private void logDeletionInHours(final int dataAmount, final int retentionHours, final String dataName) { logger.info("Deleting {} {} that are older than {} hour(s) ago.", dataAmount, dataName, retentionHours); } @Override public void run(final ApplicationArguments args) { try { deleteClientMetadata(); deleteKeySubmissionMetadataWithClient(); deleteKeySubmissionMetadataWithUser(); deleteOutdatedApiTokens(); deleteOutdatedDeviceTokens(); deleteOutdatedElsTokens(); deleteOutdatedExposureRiskMetadata(); deleteOutdatedOneTimePasswords(); deleteOutdatedSalt(); deleteTestResultsMetadata(); deleteUserMetaData(); deleteOutdatedScanInstance(); deleteOutdatedExposureWindows(); deleteSummarizedExposureWindowsWithUserMetadata(); deleteExposureWindowsTestResult(); deleteExposureWindowAtTestRegistration(); deleteScanInstanceAtTestRegistration(); } catch (final Exception e) { logger.error("Apply of retention policy failed.", e); Application.killApplication(appContext); } } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/ios/controller/IosControllerTest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.controller; import static app.coronawarn.datadonation.common.utils.TimeUtils.getZonedDateTimeFor; import static app.coronawarn.datadonation.services.ppac.ios.testdata.TestData.buildBase64String; import static app.coronawarn.datadonation.services.ppac.ios.testdata.TestData.buildIosDeviceData; import static app.coronawarn.datadonation.services.ppac.ios.testdata.TestData.buildUuid; import static app.coronawarn.datadonation.services.ppac.ios.testdata.TestData.jsonify; import static app.coronawarn.datadonation.services.ppac.ios.testdata.TestData.postLogOtpCreationRequest; import static app.coronawarn.datadonation.services.ppac.ios.testdata.TestData.postOtpCreationRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.http.HttpStatus.BAD_REQUEST; import app.coronawarn.datadonation.common.config.UrlConstants; import app.coronawarn.datadonation.common.persistence.domain.ElsOneTimePassword; import app.coronawarn.datadonation.common.persistence.domain.OneTimePassword; import app.coronawarn.datadonation.common.persistence.repository.ApiTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.DeviceTokenRepository; import app.coronawarn.datadonation.common.persistence.service.ElsOtpService; import app.coronawarn.datadonation.common.persistence.service.OtpCreationResponse; import app.coronawarn.datadonation.common.persistence.service.OtpService; import app.coronawarn.datadonation.common.protocols.internal.ppdd.EDUSOneTimePassword; import app.coronawarn.datadonation.common.protocols.internal.ppdd.EDUSOneTimePasswordRequestIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ELSOneTimePassword; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ELSOneTimePasswordRequestIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPACIOS; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import app.coronawarn.datadonation.services.ppac.config.TestBeanConfig; import app.coronawarn.datadonation.services.ppac.ios.client.IosDeviceApiClient; import app.coronawarn.datadonation.services.ppac.ios.client.domain.PerDeviceDataResponse; import app.coronawarn.datadonation.services.ppac.ios.verification.JwtProvider; import app.coronawarn.datadonation.services.ppac.ios.verification.apitoken.authentication.ApiTokenAuthenticationStrategy; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Import; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Import(TestBeanConfig.class) @ActiveProfiles("test") @DirtiesContext public class IosControllerTest { private static final String IOS_OTP_URL = UrlConstants.IOS + UrlConstants.OTP; private static final String IOS_LOG_OTP_URL = UrlConstants.IOS + UrlConstants.LOG; @Autowired private TestRestTemplate testRestTemplate; @MockBean private IosDeviceApiClient iosDeviceApiClient; @MockBean JwtProvider jwtProvider; @MockBean ApiTokenAuthenticationStrategy apiTokenAuthenticationStrategy; @Autowired private PpacConfiguration ppacConfiguration; @SpyBean private OtpService otpService; @SpyBean private ElsOtpService elsOtpService; @Autowired private ApiTokenRepository apiTokenRepository; @Autowired private DeviceTokenRepository deviceTokenRepository; @BeforeEach void clearDatabase() { apiTokenRepository.deleteAll(); deviceTokenRepository.deleteAll(); } private EDUSOneTimePasswordRequestIOS buildValidOtpPayload(String password) { PPACIOS ppacios = getPpacIos(); return EDUSOneTimePasswordRequestIOS.newBuilder().setAuthentication(ppacios) .setPayload(EDUSOneTimePassword.newBuilder().setOtp(password)).build(); } private ELSOneTimePasswordRequestIOS buildValidLogOtpPayload(String password) { PPACIOS ppacios = getPpacIos(); return ELSOneTimePasswordRequestIOS.newBuilder().setAuthentication(ppacios) .setPayload(ELSOneTimePassword.newBuilder().setOtp(password)).build(); } private PPACIOS getPpacIos() { return PPACIOS.newBuilder().setApiToken(buildUuid()) .setDeviceToken(buildBase64String(ppacConfiguration.getIos().getMinDeviceTokenLength() + 1)).build(); } @Nested class CreateOtpTests { @Test void testOtpServiceIsCalled() { PerDeviceDataResponse data = buildIosDeviceData(OffsetDateTime.now(), true); String password = <PASSWORD>Uuid(); when(iosDeviceApiClient.queryDeviceData(anyString(), any())).thenReturn(ResponseEntity.ok(jsonify(data))); when(jwtProvider.generateJwt()).thenReturn("secretkey"); postOtpCreationRequest(buildValidOtpPayload(password), testRestTemplate, IOS_OTP_URL, false); var otpCaptor = ArgumentCaptor.forClass(ElsOneTimePassword.class); var validityCaptor = ArgumentCaptor.forClass(Integer.class); verify(otpService, times(1)).createOtp(otpCaptor.capture(), validityCaptor.capture()); OneTimePassword cptOtp = otpCaptor.getValue(); ZonedDateTime expectedExpirationTime = ZonedDateTime.now(ZoneOffset.UTC) .plusHours(ppacConfiguration.getOtpValidityInHours()); ZonedDateTime actualExpirationTime = getZonedDateTimeFor(cptOtp.getExpirationTimestamp()); assertThat(validityCaptor.getValue()).isEqualTo(ppacConfiguration.getOtpValidityInHours()); assertThat(actualExpirationTime).isEqualToIgnoringSeconds(expectedExpirationTime); assertThat(cptOtp.getPassword()).isEqualTo(password); } @Test void testElsOtpServiceIsCalled() { PerDeviceDataResponse data = buildIosDeviceData(OffsetDateTime.now(), true); String password = <PASSWORD>(); when(iosDeviceApiClient.queryDeviceData(anyString(), any())).thenReturn(ResponseEntity.ok(jsonify(data))); when(jwtProvider.generateJwt()).thenReturn("secretkey"); postLogOtpCreationRequest(buildValidLogOtpPayload(password), testRestTemplate, IOS_LOG_OTP_URL, false); var otpCaptor = ArgumentCaptor.forClass(ElsOneTimePassword.class); var validityCaptor = ArgumentCaptor.forClass(Integer.class); verify(elsOtpService, times(1)).createOtp(otpCaptor.capture(), validityCaptor.capture()); ElsOneTimePassword cptOtp = otpCaptor.getValue(); ZonedDateTime expectedExpirationTime = ZonedDateTime.now(ZoneOffset.UTC) .plusHours(ppacConfiguration.getOtpValidityInHours()); ZonedDateTime actualExpirationTime = getZonedDateTimeFor(cptOtp.getExpirationTimestamp()); assertThat(validityCaptor.getValue()).isEqualTo(ppacConfiguration.getOtpValidityInHours()); assertThat(actualExpirationTime).isEqualToIgnoringSeconds(expectedExpirationTime); assertThat(cptOtp.getPassword()).isEqualTo(password); } @Test void testResponseIs400WhenOtpIsInvalidUuid() { PerDeviceDataResponse data = buildIosDeviceData(OffsetDateTime.now(), true); String password = "<PASSWORD>"; when(iosDeviceApiClient.queryDeviceData(anyString(), any())).thenReturn(ResponseEntity.ok(jsonify(data))); when(jwtProvider.generateJwt()).thenReturn("secretkey"); ResponseEntity<OtpCreationResponse> response = postOtpCreationRequest(buildValidOtpPayload(password), testRestTemplate, IOS_OTP_URL, false); assertThat(response.getStatusCode()).isEqualTo(BAD_REQUEST); } } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/InternalServerError.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; @SuppressWarnings("serial") public class InternalServerError extends RuntimeException { public InternalServerError(final Throwable cause) { super("Internal error occurred: " + cause.getMessage(), cause); } InternalServerError(String msg, final Throwable cause) { super(msg, cause); } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/testdata/MetricsMockData.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.testdata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ClientMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureRiskMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindow; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindowTestResult; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindowsAtTestRegistration; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithClientMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithUserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ScanInstance; import app.coronawarn.datadonation.common.persistence.domain.metrics.ScanInstancesAtTestRegistration; import app.coronawarn.datadonation.common.persistence.domain.metrics.SummarizedExposureWindowsWithUserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TestResultMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.UserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.ClientMetadataDetails; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails; import java.time.LocalDate; import java.util.List; import java.util.Set; import java.util.UUID; public final class MetricsMockData { private static final UserMetadataDetails mockUserMetadata = new UserMetadataDetails(2, 2, 3); private static final TechnicalMetadata mockTechnicalMetadata = new TechnicalMetadata(LocalDate.now(), true, true, true, true); private static final CwaVersionMetadata mockCwaVersionMetadata = new CwaVersionMetadata(1, 1, 1); private static final ClientMetadataDetails mockClientMetadata = new ClientMetadataDetails(mockCwaVersionMetadata, "eTag", 2, 2, 1, 2l, 3l); public static ExposureRiskMetadata getExposureRiskMetadataWithInvalidRiskLevel() { return new ExposureRiskMetadata(null, 4, true, LocalDate.now(), false, 4, true, LocalDate.now(), false, mockUserMetadata, mockTechnicalMetadata, mockCwaVersionMetadata); } public static ExposureRiskMetadata getExposureRiskMetadata() { return new ExposureRiskMetadata(null, 1, true, LocalDate.now(), false, 1, true, LocalDate.now(), false, mockUserMetadata, mockTechnicalMetadata, mockCwaVersionMetadata); } public static List<ExposureWindow> getExposureWindow() { return List.of(new ExposureWindow(null, LocalDate.now(), 1, 3, 2, 3, 4.54, mockClientMetadata, mockTechnicalMetadata, getScanInstances())); } public static List<TestResultMetadata> getTestResultMetric() { return List.of(new TestResultMetadata(null, 1, 2, 3, 4, 1, 1, 1, 1, mockUserMetadata, mockTechnicalMetadata, mockCwaVersionMetadata)); } public static List<KeySubmissionMetadataWithClientMetadata> getKeySubmissionWithClientMetadata() { return List.of(new KeySubmissionMetadataWithClientMetadata(null, true, true, false, false, true, 1, false, mockClientMetadata, mockTechnicalMetadata)); } public static List<KeySubmissionMetadataWithUserMetadata> getKeySubmissionWithUserMetadata() { return List.of(new KeySubmissionMetadataWithUserMetadata(null, true, true, false, false, 1, 2, 3, 4, 1, 1, mockUserMetadata, mockTechnicalMetadata, mockCwaVersionMetadata)); } public static UserMetadata getUserMetadata() { return new UserMetadata(null, mockUserMetadata, mockTechnicalMetadata); } public static ClientMetadata getClientMetadata() { return new ClientMetadata(null, mockClientMetadata, mockTechnicalMetadata); } private static Set<ScanInstance> getScanInstances() { return Set.of(new ScanInstance(null, null, 3, 4, 5, null), new ScanInstance(null, null, 6, 7, 7, null)); } public static List<ExposureWindowTestResult> getExposureWindowTestResults() { return List.of(new ExposureWindowTestResult(null, 2, mockClientMetadata, mockTechnicalMetadata, getExposureWindowsAtTestRegistration())); } private static Set<ExposureWindowsAtTestRegistration> getExposureWindowsAtTestRegistration() { return Set.of(new ExposureWindowsAtTestRegistration(null, null, LocalDate.now(), 3, 4, 3, 3, 4.56, getScanInstancesAtTestRegistration(), false, mockTechnicalMetadata)); } private static Set<ScanInstancesAtTestRegistration> getScanInstancesAtTestRegistration() { return Set.of(new ScanInstancesAtTestRegistration(null, null, 3, 4, 5, null), new ScanInstancesAtTestRegistration(null, null, 6, 7, 7, null)); } public static List<SummarizedExposureWindowsWithUserMetadata> getSummarizedExposureWindowsWithUserMetadata() { return List .of(new SummarizedExposureWindowsWithUserMetadata(null, LocalDate.now(), UUID.randomUUID().toString(), 3, 4.56, getUserMetadata().getUserMetadataDetails(), getUserMetadata().getTechnicalMetadata())); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/validation/DateInRange.java<|end_filename|> package app.coronawarn.datadonation.common.validation; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.time.LocalDate; import javax.validation.Constraint; import javax.validation.Payload; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Documented @Constraint(validatedBy = { DateInRangeValidator.class }) public @interface DateInRange { /** * Groups where potential violations should be kept together. */ Class<?>[] groups() default { }; /** * Payload. */ Class<? extends Payload>[] payload() default { }; /** * Date must be between {from} and {till}. */ String message() default "Date must be between {from} and {till}"; /** * Default if not set: {@link LocalDate#MIN}. */ String from() default ""; /** * Default if not set: {@link LocalDate#MAX}. */ String till() default ""; } <|start_filename|>services/edus/src/test/java/app/coronawarn/datadonation/services/edus/otp/StringUtils.java<|end_filename|> package app.coronawarn.datadonation.services.edus.otp; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class StringUtils { /** * Returns an stringified object. * * @param obj Object to be converted to string * @return Json String */ public static String asJsonString(final Object obj) throws JsonProcessingException { return new ObjectMapper().writeValueAsString(obj); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/config/ThirdPartyBeanRegistration.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.config; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Declare objects from third party libraries which are not component scanned as Spring beans. */ @Configuration public class ThirdPartyBeanRegistration { @Bean public DefaultHostnameVerifier hostnameVerifier() { return new DefaultHostnameVerifier(); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/config/SecurityLogger.java<|end_filename|> package app.coronawarn.datadonation.common.config; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public interface SecurityLogger { Marker SECURITY = MarkerFactory.getMarker("SECURITY"); void error(final Exception exception); void securityWarn(final Exception exception); void successAndroid(final String endpoint); void successIos(final String endpoint); } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/devicetoken/DeviceTokenService.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.devicetoken; import app.coronawarn.datadonation.common.persistence.domain.DeviceToken; import app.coronawarn.datadonation.common.persistence.repository.DeviceTokenRepository; import app.coronawarn.datadonation.common.utils.TimeUtils; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.springframework.data.relational.core.conversion.DbActionExecutionException; import org.springframework.stereotype.Service; @Service public class DeviceTokenService { private final DeviceTokenRepository deviceTokenRepository; private final DeviceTokenRedemptionStrategy redemptionStrategy; public DeviceTokenService(final DeviceTokenRepository deviceTokenRepository, final DeviceTokenRedemptionStrategy redemptionStrategy) { this.deviceTokenRepository = deviceTokenRepository; this.redemptionStrategy = redemptionStrategy; } /** * Hashes a given DeviceToken with 'SHA-256' and stores it together with the current epoch seconds in UTC. * * @param deviceToken The input DeviceToken. */ public void hashAndStoreDeviceToken(final String deviceToken) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-256"); final byte[] tokenHash = digest.digest(deviceToken.getBytes(StandardCharsets.UTF_8)); final DeviceToken newDeviceToken = new DeviceToken(tokenHash, TimeUtils.getEpochMilliSecondForNow()); deviceTokenRepository.save(newDeviceToken); } catch (DbActionExecutionException | NoSuchAlgorithmException e) { redemptionStrategy.redeem(e); } } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/OtpTestGenerationResponse.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; import com.fasterxml.jackson.annotation.JsonFormat; import java.time.ZonedDateTime; public class OtpTestGenerationResponse { @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX") private ZonedDateTime expirationDate; private String otp; public OtpTestGenerationResponse(ZonedDateTime expirationDate, String otp) { this.expirationDate = expirationDate; this.otp = otp; } public ZonedDateTime getExpirationDate() { return expirationDate; } public void setExpirationDate(ZonedDateTime expirationDate) { this.expirationDate = expirationDate; } public String getOtp() { return otp; } public void setOtp(String otp) { this.otp = otp; } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/BasicEvaluationTypeNotPresent.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class BasicEvaluationTypeNotPresent extends RuntimeException { private static final long serialVersionUID = -2513064483236579622L; public BasicEvaluationTypeNotPresent() { super("Evaluation Type BASIC not found in Android attestation response"); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/DeviceBlocked.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class DeviceBlocked extends RuntimeException { public DeviceBlocked() { super("PPAC failed due to blocked device"); } } <|start_filename|>services/els-verify/src/test/java/app/coronawarn/datadonation/services/els/otp/ElsOtpControllerTest.java<|end_filename|> package app.coronawarn.datadonation.services.els.otp; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import app.coronawarn.datadonation.common.persistence.domain.OneTimePassword; import org.junit.jupiter.api.Test; final class ElsOtpControllerTest { @Test void testCalculateStrongClientIntegrityCheckInvalid() { final OneTimePassword invalid = new OneTimePassword(null, null, null, true, null, null, null); assertFalse(ElsOtpController.calculateStrongClientIntegrityCheck(invalid)); } @Test void testCalculateStrongClientIntegrityCheckValidAndroid() { final OneTimePassword valid = new OneTimePassword(null, null, null, true, true, true, true); assertTrue(ElsOtpController.calculateStrongClientIntegrityCheck(valid)); } @Test void testCalculateStrongClientIntegrityCheckValidIos() { final OneTimePassword valid = new OneTimePassword(); assertTrue(ElsOtpController.calculateStrongClientIntegrityCheck(valid)); } @Test void testIsOtpFromIosDevice() { final OneTimePassword valid = new OneTimePassword(); assertTrue(ElsOtpController.isOtpFromIosDevice(valid)); } @Test void testIsOtpFromValidAndroidDevice() { final OneTimePassword valid = new OneTimePassword(null, null, null, true, true, true, true); assertTrue(ElsOtpController.isOtpFromValidAndroidDevice(valid)); } @Test void testOtpController() { ElsOtpController elsController = new ElsOtpController(null); assertThat(elsController).isNotNull(); } } <|start_filename|>services/edus/src/main/java/app/coronawarn/datadonation/services/edus/otp/OtpRedemptionResponse.java<|end_filename|> package app.coronawarn.datadonation.services.edus.otp; import app.coronawarn.datadonation.common.persistence.service.OtpState; public class OtpRedemptionResponse { private String otp; private OtpState state; private boolean strongClientIntegrityCheck; /** * Constructor. * * @param otp The one time password. * @param state The OTP state. * @param strongClientIntegrityCheck The strongClientIntegrityCheck. */ public OtpRedemptionResponse(String otp, OtpState state, boolean strongClientIntegrityCheck) { this.otp = otp; this.state = state; this.strongClientIntegrityCheck = strongClientIntegrityCheck; } public String getOtp() { return otp; } public void setOtp(String otp) { this.otp = otp; } public OtpState getState() { return state; } public void setState(OtpState state) { this.state = state; } public boolean isStrongClientIntegrityCheck() { return strongClientIntegrityCheck; } public void setStrongClientIntegrityCheck(boolean strongClientIntegrityCheck) { this.strongClientIntegrityCheck = strongClientIntegrityCheck; } } <|start_filename|>services/els-verify/src/test/java/app/coronawarn/datadonation/services/els/otp/ElsOtpRedemtionResponseTest.java<|end_filename|> package app.coronawarn.datadonation.services.els.otp; import static org.assertj.core.api.Assertions.assertThat; import app.coronawarn.datadonation.common.persistence.service.OtpState; import org.junit.jupiter.api.Test; class ElsOtpRedemtionResponseTest { @Test void modifyElsRedemptionResponseUsingSetters() { final String expValue = "eb1f6e7d-7824-421e-9810-ec7a706f9372"; ElsOtpRedemptionResponse elsOtpRedemptionResponse = new ElsOtpRedemptionResponse("eb1f6e7d-7824-421e-9810-ec7a706f9370", OtpState.VALID, true); elsOtpRedemptionResponse.setOtp(expValue); elsOtpRedemptionResponse.setState(OtpState.REDEEMED); elsOtpRedemptionResponse.setStrongClientIntegrityCheck(false); assertThat(elsOtpRedemptionResponse.getOtp()).isEqualTo(expValue); assertThat(elsOtpRedemptionResponse.getState()).isEqualTo(OtpState.REDEEMED); assertThat(elsOtpRedemptionResponse.isStrongClientIntegrityCheck()).isFalse(); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/controller/validation/PpaDataRequestIosPayloadValidator.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.controller.validation; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataRequestIOS; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import java.util.Base64; import java.util.UUID; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.stereotype.Component; @Component public class PpaDataRequestIosPayloadValidator implements ConstraintValidator<ValidPpaDataRequestIosPayload, PPADataRequestIOS> { private Integer minDeviceTokenLength; private Integer maxDeviceTokenLength; /** * Constructs a validator instance. */ public PpaDataRequestIosPayloadValidator(PpacConfiguration ppacConfiguration) { this.minDeviceTokenLength = ppacConfiguration.getIos().getMinDeviceTokenLength(); this.maxDeviceTokenLength = ppacConfiguration.getIos().getMaxDeviceTokenLength(); } @Override public boolean isValid(PPADataRequestIOS value, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); String deviceToken = value.getAuthentication().getDeviceToken(); String apiToken = value.getAuthentication().getApiToken(); return checkDeviceTokenIsBase64(deviceToken, context) && checkDeviceTokenLength(deviceToken, context) && checkApiTokenUuid(apiToken, context); } private boolean checkApiTokenUuid(String apiToken, ConstraintValidatorContext constraintValidatorContext) { try { UUID.fromString(apiToken); return true; } catch (final IllegalArgumentException e) { addViolation(constraintValidatorContext, "Api Token must a valid UUID v4 String"); return false; } } private boolean checkDeviceTokenLength(String deviceToken, ConstraintValidatorContext constraintValidatorContext) { boolean minLengthViolation = deviceToken.length() < this.minDeviceTokenLength; boolean maxLengthViolation = deviceToken.length() > this.maxDeviceTokenLength; boolean deviceTokenRangeViolation = minLengthViolation || maxLengthViolation; if (deviceTokenRangeViolation) { addViolation(constraintValidatorContext, String .format("Device token length must be in range %s and %s, but is %s", minDeviceTokenLength, maxDeviceTokenLength, deviceToken.length())); return false; } return true; } private boolean checkDeviceTokenIsBase64(String deviceToken, ConstraintValidatorContext constraintValidatorContext) { try { Base64.getDecoder().decode(deviceToken); return true; } catch (final IllegalArgumentException e) { addViolation(constraintValidatorContext, "Device Token must a valid base64 encoded String"); return false; } } private void addViolation(ConstraintValidatorContext validatorContext, String message) { validatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation(); } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/config/AndroidServiceConfigTest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.config; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; //TODO: Convert to full PPAC config test class AndroidConfigValidationTest { private Validator validator; @BeforeEach void setup() { validator = Validation.buildDefaultValidatorFactory().getValidator(); } @Test void testNonEmptyStringViolations() { PpacConfiguration.Android config = new PpacConfiguration.Android(); ConstraintViolation<PpacConfiguration.Android> error = validator.validate(config).stream().findAny().orElse(null); assertNotNull(error); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/controller/validation/ValidPpaDataRequestIosPayload.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.controller.validation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) @Constraint(validatedBy = PpaDataRequestIosPayloadValidator.class) @Documented //PPADataRequestIOS public @interface ValidPpaDataRequestIosPayload { /** * Validation message. */ String message() default "Invalid submission payload for ppac."; /** * Validation groups. */ Class<?>[] groups() default {}; /** * Payload type. */ Class<? extends Payload>[] payload() default {}; } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/ElsDeviceAttestationVerifier.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation; import app.coronawarn.datadonation.services.ppac.android.attestation.salt.SaltVerificationStrategy; import app.coronawarn.datadonation.services.ppac.android.attestation.signature.SignatureVerificationStrategy; import app.coronawarn.datadonation.services.ppac.android.attestation.timestamp.NoOpTimestampVerificationStrategy; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.springframework.stereotype.Component; /** * The implementation of this attestation verifier uses the original {@link DeviceAttestationVerifier} but skips the * device time check. */ @Component public class ElsDeviceAttestationVerifier extends DeviceAttestationVerifier { /** * Constructs a verifier instance. * * @param hostnameVerifier The host name verifier. * @param appParameters The configuration * @param saltVerificationStrategy The salt verification strategy * @param signatureVerificationStrategy The signature verification strategy * @param integrityValidator The integrity validator */ public ElsDeviceAttestationVerifier(DefaultHostnameVerifier hostnameVerifier, PpacConfiguration appParameters, SaltVerificationStrategy saltVerificationStrategy, SignatureVerificationStrategy signatureVerificationStrategy, PpacAndroidIntegrityValidator integrityValidator) { super(hostnameVerifier, appParameters, saltVerificationStrategy, signatureVerificationStrategy, new NoOpTimestampVerificationStrategy(), integrityValidator); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/signature/SignatureVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.signature; import com.google.api.client.json.webtoken.JsonWebSignature; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; public interface SignatureVerificationStrategy { /** * Verify that X509 certificates (chain) which are included in the 'x5c' header of the JWS (and * used to validate the JWS Signature) are trusted by the default JVM TrustManager. Parse and * return the leaf {@link X509Certificate} object in the chain in case it is verified. */ public X509Certificate verifySignature(JsonWebSignature jws) throws GeneralSecurityException; } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/attestation/TimeUtilsTest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation; import static app.coronawarn.datadonation.common.utils.TimeUtils.isInRange; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Instant; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class TimeUtilsTest { @ParameterizedTest @ValueSource(ints = {0, 1, 200, 5000, 7199, 7200}) void testWithDatesInRange(int presentOffset) { Instant present = Instant.now(); Instant upperLimit = present.plusSeconds(7200); Instant lowerLimit = present.minusSeconds(7200); Instant futureTimestamp = present.plusSeconds(presentOffset); assertTrue(isInRange(futureTimestamp.toEpochMilli(), lowerLimit, upperLimit)); Instant pastTimestamp = present.plusSeconds(presentOffset); assertTrue(isInRange(pastTimestamp.toEpochMilli(), lowerLimit, upperLimit)); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/PpacAndroidIntegrityValidator.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation; import static java.lang.Boolean.TRUE; import app.coronawarn.datadonation.services.ppac.android.attestation.AttestationStatement.EvaluationType; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.BasicEvaluationTypeNotPresent; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.BasicIntegrityIsRequired; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.CtsProfileMatchRequired; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.HardwareBackedEvaluationTypeNotPresent; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import org.springframework.stereotype.Component; @Component public class PpacAndroidIntegrityValidator { private final PpacConfiguration appParameters; public PpacAndroidIntegrityValidator(PpacConfiguration appParameters) { this.appParameters = appParameters; } /** * Validate integrity for a given AttestationStatement with the configuration for Otp/EDUS. * * @param attestationStatement the given attestation. */ public void validateIntegrityForEdus(AttestationStatement attestationStatement) { if (TRUE.equals(appParameters.getAndroid().getOtp().getRequireBasicIntegrity()) && !attestationStatement.isBasicIntegrity()) { throw new BasicIntegrityIsRequired(); } if (TRUE.equals(appParameters.getAndroid().getOtp().getRequireCtsProfileMatch()) && !attestationStatement.isCtsProfileMatch()) { throw new CtsProfileMatchRequired(); } if (TRUE.equals(appParameters.getAndroid().getOtp().getRequireEvaluationTypeBasic()) && !attestationStatement.isEvaluationTypeEqualTo(EvaluationType.BASIC)) { throw new BasicEvaluationTypeNotPresent(); } if (TRUE.equals(appParameters.getAndroid().getOtp().getRequireEvaluationTypeHardwareBacked()) && !attestationStatement.isEvaluationTypeEqualTo(EvaluationType.HARDWARE_BACKED)) { throw new HardwareBackedEvaluationTypeNotPresent(); } } /** * Validate integrity for a given AttestationStatement with the configuration for PPA. * * @param attestationStatement the given attestation. */ public void validateIntegrityForPpa(AttestationStatement attestationStatement) { if (TRUE.equals(appParameters.getAndroid().getDat().getRequireBasicIntegrity()) && !attestationStatement.isBasicIntegrity()) { throw new BasicIntegrityIsRequired(); } if (TRUE.equals(appParameters.getAndroid().getDat().getRequireCtsProfileMatch()) && !attestationStatement.isCtsProfileMatch()) { throw new CtsProfileMatchRequired(); } if (TRUE.equals(appParameters.getAndroid().getDat().getRequireEvaluationTypeBasic()) && !attestationStatement.isEvaluationTypeEqualTo(EvaluationType.BASIC)) { throw new BasicEvaluationTypeNotPresent(); } if (TRUE.equals(appParameters.getAndroid().getDat().getRequireEvaluationTypeHardwareBacked()) && !attestationStatement.isEvaluationTypeEqualTo(EvaluationType.HARDWARE_BACKED)) { throw new HardwareBackedEvaluationTypeNotPresent(); } } /** * Validate integrity for a given AttestationStatement with the configuration for ELS. * * @param attestationStatement the given attestation. */ public void validateIntegrityForEls(AttestationStatement attestationStatement) { if (TRUE.equals(appParameters.getAndroid().getLog().getRequireBasicIntegrity()) && !attestationStatement.isBasicIntegrity()) { throw new BasicIntegrityIsRequired(); } if (TRUE.equals(appParameters.getAndroid().getLog().getRequireCtsProfileMatch()) && !attestationStatement.isCtsProfileMatch()) { throw new CtsProfileMatchRequired(); } if (TRUE.equals(appParameters.getAndroid().getLog().getRequireEvaluationTypeBasic()) && !attestationStatement.isEvaluationTypeEqualTo(EvaluationType.BASIC)) { throw new BasicEvaluationTypeNotPresent(); } if (TRUE.equals(appParameters.getAndroid().getLog().getRequireEvaluationTypeHardwareBacked()) && !attestationStatement.isEvaluationTypeEqualTo(EvaluationType.HARDWARE_BACKED)) { throw new HardwareBackedEvaluationTypeNotPresent(); } } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/devicetoken/DeviceTokenRedemptionStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.devicetoken; public interface DeviceTokenRedemptionStrategy { /** * How to handle exceptions during OTP redemption. * * @param e {@link Exception} to be handled * @throws InternalError in case redemption fails */ void redeem(Exception e) throws InternalError; } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/attestation/PpacAndroidIntegrityValidatorTest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation; import static org.junit.jupiter.api.Assertions.assertThrows; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.BasicEvaluationTypeNotPresent; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.BasicIntegrityIsRequired; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.CtsProfileMatchRequired; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.HardwareBackedEvaluationTypeNotPresent; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration.Android; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration.Android.Dat; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration.Android.Log; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration.Android.Otp; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class PpacAndroidIntegrityValidatorTest { private PpacAndroidIntegrityValidator androidIntegrityValidator; private AttestationStatement attestationStatement; private Dat dat; private Log log; private Otp otp; @BeforeEach void beforeEach() { PpacConfiguration ppacConfiguration = new PpacConfiguration(); Android android = new Android(); dat = new Dat(); android.setDat(dat); log = new Log(); android.setLog(log); otp = new Otp(); android.setOtp(otp); ppacConfiguration.setAndroid(android); androidIntegrityValidator = new PpacAndroidIntegrityValidator(ppacConfiguration); attestationStatement = new AttestationStatement(); } @Test void testDatShouldThrowBasicIntegrityIsRequiredException() { dat.setRequireBasicIntegrity(true); assertThrows(BasicIntegrityIsRequired.class, () -> androidIntegrityValidator.validateIntegrityForPpa(attestationStatement)); } @Test void testDatShouldThrowCtsProfileRequiredException() { dat.setRequireCtsProfileMatch(true); assertThrows(CtsProfileMatchRequired.class, () -> androidIntegrityValidator.validateIntegrityForPpa(attestationStatement)); } @Test void testDatShouldThrowBasicEvaluationTypeNotPresentException() { dat.setRequireEvaluationTypeBasic(true); assertThrows(BasicEvaluationTypeNotPresent.class, () -> androidIntegrityValidator.validateIntegrityForPpa(attestationStatement)); } @Test void testDatShouldThrowHardwareBackedTypeNotPresentException() { dat.setRequireEvaluationTypeHardwareBacked(true); assertThrows(HardwareBackedEvaluationTypeNotPresent.class, () -> androidIntegrityValidator.validateIntegrityForPpa(attestationStatement)); } @Test void testNoDatValidationRequired() { androidIntegrityValidator.validateIntegrityForPpa(attestationStatement); } @Test void testOtpShouldThrowBasicIntegrityIsRequiredException() { otp.setRequireBasicIntegrity(true); assertThrows(BasicIntegrityIsRequired.class, () -> androidIntegrityValidator.validateIntegrityForEdus(attestationStatement)); } @Test void testOtpShouldThrowCtsProfileRequiredException() { otp.setRequireCtsProfileMatch(true); assertThrows(CtsProfileMatchRequired.class, () -> androidIntegrityValidator.validateIntegrityForEdus(attestationStatement)); } @Test void testOtpShouldThrowBasicEvaluationTypeNotPresentException() { otp.setRequireEvaluationTypeBasic(true); assertThrows(BasicEvaluationTypeNotPresent.class, () -> androidIntegrityValidator.validateIntegrityForEdus(attestationStatement)); } @Test void testOtpShouldThrowHardwareBackedTypeNotPresentException() { otp.setRequireEvaluationTypeHardwareBacked(true); assertThrows(HardwareBackedEvaluationTypeNotPresent.class, () -> androidIntegrityValidator.validateIntegrityForEdus(attestationStatement)); } @Test void testNoOtpValidationRequired() { androidIntegrityValidator.validateIntegrityForEdus(attestationStatement); } @Test void testLogShouldThrowBasicIntegrityIsRequiredException() { log.setRequireBasicIntegrity(true); assertThrows(BasicIntegrityIsRequired.class, () -> androidIntegrityValidator.validateIntegrityForEls(attestationStatement)); } @Test void testLogShouldThrowCtsProfileRequiredException() { log.setRequireCtsProfileMatch(true); assertThrows(CtsProfileMatchRequired.class, () -> androidIntegrityValidator.validateIntegrityForEls(attestationStatement)); } @Test void testLogShouldThrowBasicEvaluationTypeNotPresentException() { log.setRequireEvaluationTypeBasic(true); assertThrows(BasicEvaluationTypeNotPresent.class, () -> androidIntegrityValidator.validateIntegrityForEls(attestationStatement)); } @Test void testLogShouldThrowHardwareBackedTypeNotPresentException() { log.setRequireEvaluationTypeHardwareBacked(true); assertThrows(HardwareBackedEvaluationTypeNotPresent.class, () -> androidIntegrityValidator.validateIntegrityForEls(attestationStatement)); } @Test void testNoElsValidationRequired() { androidIntegrityValidator.validateIntegrityForEls(attestationStatement); } } <|start_filename|>services/els-verify/src/test/java/app/coronawarn/datadonation/services/els/otp/OtpRedemptionIntegrationTest.java<|end_filename|> package app.coronawarn.datadonation.services.els.otp; import static app.coronawarn.datadonation.services.els.otp.StringUtils.asJsonString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.openMocks; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; import app.coronawarn.datadonation.common.config.UrlConstants; import app.coronawarn.datadonation.common.persistence.domain.ElsOneTimePassword; import app.coronawarn.datadonation.common.persistence.repository.ElsOneTimePasswordRepository; import java.time.LocalDateTime; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext class OtpRedemptionIntegrationTest { private static final String VALID_UUID = "fb954b83-02ff-4cb7-8f07-fae2bcd64363"; private static final String LOG_OTP_REDEEM_URL = UrlConstants.SURVEY + UrlConstants.LOG; @MockBean ElsOneTimePasswordRepository elsOtpRepository; @Autowired private ElsOtpController elsOtpController; private MockMvc mockMvc; @BeforeEach public void setup() { openMocks(this); this.mockMvc = standaloneSetup(elsOtpController).setControllerAdvice(new ElsOtpControllerExceptionHandler()) .build(); } @Test void testShouldReturnResponseStatusCode200AndStateValidWhenLogOtpNotRedeemed() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); ElsOneTimePassword otp = new ElsOneTimePassword(VALID_UUID); otp.setExpirationTimestamp(LocalDateTime.now().plusDays(5)); when(elsOtpRepository.findById(any())).thenReturn(Optional.of(otp)); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("valid")); } @Test void testStrongClientIntegrityCheckForIos() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); ElsOneTimePassword otpWithValidIosStrongIntegrityCheck = createOtp(VALID_UUID, LocalDateTime.now().plusDays(5), null); otpWithValidIosStrongIntegrityCheck.setAndroidPpacBasicIntegrity(null); otpWithValidIosStrongIntegrityCheck.setAndroidPpacCtsProfileMatch(null); otpWithValidIosStrongIntegrityCheck.setAndroidPpacEvaluationTypeHardwareBacked(null); otpWithValidIosStrongIntegrityCheck.setAndroidPpacEvaluationTypeBasic(null); when(elsOtpRepository.findById(any())).thenReturn(Optional.of(otpWithValidIosStrongIntegrityCheck)); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("valid")) .andExpect(MockMvcResultMatchers.jsonPath("$.strongClientIntegrityCheck").value(true)); } @Test void testStrongClientIntegrityCheckForAndroid() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); ElsOneTimePassword otpWithValidAndroidStrongIntegrityCheck = createOtp(VALID_UUID, LocalDateTime.now().plusDays(5), null); otpWithValidAndroidStrongIntegrityCheck.setAndroidPpacBasicIntegrity(true); otpWithValidAndroidStrongIntegrityCheck.setAndroidPpacCtsProfileMatch(true); otpWithValidAndroidStrongIntegrityCheck.setAndroidPpacEvaluationTypeHardwareBacked(true); when(elsOtpRepository.findById(any())).thenReturn(Optional.of(otpWithValidAndroidStrongIntegrityCheck)); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("valid")) .andExpect(MockMvcResultMatchers.jsonPath("$.strongClientIntegrityCheck").value(true)); } @Test void testInvalidStrongClientIntegrityCheckForAndroid() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); ElsOneTimePassword otpWithInvalidAndroidStrongIntegrityCheck = createOtp(VALID_UUID, LocalDateTime.now().plusDays(5), null); otpWithInvalidAndroidStrongIntegrityCheck.setAndroidPpacBasicIntegrity(true); otpWithInvalidAndroidStrongIntegrityCheck.setAndroidPpacCtsProfileMatch(false); otpWithInvalidAndroidStrongIntegrityCheck.setAndroidPpacEvaluationTypeHardwareBacked(false); when(elsOtpRepository.findById(any())).thenReturn(Optional.of(otpWithInvalidAndroidStrongIntegrityCheck)); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("valid")) .andExpect(MockMvcResultMatchers.jsonPath("$.strongClientIntegrityCheck").value(false)); } @Test void testShouldReturnResponseStatusCodeUuidCaseInsensitive() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID.toUpperCase()); when(elsOtpRepository.findById(VALID_UUID.toLowerCase())) .thenReturn(Optional.of(createOtp(VALID_UUID.toLowerCase(), LocalDateTime.now().plusDays(5), null))); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("valid")); ArgumentCaptor<ElsOneTimePassword> argument = ArgumentCaptor.forClass(ElsOneTimePassword.class); verify(elsOtpRepository, times(1)).save(argument.capture()); assertEquals(VALID_UUID.toLowerCase(), argument.getValue().getPassword()); } @Test void testShouldReturnResponseStatusCode400WhenInvalidRequest() throws Exception { ElsOtpRedemptionRequest elsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); elsOtpRedemptionRequest.setOtp("invalid_otp_payload"); when(elsOtpRepository.findById(any())) .thenReturn(Optional.of(createOtp(VALID_UUID, LocalDateTime.now().plusDays(5)))); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(elsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test void testShouldReturnResponseStatusCode400AndOtpStateExpiredWhenExpiredOtp() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); when(elsOtpRepository.findById(any())) .thenReturn(Optional.of(createOtp(VALID_UUID, LocalDateTime.now().minusDays(1)))); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("expired")); } @Test void testShouldReturnResponseStatusCode400AndOtpStateRedeemedWhenAlreadyRedeemed() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); when(elsOtpRepository.findById(any())).thenReturn( Optional.of(createOtp(VALID_UUID, LocalDateTime.now().plusDays(5), LocalDateTime.now().minusDays(1)))); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("redeemed")); } @Test void testShouldReturnResponseStatusCode400AndOtpStateRedeemedWhenRedeemedAndExpired() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); when(elsOtpRepository.findById(any())).thenReturn( Optional.of(createOtp(VALID_UUID, LocalDateTime.now().minusDays(1), LocalDateTime.now().minusDays(1)))); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()).andExpect(MockMvcResultMatchers.jsonPath("$.state").value("redeemed")); } @Test void testShouldReturnResponseStatusCode404WhenOtpNotFound() throws Exception { ElsOtpRedemptionRequest elsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); elsOtpRedemptionRequest.setOtp(VALID_UUID); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(elsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test void databaseExceptionShouldReturnResponseStatusCode500() throws Exception { ElsOtpRedemptionRequest validElsOtpRedemptionRequest = new ElsOtpRedemptionRequest(); validElsOtpRedemptionRequest.setOtp(VALID_UUID); when(elsOtpRepository.findById(any())).thenThrow(new DataAccessResourceFailureException("")); mockMvc .perform(MockMvcRequestBuilders.post(LOG_OTP_REDEEM_URL).content(asJsonString(validElsOtpRedemptionRequest)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isInternalServerError()); } private ElsOneTimePassword createOtp(String uuid, LocalDateTime expirationTime) { return createOtp(uuid, expirationTime, null); } private ElsOneTimePassword createOtp(String uuid, LocalDateTime expirationTime, LocalDateTime redemptionTime) { ElsOneTimePassword otp = new ElsOneTimePassword(uuid); otp.setExpirationTimestamp(expirationTime); otp.setRedemptionTimestamp(redemptionTime); return otp; } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/validation/DateInRangeValidatorTest.java<|end_filename|> package app.coronawarn.datadonation.common.validation; import static java.time.LocalDate.EPOCH; import static java.time.LocalDate.MAX; import static java.time.LocalDate.MIN; import static java.time.LocalDate.now; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class DateInRangeValidatorTest { static Set<ConstraintViolation<ObjectWithDateMember>> validate(ObjectWithDateMember o) { return Validation.buildDefaultValidatorFactory().getValidator().validate(o); } @Test void testNull() { final ObjectWithDateMember o = new ObjectWithDateMember(); Set<ConstraintViolation<ObjectWithDateMember>> violations = validate(o); assertEquals(0, violations.size(), "Violations are not empty!"); o.setDateToBeValidatedNull(now()); violations = validate(o); assertEquals(0, violations.size(), "Violations are not empty!"); o.setDateToBeValidatedNull(MIN); violations = validate(o); assertEquals(0, violations.size(), "Violations are not empty!"); o.setDateToBeValidatedNull(MAX); violations = validate(o); assertEquals(0, violations.size(), "Violations are not empty!"); o.setDateToBeValidatedNull(EPOCH); violations = validate(o); assertEquals(0, violations.size(), "Violations are not empty!"); } @Test void testDateInRange() { final ObjectWithDateMember o = new ObjectWithDateMember(); o.setDateToBeValidated(now()); Set<ConstraintViolation<ObjectWithDateMember>> violations = validate(o); assertEquals(1, violations.size(), "Current date should violate the given range!"); assertEquals("Date must be between 1970-01-01 and 2000-01-01", violations.iterator().next().getMessage()); } @Test void testDateInRangeFrom() { final ObjectWithDateMember o = new ObjectWithDateMember(); o.setDateToBeValidatedFrom(MIN); Set<ConstraintViolation<ObjectWithDateMember>> violations = validate(o); assertEquals(1, violations.size(), MIN + " should violate the given range!"); assertEquals("Date must be after 1970-01-01", violations.iterator().next().getMessage()); } @Test void testDateInRangeTill() { final ObjectWithDateMember o = new ObjectWithDateMember(); o.setDateToBeValidatedTill(MAX); Set<ConstraintViolation<ObjectWithDateMember>> violations = validate(o); assertEquals(1, violations.size(), MAX + " should violate the given range!"); assertEquals("Date must be before 2000-01-01", violations.iterator().next().getMessage()); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/repository/metrics/KeySubmissionMetadataWithUserMetadataRepository.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithUserMetadata; import java.time.LocalDate; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; public interface KeySubmissionMetadataWithUserMetadataRepository extends CrudRepository<KeySubmissionMetadataWithUserMetadata, Long> { @Query("SELECT COUNT(*) FROM key_submission_metadata_with_user_metadata WHERE submitted_at < :threshold") int countOlderThan(@Param("threshold") LocalDate threshold); @Modifying @Query("DELETE FROM key_submission_metadata_with_user_metadata WHERE submitted_at < :threshold") void deleteOlderThan(@Param("threshold") LocalDate threshold); } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/logging/PpacErrorCode.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.logging; import app.coronawarn.datadonation.common.config.SecurityLogger; import java.util.function.BiConsumer; public enum PpacErrorCode { // iOS related error codes API_TOKEN_ALREADY_ISSUED(SecurityLogger::securityWarn), API_TOKEN_EXPIRED(SecurityLogger::securityWarn), API_TOKEN_QUOTA_EXCEEDED(SecurityLogger::securityWarn), DEVICE_BLOCKED(SecurityLogger::securityWarn), DEVICE_TOKEN_INVALID(SecurityLogger::securityWarn), DEVICE_TOKEN_REDEEMED(SecurityLogger::securityWarn), DEVICE_TOKEN_SYNTAX_ERROR(SecurityLogger::securityWarn), // Android related error codes APK_CERTIFICATE_MISMATCH(SecurityLogger::securityWarn), APK_PACKAGE_NAME_MISMATCH(SecurityLogger::securityWarn), ATTESTATION_EXPIRED(SecurityLogger::securityWarn), JWS_SIGNATURE_VERIFICATION_FAILED(SecurityLogger::securityWarn), NONCE_MISMATCH(SecurityLogger::securityWarn), SALT_REDEEMED(SecurityLogger::securityWarn), BASIC_INTEGRITY_REQUIRED(SecurityLogger::securityWarn), CTS_PROFILE_MATCH_REQUIRED(SecurityLogger::securityWarn), EVALUATION_TYPE_BASIC_REQUIRED(SecurityLogger::securityWarn), EVALUATION_TYPE_HARDWARE_BACKED_REQUIRED(SecurityLogger::securityWarn), MISSING_MANDATORY_AUTHENTICATION_FIELDS(SecurityLogger::securityWarn), FAILED_ATTESTATION_HOSTNAME_VALIDATION(SecurityLogger::securityWarn), // COMMONS METRICS_DATA_NOT_VALID(SecurityLogger::securityWarn), INTERNAL_SERVER_ERROR(SecurityLogger::error), UNKNOWN(SecurityLogger::error); private final BiConsumer<SecurityLogger, RuntimeException> logInvocation; PpacErrorCode(BiConsumer<SecurityLogger, RuntimeException> logInvocation) { this.logInvocation = logInvocation; } public void secureLog(SecurityLogger securityLogger, RuntimeException runtimeException) { this.logInvocation.accept(securityLogger, runtimeException); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/controller/IosApiErrorHandler.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.controller; import static app.coronawarn.datadonation.services.ppac.commons.web.DataSubmissionResponse.of; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.API_TOKEN_EXPIRED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.API_TOKEN_QUOTA_EXCEEDED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.DEVICE_BLOCKED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.DEVICE_TOKEN_INVALID; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.DEVICE_TOKEN_REDEEMED; import static app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode.DEVICE_TOKEN_SYNTAX_ERROR; import app.coronawarn.datadonation.common.config.SecurityLogger; import app.coronawarn.datadonation.services.ppac.commons.web.DataSubmissionResponse; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.ApiTokenAlreadyUsed; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.ApiTokenExpired; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.ApiTokenQuotaExceeded; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.DeviceBlocked; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.DeviceTokenInvalid; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.DeviceTokenRedeemed; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.DeviceTokenSyntaxError; import app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode; import java.util.Map; import javax.validation.ConstraintViolationException; import org.apache.catalina.connector.ClientAbortException; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE) public class IosApiErrorHandler extends ResponseEntityExceptionHandler { private SecurityLogger securityLogger; public IosApiErrorHandler(SecurityLogger securityLogger) { this.securityLogger = securityLogger; } private static final Map<Class<? extends RuntimeException>, PpacErrorCode> ERROR_CODES = Map.of(ApiTokenAlreadyUsed.class, PpacErrorCode.API_TOKEN_ALREADY_ISSUED, ApiTokenExpired.class, API_TOKEN_EXPIRED, DeviceTokenSyntaxError.class, DEVICE_TOKEN_SYNTAX_ERROR, DeviceTokenInvalid.class, DEVICE_TOKEN_INVALID, ConstraintViolationException.class, DEVICE_TOKEN_SYNTAX_ERROR, DeviceBlocked.class, DEVICE_BLOCKED, DeviceTokenRedeemed.class, DEVICE_TOKEN_REDEEMED, ApiTokenQuotaExceeded.class, API_TOKEN_QUOTA_EXCEEDED); @ExceptionHandler(value = {DeviceBlocked.class}) protected ResponseEntity<Object> handleAuthenticationErrors(RuntimeException e, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(e); errorCode.secureLog(securityLogger, e); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(of(errorCode)); } @ExceptionHandler(value = {DeviceTokenSyntaxError.class, ConstraintViolationException.class, DeviceTokenInvalid.class}) protected ResponseEntity<Object> handleBadRequests(RuntimeException e, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(e); errorCode.secureLog(securityLogger, e); return ResponseEntity.badRequest().body(of(errorCode)); } @ExceptionHandler(value = {ApiTokenExpired.class, ApiTokenAlreadyUsed.class, DeviceTokenRedeemed.class}) protected ResponseEntity<Object> handleForbiddenErrors(RuntimeException e, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(e); errorCode.secureLog(securityLogger, e); return ResponseEntity.status(HttpStatus.FORBIDDEN).body(of(errorCode)); } @ExceptionHandler(value = {ApiTokenQuotaExceeded.class}) protected ResponseEntity<DataSubmissionResponse> handleTooManyRequestsErrors(RuntimeException e, WebRequest webRequest) { final PpacErrorCode errorCode = getErrorCode(e); errorCode.secureLog(securityLogger, e); return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) .body(of(errorCode)); } @ExceptionHandler(ClientAbortException.class) @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE) public Object exceptionHandler(ClientAbortException exc) { return null; //socket is closed, cannot return any response } private PpacErrorCode getErrorCode(RuntimeException runtimeException) { return ERROR_CODES.getOrDefault(runtimeException.getClass(), PpacErrorCode.UNKNOWN); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/CtsProfileMatchRequired.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class CtsProfileMatchRequired extends RuntimeException { private static final long serialVersionUID = 3672399350081903614L; public CtsProfileMatchRequired() { super("Cts profile match required in Android attestation response"); } } <|start_filename|>services/edus/src/main/java/app/coronawarn/datadonation/services/edus/otp/OtpState.java<|end_filename|> package app.coronawarn.datadonation.services.edus.otp; import com.fasterxml.jackson.annotation.JsonValue; public enum OtpState { EXPIRED("expired"), REDEEMED("redeemed"), VALID("valid"); private String state; OtpState(String state) { this.state = state; } @JsonValue final String state() { return this.state; } @Override public String toString() { return state; } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/signature/ProdSignatureVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.signature; import com.google.api.client.json.webtoken.JsonWebSignature; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import org.springframework.stereotype.Component; @Component public class ProdSignatureVerificationStrategy implements SignatureVerificationStrategy { /** * Verify using the default JVM TrustManager that contains all Root CA certificate chains. This is * currently based on the internal implementation from the Google library used. */ @Override public X509Certificate verifySignature(JsonWebSignature jws) throws GeneralSecurityException { return jws.verifySignature(); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/validation/DateInRangeValidator.java<|end_filename|> package app.coronawarn.datadonation.common.validation; import static org.springframework.util.ObjectUtils.isEmpty; import java.time.LocalDate; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class DateInRangeValidator implements ConstraintValidator<DateInRange, LocalDate> { protected LocalDate from = LocalDate.MIN; protected LocalDate till = LocalDate.MAX; @Override public void initialize(final DateInRange annotation) { if (!isEmpty(annotation.from())) { from = LocalDate.parse(annotation.from()); } if (!isEmpty(annotation.till())) { till = LocalDate.parse(annotation.till()); } assert from == null || till == null || from.isBefore(till) : "{from: " + from + "} is not before {till: " + till + "}"; } @Override public boolean isValid(final LocalDate date, final ConstraintValidatorContext context) { // null values are valid if (date == null) { return true; } return (from.isBefore(date) || from.isEqual(date)) && (till.isEqual(date) || till.isAfter(date)); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/ExternalServiceError.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; import feign.FeignException; @SuppressWarnings("serial") public class ExternalServiceError extends InternalServerError { public ExternalServiceError(FeignException cause) { super("Responded with HTTP-" + cause.status() + ": " + cause.getMessage(), cause); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/timestamp/TimestampVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.timestamp; public interface TimestampVerificationStrategy { void validateTimestamp(long attestationTimestamp); } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/timestamp/NoOpTimestampVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.timestamp; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("loadtest") public final class NoOpTimestampVerificationStrategy implements TimestampVerificationStrategy { @Override public void validateTimestamp(long attestationTimestamp) { // do nothing during load testing } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/timestamp/ProdTimestampVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.timestamp; import static app.coronawarn.datadonation.common.utils.TimeUtils.isInRange; import app.coronawarn.datadonation.services.ppac.android.attestation.errors.FailedAttestationTimestampValidation; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import java.time.Instant; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("!loadtest") public final class ProdTimestampVerificationStrategy implements TimestampVerificationStrategy { private final PpacConfiguration appParameters; public ProdTimestampVerificationStrategy(PpacConfiguration config) { this.appParameters = config; } @Override public void validateTimestamp(long timestampMs) { Integer attestationValidity = appParameters.getAndroid().getAttestationValidity(); Instant present = Instant.now(); Instant upperLimit = present.plusSeconds(attestationValidity); Instant lowerLimit = present.minusSeconds(attestationValidity); if (!isInRange(timestampMs, lowerLimit, upperLimit)) { throw new FailedAttestationTimestampValidation(); } } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/errors/ApiTokenQuotaExceeded.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.errors; public class ApiTokenQuotaExceeded extends RuntimeException { public ApiTokenQuotaExceeded() { super("PPAC failed due to Api Token quota exceeded"); } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/controller/RequestExecutor.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.controller; import static app.coronawarn.datadonation.common.config.UrlConstants.ANDROID; import static app.coronawarn.datadonation.common.config.UrlConstants.DATA; import static app.coronawarn.datadonation.common.config.UrlConstants.LOG; import static app.coronawarn.datadonation.common.config.UrlConstants.OTP; import app.coronawarn.datadonation.common.persistence.service.OtpCreationResponse; import app.coronawarn.datadonation.common.protocols.internal.ppdd.EDUSOneTimePasswordRequestAndroid; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ELSOneTimePasswordRequestAndroid; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataRequestAndroid; import app.coronawarn.datadonation.services.ppac.commons.web.DataSubmissionResponse; import java.net.URI; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; /** * RequestExecutor executes requests against the diagnosis key submission endpoint and holds a * various methods for test request generation. */ public class RequestExecutor { private static final URI ANDROID_DATA_URL = URI.create(ANDROID + DATA); private static final URI ANDROID_OTP_URL = URI.create(ANDROID + OTP); private static final URI ANDROID_ELS_OTP_URL = URI.create(ANDROID + LOG); private final TestRestTemplate testRestTemplate; public RequestExecutor(TestRestTemplate testRestTemplate) { this.testRestTemplate = testRestTemplate; } public ResponseEntity<DataSubmissionResponse> execute(HttpMethod method, RequestEntity<PPADataRequestAndroid> requestEntity) { return testRestTemplate.exchange(ANDROID_DATA_URL, method, requestEntity, DataSubmissionResponse.class); } public ResponseEntity<OtpCreationResponse> executeOtp(HttpMethod method, RequestEntity<EDUSOneTimePasswordRequestAndroid> requestEntity) { return testRestTemplate.exchange(ANDROID_OTP_URL, method, requestEntity, OtpCreationResponse.class); } public ResponseEntity<OtpCreationResponse> executeElsOtp(HttpMethod method, RequestEntity<ELSOneTimePasswordRequestAndroid> requestEntity) { return testRestTemplate.exchange(ANDROID_ELS_OTP_URL, method, requestEntity, OtpCreationResponse.class); } public ResponseEntity<DataSubmissionResponse> executePost(PPADataRequestAndroid body, HttpHeaders headers) { return execute(HttpMethod.POST, new RequestEntity<>(body, headers, HttpMethod.POST, ANDROID_DATA_URL)); } public ResponseEntity<OtpCreationResponse> executeOtpPost(EDUSOneTimePasswordRequestAndroid body, HttpHeaders headers) { return executeOtp(HttpMethod.POST, new RequestEntity<>(body, headers, HttpMethod.POST, ANDROID_OTP_URL)); } public ResponseEntity<OtpCreationResponse> executeOtpPost(ELSOneTimePasswordRequestAndroid body, HttpHeaders headers) { return executeElsOtp(HttpMethod.POST, new RequestEntity<>(body, headers, HttpMethod.POST, ANDROID_ELS_OTP_URL)); } public ResponseEntity<DataSubmissionResponse> executePost(PPADataRequestAndroid body) { return executePost(body, buildDefaultHeader()); } public ResponseEntity<OtpCreationResponse> executeOtpPost(EDUSOneTimePasswordRequestAndroid body) { return executeOtpPost(body, buildDefaultHeader()); } public ResponseEntity<OtpCreationResponse> executeOtpPost(ELSOneTimePasswordRequestAndroid body) { return executeOtpPost(body, buildDefaultHeader()); } private HttpHeaders buildDefaultHeader() { return new HttpHeaders(); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/ElsOtpService.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; import app.coronawarn.datadonation.common.persistence.domain.ElsOneTimePassword; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Service; @Service public class ElsOtpService extends AbstractOtpService<ElsOneTimePassword> { /** * Constructs the ElsOtpService. * * @param otpRepository The OTP Repository. */ protected ElsOtpService(CrudRepository<ElsOneTimePassword, String> otpRepository) { super(otpRepository); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/BasicIntegrityIsRequired.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public class BasicIntegrityIsRequired extends RuntimeException { private static final long serialVersionUID = 2664915373178687868L; public BasicIntegrityIsRequired() { super("Basic Integrity is required in Android attestation response"); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/repository/DeviceTokenRepository.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository; import app.coronawarn.datadonation.common.persistence.domain.DeviceToken; import java.util.Optional; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; /** * <code>created_at</code> time in <strong>milliseconds</strong> since epoch. */ @Repository public interface DeviceTokenRepository extends CrudRepository<DeviceToken, Long> { @Query("SELECT * FROM device_token d WHERE d.device_token_hash = :deviceTokenHash ") Optional<DeviceToken> findByDeviceTokenHash(@Param("deviceTokenHash") byte[] deviceToken); @Modifying @Query("delete from device_token where created_at < :threshold") void deleteOlderThan(@Param("threshold") long threshold); @Query("select count(*) from device_token where created_at < :threshold") int countOlderThan(@Param("threshold") long threshold); @Modifying @Query("insert into device_token (id,device_token_hash,created_at)" + "values(:id,:deviceTokenHash,:createdAt)") void persist(@Param("id") Long id, @Param("deviceTokenHash") byte[] deviceTokenHash, @Param("createdAt") long createdAt); } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/verification/devicedata/ProdPerDeviceDataValidator.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.verification.devicedata; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import app.coronawarn.datadonation.services.ppac.ios.client.IosDeviceApiClient; import app.coronawarn.datadonation.services.ppac.ios.verification.JwtProvider; import app.coronawarn.datadonation.services.ppac.ios.verification.devicetoken.DeviceTokenService; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.DeviceTokenInvalid; import app.coronawarn.datadonation.services.ppac.ios.verification.errors.ExternalServiceError; import feign.FeignException; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("!loadtest") public class ProdPerDeviceDataValidator extends PerDeviceDataValidator { public ProdPerDeviceDataValidator(IosDeviceApiClient iosDeviceApiClient, JwtProvider jwtProvider, DeviceTokenService deviceTokenService, PpacConfiguration ppacConfiguration) { super(iosDeviceApiClient, jwtProvider, deviceTokenService, ppacConfiguration); } @Override protected void treatBadRequest(FeignException.BadRequest e) { if (isBadDeviceToken(e.contentUTF8())) { throw new DeviceTokenInvalid(); } throw new ExternalServiceError(e); } private boolean isBadDeviceToken(String message) { final String missingOrIncorrectlyFormattedDeviceTokenPayload = ppacConfiguration.getIos().getMissingOrIncorrectlyFormattedDeviceTokenPayload(); return missingOrIncorrectlyFormattedDeviceTokenPayload.toLowerCase() .contains(message.toLowerCase()); } @Override protected void treatGeneralRequestError(FeignException e) { throw new ExternalServiceError(e); } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/config/TestBeanConfig.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.config; import app.coronawarn.datadonation.services.ppac.android.controller.RequestExecutor; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestBeanConfig { @Bean public RequestExecutor requestExecutor(TestRestTemplate testRestTemplate) { return new RequestExecutor(testRestTemplate); } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/attestation/TestSignatureVerificationStrategy.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation; import com.google.api.client.json.webtoken.JsonWebSignature; import app.coronawarn.datadonation.services.ppac.android.attestation.signature.SignatureVerificationStrategy; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; public class TestSignatureVerificationStrategy implements SignatureVerificationStrategy { private X509Certificate certificate; public TestSignatureVerificationStrategy(X509Certificate certificate) { this.certificate = certificate; } /** * Just return the configured test related certificate as if it were trusted by the platform's * TrustManagers. */ @Override public X509Certificate verifySignature(JsonWebSignature jws) throws GeneralSecurityException { return this.certificate; } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/persistence/repository/metrics/TestResultMetadataRepositoryTest.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TestResultMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails; import java.time.LocalDate; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class TestResultMetadataRepositoryTest { @Autowired private TestResultMetadataRepository testResultMetadataRepository; @AfterEach void tearDown() { testResultMetadataRepository.deleteAll(); } @Test void testResultMetadataShouldBePersistedCorrectly() { CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(1, 1, 1); TestResultMetadata testResultMetadata = new TestResultMetadata(null, 1, 2, 3, 4, 5, 1, 1, 1, new UserMetadataDetails(1, 2, 2), new TechnicalMetadata(LocalDate.now(), true, true, false, false), cwaVersionMetadata); testResultMetadataRepository.save(testResultMetadata); TestResultMetadata loadedEntity = testResultMetadataRepository.findAll().iterator().next(); assertEquals(loadedEntity.getUserMetadata(), testResultMetadata.getUserMetadata()); assertEquals(loadedEntity.getDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(), testResultMetadata.getDaysSinceMostRecentDateAtRiskLevelAtTestRegistration()); assertEquals(loadedEntity.getHoursSinceHighRiskWarningAtTestRegistration(), testResultMetadata.getHoursSinceHighRiskWarningAtTestRegistration()); assertEquals(loadedEntity.getHoursSinceTestRegistration(), testResultMetadata.getHoursSinceTestRegistration()); assertEquals(loadedEntity.getRiskLevelAtTestRegistration(), testResultMetadata.getRiskLevelAtTestRegistration()); assertEquals(loadedEntity.getPtHoursSinceHighRiskWarning(), testResultMetadata.getPtHoursSinceHighRiskWarning()); assertEquals(loadedEntity.getPtRiskLevel(), testResultMetadata.getPtRiskLevel()); assertEquals(loadedEntity.getPtDaysSinceMostRecentDateAtRiskLevel(), testResultMetadata.getPtDaysSinceMostRecentDateAtRiskLevel()); assertEquals(loadedEntity.getTechnicalMetadata(), testResultMetadata.getTechnicalMetadata()); assertEquals(loadedEntity.getTestResult(), testResultMetadata.getTestResult()); assertNotNull(loadedEntity.getId()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionPatch(), cwaVersionMetadata.getCwaVersionPatch()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionMajor(), cwaVersionMetadata.getCwaVersionMajor()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionMinor(), cwaVersionMetadata.getCwaVersionMinor()); } } <|start_filename|>services/retention/src/test/java/app/coronawarn/datadonation/services/retention/TestData.java<|end_filename|> package app.coronawarn.datadonation.services.retention; import static java.time.Instant.now; import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.HOURS; import app.coronawarn.datadonation.common.persistence.domain.metrics.ClientMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureRiskMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindow; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindowTestResult; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindowsAtTestRegistration; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithClientMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithUserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.ScanInstance; import app.coronawarn.datadonation.common.persistence.domain.metrics.ScanInstancesAtTestRegistration; import app.coronawarn.datadonation.common.persistence.domain.metrics.SummarizedExposureWindowsWithUserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TestResultMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.UserMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.ClientMetadataDetails; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails; import app.coronawarn.datadonation.common.persistence.repository.ApiTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.DeviceTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.ElsOneTimePasswordRepository; import app.coronawarn.datadonation.common.persistence.repository.OneTimePasswordRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ClientMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureRiskMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowTestResultsRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowsAtTestRegistrationRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.KeySubmissionMetadataWithClientMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.KeySubmissionMetadataWithUserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ScanInstancesAtTestRegistrationRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.SummarizedExposureWindowsWithUserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.TestResultMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.UserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.ppac.android.SaltRepository; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.ZoneOffset; import java.util.Set; import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.test.context.ActiveProfiles; @Component @Order(-1) @ActiveProfiles("test") public class TestData implements ApplicationRunner { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private ApiTokenRepository apiTokenRepository; @Autowired private DeviceTokenRepository deviceTokenRepository; @Autowired private OneTimePasswordRepository otpRepository; @Autowired private ElsOneTimePasswordRepository elsOtpRepository; @Autowired private SaltRepository saltRepository; @Autowired private ExposureRiskMetadataRepository exposureRiskMetadataRepository; @Autowired private ExposureWindowRepository exposureWindowRepository; @Autowired private KeySubmissionMetadataWithClientMetadataRepository keySubmissionWithClientMetadataRepository; @Autowired private KeySubmissionMetadataWithUserMetadataRepository keySubmissionWithUserMetadataDetailsRepository; @Autowired private TestResultMetadataRepository testResultMetadataRepository; @Autowired private ClientMetadataRepository clientMetadataRepository; @Autowired private UserMetadataRepository userMetadataRepository; @Autowired private ExposureWindowsAtTestRegistrationRepository exposureWindowsAtTestRegistrationRepository; @Autowired private ExposureWindowTestResultsRepository exposureWindowTestResultsRepository; @Autowired private SummarizedExposureWindowsWithUserMetadataRepository summarizedExposureWindowsWithUserMetadataRepository; @Autowired private ScanInstancesAtTestRegistrationRepository scanInstancesAtTestRegistrationRepository; @Override public void run(ApplicationArguments args) { logger.info("Generating test data"); IntStream.range(0, 35) .peek(this::insertApiToken) .peek(this::insertExposureRiskMetadata) .peek(this::insertExposureWindows) .peek(this::insertKeySubmissionMetadataWithClient) .peek(this::insertKeySubmissionMetadataWithUser) .peek(this::insertTestResultMetadata) .peek(this::insertDeviceTokens) .peek(this::insertOtps) .peek(this::insertElsOtps) .peek(this::insertClientMetadata) .peek(this::insertSalt) .peek(this::insertExposureWindowsAtTestRegistration) .peek(this::insertExposureWindowTestResult) .peek(this::insertSummarizedExposureWindowsWithUserMetadata) .peek(this::insertScanInstancesAtTestRegistration) .forEach(this::insertUserMetadata); logger.info("Finished generating test data"); } private void insertUserMetadata(int i) { UserMetadata userMetadata = new UserMetadata(null, new UserMetadataDetails(1, 1, 1), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false)); userMetadataRepository.save(userMetadata); } private void insertClientMetadata(int i) { ClientMetadata clientMetadata = new ClientMetadata(null, new ClientMetadataDetails(new CwaVersionMetadata(1, 0, 0), "etag", 1, 0, 0, 1l, 1l), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false)); clientMetadataRepository.save(clientMetadata); } private void insertSalt(int i) { saltRepository.persist("salt" + i, now().minus(i, HOURS).toEpochMilli()); } private void insertOtps(int i) { otpRepository.insert("passwordA" + i, now().minus(i, DAYS).getEpochSecond(), now().getEpochSecond()); otpRepository.insert("passwordB" + i, now().getEpochSecond(), now().minus(i, DAYS).getEpochSecond()); } private void insertElsOtps(int i) { elsOtpRepository.insert("ELSPassword" + i, now().minus(i, DAYS).getEpochSecond(), now().getEpochSecond()); } private void insertDeviceTokens(int i) { deviceTokenRepository.persist((long) i, ("" + i).getBytes(StandardCharsets.UTF_8), now().minus(i, HOURS).toEpochMilli()); } private void insertTestResultMetadata(int i) { TestResultMetadata trm = new TestResultMetadata(null, 1, 1, 1, 1, 1, 1, 1, 1, new UserMetadataDetails(1, 1, 1), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false), new CwaVersionMetadata(1, 1, 1)); testResultMetadataRepository.save(trm); } private void insertKeySubmissionMetadataWithUser(int i) { KeySubmissionMetadataWithUserMetadata UserMetadataDetails = new KeySubmissionMetadataWithUserMetadata(null, true, false, false, false, 1, 1, 1, 1, null, null, new app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails(1, 1, 1), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false), new CwaVersionMetadata(1, 1, 1)); keySubmissionWithUserMetadataDetailsRepository.save(UserMetadataDetails); } private void insertKeySubmissionMetadataWithClient(int i) { KeySubmissionMetadataWithClientMetadata clientMetadata = new KeySubmissionMetadataWithClientMetadata(null, true, true, false, false, false, 1, false, new ClientMetadataDetails(new CwaVersionMetadata(1, 1, 1), "etag", 1, 0, 0, 1l, 1l), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false)); keySubmissionWithClientMetadataRepository.save(clientMetadata); } private void insertExposureWindows(int i) { ExposureWindow ew = new ExposureWindow(null, LocalDate.now(ZoneOffset.UTC).minusDays(i + 1), 1, 2, 1, 1, 1.0, new ClientMetadataDetails(new CwaVersionMetadata(1, 1, 1), "etag", 1, 0, 0, 1l, 1l), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false), Set.of(new ScanInstance(null, null, 1, 2, 3, null), new ScanInstance(null, null, 3, 3, 3, null))); exposureWindowRepository.save(ew); } private void insertExposureWindowsAtTestRegistration(int i) { ExposureWindowsAtTestRegistration ewTestRegistration = new ExposureWindowsAtTestRegistration(null, 1, LocalDate.now(ZoneOffset.UTC), 1, 2, 1, 1, 1.0, Set.of(new ScanInstancesAtTestRegistration(null, null, 1, 2, 3, new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false))), false, new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false)); exposureWindowsAtTestRegistrationRepository.save(ewTestRegistration); } private void insertExposureWindowTestResult(int i) { ExposureWindowTestResult ewTestResult = new ExposureWindowTestResult(null, 1, new ClientMetadataDetails(new CwaVersionMetadata(1, 1, 1), "etag", 1, 0, 0, 1l, 1l), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false), Set.of( new ExposureWindowsAtTestRegistration(null, 1, LocalDate.now(ZoneOffset.UTC), 1, 2, 1, 1, 1.0, Set.of(new ScanInstancesAtTestRegistration(null, null, 1, 2, 3, new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false))), false, new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false)))); exposureWindowTestResultsRepository.save(ewTestResult); } private void insertSummarizedExposureWindowsWithUserMetadata(int i) { SummarizedExposureWindowsWithUserMetadata summarizedExposureWindowsWithUserMetadata = new SummarizedExposureWindowsWithUserMetadata( null, LocalDate.now(ZoneOffset.UTC), "", 1, 1.0, new UserMetadataDetails(1, 1, 1), new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false)); summarizedExposureWindowsWithUserMetadataRepository.save(summarizedExposureWindowsWithUserMetadata); } private void insertScanInstancesAtTestRegistration(int i) { ScanInstancesAtTestRegistration scanInstancesAtTestRegistration = new ScanInstancesAtTestRegistration(null, 1, 1, 1, 1, new TechnicalMetadata((LocalDate.now(ZoneOffset.UTC).minusDays(i)), false, false, false, false)); scanInstancesAtTestRegistrationRepository.save(scanInstancesAtTestRegistration); } private void insertExposureRiskMetadata(int i) { TechnicalMetadata tm = new TechnicalMetadata(LocalDate.now(ZoneOffset.UTC).minusDays(i), false, false, false, false); UserMetadataDetails um = new UserMetadataDetails(1, 1, 1); ExposureRiskMetadata erm = new ExposureRiskMetadata(null, 1, false, LocalDate.now(ZoneOffset.UTC).minusDays(i), false, 1, false, LocalDate.now(ZoneOffset.UTC).minusDays(i), false, um, tm, new CwaVersionMetadata(1, 1, 1)); exposureRiskMetadataRepository.save(erm); } private void insertApiToken(int i) { long theNewNormal = now().minus(i, DAYS).getEpochSecond(); apiTokenRepository.insert("test token" + i, theNewNormal, theNewNormal, theNewNormal, theNewNormal); } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/OtpCreationResponse.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; import com.fasterxml.jackson.annotation.JsonFormat; import java.time.ZonedDateTime; public class OtpCreationResponse { @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX") private ZonedDateTime expirationDate; public OtpCreationResponse() { // empty constructor } public OtpCreationResponse(ZonedDateTime expirationDate) { this.expirationDate = expirationDate; } public ZonedDateTime getExpirationDate() { return expirationDate; } public void setExpirationDate(ZonedDateTime expirationDate) { this.expirationDate = expirationDate; } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/android/controller/PpaDataRequestAndroidConverterTest.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.controller; import static app.coronawarn.datadonation.common.protocols.internal.ppdd.PPARiskLevel.RISK_LEVEL_HIGH; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureWindowTestResult; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.ClientMetadataDetails; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import app.coronawarn.datadonation.common.persistence.service.PpaDataStorageRequest; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ExposureRiskMetadata; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAClientMetadataAndroid; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataAndroid; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataRequestAndroid; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataRequestIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAExposureWindow; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAExposureWindowInfectiousness; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPANewExposureWindow; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPARiskLevel; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPASemanticVersion; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPATestResult; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPATestResultMetadata; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAUserMetadata; import app.coronawarn.datadonation.common.utils.TimeUtils; import app.coronawarn.datadonation.services.ppac.android.attestation.AttestationStatement; import app.coronawarn.datadonation.services.ppac.config.PpacConfiguration; import java.time.LocalDate; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; @ExtendWith(MockitoExtension.class) public class PpaDataRequestAndroidConverterTest extends PpaDataRequestAndroidConverter { private PpacConfiguration ppacConfig; @InjectMocks private AttestationStatement attestationStatement; @BeforeEach public void setup() { ppacConfig = new PpacConfiguration(); //The maximum number of exposure windows to store per submission. //672 = 24 hours per day * 0,5 hours per Exposure Window * 14 days ppacConfig.setMaxExposureWindowsToRejectSubmission(672); ppacConfig.setMaxExposureWindowsToStore(672); } @Test public void convertToExposureMetricsTestRiskLevelUnknownValue() { ExposureRiskMetadata exposureRiskMetadata = ExposureRiskMetadata.newBuilder() .setPtRiskLevelValue(PPARiskLevel.RISK_LEVEL_UNKNOWN_VALUE).build(); app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureRiskMetadata dbExposureRiskMetadata = convertToExposureMetrics( Collections.singletonList(exposureRiskMetadata), PPAUserMetadata.getDefaultInstance(), TechnicalMetadata.newEmptyInstance(), PPAClientMetadataAndroid.getDefaultInstance()); assertNull(dbExposureRiskMetadata.getPtRiskLevelChanged()); assertNull(dbExposureRiskMetadata.getPtMostRecentDateAtRiskLevel()); assertNull(dbExposureRiskMetadata.getPtMostRecentDateChanged()); } @Test public void convertToExposureMetricsTest() { ExposureRiskMetadata exposureRiskMetadata = ExposureRiskMetadata.newBuilder() .setPtRiskLevelValue(PPARiskLevel.RISK_LEVEL_HIGH_VALUE) .setPtRiskLevelChangedComparedToPreviousSubmission(true) .setPtMostRecentDateAtRiskLevel(0) .setPtDateChangedComparedToPreviousSubmission(false) .build(); PPASemanticVersion semanticVersion = PPASemanticVersion.newBuilder().setMajor(2).setMinor(2).setPatch(1).build(); app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureRiskMetadata dbExposureRiskMetadata = convertToExposureMetrics( Collections.singletonList(exposureRiskMetadata), PPAUserMetadata.getDefaultInstance(), TechnicalMetadata.newEmptyInstance(), PPAClientMetadataAndroid.newBuilder().setAndroidApiLevel(1) .setCwaVersion(semanticVersion).build() ); assertTrue(dbExposureRiskMetadata.getPtRiskLevelChanged()); assertEquals(LocalDate.of(1970, 1, 1), dbExposureRiskMetadata.getPtMostRecentDateAtRiskLevel()); assertFalse(dbExposureRiskMetadata.getPtMostRecentDateChanged()); } @ParameterizedTest @EnumSource(value = PPATestResult.class, names = {"TEST_RESULT_POSITIVE", "TEST_RESULT_NEGATIVE", "TEST_RESULT_RAT_POSITIVE", "TEST_RESULT_RAT_NEGATIVE"}) public void testConvertToExposureWindowTestResults(PPATestResult ppaTestResults) { final Long epochSecondForNow = TimeUtils.getEpochSecondsForNow(); final PPAExposureWindow ppaExposureWindow = PPAExposureWindow .newBuilder() .setCalibrationConfidence(1) .setInfectiousness(PPAExposureWindowInfectiousness.INFECTIOUSNESS_HIGH) .setDate(epochSecondForNow) .build(); final PPANewExposureWindow ppaNewExposureWindow = PPANewExposureWindow .newBuilder() .setExposureWindow(ppaExposureWindow) .build(); final PPATestResultMetadata ppaTestResultMetadata = PPATestResultMetadata.newBuilder() .setTestResult(ppaTestResults) .setRiskLevelAtTestRegistration(RISK_LEVEL_HIGH) .setHoursSinceTestRegistration(5) .setHoursSinceHighRiskWarningAtTestRegistration(5) .setDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(5) .addExposureWindowsAtTestRegistration(ppaNewExposureWindow) .addExposureWindowsUntilTestResult(ppaNewExposureWindow) .build(); final PPADataAndroid payload = PPADataAndroid.newBuilder() .addTestResultMetadataSet(ppaTestResultMetadata).build(); PPADataRequestAndroid ppaDataRequestAndroid = PPADataRequestAndroid.newBuilder() .setPayload(payload).build(); // when final PpaDataStorageRequest ppaDataStorageRequest = convertToStorageRequest(ppaDataRequestAndroid, ppacConfig, attestationStatement); assertThat(ppaDataStorageRequest).isNotNull(); assertThat(ppaDataStorageRequest.getTestResultMetric()).isPresent(); final List<ExposureWindowTestResult> testResultsMetadata = ppaDataStorageRequest .getExposureWindowTestResult().get(); assertThat(testResultsMetadata.get(0).getTestResult()).isEqualTo(ppaTestResults.getNumber()); assertThat(testResultsMetadata.get(0).getExposureWindowsAtTestRegistrations().size()).isEqualTo(2); } @ParameterizedTest @EnumSource(value = PPATestResult.class, names = {"TEST_RESULT_RAT_PENDING", "TEST_RESULT_UNKNOWN", "TEST_RESULT_PENDING", "TEST_RESULT_RAT_INVALID"}) public void testConvertToExposureWindowTestResultsFailedBecausePpaTestResult(PPATestResult ppaTestResults) { final Long epochSecondForNow = TimeUtils.getEpochSecondsForNow(); final PPAExposureWindow ppaExposureWindow = PPAExposureWindow .newBuilder() .setCalibrationConfidence(1) .setInfectiousness(PPAExposureWindowInfectiousness.INFECTIOUSNESS_HIGH) .setDate(epochSecondForNow) .build(); final PPANewExposureWindow ppaNewExposureWindow = PPANewExposureWindow .newBuilder() .setExposureWindow(ppaExposureWindow) .build(); final PPATestResultMetadata ppaTestResultMetadata = PPATestResultMetadata.newBuilder() .setTestResult(ppaTestResults) .setRiskLevelAtTestRegistration(RISK_LEVEL_HIGH) .setHoursSinceTestRegistration(5) .setHoursSinceHighRiskWarningAtTestRegistration(5) .setDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(5) .addExposureWindowsAtTestRegistration(ppaNewExposureWindow) .addExposureWindowsUntilTestResult(ppaNewExposureWindow) .build(); final PPADataAndroid payload = PPADataAndroid.newBuilder() .addTestResultMetadataSet(ppaTestResultMetadata).build(); PPADataRequestAndroid ppaDataRequestIOS = PPADataRequestAndroid.newBuilder() .setPayload(payload).build(); // when final PpaDataStorageRequest ppaDataStorageRequest = convertToStorageRequest(ppaDataRequestIOS, ppacConfig, attestationStatement); assertThat(ppaDataStorageRequest).isNotNull(); assertThat(ppaDataStorageRequest.getTestResultMetric()).isPresent(); assertThat(ppaDataStorageRequest.getExposureWindowTestResult()).contains(Collections.emptyList()); } @Override protected ClientMetadataDetails convertToClientMetadataDetails(PPAClientMetadataAndroid clientMetadata) { PPASemanticVersion cwaVersion = clientMetadata.getCwaVersion(); CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(cwaVersion.getMajor(), cwaVersion.getMinor(), cwaVersion.getPatch()); return new ClientMetadataDetails(cwaVersionMetadata, clientMetadata.getAppConfigETag(), null, null, null, clientMetadata.getAndroidApiLevel(), clientMetadata.getEnfVersion()); } @Override protected CwaVersionMetadata convertToCwaVersionMetadata(PPAClientMetadataAndroid clientMetadata) { PPASemanticVersion ppaSemanticVersion = clientMetadata.getCwaVersion(); return new CwaVersionMetadata(ppaSemanticVersion.getMajor(), ppaSemanticVersion.getMinor(), ppaSemanticVersion.getPatch()); } } <|start_filename|>services/retention/src/test/java/app/coronawarn/datadonation/services/retention/runner/RetentionPolicyTest.java<|end_filename|> package app.coronawarn.datadonation.services.retention.runner; import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.HOURS; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import app.coronawarn.datadonation.common.persistence.repository.ApiTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.DeviceTokenRepository; import app.coronawarn.datadonation.common.persistence.repository.ElsOneTimePasswordRepository; import app.coronawarn.datadonation.common.persistence.repository.OneTimePasswordRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ClientMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureRiskMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowTestResultsRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ExposureWindowsAtTestRegistrationRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.KeySubmissionMetadataWithClientMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.KeySubmissionMetadataWithUserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ScanInstanceRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.ScanInstancesAtTestRegistrationRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.SummarizedExposureWindowsWithUserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.TestResultMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.metrics.UserMetadataRepository; import app.coronawarn.datadonation.common.persistence.repository.ppac.android.SaltRepository; import app.coronawarn.datadonation.services.retention.config.RetentionConfiguration; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.temporal.TemporalUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @EnableConfigurationProperties(value = RetentionConfiguration.class) @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {RetentionPolicy.class}, initializers = ConfigDataApplicationContextInitializer.class) class RetentionPolicyTest { @MockBean ExposureRiskMetadataRepository exposureRiskMetadataRepository; @MockBean ExposureWindowRepository exposureWindowRepository; @MockBean ScanInstanceRepository scanInstanceRepository; @MockBean KeySubmissionMetadataWithClientMetadataRepository keySubmissionWithClientMetadataRepository; @MockBean ClientMetadataRepository clientMetadataRepository; @MockBean KeySubmissionMetadataWithUserMetadataRepository keySubmissionMetadataWithUserMetadataRepository; @MockBean TestResultMetadataRepository testResultMetadataRepository; @MockBean ApiTokenRepository apiTokenRepository; @MockBean DeviceTokenRepository deviceTokenRepository; @MockBean OneTimePasswordRepository otpRepository; @MockBean ElsOneTimePasswordRepository elsOtpRepository; @MockBean SaltRepository saltRepository; @MockBean UserMetadataRepository userMetadataRepository; @MockBean SummarizedExposureWindowsWithUserMetadataRepository summarizedExposureWindowsWithUserMetadataRepo; @MockBean ExposureWindowTestResultsRepository exposureWindowTestResultsRepository; @MockBean ScanInstancesAtTestRegistrationRepository scanInstancesAtTestRegistrationRepository; @MockBean ExposureWindowsAtTestRegistrationRepository exposureWindowsAtTestRegistrationRepository; @Autowired RetentionConfiguration retentionConfiguration; @Autowired RetentionPolicy retentionPolicy; @Test void testRetentionPolicyRunner() { retentionPolicy.run(null); verify(apiTokenRepository, times(1)) .deleteOlderThan( subtractRetentionPeriodFromNowToSeconds(DAYS, retentionConfiguration.getApiTokenRetentionDays())); verify(deviceTokenRepository, times(1)) .deleteOlderThan( subtractRetentionPeriodFromNowToEpochMilli(HOURS, retentionConfiguration.getDeviceTokenRetentionHours())); verify(otpRepository, times(1)) .deleteOlderThan(subtractRetentionPeriodFromNowToSeconds(DAYS, retentionConfiguration.getOtpRetentionDays())); verify(elsOtpRepository, times(1)).deleteOlderThan( subtractRetentionPeriodFromNowToSeconds(DAYS, retentionConfiguration.getElsOtpRetentionDays())); verify(exposureRiskMetadataRepository, times(1)) .deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getExposureRiskMetadataRetentionDays())); verify(exposureWindowRepository, times(1)) .deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getExposureWindowRetentionDays())); verify(keySubmissionWithClientMetadataRepository, times(1)) .deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getKeyMetadataWithClientRetentionDays())); verify(keySubmissionMetadataWithUserMetadataRepository, times(1)) .deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getKeyMetadataWithUserRetentionDays())); verify(testResultMetadataRepository, times(1)) .deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getTestResultMetadataRetentionDays())); verify(saltRepository, times(1)) .deleteOlderThan( subtractRetentionPeriodFromNowToEpochMilli(HOURS, retentionConfiguration.getSaltRetentionHours())); verify(clientMetadataRepository, times(1)) .deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getClientMetadataRetentionDays())); verify(scanInstanceRepository, times(1)).deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getExposureWindowRetentionDays())); verify(summarizedExposureWindowsWithUserMetadataRepo, times(1)).deleteOlderThan( subtractRetentionDaysFromNowToLocalDate(retentionConfiguration.getSummarizedExposureWindowRetentionDays())); verify(exposureWindowTestResultsRepository, times(1)).deleteOlderThan( subtractRetentionDaysFromNowToLocalDate( retentionConfiguration.getScanInstanceAtTestRegistrationRetentionDays())); verify(scanInstancesAtTestRegistrationRepository, times(1)).deleteOlderThan( subtractRetentionDaysFromNowToLocalDate( retentionConfiguration.getScanInstanceAtTestRegistrationRetentionDays())); verify(exposureWindowsAtTestRegistrationRepository, times(1)).deleteOlderThan( subtractRetentionDaysFromNowToLocalDate( retentionConfiguration.getExposureWindowAtTestRegistrationRetentionDays())); } private LocalDate subtractRetentionDaysFromNowToLocalDate(Integer retentionDays) { return Instant.now().atOffset(ZoneOffset.UTC).toLocalDate() .minusDays(retentionDays); } private long subtractRetentionPeriodFromNowToSeconds(TemporalUnit temporalUnit, Integer retentionPeriod) { return Instant.now().truncatedTo(temporalUnit) .minus(retentionPeriod, temporalUnit) .getEpochSecond(); } private long subtractRetentionPeriodFromNowToEpochMilli(TemporalUnit temporalUnit, Integer retentionPeriod) { return Instant.now().truncatedTo(temporalUnit).minus(retentionPeriod, temporalUnit).toEpochMilli(); } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/persistence/repository/metrics/KeySubmissionMetadataWithClientMetadataRepositoryTest.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.common.persistence.domain.metrics.KeySubmissionMetadataWithClientMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.ClientMetadataDetails; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import java.time.LocalDate; import java.time.ZoneId; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class KeySubmissionMetadataWithClientMetadataRepositoryTest { @Autowired private KeySubmissionMetadataWithClientMetadataRepository keySubmissionMetadataClientMetadataRepository; @AfterEach void tearDown() { keySubmissionMetadataClientMetadataRepository.deleteAll(); } @Test void keySubmissionWithClientMetadataShouldBePersistedCorrectly() { LocalDate justADate = LocalDate.now(ZoneId.of("UTC")); CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(1, 1, 1); ClientMetadataDetails clientMetadata = new ClientMetadataDetails(cwaVersionMetadata, "abc", 2, 2, 3, 1l, 2l); TechnicalMetadata technicalMetadata = new TechnicalMetadata(justADate, true, false, true, false); KeySubmissionMetadataWithClientMetadata keySubmissionMetadata = new KeySubmissionMetadataWithClientMetadata(null, true, false, true, false, true, 1, false, clientMetadata, technicalMetadata); keySubmissionMetadataClientMetadataRepository.save(keySubmissionMetadata); KeySubmissionMetadataWithClientMetadata loadedEntity = keySubmissionMetadataClientMetadataRepository.findAll() .iterator().next(); assertEquals(loadedEntity.getAdvancedConsentGiven(), keySubmissionMetadata.getAdvancedConsentGiven()); assertEquals(loadedEntity.getLastSubmissionFlowScreen(), keySubmissionMetadata.getLastSubmissionFlowScreen()); assertEquals(loadedEntity.getSubmitted(), keySubmissionMetadata.getSubmitted()); assertEquals(loadedEntity.getSubmittedAfterCancel(), keySubmissionMetadata.getSubmittedAfterCancel()); assertEquals(loadedEntity.getSubmittedAfterSymptomFlow(), keySubmissionMetadata.getSubmittedAfterSymptomFlow()); assertEquals(loadedEntity.getSubmittedInBackground(), keySubmissionMetadata.getSubmittedInBackground()); assertEquals(loadedEntity.getSubmittedWithCheckIns(), keySubmissionMetadata.getSubmittedWithCheckIns()); assertEquals(loadedEntity.getTechnicalMetadata(), keySubmissionMetadata.getTechnicalMetadata()); assertEquals(loadedEntity.getClientMetadata(), keySubmissionMetadata.getClientMetadata()); assertNotNull(loadedEntity.getId()); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/controller/validation/ElsOneTimePasswordRequestAndroidValidator.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.controller.validation; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ELSOneTimePasswordRequestAndroid; import app.coronawarn.datadonation.services.ppac.commons.validation.UuidConstraintValidator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.stereotype.Component; @Component public class ElsOneTimePasswordRequestAndroidValidator extends UuidConstraintValidator implements ConstraintValidator<ValidEdusOneTimePasswordRequestAndroid, ELSOneTimePasswordRequestAndroid> { @Override public boolean isValid(final ELSOneTimePasswordRequestAndroid requestBody, final ConstraintValidatorContext context) { return super.isValid(requestBody.getPayload().getOtp(), context); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/ios/client/domain/PerDeviceDataResponse.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.client.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Optional; public class PerDeviceDataResponse { Boolean bit0; Boolean bit1; @JsonProperty("last_update_time") String lastUpdated; // YYYY-MM public PerDeviceDataResponse() { // empty constructor } /** * Create new instance of per-device data. * * @param bit0 first of a total of 2 bits. * @param bit1 second of a total of 2 bits. * @param lastUpdated when this per-device data was updated the last time. */ public PerDeviceDataResponse(boolean bit0, boolean bit1, String lastUpdated) { this.bit0 = bit0; this.bit1 = bit1; this.lastUpdated = lastUpdated; } public boolean isBit0() { return bit0; } public void setBit0(boolean bit0) { this.bit0 = bit0; } public boolean isBit1() { return bit1; } public void setBit1(boolean bit1) { this.bit1 = bit1; } @JsonIgnore public Optional<String> getLastUpdated() { return Optional.ofNullable(lastUpdated); } public void setLastUpdated(String lastUpdated) { this.lastUpdated = lastUpdated; } } <|start_filename|>common/persistence/src/test/java/app/coronawarn/datadonation/common/persistence/repository/metrics/ExposureRiskMetadataRepositoryTest.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.repository.metrics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import app.coronawarn.datadonation.common.persistence.domain.metrics.ExposureRiskMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.TechnicalMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.CwaVersionMetadata; import app.coronawarn.datadonation.common.persistence.domain.metrics.embeddable.UserMetadataDetails; import java.time.LocalDate; import java.time.ZoneId; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; @DataJdbcTest class ExposureRiskMetadataRepositoryTest { @Autowired private ExposureRiskMetadataRepository exposureRiskMetadataRepository; @AfterEach void tearDown() { exposureRiskMetadataRepository.deleteAll(); } @Test void exposureRiskMetadataShouldBePersistedCorrectly() { LocalDate justADate = LocalDate.now(ZoneId.of("UTC")); UserMetadataDetails userMetadata = new UserMetadataDetails(1, 2, 3); TechnicalMetadata technicalMetadata = new TechnicalMetadata(justADate, true, false, true, false); CwaVersionMetadata cwaVersionMetadata = new CwaVersionMetadata(1,2,3); ExposureRiskMetadata exposureMetrics = new ExposureRiskMetadata(null, 1, true, justADate, false, 1, true, justADate, false, userMetadata, technicalMetadata, cwaVersionMetadata); exposureRiskMetadataRepository.save(exposureMetrics); ExposureRiskMetadata loadedEntity = exposureRiskMetadataRepository.findAll().iterator().next(); assertEquals(loadedEntity.getMostRecentDateAtRiskLevel(), exposureMetrics.getMostRecentDateAtRiskLevel()); assertEquals(loadedEntity.getMostRecentDateChanged(), exposureMetrics.getMostRecentDateChanged()); assertEquals(loadedEntity.getRiskLevel(), exposureMetrics.getRiskLevel()); assertEquals(loadedEntity.getRiskLevelChanged(), exposureMetrics.getRiskLevelChanged()); assertEquals(loadedEntity.getTechnicalMetadata(), exposureMetrics.getTechnicalMetadata()); assertEquals(loadedEntity.getUserMetadata(), exposureMetrics.getUserMetadata()); assertEquals(loadedEntity.getPtRiskLevel(), exposureMetrics.getPtRiskLevel()); assertEquals(loadedEntity.getPtRiskLevelChanged(), exposureMetrics.getPtRiskLevelChanged()); assertEquals(loadedEntity.getPtMostRecentDateAtRiskLevel(), exposureMetrics.getPtMostRecentDateAtRiskLevel()); assertEquals(loadedEntity.getPtMostRecentDateChanged(), exposureMetrics.getPtMostRecentDateChanged()); assertNotNull(loadedEntity.getId()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionMinor(), cwaVersionMetadata.getCwaVersionMinor()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionMajor(), cwaVersionMetadata.getCwaVersionMajor()); assertEquals(loadedEntity.getCwaVersionMetadata().getCwaVersionPatch(), cwaVersionMetadata.getCwaVersionPatch()); } } <|start_filename|>services/ppac/src/test/java/app/coronawarn/datadonation/services/ppac/ios/testdata/TestData.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.ios.testdata; import static app.coronawarn.datadonation.common.protocols.internal.ppdd.PPALastSubmissionFlowScreen.SUBMISSION_FLOW_SCREEN_OTHER; import static app.coronawarn.datadonation.common.protocols.internal.ppdd.PPARiskLevel.RISK_LEVEL_HIGH; import static app.coronawarn.datadonation.common.protocols.internal.ppdd.PPATestResult.TEST_RESULT_POSITIVE; import static app.coronawarn.datadonation.common.utils.TimeUtils.getEpochSecondsForNow; import app.coronawarn.datadonation.common.persistence.domain.DeviceToken; import app.coronawarn.datadonation.common.persistence.service.OtpCreationResponse; import app.coronawarn.datadonation.common.protocols.internal.ppdd.EDUSOneTimePassword; import app.coronawarn.datadonation.common.protocols.internal.ppdd.EDUSOneTimePasswordRequestIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ELSOneTimePasswordRequestIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.ExposureRiskMetadata; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPACIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPADataRequestIOS; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAExposureWindow; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAExposureWindowInfectiousness; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPAKeySubmissionMetadata; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPANewExposureWindow; import app.coronawarn.datadonation.common.protocols.internal.ppdd.PPATestResultMetadata; import app.coronawarn.datadonation.common.utils.TimeUtils; import app.coronawarn.datadonation.services.ppac.commons.web.DataSubmissionResponse; import app.coronawarn.datadonation.services.ppac.ios.client.domain.PerDeviceDataResponse; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.UUID; import org.bouncycastle.util.encoders.Base64; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.testcontainers.shaded.com.fasterxml.jackson.core.JsonProcessingException; import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper; public final class TestData { public static PerDeviceDataResponse buildIosDeviceData(OffsetDateTime lastUpdated, boolean valid) { PerDeviceDataResponse data = new PerDeviceDataResponse(); if (valid) { data.setBit0(true); data.setBit1(false); } else { data.setBit0(true); data.setBit1(true); } LocalDateTime utcBasedTime = lastUpdated.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); data.setLastUpdated(utcBasedTime.format(DateTimeFormatter.ofPattern("yyyy-MM"))); return data; } public static ResponseEntity<DataSubmissionResponse> postSurvey( EDUSOneTimePasswordRequestIOS edusOneTimePasswordRequestIOS, TestRestTemplate testRestTemplate, String url, Boolean skipApiTokenExpiration) { HttpHeaders httpHeaders = getHttpHeaders(skipApiTokenExpiration); return testRestTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(edusOneTimePasswordRequestIOS, httpHeaders), DataSubmissionResponse.class); } public static ResponseEntity<DataSubmissionResponse> postSubmission( PPADataRequestIOS ppaDataRequestIOS, TestRestTemplate testRestTemplate, String url, Boolean skipApiTokenExpiration) { HttpHeaders httpHeaders = getHttpHeaders(skipApiTokenExpiration); return testRestTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(ppaDataRequestIOS, httpHeaders), DataSubmissionResponse.class); } public static ResponseEntity<OtpCreationResponse> postOtpCreationRequest( EDUSOneTimePasswordRequestIOS otpRequest, TestRestTemplate testRestTemplate, String url, Boolean skipApiTokenExpiration) { HttpHeaders httpHeaders = getHttpHeaders(skipApiTokenExpiration); return testRestTemplate .exchange(url, HttpMethod.POST, new HttpEntity<>(otpRequest, httpHeaders), OtpCreationResponse.class); } public static ResponseEntity<OtpCreationResponse> postLogOtpCreationRequest( ELSOneTimePasswordRequestIOS otpRequest, TestRestTemplate testRestTemplate, String url, Boolean skipApiTokenExpiration) { HttpHeaders httpHeaders = getHttpHeaders(skipApiTokenExpiration); return testRestTemplate .exchange(url, HttpMethod.POST, new HttpEntity<>(otpRequest, httpHeaders), OtpCreationResponse.class); } private static HttpHeaders getHttpHeaders(Boolean skipApiTokenExpiration) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.valueOf("application/x-protobuf")); httpHeaders.set("cwa-ppac-ios-accept-api-token", skipApiTokenExpiration.toString()); return httpHeaders; } public static PPADataRequestIOS buildInvalidPPADataRequestIosPayload() { PPACIOS authIos = PPACIOS.newBuilder().setApiToken("apiToken").setDeviceToken("deviceToken").build(); PPADataIOS metrics = PPADataIOS.newBuilder().build(); return PPADataRequestIOS.newBuilder().setAuthentication(authIos).setPayload(metrics).build(); } public static PPADataRequestIOS buildPPADataRequestIosPayload(String apiToken, String deviceToken, boolean withPayload) { PPACIOS authIos = PPACIOS.newBuilder().setApiToken(apiToken).setDeviceToken(deviceToken).build(); if (withPayload) { return PPADataRequestIOS.newBuilder().setAuthentication(authIos).setPayload(buildIosPayload()).build(); } return PPADataRequestIOS.newBuilder().setAuthentication(authIos).setPayload(PPADataIOS.newBuilder().build()) .build(); } public static EDUSOneTimePasswordRequestIOS buildEdusOneTimePasswordPayload(String apiToken, String deviceToken, String otp) { PPACIOS authIos = PPACIOS.newBuilder().setApiToken(apiToken).setDeviceToken(deviceToken).build(); final EDUSOneTimePassword edusOneTimePassword = EDUSOneTimePassword.newBuilder().setOtp(otp).build(); return EDUSOneTimePasswordRequestIOS.newBuilder().setAuthentication(authIos).setPayload( edusOneTimePassword) .build(); } private static PPADataIOS buildIosPayload() { final Long epochSecondForNow = TimeUtils.getEpochSecondsForNow(); final PPAExposureWindow ppaExposureWindow = PPAExposureWindow .newBuilder() .setCalibrationConfidence(1) .setInfectiousness(PPAExposureWindowInfectiousness.INFECTIOUSNESS_HIGH) .setDate(epochSecondForNow) .build(); final ExposureRiskMetadata exposureRiskMetadataSrc = ExposureRiskMetadata.newBuilder() .setDateChangedComparedToPreviousSubmission(true) .setMostRecentDateAtRiskLevel(epochSecondForNow) .setRiskLevel(RISK_LEVEL_HIGH) .setRiskLevelChangedComparedToPreviousSubmission(true) .build(); final PPANewExposureWindow ppaNewExposureWindow = PPANewExposureWindow .newBuilder() .setExposureWindow(ppaExposureWindow) .build(); final PPAKeySubmissionMetadata ppaKeySubmissionMetadata = PPAKeySubmissionMetadata.newBuilder() .setAdvancedConsentGiven(true) .setDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(5) .setHoursSinceHighRiskWarningAtTestRegistration(5) .setHoursSinceTestRegistration(5) .setLastSubmissionFlowScreen(SUBMISSION_FLOW_SCREEN_OTHER) .setSubmittedAfterSymptomFlow(true) .build(); final PPATestResultMetadata ppaTestResultMetadata = PPATestResultMetadata.newBuilder() .setTestResult(TEST_RESULT_POSITIVE) .setRiskLevelAtTestRegistration(RISK_LEVEL_HIGH) .setHoursSinceTestRegistration(5) .setHoursSinceHighRiskWarningAtTestRegistration(5) .setDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(5) .addExposureWindowsAtTestRegistration(ppaNewExposureWindow) .addExposureWindowsUntilTestResult(ppaNewExposureWindow) .build(); final PPADataIOS payload = PPADataIOS.newBuilder() .addTestResultMetadataSet(ppaTestResultMetadata) .addNewExposureWindows(ppaNewExposureWindow) .addExposureRiskMetadataSet(exposureRiskMetadataSrc) .addKeySubmissionMetadataSet(ppaKeySubmissionMetadata).build(); return payload; } public static String buildUuid() { return UUID.randomUUID().toString(); } public static String buildBase64String(int length) { char[] keyChars = new char[length]; Arrays.fill(keyChars, 'A'); String key = new String(keyChars); return Base64.toBase64String(key.getBytes(Charset.defaultCharset())) .substring(key.length() - length, key.length() + 1) + "="; } public static String jsonify(PerDeviceDataResponse data) { ObjectMapper objectMapper = new ObjectMapper(); String result = null; try { result = objectMapper.writeValueAsString(data); } catch (JsonProcessingException e) { e.printStackTrace(); } return result; } public static DeviceToken buildDeviceToken(String deviceToken) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return new DeviceToken(digest.digest(deviceToken.getBytes(StandardCharsets.UTF_8)), getEpochSecondsForNow()); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/commons/web/DataSubmissionResponse.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.commons.web; import app.coronawarn.datadonation.services.ppac.logging.PpacErrorCode; public class DataSubmissionResponse { private PpacErrorCode errorCode; public PpacErrorCode getErrorCode() { return errorCode; } /** * Simple helper method to create a DataSubmissionResponse with the provided ErrorCode {@link PpacErrorCode}. * * @param errorCode the provided ErrorCode. * @return a new instance of DataSubmissionResponse. */ public static DataSubmissionResponse of(PpacErrorCode errorCode) { DataSubmissionResponse dataSubmissionResponse = new DataSubmissionResponse(); dataSubmissionResponse.errorCode = errorCode; return dataSubmissionResponse; } } <|start_filename|>common/persistence/src/main/java/app/coronawarn/datadonation/common/persistence/service/OtpStatusException.java<|end_filename|> package app.coronawarn.datadonation.common.persistence.service; public class OtpStatusException extends RuntimeException { public OtpStatusException(String message) { super(message); } } <|start_filename|>services/ppac/src/main/java/app/coronawarn/datadonation/services/ppac/android/attestation/errors/FailedJwsParsing.java<|end_filename|> package app.coronawarn.datadonation.services.ppac.android.attestation.errors; public final class FailedJwsParsing extends RuntimeException { private static final long serialVersionUID = -1579569743042757810L; public FailedJwsParsing(Exception e) { super("Invalid JWS format received", e); } }
tlaufkoetter/cwa-ppa-server
<|start_filename|>example/registry/proto/pb/types.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: types.proto package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" wrapperspb "google.golang.org/protobuf/types/known/wrapperspb" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // A non-interactive distributed key generation (NI-DKG) tag. type NiDkgTag int32 const ( NiDkgTag_NI_DKG_TAG_UNSPECIFIED NiDkgTag = 0 NiDkgTag_NI_DKG_TAG_LOW_THRESHOLD NiDkgTag = 1 NiDkgTag_NI_DKG_TAG_HIGH_THRESHOLD NiDkgTag = 2 ) // Enum value maps for NiDkgTag. var ( NiDkgTag_name = map[int32]string{ 0: "NI_DKG_TAG_UNSPECIFIED", 1: "NI_DKG_TAG_LOW_THRESHOLD", 2: "NI_DKG_TAG_HIGH_THRESHOLD", } NiDkgTag_value = map[string]int32{ "NI_DKG_TAG_UNSPECIFIED": 0, "NI_DKG_TAG_LOW_THRESHOLD": 1, "NI_DKG_TAG_HIGH_THRESHOLD": 2, } ) func (x NiDkgTag) Enum() *NiDkgTag { p := new(NiDkgTag) *p = x return p } func (x NiDkgTag) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (NiDkgTag) Descriptor() protoreflect.EnumDescriptor { return file_types_proto_enumTypes[0].Descriptor() } func (NiDkgTag) Type() protoreflect.EnumType { return &file_types_proto_enumTypes[0] } func (x NiDkgTag) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use NiDkgTag.Descriptor instead. func (NiDkgTag) EnumDescriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{0} } type PrincipalId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Raw []byte `protobuf:"bytes,1,opt,name=raw,proto3" json:"raw,omitempty"` } func (x *PrincipalId) Reset() { *x = PrincipalId{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PrincipalId) String() string { return protoimpl.X.MessageStringOf(x) } func (*PrincipalId) ProtoMessage() {} func (x *PrincipalId) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PrincipalId.ProtoReflect.Descriptor instead. func (*PrincipalId) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{0} } func (x *PrincipalId) GetRaw() []byte { if x != nil { return x.Raw } return nil } type CanisterId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PrincipalId *PrincipalId `protobuf:"bytes,1,opt,name=principal_id,json=principalId,proto3" json:"principal_id,omitempty"` } func (x *CanisterId) Reset() { *x = CanisterId{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CanisterId) String() string { return protoimpl.X.MessageStringOf(x) } func (*CanisterId) ProtoMessage() {} func (x *CanisterId) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CanisterId.ProtoReflect.Descriptor instead. func (*CanisterId) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{1} } func (x *CanisterId) GetPrincipalId() *PrincipalId { if x != nil { return x.PrincipalId } return nil } type SubnetId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PrincipalId *PrincipalId `protobuf:"bytes,1,opt,name=principal_id,json=principalId,proto3" json:"principal_id,omitempty"` } func (x *SubnetId) Reset() { *x = SubnetId{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SubnetId) String() string { return protoimpl.X.MessageStringOf(x) } func (*SubnetId) ProtoMessage() {} func (x *SubnetId) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SubnetId.ProtoReflect.Descriptor instead. func (*SubnetId) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{2} } func (x *SubnetId) GetPrincipalId() *PrincipalId { if x != nil { return x.PrincipalId } return nil } type UserId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PrincipalId *PrincipalId `protobuf:"bytes,1,opt,name=principal_id,json=principalId,proto3" json:"principal_id,omitempty"` } func (x *UserId) Reset() { *x = UserId{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *UserId) String() string { return protoimpl.X.MessageStringOf(x) } func (*UserId) ProtoMessage() {} func (x *UserId) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UserId.ProtoReflect.Descriptor instead. func (*UserId) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{3} } func (x *UserId) GetPrincipalId() *PrincipalId { if x != nil { return x.PrincipalId } return nil } type NodeId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PrincipalId *PrincipalId `protobuf:"bytes,1,opt,name=principal_id,json=principalId,proto3" json:"principal_id,omitempty"` } func (x *NodeId) Reset() { *x = NodeId{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeId) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeId) ProtoMessage() {} func (x *NodeId) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NodeId.ProtoReflect.Descriptor instead. func (*NodeId) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{4} } func (x *NodeId) GetPrincipalId() *PrincipalId { if x != nil { return x.PrincipalId } return nil } // A non-interactive distributed key generation (NI-DKG) ID. type NiDkgId struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields StartBlockHeight uint64 `protobuf:"varint,1,opt,name=start_block_height,json=startBlockHeight,proto3" json:"start_block_height,omitempty"` DealerSubnet []byte `protobuf:"bytes,2,opt,name=dealer_subnet,json=dealerSubnet,proto3" json:"dealer_subnet,omitempty"` DkgTag NiDkgTag `protobuf:"varint,4,opt,name=dkg_tag,json=dkgTag,proto3,enum=ic_registry.NiDkgTag" json:"dkg_tag,omitempty"` RemoteTargetId *wrapperspb.BytesValue `protobuf:"bytes,5,opt,name=remote_target_id,json=remoteTargetId,proto3" json:"remote_target_id,omitempty"` } func (x *NiDkgId) Reset() { *x = NiDkgId{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NiDkgId) String() string { return protoimpl.X.MessageStringOf(x) } func (*NiDkgId) ProtoMessage() {} func (x *NiDkgId) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NiDkgId.ProtoReflect.Descriptor instead. func (*NiDkgId) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{5} } func (x *NiDkgId) GetStartBlockHeight() uint64 { if x != nil { return x.StartBlockHeight } return 0 } func (x *NiDkgId) GetDealerSubnet() []byte { if x != nil { return x.DealerSubnet } return nil } func (x *NiDkgId) GetDkgTag() NiDkgTag { if x != nil { return x.DkgTag } return NiDkgTag_NI_DKG_TAG_UNSPECIFIED } func (x *NiDkgId) GetRemoteTargetId() *wrapperspb.BytesValue { if x != nil { return x.RemoteTargetId } return nil } type NominalCycles struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields High uint64 `protobuf:"varint,1,opt,name=high,proto3" json:"high,omitempty"` Low uint64 `protobuf:"varint,2,opt,name=low,proto3" json:"low,omitempty"` } func (x *NominalCycles) Reset() { *x = NominalCycles{} if protoimpl.UnsafeEnabled { mi := &file_types_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NominalCycles) String() string { return protoimpl.X.MessageStringOf(x) } func (*NominalCycles) ProtoMessage() {} func (x *NominalCycles) ProtoReflect() protoreflect.Message { mi := &file_types_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NominalCycles.ProtoReflect.Descriptor instead. func (*NominalCycles) Descriptor() ([]byte, []int) { return file_types_proto_rawDescGZIP(), []int{6} } func (x *NominalCycles) GetHigh() uint64 { if x != nil { return x.High } return 0 } func (x *NominalCycles) GetLow() uint64 { if x != nil { return x.Low } return 0 } var File_types_proto protoreflect.FileDescriptor var file_types_proto_rawDesc = []byte{ 0x0a, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0b, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x1f, 0x0a, 0x0b, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x72, 0x61, 0x77, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x72, 0x61, 0x77, 0x22, 0x49, 0x0a, 0x0a, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x3b, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x22, 0x47, 0x0a, 0x08, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x49, 0x64, 0x12, 0x3b, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x22, 0x45, 0x0a, 0x06, 0x55, 0x73, 0x65, 0x72, 0x49, 0x64, 0x12, 0x3b, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x22, 0x45, 0x0a, 0x06, 0x4e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x3b, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x22, 0xea, 0x01, 0x0a, 0x07, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x49, 0x64, 0x12, 0x2c, 0x0a, 0x12, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x10, 0x73, 0x74, 0x61, 0x72, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x64, 0x65, 0x61, 0x6c, 0x65, 0x72, 0x5f, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x64, 0x65, 0x61, 0x6c, 0x65, 0x72, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x12, 0x2e, 0x0a, 0x07, 0x64, 0x6b, 0x67, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x15, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x61, 0x67, 0x52, 0x06, 0x64, 0x6b, 0x67, 0x54, 0x61, 0x67, 0x12, 0x45, 0x0a, 0x10, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x5f, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x79, 0x74, 0x65, 0x73, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x49, 0x64, 0x4a, 0x04, 0x08, 0x03, 0x10, 0x04, 0x52, 0x0f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x5f, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x22, 0x35, 0x0a, 0x0d, 0x4e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x6c, 0x43, 0x79, 0x63, 0x6c, 0x65, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x69, 0x67, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x04, 0x68, 0x69, 0x67, 0x68, 0x12, 0x10, 0x0a, 0x03, 0x6c, 0x6f, 0x77, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, 0x6c, 0x6f, 0x77, 0x2a, 0x63, 0x0a, 0x08, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x61, 0x67, 0x12, 0x1a, 0x0a, 0x16, 0x4e, 0x49, 0x5f, 0x44, 0x4b, 0x47, 0x5f, 0x54, 0x41, 0x47, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1c, 0x0a, 0x18, 0x4e, 0x49, 0x5f, 0x44, 0x4b, 0x47, 0x5f, 0x54, 0x41, 0x47, 0x5f, 0x4c, 0x4f, 0x57, 0x5f, 0x54, 0x48, 0x52, 0x45, 0x53, 0x48, 0x4f, 0x4c, 0x44, 0x10, 0x01, 0x12, 0x1d, 0x0a, 0x19, 0x4e, 0x49, 0x5f, 0x44, 0x4b, 0x47, 0x5f, 0x54, 0x41, 0x47, 0x5f, 0x48, 0x49, 0x47, 0x48, 0x5f, 0x54, 0x48, 0x52, 0x45, 0x53, 0x48, 0x4f, 0x4c, 0x44, 0x10, 0x02, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_types_proto_rawDescOnce sync.Once file_types_proto_rawDescData = file_types_proto_rawDesc ) func file_types_proto_rawDescGZIP() []byte { file_types_proto_rawDescOnce.Do(func() { file_types_proto_rawDescData = protoimpl.X.CompressGZIP(file_types_proto_rawDescData) }) return file_types_proto_rawDescData } var file_types_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_types_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_types_proto_goTypes = []interface{}{ (NiDkgTag)(0), // 0: ic_registry.NiDkgTag (*PrincipalId)(nil), // 1: ic_registry.PrincipalId (*CanisterId)(nil), // 2: ic_registry.CanisterId (*SubnetId)(nil), // 3: ic_registry.SubnetId (*UserId)(nil), // 4: ic_registry.UserId (*NodeId)(nil), // 5: ic_registry.NodeId (*NiDkgId)(nil), // 6: ic_registry.NiDkgId (*NominalCycles)(nil), // 7: ic_registry.NominalCycles (*wrapperspb.BytesValue)(nil), // 8: google.protobuf.BytesValue } var file_types_proto_depIdxs = []int32{ 1, // 0: ic_registry.CanisterId.principal_id:type_name -> ic_registry.PrincipalId 1, // 1: ic_registry.SubnetId.principal_id:type_name -> ic_registry.PrincipalId 1, // 2: ic_registry.UserId.principal_id:type_name -> ic_registry.PrincipalId 1, // 3: ic_registry.NodeId.principal_id:type_name -> ic_registry.PrincipalId 0, // 4: ic_registry.NiDkgId.dkg_tag:type_name -> ic_registry.NiDkgTag 8, // 5: ic_registry.NiDkgId.remote_target_id:type_name -> google.protobuf.BytesValue 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_types_proto_init() } func file_types_proto_init() { if File_types_proto != nil { return } if !protoimpl.UnsafeEnabled { file_types_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PrincipalId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_types_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CanisterId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_types_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SubnetId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_types_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*UserId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_types_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_types_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NiDkgId); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_types_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NominalCycles); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_types_proto_rawDesc, NumEnums: 1, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_types_proto_goTypes, DependencyIndexes: file_types_proto_depIdxs, EnumInfos: file_types_proto_enumTypes, MessageInfos: file_types_proto_msgTypes, }.Build() File_types_proto = out.File file_types_proto_rawDesc = nil file_types_proto_goTypes = nil file_types_proto_depIdxs = nil } <|start_filename|>utils/idl/vec.go<|end_filename|> package idl import ( "bytes" "fmt" "math/big" "github.com/aviate-labs/leb128" ) type Vec struct { Type Type } func NewVec(t Type) *Vec { return &Vec{ Type: t, } } func (v Vec) AddTypeDefinition(tdt *TypeDefinitionTable) error { if err := v.Type.AddTypeDefinition(tdt); err != nil { return err } id, err := leb128.EncodeSigned(big.NewInt(vecType)) if err != nil { return err } v_, err := v.Type.EncodeType(tdt) if err != nil { return err } tdt.Add(v, concat(id, v_)) return nil } func (v Vec) Decode(r *bytes.Reader) (interface{}, error) { l, err := leb128.DecodeUnsigned(r) if err != nil { return nil, err } var vs []interface{} for i := 0; i < int(l.Int64()); i++ { v_, err := v.Type.Decode(r) if err != nil { return nil, err } vs = append(vs, v_) } return vs, nil } func (v Vec) EncodeType(tdt *TypeDefinitionTable) ([]byte, error) { idx, ok := tdt.Indexes[v.String()] if !ok { return nil, fmt.Errorf("missing type index for: %s", v) } return leb128.EncodeSigned(big.NewInt(int64(idx))) } func (v Vec) EncodeValue(value interface{}) ([]byte, error) { vs_, ok := value.([]interface{}) if !ok { return nil, fmt.Errorf("invalid argument: %v", v) } l, err := leb128.EncodeSigned(big.NewInt(int64(len(vs_)))) if err != nil { return nil, err } var vs []byte for _, value := range vs_ { v_, err := v.Type.EncodeValue(value) if err != nil { return nil, err } vs = append(vs, v_...) } return concat(l, vs), nil } func (v Vec) String() string { return fmt.Sprintf("vec %s", v.Type) } func (Vec) Fill(Type) { } <|start_filename|>agent.go<|end_filename|> package agent import ( "encoding/hex" "fmt" "time" "github.com/fxamacker/cbor/v2" "github.com/mix-labs/IC-Go/utils/identity" "github.com/mix-labs/IC-Go/utils/idl" "github.com/mix-labs/IC-Go/utils/principal" ) type Agent struct { client *Client identity *identity.Identity ingressExpiry time.Duration rootKey []byte //ICP root identity } func NewFromPem(anonymous bool, pemPath string) (*Agent, error) { var id *identity.Identity c := NewClient("https://ic0.app") //todo:是否需要从ic拉取rootKey信息 status, _ := c.Status() if anonymous == true { id = &identity.Identity{ Anonymous: anonymous, } } privKey, err := identity.FromPem(pemPath) if err != nil { return nil, err } pubKey := privKey.Public() id = &identity.Identity{ anonymous, privKey, pubKey, } ingressExpiry := time.Second * 10 return &Agent{ client: &c, identity: id, ingressExpiry: ingressExpiry, rootKey: status.RootKey, }, nil } func New(anonymous bool, privKey string) *Agent { c := NewClient("https://ic0.app") //todo:是否需要从ic拉取rootKey信息 status, _ := c.Status() pbBytes, _ := hex.DecodeString(privKey) id := identity.New(anonymous, pbBytes) ingressExpiry := time.Second * 10 return &Agent{ client: &c, identity: id, ingressExpiry: ingressExpiry, rootKey: status.RootKey, } } func (agent *Agent) Sender() principal.Principal { if agent.identity.Anonymous == true { return principal.AnonymousID } sender := principal.NewSelfAuthenticating(agent.identity.PubKeyBytes()) return sender } func (agent *Agent) getExpiryDate() time.Time { return time.Now().Add(agent.ingressExpiry) } func (agent *Agent) queryEndpoint(canisterID string, data []byte) (*QueryResponse, error) { resp, err := agent.client.query(canisterID, data) if err != nil { return nil, err } result := new(QueryResponse) err = cbor.Unmarshal(resp, result) if err != nil { return result, err } return result, nil } func (agent *Agent) callEndpoint(canisterID string, reqId RequestID, data []byte) (RequestID, error) { return agent.client.call(canisterID, reqId, data) } func (agent *Agent) readStateEndpoint(canisterID string, data []byte) ([]byte, error) { return agent.client.readState(canisterID, data) } func (agent *Agent) Query(canisterID, methodName string, arg []byte) ([]idl.Type, []interface{}, string, error) { resp, ErrMsg, err := agent.QueryRaw(canisterID, methodName, arg) if err != nil { return nil, nil, "", err } types, values, err := idl.Decode(resp) if err != nil { return nil, nil, "", err } return types, values, ErrMsg, nil } func (agent *Agent) QueryRaw(canisterID, methodName string, arg []byte) ([]byte, string, error) { canisterIDPrincipal, err := principal.Decode(canisterID) if err != nil { return nil, "", err } req := Request{ Type: RequestTypeQuery, Sender: agent.Sender(), CanisterID: canisterIDPrincipal, MethodName: methodName, Arguments: arg, IngressExpiry: uint64(agent.getExpiryDate().UnixNano()), } _, data, err := agent.signRequest(req) if err != nil { return nil, "", err } resp, err := agent.queryEndpoint(canisterID, data) if err != nil { return nil, "", err } if resp.Status == "replied" { return resp.Reply["arg"], "", nil } else if resp.Status == "rejected" { return nil, resp.RejectMsg, nil } return nil, "", err } func (agent *Agent) Update(canisterID, methodName string, arg []byte, timeout uint64) ([]idl.Type, []interface{}, error) { resp, err := agent.UpdateRaw(canisterID, methodName, arg, timeout) if err != nil { return nil, nil, err } types, values, err := idl.Decode(resp) if err != nil { return nil, nil, err } return types, values, nil } func (agent *Agent) UpdateRaw(canisterID, methodName string, arg []byte, timeout uint64) ([]byte, error) { canisterIDPrincipal, err := principal.Decode(canisterID) if err != nil { return nil, err } req := Request{ Type: RequestTypeCall, Sender: agent.Sender(), CanisterID: canisterIDPrincipal, MethodName: methodName, Arguments: arg, IngressExpiry: uint64(agent.getExpiryDate().UnixNano()), } requestID, data, err := agent.signRequest(req) if err != nil { return nil, err } _, err = agent.callEndpoint(canisterID, *requestID, data) if err != nil { return nil, err } //poll requestID to get result //todo:这个时间写成配置之后 return agent.poll(canisterID, *requestID, time.Second, time.Second*time.Duration(timeout)) } func (agent *Agent) poll(canisterID string, requestID RequestID, delay time.Duration, timeout time.Duration) ([]byte, error) { finalStatus := "" var finalCert []byte timer := time.NewTimer(timeout) ticker := time.NewTicker(delay) stopped := true for stopped { select { case <-ticker.C: status, cert, err := agent.requestStatusRaw(canisterID, requestID) if err != nil { fmt.Printf("can not request status raw with error : %v\n", err) } finalStatus = string(status) finalCert = cert if finalStatus == "replied" || finalStatus == "done" || finalStatus == "rejected" { stopped = false } case <-timer.C: stopped = false } } if finalStatus == "replied" { paths := [][]byte{[]byte("request_status"), requestID[:], []byte("reply")} res, err := LookUp(paths, finalCert) if err != nil { return nil, err } return res, nil } defer timer.Stop() defer ticker.Stop() return nil, fmt.Errorf("call poll fail with status %v", finalStatus) } func (agent *Agent) requestStatusRaw(canisterID string, requestId RequestID) ([]byte, []byte, error) { paths := [][][]byte{{[]byte("request_status"), requestId[:]}} cert, err := agent.readStateRaw(canisterID, paths) if err != nil { return nil, nil, err } path := [][]byte{[]byte("request_status"), requestId[:], []byte("status")} status, err := LookUp(path, cert) return status, cert, err } func (agent *Agent) readStateRaw(canisterID string, paths [][][]byte) ([]byte, error) { req := Request{ Type: RequestTypeReadState, Sender: agent.Sender(), Paths: paths, IngressExpiry: uint64(agent.getExpiryDate().UnixNano()), } _, data, err := agent.signRequest(req) if err != nil { return nil, err } resp, err := agent.readStateEndpoint(canisterID, data) if err != nil { return nil, err } result := map[string][]byte{} err = cbor.Unmarshal(resp, &result) if err != nil { return nil, err } return result["certificate"], nil } func (agent *Agent) signRequest(req Request) (*RequestID, []byte, error) { requestID := NewRequestID(req) msg := []byte(IC_REQUEST_DOMAIN_SEPARATOR) msg = append(msg, requestID[:]...) sig, err := agent.identity.Sign(msg) if err != nil { return nil, nil, err } envelope := Envelope{ Content: req, SenderPubkey: agent.identity.PubKeyBytes(), SenderSig: sig, } marshaledEnvelope, err := cbor.Marshal(envelope) if err != nil { return nil, nil, err } return &requestID, marshaledEnvelope, nil } func (agent *Agent) GetCanisterControllers(canisterID string) ([]principal.Principal, error) { info, err := agent.GetCanisterInfo(canisterID, "controllers") if err != nil { return nil, err } var mResult [][]byte var result []principal.Principal err = cbor.Unmarshal(info, &mResult) if err != nil { return nil, err } for _, p := range mResult { result = append(result, principal.New(p)) } return result, nil } func (agent *Agent) GetCanisterModule(canisterID string) ([]byte, error) { return agent.GetCanisterInfo(canisterID, "module_hash") } func (agent Agent) GetCanisterInfo(canisterID, subPath string) ([]byte, error) { canisterBytes, err := principal.Decode(canisterID) if err != nil { return nil, err } paths := [][][]byte{{[]byte("canister"), canisterBytes, []byte(subPath)}} cert, err := agent.readStateRaw(canisterID, paths) if err != nil { return nil, err } path := [][]byte{[]byte("canister"), canisterBytes, []byte(subPath)} return LookUp(path, cert) } func (agent Agent) GetCanisterTime(canisterID string) ([]byte, error) { paths := [][][]byte{{[]byte("time")}} cert, err := agent.readStateRaw(canisterID, paths) if err != nil { return nil, err } path := [][]byte{[]byte("time")} return LookUp(path, cert) } <|start_filename|>utils/idl/interface_test.go<|end_filename|> package idl_test func ExampleInterface() { //v := new(idl.Bool) //idl.NewInterface(v) // Output: // 4449444c000173000000bf // 4449444c00017300000000 // 4449444c0001730000003f // 4449444c00017300004040 } <|start_filename|>utils/idl/Interface.go<|end_filename|> package idl import ( "bytes" "fmt" ) type Interface struct { _Type Type primType } //func NewInterface(t Type) *Interface { // return &Interface{ // Type: t, // } //} func (i *Interface) Fill(t Type) { i._Type = t } func (i *Interface) Decode(r *bytes.Reader) (interface{}, error) { return i._Type.Decode(r) } func (i Interface) EncodeType(tdt *TypeDefinitionTable) ([]byte, error) { return i._Type.EncodeType(tdt) } func (i Interface) EncodeValue(value interface{}) ([]byte, error) { return i._Type.EncodeValue(value) } func (i Interface) String() string { return fmt.Sprintf("interface %s", i._Type) } <|start_filename|>utils/idl/type.go<|end_filename|> package idl import ( "bytes" "fmt" ) var ( nullType int64 = -1 // 0x7f boolType int64 = -2 // 0x7e natType int64 = -3 // 0x7d intType int64 = -4 // 0x7c natXType int64 = -5 // 0x7b-0x78 intXType int64 = -9 // 0x77-0x73 floatXType int64 = -13 // 0x72 textType int64 = -15 // 0x71 reservedType int64 = -16 // 0x70 emptyType int64 = -17 // 0x6f optType int64 = -18 // 0x6e vecType int64 = -19 // 0x6d recType int64 = -20 // 0x6c varType int64 = -21 // 0x6b funcType int64 = -22 // 0x6a serviceType int64 = -23 // 0x69 principalType int64 = -24 // 0x68 ) type PrimType interface { prim() } type Type interface { // AddTypeDefinition adds itself to the definition table if it is not a primitive type. AddTypeDefinition(*TypeDefinitionTable) error // Decodes the value from the reader. Decode(*bytes.Reader) (interface{}, error) // Encodes the type. EncodeType(*TypeDefinitionTable) ([]byte, error) // Encodes the value. EncodeValue(v interface{}) ([]byte, error) Fill(v Type) fmt.Stringer } func getType(t int64) (Type, error) { // if t >= 0 { // if int(t) >= len(tds) { // return nil, fmt.Errorf("type index out of range: %d", t) // } // return tds[t], nil // } switch t { case nullType: return new(Null), nil case boolType: return new(Bool), nil case natType: return new(Nat), nil case intType: return new(Int), nil case natXType: return Nat8(), nil case natXType - 1: return Nat16(), nil case natXType - 2: return Nat32(), nil case natXType - 3: return Nat64(), nil case intXType: return Int8(), nil case intXType - 1: return Int16(), nil case intXType - 2: return Int32(), nil case intXType - 3: return Int64(), nil case floatXType: return Float32(), nil case floatXType - 1: return Float64(), nil case textType: return new(Text), nil case reservedType: return new(Reserved), nil case emptyType: return new(Empty), nil case principalType: return new(Principal), nil default: if t < -24 { return nil, &FormatError{ Description: "type: out of range", } } return nil, &FormatError{ Description: "type: not primitive", } } } type primType struct{} func (primType) AddTypeDefinition(_ *TypeDefinitionTable) error { return nil // No need to add primitive types to the type definition table. } func (primType) Fill(Type) { } func (primType) prim() {} <|start_filename|>example/registry/registry.go<|end_filename|> package registry import ( "errors" "github.com/golang/protobuf/proto" agent "github.com/mix-labs/IC-Go" "github.com/mix-labs/IC-Go/example/registry/proto/pb" ) const CanisterId = "rwlgt-iiaaa-aaaaa-aaaaa-cai" func getValue(agent *agent.Agent, key string) (*pb.RegistryGetValueResponse, error) { getValueResponse := new(pb.RegistryGetValueResponse) requestKey := []byte(key) request := &pb.RegistryGetValueRequest{ Version: nil, Key: requestKey, } requestBuf, err := proto.Marshal(request) if err != nil { return nil, err } resp, ErrMsg, err := agent.QueryRaw(CanisterId, "get_value", requestBuf) if ErrMsg != "" { return nil, errors.New(ErrMsg) } else if err != nil { return nil, err } err = proto.Unmarshal(resp, getValueResponse) if err != nil { return nil, err } return getValueResponse, nil } func GetRoutingTable(agent *agent.Agent) (*pb.RoutingTable, error) { routingTable := new(pb.RoutingTable) resp, err := getValue(agent, "routing_table") if err != nil { return nil, err } err = proto.Unmarshal(resp.Value, routingTable) if err != nil { return nil, err } return routingTable, nil } func GetSubnetList(agent *agent.Agent) (*pb.SubnetListRecord, error) { subnetList := new(pb.SubnetListRecord) resp, err := getValue(agent, "subnet_list") if err != nil { return nil, err } err = proto.Unmarshal(resp.Value, subnetList) if err != nil { return nil, err } return subnetList, nil } func GetSubnetRecord(agent *agent.Agent, subnetID string) (*pb.SubnetRecord, error) { subnetRecord := new(pb.SubnetRecord) key := "subnet_record_" + subnetID resp, err := getValue(agent, key) if err != nil { return nil, err } err = proto.Unmarshal(resp.Value, subnetRecord) if err != nil { return nil, err } return subnetRecord, nil } func GetNodeInfo(agent *agent.Agent, nodeID string) (*pb.NodeRecord, error) { nodeRecord := new(pb.NodeRecord) key := "node_record_" + nodeID resp, err := getValue(agent, key) if err != nil { return nil, err } err = proto.Unmarshal(resp.Value, nodeRecord) if err != nil { return nil, err } return nodeRecord, nil } func GetOperatorInfo(agent *agent.Agent, operatorID string) (*pb.NodeOperatorRecord, error) { operatorRecord := new(pb.NodeOperatorRecord) key := "node_operator_record_" + operatorID resp, err := getValue(agent, key) if err != nil { return nil, err } err = proto.Unmarshal(resp.Value, operatorRecord) if err != nil { return nil, err } return operatorRecord, nil } <|start_filename|>example/registry/proto/pb/node.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: node.proto package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ConnectionEndpoint_Protocol int32 const ( ConnectionEndpoint_PROTOCOL_UNSPECIFIED ConnectionEndpoint_Protocol = 0 ConnectionEndpoint_PROTOCOL_HTTP1 ConnectionEndpoint_Protocol = 1 ConnectionEndpoint_PROTOCOL_HTTP1_TLS_1_3 ConnectionEndpoint_Protocol = 2 ConnectionEndpoint_PROTOCOL_P2P1_TLS_1_3 ConnectionEndpoint_Protocol = 3 ) // Enum value maps for ConnectionEndpoint_Protocol. var ( ConnectionEndpoint_Protocol_name = map[int32]string{ 0: "PROTOCOL_UNSPECIFIED", 1: "PROTOCOL_HTTP1", 2: "PROTOCOL_HTTP1_TLS_1_3", 3: "PROTOCOL_P2P1_TLS_1_3", } ConnectionEndpoint_Protocol_value = map[string]int32{ "PROTOCOL_UNSPECIFIED": 0, "PROTOCOL_HTTP1": 1, "PROTOCOL_HTTP1_TLS_1_3": 2, "PROTOCOL_P2P1_TLS_1_3": 3, } ) func (x ConnectionEndpoint_Protocol) Enum() *ConnectionEndpoint_Protocol { p := new(ConnectionEndpoint_Protocol) *p = x return p } func (x ConnectionEndpoint_Protocol) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConnectionEndpoint_Protocol) Descriptor() protoreflect.EnumDescriptor { return file_node_proto_enumTypes[0].Descriptor() } func (ConnectionEndpoint_Protocol) Type() protoreflect.EnumType { return &file_node_proto_enumTypes[0] } func (x ConnectionEndpoint_Protocol) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConnectionEndpoint_Protocol.Descriptor instead. func (ConnectionEndpoint_Protocol) EnumDescriptor() ([]byte, []int) { return file_node_proto_rawDescGZIP(), []int{0, 0} } // A connection endpoint. type ConnectionEndpoint struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The IP address. Senders SHOULD use dotted-quad notation for IPv4 addresses // and RFC5952 representation for IPv6 addresses (which means that IPv6 // addresses are *not* enclosed in `[` and `]`, as they are not written // with the port in the same field). // // Clients MUST be prepared to accept IPv6 addresses in the forms shown in // RFC4291. IpAddr string `protobuf:"bytes,1,opt,name=ip_addr,json=ipAddr,proto3" json:"ip_addr,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` // Protocol that is used on this endpoint. If PROTOCOL_UNSPECIFIED then // code should default to PROTOCOL_HTTP1 for backwards compatability. Protocol ConnectionEndpoint_Protocol `protobuf:"varint,4,opt,name=protocol,proto3,enum=registry.node.v1.ConnectionEndpoint_Protocol" json:"protocol,omitempty"` } func (x *ConnectionEndpoint) Reset() { *x = ConnectionEndpoint{} if protoimpl.UnsafeEnabled { mi := &file_node_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConnectionEndpoint) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConnectionEndpoint) ProtoMessage() {} func (x *ConnectionEndpoint) ProtoReflect() protoreflect.Message { mi := &file_node_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConnectionEndpoint.ProtoReflect.Descriptor instead. func (*ConnectionEndpoint) Descriptor() ([]byte, []int) { return file_node_proto_rawDescGZIP(), []int{0} } func (x *ConnectionEndpoint) GetIpAddr() string { if x != nil { return x.IpAddr } return "" } func (x *ConnectionEndpoint) GetPort() uint32 { if x != nil { return x.Port } return 0 } func (x *ConnectionEndpoint) GetProtocol() ConnectionEndpoint_Protocol { if x != nil { return x.Protocol } return ConnectionEndpoint_PROTOCOL_UNSPECIFIED } type FlowEndpoint struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The flow identifier (tag). This has to be unique per NodeRecord. FlowTag uint32 `protobuf:"varint,1,opt,name=flow_tag,json=flowTag,proto3" json:"flow_tag,omitempty"` // The IP/port for this flow. Endpoint *ConnectionEndpoint `protobuf:"bytes,2,opt,name=endpoint,proto3" json:"endpoint,omitempty"` } func (x *FlowEndpoint) Reset() { *x = FlowEndpoint{} if protoimpl.UnsafeEnabled { mi := &file_node_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *FlowEndpoint) String() string { return protoimpl.X.MessageStringOf(x) } func (*FlowEndpoint) ProtoMessage() {} func (x *FlowEndpoint) ProtoReflect() protoreflect.Message { mi := &file_node_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use FlowEndpoint.ProtoReflect.Descriptor instead. func (*FlowEndpoint) Descriptor() ([]byte, []int) { return file_node_proto_rawDescGZIP(), []int{1} } func (x *FlowEndpoint) GetFlowTag() uint32 { if x != nil { return x.FlowTag } return 0 } func (x *FlowEndpoint) GetEndpoint() *ConnectionEndpoint { if x != nil { return x.Endpoint } return nil } // A node: one machine running a replica instance. type NodeRecord struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The endpoint where this node receives xnet messages. Xnet *ConnectionEndpoint `protobuf:"bytes,5,opt,name=xnet,proto3" json:"xnet,omitempty"` // The endpoint where this node receives http requests. Http *ConnectionEndpoint `protobuf:"bytes,6,opt,name=http,proto3" json:"http,omitempty"` // The P2P flow end points. P2PFlowEndpoints []*FlowEndpoint `protobuf:"bytes,8,rep,name=p2p_flow_endpoints,json=p2pFlowEndpoints,proto3" json:"p2p_flow_endpoints,omitempty"` // Endpoint where the node provides Prometheus format metrics over HTTP PrometheusMetricsHttp *ConnectionEndpoint `protobuf:"bytes,10,opt,name=prometheus_metrics_http,json=prometheusMetricsHttp,proto3" json:"prometheus_metrics_http,omitempty"` // Endpoints on which the public API is served. PublicApi []*ConnectionEndpoint `protobuf:"bytes,11,rep,name=public_api,json=publicApi,proto3" json:"public_api,omitempty"` // Endpoints on which private APIs are served. PrivateApi []*ConnectionEndpoint `protobuf:"bytes,12,rep,name=private_api,json=privateApi,proto3" json:"private_api,omitempty"` // Endpoints on which metrics compatible with the Prometheus export // format are served. PrometheusMetrics []*ConnectionEndpoint `protobuf:"bytes,13,rep,name=prometheus_metrics,json=prometheusMetrics,proto3" json:"prometheus_metrics,omitempty"` // Endpoints on which the XNet API is served XnetApi []*ConnectionEndpoint `protobuf:"bytes,14,rep,name=xnet_api,json=xnetApi,proto3" json:"xnet_api,omitempty"` // The id of the node operator that added this node. NodeOperatorId []byte `protobuf:"bytes,15,opt,name=node_operator_id,json=nodeOperatorId,proto3" json:"node_operator_id,omitempty"` } func (x *NodeRecord) Reset() { *x = NodeRecord{} if protoimpl.UnsafeEnabled { mi := &file_node_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeRecord) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeRecord) ProtoMessage() {} func (x *NodeRecord) ProtoReflect() protoreflect.Message { mi := &file_node_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NodeRecord.ProtoReflect.Descriptor instead. func (*NodeRecord) Descriptor() ([]byte, []int) { return file_node_proto_rawDescGZIP(), []int{2} } func (x *NodeRecord) GetXnet() *ConnectionEndpoint { if x != nil { return x.Xnet } return nil } func (x *NodeRecord) GetHttp() *ConnectionEndpoint { if x != nil { return x.Http } return nil } func (x *NodeRecord) GetP2PFlowEndpoints() []*FlowEndpoint { if x != nil { return x.P2PFlowEndpoints } return nil } func (x *NodeRecord) GetPrometheusMetricsHttp() *ConnectionEndpoint { if x != nil { return x.PrometheusMetricsHttp } return nil } func (x *NodeRecord) GetPublicApi() []*ConnectionEndpoint { if x != nil { return x.PublicApi } return nil } func (x *NodeRecord) GetPrivateApi() []*ConnectionEndpoint { if x != nil { return x.PrivateApi } return nil } func (x *NodeRecord) GetPrometheusMetrics() []*ConnectionEndpoint { if x != nil { return x.PrometheusMetrics } return nil } func (x *NodeRecord) GetXnetApi() []*ConnectionEndpoint { if x != nil { return x.XnetApi } return nil } func (x *NodeRecord) GetNodeOperatorId() []byte { if x != nil { return x.NodeOperatorId } return nil } var File_node_proto protoreflect.FileDescriptor var file_node_proto_rawDesc = []byte{ 0x0a, 0x0a, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x10, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x22, 0xfd, 0x01, 0x0a, 0x12, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x69, 0x70, 0x41, 0x64, 0x64, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x49, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2d, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x6f, 0x0a, 0x08, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x18, 0x0a, 0x14, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x12, 0x0a, 0x0e, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x5f, 0x48, 0x54, 0x54, 0x50, 0x31, 0x10, 0x01, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x5f, 0x48, 0x54, 0x54, 0x50, 0x31, 0x5f, 0x54, 0x4c, 0x53, 0x5f, 0x31, 0x5f, 0x33, 0x10, 0x02, 0x12, 0x19, 0x0a, 0x15, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x5f, 0x50, 0x32, 0x50, 0x31, 0x5f, 0x54, 0x4c, 0x53, 0x5f, 0x31, 0x5f, 0x33, 0x10, 0x03, 0x22, 0x6b, 0x0a, 0x0c, 0x46, 0x6c, 0x6f, 0x77, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x66, 0x6c, 0x6f, 0x77, 0x54, 0x61, 0x67, 0x12, 0x40, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x22, 0x83, 0x06, 0x0a, 0x0a, 0x4e, 0x6f, 0x64, 0x65, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x38, 0x0a, 0x04, 0x78, 0x6e, 0x65, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x04, 0x78, 0x6e, 0x65, 0x74, 0x12, 0x38, 0x0a, 0x04, 0x68, 0x74, 0x74, 0x70, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x04, 0x68, 0x74, 0x74, 0x70, 0x12, 0x4c, 0x0a, 0x12, 0x70, 0x32, 0x70, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x6c, 0x6f, 0x77, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x10, 0x70, 0x32, 0x70, 0x46, 0x6c, 0x6f, 0x77, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x5c, 0x0a, 0x17, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x15, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x48, 0x74, 0x74, 0x70, 0x12, 0x43, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x61, 0x70, 0x69, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x41, 0x70, 0x69, 0x12, 0x45, 0x0a, 0x0b, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x61, 0x70, 0x69, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x0a, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x41, 0x70, 0x69, 0x12, 0x53, 0x0a, 0x12, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x5f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x11, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x12, 0x3f, 0x0a, 0x08, 0x78, 0x6e, 0x65, 0x74, 0x5f, 0x61, 0x70, 0x69, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x52, 0x07, 0x78, 0x6e, 0x65, 0x74, 0x41, 0x70, 0x69, 0x12, 0x28, 0x0a, 0x10, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x6e, 0x6f, 0x64, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x49, 0x64, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x4a, 0x04, 0x08, 0x03, 0x10, 0x04, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x4a, 0x04, 0x08, 0x07, 0x10, 0x08, 0x4a, 0x04, 0x08, 0x09, 0x10, 0x0a, 0x52, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x52, 0x0d, 0x67, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x5f, 0x61, 0x64, 0x76, 0x65, 0x72, 0x74, 0x52, 0x0e, 0x67, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, 0x0f, 0x67, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x5f, 0x61, 0x72, 0x74, 0x69, 0x66, 0x61, 0x63, 0x74, 0x52, 0x19, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x74, 0x6c, 0x73, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x52, 0x11, 0x64, 0x63, 0x6f, 0x70, 0x5f, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_node_proto_rawDescOnce sync.Once file_node_proto_rawDescData = file_node_proto_rawDesc ) func file_node_proto_rawDescGZIP() []byte { file_node_proto_rawDescOnce.Do(func() { file_node_proto_rawDescData = protoimpl.X.CompressGZIP(file_node_proto_rawDescData) }) return file_node_proto_rawDescData } var file_node_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_node_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_node_proto_goTypes = []interface{}{ (ConnectionEndpoint_Protocol)(0), // 0: registry.node.v1.ConnectionEndpoint.Protocol (*ConnectionEndpoint)(nil), // 1: registry.node.v1.ConnectionEndpoint (*FlowEndpoint)(nil), // 2: registry.node.v1.FlowEndpoint (*NodeRecord)(nil), // 3: registry.node.v1.NodeRecord } var file_node_proto_depIdxs = []int32{ 0, // 0: registry.node.v1.ConnectionEndpoint.protocol:type_name -> registry.node.v1.ConnectionEndpoint.Protocol 1, // 1: registry.node.v1.FlowEndpoint.endpoint:type_name -> registry.node.v1.ConnectionEndpoint 1, // 2: registry.node.v1.NodeRecord.xnet:type_name -> registry.node.v1.ConnectionEndpoint 1, // 3: registry.node.v1.NodeRecord.http:type_name -> registry.node.v1.ConnectionEndpoint 2, // 4: registry.node.v1.NodeRecord.p2p_flow_endpoints:type_name -> registry.node.v1.FlowEndpoint 1, // 5: registry.node.v1.NodeRecord.prometheus_metrics_http:type_name -> registry.node.v1.ConnectionEndpoint 1, // 6: registry.node.v1.NodeRecord.public_api:type_name -> registry.node.v1.ConnectionEndpoint 1, // 7: registry.node.v1.NodeRecord.private_api:type_name -> registry.node.v1.ConnectionEndpoint 1, // 8: registry.node.v1.NodeRecord.prometheus_metrics:type_name -> registry.node.v1.ConnectionEndpoint 1, // 9: registry.node.v1.NodeRecord.xnet_api:type_name -> registry.node.v1.ConnectionEndpoint 10, // [10:10] is the sub-list for method output_type 10, // [10:10] is the sub-list for method input_type 10, // [10:10] is the sub-list for extension type_name 10, // [10:10] is the sub-list for extension extendee 0, // [0:10] is the sub-list for field type_name } func init() { file_node_proto_init() } func file_node_proto_init() { if File_node_proto != nil { return } if !protoimpl.UnsafeEnabled { file_node_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConnectionEndpoint); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_node_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*FlowEndpoint); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_node_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeRecord); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_node_proto_rawDesc, NumEnums: 1, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_node_proto_goTypes, DependencyIndexes: file_node_proto_depIdxs, EnumInfos: file_node_proto_enumTypes, MessageInfos: file_node_proto_msgTypes, }.Build() File_node_proto = out.File file_node_proto_rawDesc = nil file_node_proto_goTypes = nil file_node_proto_depIdxs = nil } <|start_filename|>example/registry/proto/pb/node_operator.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: node_operator.proto package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // A record for a node operator. Each node operator is associated with a // unique principal id, a.k.a. NOID. // // Note that while a node operator might host nodes for more than // one funding parter, its principal ID must be unique. type NodeOperatorRecord struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The principal id of the node operator. This principal is the entity that // is able to add and remove nodes. // // This must be unique across NodeOperatorRecords. NodeOperatorPrincipalId []byte `protobuf:"bytes,1,opt,name=node_operator_principal_id,json=nodeOperatorPrincipalId,proto3" json:"node_operator_principal_id,omitempty"` // The remaining number of nodes that could be added by this node operator. // This number should never go below 0. NodeAllowance uint64 `protobuf:"varint,2,opt,name=node_allowance,json=nodeAllowance,proto3" json:"node_allowance,omitempty"` // The principal id of this node operator's provider. NodeProviderPrincipalId []byte `protobuf:"bytes,3,opt,name=node_provider_principal_id,json=nodeProviderPrincipalId,proto3" json:"node_provider_principal_id,omitempty"` // The ID of the data center where this Node Operator hosts nodes. DcId string `protobuf:"bytes,4,opt,name=dc_id,json=dcId,proto3" json:"dc_id,omitempty"` // A map from node type to the number of nodes for which the associated Node // Provider should be rewarded. RewardableNodes map[string]uint32 `protobuf:"bytes,5,rep,name=rewardable_nodes,json=rewardableNodes,proto3" json:"rewardable_nodes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` } func (x *NodeOperatorRecord) Reset() { *x = NodeOperatorRecord{} if protoimpl.UnsafeEnabled { mi := &file_node_operator_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NodeOperatorRecord) String() string { return protoimpl.X.MessageStringOf(x) } func (*NodeOperatorRecord) ProtoMessage() {} func (x *NodeOperatorRecord) ProtoReflect() protoreflect.Message { mi := &file_node_operator_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NodeOperatorRecord.ProtoReflect.Descriptor instead. func (*NodeOperatorRecord) Descriptor() ([]byte, []int) { return file_node_operator_proto_rawDescGZIP(), []int{0} } func (x *NodeOperatorRecord) GetNodeOperatorPrincipalId() []byte { if x != nil { return x.NodeOperatorPrincipalId } return nil } func (x *NodeOperatorRecord) GetNodeAllowance() uint64 { if x != nil { return x.NodeAllowance } return 0 } func (x *NodeOperatorRecord) GetNodeProviderPrincipalId() []byte { if x != nil { return x.NodeProviderPrincipalId } return nil } func (x *NodeOperatorRecord) GetDcId() string { if x != nil { return x.DcId } return "" } func (x *NodeOperatorRecord) GetRewardableNodes() map[string]uint32 { if x != nil { return x.RewardableNodes } return nil } /// The payload of a request to remove Node Operator records from the Registry type RemoveNodeOperatorsPayload struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields NodeOperatorsToRemove [][]byte `protobuf:"bytes,1,rep,name=node_operators_to_remove,json=nodeOperatorsToRemove,proto3" json:"node_operators_to_remove,omitempty"` } func (x *RemoveNodeOperatorsPayload) Reset() { *x = RemoveNodeOperatorsPayload{} if protoimpl.UnsafeEnabled { mi := &file_node_operator_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RemoveNodeOperatorsPayload) String() string { return protoimpl.X.MessageStringOf(x) } func (*RemoveNodeOperatorsPayload) ProtoMessage() {} func (x *RemoveNodeOperatorsPayload) ProtoReflect() protoreflect.Message { mi := &file_node_operator_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RemoveNodeOperatorsPayload.ProtoReflect.Descriptor instead. func (*RemoveNodeOperatorsPayload) Descriptor() ([]byte, []int) { return file_node_operator_proto_rawDescGZIP(), []int{1} } func (x *RemoveNodeOperatorsPayload) GetNodeOperatorsToRemove() [][]byte { if x != nil { return x.NodeOperatorsToRemove } return nil } var File_node_operator_proto protoreflect.FileDescriptor var file_node_operator_proto_rawDesc = []byte{ 0x0a, 0x13, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x19, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x76, 0x31, 0x22, 0xfd, 0x02, 0x0a, 0x12, 0x4e, 0x6f, 0x64, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x3b, 0x0a, 0x1a, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x17, 0x6e, 0x6f, 0x64, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x25, 0x0a, 0x0e, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0d, 0x6e, 0x6f, 0x64, 0x65, 0x41, 0x6c, 0x6c, 0x6f, 0x77, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x3b, 0x0a, 0x1a, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x17, 0x6e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x13, 0x0a, 0x05, 0x64, 0x63, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x63, 0x49, 0x64, 0x12, 0x6d, 0x0a, 0x10, 0x72, 0x65, 0x77, 0x61, 0x72, 0x64, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x6e, 0x6f, 0x64, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x42, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x2e, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x61, 0x62, 0x6c, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0f, 0x72, 0x65, 0x77, 0x61, 0x72, 0x64, 0x61, 0x62, 0x6c, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x73, 0x1a, 0x42, 0x0a, 0x14, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x61, 0x62, 0x6c, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x55, 0x0a, 0x1a, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x4e, 0x6f, 0x64, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x37, 0x0a, 0x18, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x72, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x15, 0x6e, 0x6f, 0x64, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x54, 0x6f, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_node_operator_proto_rawDescOnce sync.Once file_node_operator_proto_rawDescData = file_node_operator_proto_rawDesc ) func file_node_operator_proto_rawDescGZIP() []byte { file_node_operator_proto_rawDescOnce.Do(func() { file_node_operator_proto_rawDescData = protoimpl.X.CompressGZIP(file_node_operator_proto_rawDescData) }) return file_node_operator_proto_rawDescData } var file_node_operator_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_node_operator_proto_goTypes = []interface{}{ (*NodeOperatorRecord)(nil), // 0: registry.node_operator.v1.NodeOperatorRecord (*RemoveNodeOperatorsPayload)(nil), // 1: registry.node_operator.v1.RemoveNodeOperatorsPayload nil, // 2: registry.node_operator.v1.NodeOperatorRecord.RewardableNodesEntry } var file_node_operator_proto_depIdxs = []int32{ 2, // 0: registry.node_operator.v1.NodeOperatorRecord.rewardable_nodes:type_name -> registry.node_operator.v1.NodeOperatorRecord.RewardableNodesEntry 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_node_operator_proto_init() } func file_node_operator_proto_init() { if File_node_operator_proto != nil { return } if !protoimpl.UnsafeEnabled { file_node_operator_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NodeOperatorRecord); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_node_operator_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RemoveNodeOperatorsPayload); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_node_operator_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_node_operator_proto_goTypes, DependencyIndexes: file_node_operator_proto_depIdxs, MessageInfos: file_node_operator_proto_msgTypes, }.Build() File_node_operator_proto = out.File file_node_operator_proto_rawDesc = nil file_node_operator_proto_goTypes = nil file_node_operator_proto_depIdxs = nil } <|start_filename|>example/registry/proto/pb/subnet.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: subnet.proto package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Represents the type of subnet. Subnets of different type might exhibit different // behavior, e.g. being more restrictive in what operations are allowed or privileged // compared to other subnet types. type SubnetType int32 const ( SubnetType_SUBNET_TYPE_UNSPECIFIED SubnetType = 0 // A normal subnet where no restrictions are applied. SubnetType_SUBNET_TYPE_APPLICATION SubnetType = 1 // A more privileged subnet where certain restrictions are applied, // like not charging for cycles or restricting who can create and // install canisters on it. SubnetType_SUBNET_TYPE_SYSTEM SubnetType = 2 // A subnet type that is like application subnets but can have some // additional features. SubnetType_SUBNET_TYPE_VERIFIED_APPLICATION SubnetType = 4 ) // Enum value maps for SubnetType. var ( SubnetType_name = map[int32]string{ 0: "SUBNET_TYPE_UNSPECIFIED", 1: "SUBNET_TYPE_APPLICATION", 2: "SUBNET_TYPE_SYSTEM", 4: "SUBNET_TYPE_VERIFIED_APPLICATION", } SubnetType_value = map[string]int32{ "SUBNET_TYPE_UNSPECIFIED": 0, "SUBNET_TYPE_APPLICATION": 1, "SUBNET_TYPE_SYSTEM": 2, "SUBNET_TYPE_VERIFIED_APPLICATION": 4, } ) func (x SubnetType) Enum() *SubnetType { p := new(SubnetType) *p = x return p } func (x SubnetType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SubnetType) Descriptor() protoreflect.EnumDescriptor { return file_subnet_proto_enumTypes[0].Descriptor() } func (SubnetType) Type() protoreflect.EnumType { return &file_subnet_proto_enumTypes[0] } func (x SubnetType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use SubnetType.Descriptor instead. func (SubnetType) EnumDescriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{0} } // A subnet: A logical group of nodes that run consensus type SubnetRecord struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Membership [][]byte `protobuf:"bytes,3,rep,name=membership,proto3" json:"membership,omitempty"` // Maximum amount of bytes per message. This is a hard cap, which means // ingress messages greater than the limit will be dropped. MaxIngressBytesPerMessage uint64 `protobuf:"varint,5,opt,name=max_ingress_bytes_per_message,json=maxIngressBytesPerMessage,proto3" json:"max_ingress_bytes_per_message,omitempty"` // Unit delay for blockmaker (in milliseconds). UnitDelayMillis uint64 `protobuf:"varint,7,opt,name=unit_delay_millis,json=unitDelayMillis,proto3" json:"unit_delay_millis,omitempty"` // Initial delay for notary (in milliseconds), to give time to rank-0 block // propagation. InitialNotaryDelayMillis uint64 `protobuf:"varint,8,opt,name=initial_notary_delay_millis,json=initialNotaryDelayMillis,proto3" json:"initial_notary_delay_millis,omitempty"` // ID of the Replica version to run ReplicaVersionId string `protobuf:"bytes,9,opt,name=replica_version_id,json=replicaVersionId,proto3" json:"replica_version_id,omitempty"` // The length of all DKG intervals. The DKG interval length is the number of rounds following the DKG summary. DkgIntervalLength uint64 `protobuf:"varint,10,opt,name=dkg_interval_length,json=dkgIntervalLength,proto3" json:"dkg_interval_length,omitempty"` // Gossip Config GossipConfig *GossipConfig `protobuf:"bytes,13,opt,name=gossip_config,json=gossipConfig,proto3" json:"gossip_config,omitempty"` // If set to yes, the subnet starts as a (new) NNS StartAsNns bool `protobuf:"varint,14,opt,name=start_as_nns,json=startAsNns,proto3" json:"start_as_nns,omitempty"` // The type of subnet. SubnetType SubnetType `protobuf:"varint,15,opt,name=subnet_type,json=subnetType,proto3,enum=registry.subnet.v1.SubnetType" json:"subnet_type,omitempty"` // The upper bound for the number of dealings we allow in a block. DkgDealingsPerBlock uint64 `protobuf:"varint,16,opt,name=dkg_dealings_per_block,json=dkgDealingsPerBlock,proto3" json:"dkg_dealings_per_block,omitempty"` // If `true`, the subnet will be halted: it will no longer create or execute blocks. IsHalted bool `protobuf:"varint,17,opt,name=is_halted,json=isHalted,proto3" json:"is_halted,omitempty"` // Max number of ingress messages per block. MaxIngressMessagesPerBlock uint64 `protobuf:"varint,18,opt,name=max_ingress_messages_per_block,json=maxIngressMessagesPerBlock,proto3" json:"max_ingress_messages_per_block,omitempty"` // The maximum combined size of the ingress and xnet messages that fit into a block. MaxBlockPayloadSize uint64 `protobuf:"varint,19,opt,name=max_block_payload_size,json=maxBlockPayloadSize,proto3" json:"max_block_payload_size,omitempty"` // The maximum number of instructions a message can execute. // See the comments in `subnet_config.rs` for more details. MaxInstructionsPerMessage uint64 `protobuf:"varint,20,opt,name=max_instructions_per_message,json=maxInstructionsPerMessage,proto3" json:"max_instructions_per_message,omitempty"` // The maximum number of instructions a round can execute. // See the comments in `subnet_config.rs` for more details. MaxInstructionsPerRound uint64 `protobuf:"varint,21,opt,name=max_instructions_per_round,json=maxInstructionsPerRound,proto3" json:"max_instructions_per_round,omitempty"` // The maximum number of instructions an `install_code` message can execute. // See the comments in `subnet_config.rs` for more details. MaxInstructionsPerInstallCode uint64 `protobuf:"varint,22,opt,name=max_instructions_per_install_code,json=maxInstructionsPerInstallCode,proto3" json:"max_instructions_per_install_code,omitempty"` // Information on whether a feature is supported by this subnet. Features *SubnetFeatures `protobuf:"bytes,23,opt,name=features,proto3" json:"features,omitempty"` // The number of canisters allowed to be created on this subnet. // // A value of 0 is equivalent to setting no limit. This also provides an easy way // to maintain compatibility of different versions of replica and registry. MaxNumberOfCanisters uint64 `protobuf:"varint,24,opt,name=max_number_of_canisters,json=maxNumberOfCanisters,proto3" json:"max_number_of_canisters,omitempty"` // The list of public keys whose owners have "readonly" SSH access to all replicas on this subnet, // in case it is necessary to perform subnet recovery. SshReadonlyAccess []string `protobuf:"bytes,25,rep,name=ssh_readonly_access,json=sshReadonlyAccess,proto3" json:"ssh_readonly_access,omitempty"` // The list of public keys whose owners have "backup" SSH access to nodes on the NNS subnet // to make sure the NNS can be backed up. SshBackupAccess []string `protobuf:"bytes,26,rep,name=ssh_backup_access,json=sshBackupAccess,proto3" json:"ssh_backup_access,omitempty"` // ECDSA Config EcdsaConfig *EcdsaConfig `protobuf:"bytes,27,opt,name=ecdsa_config,json=ecdsaConfig,proto3" json:"ecdsa_config,omitempty"` } func (x *SubnetRecord) Reset() { *x = SubnetRecord{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SubnetRecord) String() string { return protoimpl.X.MessageStringOf(x) } func (*SubnetRecord) ProtoMessage() {} func (x *SubnetRecord) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SubnetRecord.ProtoReflect.Descriptor instead. func (*SubnetRecord) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{0} } func (x *SubnetRecord) GetMembership() [][]byte { if x != nil { return x.Membership } return nil } func (x *SubnetRecord) GetMaxIngressBytesPerMessage() uint64 { if x != nil { return x.MaxIngressBytesPerMessage } return 0 } func (x *SubnetRecord) GetUnitDelayMillis() uint64 { if x != nil { return x.UnitDelayMillis } return 0 } func (x *SubnetRecord) GetInitialNotaryDelayMillis() uint64 { if x != nil { return x.InitialNotaryDelayMillis } return 0 } func (x *SubnetRecord) GetReplicaVersionId() string { if x != nil { return x.ReplicaVersionId } return "" } func (x *SubnetRecord) GetDkgIntervalLength() uint64 { if x != nil { return x.DkgIntervalLength } return 0 } func (x *SubnetRecord) GetGossipConfig() *GossipConfig { if x != nil { return x.GossipConfig } return nil } func (x *SubnetRecord) GetStartAsNns() bool { if x != nil { return x.StartAsNns } return false } func (x *SubnetRecord) GetSubnetType() SubnetType { if x != nil { return x.SubnetType } return SubnetType_SUBNET_TYPE_UNSPECIFIED } func (x *SubnetRecord) GetDkgDealingsPerBlock() uint64 { if x != nil { return x.DkgDealingsPerBlock } return 0 } func (x *SubnetRecord) GetIsHalted() bool { if x != nil { return x.IsHalted } return false } func (x *SubnetRecord) GetMaxIngressMessagesPerBlock() uint64 { if x != nil { return x.MaxIngressMessagesPerBlock } return 0 } func (x *SubnetRecord) GetMaxBlockPayloadSize() uint64 { if x != nil { return x.MaxBlockPayloadSize } return 0 } func (x *SubnetRecord) GetMaxInstructionsPerMessage() uint64 { if x != nil { return x.MaxInstructionsPerMessage } return 0 } func (x *SubnetRecord) GetMaxInstructionsPerRound() uint64 { if x != nil { return x.MaxInstructionsPerRound } return 0 } func (x *SubnetRecord) GetMaxInstructionsPerInstallCode() uint64 { if x != nil { return x.MaxInstructionsPerInstallCode } return 0 } func (x *SubnetRecord) GetFeatures() *SubnetFeatures { if x != nil { return x.Features } return nil } func (x *SubnetRecord) GetMaxNumberOfCanisters() uint64 { if x != nil { return x.MaxNumberOfCanisters } return 0 } func (x *SubnetRecord) GetSshReadonlyAccess() []string { if x != nil { return x.SshReadonlyAccess } return nil } func (x *SubnetRecord) GetSshBackupAccess() []string { if x != nil { return x.SshBackupAccess } return nil } func (x *SubnetRecord) GetEcdsaConfig() *EcdsaConfig { if x != nil { return x.EcdsaConfig } return nil } // Contains the initial DKG transcripts for the subnet and materials to construct a base CUP (i.e. // a CUP with no dependencies on previous CUPs or blocks). Such CUP materials can be used to // construct the genesis CUP or a recovery CUP in the event of a subnet stall. type CatchUpPackageContents struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Initial non-interactive low-threshold DKG transcript InitialNiDkgTranscriptLowThreshold *InitialNiDkgTranscriptRecord `protobuf:"bytes,1,opt,name=initial_ni_dkg_transcript_low_threshold,json=initialNiDkgTranscriptLowThreshold,proto3" json:"initial_ni_dkg_transcript_low_threshold,omitempty"` // Initial non-interactive high-threshold DKG transcript InitialNiDkgTranscriptHighThreshold *InitialNiDkgTranscriptRecord `protobuf:"bytes,2,opt,name=initial_ni_dkg_transcript_high_threshold,json=initialNiDkgTranscriptHighThreshold,proto3" json:"initial_ni_dkg_transcript_high_threshold,omitempty"` // The blockchain height that the CUP should have Height uint64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"` // Block time for the CUP's block Time uint64 `protobuf:"varint,4,opt,name=time,proto3" json:"time,omitempty"` // The hash of the state that the subnet should use StateHash []byte `protobuf:"bytes,5,opt,name=state_hash,json=stateHash,proto3" json:"state_hash,omitempty"` // A uri from which data to replace the registry local store should be downloaded RegistryStoreUri *RegistryStoreUri `protobuf:"bytes,6,opt,name=registry_store_uri,json=registryStoreUri,proto3" json:"registry_store_uri,omitempty"` } func (x *CatchUpPackageContents) Reset() { *x = CatchUpPackageContents{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CatchUpPackageContents) String() string { return protoimpl.X.MessageStringOf(x) } func (*CatchUpPackageContents) ProtoMessage() {} func (x *CatchUpPackageContents) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CatchUpPackageContents.ProtoReflect.Descriptor instead. func (*CatchUpPackageContents) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{1} } func (x *CatchUpPackageContents) GetInitialNiDkgTranscriptLowThreshold() *InitialNiDkgTranscriptRecord { if x != nil { return x.InitialNiDkgTranscriptLowThreshold } return nil } func (x *CatchUpPackageContents) GetInitialNiDkgTranscriptHighThreshold() *InitialNiDkgTranscriptRecord { if x != nil { return x.InitialNiDkgTranscriptHighThreshold } return nil } func (x *CatchUpPackageContents) GetHeight() uint64 { if x != nil { return x.Height } return 0 } func (x *CatchUpPackageContents) GetTime() uint64 { if x != nil { return x.Time } return 0 } func (x *CatchUpPackageContents) GetStateHash() []byte { if x != nil { return x.StateHash } return nil } func (x *CatchUpPackageContents) GetRegistryStoreUri() *RegistryStoreUri { if x != nil { return x.RegistryStoreUri } return nil } type RegistryStoreUri struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields /// The uri at which the registry store data should be retrieved. The data /// must be provided as gzipped tar archive Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` /// A SHA-256, hex encoded hash of the contents of the data stored at the /// provided URI Hash string `protobuf:"bytes,2,opt,name=hash,proto3" json:"hash,omitempty"` /// The registry version that should be used for the catch up package contents RegistryVersion uint64 `protobuf:"varint,3,opt,name=registry_version,json=registryVersion,proto3" json:"registry_version,omitempty"` } func (x *RegistryStoreUri) Reset() { *x = RegistryStoreUri{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryStoreUri) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryStoreUri) ProtoMessage() {} func (x *RegistryStoreUri) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryStoreUri.ProtoReflect.Descriptor instead. func (*RegistryStoreUri) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{2} } func (x *RegistryStoreUri) GetUri() string { if x != nil { return x.Uri } return "" } func (x *RegistryStoreUri) GetHash() string { if x != nil { return x.Hash } return "" } func (x *RegistryStoreUri) GetRegistryVersion() uint64 { if x != nil { return x.RegistryVersion } return 0 } // A list of subnet ids of all subnets present in this instance of the IC. type SubnetListRecord struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Subnets [][]byte `protobuf:"bytes,2,rep,name=subnets,proto3" json:"subnets,omitempty"` } func (x *SubnetListRecord) Reset() { *x = SubnetListRecord{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SubnetListRecord) String() string { return protoimpl.X.MessageStringOf(x) } func (*SubnetListRecord) ProtoMessage() {} func (x *SubnetListRecord) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SubnetListRecord.ProtoReflect.Descriptor instead. func (*SubnetListRecord) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{3} } func (x *SubnetListRecord) GetSubnets() [][]byte { if x != nil { return x.Subnets } return nil } // Initial non-interactive DKG transcript record type InitialNiDkgTranscriptRecord struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Id *NiDkgId `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Threshold uint32 `protobuf:"varint,2,opt,name=threshold,proto3" json:"threshold,omitempty"` Committee [][]byte `protobuf:"bytes,3,rep,name=committee,proto3" json:"committee,omitempty"` RegistryVersion uint64 `protobuf:"varint,4,opt,name=registry_version,json=registryVersion,proto3" json:"registry_version,omitempty"` InternalCspTranscript []byte `protobuf:"bytes,5,opt,name=internal_csp_transcript,json=internalCspTranscript,proto3" json:"internal_csp_transcript,omitempty"` } func (x *InitialNiDkgTranscriptRecord) Reset() { *x = InitialNiDkgTranscriptRecord{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *InitialNiDkgTranscriptRecord) String() string { return protoimpl.X.MessageStringOf(x) } func (*InitialNiDkgTranscriptRecord) ProtoMessage() {} func (x *InitialNiDkgTranscriptRecord) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InitialNiDkgTranscriptRecord.ProtoReflect.Descriptor instead. func (*InitialNiDkgTranscriptRecord) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{4} } func (x *InitialNiDkgTranscriptRecord) GetId() *NiDkgId { if x != nil { return x.Id } return nil } func (x *InitialNiDkgTranscriptRecord) GetThreshold() uint32 { if x != nil { return x.Threshold } return 0 } func (x *InitialNiDkgTranscriptRecord) GetCommittee() [][]byte { if x != nil { return x.Committee } return nil } func (x *InitialNiDkgTranscriptRecord) GetRegistryVersion() uint64 { if x != nil { return x.RegistryVersion } return 0 } func (x *InitialNiDkgTranscriptRecord) GetInternalCspTranscript() []byte { if x != nil { return x.InternalCspTranscript } return nil } // Per subnet P2P configuration // Note: protoc is mangling the name P2PConfig to P2pConfig type GossipConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // max outstanding request per peer MIN/DEFAULT/MAX 1/20/200 MaxArtifactStreamsPerPeer uint32 `protobuf:"varint,1,opt,name=max_artifact_streams_per_peer,json=maxArtifactStreamsPerPeer,proto3" json:"max_artifact_streams_per_peer,omitempty"` // timeout for a outstanding request 3_000/15_000/180_000 MaxChunkWaitMs uint32 `protobuf:"varint,2,opt,name=max_chunk_wait_ms,json=maxChunkWaitMs,proto3" json:"max_chunk_wait_ms,omitempty"` // max duplicate requests in underutilized networks 1/28/6000 MaxDuplicity uint32 `protobuf:"varint,3,opt,name=max_duplicity,json=maxDuplicity,proto3" json:"max_duplicity,omitempty"` // maximum chunk size supported on this subnet 1024/4096/131_072 MaxChunkSize uint32 `protobuf:"varint,4,opt,name=max_chunk_size,json=maxChunkSize,proto3" json:"max_chunk_size,omitempty"` // history size for receive check 1_000/5_000/30_000 ReceiveCheckCacheSize uint32 `protobuf:"varint,5,opt,name=receive_check_cache_size,json=receiveCheckCacheSize,proto3" json:"receive_check_cache_size,omitempty"` // period for re evaluating the priority function. 1_000/3_000/30_000 PfnEvaluationPeriodMs uint32 `protobuf:"varint,6,opt,name=pfn_evaluation_period_ms,json=pfnEvaluationPeriodMs,proto3" json:"pfn_evaluation_period_ms,omitempty"` // period for polling the registry for updates 1_000/3_000/30_000 RegistryPollPeriodMs uint32 `protobuf:"varint,7,opt,name=registry_poll_period_ms,json=registryPollPeriodMs,proto3" json:"registry_poll_period_ms,omitempty"` // period for sending a retransmission request RetransmissionRequestMs uint32 `protobuf:"varint,8,opt,name=retransmission_request_ms,json=retransmissionRequestMs,proto3" json:"retransmission_request_ms,omitempty"` // config for advert distribution. // If this field is not specified, the feature is turned off. AdvertConfig *GossipAdvertConfig `protobuf:"bytes,10,opt,name=advert_config,json=advertConfig,proto3" json:"advert_config,omitempty"` } func (x *GossipConfig) Reset() { *x = GossipConfig{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipConfig) ProtoMessage() {} func (x *GossipConfig) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipConfig.ProtoReflect.Descriptor instead. func (*GossipConfig) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{5} } func (x *GossipConfig) GetMaxArtifactStreamsPerPeer() uint32 { if x != nil { return x.MaxArtifactStreamsPerPeer } return 0 } func (x *GossipConfig) GetMaxChunkWaitMs() uint32 { if x != nil { return x.MaxChunkWaitMs } return 0 } func (x *GossipConfig) GetMaxDuplicity() uint32 { if x != nil { return x.MaxDuplicity } return 0 } func (x *GossipConfig) GetMaxChunkSize() uint32 { if x != nil { return x.MaxChunkSize } return 0 } func (x *GossipConfig) GetReceiveCheckCacheSize() uint32 { if x != nil { return x.ReceiveCheckCacheSize } return 0 } func (x *GossipConfig) GetPfnEvaluationPeriodMs() uint32 { if x != nil { return x.PfnEvaluationPeriodMs } return 0 } func (x *GossipConfig) GetRegistryPollPeriodMs() uint32 { if x != nil { return x.RegistryPollPeriodMs } return 0 } func (x *GossipConfig) GetRetransmissionRequestMs() uint32 { if x != nil { return x.RetransmissionRequestMs } return 0 } func (x *GossipConfig) GetAdvertConfig() *GossipAdvertConfig { if x != nil { return x.AdvertConfig } return nil } // Per subnet config for advert distribution. type GossipAdvertConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The subset of peers to broadcast to, specified in percentage. // This is only used when the P2P clients mark the advert as // requiring best effort distribution. In future, this fixed // percentage could be replaced by dynamic computation of the // distribution set size, as a function of subnet size. // 0 < best_effort_percentage <= 100 BestEffortPercentage uint32 `protobuf:"varint,1,opt,name=best_effort_percentage,json=bestEffortPercentage,proto3" json:"best_effort_percentage,omitempty"` } func (x *GossipAdvertConfig) Reset() { *x = GossipAdvertConfig{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipAdvertConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipAdvertConfig) ProtoMessage() {} func (x *GossipAdvertConfig) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipAdvertConfig.ProtoReflect.Descriptor instead. func (*GossipAdvertConfig) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{6} } func (x *GossipAdvertConfig) GetBestEffortPercentage() uint32 { if x != nil { return x.BestEffortPercentage } return 0 } type SubnetFeatures struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // This feature flag controls, whether canisters of this subnet are capable of // issuing threshold ecdsa signatures. EcdsaSignatures bool `protobuf:"varint,1,opt,name=ecdsa_signatures,json=ecdsaSignatures,proto3" json:"ecdsa_signatures,omitempty"` // This feature flag controls whether canister execution happens // in sandboxed process or not. It is disabled by default. CanisterSandboxing bool `protobuf:"varint,2,opt,name=canister_sandboxing,json=canisterSandboxing,proto3" json:"canister_sandboxing,omitempty"` // This feature flag controls whether canisters of this subnet are capable of // performing http(s) requests to the web2. HttpRequests bool `protobuf:"varint,3,opt,name=http_requests,json=httpRequests,proto3" json:"http_requests,omitempty"` } func (x *SubnetFeatures) Reset() { *x = SubnetFeatures{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SubnetFeatures) String() string { return protoimpl.X.MessageStringOf(x) } func (*SubnetFeatures) ProtoMessage() {} func (x *SubnetFeatures) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SubnetFeatures.ProtoReflect.Descriptor instead. func (*SubnetFeatures) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{7} } func (x *SubnetFeatures) GetEcdsaSignatures() bool { if x != nil { return x.EcdsaSignatures } return false } func (x *SubnetFeatures) GetCanisterSandboxing() bool { if x != nil { return x.CanisterSandboxing } return false } func (x *SubnetFeatures) GetHttpRequests() bool { if x != nil { return x.HttpRequests } return false } // Per subnet P2P configuration // Note: protoc is mangling the name P2PConfig to P2pConfig type EcdsaConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Number of quadruples to create in advance. QuadruplesToCreateInAdvance uint32 `protobuf:"varint,1,opt,name=quadruples_to_create_in_advance,json=quadruplesToCreateInAdvance,proto3" json:"quadruples_to_create_in_advance,omitempty"` } func (x *EcdsaConfig) Reset() { *x = EcdsaConfig{} if protoimpl.UnsafeEnabled { mi := &file_subnet_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EcdsaConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*EcdsaConfig) ProtoMessage() {} func (x *EcdsaConfig) ProtoReflect() protoreflect.Message { mi := &file_subnet_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EcdsaConfig.ProtoReflect.Descriptor instead. func (*EcdsaConfig) Descriptor() ([]byte, []int) { return file_subnet_proto_rawDescGZIP(), []int{8} } func (x *EcdsaConfig) GetQuadruplesToCreateInAdvance() uint32 { if x != nil { return x.QuadruplesToCreateInAdvance } return 0 } var File_subnet_proto protoreflect.FileDescriptor var file_subnet_proto_rawDesc = []byte{ 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x1a, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xee, 0x09, 0x0a, 0x0c, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x68, 0x69, 0x70, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0a, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x68, 0x69, 0x70, 0x12, 0x40, 0x0a, 0x1d, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x19, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x42, 0x79, 0x74, 0x65, 0x73, 0x50, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x75, 0x6e, 0x69, 0x74, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x5f, 0x6d, 0x69, 0x6c, 0x6c, 0x69, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x75, 0x6e, 0x69, 0x74, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x4d, 0x69, 0x6c, 0x6c, 0x69, 0x73, 0x12, 0x3d, 0x0a, 0x1b, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x79, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x5f, 0x6d, 0x69, 0x6c, 0x6c, 0x69, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x04, 0x52, 0x18, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x79, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x4d, 0x69, 0x6c, 0x6c, 0x69, 0x73, 0x12, 0x2c, 0x0a, 0x12, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x2e, 0x0a, 0x13, 0x64, 0x6b, 0x67, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x5f, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, 0x11, 0x64, 0x6b, 0x67, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x45, 0x0a, 0x0d, 0x67, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0c, 0x67, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x20, 0x0a, 0x0c, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x61, 0x73, 0x5f, 0x6e, 0x6e, 0x73, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x41, 0x73, 0x4e, 0x6e, 0x73, 0x12, 0x3f, 0x0a, 0x0b, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x33, 0x0a, 0x16, 0x64, 0x6b, 0x67, 0x5f, 0x64, 0x65, 0x61, 0x6c, 0x69, 0x6e, 0x67, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x10, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x64, 0x6b, 0x67, 0x44, 0x65, 0x61, 0x6c, 0x69, 0x6e, 0x67, 0x73, 0x50, 0x65, 0x72, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x1b, 0x0a, 0x09, 0x69, 0x73, 0x5f, 0x68, 0x61, 0x6c, 0x74, 0x65, 0x64, 0x18, 0x11, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x69, 0x73, 0x48, 0x61, 0x6c, 0x74, 0x65, 0x64, 0x12, 0x42, 0x0a, 0x1e, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x12, 0x20, 0x01, 0x28, 0x04, 0x52, 0x1a, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x50, 0x65, 0x72, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x33, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x13, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x3f, 0x0a, 0x1c, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x14, 0x20, 0x01, 0x28, 0x04, 0x52, 0x19, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x50, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3b, 0x0a, 0x1a, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x15, 0x20, 0x01, 0x28, 0x04, 0x52, 0x17, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x50, 0x65, 0x72, 0x52, 0x6f, 0x75, 0x6e, 0x64, 0x12, 0x48, 0x0a, 0x21, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x16, 0x20, 0x01, 0x28, 0x04, 0x52, 0x1d, 0x6d, 0x61, 0x78, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x50, 0x65, 0x72, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x3e, 0x0a, 0x08, 0x66, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x18, 0x17, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x52, 0x08, 0x66, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x12, 0x35, 0x0a, 0x17, 0x6d, 0x61, 0x78, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x5f, 0x6f, 0x66, 0x5f, 0x63, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x73, 0x18, 0x18, 0x20, 0x01, 0x28, 0x04, 0x52, 0x14, 0x6d, 0x61, 0x78, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4f, 0x66, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x73, 0x73, 0x68, 0x5f, 0x72, 0x65, 0x61, 0x64, 0x6f, 0x6e, 0x6c, 0x79, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x19, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x73, 0x73, 0x68, 0x52, 0x65, 0x61, 0x64, 0x6f, 0x6e, 0x6c, 0x79, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x2a, 0x0a, 0x11, 0x73, 0x73, 0x68, 0x5f, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x1a, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x73, 0x68, 0x42, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x42, 0x0a, 0x0c, 0x65, 0x63, 0x64, 0x73, 0x61, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x1b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x63, 0x64, 0x73, 0x61, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0b, 0x65, 0x63, 0x64, 0x73, 0x61, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x06, 0x10, 0x07, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x52, 0x0d, 0x69, 0x63, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x52, 0x16, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x64, 0x6b, 0x67, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x52, 0x20, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x73, 0x6f, 0x66, 0x74, 0x5f, 0x63, 0x61, 0x70, 0x22, 0xc9, 0x03, 0x0a, 0x16, 0x43, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x50, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x85, 0x01, 0x0a, 0x27, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x6e, 0x69, 0x5f, 0x64, 0x6b, 0x67, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x5f, 0x6c, 0x6f, 0x77, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x22, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x4c, 0x6f, 0x77, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x87, 0x01, 0x0a, 0x28, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x6e, 0x69, 0x5f, 0x64, 0x6b, 0x67, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x5f, 0x68, 0x69, 0x67, 0x68, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x23, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x48, 0x69, 0x67, 0x68, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x73, 0x74, 0x61, 0x74, 0x65, 0x48, 0x61, 0x73, 0x68, 0x12, 0x52, 0x0a, 0x12, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x75, 0x72, 0x69, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x55, 0x72, 0x69, 0x52, 0x10, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x55, 0x72, 0x69, 0x22, 0x63, 0x0a, 0x10, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x55, 0x72, 0x69, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x69, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x32, 0x0a, 0x10, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x73, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x22, 0xe0, 0x01, 0x0a, 0x1c, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x21, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4e, 0x69, 0x44, 0x6b, 0x67, 0x49, 0x64, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x65, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x36, 0x0a, 0x17, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x63, 0x73, 0x70, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x15, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x43, 0x73, 0x70, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x22, 0x8c, 0x04, 0x0a, 0x0c, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x40, 0x0a, 0x1d, 0x6d, 0x61, 0x78, 0x5f, 0x61, 0x72, 0x74, 0x69, 0x66, 0x61, 0x63, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x19, 0x6d, 0x61, 0x78, 0x41, 0x72, 0x74, 0x69, 0x66, 0x61, 0x63, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x50, 0x65, 0x72, 0x50, 0x65, 0x65, 0x72, 0x12, 0x29, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x5f, 0x77, 0x61, 0x69, 0x74, 0x5f, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0e, 0x6d, 0x61, 0x78, 0x43, 0x68, 0x75, 0x6e, 0x6b, 0x57, 0x61, 0x69, 0x74, 0x4d, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x44, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x79, 0x12, 0x24, 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x43, 0x68, 0x75, 0x6e, 0x6b, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x5f, 0x63, 0x61, 0x63, 0x68, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x15, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x43, 0x61, 0x63, 0x68, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x70, 0x66, 0x6e, 0x5f, 0x65, 0x76, 0x61, 0x6c, 0x75, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x5f, 0x6d, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x15, 0x70, 0x66, 0x6e, 0x45, 0x76, 0x61, 0x6c, 0x75, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x4d, 0x73, 0x12, 0x35, 0x0a, 0x17, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x5f, 0x6d, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x14, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x50, 0x6f, 0x6c, 0x6c, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x4d, 0x73, 0x12, 0x3a, 0x0a, 0x19, 0x72, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x6d, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x17, 0x72, 0x65, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x12, 0x4b, 0x0a, 0x0d, 0x61, 0x64, 0x76, 0x65, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0c, 0x61, 0x64, 0x76, 0x65, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4a, 0x04, 0x08, 0x09, 0x10, 0x0a, 0x52, 0x0c, 0x72, 0x65, 0x6c, 0x61, 0x79, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x4a, 0x0a, 0x12, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x41, 0x64, 0x76, 0x65, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x16, 0x62, 0x65, 0x73, 0x74, 0x5f, 0x65, 0x66, 0x66, 0x6f, 0x72, 0x74, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x14, 0x62, 0x65, 0x73, 0x74, 0x45, 0x66, 0x66, 0x6f, 0x72, 0x74, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x61, 0x67, 0x65, 0x22, 0x91, 0x01, 0x0a, 0x0e, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x65, 0x63, 0x64, 0x73, 0x61, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x65, 0x63, 0x64, 0x73, 0x61, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x12, 0x2f, 0x0a, 0x13, 0x63, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x5f, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x69, 0x6e, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x12, 0x63, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x69, 0x6e, 0x67, 0x12, 0x23, 0x0a, 0x0d, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x68, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x22, 0x53, 0x0a, 0x0b, 0x45, 0x63, 0x64, 0x73, 0x61, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x44, 0x0a, 0x1f, 0x71, 0x75, 0x61, 0x64, 0x72, 0x75, 0x70, 0x6c, 0x65, 0x73, 0x5f, 0x74, 0x6f, 0x5f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x69, 0x6e, 0x5f, 0x61, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x1b, 0x71, 0x75, 0x61, 0x64, 0x72, 0x75, 0x70, 0x6c, 0x65, 0x73, 0x54, 0x6f, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x6e, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x2a, 0xab, 0x01, 0x0a, 0x0a, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x17, 0x53, 0x55, 0x42, 0x4e, 0x45, 0x54, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x53, 0x55, 0x42, 0x4e, 0x45, 0x54, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x41, 0x50, 0x50, 0x4c, 0x49, 0x43, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x01, 0x12, 0x16, 0x0a, 0x12, 0x53, 0x55, 0x42, 0x4e, 0x45, 0x54, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x53, 0x59, 0x53, 0x54, 0x45, 0x4d, 0x10, 0x02, 0x12, 0x24, 0x0a, 0x20, 0x53, 0x55, 0x42, 0x4e, 0x45, 0x54, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x56, 0x45, 0x52, 0x49, 0x46, 0x49, 0x45, 0x44, 0x5f, 0x41, 0x50, 0x50, 0x4c, 0x49, 0x43, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x04, 0x22, 0x04, 0x08, 0x03, 0x10, 0x03, 0x2a, 0x1f, 0x53, 0x55, 0x42, 0x4e, 0x45, 0x54, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x50, 0x52, 0x45, 0x4d, 0x49, 0x55, 0x4d, 0x5f, 0x41, 0x50, 0x50, 0x4c, 0x49, 0x43, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_subnet_proto_rawDescOnce sync.Once file_subnet_proto_rawDescData = file_subnet_proto_rawDesc ) func file_subnet_proto_rawDescGZIP() []byte { file_subnet_proto_rawDescOnce.Do(func() { file_subnet_proto_rawDescData = protoimpl.X.CompressGZIP(file_subnet_proto_rawDescData) }) return file_subnet_proto_rawDescData } var file_subnet_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_subnet_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_subnet_proto_goTypes = []interface{}{ (SubnetType)(0), // 0: registry.subnet.v1.SubnetType (*SubnetRecord)(nil), // 1: registry.subnet.v1.SubnetRecord (*CatchUpPackageContents)(nil), // 2: registry.subnet.v1.CatchUpPackageContents (*RegistryStoreUri)(nil), // 3: registry.subnet.v1.RegistryStoreUri (*SubnetListRecord)(nil), // 4: registry.subnet.v1.SubnetListRecord (*InitialNiDkgTranscriptRecord)(nil), // 5: registry.subnet.v1.InitialNiDkgTranscriptRecord (*GossipConfig)(nil), // 6: registry.subnet.v1.GossipConfig (*GossipAdvertConfig)(nil), // 7: registry.subnet.v1.GossipAdvertConfig (*SubnetFeatures)(nil), // 8: registry.subnet.v1.SubnetFeatures (*EcdsaConfig)(nil), // 9: registry.subnet.v1.EcdsaConfig (*NiDkgId)(nil), // 10: types.v1.NiDkgId } var file_subnet_proto_depIdxs = []int32{ 6, // 0: registry.subnet.v1.SubnetRecord.gossip_config:type_name -> registry.subnet.v1.GossipConfig 0, // 1: registry.subnet.v1.SubnetRecord.subnet_type:type_name -> registry.subnet.v1.SubnetType 8, // 2: registry.subnet.v1.SubnetRecord.features:type_name -> registry.subnet.v1.SubnetFeatures 9, // 3: registry.subnet.v1.SubnetRecord.ecdsa_config:type_name -> registry.subnet.v1.EcdsaConfig 5, // 4: registry.subnet.v1.CatchUpPackageContents.initial_ni_dkg_transcript_low_threshold:type_name -> registry.subnet.v1.InitialNiDkgTranscriptRecord 5, // 5: registry.subnet.v1.CatchUpPackageContents.initial_ni_dkg_transcript_high_threshold:type_name -> registry.subnet.v1.InitialNiDkgTranscriptRecord 3, // 6: registry.subnet.v1.CatchUpPackageContents.registry_store_uri:type_name -> registry.subnet.v1.RegistryStoreUri 10, // 7: registry.subnet.v1.InitialNiDkgTranscriptRecord.id:type_name -> types.v1.NiDkgId 7, // 8: registry.subnet.v1.GossipConfig.advert_config:type_name -> registry.subnet.v1.GossipAdvertConfig 9, // [9:9] is the sub-list for method output_type 9, // [9:9] is the sub-list for method input_type 9, // [9:9] is the sub-list for extension type_name 9, // [9:9] is the sub-list for extension extendee 0, // [0:9] is the sub-list for field type_name } func init() { file_subnet_proto_init() } func file_subnet_proto_init() { if File_subnet_proto != nil { return } file_types_proto_init() if !protoimpl.UnsafeEnabled { file_subnet_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SubnetRecord); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CatchUpPackageContents); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryStoreUri); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SubnetListRecord); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*InitialNiDkgTranscriptRecord); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipAdvertConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SubnetFeatures); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_subnet_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EcdsaConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_subnet_proto_rawDesc, NumEnums: 1, NumMessages: 9, NumExtensions: 0, NumServices: 0, }, GoTypes: file_subnet_proto_goTypes, DependencyIndexes: file_subnet_proto_depIdxs, EnumInfos: file_subnet_proto_enumTypes, MessageInfos: file_subnet_proto_msgTypes, }.Build() File_subnet_proto = out.File file_subnet_proto_rawDesc = nil file_subnet_proto_goTypes = nil file_subnet_proto_depIdxs = nil } <|start_filename|>agent_test.go<|end_filename|> package agent import ( "encoding/hex" "fmt" "math/big" "testing" "github.com/fxamacker/cbor/v2" "github.com/mix-labs/IC-Go/utils" "github.com/mix-labs/IC-Go/utils/identity" "github.com/mix-labs/IC-Go/utils/idl" "github.com/mix-labs/IC-Go/utils/principal" ) //EXT data structure type supply struct { Ok uint64 `ic:"ok"` Err string `ic:"err"` } type Time struct { Some big.Int `ic:"some"` None uint8 `ic:"none"` } type listing struct { Locked Time `ic:locked` Price uint64 `ic:"price"` Seller principal.Principal `ic:"seller"` } type listingTuple struct { A uint32 `ic:"0"` B listing `ic:"1"` } type listings []listingTuple type TokenIndex uint32 type RegistryTuple struct { A TokenIndex `ic:"0"` B string `ic:"1"` } type Registrys []RegistryTuple //PUNK data structure type principalOp struct { Some principal.Principal `ic:"some"` None uint8 `ic:"none"` } type priceOp struct { Some uint64 `ic:"some"` None uint8 `ic:"none"` } type NULL *uint8 type Operation struct { Delist NULL `ic:"delist"` Init NULL `ic:"init"` List NULL `ic:"list"` Mint NULL `ic:"mint"` Purchase NULL `ic:"purchase"` Transfer NULL `ic:"transfer"` //To formulate a enum struct Index string `ic:"EnumIndex"` } type transaction struct { Caller principal.Principal `ic:"caller"` To principalOp `ic:"to"` From principalOp `ic:"from"` Index big.Int `ic:"index"` Price priceOp `ic:"price"` Timestamp big.Int `ic:"timestamp"` TokenId big.Int `ic:"tokenId"` Op Operation `ic:"op"` } type DetailValue struct { I64 int64 `ic:"I64"` U64 uint64 `ic:"U64"` Vec []DetailValue `ic:"Vec"` Slice []uint8 `ic:"Slice"` TokenIdU64 uint64 `ic:"TokenIdU64"` Text string `ic:"Text"` True *uint8 `ic:"True"` False *uint8 `ic:"False"` Float float64 `ic:"Float"` Principal principal.Principal `ic:"Principal"` Index string `ic:"EnumIndex"` } type Details struct { Text string `ic:"0"` Value DetailValue `ic:"1"` } type Event struct { Time uint64 `ic:"time"` Operation string `ic:"operation"` Details []Details `ic:"details"` Caller principal.Principal `ic:"caller"` } type GetTransactionsResponseBorrowed struct { Data []Event `ic:"data"` Page uint32 `ic:"page"` } func TestAgent_QueryRaw(t *testing.T) { //EXT canister //canisterID := "bzsui-sqaaa-aaaah-qce2a-cai" //PUNK canister //canisterID := "qfh5c-6aaaa-aaaah-qakeq-cai" //agent := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") agent, err := NewFromPem(false, "./utils/identity/priv.pem") if err != nil { t.Log(err) } canisterID := principal.Principal([]byte{0, 0, 0, 0, 0, 240, 17, 32, 1, 1}).Encode() methodName := "get_transactions" rec := map[string]idl.Type{} rec["page"] = idl.NewOpt(idl.Nat32()) rec["witness"] = new(idl.Bool) value := map[string]interface{}{} value["page"] = big.NewInt(1) value["witness"] = false arg, _ := idl.Encode([]idl.Type{idl.NewRec(rec)}, []interface{}{value}) fmt.Println(arg, canisterID, methodName) _, result, errMsg, err := agent.Query(canisterID, methodName, arg) myresult := GetTransactionsResponseBorrowed{} utils.Decode(&myresult, result[0]) //fmt.Println(result) // ////EXT method ////methodName := "supply" ////methodName := "listings" ////methodName := "getRegistry" // ////PUNK method //methodName := "getHistoryByIndex" // ////arg, err := idl.Encode([]idl.Type{new(idl.Null)}, []interface{}{nil}) //arg, err := idl.Encode([]idl.Type{new(idl.Nat)}, []interface{}{big.NewInt(10)}) //if err != nil { // t.Error(err) //} //Type, result, errMsg, err := agent.Query(canisterID, methodName, arg) // ////myresult := supply{} ////myresult := listings{} ////myresult := Registrys{} // //myresult := transaction{} ////fmt.Println(result[0]) //utils.Decode(&myresult, result[0]) t.Log("errMsg:", errMsg, "err:", err, "result:", myresult) fmt.Println(myresult.Data[1]) } func TestAgent_UpdateRaw(t *testing.T) { // canisterID := "gvbup-jyaaa-aaaah-qcdwa-cai" // agent := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") // methodName := "transfer" // var argType []idl.Type // var argValue []interface{} // p, _ := principal.Decode("aaaaa-aa") // argType = append(argType, new(idl.Principal)) // argType = append(argType, new(idl.Nat)) // argValue = append(argValue, p) // argValue = append(argValue, big.NewInt(10000000000)) var myresult uint64 canisterID := "d24m2-dqaaa-aaaah-aa4zq-cai" ag := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") methodName := "total" arg, _ := idl.Encode([]idl.Type{new(idl.Null)}, []interface{}{nil}) _, result, err := ag.Update(canisterID, methodName, arg, 30) if err != nil { panic(err) } utils.Decode(&myresult, result[0]) // arg, _ := idl.Encode(argType, argValue) // _, result, err := agent.Update(canisterID, methodName, arg) t.Log("errMsg:", err, "result:", myresult) } func TestAgent_GetCanisterModule(t *testing.T) { canisterID := "bzsui-sqaaa-aaaah-qce2a-cai" agent := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") result, err := agent.GetCanisterModule(canisterID) if err != nil { t.Log("err:", err) } else if result == nil { t.Log("no module") } else { t.Log("hash:", hex.EncodeToString(result)) } } func TestAgent_GetCanisterControllers(t *testing.T) { canisterID := "6b4pv-sqaaa-aaaah-qaava-cai" agent := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") result, err := agent.GetCanisterControllers(canisterID) if err != nil { t.Log("err:", err) } else { for _, i := range result { t.Log("controller:", i.Encode()) } } t.Log(result) } func TestPrincipal(t *testing.T) { pkBytes, _ := hex.DecodeString("833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") identity := identity.New(false, pkBytes) p := principal.NewSelfAuthenticating(identity.PubKeyBytes()) t.Log(p.Encode(), len(identity.PubKeyBytes())) } func TestCbor(t *testing.T) { canisterID, _ := principal.Decode("gvbup-jyaaa-aaaah-qcdwa-cai") agent := New(true, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") req := Request{ Type: "call", Sender: agent.Sender(), IngressExpiry: uint64(agent.getExpiryDate().UnixNano()), CanisterID: canisterID, MethodName: "transfer", Arguments: []byte("i love vivian"), } envelope := Envelope{ req, []byte{}, []byte{}, } data, _ := cbor.Marshal(envelope) resp := new(Envelope) cbor.Unmarshal(data, resp) t.Log("sender", resp.Content.Sender.Encode()) t.Log("type", resp.Content.Type) t.Log("ingress expiryt", resp.Content.IngressExpiry) t.Log("method", resp.Content.MethodName) t.Log("arg", resp.Content.Arguments) t.Log("canister", resp.Content.CanisterID.Encode()) } func TestAgent_GetCanisterTime(t *testing.T) { canisterID := "b65vx-3qaaa-aaaaa-7777q-cai" agent := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") result, err := agent.GetCanisterTime(canisterID) if err != nil { t.Log("err:", err) } else { t.Log("result:", result) } } func TestAgent_GetCanisterCandid(t *testing.T) { canisterID := "oeee4-qaaaa-aaaak-qaaeq-cai" agent := New(false, "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42") arg, _ := idl.Encode([]idl.Type{new(idl.Null)}, []interface{}{nil}) methodName := "__get_candid_interface_tmp_hack" _, result, err := agent.Update(canisterID, methodName, arg, 30) if err != nil { panic(err) } if err != nil { t.Log("err:", err) } else { t.Log("result:", result) } } <|start_filename|>example/registry/proto/pb/mixed_hash_tree.pb.go<|end_filename|> // Protocol buffer mirror of `ic_crypto_tree_hash::MixedHashTree`. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: mixed_hash_tree.proto package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" emptypb "google.golang.org/protobuf/types/known/emptypb" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // A tree containing both data and merkle proofs. type MixedHashTree struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to TreeEnum: // *MixedHashTree_Empty // *MixedHashTree_Fork_ // *MixedHashTree_Labeled_ // *MixedHashTree_LeafData // *MixedHashTree_PrunedDigest TreeEnum isMixedHashTree_TreeEnum `protobuf_oneof:"tree_enum"` } func (x *MixedHashTree) Reset() { *x = MixedHashTree{} if protoimpl.UnsafeEnabled { mi := &file_mixed_hash_tree_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MixedHashTree) String() string { return protoimpl.X.MessageStringOf(x) } func (*MixedHashTree) ProtoMessage() {} func (x *MixedHashTree) ProtoReflect() protoreflect.Message { mi := &file_mixed_hash_tree_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MixedHashTree.ProtoReflect.Descriptor instead. func (*MixedHashTree) Descriptor() ([]byte, []int) { return file_mixed_hash_tree_proto_rawDescGZIP(), []int{0} } func (m *MixedHashTree) GetTreeEnum() isMixedHashTree_TreeEnum { if m != nil { return m.TreeEnum } return nil } func (x *MixedHashTree) GetEmpty() *emptypb.Empty { if x, ok := x.GetTreeEnum().(*MixedHashTree_Empty); ok { return x.Empty } return nil } func (x *MixedHashTree) GetFork() *MixedHashTree_Fork { if x, ok := x.GetTreeEnum().(*MixedHashTree_Fork_); ok { return x.Fork } return nil } func (x *MixedHashTree) GetLabeled() *MixedHashTree_Labeled { if x, ok := x.GetTreeEnum().(*MixedHashTree_Labeled_); ok { return x.Labeled } return nil } func (x *MixedHashTree) GetLeafData() []byte { if x, ok := x.GetTreeEnum().(*MixedHashTree_LeafData); ok { return x.LeafData } return nil } func (x *MixedHashTree) GetPrunedDigest() []byte { if x, ok := x.GetTreeEnum().(*MixedHashTree_PrunedDigest); ok { return x.PrunedDigest } return nil } type isMixedHashTree_TreeEnum interface { isMixedHashTree_TreeEnum() } type MixedHashTree_Empty struct { Empty *emptypb.Empty `protobuf:"bytes,1,opt,name=empty,proto3,oneof"` } type MixedHashTree_Fork_ struct { Fork *MixedHashTree_Fork `protobuf:"bytes,2,opt,name=fork,proto3,oneof"` } type MixedHashTree_Labeled_ struct { Labeled *MixedHashTree_Labeled `protobuf:"bytes,3,opt,name=labeled,proto3,oneof"` } type MixedHashTree_LeafData struct { LeafData []byte `protobuf:"bytes,4,opt,name=leaf_data,json=leafData,proto3,oneof"` } type MixedHashTree_PrunedDigest struct { PrunedDigest []byte `protobuf:"bytes,5,opt,name=pruned_digest,json=prunedDigest,proto3,oneof"` } func (*MixedHashTree_Empty) isMixedHashTree_TreeEnum() {} func (*MixedHashTree_Fork_) isMixedHashTree_TreeEnum() {} func (*MixedHashTree_Labeled_) isMixedHashTree_TreeEnum() {} func (*MixedHashTree_LeafData) isMixedHashTree_TreeEnum() {} func (*MixedHashTree_PrunedDigest) isMixedHashTree_TreeEnum() {} type MixedHashTree_Fork struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields LeftTree *MixedHashTree `protobuf:"bytes,1,opt,name=left_tree,json=leftTree,proto3" json:"left_tree,omitempty"` RightTree *MixedHashTree `protobuf:"bytes,2,opt,name=right_tree,json=rightTree,proto3" json:"right_tree,omitempty"` } func (x *MixedHashTree_Fork) Reset() { *x = MixedHashTree_Fork{} if protoimpl.UnsafeEnabled { mi := &file_mixed_hash_tree_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MixedHashTree_Fork) String() string { return protoimpl.X.MessageStringOf(x) } func (*MixedHashTree_Fork) ProtoMessage() {} func (x *MixedHashTree_Fork) ProtoReflect() protoreflect.Message { mi := &file_mixed_hash_tree_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MixedHashTree_Fork.ProtoReflect.Descriptor instead. func (*MixedHashTree_Fork) Descriptor() ([]byte, []int) { return file_mixed_hash_tree_proto_rawDescGZIP(), []int{0, 0} } func (x *MixedHashTree_Fork) GetLeftTree() *MixedHashTree { if x != nil { return x.LeftTree } return nil } func (x *MixedHashTree_Fork) GetRightTree() *MixedHashTree { if x != nil { return x.RightTree } return nil } type MixedHashTree_Labeled struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Label []byte `protobuf:"bytes,1,opt,name=label,proto3" json:"label,omitempty"` Subtree *MixedHashTree `protobuf:"bytes,2,opt,name=subtree,proto3" json:"subtree,omitempty"` } func (x *MixedHashTree_Labeled) Reset() { *x = MixedHashTree_Labeled{} if protoimpl.UnsafeEnabled { mi := &file_mixed_hash_tree_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MixedHashTree_Labeled) String() string { return protoimpl.X.MessageStringOf(x) } func (*MixedHashTree_Labeled) ProtoMessage() {} func (x *MixedHashTree_Labeled) ProtoReflect() protoreflect.Message { mi := &file_mixed_hash_tree_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MixedHashTree_Labeled.ProtoReflect.Descriptor instead. func (*MixedHashTree_Labeled) Descriptor() ([]byte, []int) { return file_mixed_hash_tree_proto_rawDescGZIP(), []int{0, 1} } func (x *MixedHashTree_Labeled) GetLabel() []byte { if x != nil { return x.Label } return nil } func (x *MixedHashTree_Labeled) GetSubtree() *MixedHashTree { if x != nil { return x.Subtree } return nil } var File_mixed_hash_tree_proto protoreflect.FileDescriptor var file_mixed_hash_tree_proto_rawDesc = []byte{ 0x0a, 0x15, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x5f, 0x74, 0x72, 0x65, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x11, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xfb, 0x03, 0x0a, 0x0d, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x12, 0x2e, 0x0a, 0x05, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x48, 0x00, 0x52, 0x05, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3b, 0x0a, 0x04, 0x66, 0x6f, 0x72, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x2e, 0x46, 0x6f, 0x72, 0x6b, 0x48, 0x00, 0x52, 0x04, 0x66, 0x6f, 0x72, 0x6b, 0x12, 0x44, 0x0a, 0x07, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x2e, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x65, 0x64, 0x48, 0x00, 0x52, 0x07, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x65, 0x64, 0x12, 0x1d, 0x0a, 0x09, 0x6c, 0x65, 0x61, 0x66, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x08, 0x6c, 0x65, 0x61, 0x66, 0x44, 0x61, 0x74, 0x61, 0x12, 0x25, 0x0a, 0x0d, 0x70, 0x72, 0x75, 0x6e, 0x65, 0x64, 0x5f, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x0c, 0x70, 0x72, 0x75, 0x6e, 0x65, 0x64, 0x44, 0x69, 0x67, 0x65, 0x73, 0x74, 0x1a, 0x86, 0x01, 0x0a, 0x04, 0x46, 0x6f, 0x72, 0x6b, 0x12, 0x3d, 0x0a, 0x09, 0x6c, 0x65, 0x66, 0x74, 0x5f, 0x74, 0x72, 0x65, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x52, 0x08, 0x6c, 0x65, 0x66, 0x74, 0x54, 0x72, 0x65, 0x65, 0x12, 0x3f, 0x0a, 0x0a, 0x72, 0x69, 0x67, 0x68, 0x74, 0x5f, 0x74, 0x72, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x52, 0x09, 0x72, 0x69, 0x67, 0x68, 0x74, 0x54, 0x72, 0x65, 0x65, 0x1a, 0x5b, 0x0a, 0x07, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x65, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x3a, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x74, 0x72, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x52, 0x07, 0x73, 0x75, 0x62, 0x74, 0x72, 0x65, 0x65, 0x42, 0x0b, 0x0a, 0x09, 0x74, 0x72, 0x65, 0x65, 0x5f, 0x65, 0x6e, 0x75, 0x6d, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_mixed_hash_tree_proto_rawDescOnce sync.Once file_mixed_hash_tree_proto_rawDescData = file_mixed_hash_tree_proto_rawDesc ) func file_mixed_hash_tree_proto_rawDescGZIP() []byte { file_mixed_hash_tree_proto_rawDescOnce.Do(func() { file_mixed_hash_tree_proto_rawDescData = protoimpl.X.CompressGZIP(file_mixed_hash_tree_proto_rawDescData) }) return file_mixed_hash_tree_proto_rawDescData } var file_mixed_hash_tree_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_mixed_hash_tree_proto_goTypes = []interface{}{ (*MixedHashTree)(nil), // 0: messaging.xnet.v1.MixedHashTree (*MixedHashTree_Fork)(nil), // 1: messaging.xnet.v1.MixedHashTree.Fork (*MixedHashTree_Labeled)(nil), // 2: messaging.xnet.v1.MixedHashTree.Labeled (*emptypb.Empty)(nil), // 3: google.protobuf.Empty } var file_mixed_hash_tree_proto_depIdxs = []int32{ 3, // 0: messaging.xnet.v1.MixedHashTree.empty:type_name -> google.protobuf.Empty 1, // 1: messaging.xnet.v1.MixedHashTree.fork:type_name -> messaging.xnet.v1.MixedHashTree.Fork 2, // 2: messaging.xnet.v1.MixedHashTree.labeled:type_name -> messaging.xnet.v1.MixedHashTree.Labeled 0, // 3: messaging.xnet.v1.MixedHashTree.Fork.left_tree:type_name -> messaging.xnet.v1.MixedHashTree 0, // 4: messaging.xnet.v1.MixedHashTree.Fork.right_tree:type_name -> messaging.xnet.v1.MixedHashTree 0, // 5: messaging.xnet.v1.MixedHashTree.Labeled.subtree:type_name -> messaging.xnet.v1.MixedHashTree 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_mixed_hash_tree_proto_init() } func file_mixed_hash_tree_proto_init() { if File_mixed_hash_tree_proto != nil { return } if !protoimpl.UnsafeEnabled { file_mixed_hash_tree_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MixedHashTree); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_mixed_hash_tree_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MixedHashTree_Fork); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_mixed_hash_tree_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MixedHashTree_Labeled); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_mixed_hash_tree_proto_msgTypes[0].OneofWrappers = []interface{}{ (*MixedHashTree_Empty)(nil), (*MixedHashTree_Fork_)(nil), (*MixedHashTree_Labeled_)(nil), (*MixedHashTree_LeafData)(nil), (*MixedHashTree_PrunedDigest)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_mixed_hash_tree_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_mixed_hash_tree_proto_goTypes, DependencyIndexes: file_mixed_hash_tree_proto_depIdxs, MessageInfos: file_mixed_hash_tree_proto_msgTypes, }.Build() File_mixed_hash_tree_proto = out.File file_mixed_hash_tree_proto_rawDesc = nil file_mixed_hash_tree_proto_goTypes = nil file_mixed_hash_tree_proto_depIdxs = nil } <|start_filename|>request_test.go<|end_filename|> package agent_test import ( "crypto/sha256" "encoding/hex" "fmt" "testing" agent "github.com/mix-labs/IC-Go" ) func TestNewRequestID(t *testing.T) { req := agent.Request{ Type: agent.RequestTypeCall, CanisterID: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xD2}, MethodName: "hello", Arguments: []byte("DIDL\x00\xFD*"), } //t.Log(idl.Decode([]byte("DIDL\x00\xFD*"))) h := fmt.Sprintf("%x", agent.NewRequestID(req)) if h != "8781291c347db32a9d8c10eb62b710fce5a93be676474c42babc74c51858f94b" { t.Fatal(h) } } func TestEncodeRequestID(t *testing.T) { req := make(map[string]interface{}) req["request_type"] = agent.RequestTypeCall req["canister_id"] = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xD2} req["method_name"] = "hello" req["arg"] = []byte("DIDL\x00\xFD*") id := agent.EncodeRequestID(req) h := fmt.Sprintf("%x", id) if h != "8781291c347db32a9d8c10eb62b710fce5a93be676474c42babc74c51858f94b" { t.Fatal(h) } } func TestEncodeList(t *testing.T) { a := [][]byte{[]byte("i"),[]byte("love"),[]byte("you")} res := encodeList(a) t.Log(hex.EncodeToString([]byte("i"))) t.Log(hex.EncodeToString([]byte("love"))) t.Log(hex.EncodeToString([]byte("you"))) t.Log(hex.EncodeToString(res[:])) } func encodeList(paths [][]byte) [32]byte { var pathsBytes []byte for _, path := range paths { pathBytes := sha256.Sum256(path) pathsBytes = append(pathsBytes, pathBytes[:]...) } return sha256.Sum256(pathsBytes) } <|start_filename|>example/registry/registry_test.go<|end_filename|> package registry import ( "encoding/binary" "fmt" agent "github.com/mix-labs/IC-Go" "github.com/mix-labs/IC-Go/utils/principal" "testing" ) func TestGetRoutingTable(t *testing.T) { a := agent.New(true, "") routingTable, err := GetRoutingTable(a) if err != nil { t.Log("error:", err) } for i, entry := range routingTable.Entries { t.Log("subnet index:", i) fmt.Println("subnetID:", principal.New(entry.SubnetId.PrincipalId.Raw).Encode()) fmt.Println("start canister ID:", principal.New(entry.Range.StartCanisterId.PrincipalId.Raw).Encode()) fmt.Println("start canister ID raw:", entry.Range.StartCanisterId.PrincipalId.Raw) fmt.Println("start canister ID to uint64:", binary.BigEndian.Uint64(entry.Range.StartCanisterId.PrincipalId.Raw[:8])) fmt.Println("end canister ID:", principal.New(entry.Range.EndCanisterId.PrincipalId.Raw).Encode()) fmt.Println("end canister ID raw:", entry.Range.EndCanisterId.PrincipalId.Raw) fmt.Println("end canister ID to uint64:", binary.BigEndian.Uint64(entry.Range.EndCanisterId.PrincipalId.Raw[:8])) } } func TestGetSubnetList(t *testing.T) { a := agent.New(true, "") subnetList, err := GetSubnetList(a) if err != nil { t.Log("error:", err) } for _, entry := range subnetList.Subnets { t.Log("subnetID:", principal.New(entry).Encode()) } } func TestGetSubnetRecord(t *testing.T) { a := agent.New(true, "") subnet, err := GetSubnetRecord(a, "tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe") if err != nil { t.Log("error:", err) } t.Log("subnet Type:",subnet.SubnetType) t.Log("max canister amount",subnet.MaxNumberOfCanisters) for _, node := range subnet.Membership { t.Log("node:", principal.New(node).Encode()) } } func TestGetNodeInfo(t *testing.T) { a := agent.New(true, "") node, err := GetNodeInfo(a, "btuxg-lwlbn-43hlo-iag4h-plf64-b3u7d-ugvay-nbvrl-jkhlx-nhvw4-gae") if err != nil { t.Log("error:", err) } t.Log("operator:", principal.New(node.NodeOperatorId).Encode()) } func TestGetOperatorInfo(t *testing.T) { a := agent.New(true, "") op, err := GetOperatorInfo(a, "redpf-rrb5x-sa2it-zhbh7-q2fsp-bqlwz-4mf4y-tgxmj-g5y7p-ezjtj-5qe") if err != nil { t.Log("error:", err) } t.Log("operator:", principal.New(op.NodeOperatorPrincipalId).Encode()) t.Log("provider:", principal.New(op.NodeProviderPrincipalId).Encode()) t.Log("Node Allowance:", op.NodeAllowance) t.Log("Rewardable Nodes:", op.RewardableNodes) } <|start_filename|>example/registry/proto/pb/routing_table.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: routing_table.proto package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type CanisterIdRange struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields StartCanisterId *CanisterId `protobuf:"bytes,3,opt,name=start_canister_id,json=startCanisterId,proto3" json:"start_canister_id,omitempty"` EndCanisterId *CanisterId `protobuf:"bytes,4,opt,name=end_canister_id,json=endCanisterId,proto3" json:"end_canister_id,omitempty"` } func (x *CanisterIdRange) Reset() { *x = CanisterIdRange{} if protoimpl.UnsafeEnabled { mi := &file_routing_table_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CanisterIdRange) String() string { return protoimpl.X.MessageStringOf(x) } func (*CanisterIdRange) ProtoMessage() {} func (x *CanisterIdRange) ProtoReflect() protoreflect.Message { mi := &file_routing_table_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CanisterIdRange.ProtoReflect.Descriptor instead. func (*CanisterIdRange) Descriptor() ([]byte, []int) { return file_routing_table_proto_rawDescGZIP(), []int{0} } func (x *CanisterIdRange) GetStartCanisterId() *CanisterId { if x != nil { return x.StartCanisterId } return nil } func (x *CanisterIdRange) GetEndCanisterId() *CanisterId { if x != nil { return x.EndCanisterId } return nil } // A list of closed ranges of canister Ids. type CanisterIdRanges struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Ranges []*CanisterIdRange `protobuf:"bytes,1,rep,name=ranges,proto3" json:"ranges,omitempty"` } func (x *CanisterIdRanges) Reset() { *x = CanisterIdRanges{} if protoimpl.UnsafeEnabled { mi := &file_routing_table_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CanisterIdRanges) String() string { return protoimpl.X.MessageStringOf(x) } func (*CanisterIdRanges) ProtoMessage() {} func (x *CanisterIdRanges) ProtoReflect() protoreflect.Message { mi := &file_routing_table_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CanisterIdRanges.ProtoReflect.Descriptor instead. func (*CanisterIdRanges) Descriptor() ([]byte, []int) { return file_routing_table_proto_rawDescGZIP(), []int{1} } func (x *CanisterIdRanges) GetRanges() []*CanisterIdRange { if x != nil { return x.Ranges } return nil } // Maps a closed range of canister Ids to a subnet id. type RoutingTable struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Defined as `repeated` instead of `map` in order to preserve ordering. Entries []*RoutingTable_Entry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` } func (x *RoutingTable) Reset() { *x = RoutingTable{} if protoimpl.UnsafeEnabled { mi := &file_routing_table_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RoutingTable) String() string { return protoimpl.X.MessageStringOf(x) } func (*RoutingTable) ProtoMessage() {} func (x *RoutingTable) ProtoReflect() protoreflect.Message { mi := &file_routing_table_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RoutingTable.ProtoReflect.Descriptor instead. func (*RoutingTable) Descriptor() ([]byte, []int) { return file_routing_table_proto_rawDescGZIP(), []int{2} } func (x *RoutingTable) GetEntries() []*RoutingTable_Entry { if x != nil { return x.Entries } return nil } type RoutingTable_Entry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Range *CanisterIdRange `protobuf:"bytes,1,opt,name=range,proto3" json:"range,omitempty"` SubnetId *SubnetId `protobuf:"bytes,2,opt,name=subnet_id,json=subnetId,proto3" json:"subnet_id,omitempty"` } func (x *RoutingTable_Entry) Reset() { *x = RoutingTable_Entry{} if protoimpl.UnsafeEnabled { mi := &file_routing_table_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RoutingTable_Entry) String() string { return protoimpl.X.MessageStringOf(x) } func (*RoutingTable_Entry) ProtoMessage() {} func (x *RoutingTable_Entry) ProtoReflect() protoreflect.Message { mi := &file_routing_table_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RoutingTable_Entry.ProtoReflect.Descriptor instead. func (*RoutingTable_Entry) Descriptor() ([]byte, []int) { return file_routing_table_proto_rawDescGZIP(), []int{2, 0} } func (x *RoutingTable_Entry) GetRange() *CanisterIdRange { if x != nil { return x.Range } return nil } func (x *RoutingTable_Entry) GetSubnetId() *SubnetId { if x != nil { return x.SubnetId } return nil } var File_routing_table_proto protoreflect.FileDescriptor var file_routing_table_proto_rawDesc = []byte{ 0x0a, 0x13, 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x10, 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa9, 0x01, 0x0a, 0x0f, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x40, 0x0a, 0x11, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x63, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x52, 0x0f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x3c, 0x0a, 0x0f, 0x65, 0x6e, 0x64, 0x5f, 0x63, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x52, 0x0d, 0x65, 0x6e, 0x64, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x52, 0x03, 0x65, 0x6e, 0x64, 0x22, 0x4d, 0x0a, 0x10, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x12, 0x39, 0x0a, 0x06, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x06, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x22, 0xc1, 0x01, 0x0a, 0x0c, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x3e, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x1a, 0x71, 0x0a, 0x05, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x37, 0x0a, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x61, 0x6e, 0x69, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x2f, 0x0a, 0x09, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x49, 0x64, 0x52, 0x08, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x49, 0x64, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_routing_table_proto_rawDescOnce sync.Once file_routing_table_proto_rawDescData = file_routing_table_proto_rawDesc ) func file_routing_table_proto_rawDescGZIP() []byte { file_routing_table_proto_rawDescOnce.Do(func() { file_routing_table_proto_rawDescData = protoimpl.X.CompressGZIP(file_routing_table_proto_rawDescData) }) return file_routing_table_proto_rawDescData } var file_routing_table_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_routing_table_proto_goTypes = []interface{}{ (*CanisterIdRange)(nil), // 0: routing_table.v1.CanisterIdRange (*CanisterIdRanges)(nil), // 1: routing_table.v1.CanisterIdRanges (*RoutingTable)(nil), // 2: routing_table.v1.RoutingTable (*RoutingTable_Entry)(nil), // 3: routing_table.v1.RoutingTable.Entry (*CanisterId)(nil), // 4: types.v1.CanisterId (*SubnetId)(nil), // 5: types.v1.SubnetId } var file_routing_table_proto_depIdxs = []int32{ 4, // 0: routing_table.v1.CanisterIdRange.start_canister_id:type_name -> types.v1.CanisterId 4, // 1: routing_table.v1.CanisterIdRange.end_canister_id:type_name -> types.v1.CanisterId 0, // 2: routing_table.v1.CanisterIdRanges.ranges:type_name -> routing_table.v1.CanisterIdRange 3, // 3: routing_table.v1.RoutingTable.entries:type_name -> routing_table.v1.RoutingTable.Entry 0, // 4: routing_table.v1.RoutingTable.Entry.range:type_name -> routing_table.v1.CanisterIdRange 5, // 5: routing_table.v1.RoutingTable.Entry.subnet_id:type_name -> types.v1.SubnetId 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_routing_table_proto_init() } func file_routing_table_proto_init() { if File_routing_table_proto != nil { return } file_types_proto_init() if !protoimpl.UnsafeEnabled { file_routing_table_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CanisterIdRange); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_routing_table_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CanisterIdRanges); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_routing_table_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RoutingTable); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_routing_table_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RoutingTable_Entry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_routing_table_proto_rawDesc, NumEnums: 0, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_routing_table_proto_goTypes, DependencyIndexes: file_routing_table_proto_depIdxs, MessageInfos: file_routing_table_proto_msgTypes, }.Build() File_routing_table_proto = out.File file_routing_table_proto_rawDesc = nil file_routing_table_proto_goTypes = nil file_routing_table_proto_depIdxs = nil } <|start_filename|>utils/identity/identity.go<|end_filename|> package identity import ( "crypto" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/pem" "errors" "fmt" "io/ioutil" "crypto/ed25519" ) var errEd25519WrongID = errors.New("incorrect object identifier") var errEd25519WrongKeyType = errors.New("incorrect key type") // ed25519OID is the OID for the Ed25519 signature scheme: see // https://datatracker.ietf.org/doc/draft-ietf-curdle-pkix-04. var ed25519OID = asn1.ObjectIdentifier{1, 3, 101, 112} // subjectPublicKeyInfo reflects the ASN.1 object defined in the X.509 standard. // // This is defined in crypto/x509 as "publicKeyInfo". type subjectPublicKeyInfo struct { Algorithm pkix.AlgorithmIdentifier PublicKey asn1.BitString } // MarshalEd25519PublicKey creates a DER-encoded SubjectPublicKeyInfo for an // ed25519 public key, as defined in // https://tools.ietf.org/html/draft-ietf-curdle-pkix-04. This is analogous to // MarshalPKIXPublicKey in crypto/x509, which doesn't currently support Ed25519. func MarshalEd25519PublicKey(pk crypto.PublicKey) ([]byte, error) { pub, ok := pk.(ed25519.PublicKey) if !ok { return nil, errEd25519WrongKeyType } spki := subjectPublicKeyInfo{ Algorithm: pkix.AlgorithmIdentifier{ Algorithm: ed25519OID, }, PublicKey: asn1.BitString{ BitLength: len(pub) * 8, Bytes: pub, }, } return asn1.Marshal(spki) } // ParseEd25519PublicKey returns the Ed25519 public key encoded by the input. func ParseEd25519PublicKey(der []byte) (crypto.PublicKey, error) { var spki subjectPublicKeyInfo if rest, err := asn1.Unmarshal(der, &spki); err != nil { return nil, err } else if len(rest) > 0 { return nil, errors.New("SubjectPublicKeyInfo too long") } if !spki.Algorithm.Algorithm.Equal(ed25519OID) { return nil, errEd25519WrongID } if spki.PublicKey.BitLength != ed25519.PublicKeySize*8 { return nil, errors.New("SubjectPublicKeyInfo PublicKey length mismatch") } return ed25519.PublicKey(spki.PublicKey.Bytes), nil } // oneAsymmetricKey reflects the ASN.1 structure for storing private keys in // https://tools.ietf.org/html/draft-ietf-curdle-pkix-04, excluding the optional // fields, which we don't use here. // // This is identical to pkcs8 in crypto/x509. type oneAsymmetricKey struct { Version int Algorithm pkix.AlgorithmIdentifier PrivateKey []byte } // curvePrivateKey is the innter type of the PrivateKey field of // oneAsymmetricKey. type curvePrivateKey []byte // MarshalEd25519PrivateKey returns a DER encoding of the input private key as // specified in https://tools.ietf.org/html/draft-ietf-curdle-pkix-04. func MarshalEd25519PrivateKey(sk crypto.PrivateKey) ([]byte, error) { priv, ok := sk.(ed25519.PrivateKey) if !ok { return nil, errEd25519WrongKeyType } // Marshal the innter CurvePrivateKey. curvePrivateKey, err := asn1.Marshal(priv.Seed()) if err != nil { return nil, err } // Marshal the OneAsymmetricKey. asym := oneAsymmetricKey{ Version: 0, Algorithm: pkix.AlgorithmIdentifier{ Algorithm: ed25519OID, }, PrivateKey: curvePrivateKey, } return asn1.Marshal(asym) } // ParseEd25519PrivateKey returns the Ed25519 private key encoded by the input. func ParseEd25519PrivateKey(der []byte) (crypto.PrivateKey, error) { asym := new(oneAsymmetricKey) if rest, err := asn1.Unmarshal(der, asym); err != nil { return nil, err } else if len(rest) > 0 { return nil, errors.New("OneAsymmetricKey too long") } // Check that the key type is correct. if !asym.Algorithm.Algorithm.Equal(ed25519OID) { return nil, errEd25519WrongID } // Unmarshal the inner CurvePrivateKey. seed := new(curvePrivateKey) if rest, err := asn1.Unmarshal(asym.PrivateKey, seed); err != nil { return nil, err } else if len(rest) > 0 { return nil, errors.New("CurvePrivateKey too long") } return ed25519.NewKeyFromSeed(*seed), nil } func ToPem(sk crypto.PrivateKey, path string) error { var ( err error b []byte block *pem.Block priv ed25519.PrivateKey ) priv, ok := sk.(ed25519.PrivateKey) if !ok { return errEd25519WrongKeyType } b, err = x509.MarshalPKCS8PrivateKey(priv) block = &pem.Block{ Type: "PRIVATE KEY", Bytes: b, } err = ioutil.WriteFile(path, pem.EncodeToMemory(block), 0600) if err != nil { return err } return nil } func FromPem(file string) (ed25519.PrivateKey, error) { b, err := ioutil.ReadFile(file) if err != nil { return nil, err } block, _ := pem.Decode(b) if block.Type != "PRIVATE KEY" || block == nil { return nil, fmt.Errorf("failed to decode PEM block containing private key") } sk, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, err } return sk.(ed25519.PrivateKey), nil } func New(anonymous bool, pkBytes []byte) *Identity { if anonymous == true { return &Identity{ Anonymous: anonymous, } } privKey := ed25519.NewKeyFromSeed(pkBytes) //fmt.Println(privKey) pubKey := privKey.Public() //fmt.Println(pubKey) return &Identity{ anonymous, privKey, pubKey, } } type Identity struct { Anonymous bool PriKey ed25519.PrivateKey PubKey crypto.PublicKey } func (identity *Identity) Sign(m []byte) ([]byte, error) { if identity.Anonymous == true { return []byte{}, nil } sign := ed25519.Sign(identity.PriKey, m[:]) return sign, nil } func (identity *Identity) PubKeyBytes() []byte { var senderPubKey []byte if identity.Anonymous == false { pkBytes, _ := MarshalEd25519PublicKey(identity.PubKey) return pkBytes } return senderPubKey } <|start_filename|>example/registry/proto/pb/transport.pb.go<|end_filename|> // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.19.2 // source: transport.proto // Set of messages used to interact with the registry canister. // // The registry canister implements the following three methods: // // get_latest_version(RegistryGetLatestVersionRequest) -> // RegistryGetLatestVersionResponse // // get_value(RegistryGetValueRequest) -> RegistryGetValueResponse // // atomic_mutate(RegistryAtomicMutateRequest) -> RegistryAtomicMutateResponse // // get_latest_version() returns the latest version of the registry, i.e. the // version of the last update made to the registry. // // get_value() returns the a value for specified version of a specified key from // the registry, or the latest version if a version was not specified. // get_value() returns a RegistryError if the key was not present. // // atomic_mutate() inserts, updates or deletes a set of keys in the registry. // Mutations are atomic, meaning either all mutations are applied, or none // are applied. // // Note that registry versions are always strictly >= 0, a -1 value is used // to signal that no version was assigned. package pb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" wrapperspb "google.golang.org/protobuf/types/known/wrapperspb" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type RegistryError_Code int32 const ( // The message had a problem like a missing field // or a field that was set when it shouldn't. RegistryError_MALFORMED_MESSAGE RegistryError_Code = 0 // The 'key' specified on the request was not present // in the registry. RegistryError_KEY_NOT_PRESENT RegistryError_Code = 1 // The 'key' specified on the request was already present. RegistryError_KEY_ALREADY_PRESENT RegistryError_Code = 2 // The 'version' specified in a precondition for a mutation // was not the lastest version. RegistryError_VERSION_NOT_LATEST RegistryError_Code = 3 // The 'version' specified in a precondition for a mutation // is beyond the latest version in the registry. RegistryError_VERSION_BEYOND_LATEST RegistryError_Code = 4 // A generic internal error occurred in the registry. RegistryError_INTERNAL_ERROR RegistryError_Code = 999 ) // Enum value maps for RegistryError_Code. var ( RegistryError_Code_name = map[int32]string{ 0: "MALFORMED_MESSAGE", 1: "KEY_NOT_PRESENT", 2: "KEY_ALREADY_PRESENT", 3: "VERSION_NOT_LATEST", 4: "VERSION_BEYOND_LATEST", 999: "INTERNAL_ERROR", } RegistryError_Code_value = map[string]int32{ "MALFORMED_MESSAGE": 0, "KEY_NOT_PRESENT": 1, "KEY_ALREADY_PRESENT": 2, "VERSION_NOT_LATEST": 3, "VERSION_BEYOND_LATEST": 4, "INTERNAL_ERROR": 999, } ) func (x RegistryError_Code) Enum() *RegistryError_Code { p := new(RegistryError_Code) *p = x return p } func (x RegistryError_Code) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RegistryError_Code) Descriptor() protoreflect.EnumDescriptor { return file_transport_proto_enumTypes[0].Descriptor() } func (RegistryError_Code) Type() protoreflect.EnumType { return &file_transport_proto_enumTypes[0] } func (x RegistryError_Code) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RegistryError_Code.Descriptor instead. func (RegistryError_Code) EnumDescriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{0, 0} } type RegistryMutation_Type int32 const ( // Key is expected to not exist in the registry at the current version. // (This includes the case of a key that has existed in the past and // later got deleted). // The mutation will fail otherwise. RegistryMutation_INSERT RegistryMutation_Type = 0 // Key is expected to exist in the registry at the current version. // The mutation will fail otherwise. RegistryMutation_UPDATE RegistryMutation_Type = 1 // Key is expected to exist in the registry at the current version. // The mutation will fail otherwise. RegistryMutation_DELETE RegistryMutation_Type = 2 // If the key does not exist at the current version, it will be created. // Otherwise, the value will be updated. The name is common in the // database world, and means Update or Insert. RegistryMutation_UPSERT RegistryMutation_Type = 4 ) // Enum value maps for RegistryMutation_Type. var ( RegistryMutation_Type_name = map[int32]string{ 0: "INSERT", 1: "UPDATE", 2: "DELETE", 4: "UPSERT", } RegistryMutation_Type_value = map[string]int32{ "INSERT": 0, "UPDATE": 1, "DELETE": 2, "UPSERT": 4, } ) func (x RegistryMutation_Type) Enum() *RegistryMutation_Type { p := new(RegistryMutation_Type) *p = x return p } func (x RegistryMutation_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RegistryMutation_Type) Descriptor() protoreflect.EnumDescriptor { return file_transport_proto_enumTypes[1].Descriptor() } func (RegistryMutation_Type) Type() protoreflect.EnumType { return &file_transport_proto_enumTypes[1] } func (x RegistryMutation_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RegistryMutation_Type.Descriptor instead. func (RegistryMutation_Type) EnumDescriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{8, 0} } // Message corresponding to an error while performing // an operation on the registry. type RegistryError struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Code RegistryError_Code `protobuf:"varint,1,opt,name=code,proto3,enum=ic_registry_transport.pb.v1.RegistryError_Code" json:"code,omitempty"` // The reason for the error. // This is optional. Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` // The key on which the error occurred. // This is optional and only present for by-key errors. Key []byte `protobuf:"bytes,3,opt,name=key,proto3" json:"key,omitempty"` } func (x *RegistryError) Reset() { *x = RegistryError{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryError) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryError) ProtoMessage() {} func (x *RegistryError) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryError.ProtoReflect.Descriptor instead. func (*RegistryError) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{0} } func (x *RegistryError) GetCode() RegistryError_Code { if x != nil { return x.Code } return RegistryError_MALFORMED_MESSAGE } func (x *RegistryError) GetReason() string { if x != nil { return x.Reason } return "" } func (x *RegistryError) GetKey() []byte { if x != nil { return x.Key } return nil } // A single change made to a key in the registry. type RegistryValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The value that was set in this mutation. If the // mutation is a deletion, the field has no meaning. Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` // The version at which this mutation happened. Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // If true, this change represents a deletion. DeletionMarker bool `protobuf:"varint,3,opt,name=deletion_marker,json=deletionMarker,proto3" json:"deletion_marker,omitempty"` } func (x *RegistryValue) Reset() { *x = RegistryValue{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryValue) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryValue) ProtoMessage() {} func (x *RegistryValue) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryValue.ProtoReflect.Descriptor instead. func (*RegistryValue) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{1} } func (x *RegistryValue) GetValue() []byte { if x != nil { return x.Value } return nil } func (x *RegistryValue) GetVersion() uint64 { if x != nil { return x.Version } return 0 } func (x *RegistryValue) GetDeletionMarker() bool { if x != nil { return x.DeletionMarker } return false } // A sequence of changes made to a key in the registry. type RegistryDelta struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Values []*RegistryValue `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"` } func (x *RegistryDelta) Reset() { *x = RegistryDelta{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryDelta) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryDelta) ProtoMessage() {} func (x *RegistryDelta) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryDelta.ProtoReflect.Descriptor instead. func (*RegistryDelta) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{2} } func (x *RegistryDelta) GetKey() []byte { if x != nil { return x.Key } return nil } func (x *RegistryDelta) GetValues() []*RegistryValue { if x != nil { return x.Values } return nil } // Message to retrieve all the changes from the registry // since 'version'. type RegistryGetChangesSinceRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Version uint64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` } func (x *RegistryGetChangesSinceRequest) Reset() { *x = RegistryGetChangesSinceRequest{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryGetChangesSinceRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryGetChangesSinceRequest) ProtoMessage() {} func (x *RegistryGetChangesSinceRequest) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryGetChangesSinceRequest.ProtoReflect.Descriptor instead. func (*RegistryGetChangesSinceRequest) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{3} } func (x *RegistryGetChangesSinceRequest) GetVersion() uint64 { if x != nil { return x.Version } return 0 } // Message corresponding to the response from the registry // canister to a get_latest_version() request. type RegistryGetChangesSinceResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // If anything went wrong, the registry canister // will set this error. Error *RegistryError `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` // The last version of the registry. Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // A list of all the keys and all the values that change // and all the intermediate changes since the version // requested. Deltas []*RegistryDelta `protobuf:"bytes,3,rep,name=deltas,proto3" json:"deltas,omitempty"` } func (x *RegistryGetChangesSinceResponse) Reset() { *x = RegistryGetChangesSinceResponse{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryGetChangesSinceResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryGetChangesSinceResponse) ProtoMessage() {} func (x *RegistryGetChangesSinceResponse) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryGetChangesSinceResponse.ProtoReflect.Descriptor instead. func (*RegistryGetChangesSinceResponse) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{4} } func (x *RegistryGetChangesSinceResponse) GetError() *RegistryError { if x != nil { return x.Error } return nil } func (x *RegistryGetChangesSinceResponse) GetVersion() uint64 { if x != nil { return x.Version } return 0 } func (x *RegistryGetChangesSinceResponse) GetDeltas() []*RegistryDelta { if x != nil { return x.Deltas } return nil } // Message to retrieve a version of some registry key // from the registry canister. type RegistryGetValueRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The version of the registry key to retrieve. // Optional: If not set (or set to the default value, 0), the method // will return the last version. Version *wrapperspb.UInt64Value `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` // The byte array corresponding to the key to retrieve // from the registry. // Required. Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` } func (x *RegistryGetValueRequest) Reset() { *x = RegistryGetValueRequest{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryGetValueRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryGetValueRequest) ProtoMessage() {} func (x *RegistryGetValueRequest) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryGetValueRequest.ProtoReflect.Descriptor instead. func (*RegistryGetValueRequest) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{5} } func (x *RegistryGetValueRequest) GetVersion() *wrapperspb.UInt64Value { if x != nil { return x.Version } return nil } func (x *RegistryGetValueRequest) GetKey() []byte { if x != nil { return x.Key } return nil } // Message corresponding to the response from the canister // to a get_value() request. // // Both 'version' and 'value' are mandatorily set if 'error' // is not set. type RegistryGetValueResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // If anything went wrong, the registry canister // will set this error. Error *RegistryError `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` // the version at which the value corresponding to the queried // key was last mutated (inserted, updated, or deleted) // before at or at the version specified // in the RegistryGetValueRequest. Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // The value retrieved from the registry. Value []byte `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` } func (x *RegistryGetValueResponse) Reset() { *x = RegistryGetValueResponse{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryGetValueResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryGetValueResponse) ProtoMessage() {} func (x *RegistryGetValueResponse) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryGetValueResponse.ProtoReflect.Descriptor instead. func (*RegistryGetValueResponse) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{6} } func (x *RegistryGetValueResponse) GetError() *RegistryError { if x != nil { return x.Error } return nil } func (x *RegistryGetValueResponse) GetVersion() uint64 { if x != nil { return x.Version } return 0 } func (x *RegistryGetValueResponse) GetValue() []byte { if x != nil { return x.Value } return nil } // Message corresponding to the response from the canister // to a get_latest_version() request. type RegistryGetLatestVersionResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // the latest registry version Version uint64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` } func (x *RegistryGetLatestVersionResponse) Reset() { *x = RegistryGetLatestVersionResponse{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryGetLatestVersionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryGetLatestVersionResponse) ProtoMessage() {} func (x *RegistryGetLatestVersionResponse) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryGetLatestVersionResponse.ProtoReflect.Descriptor instead. func (*RegistryGetLatestVersionResponse) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{7} } func (x *RegistryGetLatestVersionResponse) GetVersion() uint64 { if x != nil { return x.Version } return 0 } // A single mutation in the registry. type RegistryMutation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The type of the mutation to apply to the registry. // Always required. MutationType RegistryMutation_Type `protobuf:"varint,1,opt,name=mutation_type,json=mutationType,proto3,enum=ic_registry_transport.pb.v1.RegistryMutation_Type" json:"mutation_type,omitempty"` // The key of the entry to mutate in the registry. // Always required. Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` // The value to mutate in the registry. // Required for insert, update, but not for delete. Value []byte `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` } func (x *RegistryMutation) Reset() { *x = RegistryMutation{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryMutation) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryMutation) ProtoMessage() {} func (x *RegistryMutation) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryMutation.ProtoReflect.Descriptor instead. func (*RegistryMutation) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{8} } func (x *RegistryMutation) GetMutationType() RegistryMutation_Type { if x != nil { return x.MutationType } return RegistryMutation_INSERT } func (x *RegistryMutation) GetKey() []byte { if x != nil { return x.Key } return nil } func (x *RegistryMutation) GetValue() []byte { if x != nil { return x.Value } return nil } // A precondition on the version at which the value of a given key was // last mutated. type Precondition struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // The precondition is satisfied if and only is the version in the // RegistryValue for the key is equal to this. ExpectedVersion uint64 `protobuf:"varint,2,opt,name=expected_version,json=expectedVersion,proto3" json:"expected_version,omitempty"` } func (x *Precondition) Reset() { *x = Precondition{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Precondition) String() string { return protoimpl.X.MessageStringOf(x) } func (*Precondition) ProtoMessage() {} func (x *Precondition) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Precondition.ProtoReflect.Descriptor instead. func (*Precondition) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{9} } func (x *Precondition) GetKey() []byte { if x != nil { return x.Key } return nil } func (x *Precondition) GetExpectedVersion() uint64 { if x != nil { return x.ExpectedVersion } return 0 } // Message corresponding to a list of mutations to apply, atomically, to the // registry canister. If any of the mutations fails, the whole operation will fail. type RegistryAtomicMutateRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The set of mutations to apply to the registry. Mutations []*RegistryMutation `protobuf:"bytes,1,rep,name=mutations,proto3" json:"mutations,omitempty"` // Preconditions at the key level. Preconditions []*Precondition `protobuf:"bytes,5,rep,name=preconditions,proto3" json:"preconditions,omitempty"` } func (x *RegistryAtomicMutateRequest) Reset() { *x = RegistryAtomicMutateRequest{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryAtomicMutateRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryAtomicMutateRequest) ProtoMessage() {} func (x *RegistryAtomicMutateRequest) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryAtomicMutateRequest.ProtoReflect.Descriptor instead. func (*RegistryAtomicMutateRequest) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{10} } func (x *RegistryAtomicMutateRequest) GetMutations() []*RegistryMutation { if x != nil { return x.Mutations } return nil } func (x *RegistryAtomicMutateRequest) GetPreconditions() []*Precondition { if x != nil { return x.Preconditions } return nil } // Message corresponding to the response of an atomic_mutate request. If any of // mutations failed the corresponding errors will be reflected in 'errors'. // Otherwise 'version' will contain the version under which all the mutations // were applied. type RegistryAtomicMutateResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // If anything went wrong, the registry canister // will set this error. Errors []*RegistryError `protobuf:"bytes,1,rep,name=errors,proto3" json:"errors,omitempty"` // The last version of the registry. Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` } func (x *RegistryAtomicMutateResponse) Reset() { *x = RegistryAtomicMutateResponse{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RegistryAtomicMutateResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RegistryAtomicMutateResponse) ProtoMessage() {} func (x *RegistryAtomicMutateResponse) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RegistryAtomicMutateResponse.ProtoReflect.Descriptor instead. func (*RegistryAtomicMutateResponse) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{11} } func (x *RegistryAtomicMutateResponse) GetErrors() []*RegistryError { if x != nil { return x.Errors } return nil } func (x *RegistryAtomicMutateResponse) GetVersion() uint64 { if x != nil { return x.Version } return 0 } // Message encoding a response to any *_certified method call. type CertifiedResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The hash tree encoding both the response and the intermediate // nodes required to recompute the root hash stored in // "certified_data" of the canister. // // Note that the contents of the tree depends on the type of request // issued. HashTree *MixedHashTree `protobuf:"bytes,1,opt,name=hash_tree,json=hashTree,proto3" json:"hash_tree,omitempty"` // The certificate obtained from the system using // ic0.data_certificate_copy. Certificate []byte `protobuf:"bytes,2,opt,name=certificate,proto3" json:"certificate,omitempty"` } func (x *CertifiedResponse) Reset() { *x = CertifiedResponse{} if protoimpl.UnsafeEnabled { mi := &file_transport_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CertifiedResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*CertifiedResponse) ProtoMessage() {} func (x *CertifiedResponse) ProtoReflect() protoreflect.Message { mi := &file_transport_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use CertifiedResponse.ProtoReflect.Descriptor instead. func (*CertifiedResponse) Descriptor() ([]byte, []int) { return file_transport_proto_rawDescGZIP(), []int{12} } func (x *CertifiedResponse) GetHashTree() *MixedHashTree { if x != nil { return x.HashTree } return nil } func (x *CertifiedResponse) GetCertificate() []byte { if x != nil { return x.Certificate } return nil } var File_transport_proto protoreflect.FileDescriptor var file_transport_proto_rawDesc = []byte{ 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1b, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x15, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x5f, 0x74, 0x72, 0x65, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x94, 0x02, 0x0a, 0x0d, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x43, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, 0x93, 0x01, 0x0a, 0x04, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x4d, 0x41, 0x4c, 0x46, 0x4f, 0x52, 0x4d, 0x45, 0x44, 0x5f, 0x4d, 0x45, 0x53, 0x53, 0x41, 0x47, 0x45, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x4b, 0x45, 0x59, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x50, 0x52, 0x45, 0x53, 0x45, 0x4e, 0x54, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x4b, 0x45, 0x59, 0x5f, 0x41, 0x4c, 0x52, 0x45, 0x41, 0x44, 0x59, 0x5f, 0x50, 0x52, 0x45, 0x53, 0x45, 0x4e, 0x54, 0x10, 0x02, 0x12, 0x16, 0x0a, 0x12, 0x56, 0x45, 0x52, 0x53, 0x49, 0x4f, 0x4e, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x4c, 0x41, 0x54, 0x45, 0x53, 0x54, 0x10, 0x03, 0x12, 0x19, 0x0a, 0x15, 0x56, 0x45, 0x52, 0x53, 0x49, 0x4f, 0x4e, 0x5f, 0x42, 0x45, 0x59, 0x4f, 0x4e, 0x44, 0x5f, 0x4c, 0x41, 0x54, 0x45, 0x53, 0x54, 0x10, 0x04, 0x12, 0x13, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0xe7, 0x07, 0x22, 0x68, 0x0a, 0x0d, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x61, 0x72, 0x6b, 0x65, 0x72, 0x22, 0x65, 0x0a, 0x0d, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x42, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x22, 0x3a, 0x0a, 0x1e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x47, 0x65, 0x74, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x53, 0x69, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xc1, 0x01, 0x0a, 0x1f, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x47, 0x65, 0x74, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x53, 0x69, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x40, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x42, 0x0a, 0x06, 0x64, 0x65, 0x6c, 0x74, 0x61, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x52, 0x06, 0x64, 0x65, 0x6c, 0x74, 0x61, 0x73, 0x22, 0x63, 0x0a, 0x17, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x47, 0x65, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x36, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, 0x8c, 0x01, 0x0a, 0x18, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x47, 0x65, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x40, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x3c, 0x0a, 0x20, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x47, 0x65, 0x74, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xcb, 0x01, 0x0a, 0x10, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x57, 0x0a, 0x0d, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x32, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0c, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x36, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0a, 0x0a, 0x06, 0x49, 0x4e, 0x53, 0x45, 0x52, 0x54, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x55, 0x50, 0x44, 0x41, 0x54, 0x45, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x55, 0x50, 0x53, 0x45, 0x52, 0x54, 0x10, 0x04, 0x22, 0x4b, 0x0a, 0x0c, 0x50, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x29, 0x0a, 0x10, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xc1, 0x01, 0x0a, 0x1b, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x41, 0x74, 0x6f, 0x6d, 0x69, 0x63, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x4b, 0x0a, 0x09, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x4f, 0x0a, 0x0d, 0x70, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x70, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x22, 0x7c, 0x0a, 0x1c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x41, 0x74, 0x6f, 0x6d, 0x69, 0x63, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x42, 0x0a, 0x06, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x70, 0x62, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x06, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x74, 0x0a, 0x11, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x09, 0x68, 0x61, 0x73, 0x68, 0x5f, 0x74, 0x72, 0x65, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x2e, 0x78, 0x6e, 0x65, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x78, 0x65, 0x64, 0x48, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x52, 0x08, 0x68, 0x61, 0x73, 0x68, 0x54, 0x72, 0x65, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_transport_proto_rawDescOnce sync.Once file_transport_proto_rawDescData = file_transport_proto_rawDesc ) func file_transport_proto_rawDescGZIP() []byte { file_transport_proto_rawDescOnce.Do(func() { file_transport_proto_rawDescData = protoimpl.X.CompressGZIP(file_transport_proto_rawDescData) }) return file_transport_proto_rawDescData } var file_transport_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_transport_proto_msgTypes = make([]protoimpl.MessageInfo, 13) var file_transport_proto_goTypes = []interface{}{ (RegistryError_Code)(0), // 0: ic_registry_transport.pb.v1.RegistryError.Code (RegistryMutation_Type)(0), // 1: ic_registry_transport.pb.v1.RegistryMutation.Type (*RegistryError)(nil), // 2: ic_registry_transport.pb.v1.RegistryError (*RegistryValue)(nil), // 3: ic_registry_transport.pb.v1.RegistryValue (*RegistryDelta)(nil), // 4: ic_registry_transport.pb.v1.RegistryDelta (*RegistryGetChangesSinceRequest)(nil), // 5: ic_registry_transport.pb.v1.RegistryGetChangesSinceRequest (*RegistryGetChangesSinceResponse)(nil), // 6: ic_registry_transport.pb.v1.RegistryGetChangesSinceResponse (*RegistryGetValueRequest)(nil), // 7: ic_registry_transport.pb.v1.RegistryGetValueRequest (*RegistryGetValueResponse)(nil), // 8: ic_registry_transport.pb.v1.RegistryGetValueResponse (*RegistryGetLatestVersionResponse)(nil), // 9: ic_registry_transport.pb.v1.RegistryGetLatestVersionResponse (*RegistryMutation)(nil), // 10: ic_registry_transport.pb.v1.RegistryMutation (*Precondition)(nil), // 11: ic_registry_transport.pb.v1.Precondition (*RegistryAtomicMutateRequest)(nil), // 12: ic_registry_transport.pb.v1.RegistryAtomicMutateRequest (*RegistryAtomicMutateResponse)(nil), // 13: ic_registry_transport.pb.v1.RegistryAtomicMutateResponse (*CertifiedResponse)(nil), // 14: ic_registry_transport.pb.v1.CertifiedResponse (*wrapperspb.UInt64Value)(nil), // 15: google.protobuf.UInt64Value (*MixedHashTree)(nil), // 16: messaging.xnet.v1.MixedHashTree } var file_transport_proto_depIdxs = []int32{ 0, // 0: ic_registry_transport.pb.v1.RegistryError.code:type_name -> ic_registry_transport.pb.v1.RegistryError.Code 3, // 1: ic_registry_transport.pb.v1.RegistryDelta.values:type_name -> ic_registry_transport.pb.v1.RegistryValue 2, // 2: ic_registry_transport.pb.v1.RegistryGetChangesSinceResponse.error:type_name -> ic_registry_transport.pb.v1.RegistryError 4, // 3: ic_registry_transport.pb.v1.RegistryGetChangesSinceResponse.deltas:type_name -> ic_registry_transport.pb.v1.RegistryDelta 15, // 4: ic_registry_transport.pb.v1.RegistryGetValueRequest.version:type_name -> google.protobuf.UInt64Value 2, // 5: ic_registry_transport.pb.v1.RegistryGetValueResponse.error:type_name -> ic_registry_transport.pb.v1.RegistryError 1, // 6: ic_registry_transport.pb.v1.RegistryMutation.mutation_type:type_name -> ic_registry_transport.pb.v1.RegistryMutation.Type 10, // 7: ic_registry_transport.pb.v1.RegistryAtomicMutateRequest.mutations:type_name -> ic_registry_transport.pb.v1.RegistryMutation 11, // 8: ic_registry_transport.pb.v1.RegistryAtomicMutateRequest.preconditions:type_name -> ic_registry_transport.pb.v1.Precondition 2, // 9: ic_registry_transport.pb.v1.RegistryAtomicMutateResponse.errors:type_name -> ic_registry_transport.pb.v1.RegistryError 16, // 10: ic_registry_transport.pb.v1.CertifiedResponse.hash_tree:type_name -> messaging.xnet.v1.MixedHashTree 11, // [11:11] is the sub-list for method output_type 11, // [11:11] is the sub-list for method input_type 11, // [11:11] is the sub-list for extension type_name 11, // [11:11] is the sub-list for extension extendee 0, // [0:11] is the sub-list for field type_name } func init() { file_transport_proto_init() } func file_transport_proto_init() { if File_transport_proto != nil { return } file_mixed_hash_tree_proto_init() if !protoimpl.UnsafeEnabled { file_transport_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryError); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryValue); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryDelta); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryGetChangesSinceRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryGetChangesSinceResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryGetValueRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryGetValueResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryGetLatestVersionResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryMutation); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Precondition); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryAtomicMutateRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RegistryAtomicMutateResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_transport_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*CertifiedResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_transport_proto_rawDesc, NumEnums: 2, NumMessages: 13, NumExtensions: 0, NumServices: 0, }, GoTypes: file_transport_proto_goTypes, DependencyIndexes: file_transport_proto_depIdxs, EnumInfos: file_transport_proto_enumTypes, MessageInfos: file_transport_proto_msgTypes, }.Build() File_transport_proto = out.File file_transport_proto_rawDesc = nil file_transport_proto_goTypes = nil file_transport_proto_depIdxs = nil } <|start_filename|>utils/idl/rec.go<|end_filename|> package idl import ( "bytes" "fmt" "math/big" "sort" "strings" "github.com/aviate-labs/leb128" ) type Rec struct { Fields []Field } func NewRec(fields map[string]Type) *Rec { var rec Rec for k, v := range fields { rec.Fields = append(rec.Fields, Field{ Name: k, Type: v, }) } sort.Slice(rec.Fields, func(i, j int) bool { return Hash(rec.Fields[i].Name).Cmp(Hash(rec.Fields[j].Name)) < 0 }) return &rec } func (r Rec) AddTypeDefinition(tdt *TypeDefinitionTable) error { for _, f := range r.Fields { if err := f.Type.AddTypeDefinition(tdt); err != nil { return err } } id, err := leb128.EncodeSigned(big.NewInt(recType)) if err != nil { return err } l, err := leb128.EncodeUnsigned(big.NewInt(int64(len(r.Fields)))) if err != nil { return err } var vs []byte for _, f := range r.Fields { l, err := leb128.EncodeUnsigned(Hash(f.Name)) if err != nil { return nil } t, err := f.Type.EncodeType(tdt) if err != nil { return nil } vs = append(vs, concat(l, t)...) } tdt.Add(r, concat(id, l, vs)) return nil } func (r Rec) Decode(r_ *bytes.Reader) (interface{}, error) { rec := make(map[string]interface{}) for _, f := range r.Fields { v, err := f.Type.Decode(r_) if err != nil { return nil, err } rec[f.Name] = v } if len(rec) == 0 { return nil, nil } return rec, nil } func (r Rec) EncodeType(tdt *TypeDefinitionTable) ([]byte, error) { idx, ok := tdt.Indexes[r.String()] if !ok { return nil, fmt.Errorf("missing type index for: %s", r) } return leb128.EncodeSigned(big.NewInt(int64(idx))) } func (r Rec) EncodeValue(v interface{}) ([]byte, error) { if v == nil { return nil, nil } fs, ok := v.(map[string]interface{}) if !ok { return nil, fmt.Errorf("invalid argument: %v", v) } var vs_ []interface{} for _, f := range r.Fields { vs_ = append(vs_, fs[f.Name]) } var vs []byte for i, f := range r.Fields { v_, err := f.Type.EncodeValue(vs_[i]) if err != nil { return nil, err } vs = append(vs, v_...) } return vs, nil } func (Rec) Fill(Type) { } func (r Rec) String() string { var s []string for _, f := range r.Fields { s = append(s, fmt.Sprintf("%s:%s", f.Name, f.Type.String())) } return fmt.Sprintf("record {%s}", strings.Join(s, "; ")) }
mix-labs/IC-Go
<|start_filename|>Dockerfile<|end_filename|> FROM python:latest ENV VIRTUAL_ENV "/venv" RUN python -m venv $VIRTUAL_ENV ENV PATH "$VIRTUAL_ENV/bin:$PATH" RUN . venv/bin/activate RUN python -m pip install --upgrade pip RUN apt-get update && apt-get install -y --no-install-recommends \ poppler-utils libcairo2 libpango-1.0-0 \ libpangocairo-1.0-0 libgdk-pixbuf2.0-0 libffi-dev shared-mime-info ocrmypdf \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* WORKDIR /bot COPY . /bot RUN pip install -r requirements.txt RUN pybabel compile -D pdf_bot -d locale EXPOSE ${PORT} ENV APP_URL ${APP_URL} ENV TELE_TOKEN ${TELE_TOKEN} ENV DEV_TELE_ID ${DEV_TELE_ID} ENV GCP_CRED ${GCP_CRED} ENV GCP_KEY ${GCP_KEY} ENV SLACK_TOKEN ${SLACK_TOKEN} ENV STRIPE_TOKEN ${STRIPE_TOKEN} CMD ["python", "bot.py"] <|start_filename|>app.json<|end_filename|> { "name": "PDF Bot", "description": "Telegram's best Open Source ALL-In-One Multi Purpose RoBot for PDF editing 🤖.", "logo": "https://telegra.ph/file/7f5b5be68dd506edc4d5d.jpg", "keywords": ["telegram","best","heroku","PDF","bot"], "success_url": "https://github.com/MrBotDeveloper", "website": "https://mrbotdeveloper.github.io/PDF-Bot/", "repository": "https://github.com/MrBotDeveloper/PDF-Bot", "env": { "DEV_TELE_ID": { "description": "YOUR_TELEGRAM_USER_ID", "value": "", "required": true }, "TELE_TOKEN": { "description": "YOUR_TELEGRAM_BOT_TOKEN", "value": "", "required": true }, "GOOGLE_APPLICATION_CREDENTIALS": { "description": "Your GCP Credentials file path if in root directory just put file Name.", "value": "GCP_FILE.json", "required": true }, "STRIPE_TOKEN": { "description": "Get an token from stripe.com for receiving Donations 💰", "value": "" }, "SLACK_TOKEN": { "description": "To get all Feedbacks in slack.com not necessary if not entered you will receive feedbacks in telegram.", "value": "" } }, "stack": "container" }
Lucif3rHun1/PDF-Bot
<|start_filename|>lib/scrollview/baseListView.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/2. /// class BaseListView extends StatefulWidget { @override _BaseListViewState createState() => _BaseListViewState(); } class _BaseListViewState extends State<BaseListView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('ListView '), ), body: NotificationListener( child: NotificationListener<ScrollNotification>( child: _body4(), onNotification: (notification) { if (notification is ScrollEndNotification) { print('in:${notification.runtimeType} $notification'); } else if (notification is ScrollStartNotification) { print('in:${notification.runtimeType} $notification'); } return false; }, ), onNotification: (notification) { // print('out:${notification.runtimeType} $notification'); return true; }, ), ); } Widget _body() { List<Widget> list = new List(); for (int i = 0; i < 5; i++) { list.add(Card( child: Container( height: 40, width: MediaQuery.of(context).size.width, alignment: Alignment.center, child: Text('$i'), ), )); } return ListView( itemExtent: 5, shrinkWrap: false, addAutomaticKeepAlives: true, children: list, addSemanticIndexes: true, cacheExtent: 50, ); } Widget _body2() { return ListView.builder( itemExtent: 80, itemBuilder: _buildCell, ); } Widget _body3() { return ListView.separated( itemBuilder: _buildCell, separatorBuilder: _buildSeparatedCell, itemCount: list.length, ); } Widget _body4() { return Column( children: <Widget>[ Container( height: 30, width: MediaQuery.of(context).size.width, alignment: Alignment.center, decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.lightBlueAccent, Colors.orange])), child: Text('我是头部信息,可以自定义的'), ), Expanded( child: ListView.separated( itemBuilder: _buildCell, separatorBuilder: _buildSeparatedCell, itemCount: list.length, ), ) ], ); } Widget _buildCell(ctx, int index) { if (index < list.length - 1) { return Container( height: 80, alignment: Alignment.center, child: TestContainer( title: list[index], ), ); } else if (list.length >= 5) { return Container( alignment: Alignment.center, height: 80, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[Icon(Icons.done), Text('没有更多数据了')], ), ); } else { _getMoreData(); //加载数据 return Container( alignment: Alignment.center, child: RefreshProgressIndicator(), ); } } Widget _buildSeparatedCell(ctx, int index) { return Divider( height: 2, thickness: 0.5, indent: 10, endIndent: 10, color: index % 2 == 0 ? Colors.blue : Colors.orange, ); } List<String> list; @override void initState() { list = new List(); _getMoreData(); super.initState(); } void _getMoreData() async { await Future.delayed(Duration(milliseconds: 2000)); for (int i = 0; i < 5; i++) { list.add(DateTime.now().toString()); } setState(() {}); } } class TestContainer extends StatefulWidget { final String title; TestContainer({Key key, this.title}) : super(key: key); @override _TestContainerState createState() => _TestContainerState(); } class _TestContainerState extends State<TestContainer> { @override Widget build(BuildContext context) { return _body(); } Widget _body() { return Container( child: Text(widget.title ?? '123'), ); } @override void dispose() { print(widget.title + ' dispose'); super.dispose(); } } <|start_filename|>lib/animation/base_tagger_animation.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/21. /// class BaseTaggerAnimation extends StatefulWidget { BaseTaggerAnimation({Key key}) : super(key: key); @override _BaseTaggerAnimationState createState() => _BaseTaggerAnimationState(); } class _BaseTaggerAnimationState extends State<BaseTaggerAnimation> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<double> _radius; Animation<double> _height; @override void initState() { _animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 4000)) ..repeat(); _radius = Tween<double>(begin: 0, end: 100).animate(CurvedAnimation( parent: _animationController, curve: Interval(0, 0.5, curve: Curves.easeIn))); _height = Tween<double>(begin: 1, end: 0.5).animate(CurvedAnimation( parent: _animationController, curve: Interval(0.5, 1.0, curve: Curves.bounceOut), )); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('交织动画'), ), body: _body(), ); } Widget _body() { double height = 200; return AnimatedBuilder( animation: _animationController, builder: (ctx, child) { return Center( child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(_radius.value)), child: Container( width: height * _height.value, height: height * _height.value, color: Colors.orange, ), ), ); }, ); } @override void dispose() { _animationController.dispose(); super.dispose(); } } <|start_filename|>lib/baseWidget/base_slider.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseSliderRangPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseSliderPageState(); } static String get routeName => '/BaseSliderRangPage'; } class _BaseSliderPageState extends State<BaseSliderRangPage> { double value; RangeValues rangeValues; @override void initState() { super.initState(); value = 0.5; rangeValues = RangeValues(1, 10); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseSliderPageState'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('拖动下方slider查看效果'), SizedBox( height: 50, ), Slider( value: value, onChanged: (v) { setState(() { value = v; }); }, label: '$value', divisions: 100, activeColor: Colors.redAccent, ), RangeSlider( values: rangeValues, max: 100, min: 0, onChanged: (v) { setState(() { rangeValues = v; }); }, labels: RangeLabels('${rangeValues.start}', '${rangeValues.end}'), divisions: 100, activeColor: Colors.redAccent, ), ], ), ), ); } } <|start_filename|>lib/container/base_constraints.dart<|end_filename|> import 'package:flutter/material.dart'; class BaseConstraints extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('尺寸限制类容器'), ), body: _widget(), ); } Widget _redBox() { return ConstrainedBox( constraints: BoxConstraints(minHeight: 50, minWidth: 50), child: Container( color: Colors.red, ), ); } Widget _widget() { return Container( color: Colors.black12, constraints: BoxConstraints( minHeight: 100, minWidth: 100, maxWidth: 200, maxHeight: 200), child: UnconstrainedBox( child: _redBox(), ), ); } Widget _bd() { return Column( children: <Widget>[ Container( constraints: BoxConstraints( minWidth: 50, minHeight: 50, maxHeight: 200, maxWidth: 100), color: Colors.red, child: Container( constraints: BoxConstraints( minWidth: 30, minHeight: 30, maxHeight: 50, maxWidth: 100), // width: 30, // height: 30, color: Colors.blue, ), ), _redBox(), SizedBox( height: 10, ), // SizedBox(width: 100.0, height: 100.0, child: _redBox()), Container( width: 200, height: 200, child: ConstrainedBox( constraints: BoxConstraints( minHeight: 100, minWidth: 100, ), // color: Colors.black12, child: _redBox(), ), ), ], ); } } <|start_filename|>lib/tips/base_record.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_simple_record_and_player/fluttersimplerecordandplayer.dart'; import 'package:path_provider/path_provider.dart'; /// /// Created by fgyong on 2020/7/30. /// class BaseRecordRoute extends StatefulWidget { BaseRecordRoute({Key key}) : super(key: key); @override _BaseRecordRouteState createState() => _BaseRecordRouteState(); } class _BaseRecordRouteState extends State<BaseRecordRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('录音测试'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[ Text('录音需在真机上测试'), OutlineButton( child: Text('录音开始'), onPressed: _start, ), OutlineButton( child: Text('录音结束'), onPressed: _end, ), OutlineButton( child: Text('录音播放'), onPressed: _play, ), OutlineButton( child: Text('播放停止'), onPressed: () { _andPlayer.stopPlay(); }, ), Text('文件地址:$_path'), ], ), ); } String _path = ''; void _start() async { var p = await getTemporaryDirectory(); _path = '${p.path}/mp3/${DateTime.now()}.mp3'; _andPlayer.startRecord(null, (error) { print(error); }); } void _end() { _andPlayer.stopRecord; _path = _andPlayer.recordListPath.last.toString(); setState(() {}); print(_andPlayer.recordListPath.last.toString()); } void _play() { _andPlayer.play(_andPlayer.recordListPath.last, isLocal: true); } SimpleSoundRecordAndPlayer _andPlayer; @override void initState() { _andPlayer = SimpleSoundRecordAndPlayer(); super.initState(); } } <|start_filename|>lib/main3.dart<|end_filename|> import 'dart:isolate'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/29. /// main() async { runApp(HomeRoute()); } class HomeRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Text('Hello world'), ); } } class HomeViewModel extends ChangeNotifier {} /// 创建并管理 多线程 void m() async { var ourFirstReceivePort = new ReceivePort(); await Isolate.spawn(echo, ourFirstReceivePort.sendPort); var echoPort = await ourFirstReceivePort.first; // if you try to use our first receive port, you’ll get this error: // “Bad state: Stream has already been listened to.” // so it seems like you always need a new port to communicate with // an isolate (actor). var ourSecondReceivePort = ReceivePort(); echoPort.send(['message 1', ourSecondReceivePort.sendPort]); var msg = await ourSecondReceivePort.first; print('main received "$msg"'); // instead of 'await', use 'then' as a different way of receiving // a reply from 'echo' (handle it asynchronously, rather than // waiting for the reply) var port3 = ReceivePort(); echoPort.send(['message 2', port3.sendPort]); port3.first.then((msg) { print('main received "$msg"'); }); // use 'then' one more time var port4 = ReceivePort(); echoPort.send(['port 4', port4.sendPort]); port4.first.then((msg) { print('main received "$msg"'); }); print('end of main'); } echo(SendPort sendPort) async { var ourReceivePort = ReceivePort(); sendPort.send(ourReceivePort.sendPort); await for (var msg in ourReceivePort) { var data = msg[0]; // the 1st element we receive should be their message print('echo received "$data"'); SendPort replyToPort = msg[1]; // the 2nd element should be their port Future.delayed(const Duration(milliseconds: 100), () { replyToPort.send('echo said: ' + data); }); if (data == "bye") ourReceivePort.close(); } } <|start_filename|>lib/container/base_transform.dart<|end_filename|> import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseTransform extends StatefulWidget { _BaseTransformState createState() => _BaseTransformState(); } class _BaseTransformState extends State<BaseTransform> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('变换 Transform'), ), body: _body(), ); } double _rotate = 0, _scale = 1.0, _rotateX = 0, _rotateY = 0; Offset _offset = Offset(0, 0); Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Transform.rotate( angle: _rotate, alignment: Alignment.center, child: Container( child: Text('Transform.rotate'), color: Colors.blue, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('旋转角度:' + _rotate.toStringAsFixed(2)), CupertinoSlider( value: _rotate, max: pi * 2, min: 0, onChanged: (v) { setState(() { _rotate = v; }); }, ), ], ), SizedBox( height: 50, ), Transform.scale( scale: _scale, alignment: Alignment.center, child: Container( child: Text('Transform.scale'), color: Colors.blueAccent, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('放大倍数:' + _scale.toStringAsFixed(2)), CupertinoSlider( value: _scale, max: 3, min: 0.01, onChanged: (v) { setState(() { _scale = v; }); }, ), ], ), SizedBox( height: 50, ), Transform.translate( offset: _offset, child: Container( child: Text('Transform.translate'), color: Colors.blueAccent, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('位移X:' + _offset.dx.toStringAsFixed(2)), CupertinoSlider( value: _offset.dx, max: 100, min: -100, onChanged: (v) { setState(() { _offset = Offset(v, _offset.dy); }); }, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('位移Y:' + _offset.dy.toStringAsFixed(2)), CupertinoSlider( value: _offset.dy, max: 100, min: -100, onChanged: (v) { setState(() { _offset = Offset(_offset.dx, v); }); }, ), ], ), SizedBox( height: 50, ), Transform( transform: new Matrix4.identity() ..setEntry(3, 2, 0.01) ..rotateX(_rotateX) ..rotateY(_rotateY), alignment: Alignment.center, child: Container( width: 100, height: 100, child: Text('Matrix4'), alignment: Alignment.center, color: Colors.lightBlueAccent, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('翻转X:' + _rotateX.toStringAsFixed(2)), CupertinoSlider( value: _rotateX, max: pi / 2, min: -pi / 2, onChanged: (v) { setState(() { _rotateX = v; }); }, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('翻转Y:' + _rotateY.toStringAsFixed(2)), CupertinoSlider( value: _rotateY, max: pi / 2, min: -pi / 2, onChanged: (v) { setState(() { _rotateY = v; }); }, ), ], ), Container( color: Colors.orange, width: 120, height: 50, alignment: Alignment.center, child: RotatedBox( child: Container( width: 100, height: 100, child: Text('RotatedBox'), color: Colors.lightBlueAccent, ), quarterTurns: 1, ), ) ], ), ); } } <|start_filename|>lib/container/base_decorateBox.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseDecoratedBox extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('装饰容器'), ), body: Center( child: CupertinoScrollbar( child: SingleChildScrollView( child: _body(), )), ), ); } Widget _body() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('RadialGradient'), Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.blue, gradient: RadialGradient( colors: [Colors.orange, Colors.black12, Colors.blue]), ), ), Text('SweepGradient'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.blue, gradient: SweepGradient( colors: [Colors.orange, Colors.black12, Colors.blue]), ), ), ), Text('LinearGradient'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.blue, gradient: LinearGradient( colors: [Colors.orange, Colors.black12, Colors.blue]), ), ), ), Text('BoxShape.circle'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.blue, shape: BoxShape.circle, ), ), ), Text('BoxShape.rectangle BorderRadius.all(Radius.circular(20))'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.all(Radius.circular(20)), shape: BoxShape.rectangle, boxShadow: [ BoxShadow( offset: Offset(0, 10), color: Colors.black12, blurRadius: 10.0, spreadRadius: 3) ]), ), ), Text('DecorationImage and BoxShadow'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.all(Radius.circular(20)), backgroundBlendMode: BlendMode.darken, shape: BoxShape.rectangle, image: DecorationImage( image: AssetImage('img/fl.png'), fit: BoxFit.contain), boxShadow: [ BoxShadow( offset: Offset(-10, -10), ///左上角偏移 color: Colors.black12, //背景颜色 blurRadius: 2.0, //模糊度 2就是2个像素变成一个像素 spreadRadius: 3), //外扩范围 BoxShadow( offset: Offset(10, 10), color: Colors.black12, blurRadius: 2.0, spreadRadius: 3) ]), ), ), Text('child and image and color'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.all(Radius.circular(20)), image: DecorationImage( image: AssetImage('img/fl.png'), fit: BoxFit.contain), ), child: FlutterLogo( size: 20, ), )), Text('Border'), Padding( padding: EdgeInsets.all(20), child: Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.red, border: Border.fromBorderSide(BorderSide( color: Colors.orange, width: 10, )), // borderRadius: BorderRadius.all(Radius.circular(20)), ), child: FlutterLogo( size: 20, ), )) ], ); } } <|start_filename|>lib/util.dart<|end_filename|> class Util { static int _maxLen = 128; static String _tagValue = ''; static void v(Object object, {String tag}) { log('$tag', ' e ', object); } static void log(String tag, String stag, Object object) { String da = object.toString(); tag = tag ?? _tagValue; if (da.length <= _maxLen) { print("$tag::$stag:: $da"); return; } print( '$tag::$stag ============================= log start ============================='); while (da.isNotEmpty) { if (da.length > _maxLen) { print("${da.substring(0, _maxLen)}"); da = da.substring(_maxLen, da.length); } else { print("$da"); da = ""; } } print( '$tag::$stag ============================= log end ============================='); } } <|start_filename|>lib/scrollview/baseSingleChildScrollView.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/2. /// class BaseSingleChildScrollView extends StatefulWidget { @override _BaseSingleChildScrollViewState createState() => _BaseSingleChildScrollViewState(); } class _BaseSingleChildScrollViewState extends State<BaseSingleChildScrollView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('SingleChildScrollView'), ), body: _body(), ); } Widget _body() { List<Widget> list = new List(); for (int i = 0; i < 30; i++) { list.add(Card( child: Container( height: 140, width: MediaQuery.of(context).size.width, alignment: Alignment.center, child: Text('$i'), ), )); } return CupertinoScrollbar( child: SingleChildScrollView( reverse: true, physics: BouncingScrollPhysics(), scrollDirection: Axis.vertical, child: Column( children: list, ), ), ); } } <|start_filename|>lib/baseWidget/base_rotation.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseRotationBoxPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseSliderPageState(); } static String get routeName => '/BaseRotationBoxPage'; } class _BaseSliderPageState extends State<BaseRotationBoxPage> { @override void initState() { super.initState(); } int value = 1; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseSliderPageState'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('点击蓝色文字 看见旋转效果 \n RotatedBox会影响布局,而transform不会影响布局,只会影响绘制。'), SizedBox( height: 50, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ TextButton( child: RotatedBox( quarterTurns: value, child: Container( padding: EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.all(Radius.circular(10))), child: Text( '点我旋转', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white), ), ), ), onPressed: () { setState(() { value += 1; value %= 4; print(value); }); }, ), Text('点击左侧按钮 我会移动的'), ], ) ], ), ), ); } } <|start_filename|>lib/tips/base_tabbar.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/10. /// // ignore: must_be_immutable class BaseFYTabBar extends StatefulWidget { double offset; List<String> titles; /// int initPageIndex; /// 线条的宽度倍数 [0.1,1] double value; /// 线的高度 double lineHeight; double tabHeight; Color lineColor; /// 屏幕最大包含个数 int maxTabsOfScreen; /// 默认文字样式 TextStyle style; /// 高亮文字样式 TextStyle hlightStyle; BaseFYTabBar({ Key key, this.offset, @required this.titles, @required this.maxTabsOfScreen, this.initPageIndex = 0, this.value = 0.5, this.lineHeight = 2, this.tabHeight = 55, this.lineColor = Colors.red, this.style, this.hlightStyle, }) : super(key: key) { // assert((value >= 0.1 && value <= 1.0), 'value 范围是[0.1,1.0]'); assert(titles != null, 'titles is null'); assert(offset != null, 'offset is null'); hlightStyle ??= TextStyle(fontSize: 18, color: Colors.red); } @override _BaseFYTabbarState createState() => _BaseFYTabbarState(); } class _BaseFYTabbarState extends State<BaseFYTabBar> { bool _isFirstBuild = true; @override Widget build(BuildContext context) { return _body(); } double _width = 0; int get tabs => widget.titles.length; int get maxTabsOfScreen => widget.maxTabsOfScreen ?? 4; double _lineLeftOffset; Widget _body() { double w = MediaQuery.of(context).size.width / maxTabsOfScreen; double widthOfScreen = MediaQuery.of(context).size.width; int pages = (widget.offset / widthOfScreen).floor(); int _isCurrentPageIndex = (widget.offset / widthOfScreen).round(); if (_isFirstBuild) { _isFirstBuild = false; pages = widget.initPageIndex; } List<Widget> list = List(); for (int i = 0; i < widget.titles.length; i++) { bool _isCurrentPage = i == _isCurrentPageIndex; list.add(SliverToBoxAdapter( child: Container( alignment: Alignment.center, width: w, child: Text( widget.titles[i], style: _isCurrentPage ? widget.hlightStyle : TextStyle(), ), ), )); } double _leftMargin = w * (1 - widget.value) * 0.5, _defaultWidth = w * widget.value, _currentPageOffset = (widget.offset.toInt() % widthOfScreen.toInt()).toDouble(); _lineLeftOffset = pages * w; if (_currentPageOffset > widthOfScreen / 2) { _currentPageOffset -= widthOfScreen / 2; _lineLeftOffset = pages * w + _leftMargin; _lineLeftOffset += _currentPageOffset / widthOfScreen * 2 * w; /// 偏移量 double of = _currentPageOffset * 2 / widthOfScreen * _defaultWidth; _width = _defaultWidth + _defaultWidth - of; } else { _width = _defaultWidth + _currentPageOffset * 2 / widthOfScreen * _defaultWidth; _lineLeftOffset = pages * w + _leftMargin; } print( 'left:${_lineLeftOffset.toInt()} width:${_width.toInt()} offset:${widget.offset.toInt()}'); _isFirstBuild = false; return Stack( children: <Widget>[ Positioned( left: 0, top: 0, right: 0, height: widget.tabHeight, child: CupertinoScrollbar( child: CustomScrollView( scrollDirection: Axis.horizontal, slivers: list, ), ), ), Positioned( left: _lineLeftOffset, width: _width, height: widget.lineHeight, top: widget.tabHeight - widget.lineHeight, child: Container( height: widget.lineHeight, width: _width, color: widget.lineColor, ), ) ], ); } @override void initState() { _isFirstBuild = true; super.initState(); } } <|start_filename|>lib/layout/base_align.dart<|end_filename|> import 'package:flutter/material.dart'; class BaseAlign extends StatefulWidget { BaseAlign({Key key}) : super(key: key); @override _BaseAlignState createState() => _BaseAlignState(); } class _BaseAlignState extends State<BaseAlign> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('相对位置'), ), body: _body(), ); } Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( width: 200, height: 200, color: Colors.blue[50], child: Align( child: FlutterLogo( size: 30, )), ), DecoratedBox( decoration: BoxDecoration(color: Colors.blue), child: Center( child: Text('center2'), ), ), SizedBox( height: 20, ), DecoratedBox( decoration: BoxDecoration(color: Colors.blue), child: Center( widthFactor: 1, heightFactor: 1, child: Text('center2'), ), ) ], ), ); } } <|start_filename|>lib/file_and_http/http_dio.dart<|end_filename|> import 'dart:convert'; import 'package:dio/adapter.dart'; import 'package:dio/dio.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:convert' as convert; import 'package:flutter_easyhub/flutter_easy_hub.dart'; import 'package:fluttertest01/file_and_http/model/git_model.dart'; import 'package:fluttertest01/generated/json/base/json_convert_content.dart'; /// /// Created by fgyong on 2020/7/27. /// class BaseHttpDioRoute extends StatefulWidget { BaseHttpDioRoute({Key key}) : super(key: key); @override _BaseHttpDioRouteState createState() => _BaseHttpDioRouteState(); } class _BaseHttpDioRouteState extends State<BaseHttpDioRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Dio'), ), body: _body(), ); } Dio _dio = new Dio(); String _string; Widget _body() { return Center( child: FlutterEasyHub( child: SingleChildScrollView( child: Row( children: <Widget>[ Expanded( child: Text(_string ?? ''), ) ], ), ), ), ); } @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { _getData(); }); } void _getData() async { EasyHub.showHub(); (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) { // config the http client client.findProxy = (uri) { return "PROXY localhost:1088"; }; // you can also create a HttpClient to dio // return HttpClient(); }; Response res = await _dio.get('https://api.github.com/users/ifgyong/repos'); List<dynamic> list = res.data; List<GitModel> gitList = []; if (res.data is List) { (res.data as List).forEach((element) { GitModel modl = JsonConvert.fromJsonAsT<GitModel>(element); gitList.add(modl); }); print('${gitList.length}'); } // Map<String, dynamic> mapret = convert.jsonDecode(res.data); setState(() { _string = res.data.toString(); }); EasyHub.dismiss(); print('res.data${list.toString()}'); } } <|start_filename|>lib/tips/provider/base_provider_pan_zan.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; /// /// Created by fgyong on 2020/8/21. /// class BasePinZanProviderRoute extends StatelessWidget { static String get routeName => '/BasePinZanProviderRoute'; static MaterialPageRoute get route => MaterialPageRoute(builder: (_) => BasePinZanProviderRoute()); @override Widget build(BuildContext context) { return ChangeNotifierProvider<_RedNumberModel>( create: (_) => _RedNumberModel(count: 0, number: 0), builder: (context, child) { return BasePinZanProvider(); }, child: BasePinZanProvider(), ); } } class BasePinZanProvider extends StatefulWidget { BasePinZanProvider({Key key}) : super(key: key); @override _BasePinZanProviderState createState() => _BasePinZanProviderState(); } class _BasePinZanProviderState extends State<BasePinZanProvider> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('点赞Provider'), ), body: _body(), ); } Widget _body() { print('page'); return CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter( child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: Text('1公众号『fgyong的开发日记』公众号『fgyong的开发日记』公众号『fgyong的开发日记』' '公众号『fgyong的开发日记』公众号『fgyong的开发日记』1'), ) ], ), Text('\n\n\n当小余0 则返回上一页,大于5push下一页'), Selector<_RedNumberModel, int>( builder: (ctx, value, child) { print('number'); return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('$value'), IconButton( icon: Icon(Icons.expand_less), onPressed: () { context.read<_RedNumberModel>().add(1); }, ), IconButton( icon: Icon(Icons.expand_more), onPressed: () { context.read<_RedNumberModel>().add(-1); }, ) ], ); }, selector: (BuildContext contex, _RedNumberModel model) { return model.number; }, ), ], ), ), SliverToBoxAdapter( child: Column( children: <Widget>[ Text('count的值只是展示 不做跳转条件'), Selector<_RedNumberModel, int>( builder: (ctx, value, child) { print('count'); return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('$value'), IconButton( icon: Icon(Icons.expand_less), onPressed: () { context.read<_RedNumberModel>().addCount(1); }, ), IconButton( icon: Icon(Icons.expand_more), onPressed: () { context.read<_RedNumberModel>().addCount(-1); }, ) ], ); }, selector: (BuildContext contex, _RedNumberModel model) { return model.count; }, ), ], ), ) ], ); } @override void initState() { context.read<_RedNumberModel>().addListener(listener); super.initState(); } void listener() { final value = context.read<_RedNumberModel>(); if (value.number > 5) { Navigator.of(context).push(BasePinZanProviderRoute.route); } else if (value.number < 0) { Navigator.of(context).maybePop(); } } } class _RedNumberModel extends ChangeNotifier { int number; int count; _RedNumberModel({this.number, this.count}); @override bool operator ==(Object other) => identical(this, other) || other is _RedNumberModel && runtimeType == other.runtimeType && count == other.count; @override int get hashCode => count.hashCode; void add(int value) { number += value; notifyListeners(); } void addCount(int value) { count += value; notifyListeners(); } } <|start_filename|>lib/tips/Tabbar.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; typedef TabbarCallback = void Function(int index); // ignore: must_be_immutable class TabbarViewTWO extends StatefulWidget { TabbarCallback callback; int leftNumber; int rightNumber; String leftTitle; String rightTitle; Widget child; /// 高亮的索引 final int hightIndex; TabbarViewTWO( {Key key, this.callback, @required this.leftTitle, @required this.rightNumber, @required this.rightTitle, @required this.leftNumber, this.child, this.hightIndex}) : super(key: key); _TabbarViewState createState() => _TabbarViewState(); } class _TabbarViewState extends State<TabbarViewTWO> { @override Widget build(BuildContext context) { return _topTab(); } double _redLineLeft = 0; Widget _topTab() { _redLineLeft = MediaQuery.of(context).size.width / 2 * (widget.hightIndex ?? 0); GestureDetector c1 = GestureDetector( onTap: () { widget.callback(0); }, child: Container( width: MediaQuery.of(context).size.width / 2, alignment: Alignment.center, color: Colors.white, child: Text(widget.leftTitle, style: TextStyle( color: _redLineLeft == 0 ? Theme.of(context).focusColor : Colors.black26)), )); GestureDetector c2 = GestureDetector( onTap: () { // setState(() { // _redLineLeft = MediaQuery.of(context).size.width / 2; // }); widget.callback(1); }, child: Container( color: Colors.white, width: MediaQuery.of(context).size.width / 2, alignment: Alignment.center, child: Text( widget.rightTitle, style: TextStyle( color: _redLineLeft != 0 ? Theme.of(context).focusColor : Colors.black26), ), )); Widget red1 = ClipRRect( borderRadius: BorderRadius.all(Radius.circular(7.5)), child: Container( color: Theme.of(context).focusColor, alignment: Alignment.center, padding: EdgeInsets.only(left: 2, right: 2), child: Text( widget.rightNumber.toString(), style: TextStyle(fontSize: 10, color: Colors.white), ), ), ); // 红色的线 Positioned pLine = Positioned( bottom: 0, left: _redLineLeft, child: Container( margin: EdgeInsets.only(top: 3), width: MediaQuery.of(context).size.width / 2, height: 1, color: Theme.of(context).focusColor, )); // 红色的数字 Positioned p1_red = Positioned( child: Row( children: <Widget>[ Expanded( flex: 1, child: Center( child: Container( height: widget.leftNumber == 0 ? 0 : 15, margin: EdgeInsets.only(left: 40), constraints: BoxConstraints(minWidth: 10, maxWidth: 20), child: red1, ), ), ), Expanded( flex: 1, child: Center( child: Container( height: widget.rightNumber == 0 ? 0 : 15, margin: EdgeInsets.only(left: 60), constraints: BoxConstraints(minWidth: 10, maxWidth: 20), child: red1, ), ), ) ], ), left: 0, right: 0, top: 10, ); List<Positioned> list = [ //文字 Positioned( left: 0, right: 0, height: 40, top: 10, child: Container( alignment: Alignment.center, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[c1, c2], ), ), ), //红色的线 p1_red, pLine, ]; if (widget.child != null) { list.add(Positioned.fill( child: widget.child, top: 60, )); } Stack stack = Stack( children: list, ); return stack; } } <|start_filename|>lib/tips/asyn_and_isolate.dart<|end_filename|> import 'dart:isolate'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:async'; /// /// Created by fgyong on 2020/7/29. /// class BaseAsynAndISOlateRoute extends StatefulWidget { BaseAsynAndISOlateRoute({Key key}) : super(key: key); @override _BaseAsynAndISOlateRouteState createState() => _BaseAsynAndISOlateRouteState(); } class _BaseAsynAndISOlateRouteState extends State<BaseAsynAndISOlateRoute> { int _fps = 0; String _stringFPS = ''; @override void initState() { WidgetsBinding.instance.addTimingsCallback((timings) { _fps += 1; }); Timer(Duration(seconds: 1), () { _stringFPS = _fps.toString(); setState(() {}); _fps = 0; }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('线程'), ), body: _body(), ); } int _count = 0; String _string = ''; Widget _body() { return Center( child: CupertinoScrollbar( child: SingleChildScrollView( child: Column( children: <Widget>[ Text('FPS:$_stringFPS'), OutlineButton( child: Text('开辟线程'), onPressed: _createIso, ), OutlineButton( child: Text('主线程发送消息到子线程'), onPressed: _mainToSub, ), OutlineButton( child: Text('子线程发送消息到主线程'), onPressed: _subToMain, ), OutlineButton( child: Text('测试是否堵塞'), onPressed: () { setState(() { _count += 1; }); }, ), Text(_count.toString()), OutlineButton( child: Text('测试是否添加耗时任务是否堵塞'), onPressed: () { Timer.run(() { setState(() { _string = '耗时任务开始'; }); for (var i = 0; i < 9999999999; ++i) { // } setState(() { _string = '耗时任务结束'; }); }); }, ), Text(_string) ], ), ), ), ); } void _createIso() { createTask(); } void createTask() async { _mainReceiverPort = ReceivePort(); isolate = await Isolate.spawn(_sendSub, _mainReceiverPort.sendPort); _mainReceiverPort.listen((data) { print('main: $data ${DateTime.now()}'); if (data is List) { String msg = data[0]; if (msg == 'close') { _mainReceiverPort.close(); } } else if (data is SendPort) { _subSendPort = data; _subSendPort.send('主线程收到了端口from main '); print('main: 主线程收到了子线程的 端口'); } }); print('main:创建线程成功'); } void _mainToSub() { print('指令发出时间:${DateTime.now()}'); _subSendPort?.send(['主线程发出,送往子线程', 'read']); } void _subToMain() { _mainReceiverPort.sendPort.send(['task']); } } /// 新线程执行新的任务 并监听 Isolate isolate; Isolate isolate2; ReceivePort _subReceiverPort; ReceivePort _mainReceiverPort; SendPort _subSendPort; void _sendSub(SendPort sendPort) async { _subReceiverPort = new ReceivePort(); sendPort.send(_subReceiverPort.sendPort); _subReceiverPort.listen((data) async { print('sub:$data)'); if (data is List) { String msg = data[0]; if (data.contains('read') == true) { print('开始读文件时间:${DateTime.now()}'); for (var i = 0; i < 999999999; ++i) {} print('读文件完成时间:${DateTime.now()}'); sendPort.send(['子线程文件读写完成']); } else if (msg == 'close') { _subReceiverPort.close(); } else if (msg == 'callback') { sendPort.send(['子线程收到了消息']); } } }); } <|start_filename|>lib/tips/get/get_list_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class GetListController extends GetxController { var data = List<String>().obs; var count = 0.obs; var isLoadingMore = false.obs; void fetch() async { isLoadingMore.value = true; // Get.dialog(SizedBox(height: 50, child: Center(child: CircularProgressIndicator()))); Future.delayed(Duration(seconds: 1)).then((value) { data.add('老李来了${data.length}'); isLoadingMore.value = false; // Get.back(); }); // var l = data.length; // if (data.canUpdate) { // data.add('老李来了$l'); // } else { // printInfo(info: '更新数据失败'); // } } @override void onInit() { printInfo(info: 'getlistinit'); super.onInit(); } @override void onClose() { printInfo(info: 'getlist onClose'); super.onClose(); } void clearData() => data.clear(); void add() { count += 1; } } class GetListPageRoute extends StatefulWidget { static final String routeName = "getListPage"; @override State<StatefulWidget> createState() { return GetListPageRouteState(); } } class GetListPageRouteState extends State<GetListPageRoute> { final GetListController c = Get.put(GetListController()); @override Widget build(BuildContext context) { printInfo(info: 'build'); return Scaffold( appBar: AppBar( title: Text('get list page '), ), body: Stack( children: [ Positioned.fill( child: ObxValue((data) { return _center(); }, c.data), top: 70, ), Positioned( left: 0, right: 0, top: 0, height: 70, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ OutlineButton( onPressed: () { c.fetch(); }, child: Text('下载数据'), ), OutlineButton( onPressed: () { c.clearData(); }, child: Text('清空数据'), ), OutlineButton( onPressed: () { c.add(); }, child: ObxValue((v) { printInfo(info: '刷新了页面 $v'); return Text(' 正在加载:${v.value}'); }, c.isLoadingMore), ), SizedBox( width: 60, child: Obx(() { printInfo(info: '数组长度刷新'); return Text('${c.data.length}'); }), ) ], ), ), ], ), ); } Widget _cellBuild(BuildContext context, int index) { if (c.data.length == index) { printInfo(info: 'cellbuild 动画: c.loading ${c.isLoadingMore}'); return SizedBox( height: 50, child: Center( child: ObxValue((value) { return value.value ? CircularProgressIndicator() : OutlineButton( child: Text('点击加载更多'), onPressed: () { c.fetch(); }, ); }, c.isLoadingMore), ), ); } return ListTile( title: Text(c.data[index]), ); } Widget _center() => Center( child: ListView.builder( itemBuilder: _cellBuild, itemCount: c.data.length + 1, ), ); @override void dispose() { /// 从当前和页面删除 数据 /// 下次进来 需要重新请求数据 Get.delete<GetListController>(); super.dispose(); } @override void initState() { printInfo(info: 'get_list_page_state initState'); super.initState(); } } <|start_filename|>lib/scrollview/swich_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/util.dart'; /// /// Created by fgyong on 7/19/21. /// class BaseSwitchListTitlePage extends StatefulWidget { const BaseSwitchListTitlePage({Key key}) : super(key: key); @override _BaseSwitchListTitlePageState createState() => _BaseSwitchListTitlePageState(); static String get routeName => '/BaseSwitchListTitlePage'; } T tryCatch<T>({ T Function() bodyFunc, T Function() errorSummaryFunc, T Function() noSuchMethodFunc, T Function() rangeErrorFunc, T Function() outOfMemoryErrorFunc, T Function() typeErrorFunc, T Function() stateErrorFunc, T Function() otherFunc, void Function() finallyFunc, }) { try { if (bodyFunc != null) return bodyFunc(); } on ErrorSummary catch (e) { Util.v('$e', tag: 'ErrorSummary'); if (errorSummaryFunc != null) return errorSummaryFunc(); } on NoSuchMethodError catch (e) { Util.v('$e', tag: 'NoSuchMethodError'); if (noSuchMethodFunc != null) return noSuchMethodFunc(); } on RangeError catch (e) { Util.v('$e', tag: 'RangeError'); if (rangeErrorFunc != null) return rangeErrorFunc(); } on OutOfMemoryError catch (e) { Util.v('$e', tag: 'OutOfMemoryError'); if (outOfMemoryErrorFunc != null) return outOfMemoryErrorFunc(); } on TypeError catch (e) { Util.v('$e', tag: 'TypeError'); if (typeErrorFunc != null) return typeErrorFunc(); } on StateError catch (e) { Util.v('$e', tag: 'StateError'); if (stateErrorFunc != null) return stateErrorFunc(); } catch (e) { Util.v('$e', tag: 'Error:${e.runtimeType}'); if (otherFunc != null) return otherFunc(); } finally { Util.v('finally'); if (finallyFunc != null) finallyFunc(); } } class _BaseSwitchListTitlePageState extends State<BaseSwitchListTitlePage> { bool _isOpen = true; bool _isOpen2 = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('切换开关'), ), body: Container( child: Column( children: [ SwitchListTile( value: _isOpen, onChanged: (s) { setState(() { _isOpen = s; tryCatch<void>( bodyFunc: () {}, noSuchMethodFunc: () { Util.v('noSuchMethodFunc'); }, ); }); }, title: Text('开关上边'), subtitle: Text('二级开关下边'), secondary: Icon(Icons.forward), ), SwitchListTile( value: _isOpen2, onChanged: (s) { tryCatch(bodyFunc: () { setState(() { _isOpen2 = s; }); }); }, title: Text('开关'), subtitle: Text('二级开关'), secondary: Icon(Icons.add), ), ], ), ), ); } } <|start_filename|>lib/tips/get/get_login_page.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get/get.dart'; class GetLoginPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _GetLoginPageState(); } static String get routeName => "GetLoginPage"; } /// 登陆根据编辑的手机号和密码动态刷新按钮状态 /// 点击 展示动画 /// 结束弹窗 class _GetLoginPageState extends State<GetLoginPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('登录'), ), body: Center( child: GetBuilder<GetLoginController>( builder: (v) { return _body(); }, init: c, ), ), ); } final c = Get.put(GetLoginController()); Widget _body() { return Container( child: Column( children: [ SizedBox( height: 100, ), Padding( child: TextField( controller: c.editMobile, onChanged: (v) { c.changePwd(); }, decoration: InputDecoration(hintText: '账号', labelText: '账号'), ), padding: EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10), ), Padding( child: TextField( controller: c.editPwd, onChanged: (v) { c.changePwd(); }, decoration: InputDecoration(hintText: '密码', hintMaxLines: 1, labelText: '密码'), ), padding: EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10), ), SizedBox( height: 40, ), SizedBox( height: 30, child: Container( child: ObxValue( (v) => OutlineButton( child: ObxValue( (v2) => v2.value == true ? SizedBox( height: 20, width: 20, child: CircularProgressIndicator(), ) : Text( '登陆', style: TextStyle( color: v.value == true ? Colors.black : Colors.grey), ), c.commit), onPressed: v.value == true ? () { c.login(); } : null, ), c.canLogin.obs), ), ) ], ), margin: EdgeInsets.only(left: 20, right: 20), ); } @override void initState() { c.msg.listen((data) { // Get.snackbar('title', data, snackStyle: SnackStyle.FLOATING); printInfo(info: data); Fluttertoast.showToast( msg: data, toastLength: Toast.LENGTH_SHORT, ); }); printInfo(info: '_GetLoginPageState initState'); super.initState(); } @override void dispose() { Get.delete<GetLoginController>(); super.dispose(); } } class GetLoginBind extends Bindings { @override void dependencies() { Get.lazyPut(() => GetLoginController()); } } class GetLoginController extends GetxController { var editMobile = TextEditingController(); var editPwd = TextEditingController(); var msg = "".obs; var canLogin = false.obs; var commit = false.obs; void changeName() { canLogin.value = canCommit(); } void changePwd() { canLogin.value = canCommit(); // canLogin.subject.add(canCommit()); } bool canCommit() { return editMobile.text.length > 0 && editPwd.text.length > 0; } void login() async { Get.focusScope.unfocus(); commit.value = true; await Future.delayed(Duration(seconds: 1)); if (editPwd.value.text == "<PASSWORD>" && editMobile.text.trim() == '110') { msg.subject.add('登陆成功'); } else { msg.subject.add('账号或者密码错误'); } commit.value = false; } } <|start_filename|>lib/comment/config.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class ThemeYo { static TextStyle get textStyle { return TextStyle(color: Colors.black, fontSize: 25); } static TextStyle get subTileTextStyle { return TextStyle(color: Colors.black54, fontSize: 15); } static TextStyle get itemTextStyle { return TextStyle(color: Colors.black45, fontSize: 15); } } <|start_filename|>lib/tips/bloc/login_bloc/bloc/login_event.dart<|end_filename|> part of '../bloc/login_bloc.dart'; /// /// Created by fgyong on 2020/8/20. /// /// 登陆相关的事件 abstract class LoginEvent extends Equatable { const LoginEvent(); @override List<Object> get props => []; } /// 修改密码 class LoginChagnePassword extends LoginEvent { final String password; const LoginChagnePassword({this.password}); @override List<Object> get props => [password]; } /// 修改账户 class LoginChagneName extends LoginEvent { final String name; const LoginChagneName({this.name}); @override List<Object> get props => [name]; } /// 提交事件 class LoginSubmitted extends LoginEvent { const LoginSubmitted(); @override List<Object> get props => []; } <|start_filename|>lib/baseWidget/baseState.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class TapBox extends StatefulWidget { TapBoxState createState() => TapBoxState(); } class TapBoxState extends State<TapBox> { bool _selected = false, _selected2 = false, _selected3 = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('管理状态'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( height: 30, child: Text('自己管理状态'), ), Container( color: _selected ? Colors.red : Colors.black12, child: TapBox1(), ), SizedBox( height: 30, child: Text('父组件管理状态'), ), Container( color: _selected2 ? Colors.red : Colors.black12, child: TapBox2( onchange: (v) { setState(() { _selected2 = v; }); }, selected: _selected2, ), ), SizedBox( height: 30, child: Text('混合管理状态'), ), Container( color: _selected3 ? Colors.red : Colors.black12, child: TapBox3( onchange: (v) { setState(() { _selected3 = v; }); }, selected: _selected3, ), ) ], ), ), ); } void _tap() { setState(() { _selected = !_selected; }); } } class TapBox1 extends StatefulWidget { TapBox1({Key key}) : super(key: key); TapBoxState1 createState() => TapBoxState1(); } typedef onChange = Function(bool); class TapBoxState1 extends State<TapBox1> { bool _selected; @override void initState() { _selected = false; super.initState(); } @override Widget build(BuildContext context) { return Container( color: _selected == true ? Colors.red : Colors.black12, child: FlatButton( child: Text(_selected == true ? 'Active' : 'Inactive'), onPressed: _tap, ), ); } void _tap() { setState(() { _selected = !_selected; }); } } class TapBox2 extends StatefulWidget { final bool selected; final onChange onchange; TapBox2({Key key, this.selected, this.onchange}) : super(key: key); TapBoxState2 createState() => TapBoxState2(); } class TapBoxState2 extends State<TapBox2> { bool _selected; @override void initState() { _selected = widget.selected == true; super.initState(); } @override Widget build(BuildContext context) { return Container( color: widget.selected == true ? Colors.red : Colors.black12, child: FlatButton( child: Text(widget.selected == true ? 'Active' : 'Inactive'), onPressed: _tap, ), ); } void _tap() { if (widget.onchange != null) { _selected = !_selected; widget.onchange(_selected); } } } class TapBox3 extends StatefulWidget { final bool selected; final onChange onchange; TapBox3({Key key, this.selected, this.onchange}) : super(key: key); TapBoxState3 createState() => TapBoxState3(); } class TapBoxState3 extends State<TapBox3> { bool _touching = false; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Container( child: GestureDetector( child: Container( height: 50, width: 120, alignment: Alignment.center, child: Text(widget.selected == true ? 'Active' : 'Inactive'), decoration: new BoxDecoration( color: widget.selected == true ? Colors.red : Colors.black12, border: _touching ? Border.all( color: widget.selected == false ? Colors.red : Colors.blue, width: 4) : null), ), onTap: _tap, onTapDown: (TapDownDetails details) { _touchStart(); }, onTapUp: (detail) { _touchend(); }, ), ); } void _tap() { if (widget.onchange != null) { widget.onchange(!widget.selected); } } void _touchStart() { setState(() { _touching = true; }); } void _touchend() { setState(() { _touching = false; }); } } <|start_filename|>lib/tips/bloc/login_bloc/model/login2_model.dart<|end_filename|> import 'package:equatable/equatable.dart'; /// /// Created by fgyong on 2020/8/19. /// abstract class UserAction { final String value; const UserAction(this.value); bool get visiable; } class UserName extends UserAction { UserName(String value) : super(value); /// 这里可以写校验规则 @override bool get visiable { /// 名字长度大于3 符合要求 return (value?.isNotEmpty ?? false) ? value.length > 3 : false; } } class UserPassword extends UserAction { UserPassword(String value) : super(value); /// 这里可以写校验规则 @override bool get visiable { /// 密码长度大于3 符合要求 return (value?.isNotEmpty ?? false) ? value.length > 1 : false; } } <|start_filename|>lib/baseWidget/baseTextField.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseField extends StatefulWidget { _BaseFieldState createState() => _BaseFieldState(); } class _BaseFieldState extends State<BaseField> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('输入框和表单'), ), body: _body(), ); } Widget _body() { return Column( children: <Widget>[ Text('TextField'), _field, Text(_editingController.value.text), SizedBox( height: 30, ), Text('CupertinoTextField'), _cupertinoTextField, SizedBox( height: 30, ), Text('Form 校验结果:${_done.toString()}'), _form, ], ); } TextField _field; FocusNode _focusNode; FocusNode _focusNode2; CupertinoTextField _cupertinoTextField; TextEditingController _editingController; TextEditingController _editingController2; TextEditingController _editingController3; Form _form; GlobalKey<FormState> _globalKey = new GlobalKey(); bool _done = false; @override void initState() { _focusNode = new FocusNode(); _editingController = new TextEditingController() ..addListener(() { print("${_editingController.value.text}"); }); _field = TextField( focusNode: _focusNode, onChanged: (v) { setState(() {}); }, onSubmitted: (v) { _focusNode.unfocus(); }, controller: _editingController, obscureText: false, //是否是密码 decoration: InputDecoration(hintText: '手机号', labelText: '手机号'), keyboardType: TextInputType.number, ); _editingController2 = new TextEditingController(); _focusNode2 = new FocusNode(); _cupertinoTextField = CupertinoTextField( focusNode: _focusNode2, controller: _editingController2, placeholder: '密码', prefix: Icon(Icons.lock), textInputAction: TextInputAction.go, obscureText: true, ); _editingController3 = new TextEditingController(); _form = Form( key: _globalKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TextFormField( decoration: const InputDecoration( hintText: 'Enter your email', icon: Icon(Icons.mail)), validator: (value) { if (value.isEmpty) { return 'Please enter some text'; } return null; }, ), TextFormField( controller: _editingController3, decoration: InputDecoration( labelText: "密码", hintText: "您的登录密码", icon: Icon(Icons.lock)), obscureText: true, //校验密码 validator: (v) { return v.trim().length > 5 ? null : "密码不能少于6位"; }), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: RaisedButton( onPressed: () { // Validate will return true if the form is valid, or false if // the form is invalid. if (_globalKey.currentState.validate()) { // Process data. print('校验通过'); } setState(() { _done = _globalKey.currentState.validate(); }); }, child: Text('Submit'), ), ), ], ), ); super.initState(); } void _unFocus() { _focusNode.focusInDirection(TraversalDirection.down); } } <|start_filename|>lib/layout/baseFlex.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseFlex extends StatefulWidget { /// FractionallySizedBox 按照父容器的大小的 比例展示子组件 /// BaseFlexState createState() => BaseFlexState(); } class BaseFlexState extends State<BaseFlex> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('弹性布局'), ), body: SingleChildScrollView( child: Column( children: <Widget>[ Text('MainAxisAlignment.start'), _bd(MainAxisAlignment.start, CrossAxisAlignment.start), Text('MainAxisAlignment.center'), _bd(MainAxisAlignment.center, CrossAxisAlignment.start), Text('MainAxisAlignment.end'), _bd(MainAxisAlignment.end, CrossAxisAlignment.start), Text('MainAxisAlignment.spaceAround'), _bd(MainAxisAlignment.spaceAround, CrossAxisAlignment.start), Text('MainAxisAlignment.spaceEvenly'), _bd(MainAxisAlignment.spaceEvenly, CrossAxisAlignment.start), Text('MainAxisAlignment.spaceBetween'), _bd(MainAxisAlignment.spaceBetween, CrossAxisAlignment.start), _bd2(), _bd3(), Row( children: <Widget>[ SizedBox( width: 20, ), Expanded( child: OutlineButton( child: Text('Expanded btn'), ), ), SizedBox( width: 20, ), ], ), OutlineButton( onPressed: () {}, child: Text('btn'), ), ], ), ), ); } Widget _body() { return Container( child: FractionallySizedBox( widthFactor: 0.5, heightFactor: 0.5, child: Container( color: Colors.deepOrangeAccent, child: FractionallySizedBox( widthFactor: 0.5, heightFactor: 0.5, child: Container( color: Colors.orange, ), ), ), ), ); } Widget _bd(MainAxisAlignment mainAxisAlignment, CrossAxisAlignment cl) { return Container( margin: EdgeInsets.symmetric(vertical: 20), child: Flex( mainAxisAlignment: mainAxisAlignment, crossAxisAlignment: cl, textDirection: TextDirection.ltr, direction: Axis.horizontal, children: <Widget>[ Container( height: 30, width: 100, child: Text('1'), alignment: Alignment.center, color: Colors.red, ), Container( alignment: Alignment.center, height: 30, width: 100, child: Text('2'), color: Colors.red, ), Container( alignment: Alignment.center, child: Text('3'), height: 30, width: 100, color: Colors.red, ), ], ), ); } Widget _bd2() { return Container( height: 30, child: Row(children: <Widget>[ Expanded( flex: 1, child: Container( color: Colors.red, ), ), Expanded( flex: 2, child: Container( color: Colors.orange, ), ), Expanded( flex: 3, child: Container( color: Colors.blue, ), ) ])); } Widget _bd3() { return Container( height: 30, margin: EdgeInsets.symmetric(vertical: 20), child: Row(children: <Widget>[ Container( width: 50, color: Colors.red, ), Spacer( flex: 1, ), Container( width: 50, color: Colors.red, ), Spacer( flex: 2, ), Container( width: 50, color: Colors.red, ), ])); } Widget _bd4() { return Container( child: Row( children: <Widget>[ Expanded( child: OutlineButton( child: Text('btn'), ), ), ], ), ); } } <|start_filename|>lib/layout/base_stack.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class BaseStack extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('相对位置'), ), body: Center( child: Column( children: <Widget>[ Container( margin: EdgeInsets.only(top: 20), child: _body(), constraints: BoxConstraints.loose(Size(100, 100)), ), Container( margin: EdgeInsets.only(top: 20), child: _body2(), color: Colors.black12, constraints: BoxConstraints.expand(width: 200, height: 200), ), Container( margin: EdgeInsets.only(top: 20), child: _body3(), color: Colors.black12, constraints: BoxConstraints.expand(width: 200, height: 200), ) ], ), ), ); } Widget _body() { return Stack( fit: StackFit.loose, alignment: Alignment.bottomRight, children: <Widget>[ Positioned.fill( child: Container( color: Colors.red, )), Positioned.fill( left: 20, right: 20, bottom: 20, top: 20, child: Container( color: Colors.deepOrangeAccent, )), Positioned.fill( left: 40, right: 40, bottom: 40, top: 40, child: Container( color: Colors.orange, )), ], ); } Widget _body2() { return Stack( fit: StackFit.expand, alignment: Alignment.center, children: <Widget>[ Container( child: Text("Hello world", style: TextStyle(color: Colors.white)), color: Colors.red, ), Positioned( top: 20.0, child: Container( child: Text("Are you OK?"), color: Colors.blue, ), ), Positioned( left: 18.0, child: Container( child: Text("I am Jack"), color: Colors.blue, )), ], ); } Widget _body3() { return Stack( fit: StackFit.loose, alignment: Alignment.bottomRight, children: <Widget>[ Positioned( left: 0, right: 0, height: 50, child: Container( color: Colors.red, alignment: Alignment.center, child: Text('Are you OK?'), ), ), Positioned( right: 0, height: 50, width: 50, top: 0, child: Container( color: Colors.red, alignment: Alignment.center, child: Text('I ma Jack!'), ), ), Positioned( height: 40, width: 60, child: Container( color: Colors.blue, alignment: Alignment.center, child: Text('hello'), ), ), ], ); } } <|start_filename|>lib/tips/bloc/login_bloc/bloc/login_state.dart<|end_filename|> part of 'login_bloc.dart'; /// /// Created by fgyong on 2020/8/19. /// /// 事件变更状态[正在请求,报错,登陆成功,初始化] enum Login2Progress { isRequesting, error, success, init } /// 存储数据的model 在[bloc]中称作[state] class LoginState2 extends Equatable { final String name; final String password; final Login2Progress progress; LoginState2({this.name, this.password, this.progress = Login2Progress.init}); @override List<Object> get props => [name, password, btnVisiable, progress]; LoginState2 copyWith( {String name, String pwd, Login2Progress login2progress}) { return LoginState2( name: name ?? this.name, password: <PASSWORD> ?? <PASSWORD>, progress: login2progress ?? this.progress); } /// 使用 [UserName] &&[UserPassword]来校验规则 bool get btnVisiable => nameVisiable && passwordVisiable; bool get nameVisiable => UserName(name).visiable; bool get passwordVisiable => UserPassword(password).visiable; /// 是否展示名字错误信息 bool get showNameErrorText { if (name?.isEmpty ?? true) return false; return nameVisiable == false; } /// 是否展示密码错误信息 bool get showPasswordErrorText { if (password?.isEmpty ?? true) return false; return passwordVisiable == false; } @override String toString() { return '$props'; } } <|start_filename|>lib/secondPage.dart<|end_filename|> import 'dart:developer'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:fluttertest01/counter.dart'; class SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('second'), ), body: Hero( tag: 'null', child: Container( height: 100, color: Colors.lightBlueAccent, width: 200, child: FlatButton( onPressed: () { context.read<Counter>().changeValue(2); // Navigator.of(context) // .push(MaterialPageRoute(builder: (ctx) => SecondPage())); }, child: Text('2')), ), ), // floatingActionButton: FloatingActionButton( // onPressed: () { // Navigator.of(context).pop(); // }, // tooltip: 'Increment', // child: Icon(Icons.add), // ), // This trailing comma makes auto-formatting nicer for build methods. ); } } <|start_filename|>lib/file_and_http/model/git_model.dart<|end_filename|> import 'package:fluttertest01/generated/json/base/json_convert_content.dart'; import 'package:fluttertest01/generated/json/base/json_filed.dart'; class GitModel with JsonConvert<GitModel> { double id; @JSONField(name: "node_id") String nodeId; String name; @JSONField(name: "full_name") String fullName; bool private; GitOwner owner; @JSONField(name: "html_url") String htmlUrl; String description; bool fork; String url; @JSONField(name: "forks_url") String forksUrl; @JSONField(name: "keys_url") String keysUrl; @JSONField(name: "collaborators_url") String collaboratorsUrl; @JSONField(name: "teams_url") String teamsUrl; @JSONField(name: "hooks_url") String hooksUrl; @JSONField(name: "issue_events_url") String issueEventsUrl; @JSONField(name: "events_url") String eventsUrl; @JSONField(name: "assignees_url") String assigneesUrl; @JSONField(name: "branches_url") String branchesUrl; @JSONField(name: "tags_url") String tagsUrl; @JSONField(name: "blobs_url") String blobsUrl; @JSONField(name: "git_tags_url") String gitTagsUrl; @JSONField(name: "git_refs_url") String gitRefsUrl; @JSONField(name: "trees_url") String treesUrl; @JSONField(name: "statuses_url") String statusesUrl; @JSONField(name: "languages_url") String languagesUrl; @JSONField(name: "stargazers_url") String stargazersUrl; @JSONField(name: "contributors_url") String contributorsUrl; @JSONField(name: "subscribers_url") String subscribersUrl; @JSONField(name: "subscription_url") String subscriptionUrl; @JSONField(name: "commits_url") String commitsUrl; @JSONField(name: "git_commits_url") String gitCommitsUrl; @JSONField(name: "comments_url") String commentsUrl; @JSONField(name: "issue_comment_url") String issueCommentUrl; @JSONField(name: "contents_url") String contentsUrl; @JSONField(name: "compare_url") String compareUrl; @JSONField(name: "merges_url") String mergesUrl; @JSONField(name: "archive_url") String archiveUrl; @JSONField(name: "downloads_url") String downloadsUrl; @JSONField(name: "issues_url") String issuesUrl; @JSONField(name: "pulls_url") String pullsUrl; @JSONField(name: "milestones_url") String milestonesUrl; @JSONField(name: "notifications_url") String notificationsUrl; @JSONField(name: "labels_url") String labelsUrl; @JSONField(name: "releases_url") String releasesUrl; @JSONField(name: "deployments_url") String deploymentsUrl; @JSONField(name: "created_at") String createdAt; @JSONField(name: "updated_at") String updatedAt; @JSONField(name: "pushed_at") String pushedAt; @JSONField(name: "git_url") String gitUrl; @JSONField(name: "ssh_url") String sshUrl; @JSONField(name: "clone_url") String cloneUrl; @JSONField(name: "svn_url") String svnUrl; String homepage; double size; @JSONField(name: "stargazers_count") double stargazersCount; @JSONField(name: "watchers_count") double watchersCount; String language; @JSONField(name: "has_issues") bool hasIssues; @JSONField(name: "has_projects") bool hasProjects; @JSONField(name: "has_downloads") bool hasDownloads; @JSONField(name: "has_wiki") bool hasWiki; @JSONField(name: "has_pages") bool hasPages; @JSONField(name: "forks_count") double forksCount; @JSONField(name: "mirror_url") dynamic mirrorUrl; bool archived; bool disabled; @JSONField(name: "open_issues_count") double openIssuesCount; GitLicense license; double forks; @JSONField(name: "open_issues") double openIssues; double watchers; @JSONField(name: "default_branch") String defaultBranch; } class GitOwner with JsonConvert<GitOwner> { String login; double id; @JSONField(name: "node_id") String nodeId; @JSONField(name: "avatar_url") String avatarUrl; @JSONField(name: "gravatar_id") String gravatarId; String url; @JSONField(name: "html_url") String htmlUrl; @JSONField(name: "followers_url") String followersUrl; @JSONField(name: "following_url") String followingUrl; @JSONField(name: "gists_url") String gistsUrl; @JSONField(name: "starred_url") String starredUrl; @JSONField(name: "subscriptions_url") String subscriptionsUrl; @JSONField(name: "organizations_url") String organizationsUrl; @JSONField(name: "repos_url") String reposUrl; @JSONField(name: "events_url") String eventsUrl; @JSONField(name: "received_events_url") String receivedEventsUrl; String type; @JSONField(name: "site_admin") bool siteAdmin; } class GitLicense with JsonConvert<GitLicense> { String key; String name; @JSONField(name: "spdx_id") String spdxId; dynamic url; @JSONField(name: "node_id") String nodeId; } <|start_filename|>lib/file_and_http/model/user.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:json_annotation/json_annotation.dart'; /// /// Created by fgyong on 2020/7/28. /// //@JsonSerializable() //class UserModel { // String name; // String age; // UserModel({this.name, this.age}); // factory UserModel.fromJson(Map<String, dynamic> js) => // _$UserModelFromJson(js); //} // //@JsonSerializable() //class UserList { // List<UserModel> list; // UserList({this.list}); // factory UserList.fromJson(Map<String, dynamic> ll) => _$UserListFromJson(ll); //} class UserModel { List<X> list; UserModel({this.list}); factory UserModel.fromJson(Map<String, dynamic> json) { return UserModel( list: json['list'] != null ? (json['list'] as List).map((i) => X.fromJson(i)).toList() : null, ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.list != null) { data['list'] = this.list.map((v) => v.toJson()).toList(); } return data; } } class X { String name; X({this.name}); factory X.fromJson(Map<String, dynamic> json) { return X( name: json['name'], ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['name'] = this.name; return data; } } <|start_filename|>lib/tips/bloc/login_bloc/login_bloc_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertest01/tips/bloc/login_bloc/bloc/login_bloc.dart'; import 'package:fluttertest01/tips/bloc/login_bloc/view/login2_view.dart'; /// /// Created by fgyong on 2020/8/19. /// /// 使用[bloc]完成的登陆功能 class LoginBlocRoute extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider( child: BaseLogin2Page(), create: (_) => LoginBloc(LoginState2()), ); } } <|start_filename|>lib/animation/base_animaiton.dart<|end_filename|> import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/15. /// class BaseAnimation extends StatefulWidget { @override _BaseAnimationState createState() => _BaseAnimationState(); } class _BaseAnimationState extends State<BaseAnimation> with TickerProviderStateMixin { AnimationController _animationController; Animation _animation; @override void initState() { // /// 在1000毫秒内生成值 // final AnimationController _animationController = AnimationController( // vsync: this, duration: Duration(milliseconds: 1000)); // // /// 生成值是由红色渐变为绿色 // final Animation _animation = // ColorTween(begin: Colors.red, end: Colors.green) // .animate(_animationController); // // /// 生成的曲线规则是正向是 Curves.bounceInOut,逆向是Curves.linear // final Animation curv = CurvedAnimation( // parent: _animation, // curve: Curves.bounceInOut, // reverseCurve: Curves.linear); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(''), ), body: _body(), ); } int count = 0; Widget _body() { count++; return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ScaleANimationRoute( key: ObjectKey(count), ), OutlineButton( child: Text('刷新'), onPressed: () { setState(() {}); }, ) ], ), ); } } /// 自定义了一个曲线 class SinLine extends Curve { @override double transform(double t) { return sin(t * pi / 2); } } class ScaleANimationRoute extends StatefulWidget { ScaleANimationRoute({Key key}) : super(key: key); @override _ScaleANimationRouteState createState() => _ScaleANimationRouteState(); } class _ScaleANimationRouteState extends State<ScaleANimationRoute> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation _animation; @override void initState() { _animationController = AnimationController( duration: Duration(milliseconds: 1000), lowerBound: 0.0, upperBound: 1.0, vsync: this); // ..addStatusListener((status) { // if (status == AnimationStatus.completed) { // /// 如果结束,则反向运动 // _animationController.reverse(); // } else if (status == AnimationStatus.dismissed) { // // 如果反向结束 则正向开始 // _animationController.forward(); // } // }); _animation = CurvedAnimation(parent: _animationController, curve: Curves.bounceOut); _animation = new Tween<Offset>(begin: Offset(0, 0), end: Offset(1.0, 1.0)) .animate(_animation); ///正向启动 _animationController.forward(); super.initState(); } @override Widget build(BuildContext context) { return SlideTransition( position: _animation, child: Container( color: Colors.lightBlueAccent, width: 100, height: 100, ), ); } // @override // Widget build(BuildContext context) { // // return AnimatedLessWidget( // child: Text( // '弹簧动画', // ), // animation: _animation, // ); // } // @override // Widget build(BuildContext context) { // print('刷新一次'); // int count = 0; // return AnimatedBuilder( // child: AnimateWidgetFrame( // animation: _animation, // ), // animation: _animation, // builder: (ctx, child) { // print('动画刷新次数:${count++}'); // return Container( // width: 100 * _animation.value, // height: 100 * _animation.value, // color: Colors.lightBlueAccent, // ); // }, // ); // } @override void dispose() { _animationController.dispose(); super.dispose(); } } class AnimateWidgetFrame extends AnimatedWidget { AnimateWidgetFrame({Key key, Animation<double> animation}) : super(key: key, listenable: animation); @override Widget build(BuildContext context) { final Animation<double> animation = listenable; return Container( width: 100 * animation.value, height: 100 * animation.value, color: Colors.lightBlueAccent, ); } } class AnimatedLessWidget extends StatelessWidget { final Widget child; final Animation<double> animation; AnimatedLessWidget({this.child, this.animation}); @override Widget build(BuildContext context) { return AnimatedBuilder( child: child, animation: animation, builder: (ctx, w) { return Container( width: 100 * animation.value, height: 100 * animation.value, color: Colors.lightBlueAccent, child: w, ); }, ); } } <|start_filename|>lib/layout/base_flow_and_wrap.dart<|end_filename|> import 'package:flutter/material.dart'; class BaseFlowAndWrap extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('流式布局'), ), body: Column( children: <Widget>[ Container( child: _body(), color: Colors.black12, ), Container( margin: EdgeInsets.only(top: 20), child: _bd2(), color: Colors.black12, ) ], ), ); } Widget _body() { return Wrap( runAlignment: WrapAlignment.start, alignment: WrapAlignment.center, spacing: 20.0, runSpacing: 30, direction: Axis.horizontal, children: <Widget>[ _item('Are you ok ?', 'A'), _item('I am ok ', 'B'), _item('马什么?', 'C'), _item('什么梅?', 'D'), _item('马东什么?', 'E'), ], ); } Widget _item(String title, String subavator) { return Chip( avatar: new CircleAvatar( backgroundColor: Colors.blue, child: Text(subavator), ), label: Text(title), ); return OutlineButton.icon( onPressed: null, icon: Icon(Icons.mail), label: Text(title)); } Widget _bd2() { return Flow.unwrapped( delegate: BaseFlowDelegate(margin: EdgeInsets.all(20)), children: _list(), ); } List<Widget> _list() { return <Widget>[ _item('Are you ok ?', 'A'), _item('I am ok ', 'B'), _item('马什么?', 'C'), _item('什么梅?', 'D'), _item('马东什么?', 'E'), ]; } } class BaseFlowDelegate extends FlowDelegate { EdgeInsets margin; BaseFlowDelegate({this.margin = EdgeInsets.zero}); @override void paintChildren(FlowPaintingContext context) { var x = margin.left; var y = margin.top; //计算每一个子widget的位置 for (int i = 0; i < context.childCount; i++) { var w = context.getChildSize(i).width + x + margin.right; if (w <= context.size.width) { context.paintChild(i, transform: new Matrix4.translationValues(x, y, 0.0)); x = w + margin.left; } else { x = margin.left; y += context.getChildSize(i).height + margin.top + margin.bottom; //绘制子widget(有优化) context.paintChild(i, transform: new Matrix4.translationValues(x, y, 0.0)); x += context.getChildSize(i).width + margin.left + margin.right; } } } @override getSize(BoxConstraints constraints) { //指定Flow的大小 return Size(double.infinity, 300); } @override bool shouldRepaint(FlowDelegate oldDelegate) { return oldDelegate != this; } } <|start_filename|>lib/features/base_touch_handle.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/8. /// class BaseTouchHandle extends StatefulWidget { @override _BaseTouchHandleState createState() => _BaseTouchHandleState(); } class _BaseTouchHandleState extends State<BaseTouchHandle> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('原始手势处理'), ), body: _body2(), ); } //定义一个状态,保存当前指针位置 PointerEvent _event; String _eventState = ''; Widget _body() { return Center( child: Listener( child: Center( child: Column( children: <Widget>[ IgnorePointer( child: Listener( child: SizedBox( height: 50, child: Container( color: Colors.red, height: 50, width: 100, child: Text(_eventState), ), ), onPointerDown: (PointerDownEvent ev) { setState(() { _event = ev; _eventState = '子树 -> 手势按下'; }); }, ), ) ], ), ), onPointerUp: (PointerUpEvent ev) { setState(() { _event = ev; _eventState = '抬起手势'; }); }, ), ); } Widget _body2() { return Center( child: Listener( child: Center( child: Container( color: Colors.red, height: 200, width: 100, child: Stack( children: <Widget>[ Listener( child: ConstrainedBox( child: DecoratedBox( decoration: BoxDecoration(color: Colors.blue), child: Text(_eventState), ), constraints: BoxConstraints.tight(Size(100.0, 100.0)), ), onPointerDown: (PointerDownEvent ev) { setState(() { _eventState = '点击 蓝色'; }); }, ), Listener( child: ConstrainedBox( child: DecoratedBox( decoration: BoxDecoration(color: Colors.orange), child: Text(_eventState), ), constraints: BoxConstraints.tight(Size(100.0, 50.0)), ), onPointerDown: (PointerDownEvent ev) { setState(() { _eventState = '点击橘黄色区域'; }); }, ), ], ), ), ), behavior: HitTestBehavior.deferToChild, onPointerUp: (PointerUpEvent ev) { setState(() { _event = ev; _eventState = '抬起手势'; }); }, ), ); } } <|start_filename|>lib/tips/bloc/login_bloc/bloc/login_bloc.dart<|end_filename|> import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:equatable/equatable.dart'; import '../model/login_models.dart'; part 'login_event.dart'; part 'login_state.dart'; /// /// Created by fgyong on 2020/8/19. /// class LoginBloc extends Bloc<LoginEvent, LoginState2> { LoginBloc(initialState) : super(initialState); @override Stream<LoginState2> mapEventToState(event) async* { if (event is LoginChagneName) { yield _mapChangeUserNameToState(event, state); } else if (event is LoginChagnePassword) { yield _mapChangePasswordToState(event, state); } else if (event is LoginSubmitted) { yield* _mapSubmittedToState(event, state); } } /// 改变密码 LoginState2 _mapChangePasswordToState( LoginChagnePassword event, LoginState2 state2) { return state2.copyWith(pwd: event.password ?? ''); } /// 改变名字 LoginState2 _mapChangeUserNameToState( LoginChagneName event, LoginState2 state2) { return state2.copyWith(name: event.name ?? ''); } /// 提交 Stream<LoginState2> _mapSubmittedToState( LoginSubmitted event, LoginState2 state2) async* { try { if (state2.name.isNotEmpty && state2.password.isNotEmpty) { yield state2.copyWith(login2progress: Login2Progress.isRequesting); await Future.delayed(Duration(seconds: 2)); yield state2.copyWith(login2progress: Login2Progress.success); yield state2.copyWith(login2progress: Login2Progress.init); } } on Exception catch (e) { yield state2.copyWith(login2progress: Login2Progress.error); } } } <|start_filename|>lib/features/share_data.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/3. /// class ShareData extends InheritedWidget { int count; ShareData({Key key, this.count, @required Widget child}) : super(key: key, child: child); @override bool updateShouldNotify(InheritedWidget oldWidget) { return this != oldWidget; } static ShareData of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<ShareData>(); } static ShareData ofNoRefresh(BuildContext context) { return context.getElementForInheritedWidgetOfExactType<ShareData>().widget; } } class BaseShareData extends StatefulWidget { @override _BaseShareDataState createState() => _BaseShareDataState(); } class _BaseShareDataState extends State<BaseShareData> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('共享数据'), ), body: _body(), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () { setState(() { _count += 1; }); }, ), ); } int _count = 0; Widget _body() { return ShareData( count: _count, child: Column( children: <Widget>[ BaseShareData2( have: true, child: Row( children: <Widget>[ BaseShareData2( have: false, ), BaseShareData2( have: false, ) ], ), ), BaseShareData2( have: false, child: Row( children: <Widget>[ BaseShareData2( have: true, ), BaseShareData2( have: false, ) ], ), ) ], ), ); } } class BaseShareData2 extends StatefulWidget { final bool have; final Widget child; BaseShareData2({this.have, this.child}); @override _BaseShareData2State createState() => _BaseShareData2State(); } class _BaseShareData2State extends State<BaseShareData2> { @override Widget build(BuildContext context) { print('build ${widget.have}'); List<Widget> list = new List(); list.add(Text( widget.have == false ? widget.have.toString() : ShareData.of(context).count.toString(), style: TextStyle(fontSize: 20), )); if (widget.child != null) { list.add(widget.child); } return Container( child: Column( children: list, ), alignment: Alignment.center, ); } @override void didChangeDependencies() { print('didChangeDependencies'); super.didChangeDependencies(); } } <|start_filename|>lib/scrollview/baseGridView.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/scrollview/baseListView.dart'; /// /// Created by fgyong on 2020/7/3. /// class BaseGridView extends StatefulWidget { @override _BaseGridViewState createState() => _BaseGridViewState(); } class _BaseGridViewState extends State<BaseGridView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GridView'), ), body: _body(), ); } Widget _body() { // List<Widget> list = new List(); // for (int i = 0; i < 10; i++) { // list.add(Container( // height: 80, // color: Colors.primaries[i % Colors.primaries.length], // alignment: Alignment.center, // child: TestContainer( // title: DateTime.now().toString(), // ))); // } return GridView.builder( gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( // crossAxisCount: 4, maxCrossAxisExtent: MediaQuery.of(context).size.width / 4 + 10.0, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 2), itemBuilder: _buildCell, itemCount: _list.length, semanticChildCount: 13, ); } List<Widget> _list; Widget _buildCell(BuildContext context, int index) { if (index < _list.length - 1) { return Container( height: 80, alignment: Alignment.center, child: _list[index]); } else if (_list.length < 100) { _getData(); return Container( alignment: Alignment.center, child: RefreshProgressIndicator(), ); } else { return Container( height: 80, alignment: Alignment.center, child: _list[index]); } } @override void initState() { _list = new List(); _getData(); super.initState(); } void _getData() async { await Future.delayed(Duration(milliseconds: 1500)); _list.addAll([ Icon(Icons.directions), Icon(Icons.title), Icon(Icons.refresh), Icon(Icons.dehaze), Icon(Icons.ac_unit), ]); setState(() {}); } } <|start_filename|>lib/counter.dart<|end_filename|> import 'package:flutter/cupertino.dart'; class Counter extends ChangeNotifier { int index = 0; void add() { index += 1; notifyListeners(); } void changeValue(int index) { this.index = index; notifyListeners(); } } class CounterValue extends ChangeNotifier { int _index = 0; int get value => _index; void add() { _index += 2; notifyListeners(); } } class CounterValue2 extends ChangeNotifier { int _index = 0; int get value => _index; void add() { _index += 2; notifyListeners(); } } <|start_filename|>lib/tips/page_view.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/tips/Tabbar.dart'; /// /// Created by fgyong on 2020/8/3. /// class BasePageViewRoute extends StatefulWidget { BasePageViewRoute({Key key}) : super(key: key); @override _BasePageViewRouteState createState() => _BasePageViewRouteState(); } class _BasePageViewRouteState extends State<BasePageViewRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('pageView'), ), body: _body(), ); } int hightIndex = 0; Widget _body() { return TabbarViewTWO( callback: _changeIndex, hightIndex: hightIndex, child: PageView( pageSnapping: true, controller: _pageController, onPageChanged: (index) { _pageController.jumpToPage(index); }, children: <Widget>[ Text('1'), Text('2'), ], ), leftTitle: 'left', rightTitle: 'right', leftNumber: 0, rightNumber: 0, ); } void _changeIndex(int index) { _pageController.jumpToPage(index); setState(() { hightIndex = index; }); } PageController _pageController; @override void initState() { _pageController = PageController(); super.initState(); } } <|start_filename|>lib/tips/hive/hive_person.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/10/10. /// import 'package:hive/hive.dart'; import 'package:json_annotation/json_annotation.dart'; @HiveType(typeId: 1) @HiveType() class Person extends HiveObject { @HiveField(0) String name; Person(this.name); } class PersonAdapter extends TypeAdapter<Person> { @override Person read(BinaryReader reader) { return Person(reader.read()); } @override int get typeId => 2; @override void write(BinaryWriter writer, Person obj) { writer.write(obj.name); // writer.write(obj.age); // writer.write(obj.friends); } } <|start_filename|>lib/file_and_http/json_to_model.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:fluttertest01/file_and_http/model/user.dart'; import 'package:fluttertest01/file_and_http/model/user_entity.dart'; import 'package:fluttertest01/generated/json/base/json_convert_content.dart'; /// /// Created by fgyong on 2020/7/27. /// class BaseJsonToModelRoute extends StatefulWidget { BaseJsonToModelRoute({Key key}) : super(key: key); @override _BaseJsonToModelRouteState createState() => _BaseJsonToModelRouteState(); } class _BaseJsonToModelRouteState extends State<BaseJsonToModelRoute> { String jsonStr = '{"list":[{"name":"<NAME>"},{"name":"<NAME>"}]}'; @override void initState() { // List items = json.decode(jsonStr); // // print(items[0]['name']); super.initState(); } String _string = '姓名:\n'; void _toModel() { UserEntity list = JsonConvert.fromJsonAsT<UserEntity>(json.decode(jsonStr)); list.xList.forEach((element) { _string += element.name; _string += '\n'; print(element.name); }); } @override Widget build(BuildContext context) { _toModel(); return Scaffold( appBar: AppBar( title: Text('json to model'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[Text(_string)], ), ); } } <|start_filename|>lib/features/base_will_pop.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/3. /// class BaseWillPop extends StatefulWidget { @override _BaseWillPopState createState() => _BaseWillPopState(); } class _BaseWillPopState extends State<BaseWillPop> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseWillPop'), ), body: WillPopScope( child: _body(), onWillPop: () async { //code showDialog( context: context, builder: (ctx) => CupertinoAlertDialog( title: Text('提示'), content: Text('真的退出吗?'), actions: <Widget>[ FlatButton( child: Text('真的 退出了'), onPressed: () { Navigator.of(context).popUntil((route) { return route.isFirst; }); }, ), FlatButton( child: Text('暂不退出了'), onPressed: () { Navigator.maybePop(context); }, ), ], )); return false; }), ); } Widget _body() { return Container(); } } <|start_filename|>lib/tips/get/get_store.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:get_storage/get_storage.dart'; class GetStoreRoute extends StatefulWidget { GetStoreRoute({Key key}) : super(key: key); @override _GetStoreState createState() => _GetStoreState(); } class _GetStoreState extends State<GetStoreRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GetStorage存储'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: [ Text('GetStorage 添加和读取 :'), Padding( child: TextField( controller: c.editK, decoration: InputDecoration(hintText: 'key', labelText: 'key'), ), padding: EdgeInsets.all(20), ), Padding( child: TextField( controller: c.editC, decoration: InputDecoration(hintText: 'value', labelText: 'value'), ), padding: EdgeInsets.all(20), ), Row( children: [ OutlineButton( child: Text('添加'), onPressed: c.add, ), OutlineButton( child: Text('清空'), onPressed: c.clearData, ), OutlineButton( child: Text('保存'), onPressed: c.save, ), ], mainAxisAlignment: MainAxisAlignment.spaceAround, ), SizedBox( height: 10, ), Text('添加操作日志:'), ObxValue((v) { return Text('${v.value}'); }, c.log), Text('读取到的:keyAndValue:'), SizedBox( child: ObxValue((keyAndValue) { return Text('$keyAndValue'); }, c.keyAndValue), // alignment: Alignment.center, width: 100, height: 200, ), ], ), ); } @override void initState() { printInfo(info: '${widget.runtimeType}initState'); super.initState(); } @override void dispose() { Get.delete<GetStoreController>(); super.dispose(); } final c = Get.put<GetStoreController>(GetStoreController()); } class GetStoreController extends GetxController { final log = ''.obs; final editC = TextEditingController(); final editK = TextEditingController(); final box = GetStorage(); final boxObx = GetStorage(); final keyAndValue = ''.obs; void add() async { if (editK.text.isNotEmpty) { box.write('${editK.text}', '${editC.text}'); } } @override void onInit() { GetStorage.init(); printInfo(info: 'GetStoreController init'); /// 监听固定的 key box.listenKey('key', (v) { log.value = log.value + 'key->$v \n'; }); /// 监听变动 /// 可以每次变动去监测所有数据 box.listen(() { var changeStr = box.changes.toString(); var value = ''; box.getKeys<Iterable<String>>().forEach((element) { var currentKeyAndValue = 'key:$element' + " value:" + boxObx.read(element).toString() + '' '\n'; value += value + currentKeyAndValue; printInfo(info: currentKeyAndValue); }); keyAndValue.value = value; log.value = log.value + '$changeStr \n'; }); super.onInit(); } void clearData() { log.value = ''; box.erase(); } void save() { box.save(); } } <|start_filename|>lib/tips/bloc/base_bloc_list.dart<|end_filename|> import 'dart:html'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; /// /// Created by fgyong on 2020/8/19. /// class BaseBlocListRoute extends StatefulWidget { BaseBlocListRoute({Key key}) : super(key: key); @override _BaseBlocListRouteState createState() => _BaseBlocListRouteState(); } class _BaseBlocListRouteState extends State<BaseBlocListRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('下拉列表BLoC'), ), body: _body(), ); } Widget _body() {} } class ListCubit extends Cubit<Model> { ListCubit(Model state) : super(state); Future<List<_Item>> request(int count) async { await Future.delayed(Duration(seconds: 1)); List<_Item> list = List(); for (int i = 0; i < count; i++) { list.add(_Item(title: 'title${list.length}', subTitle: 'subtitle')); } return list; } } enum ListState { success, faild, isLoading, } class Model extends Equatable { Model({this.list}) { this.list ??= List(); } List<_Item> list; ListState state; Model copyWith(List<_Item> list) { return Model(list: list); } @override List<Object> get props => [list]; } // ignore: unused_element class _Item extends Equatable { String title, subTitle; _Item({this.title, this.subTitle}); @override List<Object> get props => [title, subTitle]; } <|start_filename|>lib/tips/bloc/list_cubit/bloc/list_bloc.dart<|end_filename|> import 'dart:convert'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertest01/tips/bloc/list_cubit/list_events/list_event.dart'; import 'package:fluttertest01/tips/bloc/list_cubit/list_status/list_state.dart'; import 'package:fluttertest01/tips/bloc/list_cubit/model/list_data.dart'; import 'package:http/http.dart' as http; /// /// Created by fgyong on 2020/9/22. /// class PostBloc extends Bloc<PostEvent, PostState> { PostBloc(initialState, this.httpClient) : super(initialState); final http.Client httpClient; @override Stream<PostState> mapEventToState(PostEvent event) async* { final currentState = state; print('$event'); try { if (event is PostFetchedEvent && _hasReachMax(state) == false) { if (currentState is PostInitial) { final posts = await _fetchPosts(0, 20); yield PostSuccess(posts: posts, hasReachedMax: false); return; } else if (currentState is PostSuccess) { yield PostSuccessIsLoading( posts: currentState.posts, hasReachMax: currentState.hasReachedMax); final posts = await _fetchPosts((currentState).posts.length, 20); yield posts.isEmpty ? (currentState).copyWith(hasReachedMax: true) : PostSuccess( posts: (currentState).posts + posts, hasReachedMax: false); } } } catch (_) { yield PostFailure(); } } /// 是否有最大值 bool _hasReachMax(PostState state) { return state is PostSuccess && (state).hasReachedMax == true; } /// 加载数据 Future<List<Post>> _fetchPosts(int startIndex, int limit) async { await Future.delayed(Duration(seconds: 1)); List<Post> list = []; if (startIndex > 40) return list; for (int i = startIndex; i < startIndex + limit; i++) { list.add(Post( id: i, title: 'title $i', body: 'body 测试数据,body就是这么长', )); } return list; } } <|start_filename|>lib/animation/base_animation_diy.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/24. /// class BaseDIYPage extends StatefulWidget { BaseDIYPage({Key key}) : super(key: key); @override _BaseDIYPageState createState() => _BaseDIYPageState(); } class _BaseDIYPageState extends State<BaseDIYPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('过渡性组件'), ), body: _body(), floatingActionButton: FloatingActionButton( child: Text('+'), onPressed: () { setState(() {}); }, ), ); } int _key = 1; Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ BaseDIYAnimationSwitch( key: ObjectKey(_key), duration: Duration( milliseconds: 2000, ), reverseDuration: Duration( milliseconds: 3000, ), child: Container( color: Colors.red, width: 100, height: 100, ), ), TextButton( child: Text('更新key '), onPressed: () { setState(() { _key += 1; }); }, ), Row( children: <Widget>[ AnimatedOpacity( key: ValueKey('AnimatedOpacity'), opacity: _ope, duration: Duration(seconds: 3), child: Container( color: _opColor, width: 100, height: 100, ), ), TextButton( child: Text('AnimatedOpacity'), onPressed: () { setState(() { _opColor = _opColor == Colors.lightBlueAccent ? Colors.orange : Colors.lightBlueAccent; _ope = _ope == 1 ? 0 : 1; }); }, ) ], ), Row( children: <Widget>[ AnimatedPadding( padding: _padding, duration: Duration(seconds: 1), child: Container( color: Colors.orange, width: 100, height: 100, ), ), TextButton( child: Text('AnimatedPadding'), onPressed: () { setState(() { _padding = _padding.left == _padding.right ? EdgeInsets.only( left: 30, right: 20, top: 20, bottom: 20) : EdgeInsets.only(left: 10, right: 10); }); }, ) ], ), Row( children: <Widget>[ Container( color: Colors.blue, width: 100, height: 100, child: AnimatedAlign( alignment: _alignment, duration: Duration(seconds: 1), child: Text( 'align', style: TextStyle(color: Colors.white), ), ), ), TextButton( child: Text('AnimatedAlign'), onPressed: () { setState(() { _alignment = Alignment.bottomRight == _alignment ? Alignment.topLeft : Alignment.bottomRight; }); }, ) ], ), ], ), ); } Color _opColor = Colors.red; double _ope = 1; EdgeInsets _padding = EdgeInsets.only(left: 10, right: 10); Alignment _alignment = Alignment.center; } class BaseDIYAnimationSwitch extends StatefulWidget { final Curve curve; final Duration duration, reverseDuration; final Widget child; BaseDIYAnimationSwitch( {Key key, this.curve, this.duration, this.child, this.reverseDuration}) : super(key: key); @override _BaseDIYAnimationSwitchState createState() => _BaseDIYAnimationSwitchState(); } class _BaseDIYAnimationSwitchState extends State<BaseDIYAnimationSwitch> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<double> animation; @override void initState() { _animationController = AnimationController( duration: widget.duration, vsync: this, reverseDuration: widget.reverseDuration) ..forward(); animation = Tween(begin: 0.0, end: 1.0).animate(_animationController); super.initState(); } @override void didUpdateWidget(BaseDIYAnimationSwitch oldWidget) { super.didUpdateWidget(oldWidget); _updateCurve(); /// 当runType和 key有一个不一样的话再去更新动画 if (Widget.canUpdate(oldWidget, widget) == false) { if (oldWidget.child != null) { _animationController.reverse(); } _animationController ..duration = widget.duration ..reverseDuration = widget.reverseDuration; _animationController ..value = 0 ..forward(); } } @override Widget build(BuildContext context) { return _body(); } Widget _body() { return AnimatedBuilder( child: widget.child, animation: animation, builder: (ctx, child) { return Opacity( opacity: animation.value, child: child, ); }, ); } void _updateCurve() { if (widget.curve != null) { animation = CurvedAnimation(parent: _animationController, curve: widget.curve); } else { animation = _animationController; } } @override void dispose() { _animationController.dispose(); super.dispose(); } } class BaseAnimaitnAlign extends ImplicitlyAnimatedWidget { final Curve curve; final EdgeInsetsGeometry padding; final Widget child; final Duration duration; final VoidCallback onEnd; const BaseAnimaitnAlign( {Key key, this.curve = Curves.linear, @required this.duration, this.onEnd, this.padding, this.child}) : assert(curve != null), assert(duration != null), assert(child != null, ''), super(key: key, curve: curve, onEnd: onEnd, duration: duration); @override ImplicitlyAnimatedWidgetState<ImplicitlyAnimatedWidget> createState() { return BaseAnimaitnAlignState(); } } class BaseAnimaitnAlignState extends ImplicitlyAnimatedWidgetState<BaseAnimaitnAlign> { EdgeInsetsGeometryTween _padding; @override void forEachTween(TweenVisitor<dynamic> visitor) { _padding = visitor( _padding, widget.padding, (dynamic value) => EdgeInsetsGeometryTween(begin: value as EdgeInsetsGeometry)) as EdgeInsetsGeometryTween; } @override Widget build(BuildContext context) { return Padding( padding: _padding .evaluate(animation) .clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity), child: widget.child, ); } } <|start_filename|>lib/animation/base_hreo.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/21. /// class BaseHreo extends StatefulWidget { final String heroKey; BaseHreo({Key key, this.heroKey}) : super(key: key); @override _BaseHreoState createState() => _BaseHreoState(); } class _BaseHreoState extends State<BaseHreo> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Hero 动画'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[ Hero( child: Container( width: 100, height: 100, child: Image.asset('img/2.png'), ), tag: 'key', ), OutlineButton( child: Text('push'), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (ctx) => _BaseHreo( heroKey: 'key', ))); }, ) ], ), ); } } class _BaseHreo extends StatelessWidget { final String heroKey; _BaseHreo({Key key, this.heroKey}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('hero 动画'), ), body: _body(), ); } Widget _body() { return Align( alignment: Alignment.bottomCenter, child: Hero( child: ClipRRect( child: Container( width: 300, height: 300, child: Image.asset( 'img/2.png', fit: BoxFit.fill, ), ), borderRadius: BorderRadius.all(Radius.circular(150)), ), tag: heroKey ?? 'key', ), ); } } <|start_filename|>lib/mainUtil.dart<|end_filename|> export './Features/base_will_pop.dart'; export './animation/base_animaiton.dart'; export './animation/base_animation_diy.dart'; export './animation/base_animation_switch.dart'; export './animation/base_hreo.dart'; export './animation/base_pageRoute.dart'; export './animation/base_tagger_animation.dart'; export './baseWidget/baseButtons.dart'; export './baseWidget/baseIndicator.dart'; export './baseWidget/baseState.dart'; export './baseWidget/baseSwitch.dart'; export './baseWidget/baseText.dart'; export './baseWidget/baseTextField.dart'; export './baseWidget/dialog.dart'; export './baseWidget/imgAndIcon.dart'; export './comment/config.dart'; export './container/base_bars.dart'; export './container/base_container.dart'; export './container/base_decorateBox.dart'; export './container/base_clip.dart'; export './container/base_constraints.dart'; export './container/base_padding.dart'; export './container/base_transform.dart'; export './features/base_color_and_theme.dart'; export './features/base_eventbus.dart'; export './features/base_future_stream.dart'; export './features/base_gesturedetetor.dart'; export './features/base_notification.dart'; export './features/base_touch_handle.dart'; export './features/share_data.dart'; export './file_and_http/fileAction.dart'; export './file_and_http/http_client.dart'; export './file_and_http/http_dio.dart'; export './file_and_http/http_socket.dart'; export './file_and_http/json_to_model.dart'; export './layout/baseFlex.dart'; export './layout/base_align.dart'; export './layout/base_flow_and_wrap.dart'; export './layout/base_row_and_column.dart'; export './layout/base_stack.dart'; export './scrollview/scrollview.dart'; export './scrollview/baseCustomScrollview.dart'; export './scrollview/baseGridView.dart'; export './scrollview/baseListView.dart'; export './scrollview/baseListenScrollViewOffset.dart'; export './scrollview/baseSingleChildScrollView.dart'; export './tips/asyn_and_isolate.dart'; export './tips/async_and_async*.dart'; export './tips/base_bloc.dart'; export './tips/base_key.dart'; export './tips/layout/base_layout.dart'; export './tips/provider/base_provider.dart'; export './tips/base_record.dart'; export './tips/bloc/base_login_cubit.dart'; export './tips/fish_redux_page.dart'; export './tips/keepStateAlive.dart'; export './tips/page_view.dart'; export './tips/page_view_tabbar.dart'; export './tips/redux_page.dart'; export './tips/rx_dart/base_rxDart.dart'; export './tips/scoped_page.dart'; export './tips/wechat_view.dart'; export './tips/base_render_tree.dart'; export './custom_animation/base_custom_animation.dart'; export './tips/img/base_img.dart'; export './tips/channel/base_channel.dart'; export './tips/touch/base_touch_handle.dart'; /// /// Created by fgyong on 2020/8/26. /// <|start_filename|>lib/tips/bloc/login_cubit/model/login_cubit_models.dart<|end_filename|> export 'base_login_model.dart'; /// /// Created by fgyong on 2020/8/20. /// <|start_filename|>lib/generated/json/base/json_convert_content.dart<|end_filename|> // ignore_for_file: non_constant_identifier_names // ignore_for_file: camel_case_types // ignore_for_file: prefer_single_quotes // This file is automatically generated. DO NOT EDIT, all your changes would be lost. import 'package:fluttertest01/file_and_http/model/user_entity.dart'; import 'package:fluttertest01/generated/json/user_entity_helper.dart'; import 'package:fluttertest01/file_and_http/model/git_model.dart'; import 'package:fluttertest01/generated/json/git_model_helper.dart'; class JsonConvert<T> { T fromJson(Map<String, dynamic> json) { return _getFromJson<T>(runtimeType, this, json); } Map<String, dynamic> toJson() { return _getToJson<T>(runtimeType, this); } static _getFromJson<T>(Type type, data, json) { switch (type) { case UserEntity: return userEntityFromJson(data as UserEntity, json) as T; case UserList: return userListFromJson(data as UserList, json) as T; case GitModel: return gitModelFromJson(data as GitModel, json) as T; case GitOwner: return gitOwnerFromJson(data as GitOwner, json) as T; case GitLicense: return gitLicenseFromJson(data as GitLicense, json) as T; } return data as T; } static _getToJson<T>(Type type, data) { switch (type) { case UserEntity: return userEntityToJson(data as UserEntity); case UserList: return userListToJson(data as UserList); case GitModel: return gitModelToJson(data as GitModel); case GitOwner: return gitOwnerToJson(data as GitOwner); case GitLicense: return gitLicenseToJson(data as GitLicense); } return data as T; } //Go back to a single instance by type static _fromJsonSingle(String type, json) { switch (type) { case 'UserEntity': return UserEntity().fromJson(json); case 'UserList': return UserList().fromJson(json); case 'GitModel': return GitModel().fromJson(json); case 'GitOwner': return GitOwner().fromJson(json); case 'GitLicense': return GitLicense().fromJson(json); } return null; } //empty list is returned by type static _getListFromType(String type) { switch (type) { case 'UserEntity': return List<UserEntity>(); case 'UserList': return List<UserList>(); case 'GitModel': return List<GitModel>(); case 'GitOwner': return List<GitOwner>(); case 'GitLicense': return List<GitLicense>(); } return null; } static M fromJsonAsT<M>(json) { String type = M.toString(); if (json is List && type.contains("List<")) { String itemType = type.substring(5, type.length - 1); List tempList = _getListFromType(itemType); json.forEach((itemJson) { tempList .add(_fromJsonSingle(type.substring(5, type.length - 1), itemJson)); }); return tempList as M; } else { return _fromJsonSingle(M.toString(), json) as M; } } } <|start_filename|>lib/tips/bloc/list_cubit/obs/post_obs.dart<|end_filename|> import 'package:bloc/bloc.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/9/22. /// class PostOBs extends BlocObserver { @override void onChange(Cubit cubit, Change change) { print('$cubit $change'); super.onChange(cubit, change); } } <|start_filename|>lib/tips/provider/base_stream_pge.dart<|end_filename|> import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; /// /// Created by fgyong on 2020/8/20. /// class BaseProviderStreamRoute extends StatelessWidget { BaseProviderStreamRoute({Key key}) : super(key: key); static MaterialPageRoute get pageRoute => MaterialPageRoute(builder: (_) => _BaseProviderStreamRoute2()); @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => _ModelStream(), lazy: false, builder: (context, child) { return _BaseProviderStreamRoute2(); }, ); } } class _BaseProviderStreamRoute2 extends StatelessWidget { @override Widget build(BuildContext context) { _ModelStream stream = context.read<_ModelStream>(); return StreamProvider<int>.value( value: stream.firstStream, lazy: false, initialData: 0, child: _BaseProviderStreamRoute(), ); } } class _BaseProviderStreamRoute extends StatefulWidget { @override State<StatefulWidget> createState() { return __BaseProviderStream(); } } class __BaseProviderStream extends State<_BaseProviderStreamRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('定时器'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('${context.select<int, String>((value) => value.toString())}'), OutlineButton( child: Text('stop'), onPressed: () {}, ) ], ), ), ); } } class _ModelStream extends ChangeNotifier { StreamController<int> _streamController; Timer _timer; int count = 0; _ModelStream() { _streamController = StreamController(); initTimer(); } void initTimer() { _timer = Timer.periodic(Duration(seconds: 1), (timer) { _streamController.add(count++); }); } Stream<int> get firstStream => _streamController.stream; void add() { _streamController.add(1); } void reset() { count = 0; } @override void dispose() { _timer?.cancel(); _timer = null; super.dispose(); } } class _ValueModel { final int value; const _ValueModel({this.value}); @override bool operator ==(Object other) => identical(this, other) || other is _ValueModel && runtimeType == other.runtimeType && value == other.value; @override int get hashCode => value.hashCode; _ValueModel.name(this.value); } <|start_filename|>lib/tips/base_render_tree.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/26. /// class BaseRenderTree extends StatefulWidget { BaseRenderTree({Key key}) : super(key: key); @override _BaseRenderTreeState createState() => _BaseRenderTreeState(); static String get routeName => '/BaseRenderTree'; } class _BaseRenderTreeState extends State<BaseRenderTree> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('3棵树'), ), body: _body(), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: _add, ), ); } void _add() { setState(() { _count += 1; }); } int _count = 0; Widget _body() { print('build'); return Center( child: Column( children: <Widget>[ Text.rich( TextSpan( text: '每次刷新只', children: [ _widgetBold('改变Text文本,`renderobject` 不会重新创建'), _widget('只有当'), _widgetBold('`key`或者类型'), _widget('改变才会重新创建`renderobject`') ], ), ), Container( child: Text('$_count'), ), const _LessRoute(), ], ), ); } Widget _listView() { return CustomScrollView( slivers: <Widget>[ SliverList( delegate: SliverChildBuilderDelegate((context, index) { return Text('$index'); }, childCount: 10), ), SliverGrid( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, crossAxisSpacing: 10, mainAxisSpacing: 10, ), delegate: SliverChildBuilderDelegate((context, index) { return Text('$index'); }, childCount: 12), ) ], ); } Widget _widget2() { return Stack(); } TextSpan _widgetBold(String string) { return TextSpan( text: '$string', style: TextStyle( fontSize: 15, color: Colors.blueAccent, fontWeight: FontWeight.bold), ); } TextSpan _widget(String string) { return TextSpan( text: '$string', ); } } class _LessRoute extends StatelessWidget { @override Widget build(BuildContext context) { print('_LessRoute build'); return Container( child: Text('const 修饰的组件,父组件怎么刷新,子组件都不刷新'), ); } const _LessRoute(); } <|start_filename|>lib/baseWidget/baseButtons.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseButtons extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('按钮'), ), body: Center( child: _body(), ), ); } Widget _body() { return Container( margin: EdgeInsets.only( top: 50, ), child: Column( children: <Widget>[ Text('FlatButton'), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FlatButton( child: Text('nomal'), onPressed: () { print('FlatButton'); }, ), FlatButton( child: Text('active'), focusNode: new FocusNode()..requestFocus(), onPressed: () { print('FlatButton'); }, ), ], ), Text('RaisedButton'), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text('normal'), onPressed: () { print('RaisedButton'); }, ), SizedBox( width: 30, ), RaisedButton( child: Text('active'), onPressed: () { print('RaisedButton'); }, ) ], ), Text('IconButton'), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ IconButton( icon: Icon(Icons.add), onPressed: () { print('IconButton'); }, ), SizedBox( width: 30, ), IconButton( icon: Icon(Icons.add), onPressed: () { print('IconButton'); }, ), ], ), // Text('FloatingActionButton'), // Row( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // FloatingActionButton( // child: Icon(Icons.add), // onPressed: () {}, // ), // SizedBox( // width: 30, // ), // FloatingActionButton( // child: Icon(Icons.add), // onPressed: () {}, // ), // ], // ), Container( child: Text('BackButton CloseButton'), margin: EdgeInsets.only(top: 20), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ BackButton( onPressed: () {}, ), SizedBox( width: 30, ), CloseButton( onPressed: () {}, ), ], ), Container( child: Text('OutlineButton'), margin: EdgeInsets.only(top: 20), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ OutlineButton( child: Text('OutlineButton'), onPressed: () {}, ), SizedBox( width: 10, ), OutlineButton.icon( icon: Icon(Icons.add), label: Text('label'), onPressed: () {}, ), SizedBox( width: 10, ), OutlineButton.icon( icon: Icon(Icons.add), label: Text('active'), onPressed: () {}, ), ], ), SizedBox( height: 50, ), _diyIconButton(), ], ), ); } Widget _diyIconButton() { return OutlineButton.icon( onPressed: () {}, icon: Icon(Icons.add), label: Text('diy style'), color: Colors.black12, textColor: Colors.blue, disabledBorderColor: Colors.black, highlightedBorderColor: Colors.greenAccent, splashColor: Colors.red); } } <|start_filename|>lib/tips/channel/base_channel.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// /// Created by fgyong on 2020/9/7. /// class BaseChannelRoute extends StatefulWidget { BaseChannelRoute({Key key}) : super(key: key); @override _BaseChannelRouteState createState() => _BaseChannelRouteState(); static String get routeName => 'BaseChannelRoute'; } class _BaseChannelRouteState extends State<BaseChannelRoute> { static const platform = const MethodChannel('samples.flutter.io/battery'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('获取电量'), ), body: _body(), ); } String _string = ''; Widget _body() { return Column( children: [ OutlineButton( child: Text('获取电量'), onPressed: _get, ), Text('$_string') ], ); } Future<void> _get() async { try { final int result = await platform.invokeMethod('getBatteryLevel'); setState(() { _string = result.toString(); }); } on PlatformException catch (e) { print('$e'); } } } <|start_filename|>lib/baseWidget/imgAndIcon.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseImgAndIcon extends StatefulWidget { BaseImgAndIconState createState() => BaseImgAndIconState(); } class BaseImgAndIconState extends State<BaseImgAndIcon> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('图片和Icon'), ), body: Center( child: _body(), ), ); } void _clear() { PaintingBinding.instance.imageCache.clear(); } Widget _body() { return Container( child: CupertinoScrollbar( child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter( child: Container( height: 30, child: Text('Image from disk'), ), ), SliverToBoxAdapter( child: Container( width: 100, child: Image.asset('img/1.jpeg'), ), ), SliverToBoxAdapter( child: Container( height: 30, child: Text('Image from remote'), ), ), SliverToBoxAdapter( child: Image( image: NetworkImage( "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1593336370404&di=c03084a66d06c1af8995088158e907c3&imgtype=0&src=http%3A%2F%2Fdmimg.5054399.com%2Fallimg%2Fpkm%2Fpk%2F13.jpg"), width: 100.0, height: 200, color: Colors.greenAccent, colorBlendMode: BlendMode.colorBurn, repeat: ImageRepeat.repeat, ), ), // https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1593338791382&di=4dfae11210313f734093208ae6ae6f1a&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F9%2F518c658448267.jpg SliverToBoxAdapter( child: Image( image: NetworkImage( "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2053400745,529716701&fm=26&gp=0.jpg"), width: 100.0, height: 200, // color: Colors.red, // colorBlendMode: BlendMode.colorBurn, loadingBuilder: ( BuildContext context, Widget child, ImageChunkEvent loadingProgress, ) { if (loadingProgress == null) { _clear(); Future.delayed(Duration(seconds: 2)).then((value) { return child; }); return child; } return Container( height: 300, child: CircularProgressIndicator(), alignment: Alignment.center, ); }, ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.fill, ), ), Text('fill') ], ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, height: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.fitWidth, ), ), Text('fitWidth') ], ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, height: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.fitHeight, ), ), Text('fitHeight') ], ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, height: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.cover, ), ), Text('cover') ], ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, height: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.contain, ), ), Text('contain') ], ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, height: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.scaleDown, ), ), Text('scaleDown') ], ), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Container( width: 100, height: 100, color: Colors.red, child: Image.asset( 'img/1.jpeg', fit: BoxFit.none, ), ), Text('none') ], ), ), SliverToBoxAdapter( child: Text('\uE915 \uE002 \uE900', style: TextStyle( fontFamily: "MaterialIcons", fontSize: 24.0, color: Colors.green)), ), SliverToBoxAdapter( child: Row( children: <Widget>[ Icon( Icons.clear, color: Colors.red, ), Icon( Icons.add, color: Colors.greenAccent, ), Icon( Icons.collections, color: Colors.blue, ), Icon( Icons.extension, color: Colors.orange, ) ], ), ) ], ), ), margin: EdgeInsets.all(20), ); } } <|start_filename|>lib/tips/bloc/list_cubit/list_events/list_event.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/9/22. /// import 'package:equatable/equatable.dart'; abstract class PostEvent extends Equatable { @override List<Object> get props => []; } class PostFetchedEvent extends PostEvent {} <|start_filename|>lib/tips/base_slider.dart<|end_filename|> import 'package:connectivity/connectivity.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; class BaseSliderPage extends StatefulWidget { @override State<StatefulWidget> createState() => _BaseSliderPageState(); static String get routeName => '/BaseSliderPage'; } class _BaseSliderPageState extends State<BaseSliderPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseSliderPage'), ), body: _body(), ); } Widget _body() { return Column( children: [ _buildItem(), _buildItem(), _buildItem(), _buildItem(), _buildItem(), ], ); } Widget _buildItem() { return Slidable( actionPane: SlidableDrawerActionPane(), actionExtentRatio: 0.25, child: Container( color: Colors.white, child: ListTile( leading: CircleAvatar( backgroundColor: Colors.indigoAccent, child: Text('3'), foregroundColor: Colors.white, ), title: Text('Tile n°3'), subtitle: Text('SlidableDrawerDelegate'), ), ), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.blue, icon: Icons.archive, onTap: () => _showSnackBar('Archive'), ), IconSlideAction( caption: 'Share', color: Colors.indigo, icon: Icons.share, onTap: () => _showSnackBar('Share'), ), ], secondaryActions: <Widget>[ IconSlideAction( caption: 'More', color: Colors.black45, icon: Icons.more_horiz, onTap: () => _showSnackBar('More'), ), IconSlideAction( caption: 'Delete', color: Colors.red, icon: Icons.delete, onTap: () => _showSnackBar('Delete'), ), ], ); } void _showSnackBar(String str) { ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(str))); } @override void initState() { super.initState(); } } <|start_filename|>lib/tips/bloc/login_cubit/view/base_login_view.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../base_login_cubit.dart'; /// /// Created by fgyong on 2020/8/19. /// class BaseLoginPage extends StatefulWidget { BaseLoginPage({Key key}) : super(key: key); @override _BaseLoginPageState createState() => _BaseLoginPageState(); } class _BaseLoginPageState extends State<BaseLoginPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('loginBLoC Cubit'), ), body: _body(), ); } Widget _body() { return BlocListener<LoginCubit, LoginModel>( listener: (context, state) { if (state.state == LoginState.success) { Scaffold.of(context) ..hideCurrentSnackBar() ..showSnackBar(const SnackBar(content: Text('登陆成功'))); } }, child: Center( child: Column( children: <Widget>[ TextFiledNameRoute(), TextFiledPasswordRoute(), const SizedBox( height: 20, ), LoginButton() ], ), ), ); } @override void initState() { Bloc.observer = BlocObserver(); super.initState(); } } class TextFiledPasswordRoute extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<LoginCubit, LoginModel>( builder: (BuildContext context, LoginModel state) { return TextField( onChanged: (v) { context .bloc<LoginCubit>() .handleLoginEvents(LoginCubitChagnePassword(password: v)); }, textAlign: TextAlign.center, decoration: InputDecoration( labelText: 'password', errorText: state.password?.isEmpty ?? false ? 'password不可用' : null), ); }, buildWhen: (previos, current) => previos.password != current.password); } } class TextFiledNameRoute extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<LoginCubit, LoginModel>( builder: (BuildContext context, LoginModel state) { return TextField( onChanged: (v) { context .bloc<LoginCubit>() .handleLoginEvents(LoginCubitChagneName(name: v)); }, textAlign: TextAlign.center, decoration: InputDecoration( labelText: 'name', errorText: state.name?.isEmpty ?? false ? 'name不可用' : null), ); }, buildWhen: (previos, current) => previos.name != current.name); } } class LoginButton extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<LoginCubit, LoginModel>( builder: (BuildContext context, LoginModel state) { switch (state.state) { case LoginState.isLoading: return const CircularProgressIndicator(); default: return RaisedButton( child: const Text('login'), onPressed: state.btnVisiable ? () { context .bloc<LoginCubit>() .handleLoginEvents(LoginCubitSubmitted()); } : null, ); } }, buildWhen: (previos, current) => previos.btnVisiable != current.btnVisiable || (current.state != previos.state)); } } <|start_filename|>lib/scrollview/baseCustomScrollview.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/scrollview/baseListView.dart'; /// /// Created by fgyong on 2020/7/3. /// class BaseCustomScrollView extends StatefulWidget { @override _BaseCustomScrollViewState createState() => _BaseCustomScrollViewState(); } class _BaseCustomScrollViewState extends State<BaseCustomScrollView> { @override Widget build(BuildContext context) { return Scaffold( body: _body(), ); } Widget _body() { List<Widget> list = new List(); for (int i = 0; i < 5; i++) { list.add(Card( child: Container( height: 40, width: MediaQuery.of(context).size.width, alignment: Alignment.center, child: Text('$i'), ), )); } return CupertinoScrollbar( child: CustomScrollView( slivers: <Widget>[ SliverAppBar( expandedHeight: 300, flexibleSpace: FlexibleSpaceBar( title: Text('flexibleSpace'), collapseMode: CollapseMode.parallax, //消失效果 stretchModes: [StretchMode.fadeTitle], //消失效果 background: PageView( children: <Widget>[ Container( // color: Colors.orange, alignment: Alignment.center, child: Image.asset('img/2.png'), ), Container( alignment: Alignment.center, child: Image.asset('img/2.png'), ), Container( alignment: Alignment.center, // color: Colors.orange, child: Image.asset('img/2.png'), ), Container( alignment: Alignment.center, child: Image.asset('img/2.png'), ), ], ), centerTitle: true, ), // title: Text('12'), pinned: true, // snap: true, ), SliverList( delegate: SliverChildListDelegate(list), ), SliverGrid( delegate: SliverChildBuilderDelegate(_buildCell, childCount: list.length), gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200), ), SliverToBoxAdapter( child: Container( height: 200, width: 200, child: PageView( children: <Widget>[ Container( height: 50, width: 200, alignment: Alignment.center, child: Text( '中间插画,可以左右滑动的哦!!!', style: TextStyle(fontSize: 30), ), decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.deepOrangeAccent, Colors.orange])), ), Container( height: 50, width: 200, alignment: Alignment.center, child: Text( '中间插画,可以左右滑动的哦!!!', style: TextStyle(fontSize: 30), ), decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.deepOrangeAccent, Colors.orange])), ) ], ), ), ), SliverGrid( delegate: SliverChildBuilderDelegate(_buildCell, childCount: list.length), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), ), ], ), ); } Widget _buildCell(ctx, int index) { if (index < list.length - 1) { return Container( height: 80, alignment: Alignment.center, color: Colors.primaries[index % Colors.primaries.length], child: TestContainer( title: list[index], ), ); } else if (list.length >= 30) { return Container( alignment: Alignment.center, height: 80, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[Icon(Icons.done), Text('没有更多数据了')], ), ); } else { _getMoreData(); //加载数据 return Container( alignment: Alignment.center, child: RefreshProgressIndicator(), ); } } List<String> list; @override void initState() { list = new List(); _getMoreData(); super.initState(); } void _getMoreData() async { await Future.delayed(Duration(milliseconds: 2000)); setState(() { for (int i = 0; i < 10; i++) { list.add(DateTime.now().toString()); } }); } } <|start_filename|>lib/container/base_container.dart<|end_filename|> import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseContainer extends StatefulWidget { @override _BaseContainerState createState() => _BaseContainerState(); } class _BaseContainerState extends State<BaseContainer> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Container容器'), ), body: _body(), ); } Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( clipBehavior: Clip.none, width: 200, height: 100, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10)), gradient: LinearGradient(colors: [Colors.orange, Colors.deepOrange])), transform: Matrix4.identity()..rotateZ(pi / 10), child: Text( 'www.flutter.fgyong.cn', style: TextStyle(fontSize: 18, color: Colors.white), ), alignment: Alignment.center, ) ], ), ); } } <|start_filename|>lib/baseWidget/dialog.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseDialog extends StatefulWidget { @override State<StatefulWidget> createState() { return BaseDialogState(); } } class BaseDialogState extends State<BaseDialog> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('弹框'), ), body: _body(), ); } Widget _body() { Widget w = Column( children: <Widget>[ OutlineButton( child: Text('showCupertinoModalPopup'), onPressed: _showActionSheet, ), OutlineButton( child: Text('showCupertinoDialog'), onPressed: _showCupertinoDialog, ), OutlineButton( child: Text('showAboutDialog'), onPressed: _showAboutDialog, ), OutlineButton( child: Text('showGeneralDialog'), onPressed: _showGeneralDialog, ), OutlineButton( child: Text('showDialog'), onPressed: _showDialog, ), //_showBottomSheet OutlineButton( child: Text('showDatePicker'), onPressed: _showDatePicker, ), //_showTimePicker OutlineButton( child: Text('showTimePicker'), onPressed: _showTimePicker, ), ], ); return w; } void _showActionSheet() { showCupertinoModalPopup( context: context, builder: (ctx) { return CupertinoActionSheet( title: Text('温馨提示'), message: Text('我是支付选项,任意选择一个进行支付哦'), actions: <Widget>[ CupertinoActionSheetAction(onPressed: _pop, child: Text('微信')), CupertinoActionSheetAction(onPressed: _pop, child: Text('支付宝')), CupertinoActionSheetAction( onPressed: _pop, child: Text('取消'), isDestructiveAction: true, ), ], ); }); } void _showCupertinoDialog() { showCupertinoDialog( context: context, builder: (ctx) { return CupertinoActionSheet( title: Text('温馨提示'), message: Text('我是showCupertinoDialog'), actions: <Widget>[ CupertinoActionSheetAction(onPressed: _pop, child: Text('微信')), CupertinoActionSheetAction(onPressed: _pop, child: Text('支付宝')), CupertinoActionSheetAction( onPressed: _pop, child: Text('取消'), isDestructiveAction: true, ), ], ); }); } void _showAboutDialog() { showAboutDialog( context: context, applicationVersion: '1.0.0', applicationIcon: Icon(Icons.scatter_plot), applicationName: '<NAME>', ); } void _showGeneralDialog() { showGeneralDialog( context: context, barrierDismissible: true, barrierLabel: 'cancel', transitionDuration: Duration(milliseconds: 1000), pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return Material( child: Scaffold( body: Center( child: CupertinoActionSheet( title: Text('温馨提示'), message: Text('我是showGeneralDialog,任意选择一个进行支付哦'), actions: <Widget>[ CupertinoActionSheetAction( onPressed: _pop, child: Text('微信')), CupertinoActionSheetAction( onPressed: _pop, child: Text('支付宝')), CupertinoActionSheetAction( onPressed: _pop, child: Text('取消'), isDestructiveAction: true, ), ], ), ), ), ); }); } void _showDialog() { showDialog(context: context, builder: (_) => bd()); } void _showDatePicker() { showDatePicker( context: this.context, initialDate: DateTime.now(), //初始时间 firstDate: DateTime.now(), //开始时间 lastDate: DateTime.now().add(Duration(days: 10)), //最后时间是当前时间加上10天 initialDatePickerMode: DatePickerMode.year, //最开始展示年份 initialEntryMode: DatePickerEntryMode.input, //开始是输入时间还是日历 selectableDayPredicate: (time) { print(time.toString()); return true; }); } void _showTimePicker() { showTimePicker( context: this.context, initialTime: TimeOfDay(hour: 1, minute: 10)); } void _pop() { Navigator.maybePop(context); } Widget bd() { return CupertinoActionSheet( title: Text('温馨提示'), message: Text('我是支付选项,任意选择一个进行支付哦'), actions: <Widget>[ CupertinoActionSheetAction(onPressed: _pop, child: Text('微信')), CupertinoActionSheetAction(onPressed: _pop, child: Text('支付宝')), CupertinoActionSheetAction( onPressed: _pop, child: Text('取消'), isDestructiveAction: true, ), ], ); } } <|start_filename|>lib/tips/base_bloc.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertest01/baseWidget/baseState.dart'; import 'package:fluttertest01/test.dart'; import 'package:equatable/equatable.dart'; import 'package:fluttertest01/tips/bloc/list_cubit/page/list_bloc_route.dart'; import 'package:fluttertest01/tips/bloc/login_bloc/login_bloc_page.dart'; import '../tips/bloc/base_login_cubit.dart'; /// /// Created by fgyong on 2020/8/11. /// class BaseBLoCPageRoute extends StatefulWidget { BaseBLoCPageRoute({Key key}) : super(key: key); @override _BaseBLoCPageRouteState createState() => _BaseBLoCPageRouteState(); static String get routeName => 'BaseBLoCRoute'; } class _BaseBLoCPageRouteState extends State<BaseBLoCPageRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BLoC'), ), body: _body(), ); } Widget _body() { return CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter( child: OutlineButton( child: Text('简单数字加减例子'), onPressed: () { push(BaseBLocRoute2()); }, ), ), SliverToBoxAdapter( child: OutlineButton( child: Text('login Cubit'), onPressed: () { push(BaseLoginPageRoute()); }, ), ), SliverToBoxAdapter( child: OutlineButton( child: Text('login BLoC'), onPressed: () { push(LoginBlocRoute()); }, ), ), SliverToBoxAdapter( child: OutlineButton( child: Text('posts BLoC'), onPressed: () { push(ListBlocRoute()); }, ), ) ], ); } void push(Widget widget) { Navigator.of(context).push(MaterialPageRoute(builder: (_) => widget)); } } class BaseBLocRoute2 extends StatefulWidget { /// 局部刷新 数字加减例子页面 BaseBLocRoute2({Key key}) : super(key: key); @override _BaseBLocRoute2State createState() => _BaseBLocRoute2State(); } class _BaseBLocRoute2State extends State<BaseBLocRoute2> { @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (_) => CounterCubit(), ), BlocProvider( create: (_) => CounterCubit2(), ), ], child: BaseBLoCRoute(), ); } } class BaseBLoCRoute extends StatefulWidget { BaseBLoCRoute({Key key}) : super(key: key); @override _BaseBLoCRouteState createState() => _BaseBLoCRouteState(); } class _BaseBLoCRouteState extends State<BaseBLoCRoute> { @override Widget build(BuildContext context) { print('page build +1'); return Scaffold( appBar: AppBar( title: Text('局部刷新数字加减'), ), body: _body(), ); } Widget _body() { return Center( child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter( child: BlocBuilder<CounterCubit, Model>( builder: (_, count) { print('CounterCubit1 '); return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( child: Text( 'count: ${count.count}', ), padding: EdgeInsets.all(20), ), OutlineButton( child: Icon(Icons.arrow_drop_up), onPressed: () { context.bloc<CounterCubit>().addCount(1); }, ), OutlineButton( child: Icon(Icons.arrow_drop_down), onPressed: () { context.bloc<CounterCubit>().addCount(-1); }, ) ], ); }, buildWhen: (m1, m2) => m1.count != m2.count, ), ), SliverToBoxAdapter( child: SizedBox( height: 50, ), ), SliverToBoxAdapter( child: BlocBuilder<CounterCubit, Model>( builder: (_, count) { print('CounterCubit age build '); return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( child: Text( 'age:${count.age}', ), padding: EdgeInsets.all(20), ), OutlineButton( child: Icon(Icons.arrow_drop_up), onPressed: () { context.bloc<CounterCubit>().addAge(1); }, ), OutlineButton( child: Icon(Icons.arrow_drop_down), onPressed: () { context.bloc<CounterCubit>().addAge(-1); }, ) ], ); }, buildWhen: (m1, m2) => m1.age != m2.age, ), ), SliverToBoxAdapter( child: BlocBuilder<CounterCubit2, Model>( builder: (_, count) { print('CounterCubit2 '); return Column( children: <Widget>[ Text('CounterCubit2: ${count.age}'), OutlineButton( child: Icon(Icons.add), onPressed: () { context.bloc<CounterCubit2>().addAge(1); }, ) ], ); }, ), ), SliverToBoxAdapter( child: BlocConsumer<CounterCubit, Model>(builder: (ctx, state) { return Column( children: <Widget>[ Text( 'age:${context.bloc<CounterCubit>().state.age} count:${context.bloc<CounterCubit>().state.count}'), OutlineButton( child: Text('age+1'), onPressed: () { context.bloc<CounterCubit>().addAge(1); }, ), OutlineButton( child: Text('age-1'), onPressed: () { context.bloc<CounterCubit>().addAge(-1); }, ), OutlineButton( child: Text('count+1'), onPressed: () { context.bloc<CounterCubit>().addCount(1); }, ), OutlineButton( child: Text('count-1'), onPressed: () { context.bloc<CounterCubit>().addCount(-1); }, ) ], ); }, listener: (ctx, state) { if (state.age + state.count == 10) Navigator.maybePop(context); }), ), ], ), ); } @override void initState() { Bloc.observer = SimpleBlocObserver(); super.initState(); } } class CounterCubit extends Cubit<Model> { CounterCubit() : super(Model(count: 0, name: '老王')); void increment() { print('CounterCubit +1'); emit(state.addCount(1)); } void decrement() { print('CounterCubit -1'); emit(state.clone()); } void addAge(int v) { emit(state.addAge(v)); } void addCount(int v) { emit(state.addCount(v)); } } // ignore: must_be_immutable class Model extends Equatable { int count; int age; String name; Model({this.count = 0, this.name, this.age = 0}); @override List<Object> get props => [count, name, age]; Model addCount(int value) { return clone()..count = count + value; } Model addAge(int value) { return clone()..age = age + value; } Model clone() { return Model(count: count, name: name, age: age); } @override bool operator ==(Object other) { if (other is Model) return this.count == other.count && age == other.age && name == other.name; return false; } @override int get hashCode => super.hashCode; } class CounterCubit2 extends Cubit<Model> { CounterCubit2() : super(Model()); Model addAge(int v) { emit(state.addAge(v)); } } /// 观察者来观察 事件的变化 可以使用默认的 [BlocObserver] class SimpleBlocObserver extends BlocObserver { @override void onEvent(Bloc bloc, Object event) { print(event); super.onEvent(bloc, event); } @override void onChange(Cubit cubit, Change change) { print(change); super.onChange(cubit, change); } @override void onTransition(Bloc bloc, Transition transition) { print(transition); super.onTransition(bloc, transition); } @override void onError(Cubit cubit, Object error, StackTrace stackTrace) { print(error); super.onError(cubit, error, stackTrace); } } <|start_filename|>lib/page_view/page_view.dart<|end_filename|> import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/page_view/page_view_custom.dart'; class CustomPageViewPage extends StatefulWidget { List<double> widgetHeights; int initPage; int pageCount; @override State<StatefulWidget> createState() => _CustomPageViewState(); static String get routeName => '/page_view'; } class _CustomPageViewState extends State<CustomPageViewPage> { @override Widget build(BuildContext context) { return Scaffold( body: Container( alignment: Alignment.center, color: Colors.white, child: CustomScrollView( slivers: [ SliverToBoxAdapter( child: Container( child: Text('我是第1行'), height: 200, ), ), SliverToBoxAdapter( child: Container( height: _pageViewHeight, width: double.maxFinite, alignment: Alignment.center, child: CustomPageView( widgetHeights: [100, 200, 300], initPage: 1, pageCount: 3, itemBuilder: (ctx, index) { return _item(index); }, freshWidget: (fn) { if (mounted) setState(fn); }, freshHeightCallBack: (height) { _pageViewHeight = height; }, ), ), ), SliverToBoxAdapter( child: Text('我是第二行'), ), ], ), ), appBar: AppBar( title: Text('pageView' ''), ), ); } Widget _item(int index) { print('build $index'); index += 1; return Opacity( opacity: 1, child: Container( color: Colors.accents[index % Colors.accents.length], height: (index * 100).toDouble(), alignment: Alignment.center, child: Text('$index'), ), ); } double _pageViewHeight; @override void initState() { super.initState(); _pageViewHeight = 200; } @override void dispose() { super.dispose(); } } <|start_filename|>lib/video/base_video_ijk_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_ijkplayer/flutter_ijkplayer.dart'; class BaseIJKVideoPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _HomePageState(); } static String get routeName => '/BaseIJKVideoPage'; } class _HomePageState extends State<BaseIJKVideoPage> { IjkMediaController controller = IjkMediaController(); @override void initState() { controller = IjkMediaController(); index = 0; controller.ijkStatusStream.asBroadcastStream(onListen: (ijk) { print('ijkStatusStream: ${ijk.toString()}'); }); controller.textureIdStream.asBroadcastStream(onListen: (index) { print('textureIdStream: $index'); }); super.initState(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('IJK video'), actions: <Widget>[ IconButton( icon: Icon(Icons.store), onPressed: () {}, ), ], ), body: buildIjkPlayer(), floatingActionButton: FloatingActionButton( child: Icon(Icons.next_plan_outlined), onPressed: () async { await controller.setNetworkDataSource(url, autoPlay: true); print("set data source success"); // controller.playOrPause(); }, ), ); } int index = 0; String get url { index += 1; /// https://blog.csdn.net/suwu150/article/details/90345041 m3u8资源列表 var list = [ 'https://vd3.bdstatic.com/mda-mc2t866ix18tmrbw/sc/cae_h264_clips/1614770378/mda-mc2t866ix18tmrbw.mp4', // 'https://vd2.bdstatic.com/mda-mdpdktv9j7dc629c/1080p/cae_h264/1619258626/mda-mdpdktv9j7dc629c.mp4', 'http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv2.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv3hd.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv4.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv5phd.m3u8', ]; return list[index % (list.length)]; } Widget buildIjkPlayer() { return Center( child: Container( height: 400, // 这里随意 child: IjkPlayer( mediaController: controller, ), ), ); } } <|start_filename|>lib/baseWidget/baseText.dart<|end_filename|> import 'dart:developer'; import 'dart:io'; import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; class BaseWidgetTextPage extends StatefulWidget { @override State<StatefulWidget> createState() { return BaseWidgetTextPageState(); } } class BaseWidgetTextPageState extends State<BaseWidgetTextPage> { double _textScaleFactor = 2.0; //字体放大倍数 TextOverflow _overflow = TextOverflow.visible; TextDecorationStyle _decorationStyle = TextDecorationStyle.dashed; @override Widget build(BuildContext context) { _textScaleFactor = 2.0; var w = MediaQuery.of(context).size.width; TextSpan sp = TextSpan(children: [ TextSpan( text: 'TextOverflow.ellipsisTextOverflow.elli ', style: TextStyle( fontSize: 20, ), ), WidgetSpan( child: Container( child: Text( '我是结尾', style: TextStyle( fontSize: 20, ), ), )), ]); Widget ch = Text.rich( sp, maxLines: 2, textScaleFactor: _textScaleFactor, overflow: _overflow, ); return Scaffold( appBar: AppBar( title: Text('text'), ), body: Column( children: <Widget>[ Row( children: [ Container( width: 50, height: 50, color: Colors.redAccent, ), Expanded( child: _buildStartLevelText( context, name: '仿照美团中间。。。后边再新增文字类型后边再新增文字类型后边再新增文字类型后边再新增文字类型', type: '类型', )), Container( width: 50, height: 50, color: Colors.redAccent, ) ], ), Container( child: Text( 'text HelloWord', textAlign: TextAlign.left, ), ), Container( margin: EdgeInsets.all(10), alignment: Alignment.centerLeft, child: Text( '加了style的文本', style: TextStyle( fontFamily: 'Merriweather', // package: 'flutter-example-git', color: Colors.red, letterSpacing: 1, wordSpacing: 3, fontSize: 30, height: 1.4, background: new Paint()..color = Colors.black12, decoration: TextDecoration.underline, decorationColor: Colors.blue, decorationStyle: _decorationStyle), ), ), Container( alignment: Alignment.center, child: ch, height: 150, ), Text('TextOverflow'), Padding( child: Row( children: <Widget>[ CupertinoSegmentedControl<TextOverflow>( children: { TextOverflow.ellipsis: Text('ellipsis'), TextOverflow.clip: Text('clip'), TextOverflow.fade: Text('fade'), TextOverflow.visible: Text('visible'), }, onValueChanged: (value) { setState(() { _overflow = value; }); }, selectedColor: Theme.of(context).primaryColor, groupValue: _overflow, ) ], ), padding: EdgeInsets.all(10), ), Text('TextDecorationStyle'), Row( children: <Widget>[ CupertinoSegmentedControl<TextDecorationStyle>( children: { TextDecorationStyle.double: Text('double'), TextDecorationStyle.wavy: Text('wavy'), TextDecorationStyle.dashed: Text('dashed'), TextDecorationStyle.solid: Text('solid'), TextDecorationStyle.dotted: Text('dotted'), }, onValueChanged: (value) { setState(() { _decorationStyle = value; }); }, selectedColor: Theme.of(context).primaryColor, groupValue: _decorationStyle, ) ], ), Container( height: 30, margin: EdgeInsets.only(top: 10, bottom: 10), child: Text.rich(TextSpan( text: '------textSpan-----', style: TextStyle( fontSize: 20, ))), ), Text.rich( TextSpan( text: '<NAME>,hello!', style: TextStyle( fontSize: 20, ), children: [ TextSpan( text: 'Bo', style: TextStyle( fontSize: 20, color: Colors.blue, backgroundColor: Colors.black12)), TextSpan( text: 'b,hello!', style: TextStyle( fontSize: 30, color: Colors.red, backgroundColor: Colors.lightGreenAccent)), TextSpan( text: 'two line', style: TextStyle( fontSize: 30, color: Colors.red, backgroundColor: Colors.lightGreenAccent, decoration: TextDecoration.underline, decorationColor: Colors.blue, decorationStyle: TextDecorationStyle.double)), TextSpan( text: '\n点击打开我 🖱http://www.fgyong.cn', style: TextStyle(fontSize: 20, height: 2), recognizer: new TapGestureRecognizer() ..onTap = () { _openUrl('http://www.fgyong.cn'); }, ), ]), ), DefaultTextStyle( //1.设置文本默认样式 style: TextStyle( color: Colors.blue, fontSize: 20.0, ), textAlign: TextAlign.start, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("<NAME>"), Text("I am Ok"), Text( "I am Jack", style: TextStyle( inherit: false, //2.不继承默认样式 color: Colors.grey, ), ), ], ), ), Container( color: Colors.redAccent, child: Container( width: 180, height: 100, child: CustomPaint( painter: _CustomPaint(), ), ), ), _TextSpan() ], ), ); } Text _buildStartLevelText(BuildContext context, {String name, String type, int lines}) { double width = MediaQuery.of(context).size.width - 100; lines ??= 2; TextStyle textStyle1 = TextStyle(fontSize: 16, fontWeight: FontWeight.bold); TextStyle textStyle2 = TextStyle(fontSize: 11); try { TextSpan textSpan = TextSpan( children: [ TextSpan( text: "$name ", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), TextSpan(text: type, style: TextStyle(fontSize: 11)), ], ); TextPainter textPainter = TextPainter( text: textSpan, textDirection: TextDirection.ltr, maxLines: lines, ellipsis: '...'); textPainter.layout( minWidth: 0, maxWidth: width, ); String retName = name; while (textPainter.didExceedMaxLines == true && name != null && name.isNotEmpty) { log('didExceedMaxLines :$name'); name = name.substring(0, name.length - 1); textSpan = TextSpan( children: [ TextSpan(text: "$name... ", style: textStyle1), TextSpan(text: type, style: textStyle2), ], ); textPainter.text = textSpan; textPainter.layout( minWidth: 0, maxWidth: width, ); } Text richText = Text.rich( TextSpan( children: [ TextSpan( text: "$name${name == retName ? '' : '...'} ", style: textStyle1), WidgetSpan( child: Container( margin: EdgeInsets.only(top: 3, bottom: (Platform.isIOS ? 0 : 1)), padding: const EdgeInsets.only(left: 0, right: 4), child: Padding( padding: const EdgeInsets.only(bottom: 1.0), child: Text( "${type ?? ""}", style: textStyle2, ), ), )), ], ), softWrap: true, overflow: TextOverflow.ellipsis, maxLines: lines, ); return richText; } catch (e) { var richText = Text.rich( TextSpan( children: [ TextSpan(text: "$name ", style: textStyle1), WidgetSpan( child: Container( margin: EdgeInsets.only(top: 3, bottom: (Platform.isIOS ? 0 : 1)), padding: const EdgeInsets.only(left: 0, right: 4), child: Padding( padding: const EdgeInsets.only(bottom: 1.0), child: Text( "${type ?? ""}", style: textStyle2, ), ), )), ], ), softWrap: true, overflow: TextOverflow.ellipsis, maxLines: lines, ); return richText; } } void _openUrl(String url) async { if (await canLaunch(url)) { await launch(url); } else { throw 'could not launch $url'; } } } class _TextSpan extends StatefulWidget { @override State<StatefulWidget> createState() { return __TextSpanState(); } } class __TextSpanState extends State<_TextSpan> { @override Widget build(BuildContext context) { return Container(); } @override void initState() { super.initState(); log('__TextSpanState initState'); } @override void dispose() { log('__TextSpanState dispose'); super.dispose(); } } class _LessWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Text('_lessWidget'); } } class _CustomPaint extends CustomPainter { @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; } ParagraphBuilder builder; @override void paint(Canvas canvas, Size size) { final textStyle = TextStyle( color: Colors.black, fontSize: 30, ); final textSpan = TextSpan( text: 'Hello, world.', style: textStyle, ); final textPainter = TextPainter( text: textSpan, textDirection: TextDirection.ltr, maxLines: 2); textPainter.layout( minWidth: 0, maxWidth: size.width, ); // final offset = Offset(0, 0); // textPainter.paint(canvas, offset); builder = ParagraphBuilder(ParagraphStyle( fontSize: textStyle.fontSize, fontFamily: textStyle.fontFamily, fontStyle: textStyle.fontStyle, fontWeight: textStyle.fontWeight, textAlign: TextAlign.start, ellipsis: '...', maxLines: 2)); String t = 'Paragraph123456789012'; builder.addText('$t'); Paragraph paragraph = builder.build() ..layout(ParagraphConstraints(width: size.width)); if (paragraph.didExceedMaxLines) { while (true) { t = t.substring(0, t.length - 1); if (t == null || (t?.isEmpty ?? true)) { break; } var texts = paragraph.getBoxesForRange(t.length - 1, t.length).first; if (size.width - texts.right > 80) { break; } // print('$texts'); } } builder = ParagraphBuilder(ParagraphStyle( fontSize: textStyle.fontSize, fontFamily: textStyle.fontFamily, fontStyle: textStyle.fontStyle, fontWeight: textStyle.fontWeight, textAlign: TextAlign.start, ellipsis: '...', maxLines: 2)); builder.addText('$t...'); paragraph = builder.build() ..layout(ParagraphConstraints(width: size.width)); canvas.drawParagraph(paragraph, Offset(0, 0)); // TextPainter textPainter = TextPainter()..layout(maxWidth: 100); } } <|start_filename|>lib/scrollview/baseListenScrollViewOffset.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/3. /// class BaseListenScrollView extends StatefulWidget { @override _BaseListenScrollViewState createState() => _BaseListenScrollViewState(); } class _BaseListenScrollViewState extends State<BaseListenScrollView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('监听滚动'), ), body: _body(), ); } Widget _body() { return Stack( alignment: Alignment.center, children: <Widget>[ CupertinoScrollbar( // isAlwaysShown: false, child: NotificationListener<ScrollNotification>( onNotification: (ScrollNotification no) { var v = no.metrics.pixels / no.metrics.maxScrollExtent; setState(() { _value = v * 100; }); return true; }, child: ListView.builder( itemBuilder: _child, controller: _controller, itemCount: 50, ), ), ), CircleAvatar( radius: 40, child: Container( child: Text('${_value.toStringAsFixed(2)}%'), ), ) ], ); } Widget _child(ctx, int index) { return Container( height: 80, color: Colors.primaries[index % Colors.primaries.length], ); } ScrollController _controller; double _value = 0; @override void initState() { _controller = new ScrollController() ..addListener(() { print('${_controller.offset}'); }); super.initState(); } } <|start_filename|>lib/baseWidget/base_page_view_page.dart<|end_filename|> import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/baseWidget/base_page_view.dart'; class BasePageViewPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseSliderPageState(); } static String get routeName => '/BasePageViewPage'; } class _BaseSliderPageState extends State<BasePageViewPage> { @override void initState() { super.initState(); _height = 100; } double _height; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseSliderPageState'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: Text('滑动渐变pageView'), ), Container( alignment: Alignment.center, child: HotelPageView( widgetHeights: [100, 200, 150], pageCount: 3, initPage: 0, freshWidget: (fn) { if (mounted) { setState(fn); } }, freshHeightCallBack: (height) { scheduleMicrotask(() { if (mounted) { setState(() { _height = height; }); } }); }, itemBuilder: (ctx, index) { double height = [100.0, 200.0, 160.0][index]; return Container( height: height, child: Container( color: Colors.accents[(index + 1) % Colors.accents.length], height: height, ), color: Colors.accents[index % Colors.accents.length], ); }, ), height: _height, width: 200, ) ], ), ), ); } } <|start_filename|>lib/test.dart<|end_filename|> void runTest() { t2(); } void test1() { var items = ['Salad', 'Popcorn', 'T']; if (items.any((element) => element.contains('a'))) { print('At least one element contains "a"'); } if (items.any((element) => element.contains('T'))) { print('at lease one el contains T'); } if (items.every((element) => element.length >= 5)) { print('All elements have length >= 5'); } } t2() { var numbers = [1, 3, -2, 0, 4, 5]; var numbersUntilZero = numbers.takeWhile((number) => number != 0); print('Numbers until 0: $numbersUntilZero'); var numbersAfterZero = numbers.skipWhile((number) => number != 0); print('Numbers after 0: $numbersAfterZero'); Iterable iterable = numbers.map((e) { return e + 1; }); print(iterable.toString()); } <|start_filename|>lib/tips/redux_page.dart<|end_filename|> import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_redux/flutter_redux.dart'; import 'package:redux/redux.dart'; /// /// Created by fgyong on 2020/8/12. /// class BaseReduxPateRoute extends StatelessWidget { Store<int> store; @override Widget build(BuildContext context) { return _body(); } static String get routeName => 'BaseReduxPateRoute'; Widget _body() => BaseReduxPage(); } class BaseReduxPage extends StatefulWidget { BaseReduxPage({Key key}) : super(key: key); @override _BaseBaseReduxPageState createState() => _BaseBaseReduxPageState(); } class _MiddleWare<_Model> extends MiddlewareClass<_Model> { @override call(Store<_Model> store, action, next) { if (action == Actions.DecrementValue) {} print(action); next(action); } } class _BaseBaseReduxPageState extends State<BaseReduxPage> { String _build = ''; Store<_Model> store; mw(Store<_Model> store, action, NextDispatcher next) { print('1:${new DateTime.now()}: $action'); next(action); } mw2(Store<_Model> store, action, NextDispatcher next) { print('2:${new DateTime.now()}: $action'); next(action); } StreamController _streamController; _Model _model = _Model(); @override void initState() { store = Store(counterReducer, initialState: _Model(), middleware: [ mw, mw2, ]); store.onChange.listen((event) { print('init $event'); }); _streamController = StreamController.broadcast() ..stream.listen((event) { print('init${event}'); }); _streamController.add(counterReducer); super.initState(); } @override Widget build(BuildContext context) { _build += 'p1 build \n'; return StoreProvider( store: store, child: Scaffold( appBar: AppBar( title: Text('ReduxModel'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ OutlineButton( child: Text('change'), onPressed: () { _model = counterReducer(_model, Actions.DecrementValue); }, ), // StreamBuilder<_Model>( // stream: _streamController.stream, // builder: (context, snapshot) { // return Text(snapshot.data.value.toString()); // }, // ), Text(_build), StoreConnector<_Model, String>( converter: (store) => store.state.value.toString(), builder: (context, count) { _build += 's1'; return Text('value:$count'); }, ), StoreConnector<_Model, String>( converter: (store) => store.state.count.toString(), builder: (context, count) { _build += 's2'; return Text('count:$count'); }, ), StoreConnector<_Model, VoidCallback>( converter: (store) { return () => store.dispatch(Actions.IncrementValue); }, builder: (context, callback) { return OutlineButton( child: Text('+1 value'), onPressed: callback, ); }, ), StoreConnector<_Model, VoidCallback>( converter: (store) { return () => store.dispatch(Actions.DecrementValue); }, builder: (context, callback) { return OutlineButton( child: Text('-1 value'), onPressed: callback, ); }, ), StoreConnector<_Model, VoidCallback>( converter: (store) { return () => store.dispatch(Actions.IncrementCount); }, builder: (context, callback) { return OutlineButton( child: Text('+count'), onPressed: callback, ); }, ), StoreConnector<_Model, VoidCallback>( converter: (store) { return () => store.dispatch(Actions.DecrementCount); }, builder: (context, callback) { return OutlineButton( child: Text('-count'), onPressed: callback, ); }, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ OutlineButton( child: Icon(Icons.refresh), onPressed: () { if (mounted) setState(() {}); }, ), OutlineButton( child: Icon(Icons.clear), onPressed: () { if (mounted) setState(() { _build = ''; }); }, ), ], ) ], ), )), ); } } enum Actions { IncrementValue, IncrementCount, DecrementCount, DecrementValue } class _Model { int value, count; _Model({this.value, this.count}) { value ??= 0; count ??= 0; } } _Model counterReducer(_Model state, dynamic action) { // print(0); if (action == Actions.IncrementValue) { state.value += 1; return state; } else if (action == Actions.DecrementCount) { state.count -= 1; return state; } else if (action == Actions.IncrementCount) { state.count += 1; } else if (action == Actions.DecrementValue) { state.value -= 1; } return state; } <|start_filename|>lib/features/base_future_stream.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/8. /// class BaseFutureStream extends StatefulWidget { @override _BaseFutureStreamState createState() => _BaseFutureStreamState(); } class _BaseFutureStreamState extends State<BaseFutureStream> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('异步更新 Future Stream'), ), body: _bd(), ); } Widget _bd2() { return FutureBuilder( future: _getData(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { return Center( child: Text('error:${snapshot.error}'), ); } else { return Center( child: Text('data:${snapshot.data}'), ); } } else { return Center( child: CircularProgressIndicator(), ); } }, ); } Future<String> _getData() async { return Future.delayed(Duration(seconds: 2), () => "我是从互联网上获取的数据"); } Widget _bd() { return Center( child: StreamBuilder<int>( stream: _counter(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { return Center( child: Text('error:${snapshot.error}'), ); } else { return Center( child: Text('data:${snapshot.data}'), ); } } else { return Center( child: Text( 'state:${snapshot.connectionState},count:${snapshot.data}'), ); } }, ), ); } Stream<int> _counter() { return Stream.periodic(Duration(milliseconds: 500), (i) { return i; }); } @override void initState() { super.initState(); } } <|start_filename|>lib/baseWidget/baseIndicator.dart<|end_filename|> import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseIndicator extends StatefulWidget { _BaseIndicatorState createState() => _BaseIndicatorState(); } class _BaseIndicatorState extends State<BaseIndicator> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('进度指示器'), ), body: _body(), ); } Widget _body() { return Column( children: <Widget>[ SizedBox( height: 20, ), LinearProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.orange), backgroundColor: Colors.black12, ), SizedBox( height: 20, ), LinearProgressIndicator( // value: 0.1, valueColor: AlwaysStoppedAnimation(Colors.orange), backgroundColor: Colors.black12, ), SizedBox( height: 20, ), SizedBox( height: 20, width: 200, child: LinearProgressIndicator( // value: 0.1, valueColor: AlwaysStoppedAnimation(Colors.orange), backgroundColor: Colors.black12, ), ), SizedBox( height: 50, ), CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.orange), backgroundColor: Colors.greenAccent, ), SizedBox( height: 50, ), SizedBox( height: 200, width: 200, child: CircularProgressIndicator( valueColor: ColorTween(begin: Colors.grey, end: Colors.orange) .animate(_controller), backgroundColor: Colors.black12, strokeWidth: 10, ), ), SizedBox( height: 30, ), SizedBox( height: 200, width: 200, child: Stack( children: <Widget>[ Positioned.fill( child: CircularProgressIndicator( valueColor: ColorTween(begin: Colors.blue, end: Colors.orange) .animate(_controller), backgroundColor: Colors.black12, strokeWidth: 10, value: _value, ), ), Positioned.fill( child: Center( child: Text( '${(_value * 100).toDouble().toStringAsFixed(2)}%', style: TextStyle(fontSize: 20, color: Colors.orange), ), )) ], ), ), ], ); } AnimationController _controller; Timer _timer; double _value = 0; @override void initState() { _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 2000)) ..repeat(); _timer = Timer.periodic(Duration(milliseconds: 16), (t) { _value += 0.01; if (_value >= 1.0) { _value = 0; } setState(() {}); }); super.initState(); } @override void dispose() { _controller.dispose(); _timer?.cancel(); _timer = null; super.dispose(); } } <|start_filename|>lib/baseWidget/base_page_view.dart<|end_filename|> import 'dart:async'; import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; typedef FreshSuper = void Function(void Function() fn); typedef FreshHeightCallBack = void Function(double height); enum MovingDirection { left, right } // ignore: must_be_immutable class HotelPageView extends StatefulWidget { List<double> widgetHeights; int initPage; int pageCount; IndexedWidgetBuilder itemBuilder; FreshSuper freshWidget; FreshHeightCallBack freshHeightCallBack; PageController pageController; ScrollPhysics physics; Axis scrollDirection; final ValueChanged<int> onPageChanged; final bool opacityVisibility; HotelPageView( {@required this.widgetHeights, @required this.initPage, @required this.pageCount, @required this.itemBuilder, @required this.freshWidget, @required this.freshHeightCallBack, this.pageController, this.physics, this.opacityVisibility = true, this.onPageChanged, this.scrollDirection}) { assert(() { if ((widgetHeights?.length ?? 0) < pageCount) { return false; } return true; }(), '组件高度数量必须和页面数量一致 heights:${widgetHeights?.length} count:$pageCount'); assert(() { if (itemBuilder == null || freshWidget == null || freshHeightCallBack == null) { return false; } return true; }(), 'itemBuilder 、freshHeightCallBack、freshWidget 是必须的'); initPage ??= 0; // assert(() { // if (initPage >= (widgetHeights?.length ?? 0) || initPage < 0) { // return false; // } // return true; // }(), 'initPage 是范围有问题'); pageController ??= PageController(initialPage: initPage ?? 0); physics ??= const BouncingScrollPhysics(); scrollDirection ??= Axis.horizontal; widgetHeights ??= []; } @override State<StatefulWidget> createState() => _HotelPageViewState(); } class _HotelPageViewState extends State<HotelPageView> { @override Widget build(BuildContext context) { return Visibility( child: Container( alignment: Alignment.center, child: Listener( child: NotificationListener<ScrollNotification>( child: Container( height: _pageViewHeight, width: double.maxFinite, alignment: Alignment.center, child: PageView.builder( scrollDirection: widget.scrollDirection, controller: _pageController, itemCount: widget?.pageCount ?? 0, physics: widget.physics, onPageChanged: (index) { _currentIndex = index; print('index:$index'); // _pageController.animateToPage(index, // duration: Duration(milliseconds: 300), // curve: Curves.bounceIn); // }, // children: [_item(0), _item(1), _item(2)], // childrenDelegate: // SliverChildListDelegate([_item(0), _item(1), _item(2)]), // ) itemBuilder: (ctx, index) { return Opacity( opacity: widget?.opacityVisibility == true ? (index == _nextIndex ? alpha : 1 - alpha) : 1, child: widget?.itemBuilder(ctx, index), ); }), ), onNotification: (scr) { // print('notion:${_pageController.page.toString()}'); return false; }, ), onPointerUp: (touch) { _touching = false; print('onPointerUp ${touch.toString()}'); }, ), ), visible: (widget?.pageCount ?? 0) > 0 || (widget?.widgetHeights?.isNotEmpty ?? false), ); } int _currentIndex; int _nextIndex; double alpha; double _pageViewHeight; List<double> _heightList; PageController _pageController; MovingDirection movingDirection; double _oldOffset; bool _touching; @override void initState() { super.initState(); alpha = 0; movingDirection = MovingDirection.right; _pageController = widget.pageController; _currentIndex = widget.initPage ?? 0; _nextIndex = _currentIndex + 1; _pageViewHeight = widget?.widgetHeights[widget?.initPage]; _heightList = widget?.widgetHeights; if (widget?.freshHeightCallBack != null) { widget?.freshHeightCallBack(_pageViewHeight); } _pageController.addListener(() { var fr = () { if (_oldOffset == _pageController.page) { if (_touching != true) { _updateHeightToPageIndex(_currentIndex); } return; } _oldOffset = _pageController.page; _touching = true; //向左滑 if (_pageController.page > _currentIndex) { _currentIndex = _pageController.page.floor(); _nextIndex = _pageController.page.ceil(); movingDirection = MovingDirection.left; _pageViewHeight = _heightList[_currentIndex] + (_heightList[_nextIndex] - _heightList[_currentIndex]) * (_pageController.page - _currentIndex); alpha = (_pageController.page - _currentIndex); } //向右滑 else if (_pageController.page < _currentIndex) { _currentIndex = _pageController.page.ceil(); _nextIndex = _pageController.page.floor(); movingDirection = MovingDirection.right; double currentMinPage = _pageController.page; // if (_pageController.page < _nextIndex.toDouble()) { // currentMinPage = _nextIndex.toDouble(); // } // currentMinPage = _pageController.page; _pageViewHeight = _heightList[_currentIndex] + (_heightList[_nextIndex] - _heightList[_currentIndex]) * (_currentIndex - currentMinPage); alpha = (_currentIndex - currentMinPage); } if (alpha < 0) alpha = 0; if (alpha > 1.0) alpha = 1.0; if (alpha == double.nan) alpha = 0; if (widget?.freshHeightCallBack != null) { widget?.freshHeightCallBack(_pageViewHeight); } }; if (widget?.freshWidget != null) { widget?.freshWidget(fr); } }); } void _updateHeightToPageIndex(int index) { if (index < (widget?.widgetHeights?.length ?? 0)) { _pageViewHeight = widget?.widgetHeights[index]; if (movingDirection == MovingDirection.left) { _nextIndex = -1; alpha = 0; } else if (movingDirection == MovingDirection.right) { _nextIndex = index + 1; alpha = 0; } if (widget?.freshHeightCallBack != null) { widget?.freshHeightCallBack(_pageViewHeight); } } } @override void dispose() { // _pageController?.dispose(); super.dispose(); } } class Stu extends StatefulWidget { @override State<StatefulWidget> createState() { return _StuState(); } final Widget child; Stu({Key key, this.child}) : super(key: key); } class _StuState extends State<Stu> { @override Widget build(BuildContext context) { return Container( child: widget.child, ); } } <|start_filename|>lib/tips/scoped_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; /// /// Created by fgyong on 2020/8/12. /// class BaseScopedPateRoute extends StatelessWidget { @override Widget build(BuildContext context) { return ScopedModel<_BaseModel>( model: _BaseModel(), child: ScopedModel<_BaseModel2>( model: _BaseModel2(), child: _body(), ), ); } static String get routeName => 'BaseScopedPate'; Widget _body() => BaseScopedPate(); } class BaseScopedPate extends StatefulWidget { BaseScopedPate({Key key}) : super(key: key); @override _BaseScopedPateState createState() => _BaseScopedPateState(); } class _BaseScopedPateState extends State<BaseScopedPate> { String _build = ''; @override Widget build(BuildContext context) { _build += 'p1 build \n'; return Scaffold( appBar: AppBar( title: Text('ScopedModel'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(_build), ScopedModelDescendant<_BaseModel>( builder: (context, child, model) { _build += 'b1 '; return Center( child: Text('${model.count}'), ); }, child: Text('外部小部件'), ), ScopedModelDescendant<_BaseModel2>( builder: (context, child, model) { _build += 'b2 '; return Center( child: Text('${model.count}'), ); }, child: Text('外部小部件'), ), OutlineButton( child: Icon(Icons.add), onPressed: () { ScopedModel.of<_BaseModel>(context).add(1); }, ), OutlineButton( child: Text('-'), onPressed: () { ScopedModel.of<_BaseModel2>(context).add(-1); }, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ OutlineButton( child: Icon(Icons.refresh), onPressed: () { if (mounted) setState(() {}); }, ), OutlineButton( child: Icon(Icons.clear), onPressed: () { if (mounted) setState(() { _build = ''; }); }, ), ], ) ], ), )); } } class _BaseModel extends Model { int _count = 0; void add(int a) { _count += a; notifyListeners(); } int get count => _count; } class _BaseModel2 extends Model { int _count = 0; void add(int a) { _count += a; notifyListeners(); } int get count => _count; } <|start_filename|>lib/tips/revierpod/base_river_pod.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:get/get.dart'; import 'package:hooks_riverpod/all.dart'; class BaseRiverPodRoute extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseRiverPodRouteState(); } static String get routeName => '/BaseRiverPodRoute'; } class _BaseRiverPodRouteState extends State<BaseRiverPodRoute> { @override Widget build(BuildContext context) { final p = Provider((v) { return 123; }); return Scaffold( appBar: AppBar( title: Text('riverpod'), ), body: Center( child: Column( children: [ FlatButton( child: Text('数字加减'), onPressed: add, ) ], ), ), ); } void add() { Get.to(_PlusWidget()); } } class _PlusWidget extends HookWidget { final helloWorldProvider = StateProvider((_) => 0); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('plus')), body: Center( child: Consumer(builder: (context, watch, _) { final counter = watch(helloWorldProvider); /// 或者使用value 来读取state /// Provider((_) => 0) // final int value = useProvider(helloWorldProvider.select((value) => value.state%2==0)); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('加减数字《StateProvider》'), SizedBox( height: 10, ), Text(counter.state.toString()), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( color: Colors.grey, margin: EdgeInsets.all(10), child: FlatButton( child: Text('点我+1'), onPressed: () { counter.state++; }, ), ), Container( color: Colors.grey, margin: EdgeInsets.all(10), child: FlatButton( child: Text('点我-1'), onPressed: () { counter.state--; }, ), ), ], ), SizedBox( height: 30, ), Text('不可变Widget《Provider》'), _PlusNoChangeWidget(), ], ); }), ), ); } } class _PlusNoChangeWidget extends HookWidget { final helloWorldProvider = Provider((_) => '我不可变,用于读取配置'); @override Widget build(BuildContext context) { return Consumer(builder: (context, watch, _) { final counter = watch(helloWorldProvider); /// 或者使用value 来读取state /// Provider((_) => 0) /// final int value = useProvider(helloWorldProvider).state; return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(counter.toString()), ], ); }); } } <|start_filename|>lib/tips/img/base_img.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/9/2. /// class BaseImagePage extends StatefulWidget { BaseImagePage({Key key}) : super(key: key); @override _BaseImagePageState createState() => _BaseImagePageState(); static String get routeName => '/BaseImagePage'; } class _BaseImagePageState extends State<BaseImagePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('图片加载'), ), body: _body(), ); } Widget _body() { Image widget = Image.asset('img/2.png'); print('${widget.width} ${widget.height}'); print('${widget.toString()}'); return Center( child: Image.asset('img/2.png'), ); } } <|start_filename|>lib/features/base_notification.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/9. /// class BaseNotificationPage extends StatefulWidget { @override _BaseNotificationPageState createState() => _BaseNotificationPageState(); } class _BaseNotificationPageState extends State<BaseNotificationPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('通知'), ), body: _body2(), ); } Widget _body() { return NotificationListener<ScrollStartNotification>( onNotification: (notification) { switch (notification.runtimeType) { case ScrollStartNotification: print("开始滚动"); break; case ScrollUpdateNotification: print("正在滚动"); break; case ScrollEndNotification: print("滚动停止"); break; case OverscrollNotification: print("滚动到边界"); break; } return true; }, child: CupertinoScrollbar( child: SingleChildScrollView( child: Container( height: 2000, width: 400, color: Colors.orange, ), ), ), ); } int _code = 0; Widget _body2() { return NotificationListener<FyNotification>( onNotification: (notification) { print('我是外层监听'); return false; }, child: NotificationListener<FyNotification>( onNotification: (FyNotification notification) { setState(() { _code = notification.code; }); print('我是内层监听'); return false; }, child: Center( child: Column( children: <Widget>[ Builder( builder: (context) { return OutlineButton( child: Text('发送通知'), onPressed: () { FyNotification(code: 200).dispatch(context); }, ); }, ), Text('$_code'), ], ), ), ), ); } } class FyNotification extends Notification { int code; FyNotification({this.code}); } <|start_filename|>lib/tips/rx_dart/base_rxDart.dart<|end_filename|> import 'dart:async'; import 'dart:ffi'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:rxdart/rxdart.dart'; /// /// Created by fgyong on 2020/8/24. /// class BaseDartPage extends StatefulWidget { BaseDartPage({Key key}) : super(key: key); @override _BaseDartPageState createState() => _BaseDartPageState(); static String get routeName => '/BaseDartPage'; } class _BaseDartPageState extends State<BaseDartPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Stream'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[ TextField( onChanged: (v) { _streamController.add(v); }, ) ], ), ); } StreamController<String> _streamController; PublishSubject _subject; StreamSubscription<String> _subscription; @override void initState() { _streamController = StreamController(); // _subscription =StreamSubscription() _streamController.stream.listen((event) {}); _streamController.add('data'); // _subject = PublishSubject(); // _subject.stream..where((event) => event.length < 5); // // _subject.add('str'); // Rx.repeat<int>((repeatIndex) => Stream.value(repeatIndex)).listen((event) { // print(event); // }); // Rx.timer<int>(0, Duration(seconds: 1)).listen((event) { // print(event); // }); print(Zone.root.toString()); super.initState(); } } <|start_filename|>lib/baseWidget/animation_text_kit.dart<|end_filename|> import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class AnimationTextKitPage extends StatefulWidget { @override State<StatefulWidget> createState() => _AnimationTextKitState(); static String get routeName => '/AnimationTextKitPage'; } class _AnimationTextKitState extends State<AnimationTextKitPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('AnimationTextKit'), ), body: Column( children: [ _item(TypewriterAnimatedText( 'Hello world!', textStyle: const TextStyle( fontSize: 32.0, fontWeight: FontWeight.bold, ), speed: const Duration(milliseconds: 200), )), _item(ColorizeAnimatedText('ColorizeAnimatedText ', textStyle: const TextStyle( fontSize: 32.0, fontWeight: FontWeight.bold, ), colors: [Colors.red, Colors.blueAccent])), _item(FadeAnimatedText('FadeAnimatedText')), _item(FlickerAnimatedText('FadeAnimatedText')), _item(RotateAnimatedText('RotateAnimatedText')), _item(ScaleAnimatedText('ScaleAnimatedText')), TextLiquidFill(text: 'TextLiquidFill'), _item(TyperAnimatedText('TyperAnimatedText ', speed: Duration(milliseconds: 400))), ], ), ); } Widget _item(AnimatedText text) { return AnimatedTextKit( animatedTexts: [text], totalRepeatCount: 4, pause: const Duration(milliseconds: 500), displayFullTextOnTap: true, stopPauseOnTap: true, ); } } <|start_filename|>lib/tips/bloc/login_cubit/cubit/base_login_cubit.dart<|end_filename|> import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertest01/tips/bloc/login_cubit/model/base_login_model.dart'; import 'package:equatable/equatable.dart'; /// /// Created by fgyong on 2020/8/19. /// class LoginCubit extends Cubit<LoginModel> { LoginCubit(state) : super(state); void login() async { emit(state.copyWith(loginState: LoginState.isLoading)); await Future.delayed(Duration(seconds: 2)); if (state.btnVisiable == true) emit(state.copyWith(loginState: LoginState.success)); emit(state.copyWith(loginState: LoginState.faild)); } void logOut() async { emit(state.copyWith( name: null, pwd: null, )); } void changeName({String name}) { emit(state.copyWith( name: name, pwd: state.password, loginState: state.state)); } void changePassword({String pwd}) { emit(state.copyWith(name: state.name, pwd: pwd, loginState: state.state)); } /// /// 把所有之间集中于一个函数,只用不同的class来区分事件 /// 类似 mapToState void handleLoginEvents(LoginEvent event) { switch (event.runtimeType) { case LoginCubitChagneName: emit(state.copyWith(name: (event as LoginCubitChagneName).name)); break; case LoginCubitChagnePassword: emit(state.copyWith(pwd: (event as LoginCubitChagnePassword).password)); break; case LoginCubitSubmitted: emit(state.copyWith(loginState: LoginState.isLoading)); Future.delayed(Duration(seconds: 2)).then((_) { emit(state.copyWith( loginState: state.btnVisiable == true ? LoginState.success : LoginState.faild)); }); break; } } } /// 登陆相关的事件 abstract class LoginEvent extends Equatable { const LoginEvent(); @override List<Object> get props => []; } /// 修改密码 class LoginCubitChagnePassword extends LoginEvent { final String password; const LoginCubitChagnePassword({this.password}); @override List<Object> get props => [password]; } /// 修改账户 class LoginCubitChagneName extends LoginEvent { final String name; const LoginCubitChagneName({this.name}); @override List<Object> get props => [name]; } /// 提交事件 class LoginCubitSubmitted extends LoginEvent { const LoginCubitSubmitted(); @override List<Object> get props => []; } <|start_filename|>lib/features/base_eventbus.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/9. /// class BaseEventBus extends StatefulWidget { @override _BaseEventBusState createState() => _BaseEventBusState(); } class _BaseEventBusState extends State<BaseEventBus> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('事件总线'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[ Text(_str), OutlineButton( onPressed: () { // _bus.fire('test', '全局调用了一次哦'); Navigator.of(context) .push(MaterialPageRoute(builder: (c) => _Page2())); }, child: Text('点我push new page'), ) ], ), ); } String _str = ''; FYEventBus _bus; @override void initState() { _bus = FYEventBus() ..on('test', (string) { setState(() { _str += string; }); }); super.initState(); } @override void dispose() { _bus.off('test', null); super.dispose(); } } class _Page2 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('过来传值了'), ), body: _body(), ); } FYEventBus _bus = FYEventBus(); Widget _body() { return Center( child: Column( children: <Widget>[ OutlineButton( onPressed: () { _bus.fire('test', '\n点我发送请求A'); }, child: Text('点我发送请求A'), ), OutlineButton( onPressed: () { _bus.fire('test', '\n点我发送请求B'); }, child: Text('点我发送请求B'), ) ], ), ); } } typedef EventBusCallback = void Function(Object object); class FYEventBus { static FYEventBus _bus = new FYEventBus._(); FYEventBus._(); /// 工厂构造 单例模式 factory FYEventBus() => _bus; //保存全局 var _emap = new Map<Object, List<EventBusCallback>>(); /// 监听回调 void on(eventName, EventBusCallback callback) { if (eventName == null || callback == null) return; _emap[eventName] ??= new List(); if (_emap[eventName].contains(callback) == false) { _emap[eventName].add(callback); } } /// 删除回调 void off(eventName, EventBusCallback callback) { if (eventName == null || callback == null) return; if (callback == null) { _emap[eventName] = null; } else { _emap[eventName].remove(callback); } } /// 发送回调 void fire(eventName, [arg]) { if (eventName == null) return; var list = _emap[eventName]; if (list == null) return; for (var j = list.length - 1; j >= 0; --j) { var o = list[j]; o(arg); } } } <|start_filename|>lib/features/base_gesturedetetor.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/9. /// class BaseGesuredetetor extends StatefulWidget { @override _BaseGesuredetetorState createState() => _BaseGesuredetetorState(); } class _BaseGesuredetetorState extends State<BaseGesuredetetor> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('手势识别'), ), body: _body3(), ); } String _string; double _left = 0, _top = 0; Offset _offset = Offset(0, 0); double _width = 300, _height = 300; Widget _body() { return Stack( children: <Widget>[ GestureDetector( child: Container( width: _width, height: _height, margin: EdgeInsets.only( left: _left > 0 ? _left : 0, top: _top < 0 ? 0 : _top), child: Text(_string == null ? '点击我识别手势' : _string), color: Colors.orange, ), onScaleUpdate: (ScaleUpdateDetails detail) { setState(() { _width = 200 * detail.scale.clamp(0.5, 2); _height = _width; }); }, ), ], ); } bool _selected = false; Widget _body2() { return Center( child: Text.rich( TextSpan(text: '你好,', children: [ TextSpan( text: 'Flutter', recognizer: _gestureRecognizer(), style: TextStyle( color: _selected ? Colors.blue : Colors.orange, fontSize: _selected ? 30 : 20)) ]), ), ); } GestureRecognizer _gestureRecognizer() { return TapGestureRecognizer() ..onTap = () { setState(() { _selected = !_selected; }); }; } String _moveDetail = ''; Widget _body3() { return Stack( children: <Widget>[ GestureDetector( child: Container( width: _width, height: _height, margin: EdgeInsets.only( left: _left > 0 ? _left : 0, top: _top < 0 ? 0 : _top), child: Text( (_string == null ? '点击我识别手势' : _string) + _moveDetail ?? ''), color: Colors.orange, ), onTap: () { setState(() { _string += '点击手势'; }); }, onTapUp: (TapUpDetails detail) { setState(() { _string += 'up:' + detail.toString(); }); }, onHorizontalDragUpdate: (DragUpdateDetails detail) { setState(() { _moveDetail = detail.toString(); }); }, ), ], ); } } <|start_filename|>lib/tips/bloc/login_cubit/bloc_observer/bloc_observer.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; /// /// Created by fgyong on 2020/8/19. /// class DefaultBlocObserver extends BlocObserver { @override void onChange(Cubit cubit, Change change) { if (kDebugMode) print( '${cubit.toString()} new:${change.toString()} old:${cubit.state.toString()}'); super.onChange(cubit, change); } } <|start_filename|>lib/page_view/page_view_custom.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; typedef FreshSuper = void Function(void Function() fn); typedef FreshHeightCallBack = void Function(double height); // ignore: must_be_immutable class CustomPageView extends StatefulWidget { List<double> widgetHeights; int initPage; int pageCount; @required IndexedWidgetBuilder itemBuilder; FreshSuper freshWidget; FreshHeightCallBack freshHeightCallBack; final ValueChanged<int> onPageChanged; final bool opacityVisibility; CustomPageView( {@required this.widgetHeights, @required this.initPage, @required this.pageCount, @required this.itemBuilder, @required this.freshWidget, @required this.freshHeightCallBack, this.opacityVisibility = true, this.onPageChanged}) { assert(() { if ((widgetHeights?.length ?? 0) != pageCount) { return false; } return true; }(), '组件高度数量必须和页面数量一致'); assert(() { if (itemBuilder == null || freshWidget == null || freshHeightCallBack == null) { return false; } return true; }(), 'itemBuilder 、freshHeightCallBack、freshWidget 是必须的'); initPage ??= 0; assert(() { if (initPage >= (widgetHeights?.length ?? 0) || initPage < 0) { return false; } return true; }(), 'initPage 是范围有问题'); } @override State<StatefulWidget> createState() => _CustomPageViewState(); static String get routeName => '/page_view'; } class _CustomPageViewState extends State<CustomPageView> { @override Widget build(BuildContext context) { return Container( alignment: Alignment.center, color: Colors.white, child: CustomScrollView( slivers: [ SliverToBoxAdapter( child: Container( height: _pageViewHeight, width: double.maxFinite, alignment: Alignment.center, child: PageView.builder( controller: _pageController, itemCount: widget?.pageCount, onPageChanged: (index) { _currentIndex = index; if (widget?.onPageChanged != null) widget?.onPageChanged(index); }, itemBuilder: (ctx, index) { return Opacity( opacity: widget?.opacityVisibility == true ? (index == _nextIndex ? alpha : 1 - alpha) : 1, child: widget?.itemBuilder(ctx, index), ); }, ), ), ), ], ), ); } int _currentIndex; int _nextIndex; double alpha; double _pageViewHeight; List<double> _heightList; PageController _pageController; @override void initState() { super.initState(); alpha = 0; _pageController = PageController(initialPage: widget?.initPage ?? 0); _currentIndex = widget.initPage ?? 0; _nextIndex = _currentIndex + 1; _pageViewHeight = widget?.widgetHeights[widget?.initPage]; _heightList = widget?.widgetHeights; if (widget?.freshHeightCallBack != null) { widget?.freshHeightCallBack(_pageViewHeight); } _pageController.addListener(() { var fr = () { //向左滑 if (_pageController.page > _currentIndex) { _currentIndex = _pageController.page.floor(); _nextIndex = _pageController.page.ceil(); _pageViewHeight = _heightList[_currentIndex] + (_heightList[_nextIndex] - _heightList[_currentIndex]) * (_pageController.page - _currentIndex); alpha = (_pageController.page - _currentIndex); } //向右滑 else if (_pageController.page < _currentIndex) { _currentIndex = _pageController.page.ceil(); _nextIndex = _pageController.page.floor(); _pageViewHeight = _heightList[_currentIndex] + (_heightList[_nextIndex] - _heightList[_currentIndex]) * (_currentIndex - _pageController.page); alpha = (_currentIndex - _pageController.page); } if (alpha < 0) alpha = 0; if (alpha > 1.0) alpha = 1.0; if (alpha == double.nan) alpha = 0; if (widget?.freshHeightCallBack != null) { widget?.freshHeightCallBack(_pageViewHeight); } }; if (widget?.freshWidget != null) { widget?.freshWidget(fr); } }); } @override void dispose() { _pageController?.dispose(); super.dispose(); } } <|start_filename|>lib/baseWidget/baseSwitch.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; class BaseSwitch extends StatefulWidget { @override State<StatefulWidget> createState() { return BaseSwitchState(); } } class BaseSwitchState extends State<BaseSwitch> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('弹框'), ), body: Container( margin: EdgeInsets.all(30), child: _body(), ), ); } bool _state1 = false, _state2 = true, _s3 = true, _s4 = false; bool _checkList1 = false, _checkList2 = false; RadioC _radio1 = RadioC.unselected, _radio2 = RadioC.unselected; Widget _body() { Widget w = Column( children: <Widget>[ Container( height: 30, child: Text('CupertinoSwitchState:$_state1'), ), CupertinoSwitch( value: _state1, onChanged: (v) { setState(() { _state1 = v; }); }, trackColor: Colors.orange, activeColor: Colors.greenAccent, ), Container( height: 30, child: Text('SwitchStates:$_state2'), ), Switch( value: _state2, onChanged: (v) { setState(() { _state2 = v; }); }, ), Container( height: 30, child: Text('Checkbox'), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Checkbox( value: _s3, onChanged: (v) { setState(() { _s3 = v; }); }, ), Checkbox( value: _s4, onChanged: (v) { setState(() { _s4 = v; }); }, ) ], ), CheckboxListTile( onChanged: (v) { setState(() { _checkList1 = v; }); }, title: Text('checkListTitle box is leading'), value: _checkList1, controlAffinity: ListTileControlAffinity.leading, secondary: Icon(Icons.message), activeColor: Colors.orange, checkColor: Colors.blue, subtitle: Text('我是subtitle'), dense: true, ), CheckboxListTile( onChanged: (v) { setState(() { _checkList2 = v; }); }, title: Text('checkListTitle box is trailing'), value: _checkList2, secondary: Icon(Icons.message), controlAffinity: ListTileControlAffinity.leading, ), RadioListTile<RadioC>( title: Text('radiotitle'), subtitle: Text('subtitle'), secondary: Icon(Icons.list), value: RadioC.selected, groupValue: _radio1, activeColor: Colors.red, onChanged: (v) { print('$v'); setState(() { _radio1 = v; }); }, ), RadioListTile<RadioC>( title: Text('radiotitle'), subtitle: Text('subtitle'), secondary: Icon(Icons.list), value: RadioC.unselected, groupValue: _radio2, activeColor: Colors.red, onChanged: (v) { print('$v'); setState(() { _radio2 = v; }); }, ), LabeledRadio( label: 'This is the first label text', padding: const EdgeInsets.symmetric(horizontal: 5.0), value: true, groupValue: _isRadioSelected, onChanged: (bool newValue) { setState(() { _isRadioSelected = newValue; }); }, ), LabeledRadio( label: 'This is the second label text', padding: const EdgeInsets.symmetric(horizontal: 5.0), value: false, groupValue: _isRadioSelected, onChanged: (bool newValue) { setState(() { _isRadioSelected = newValue; }); }, ), LinkedLabelRadio( label: 'First tappable label text', padding: EdgeInsets.symmetric(horizontal: 5.0), value: true, groupValue: _isRadioSelected2, onChanged: (bool newValue) { setState(() { _isRadioSelected2 = newValue; }); }, ), LinkedLabelRadio( label: 'Second tappable label text', padding: EdgeInsets.symmetric(horizontal: 5.0), value: false, groupValue: _isRadioSelected2, onChanged: (bool newValue) { setState(() { _isRadioSelected2 = newValue; }); }, ), ], ); return w; } } enum RadioC { selected, unselected, unknow, } class LinkedLabelRadio extends StatelessWidget { const LinkedLabelRadio({ this.label, this.padding, this.groupValue, this.value, this.onChanged, }); final String label; final EdgeInsets padding; final bool groupValue; final bool value; final Function onChanged; @override Widget build(BuildContext context) { return Padding( padding: padding, child: Row( children: <Widget>[ Radio<bool>( groupValue: groupValue, value: value, onChanged: (bool newValue) { onChanged(newValue); }), RichText( text: TextSpan( text: label, style: TextStyle( color: Colors.blueAccent, decoration: TextDecoration.underline, ), recognizer: TapGestureRecognizer() ..onTap = () { print('Label has been tapped.'); }, ), ), ], ), ); } } bool _isRadioSelected = false; bool _isRadioSelected2 = false; class LabeledRadio extends StatelessWidget { const LabeledRadio({ this.label, this.padding, this.groupValue, this.value, this.onChanged, }); final String label; final EdgeInsets padding; final bool groupValue; final bool value; final Function onChanged; @override Widget build(BuildContext context) { return InkWell( onTap: () { if (value != groupValue) onChanged(value); }, child: Padding( padding: padding, child: Row( children: <Widget>[ Radio<bool>( groupValue: groupValue, value: value, onChanged: (bool newValue) { onChanged(newValue); }, ), Text(label), ], ), ), ); } } <|start_filename|>lib/file_and_http/model/user_entity.dart<|end_filename|> import 'package:fluttertest01/generated/json/base/json_convert_content.dart'; import 'package:fluttertest01/generated/json/base/json_filed.dart'; class UserEntity with JsonConvert<UserEntity> { @JSONField(name: "list") List<UserList> xList; } class UserList with JsonConvert<UserList> { String name; } <|start_filename|>lib/u3d/u3d_page.dart<|end_filename|> /// /// Created by fgyong on 7/20/21. /// import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseU3DPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseU3DPageState(); } static String get routeName => '/BaseU3DPage'; } class _BaseU3DPageState extends State<BaseU3DPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseU3DPage'), ), body: _body(), ); } Widget _body() { return Container( child: Text('123'), ); } } <|start_filename|>lib/layout/base_row_and_column.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseRowAndColumn extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('线性布局'), ), body: SafeArea( child: _bd3(), )); } Widget _bd2() { return Column( children: <Widget>[ _column(MainAxisAlignment.start, CrossAxisAlignment.start), _column(MainAxisAlignment.center, CrossAxisAlignment.start), _column(MainAxisAlignment.end, CrossAxisAlignment.start), _column(MainAxisAlignment.spaceAround, CrossAxisAlignment.start), _column(MainAxisAlignment.spaceEvenly, CrossAxisAlignment.start), _column(MainAxisAlignment.spaceBetween, CrossAxisAlignment.start), _column(MainAxisAlignment.start, CrossAxisAlignment.start), _column(MainAxisAlignment.start, CrossAxisAlignment.center), _column(MainAxisAlignment.start, CrossAxisAlignment.end), _column(MainAxisAlignment.start, CrossAxisAlignment.stretch), // _column(MainAxisAlignment.start, CrossAxisAlignment.start), ], ); } Widget _column(MainAxisAlignment mainAxisAlignment, CrossAxisAlignment crossAxisAlignment) { return Container( margin: EdgeInsets.symmetric(vertical: 20), color: Colors.black12, height: 105, child: Column( mainAxisAlignment: mainAxisAlignment, crossAxisAlignment: crossAxisAlignment, children: <Widget>[ Text('$mainAxisAlignment $crossAxisAlignment'), Container( color: Colors.blue, child: Text('Hello,'), ), Container( color: Colors.red, child: Text('I am'), ), Container( color: Colors.orange, child: Text('<NAME>'), ), ], ), ); } Widget _bd() { return Column( children: <Widget>[ _body(MainAxisAlignment.start, CrossAxisAlignment.start), _body(MainAxisAlignment.end, CrossAxisAlignment.start), _body(MainAxisAlignment.spaceBetween, CrossAxisAlignment.start), _body(MainAxisAlignment.spaceEvenly, CrossAxisAlignment.start), _body(MainAxisAlignment.spaceAround, CrossAxisAlignment.start), _body(MainAxisAlignment.center, CrossAxisAlignment.start), _body(MainAxisAlignment.center, CrossAxisAlignment.start), _body(MainAxisAlignment.center, CrossAxisAlignment.stretch), _body(MainAxisAlignment.center, CrossAxisAlignment.end), ], ); } Widget _body(MainAxisAlignment mainAxisAlignment, CrossAxisAlignment crossAxisAlignment) { return Container( margin: EdgeInsets.symmetric(vertical: 10), child: Column( children: <Widget>[ Text('$mainAxisAlignment $crossAxisAlignment'), Container( height: 50, child: Row( mainAxisAlignment: mainAxisAlignment, crossAxisAlignment: crossAxisAlignment, children: <Widget>[ Container( color: Colors.blue, child: Text('Hello,'), ), Container( color: Colors.red, child: Text('I am'), ), Container( color: Colors.orange, child: Text('<NAME>'), ), ], ), color: Colors.black12, ) ], ), ); } Widget _bd3() { return Container( child: Column( children: <Widget>[ Expanded( child: Container( margin: EdgeInsets.all(20), color: Colors.red, child: Text('Are you OK?'), ), ), ], ), ); } } <|start_filename|>lib/tips/base_connect.dart<|end_filename|> import 'package:connectivity/connectivity.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BaseNetWorkConnect extends StatefulWidget { @override State<StatefulWidget> createState() => _BaseNetWorkConnectState(); static String get routeName => '/_BaseNetWorkConnectState'; } class _BaseNetWorkConnectState extends State<BaseNetWorkConnect> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseNetWorkConnect'), ), body: _body(), ); } String ret = ''; Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [TextButton(onPressed: check, child: Text('刷新 $ret'))], ), ); } Connectivity connect; @override void initState() { super.initState(); connect = Connectivity(); check(); connect.onConnectivityChanged.listen((event) { statusToStr(event); if (mounted) setState(() {}); }, onDone: () { print('done'); }, onError: (error) { print(error); }); } void check() async { connect.checkConnectivity().then((event) { statusToStr(event); if (mounted) setState(() {}); }); } String statusToStr(ConnectivityResult event) { switch (event) { case ConnectivityResult.none: ret = 'none'; break; case ConnectivityResult.wifi: ret = 'wifi'; break; case ConnectivityResult.mobile: ret = 'mobile'; break; } return ret; } } <|start_filename|>lib/tips/wechat_view.dart<|end_filename|> import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/10. /// class WeChatSoundWidget extends StatefulWidget { WeChatSoundWidget({Key key}) : super(key: key); @override _FYTabbarWidgetState createState() => _FYTabbarWidgetState(); } class _FYTabbarWidgetState extends State<WeChatSoundWidget> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('tabbar'), ), body: _body(), ); } bool _isStop = false; Widget _body() { return Center( child: Column( children: <Widget>[ FlatButton( child: Text( 'push stop', ), onPressed: () { setState(() { _isStop = !_isStop; }); }, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SoundWidget( color: Colors.green, bgColor: Colors.blueAccent, stop: _isStop, stopColor: Colors.red, lineWidth: 4, radius: 100, lines: 3, duration: Duration(seconds: 3), soundDirection: SoundDirection.top, ), ], ), Row( children: <Widget>[ SoundWidget( color: Colors.green, bgColor: Colors.blueAccent, stop: _isStop, stopColor: Colors.red, lineWidth: 4, radius: 100, lines: 3, duration: Duration(seconds: 3), soundDirection: SoundDirection.left, ), SoundWidget( color: Colors.green, bgColor: Colors.blueAccent, stop: _isStop, stopColor: Colors.red, lineWidth: 4, radius: 100, lines: 3, duration: Duration(seconds: 3), soundDirection: SoundDirection.right, ) ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SoundWidget( color: Colors.green, bgColor: Colors.blueAccent, stop: _isStop, stopColor: Colors.red, lineWidth: 4, radius: 100, lines: 3, duration: Duration(seconds: 3), soundDirection: SoundDirection.down, ), ], ) ], ), ); } @override void initState() { super.initState(); } } // ignore: must_be_immutable class SoundWidget extends StatefulWidget { Color color; Color bgColor; Color stopColor; bool stop; double radius; double lineWidth; double startAngle, sweepAngle; int lines; Duration duration; bool centerFill; SoundDirection soundDirection; SoundWidget( {Key key, this.color, this.bgColor, @required this.stop, this.stopColor, this.radius, this.lineWidth, this.startAngle, this.sweepAngle, this.lines, this.duration, this.centerFill, this.soundDirection}) { this.color ??= Colors.green; stopColor ??= Colors.black12; radius ??= 50; bgColor ??= Colors.black12; lineWidth ??= 4; duration ??= Duration(seconds: 1); centerFill ??= true; } @override _FYSoundWidgetState createState() => _FYSoundWidgetState(); } class _FYSoundWidgetState extends State<SoundWidget> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return _body(); } Widget _body() { return Center( child: AnimatedBuilder( animation: _animationController, builder: (ctx, child) { return CustomPaint( painter: _CustomSoundWidget( value: _animationController.value, color: widget.color, bgColor: widget.bgColor, stop: widget.stop, stopColor: widget.stopColor, lineWidth: widget.lineWidth, lines: widget.lines, centerFill: widget.centerFill, startAngle: widget.startAngle, sweepAngle: widget.sweepAngle, soundDirection: widget.soundDirection), size: Size(widget.radius, widget.radius), ); }, ), ); } AnimationController _animationController; @override void initState() { _animationController = AnimationController(vsync: this, duration: widget.duration)..repeat(); super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); } } enum SoundDirection { top, down, left, right } class _CustomSoundWidget extends CustomPainter { double value; double lineWidth; Color color; Color bgColor; Color stopColor; bool stop; double startAngle, sweepAngle; int lines; bool centerFill; SoundDirection soundDirection; _CustomSoundWidget( {this.value = 0.0, this.color, this.bgColor, this.stop, this.stopColor, this.lineWidth, this.startAngle, this.sweepAngle, this.lines, this.centerFill, this.soundDirection}) { if (startAngle == null && sweepAngle == null) { soundDirection ??= SoundDirection.left; switch (soundDirection) { case SoundDirection.left: startAngle = -pi / 4 * 3; sweepAngle = (-pi / 2); break; case SoundDirection.top: startAngle = -pi / 4 * 3; sweepAngle = (pi / 2); break; case SoundDirection.right: startAngle = -(pi / 4); sweepAngle = pi / 2; break; case SoundDirection.down: startAngle = pi / 4 * 3; sweepAngle = (-pi / 2); break; } } lines ??= 3; // lines += 1; centerFill ??= true; } Paint _paint; @override void paint(Canvas canvas, Size size) { _paint = Paint() ..strokeWidth = lineWidth ?? 4 ..style = PaintingStyle.stroke ..color = this.color; double sep = 0.9 / lines; for (var i = 0; i < lines; ++i) { if (value >= (0.9 - sep * i)) { _paint.color = this.color; } else { _paint.color = this.bgColor; } if (stop == true) { _paint.color = stopColor; } double wh = (1 - sep * i); bool point = false; if (i == lines - 1 && centerFill == true) { point = true; _paint.style = PaintingStyle.fill; } else { _paint.style = PaintingStyle.stroke; } var rect = Rect.fromLTWH(0, 0, size.width * wh, size.height * wh); canvas.drawArc(rect, startAngle, sweepAngle, point, _paint); } } @override bool shouldRepaint(_CustomSoundWidget oldDelegate) { return oldDelegate.value != value || this.stop != oldDelegate.stop || oldDelegate.color != color || oldDelegate.bgColor != bgColor || oldDelegate.startAngle != startAngle || oldDelegate.soundDirection != soundDirection || oldDelegate.sweepAngle != sweepAngle; } } <|start_filename|>lib/tips/async_and_async*.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:io'; /// /// Created by fgyong on 2020/7/29. /// class BaseAsync extends StatefulWidget { BaseAsync({Key key}) : super(key: key); @override _BaseAsyncState createState() => _BaseAsyncState(); } class _BaseAsyncState extends State<BaseAsync> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('异步与同步数据流'), ), body: _body(), ); } Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Expanded( child: Text('${stringBuffer.toString()}'), ) ], ), ); } int _count = 0; Future<String> _toString() async { var s = await _stream().map((event) => event.toString()).join('|'); return s; } Future<List> _toList() async { var s = await _stream().toList(); return s; } Stream<int> _getDataFromServer() { return null; } /// 异步数据流 Stream<int> _stream() async* { if (_count < 10) { yield _count++; await Future.delayed(Duration(seconds: 1)); sleep(Duration(seconds: 1)); yield* _getDataFromServer(); } } StringBuffer stringBuffer; /// 同步获取数据 Iterable<int> _streamIterable() sync* { if (_count < 20) { yield _count; yield* _streamIterable(); } } @override void initState() { stringBuffer = StringBuffer(); setState(() { _toString().then((value) { stringBuffer.write(value); }); }); // _stream().listen((event) { //// stringBuffer.write(event); ////// stringBuffer.writeln(event) //// setState(() {}); //// print(event); // }); super.initState(); } } <|start_filename|>lib/tips/hive/base_hive.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/tips/hive/hive_person.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; import 'dart:core'; /// /// Created by fgyong on 2020/10/10. /// class BaseHive extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseHive(); } static String get routeName => '/BaseHive'; } class _BaseHive extends State<BaseHive> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('hive'), ), body: Center( child: Column( children: [ OutlineButton( child: Text('add'), onPressed: add, ), OutlineButton( child: Text('查询'), onPressed: _query, ), OutlineButton( child: Text('清空'), onPressed: _clear, ), ], ), ), ); } void _clear() async { // if (Hive.isBoxOpen('testBox') == false) { // await Hive.openBox('testBox', path: (await getTemporaryDirectory()).path); // } // var box = await Hive.box('testBox'); // await box.deleteFromDisk(); // Symbol lib = new Symbol('Person_lib'); // Symbol className = Symbol('Person'); } // void testSymbol(Symbol lib, Symbol className) {} void add() async { if (Hive.isAdapterRegistered(PersonAdapter().typeId) == false) { Hive.registerAdapter(PersonAdapter()); } if (Hive.isBoxOpen('testBox') == false) { await Hive.openBox('testBox', path: (await getTemporaryDirectory()).path); } var box = await Hive.box('testBox'); box.put('name', 'David'); box.add(Person('laowng')); box.add(Person('老李')); print('Name: ${box.get('name')}'); await box.close(); // printLog(); } void _query() async { if (Hive.isBoxOpen('testBox') == false) { await Hive.close(); await Hive.openBox<Person>('testBox', path: (await getTemporaryDirectory()).path); } var box = Hive.box<Person>('testBox'); box.values.forEach((element) { print('${element.toString()}'); }); } void printLog() async { var box = await Hive.openBox('testBox', path: (await getTemporaryDirectory()).path); print('${box.path}'); box.values.forEach((element) { print('${element.toString()}'); }); } @override void initState() { super.initState(); } } <|start_filename|>lib/generated/json/user_entity_helper.dart<|end_filename|> import 'package:fluttertest01/file_and_http/model/user_entity.dart'; userEntityFromJson(UserEntity data, Map<String, dynamic> json) { if (json['list'] != null) { data.xList = new List<UserList>(); (json['list'] as List).forEach((v) { data.xList.add(new UserList().fromJson(v)); }); } return data; } Map<String, dynamic> userEntityToJson(UserEntity entity) { final Map<String, dynamic> data = new Map<String, dynamic>(); if (entity.xList != null) { data['list'] = entity.xList.map((v) => v.toJson()).toList(); } return data; } userListFromJson(UserList data, Map<String, dynamic> json) { if (json['name'] != null) { data.name = json['name']?.toString(); } return data; } Map<String, dynamic> userListToJson(UserList entity) { final Map<String, dynamic> data = new Map<String, dynamic>(); data['name'] = entity.name; return data; } <|start_filename|>lib/animation/base_pageRoute.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/21. /// class BasePageRoute extends StatefulWidget { BasePageRoute({Key key}) : super(key: key); @override _BasePageRouteState createState() => _BasePageRouteState(); } class _BasePageRouteState extends State<BasePageRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('过度动画'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[ OutlineButton( child: Text( 'push 系统默认', ), onPressed: _pushDefault, ), OutlineButton( child: Text( 'push 自定义路由切换动画 渐入动画', ), onPressed: _pushCustom, ), OutlineButton( child: Text( 'push 自定义路由切换动画 大小', ), onPressed: _pushCustom2, ), OutlineButton( child: Text( 'push 自己封装渐入 动画', ), onPressed: _push3, ), ], ), ); } /// 默认动画 void _pushDefault() { Navigator.of(context).push(MaterialPageRoute(builder: (ctx) => PageB())); } /// 自定义动画 void _pushCustom() { Navigator.push( context, PageRouteBuilder( transitionDuration: Duration(milliseconds: 300), pageBuilder: (BuildContext context, Animation<double> a1, Animation<double> a2) { return new FadeTransition( opacity: a1, child: PageB(), ); })); } void _pushCustom2() { Navigator.push( context, PageRouteBuilder( transitionDuration: Duration(milliseconds: 300), pageBuilder: (BuildContext context, Animation<double> a1, Animation<double> a2) { return PageB(); }, transitionsBuilder: _transitionsBuilder)); } /// 过度动画处理函数 Widget _transitionsBuilder(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return new ScaleTransition( scale: animation, child: child, ); } void _push3() { Navigator.push( context, FadeTransition2(pageBuilder: (context, a, b) => PageB())); } } class PageB extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(''), ), body: Center( child: Container( width: 200, height: 200, color: Colors.orangeAccent, ), ), ); } } Widget _defaultTransitionsBuilder( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return child; } class FadeTransition2 extends PageRoute { /// 自己实现转场的动画 FadeTransition2({ RouteSettings settings, @required this.pageBuilder, this.transitionsBuilder = _defaultTransitionsBuilder, this.transitionDuration = const Duration(milliseconds: 300), this.opaque = true, this.barrierDismissible = false, this.barrierColor, this.barrierLabel, this.maintainState = true, bool fullscreenDialog = false, }) : assert(pageBuilder != null), assert(transitionsBuilder != null), assert(opaque != null), assert(barrierDismissible != null), assert(maintainState != null), assert(fullscreenDialog != null), super(settings: settings, fullscreenDialog: fullscreenDialog); /// Used build the route's primary contents. /// /// See [ModalRoute.buildPage] for complete definition of the parameters. final RoutePageBuilder pageBuilder; /// Used to build the route's transitions. /// /// See [ModalRoute.buildTransitions] for complete definition of the parameters. final RouteTransitionsBuilder transitionsBuilder; @override final Duration transitionDuration; @override final bool opaque; @override final bool barrierDismissible; @override final Color barrierColor; @override final String barrierLabel; @override final bool maintainState; @override Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return pageBuilder(context, animation, secondaryAnimation); } @override Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { if (isActive) { return FadeTransition( child: child, opacity: animation, ); } else { return Padding( padding: EdgeInsets.zero, child: child, ); } } } <|start_filename|>lib/animation/base_animation_switch.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/23. /// class BaseAnimationSwitcher extends StatefulWidget { BaseAnimationSwitcher({Key key}) : super(key: key); @override _BaseAnimationSwitcherState createState() => _BaseAnimationSwitcherState(); } class _BaseAnimationSwitcherState extends State<BaseAnimationSwitcher> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('AnimationSwitcher'), ), body: _body(), ); } int _count = 0; int _count2 = 0; Ax _ax = Ax.ttb; void _add() { setState(() { _count += 1; }); } void _plus() { setState(() { _count2 += 1; }); } void _down() { setState(() { // _ax = Ax.ttb; _count -= 1; }); } Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ClipRRect( child: AnimatedSwitcher( child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(50)), key: Key(_count.toString()), child: Container( width: 100, height: 100, color: Colors.orange, alignment: Alignment.center, child: Text( '$_count', ), ), ), duration: Duration(milliseconds: 300), transitionBuilder: (Widget child, Animation<double> animation) { return MySliderTransitiion( position: animation, child: child, ax: _ax, ); }, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( child: Text('+'), onPressed: _add, ), TextButton(child: Text('-'), onPressed: _down), ], ), _row(), ClipRRect( child: AnimatedSwitcher( child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(50)), key: Key(_count2.toString()), child: Container( width: 100, height: 100, color: Colors.accents[_count2 % Colors.accents.length], alignment: Alignment.center, child: Text( '$_count2', style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), ), ), ), duration: Duration(milliseconds: 1300), transitionBuilder: (Widget child, Animation<double> animation) { return FadeTransition( opacity: animation, child: child, ); }, ), ), TextButton( child: Text('一个widget过度\n成另外一个widget\n+数字'), onPressed: _plus, ), ], ), ); } Widget _row() { return Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ OutlineButton( child: Text('↑'), textColor: _ax == Ax.btt ? Colors.red : Colors.black, onPressed: () { setState(() { _ax = Ax.btt; }); }, ), OutlineButton( child: Text('→'), textColor: _ax == Ax.ltr ? Colors.red : Colors.black, onPressed: () { setState(() { _ax = Ax.ltr; }); }, ), OutlineButton( child: Text('↓'), textColor: _ax == Ax.ttb ? Colors.red : Colors.black, onPressed: () { setState(() { _ax = Ax.ttb; }); }, ), OutlineButton( child: Text('←'), textColor: _ax == Ax.rtl ? Colors.red : Colors.black, onPressed: () { setState(() { _ax = Ax.rtl; }); }, ) ], ); } } enum Ax { ltr, rtl, ttb, btt, } // ignore: must_be_immutable class MySliderTransitiion extends AnimatedWidget { final Widget child; final Ax ax; Tween<Offset> _tween; MySliderTransitiion( {Key key, @required Animation<double> position, this.child, this.ax = Ax.btt}) : assert(position != null), super(key: key, listenable: position) { /// 偏移在内部处理 每个方向的偏移量都不一样, /// 需要根据方向来指定偏移量 switch (this.ax) { case Ax.btt: _tween = Tween(begin: Offset(0, 1), end: Offset(0, 0)); break; case Ax.ltr: _tween = Tween(begin: Offset(-1, 0), end: Offset(0, 0)); break; case Ax.ttb: _tween = Tween(begin: Offset(0, -1), end: Offset(0, 0)); break; case Ax.rtl: _tween = Tween(begin: Offset(1, 0), end: Offset(0, 0)); break; } } Animation<double> get position => listenable; @override Widget build(BuildContext context) { Offset offset = _tween.evaluate(position); /// 根据 动画的执行正向和反向来调节 坐标位置 if (position.status == AnimationStatus.reverse) { switch (this.ax) { case Ax.ltr: offset = Offset(-offset.dx, offset.dy); break; case Ax.rtl: offset = Offset(-offset.dx, offset.dy); break; case Ax.ttb: offset = Offset(offset.dx, -offset.dy); break; case Ax.btt: offset = Offset(offset.dx, -offset.dy); break; } } return FractionalTranslation( translation: offset, child: child, ); } } <|start_filename|>lib/file_and_http/http_client.dart<|end_filename|> import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/27. /// class BaseHttpClientRoute extends StatefulWidget { BaseHttpClientRoute({Key key}) : super(key: key); @override _BaseHttpClientRouteState createState() => _BaseHttpClientRouteState(); } class _BaseHttpClientRouteState extends State<BaseHttpClientRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('HttpClient'), ), body: _body(), ); } Widget _body() { return Center( child: Column( children: <Widget>[], ), ); } void _send() async { HttpClient httpClient = new HttpClient(); Uri uri = Uri( scheme: 'https', host: 'flutterchine.club', queryParameters: {'a': '1', 'b': '2'}); HttpClientRequest request = await httpClient.getUrl(uri); } } <|start_filename|>lib/tips/get/get_route.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:get/get.dart'; class GetRoute extends StatefulWidget { GetRoute({Key key}) : super(key: key); @override _GetRouteState createState() => _GetRouteState(); static String get routeName => "GetRoute"; } class _GetRouteState extends State<GetRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('路由跳转'), ), body: Center( child: Column( children: [ OutlineButton( child: Text('to 下一个页面'), onPressed: _to, ), OutlineButton( child: Text('back 返回'), onPressed: _back, ), OutlineButton( child: Text('off 替换当前路由'), onPressed: _off, ), OutlineButton( child: Text('offAll 返回到顶部'), onPressed: _offAll, ), OutlineButton( child: Text('off Until 返回到符合条件的路由'), onPressed: _offUntil, ), ], ), ), ); } /// 新打开页面 void _to() { Get.to(GetRoute(), preventDuplicates: false, transition: Transition.topLevel, duration: Duration(seconds: 1)); } /// 返回 void _back() { Get.back(); } void _off() { Get.off(GetRoute(), preventDuplicates: false); } void _offAll() { Get.offAll(GetRoute()); } void _offUntil() { Get.offUntil(MaterialPageRoute(builder: (_) => GetRoute()), (route) => false); } } class GetRouteController extends GetxController {} <|start_filename|>lib/tips/revierpod/base_river_pod_list.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; class RiverPodListRoute extends HookWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('list'), ), body: Center( child: Text('center'), ), ); } } <|start_filename|>lib/scrollview/scrollview.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class BaseScrollViewWheel extends StatefulWidget { BaseScrollViewWheelState createState() => BaseScrollViewWheelState(); } class BaseScrollViewWheelState extends State<BaseScrollViewWheel> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('ListWheelScrollView'), ), body: Stack( children: <Widget>[ Positioned.fill(child: _body()), Positioned.fill( child: _bottom(), bottom: 0, ), ], ), ); } Widget _body() { List<Widget> list = new List(); for (int i = 0; i < 100; i++) { Widget widget = Container( width: 300, height: 100, color: Colors.primaries[i % Colors.primaries.length], ); list.add(widget); } return ListWheelScrollView( itemExtent: 100, children: list, offAxisFraction: value, //左右偏移量 /// 固定中间选中的的放大或者缩小操作 magnification: value3 + 1, useMagnifier: true, /// list 弯曲度 [0,0.01] perspective: value2 / 100.0 == 0 ? 0.00000000001 : value2 / 100.0); } Widget _bottom() { return Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('offAxisFraction'), CupertinoSlider( value: value, onChanged: (v) { setState(() { value = v; }); print(v); }), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('perspective'), CupertinoSlider( value: value2, onChanged: (v) { setState(() { value2 = v; }); print(v); }), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('magnification'), CupertinoSlider( value: value3, onChanged: (v) { setState(() { value3 = v; }); print(v); }), ], ) ], ); } double value = 0; double value2 = 0; double value3 = 0; } <|start_filename|>lib/tips/layout/base_layout.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/21. /// class BaseLayoutPage extends StatefulWidget { BaseLayoutPage({Key key}) : super(key: key); @override _BaseLayoutPageState createState() => _BaseLayoutPageState(); static String get routeName => '/_BaseLayoutPageState'; } class _BaseLayoutPageState extends State<BaseLayoutPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(''), ), body: _body(), ); } Widget _body() { return Column( children: <Widget>[ Container( // width: 100, // height: 100, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { print('$constraints'); return Text('constraints'); }, ), ) ], ); } } <|start_filename|>lib/video/base_video_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_vlc_player/flutter_vlc_player.dart'; import 'package:video_player/video_player.dart'; import 'package:youtube_player_flutter/youtube_player_flutter.dart'; class BaseVideoPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _MyHomePageState(); } static String get routeName => '/_BaseVideoPageState'; } class _BaseVideoPageState extends State<BaseVideoPage> { @override void initState() { super.initState(); _controller = VideoPlayerController.network( 'http://vd3.bdstatic.com/mda-ifvqu9yp3eaqueep/mda-ifvqu9yp3eaqueep.mp4') ..initialize().then((_) { // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. setState(() {}); }); // _controller.formatHint; } VideoPlayerController _controller; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseVideoPage'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: TextButton( onPressed: () { setState(() { _controller.value.isPlaying ? _controller.pause() : _controller.play(); }); }, child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ), ), ), AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ) ], ), ), ); } } class _MyHomePageState extends State<BaseVideoPage> { VlcPlayerController _videoPlayerController; Future<void> initializePlayer() async { setState(() {}); } @override void initState() { super.initState(); index = 0; _videoPlayerController = VlcPlayerController.network(url, hwAcc: HwAcc.FULL, autoPlay: true, options: VlcPlayerOptions(), onInit: initializePlayer); } @override void dispose() async { super.dispose(); await _videoPlayerController.stopRendererScanning(); // await _videoViewController.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Center( child: VlcPlayer( controller: _videoPlayerController, aspectRatio: 16 / 9, placeholder: Center(child: CircularProgressIndicator()), ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.next_plan_outlined), onPressed: () async { String u = url; await _videoPlayerController.setMediaFromNetwork( u, autoPlay: true, hwAcc: HwAcc.FULL, ); print("set data source success:$u"); // controller.playOrPause(); }, ), ); } int index; String get url { index += 1; /// https://blog.csdn.net/suwu150/article/details/90345041 m3u8资源列表 var list = [ 'https://vd3.bdstatic.com/mda-mc2t866ix18tmrbw/sc/cae_h264_clips/1614770378/mda-mc2t866ix18tmrbw.mp4', // 'https://vd2.bdstatic.com/mda-mdpdktv9j7dc629c/1080p/cae_h264/1619258626/mda-mdpdktv9j7dc629c.mp4', 'http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv2.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv3hd.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv4.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv5phd.m3u8', ]; return list[index % (list.length)]; } } class BaseVideoPage2 extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseVideoPage2State(); } static String get routeName => '/_BaseVideoPage2State'; } class _BaseVideoPage2State extends State<BaseVideoPage2> { YoutubePlayerController _controller; TextEditingController _idController; TextEditingController _seekToController; PlayerState _playerState; YoutubeMetaData _videoMetaData; double _volume = 100; bool _muted = false; bool _isPlayerReady = false; final List<String> _ids = [ 'nPt8bK2gbaU', 'gQDByCdjUXw', 'iLnmTe5Q2Qw', '_WoCV4c6XOE', 'KmzdUe0RSJo', '6jZDSSZZxjQ', 'p2lYr3vM_1w', '7QUtEmBT_-w', '34_PXCzGw1M', ]; @override void initState() { super.initState(); _controller = YoutubePlayerController( initialVideoId: _ids.first, flags: const YoutubePlayerFlags( mute: false, autoPlay: true, disableDragSeek: false, loop: false, isLive: false, forceHD: false, enableCaption: true, ), )..addListener(listener); _idController = TextEditingController(); _seekToController = TextEditingController(); _videoMetaData = const YoutubeMetaData(); _playerState = PlayerState.unknown; } void listener() { if (_isPlayerReady && mounted && !_controller.value.isFullScreen) { setState(() { _playerState = _controller.value.playerState; _videoMetaData = _controller.metadata; }); } } @override void deactivate() { // Pauses video while navigating to next page. _controller.pause(); super.deactivate(); } @override void dispose() { _controller.pause(); _controller.dispose(); _idController.clear(); _idController.dispose(); _seekToController.clear(); _seekToController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return YoutubePlayerBuilder( onExitFullScreen: () { // The player forces portraitUp after exiting fullscreen. This overrides the behaviour. // SystemChrome.setPreferredOrientations(DeviceOrientation.values); }, player: YoutubePlayer( controller: _controller, showVideoProgressIndicator: true, progressIndicatorColor: Colors.blueAccent, topActions: <Widget>[ const SizedBox(width: 8.0), Expanded( child: Text( _controller.metadata.title, style: const TextStyle( color: Colors.white, fontSize: 18.0, ), overflow: TextOverflow.ellipsis, maxLines: 1, ), ), IconButton( icon: const Icon( Icons.settings, color: Colors.white, size: 25.0, ), onPressed: () { print('Settings Tapped!'); }, ), ], onReady: () { _isPlayerReady = true; }, onEnded: (data) { _controller .load(_ids[(_ids.indexOf(data.videoId) + 1) % _ids.length]); _showSnackBar('Next Video Started!'); }, ), builder: (context, player) => Scaffold( appBar: AppBar( title: const Text( 'Youtube Player Flutter', style: TextStyle(color: Colors.white), ), ), body: ListView( children: [ player, Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _space, _text('Title', _videoMetaData.title), _space, _text('Channel', _videoMetaData.author), _space, _text('Video Id', _videoMetaData.videoId), _space, Row( children: [ _text( 'Playback Quality', _controller.value.playbackQuality ?? '', ), const Spacer(), _text( 'Playback Rate', '${_controller.value.playbackRate}x ', ), ], ), _space, TextField( enabled: _isPlayerReady, controller: _idController, decoration: InputDecoration( border: InputBorder.none, hintText: 'Enter youtube \<video id\> or \<link\>', fillColor: Colors.blueAccent.withAlpha(20), filled: true, hintStyle: const TextStyle( fontWeight: FontWeight.w300, color: Colors.blueAccent, ), suffixIcon: IconButton( icon: const Icon(Icons.clear), onPressed: () => _idController.clear(), ), ), ), _space, Row( children: [ _loadCueButton('LOAD'), const SizedBox(width: 10.0), _loadCueButton('CUE'), ], ), _space, Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ IconButton( icon: const Icon(Icons.skip_previous), onPressed: _isPlayerReady ? () => _controller.load(_ids[ (_ids.indexOf(_controller.metadata.videoId) - 1) % _ids.length]) : null, ), IconButton( icon: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ), onPressed: _isPlayerReady ? () { _controller.value.isPlaying ? _controller.pause() : _controller.play(); setState(() {}); } : null, ), IconButton( icon: Icon(_muted ? Icons.volume_off : Icons.volume_up), onPressed: _isPlayerReady ? () { _muted ? _controller.unMute() : _controller.mute(); setState(() { _muted = !_muted; }); } : null, ), FullScreenButton( controller: _controller, color: Colors.blueAccent, ), IconButton( icon: const Icon(Icons.skip_next), onPressed: _isPlayerReady ? () => _controller.load(_ids[ (_ids.indexOf(_controller.metadata.videoId) + 1) % _ids.length]) : null, ), ], ), _space, Row( children: <Widget>[ const Text( "Volume", style: TextStyle(fontWeight: FontWeight.w300), ), Expanded( child: Slider( inactiveColor: Colors.transparent, value: _volume, min: 0.0, max: 100.0, divisions: 10, label: '${(_volume).round()}', onChanged: _isPlayerReady ? (value) { setState(() { _volume = value; }); _controller.setVolume(_volume.round()); } : null, ), ), ], ), _space, AnimatedContainer( duration: const Duration(milliseconds: 800), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.0), color: _getStateColor(_playerState), ), padding: const EdgeInsets.all(8.0), child: Text( _playerState.toString(), style: const TextStyle( fontWeight: FontWeight.w300, color: Colors.white, ), textAlign: TextAlign.center, ), ), ], ), ), ], ), ), ); } Widget _text(String title, String value) { return RichText( text: TextSpan( text: '$title : ', style: const TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.bold, ), children: [ TextSpan( text: value, style: const TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.w300, ), ), ], ), ); } Color _getStateColor(PlayerState state) { switch (state) { case PlayerState.unknown: return Colors.grey[700]; case PlayerState.unStarted: return Colors.pink; case PlayerState.ended: return Colors.red; case PlayerState.playing: return Colors.blueAccent; case PlayerState.paused: return Colors.orange; case PlayerState.buffering: return Colors.yellow; case PlayerState.cued: return Colors.blue[900]; default: return Colors.blue; } } Widget get _space => const SizedBox(height: 10); Widget _loadCueButton(String action) { return Expanded( child: MaterialButton( color: Colors.blueAccent, onPressed: _isPlayerReady ? () { if (_idController.text.isNotEmpty) { var id = YoutubePlayer.convertUrlToId( _idController.text, ) ?? ''; if (action == 'LOAD') _controller.load(id); if (action == 'CUE') _controller.cue(id); FocusScope.of(context).requestFocus(FocusNode()); } else { _showSnackBar('Source can\'t be empty!'); } } : null, disabledColor: Colors.grey, disabledTextColor: Colors.black, child: Padding( padding: const EdgeInsets.symmetric(vertical: 14.0), child: Text( action, style: const TextStyle( fontSize: 18.0, color: Colors.white, fontWeight: FontWeight.w300, ), textAlign: TextAlign.center, ), ), ), ); } void _showSnackBar(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( message, textAlign: TextAlign.center, style: const TextStyle( fontWeight: FontWeight.w300, fontSize: 16.0, ), ), backgroundColor: Colors.blueAccent, behavior: SnackBarBehavior.floating, elevation: 1.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(50.0), ), ), ); } } <|start_filename|>lib/tips/page_view_tabbar.dart<|end_filename|> import 'dart:developer'; import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/animation/base_animation_switch.dart'; import 'package:fluttertest01/tips/base_tabbar.dart'; /// /// Created by fgyong on 2020/8/7. /// class FYTabbarWidget extends StatefulWidget { FYTabbarWidget({Key key}) : super(key: key); @override _FYTabbarWidgetState createState() => _FYTabbarWidgetState(); } class _FYTabbarWidgetState extends State<FYTabbarWidget> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('tabbar'), ), body: _body(), ); } TabController _tabController; double _offset = 0; @override void initState() { _pageController = PageController(initialPage: 1) ..addListener(() { setState(() { double of = _pageController.offset; _offset = of; }); // print(_pageController.position.pixels); // print( // '${_pageController.offset - MediaQuery.of(context).size.width * _selectedIndex}'); }); _tabController = TabController(length: 6, vsync: this) ..addListener(() { // print(_tabController.index); }); super.initState(); } PageController _pageController; Widget _body() { return Center( child: Stack( fit: StackFit.expand, children: <Widget>[ // Positioned( // top: -_top, // height: 55, // left: 0, // right: 0, // child: FlatButton( // child: Text( // 'push stop', // ), // onPressed: () { // Navigator.push(context, // MaterialPageRoute(builder: (_) => FYTabbarWidget())); // }, // )), // Positioned( // top: 55 - _top, // height: 55, // left: 0, // right: 0, // child: TabBar( // tabs: <Widget>[ // Container( // alignment: Alignment.center, //// width: 100, // child: Text( // '推荐', // style: _textStyle(0), // ), // ), // Container( // width: 100, // child: Text( // '热搜', // style: _textStyle(1), // ), // ), // Container( // width: 100, // child: Text( // '本地', // style: _textStyle(2), // ), // ), // Container( // width: 100, // color: Colors.white70, // child: Text( // '新闻', // style: _textStyle(3), // ), // ) // ], // controller: _tabController, // onTap: (v) { // _pageController.animateToPage(v, // duration: Duration(milliseconds: 300), // curve: Curves.linear); // }, // )), Positioned( left: 0, right: 0, top: 110 - _top, height: 60, child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter( child: Container( width: MediaQuery.of(context).size.width, child: BaseFYTabBar( offset: _offset, initPageIndex: 1, // pageIndex: _selectedIndex, value: 0.3, // lineColor: Colors.black, titles: [ '推荐', '上海', '浦东', '江苏', '河南', '湖北', '浦东', '徐汇', '嘉定' ], maxTabsOfScreen: 2, ), )) ], scrollDirection: Axis.horizontal, ), ), Positioned( left: 0, right: 0, top: 110 - _top + 60, child: // SliverToBoxAdapter( Container( width: MediaQuery.of(context).size.width, height: 500, child: CupertinoScrollbar( child: PageView( controller: _pageController, onPageChanged: (index) { _tabController.animateTo(index); setState(() { _selectedIndex = index; }); }, children: <Widget>[ _pageView(0), _pageView(1), _pageView(0), _pageView(0), _pageView(0), _pageView(0), ], )), ), ), ], ), ); } double _top = 0; Widget _pageView(int index) { return NotificationListener<ScrollNotification>( child: ListView.builder( itemBuilder: (ctx, index) { return Container( width: 100, height: 50, color: Colors.primaries[index % Colors.primaries.length], child: Text('$index'), ); }, itemCount: 100, ), onNotification: (ScrollNotification n) { if (n.metrics.pixels < 0) { setState(() { _top = n.metrics.pixels; }); print('$_top ${n.metrics.axisDirection}'); } return false; }, ); } int _selectedIndex = 1; TextStyle _textStyle(int index) { return index != _selectedIndex ? TextStyle( color: Colors.blueAccent, fontSize: 15, ) : TextStyle( color: Colors.red, fontSize: 20, ); } Widget _tag(String tag, int index) { return SliverToBoxAdapter( child: Container( width: 100, height: 55, child: Text( tag ?? '', style: TextStyle( color: index == _selectedIndex ? Colors.red : Colors.black), ), ), ); } } // ignore: must_be_immutable class _Page extends StatefulWidget { final String title; bool selected; _Page({Key key, this.title, this.selected}) : super(key: key); @override __PageState createState() => __PageState(); } class __PageState extends State<_Page> with WidgetsBindingObserver { @override Widget build(BuildContext context) { return _tag(widget.title); } Widget _tag( String tag, ) { return SliverToBoxAdapter( child: Container( width: 100, height: 55, child: Text( tag ?? '', style: TextStyle( color: widget.selected == true ? Colors.red : Colors.black), ), ), ); } @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void didChangeAppLifecycleState(AppLifecycleState state) { print('${state.toString()} ${widget.title})'); switch (state) { case AppLifecycleState.detached: print('detached'); break; case AppLifecycleState.inactive: print('inactive'); break; case AppLifecycleState.paused: print('paused'); break; case AppLifecycleState.resumed: print('resumed'); break; } super.didChangeAppLifecycleState(state); } @override void dispose() { super.dispose(); print('dispose()'); } @override void reassemble() { print('reassemble'); super.reassemble(); } @override Future<bool> didPopRoute() { print('didPopRoute'); return super.didPopRoute(); } @override Future<bool> didPushRoute(String route) { print('didPushRoute'); return super.didPushRoute(route); } } <|start_filename|>lib/server/basic_writer_server.dart<|end_filename|> // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Server to basic_writer_client.dart. // Receives JSON encoded data in a POST request and writes it to // the file specified in the URI. // import 'package:mysql1/mysql1.dart'; // String _host = InternetAddress.loopbackIPv4.host; // Future main() async { // var server = await HttpServer.bind(_host, 4049); // HttpServer.listenOn(server); // print('Listening on http://${server.address.address}:${server.port}/'); // await for (var req in server) { // handle(req); // } // } // void handle(HttpRequest req) async { // final response = req.response; // if (uris.containsKey(req.uri.path)) { // uris[req.uri.path](req); // } // await response.close(); // } // // void getList(HttpRequest req) async { // final response = req.response; // // req.method == 'POST' && // // contentType?.mimeType == 'application/json' // // try { // var data = req.uri.queryParametersAll; // // data['ex'] = req.requestedUri.query; // // // final content = await utf8.decoder.bind(req).join(); /*2*/ // // final conn = await MySqlConnection.connect(ConnectionSettings( // // host: '127.0.0.1', // // port: 3306, // // user: 'root', // // db: 'testDB', // // password: '<PASSWORD>')); // // // final ret = await conn.query('select * from user'); // req.response // ..statusCode = HttpStatus.ok // ..write('Wrote data for ${data} ${req.requestedUri.path} .'); // } catch (e) { // response // ..statusCode = HttpStatus.internalServerError // ..write('Exception during file I/O: $e.') // ..close(); // } // } // // typedef f = Function(HttpRequest req); // Map<String, f> uris = {'/get': getList}; <|start_filename|>lib/tips/touch/base_touch_handle.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/9/10. /// class BaseTouchHandlePage extends StatefulWidget { BaseTouchHandlePage({Key key}) : super(key: key); @override _BaseTouchHandlePageState createState() => _BaseTouchHandlePageState(); static String get routenName => "BaseTouchHandlePage"; } class _BaseTouchHandlePageState extends State<BaseTouchHandlePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('触摸事件流程探索'), ), body: _body(), ); } Widget _body() { return Center( child: GestureDetector( child: Container( child: Text('按压'), width: 100, height: 60, alignment: Alignment.center, color: Colors.orange, ), onTap: _onPress, ), ); } void _onPress() { print('object'); } } <|start_filename|>lib/tips/base_interactive_viewer.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/11/9. /// class BaseInteractiveViewer extends StatefulWidget { BaseInteractiveViewer({Key key}) : super(key: key); @override _BaseInteractiveViewerState createState() => _BaseInteractiveViewerState(); static String get routeName => "interactiveViewer"; } class _BaseInteractiveViewerState extends State<BaseInteractiveViewer> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('interactiveViewer'), ), body: _body(), ); } Widget _body() { return Center( child: InteractiveViewer( boundaryMargin: EdgeInsets.all(20.0), minScale: 0.1, maxScale: 1.6, child: Container( child: Image.asset('img/2.png'), // decoration: BoxDecoration( // gradient: LinearGradient( // begin: Alignment.topCenter, // end: Alignment.bottomCenter, // colors: [Colors.orange, Colors.red], // stops: [0.0, 1.0], // ), // ), ), ), ); } } <|start_filename|>lib/tips/get/get_increment_page.dart<|end_filename|> import 'dart:async'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class GetIncrementPage extends StatefulWidget { GetIncrementPage({Key key}) : super(key: key); @override _GetIncrementPageState createState() => _GetIncrementPageState(); } class _GetIncrementPageState extends State<GetIncrementPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('get'), ), body: Container( alignment: Alignment.center, child: _body(), ), ); } Widget _body() { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Obx(() { var n = c.count.value.count.toString(); printInfo(info: '刷新了页面 get_数字变动了 $n'); return Text('当前值:$n'); }), OutlineButton( child: Text('get 数字加'), onPressed: c.increment, ), OutlineButton( child: Text('get 数字减'), onPressed: c.down, ), Obx(() { printInfo(info: '刷新了页面 get_obx_log1'); return Text('logObx:' + c.log.toString()); }), Obx(() { printInfo(info: '刷新了页面 get_obx_log2'); return Text(c.log2.toString()); }), OutlineButton( child: Text('get log 变化'), onPressed: c.change, ), // ObxValue((var value) => Text('${value.toString()}'), c), ], ); } @override void dispose() { Get.delete<Controller2>(); super.dispose(); } final Controller2 c = Get.put(Controller2()); } class Test extends StatefulWidget { @override State<StatefulWidget> createState() => _Test(); } class _Test extends State<Test> { @override Widget build(BuildContext context) { return Container( child: Text('$value'), ); } var value; StreamController<String> subject; StreamSubscription streamSubscription; @override void initState() { subject = StreamController.broadcast(); streamSubscription = subject.stream.listen((event) { setState(() {}); }); super.initState(); } @override void dispose() { subject.close(); streamSubscription.cancel(); super.dispose(); } var nu = 0; add() { nu++; value = 'event$nu'; subject.add(value); ''.obs.value = '123'; } } /// /// Created by fgyong on 2020/10/22. /// class Controller2 extends GetxController { var count = NumberCount().obs; var count2 = 0.obs; final log = ''.obs; final log2 = ''.obs; increment() { count.value.increment(); count.refresh(); } down() { count.value.down(); count.refresh(); } @override void onClose() { printInfo(info: 'Controller close'); super.onClose(); } void change() { log.value += ' ${log.value.length}'; } } class NumberCount { var count = 0.obs; increment() { count++; } down() { count--; } } <|start_filename|>lib/tips/fish_redux_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/17. /// class BaseFishReduxPage extends StatefulWidget { BaseFishReduxPage({Key key}) : super(key: key); @override _BaseFishReduxPageState createState() => _BaseFishReduxPageState(); static String routeName = "/BaseFishReduxPage"; } class _BaseFishReduxPageState extends State<BaseFishReduxPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Fish'), ), body: _body(), ); } Widget _body() {} } <|start_filename|>lib/container/base_bars.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/2. /// class BaseBars extends StatefulWidget { @override _ScaffoldRouteState createState() => _ScaffoldRouteState(); } class _ScaffoldRouteState extends State<BaseBars> with SingleTickerProviderStateMixin { int _selectedIndex = 1; GlobalKey<ScaffoldState> _globalKey = GlobalKey(); TabController _tabController; @override void initState() { _tabController = TabController(vsync: this, length: 3); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( key: _globalKey, appBar: AppBar( //导航栏 title: Text("脚手架 tabbar 底部导航"), actions: <Widget>[ //导航栏右侧菜单 IconButton( icon: Icon(Icons.arrow_back), onPressed: () { Navigator.pop(context); }), ], bottom: TabBar( controller: _tabController, tabs: <Widget>[Text('今天'), Text('明天'), Text('后天')], ), ), drawer: new Drawer( child: _drawer(), ), //抽屉 bottomNavigationBar: BottomAppBar( color: Colors.white, shape: CircularNotchedRectangle(), // 底部导航栏打一个圆形的洞 child: Row( children: [ IconButton(icon: Icon(Icons.home)), //中间位置空出 IconButton(icon: Icon(Icons.scatter_plot)), SizedBox(), ], mainAxisAlignment: MainAxisAlignment.spaceAround, //均分底部导航栏横向空间 ), ), floatingActionButtonLocation: FloatingActionButtonLocation.miniStartTop, floatingActionButton: FloatingActionButton( //悬浮按钮 child: Icon(Icons.add), onPressed: _onAdd), resizeToAvoidBottomInset: true, //谈起键盘则页面上移 primary: true, //是否展示在顶部东航栏高度,true占用高度,否则只是在状态栏 body: TabBarView( controller: _tabController, children: <Widget>[ Container( alignment: Alignment.topCenter, child: Text('今天来了'), ), Container( alignment: Alignment.topCenter, child: Text('明天来了'), ), Container( alignment: Alignment.topCenter, child: Text('后天来了'), ), ], ), // extendBody: true, // extendBodyBehindAppBar: true, drawerEdgeDragWidth: 20, //手势多动偏移量 默认20px drawerDragStartBehavior: DragStartBehavior.start, drawerEnableOpenDragGesture: true, //手势拖动打开抽屉 ); } BottomNavigationBar _bottomNavigationBar() { return BottomNavigationBar( // 底部导航 items: <BottomNavigationBarItem>[ BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')), BottomNavigationBarItem( icon: Icon(Icons.business), title: Text('Business')), BottomNavigationBarItem( icon: Icon(Icons.school), title: Text('School')), ], currentIndex: _selectedIndex, fixedColor: Colors.blue, onTap: _onItemTapped, ); } int _count = 0; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } void _onAdd() { setState(() { _count++; }); } Widget _bd2() { return OutlineButton.icon( onPressed: () { Navigator.pop(context); }, icon: Icon( Icons.close, size: 25, ), label: Text('pop ')); } Widget _drawer() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('点击我返回,左滑返回,点击遮罩返回'), _bd2(), ], ); } } <|start_filename|>lib/tips/provider/base_provider.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/tips/provider/base_provider_pan_zan.dart'; import 'package:fluttertest01/tips/provider/base_stream_pge.dart'; import 'package:provider/provider.dart'; /// /// Created by fgyong on 2020/7/30. /// class BaseProviderRouteProvider extends StatelessWidget { @override Widget build(BuildContext context) { return BaseProviderRouteList(); } static String get routeName => '/BaseProviderRouteProvider'; } class BaseProviderRouteList extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseProviderRouteProvider'), ), body: _body(), ); } Widget _body() { return Builder(builder: (context) { return CustomScrollView( slivers: <Widget>[ item('数字加减', () { Navigator.of(context).push(BaseProviderRoute.pageRoute); }), item('定时器', () { Navigator.push(context, BaseProviderStreamRoute.pageRoute); }), item('数字加减监听跳转新页面', () { Navigator.push(context, BasePinZanProviderRoute.route); }) ], ); }); } Widget item(String name, GestureTapCallback callback) { return SliverToBoxAdapter( child: OutlineButton( child: Text('$name'), onPressed: callback, ), ); } } class BaseProviderRoute extends StatelessWidget { BaseProviderRoute({Key key}) : super(key: key); static MaterialPageRoute get pageRoute => MaterialPageRoute(builder: (_) => BaseProviderRoute()); @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<ProviderModel>( create: (_) => ProviderModel(), lazy: false, ), ChangeNotifierProvider<ProviderModel2>( create: (_) => ProviderModel2(), lazy: false, ), ], child: BaseProvider(), ); return ChangeNotifierProvider( create: (_) => ProviderModel(), lazy: true, builder: (ctx, child) { return BaseProvider(); }, ); } } class BaseProvider extends StatefulWidget { BaseProvider({Key key}) : super(key: key); @override _BaseProviderState createState() { return _BaseProviderState(); } } class _BaseProviderState extends State<BaseProvider> { @override void initState() { super.initState(); } String _string = ''; @override Widget build(BuildContext context) { print('page 1'); _string += 'page '; ProviderModel _model = context.select<ProviderModel, ProviderModel>((value) => value); ProviderModel2 _model2 = context.select<ProviderModel2, ProviderModel2>((value) => value); return Scaffold( appBar: AppBar( title: Text('Provider 全局与局部刷新'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( '${_model._count} ${_model._count2} ${_model._count3} m2:${_model2.value}'), Text('全局刷新<Consumer>'), Consumer<ProviderModel>( builder: (BuildContext context, ProviderModel value, Widget child) { print('Consumer 0 刷新'); _string += 'c0 '; return _Row( value: value._count.toString(), callback: () { context.read<ProviderModel>().plus(); }, ); }, child: _Row( value: '0', callback: () { context.read<ProviderModel>().plus(); }, ), ), SizedBox( height: 40, ), Text('局部刷新<Selector>'), Selector<ProviderModel, int>( builder: (ctx, value, child) { print('Selector 1 刷新'); _string += 's1 '; return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Selector<Model,int>次数:' + value.toString()), OutlineButton( onPressed: () { context.read<ProviderModel>().plus2(); }, child: Icon(Icons.add), ) ], ); }, selector: (ctx, model) => model._count2, shouldRebuild: (m1, m2) { print('s1:$m1 $m2 ${m1 != m2 ? '不相等,本次刷新' : '数据相等,本次不刷新'}'); return m1 != m2; }, ), SizedBox( height: 40, ), Text('局部刷新<Selector>'), Selector<ProviderModel, int>( selector: (context, model) => model._count3, shouldRebuild: (m1, m2) { print('s2:$m1 $m2 ${m1 != m2 ? '不相等,本次刷新' : '数据相等,本次不刷新'}'); return m1 != m2; }, builder: (ctx, value, child) { print('selector 2 刷新'); _string += 's2 '; return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Selector<Model,int>次数:' + value.toString()), OutlineButton( onPressed: () { ctx.read<ProviderModel>().plus3(); }, child: Icon(Icons.add), ) ], ); }, ), SizedBox( height: 40, ), Text('刷新次数和顺序:↓'), Text(_string), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ OutlineButton( child: Icon(Icons.refresh), onPressed: () { setState(() { _string += '\n'; }); }, ), OutlineButton( child: Icon(Icons.close), onPressed: () { setState(() { _string = ''; }); }, ), ], ), Text('model2 局部刷新'), Selector<ProviderModel2, int>( selector: (context, model) => model.value, builder: (ctx, value, child) { print('model2 s1 刷新'); _string += 'm2s1 '; return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Selector<Model2,int>次数:' + value.toString()), OutlineButton( onPressed: () { ctx.read<ProviderModel2>().add(2); }, child: Icon(Icons.add), ) ], ); }, ), SizedBox( height: 40, ), // StreamProvider(create: null) ], ), ), ); } } // ignore: must_be_immutable //class FutureModel extends ChangeNotifier { // static Future<FutureModel> doHttp(BuildContext context) async { // await Future.delayed(Duration(seconds: 2)); // // return FutureModel( // value: 2, // ); // } // // int value = 0; // FutureModel({this.value}) { // notifyListeners(); // } //} class ProviderModel2 extends ChangeNotifier { int _value = 0; ProviderModel2(); set setValue(int v) { _value = v; notifyListeners(); } get value => _value; void add(int v) { _value += v; notifyListeners(); } } class ProviderModel extends ChangeNotifier { ProviderModel({int value, int valu2, int value3}) { _count = value ?? 0; _count2 = valu2 ?? 0; _count3 = value3 ?? 0; } int _count = 0, _count2 = 0, _count3 = 0; String _log = ''; set count(int count) { _count = count; notifyListeners(); } get count => _count; /// 查看刷新日志 get log => _log; set logStr(String str) { _log = str; notifyListeners(); } void addLog(String str) { _log += str; notifyListeners(); } void plus() { this.count = _count + 1; notifyListeners(); } void plus2() { this._count2 += 1; notifyListeners(); } void plus3() { _count3 += 1; notifyListeners(); } } class _Row extends StatelessWidget { final String value; final GestureTapCallback callback; _Row({this.value, this.callback}); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Consumer(Model)次数:$value'), OutlineButton( onPressed: this.callback, child: Icon(Icons.add), ) ], ); } } <|start_filename|>lib/custom_animation/base_custom_animation.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/31. /// class BaseCustomListAnimationPage extends StatelessWidget { static String get routeName => '/BaseCustomListAnimationPage'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(''), ), body: _body(), ); } Widget _body() { return NestedScrollView( headerSliverBuilder: _listView, body: ListView.builder( itemBuilder: (context, index) { return ListTile( title: Text('$index'), ); }, itemCount: 10, )); } List<Widget> _listView(BuildContext context, bool innerBoxIsScrolled) { return [ SliverAppBar( title: Text('123'), floating: false, ) ]; } } <|start_filename|>lib/tips/get/get_example.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/tips/get/get_increment_page.dart'; import 'package:fluttertest01/tips/get/get_list_page.dart'; import 'package:fluttertest01/tips/get/get_login_page.dart'; import 'package:fluttertest01/tips/get/get_route.dart'; import 'package:fluttertest01/tips/get/get_store.dart'; import 'package:get/get.dart'; /// /// Created by fgyong on 2020/10/22. /// class BaseGetPage extends StatefulWidget { BaseGetPage({Key key}) : super(key: key); @override _BaseGetPageState createState() => _BaseGetPageState(); static get routeName => '/getPage'; } class _BaseGetPageState extends State<BaseGetPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('get'), ), body: Container( alignment: Alignment.center, child: _body(), ), ); } Widget _body() { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ OutlineButton( child: Text('get 数字加减'), onPressed: _pushNumber, ), OutlineButton( child: Text('show SnackBar top'), onPressed: () { Get.snackbar( "Hey i'm a Get SnackBar!", // title "It's unbelievable! I'm using SnackBar without context, without boilerplate, without Scaffold, it is something truly amazing!", // message icon: Icon(Icons.alarm), shouldIconPulse: true, onTap: null, barBlur: 20, isDismissible: true, duration: Duration(seconds: 3), snackPosition: SnackPosition.TOP); }, ), OutlineButton( child: Text('show SnackBar BOTTOM'), onPressed: () { Get.snackbar( "Hey i'm a Get SnackBar!", // title "It's unbelievable! I'm using SnackBar without context, without boilerplate, without Scaffold, it is something truly amazing!", // message icon: Icon(Icons.alarm), shouldIconPulse: true, onTap: null, barBlur: 20, isDismissible: true, duration: Duration(seconds: 3), snackPosition: SnackPosition.BOTTOM); }, ), Text('屏幕宽:${Get.width} 高:${Get.height}'), OutlineButton( child: Text('dialog'), onPressed: () { Get.dialog(Text('dialog')); Future.delayed(Duration(seconds: 2)).then((value) => Get.back()); }, ), OutlineButton( child: Text('bottomSheet'), onPressed: () { Get.bottomSheet(Container( child: Wrap( children: <Widget>[ ListTile(leading: Icon(Icons.music_note), title: Text('Music'), onTap: () => {}), ListTile( leading: Icon(Icons.videocam), title: Text('Video'), onTap: () => {}, ), ], ), )); }, ), _gotoList(), _login(), _route(), _store() // ObxValue((var value) => Text('${value.toString()}'), c), ], ); } Widget _gotoList() => OutlineButton( child: Text('goto list 列表展示'), onPressed: () { Get.toNamed(GetListPageRoute.routeName); }, ); Widget _login() => OutlineButton( child: Text('get 登陆 全过程'), onPressed: () { Get.toNamed(GetLoginPage.routeName); }, ); Widget _route() => OutlineButton( child: Text('get 路由切换'), onPressed: () { Get.to(GetRoute()); }, ); Widget _store() => OutlineButton( child: Text('get 存储'), onPressed: () { Get.to(GetStoreRoute()); }, ); void _pushNumber() { Get.to(GetIncrementPage()); } @override void initState() { super.initState(); } @override void dispose() { Get.delete<Controller>(); Get.reset(clearFactory: true); super.dispose(); } final Controller c = Get.put(Controller()); } class Controller extends GetxController { var count = 0.obs; var count2 = 0.obs; final log = ''.obs; final log2 = ''.obs; increment() => count++; @override void onClose() { printInfo(info: 'Controller close'); super.onClose(); } void change() { log.value += ' ${log.value.length}'; } } <|start_filename|>lib/container/base_padding.dart<|end_filename|> import 'package:flutter/material.dart'; class BasePadding extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Padding'), ), body: _body(), ); } Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( color: Colors.black12, child: Padding( /// 设置上下左右各10像素 颜色是父级颜色 padding: EdgeInsets.all(10), child: Container( color: Colors.red, child: Text('设置上下左右各10像素 颜色是父级颜色'), ), ), ), Container( color: Colors.black12, child: Padding( /// 设置上下20像素 颜色是父级颜色 padding: EdgeInsets.symmetric(vertical: 20), child: Container( color: Colors.blue, child: Text('设置上下20像素 颜色是父级颜色'), ), ), ), Container( color: Colors.black12, child: Padding( /// 设置上下左右各30像素 颜色是父级颜色 padding: EdgeInsets.only(left: 30, top: 30, right: 30, bottom: 30), child: Container( color: Colors.orange, child: Text('设置上下左右各30像素 颜色是父级颜色'), ), ), ) ], ), ); } } <|start_filename|>lib/video/base_download_file_page.dart<|end_filename|> import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:dio/dio.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/util.dart'; import 'package:get_storage/get_storage.dart'; import 'package:permission_handler/permission_handler.dart'; class BaseDownFilePage extends StatefulWidget { @override State<StatefulWidget> createState() { return _BaseDownFilePageState(); } static String get routeName => '/BaseDownFilePage'; } class _BaseDownFilePageState extends State<BaseDownFilePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseDownFilePage'), ), body: _body(), ); } Widget _body() { return Center( child: CustomScrollView( slivers: [ SliverToBoxAdapter( child: TextButton( onPressed: () { setState(() { downLoadFile(2); }); }, child: Text('下载')), ), SliverToBoxAdapter( child: Container( width: 100, alignment: Alignment.center, child: CircularProgressIndicator( value: value, ), ), ), SliverToBoxAdapter( child: Text('$ret'), ), ], ), ); } double value = 0; String ret; void downLoadFile(int ix) async { index = ix; value = 0; var p = await path(); var last = p.path + '/$index.mp4'; // Directory(last).create(); File(last)..create(); // Uri.file(last); // p.createTemp() print('path:$last'); // final st = await Permission.storage.request(); // Permission.mediaLibrary.request(); // print('权限 $st'); var response = await Dio().download( 'http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8', '$last', onReceiveProgress: (received, total) { if (total != -1) { print((received / total * 100).toStringAsFixed(0) + "%"); setState(() { value = received / total; }); } }, ); ///#EXTM3U // #EXT-X-VERSION:3 // #EXT-X-MEDIA-SEQUENCE:253646 // #EXT-X-TARGETDURATION:10 // #EXTINF:10.000, // cctv1hd-1626437551000.ts // #EXTINF:10.000, // cctv1hd-1626437561000.ts // #EXTINF:10.000, // cctv1hd-1626437571000.ts // #EXTINF:10.000, // cctv1hd-1626437581000.ts // #EXTINF:10.000, // cctv1hd-1626437591000.ts // #EXTINF:10.000, // cctv1hd-1626437601000.ts /// https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8 /// http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8 response = await Dio() .get('https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8'); Util.v('$response'); setState(() { ret = response.data; }); } Future<Directory> path() async { final p = await getTemporaryDirectory(); return p; } int index; String get url { index += 1; /// https://blog.csdn.net/suwu150/article/details/90345041 m3u8资源列表 var list = [ 'https://vd3.bdstatic.com/mda-mc2t866ix18tmrbw/sc/cae_h264_clips/1614770378/mda-mc2t866ix18tmrbw.mp4', // 'https://vd2.bdstatic.com/mda-mdpdktv9j7dc629c/1080p/cae_h264/1619258626/mda-mdpdktv9j7dc629c.mp4', 'http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv2.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv3hd.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv4.m3u8', 'http://ivi.bupt.edu.cn/hls/cctv5phd.m3u8', ]; return list[index % (list.length)]; } @override void initState() { index = 0; super.initState(); } } <|start_filename|>lib/features/base_color_and_theme.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/8. /// class BaseColorAndTheme extends StatefulWidget { @override _BaseColorAndThemeState createState() => _BaseColorAndThemeState(); } class _BaseColorAndThemeState extends State<BaseColorAndTheme> { Color _color; @override Widget build(BuildContext context) { ThemeData themeData = Theme.of(context); return Theme( child: Scaffold( appBar: AppBar( title: Text('颜色和主题'), ), body: _body(), ), data: ThemeData( primarySwatch: _color, iconTheme: IconThemeData(color: _color), textTheme: TextTheme(button: TextStyle(backgroundColor: _color))), ); } Widget _body() { return Center( child: Column( children: <Widget>[ FlatButton( child: Text('切换颜色'), color: Theme.of(context).buttonColor, onPressed: () { setState(() { // _iconColor = Colors.orange; _color = _color == Colors.orange ? Colors.green : Colors.orange; }); // Navigator.of(context) // .push(MaterialPageRoute(builder: (ctx) => _BaseRoutePage())); }, ), Row( children: <Widget>[ Icon( Icons.add, size: 50, ), Text('颜色跟随主题') ], ), Theme( child: Row( children: <Widget>[ Icon( Icons.add, size: 50, ), Text('颜色固定') ], ), data: ThemeData( iconTheme: IconThemeData(color: Colors.red), ), ) ], ), ); } @override void initState() { _color = Colors.teal; super.initState(); } } <|start_filename|>lib/tips/bloc/base_login_cubit.dart<|end_filename|> export 'login_cubit/cubit/cubit.dart'; export 'login_cubit/model/login_cubit_models.dart'; export 'login_cubit/view/login_views.dart'; export 'login_cubit/page/login_pages.dart'; /// /// Created by fgyong on 2020/8/20. /// <|start_filename|>lib/tips/bloc/list_cubit/page/list_bloc_route.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fluttertest01/tips/bloc/list_cubit/model/list_data.dart'; import 'package:fluttertest01/tips/bloc/list_cubit/obs/post_obs.dart'; import '../bloc/list_bloc.dart'; import '../list_events/list_event.dart'; import '../list_status/list_state.dart'; import 'package:http/http.dart' as http; /// /// Created by fgyong on 2020/9/22. /// class ListBlocRoute extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider<PostBloc>( create: (_) => PostBloc(PostInitial(), http.Client())..add(PostFetchedEvent()), child: ListBlocPage(), ); } } class ListBlocPage extends StatefulWidget { @override State<StatefulWidget> createState() => _ListBLocPageState(); } class _ListBLocPageState extends State<ListBlocPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('列表 bloc'), ), body: _body(), ); } Widget _body() { return BlocBuilder( cubit: _postBloc, buildWhen: (pro, next) => pro != next, builder: (context, state) { if (state is PostInitial) { return Center( child: CircularProgressIndicator(), ); } else if (state is PostFailure) { return Center( child: Text('text error'), ); } else if (state is PostSuccess || state is PostSuccessIsLoading) { if ((state).posts.isEmpty) { return Center( child: Text('no posts'), ); } return CupertinoScrollbar( child: ListView.builder( controller: _scrollController, itemBuilder: (context, int index) { if (index < (state).posts.length) { return PostWidget(post: (state).posts[index]); } else { return BottomLoader(); } }, itemCount: state.hasReachedMax ? (state).posts.length : (state).posts.length + 1)); } else { return Center(); } }, ); } final _scrollController = ScrollController(); PostBloc _postBloc; @override void initState() { _scrollController.addListener(_onScroll); _postBloc = context.bloc<PostBloc>(); Bloc.observer = PostOBs(); super.initState(); } void _onScroll() { if (_scrollController.position.maxScrollExtent - _scrollController.position.pixels <= 200) { if ((_postBloc.state is PostSuccessIsLoading) == false) { _postBloc.add(PostFetchedEvent()); } } } } class PostWidget extends StatelessWidget { final Post post; const PostWidget({Key key, @required this.post}) : super(key: key); @override Widget build(BuildContext context) { return ListTile( leading: Text( '${post.id}', style: TextStyle(fontSize: 10.0), ), title: Text(post.title), isThreeLine: true, subtitle: Text(post.body), dense: true, ); } } class BottomLoader extends StatelessWidget { @override Widget build(BuildContext context) { return Container( alignment: Alignment.center, child: Center( child: SizedBox( width: 33, height: 33, child: CircularProgressIndicator( strokeWidth: 1.5, ), ), ), ); } } <|start_filename|>lib/tips/keepStateAlive.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/24. /// class BaseKeepStateAlive extends StatefulWidget { final bool keepAlive; BaseKeepStateAlive({Key key, this.keepAlive = false}) : super(key: key); @override _BaseKeepStateAliveState createState() => _BaseKeepStateAliveState(); } class _BaseKeepStateAliveState extends State<BaseKeepStateAlive> with AutomaticKeepAliveClientMixin { int _index = 0; List<Widget> _pages; PageController _pageController; @override void initState() { _pageController = PageController(); _pages = [ BaseKeepStateAlive2( keepAlive: true, ), BaseKeepStateAlive2( keepAlive: false, title: '状态不保持', ) ]; super.initState(); } @override Widget build(BuildContext context) { return Scaffold( // appBar: AppBar( // title: Text('状态保持'), // ), body: PageView.builder( itemBuilder: (ctx, index) { return _pages[index]; }, controller: _pageController, // physics: NeverScrollableScrollPhysics(), /// 滑动切换页面 pageSnapping: true, itemCount: _pages.length, onPageChanged: (index) { setState(() { _index = index; _pageController.animateToPage(index, duration: Duration(milliseconds: 300), curve: Curves.linearToEaseOut); }); }, ), bottomNavigationBar: BottomNavigationBar( items: [ BottomNavigationBarItem(icon: Icon(Icons.print), title: Text('首页')), BottomNavigationBarItem(icon: Icon(Icons.print), title: Text('第二页')) ], currentIndex: _index, onTap: (index) { setState(() { _index = index; _pageController.animateToPage(index, duration: Duration(milliseconds: 300), curve: Curves.linearToEaseOut); }); }, ), ); } bool _wantAlive = false; Widget _body() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ OutlineButton( child: Text('保持活性'), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (_) => BaseKeepStateAlive2( keepAlive: true, ))); }, ), OutlineButton( child: Text('不保持活性'), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (_) => BaseKeepStateAlive2( keepAlive: false, ))); }, ) ], ), // OutlineButton( // child: Text('push新页面'), // onPressed: () { // Navigator.of(context) // .push(MaterialPageRoute(builder: (_) => _PageSecond())); // }, // ) ], ), ); } @override bool get wantKeepAlive => _wantAlive; } class BaseKeepStateAlive2 extends StatefulWidget { final bool keepAlive; final String title; BaseKeepStateAlive2({Key key, this.keepAlive = false, this.title}) : super(key: key); @override _BaseKeepStateAliveState2 createState() => _BaseKeepStateAliveState2(); } class _BaseKeepStateAliveState2 extends State<BaseKeepStateAlive2> with AutomaticKeepAliveClientMixin { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('状态保持'), ), body: _body(), floatingActionButton: FloatingActionButton( child: Text('+'), heroTag: widget.title, onPressed: () { setState(() { _count += 1; }); }, ), ); } int _count = 0; Widget _body() { _count += 1; print('build'); return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(widget.title == null ? '状态保持A' : widget.title), Text('${_count}'), OutlineButton( child: Text('push新页面'), onPressed: () { Navigator.of(context) .push(MaterialPageRoute(builder: (_) => _PageSecond())); }, ) ], ), ); } @override bool get wantKeepAlive => widget.keepAlive; } class _PageSecond extends StatefulWidget { _PageSecond({Key key}) : super(key: key); @override __PageSecondState createState() => __PageSecondState(); } class __PageSecondState extends State<_PageSecond> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(''), ), body: _body(), ); } Widget _body() { return Center( child: OutlineButton( child: Text('返回查看'), onPressed: () { Navigator.of(context).maybePop(); }, ), ); } } <|start_filename|>lib/tips/bloc/login_cubit/model/base_login_model.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:equatable/equatable.dart'; /// /// Created by fgyong on 2020/8/19. /// enum LoginState { success, faild, isLoading, } enum BtnState { available, unAvailable } class LoginModel extends Equatable { final String name; final String password; final LoginState state; LoginModel({this.name, this.password, this.state}); @override List<Object> get props => [name, password, state, btnVisiable]; LoginModel copyWith({String name, String pwd, LoginState loginState}) { return LoginModel( name: name ?? this.name, password: <PASSWORD> ?? <PASSWORD>, state: loginState ?? this.state); } bool get btnVisiable => (password?.isNotEmpty ?? false) && (name?.isNotEmpty ?? false); @override String toString() { return '$props'; } } <|start_filename|>lib/main.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertest01/baseWidget/animation_text_kit.dart'; import 'package:fluttertest01/baseWidget/base_page_view.dart'; import 'package:fluttertest01/baseWidget/base_page_view_page.dart'; import 'package:fluttertest01/baseWidget/base_rotation.dart'; import 'package:fluttertest01/baseWidget/base_slider.dart'; import 'package:fluttertest01/scrollview/swich_page.dart'; import 'package:fluttertest01/u3d/u3d_page.dart'; import 'package:fluttertest01/video/base_download_file_page.dart'; import 'package:fluttertest01/video/base_video_ijk_page.dart'; import 'package:fluttertest01/video/base_video_page.dart'; import 'package:fluttertest01/page_view/page_view.dart'; import 'package:fluttertest01/tips/base_%20visibility_detector.dart'; import 'package:fluttertest01/tips/base_connect.dart'; import 'package:fluttertest01/tips/base_interactive_viewer.dart'; import 'package:fluttertest01/tips/base_qrcode.dart'; import 'package:fluttertest01/tips/base_slider.dart'; import 'package:fluttertest01/tips/get/get_example.dart'; import 'package:fluttertest01/tips/get/get_list_page.dart'; import 'package:fluttertest01/tips/get/get_login_page.dart'; import 'package:fluttertest01/tips/hive/base_hive.dart'; import 'package:fluttertest01/tips/revierpod/base_river_pod.dart'; import 'package:get/get.dart'; import 'package:get/utils.dart'; import 'package:hooks_riverpod/all.dart'; import 'mainUtil.dart'; void main() async { runApp(ProviderScope( child: MyApp(), )); // runZonedGuarded(() => runApp(new MyApp()), (Object error, StackTrace stack) { // print('${error.toString()} stack:${stack.toString()}'); // }); // await Hive.init('${getTemporaryDirectory()}'); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return GetMaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, dividerTheme: DividerThemeData( color: Colors.black12, thickness: 0.5, endIndent: 25, indent: 35, space: 1) // fontFamily: 'Merriweather' ), home: MyHome( title: 'Flutter Demo Home Page', ), initialRoute: '/', getPages: [ GetPage(name: '/', page: () => MyHome()), GetPage( name: GetLoginPage.routeName, page: () => GetLoginPage(), binding: GetLoginBind()) ], routes: { '/text': (ctx) => BaseWidgetTextPage(), '/btn': (ctx) => BaseButtons(), '/img': (ctx) => BaseImgAndIcon(), '/flex': (ctx) => BaseFlex(), '/sheet': (ctx) => BaseDialog(), '/sw': (ctx) => BaseSwitch(), '/field': (ctx) => BaseField(), '/in': (ctx) => BaseIndicator(), '/st': (ctx) => TapBox(), '/wheel': (ctx) => BaseScrollViewWheel(), '/align': (ctx) => BaseAlign(), '/stack': (ctx) => BaseStack(), '/row': (ctx) => BaseRowAndColumn(), '/pad': (ctx) => BasePadding(), '/flow': (ctx) => BaseFlowAndWrap(), '/box': (c) => BaseConstraints(), '/clip': (c) => BaseClip(), '/dbox': (c) => BaseDecoratedBox(), '/transform': (_) => BaseTransform(), '/contain': (_) => BaseContainer(), '/bars': (_) => BaseBars(), '/scrollview': (_) => BaseSingleChildScrollView(), '/list': (_) => BaseListView(), '/grid': (_) => BaseGridView(), '/cscrollview': (_) => BaseCustomScrollView(), '/listenoffset': (_) => BaseListenScrollView(), '/willpop': (_) => BaseWillPop(), '/sharedata': (_) => BaseShareData(), '/colortheme': (_) => BaseColorAndTheme(), '/futurestream': (_) => BaseFutureStream(), '/touchhandle': (_) => BaseTouchHandle(), '/gesture': (_) => BaseGesuredetetor(), '/ebus': (_) => BaseEventBus(), '/notifi': (_) => BaseNotificationPage(), '/animation': (_) => BaseAnimation(), '/route': (_) => BasePageRoute(), '/hero': (_) => BaseHreo(), '/jz': (_) => BaseTaggerAnimation(), '/animationswitch': (_) => BaseAnimationSwitcher(), '/diyanimation': (_) => BaseDIYPage(), '/BaseKeepStateAlive': (_) => BaseKeepStateAlive(), '/BaseFileRoute': (_) => BaseFileRoute(), '/BaseHttpClientRoute': (_) => BaseHttpClientRoute(), '/BaseHttpDioRoute': (_) => BaseHttpDioRoute(), '/BaseSocketRoute': (_) => BaseSocketRoute(), '/BaseJsonToModelRoute': (_) => BaseJsonToModelRoute(), '/BaseAsynAndISOlateRoute': (_) => BaseAsynAndISOlateRoute(), '/BaseProviderRoute': (_) => BaseProviderRoute(), '/BaseRecordRoute': (_) => BaseRecordRoute(), '/BaseAsync': (_) => BaseAsync(), '/BasePageViewRoute': (_) => BasePageViewRoute(), '/FYTabbarWidget': (_) => FYTabbarWidget(), '/WeChatSoundWidget': (_) => WeChatSoundWidget(), '/BaseBLoCRoute': (_) => BaseBLocRoute2(), BaseScopedPateRoute.routeName: (_) => BaseScopedPateRoute(), BaseReduxPateRoute.routeName: (_) => BaseReduxPateRoute(), BaseFishReduxPage.routeName: (_) => BaseFishReduxPage(), BaseBLoCPageRoute.routeName: (_) => BaseBLoCPageRoute(), BaseLoginPageRoute.routeName: (_) => BaseLoginPageRoute(), BaseProviderRouteProvider.routeName: (_) => BaseProviderRouteProvider(), BaseKeyPage.routeName: (_) => BaseKeyPage(), BaseLayoutPage.routeName: (_) => BaseLayoutPage(), BaseDartPage.routeName: (_) => BaseDartPage(), BaseRenderTree.routeName: (_) => BaseRenderTree(), BaseCustomListAnimationPage.routeName: (_) => BaseCustomListAnimationPage(), BaseImagePage.routeName: (_) => BaseImagePage(), BaseChannelRoute.routeName: (_) => BaseChannelRoute(), BaseTouchHandlePage.routenName: (_) => BaseTouchHandlePage(), BaseHive.routeName: (_) => BaseHive(), BaseGetPage.routeName: (_) => BaseGetPage(), BaseQRCodePage.routeName: (_) => BaseQRCodePage(), BaseInteractiveViewer.routeName: (_) => BaseInteractiveViewer(), GetListPageRoute.routeName: (_) => GetListPageRoute(), BaseRiverPodRoute.routeName: (_) => BaseRiverPodRoute(), CustomPageViewPage.routeName: (_) => CustomPageViewPage(), AnimationTextKitPage.routeName: (_) => AnimationTextKitPage(), BaseNetWorkConnect.routeName: (_) => BaseNetWorkConnect(), BaseSliderPage.routeName: (_) => BaseSliderPage(), BaseVisibilityDetector.routeName: (_) => BaseVisibilityDetector(), BaseSliderRangPage.routeName: (_) => BaseSliderRangPage(), BaseRotationBoxPage.routeName: (_) => BaseRotationBoxPage(), BasePageViewPage.routeName: (_) => BasePageViewPage(), BaseVideoPage.routeName: (_) => BaseVideoPage(), BaseVideoPage2.routeName: (_) => BaseVideoPage2(), BaseIJKVideoPage.routeName: (_) => BaseIJKVideoPage(), BaseDownFilePage.routeName: (_) => BaseDownFilePage(), BaseSwitchListTitlePage.routeName: (_) => BaseSwitchListTitlePage(), BaseU3DPage.routeName: (_) => BaseU3DPage(), }, ); } } class MyHome extends StatefulWidget { final String title; MyHome({Key key, this.title}) : super(key: key); @override State<StatefulWidget> createState() { return MyHomeState(); } } class MyHomeState extends State<MyHome> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('home'), ), body: SafeArea( child: _body(), ), ); } Widget _body() { Widget w = CupertinoScrollbar( child: CustomScrollView( slivers: <Widget>[ _title('基础组件', subTile: '文本、样式、按钮、图片、Icon、单选和复选框、输入框、进度指示器', list: [ _child( '文本 text 、style', '/text', ), _child('按钮', '/btn'), _child('图片和Icon', '/img'), _child('单选和复选', '/sw'), _child('输入框表单', '/field'), _child('进度指示器', '/in'), _child('弹窗', '/sheet'), _child('状态管理', '/st') ]), _title('布局', subTile: '线性:Row、Column、弹性:Flex、流水布局:Wrap、Flow、层叠:Stack、Positioned', list: [ _child('绝对位置stack、Positioned', '/stack'), _child('相对位置', '/align'), _child('弹性布局 Row Column', '/row'), _child('弹性布局 Flex', '/flex'), _child('流式布局 wrap flow', '/flow'), ]), _title('容器', subTile: 'padding、margin、尺寸、装饰、变换、脚手架、tabBar。底部导航、APPBar', list: [ _child('padding', '/pad'), _child('container 容器', '/contain'), _child('尺寸限制容器', '/box'), _child('装饰类容器', '/dbox'), _child('变换transform', '/transform'), _child('裁剪容器', '/clip'), _child('导航 脚手架 Tabbar', '/bars'), ]), _title('滑动组件', subTile: 'SingleScrollView、List、GridView、CustomScrollView', list: [ _child('SingleScrollView', '/scrollview'), _child('listView', '/list'), _child('gridView', '/grid'), _child('customScrollview', '/cscrollview'), _child('监听滚动', '/listenoffset'), _child('车轮list', '/wheel'), _child('SwitchList', BaseSwitchListTitlePage.routeName), ]), _title('功能能组件', subTile: '导航返回拦截、数据共享、跨组件状态共享、颜色和主题、异步更新UI', list: [ _child('导航返回键拦截', '/willpop'), _child('共享数据', '/sharedata'), _child('颜色和主题', '/colortheme'), _child('异步更新', '/futurestream'), _child('选择组件', BaseSliderRangPage.routeName), _child('旋转box', BaseRotationBoxPage.routeName), _child('滑动渐变pageView', BasePageViewPage.routeName), ]), _title('时间处理和通知', subTile: '原始指针和时间、手势、全局总线、通知', list: [ _child('原始指针处理', '/touchhandle'), _child('手势识别', '/gesture'), _child('全局事件总线', '/ebus'), _child('通知', '/notifi'), ]), _title('动画', subTile: '路由动画、Hero动画、交织动画、过度组件(AnimatedSwitcher)', list: [ _child('动画结构', '/animation'), _child('过度动画', '/route'), _child('hero动画', '/hero'), _child('交织动画', '/jz'), _child('切换动画', '/animationswitch'), _child('过渡性动画', '/diyanimation'), ]), // _title( // '自定义组件', // ), _title('文件操作与网络请求', subTile: 'Http HttpClient Dio Http分块下载、WebSocket、Json转Model', list: [ _child('文件读写', '/BaseFileRoute'), _child('HTTP client', '/BaseHttpClientRoute'), _child('dio请求', '/BaseHttpDioRoute'), _child('使用Socket', '/BaseSocketRoute'), _child('json 转model', '/BaseJsonToModelRoute'), ]), _title('其他每周小部件与Tips', subTile: '状态保持、状态管理、详解key、同步与异步', list: [ _child('保持页面数据不丢失', '/BaseKeepStateAlive'), _child('异步与多线程', '/BaseAsynAndISOlateRoute'), _child('异步与同步数据流', '/BaseAsync'), _child('录音与播放', '/BaseRecordRoute'), _child('pageview 联动', '/BasePageViewRoute'), _child('仿头条项目', '/FYTabbarWidget'), _child('微信语音动画', '/WeChatSoundWidget'), _child('状态管理(1)ScopedModel', BaseScopedPateRoute.routeName), _child('状态管理(2)redux', BaseReduxPateRoute.routeName), _child('状态管理(3)BLoC', BaseBLoCPageRoute.routeName), _child('状态管理(4)provider', BaseProviderRouteProvider.routeName), _child('阿里fish(5) redux', BaseFishReduxPage.routeName), _child('详解 key', BaseKeyPage.routeName), _child('获取widget大小的layoutBuilder', BaseLayoutPage.routeName), _child('rxdart', BaseDartPage.routeName), _child('渲染树', BaseRenderTree.routeName), _child('图片加载', BaseImagePage.routeName), _child('通道', BaseChannelRoute.routeName), _child('触摸分发流程', BaseTouchHandlePage.routenName), _child('hive 数据存储', BaseHive.routeName), _child('get demo', BaseGetPage.routeName), _child("扫描二维码", BaseQRCodePage.routeName), _child("放大缩小组件", BaseInteractiveViewer.routeName), _child('新的状态管理思路 riverPod', BaseRiverPodRoute.routeName), _child('网络状态监控', BaseNetWorkConnect.routeName), _child('cell滑动删除效果', BaseSliderPage.routeName), _child('真实曝光', BaseVisibilityDetector.routeName), ]), _title('自定义的动画组件', list: [ _child('page controller', BaseCustomListAnimationPage.routeName), _child('page view', CustomPageViewPage.routeName), _child('动画文本', AnimationTextKitPage.routeName), _child('3d', BaseU3DPage.routeName), ]), _title('视频,gif', list: [ _child('视频', BaseVideoPage.routeName), _child('youTobBe视频', BaseVideoPage2.routeName), _child('ijk', BaseIJKVideoPage.routeName), _child('下载视频', BaseDownFilePage.routeName), ]), ], ), ); return w; } Widget _title(String text, {List<Widget> list, String subTile = ''}) { list ??= []; if (list.length == 0) { list.add(Container( height: 0.1, color: Colors.black38, )); } return SliverToBoxAdapter( child: Card( margin: EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10), child: ExpansionTile( subtitle: Container( margin: EdgeInsets.only(left: 20, top: 5, bottom: 5, right: 10), child: Text( subTile, style: ThemeYo.subTileTextStyle, ), ), title: Container( margin: EdgeInsets.only(left: 20, top: 5, bottom: 5, right: 10), child: Text( text, style: ThemeYo.textStyle, ), ), children: list, ), ), ); } Widget _child(String title, String route, {bool isFirst = false}) { List<Widget> list = new List(); list.add(const Divider()); list.add(Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( child: FlatButton( child: Container( margin: EdgeInsets.only(left: 20), child: Row( children: <Widget>[ Text( title, style: ThemeYo.itemTextStyle, ), Expanded( flex: 1, child: SizedBox(), ), Icon( Icons.arrow_forward_ios, color: Colors.black12, size: 14, ) ], ), alignment: Alignment.centerLeft, ), onPressed: () { // Navigator.pushNamed(this.context, route); Get.toNamed(route); }, ), ), ], )); return Container( child: Column( children: list, ), // height: 25, ); } } <|start_filename|>lib/tips/base_ visibility_detector.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:visibility_detector/visibility_detector.dart'; class BaseVisibilityDetector extends StatefulWidget { @override State<StatefulWidget> createState() => _BaseVisibilityDetectorState(); static String get routeName => '/BaseVisibilityDetector'; } class _BaseVisibilityDetectorState extends State<BaseVisibilityDetector> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('BaseVisibilityDetector'), ), body: CustomScrollView( slivers: [ _item('0'), _item('1'), _item('2'), _item('3'), _item('4'), _item('5'), _item('6'), _item2('6'), _item('7'), _item('8'), _item('9'), _item('10'), ], ), ); } SliverToBoxAdapter _item(String index) { return SliverToBoxAdapter( child: VisibilityDetector( key: ValueKey('key_$index'), child: Container( height: 100, child: Text('key_$index'), ), onVisibilityChanged: (show) { print('$index ${show.visibleFraction * 100}'); }, ), ); } SliverToBoxAdapter _item2(String index) { return SliverToBoxAdapter( child: VisibilityDetector( key: ValueKey('key2_$index'), child: SizedBox( height: 100, child: TextField(), ), onVisibilityChanged: (show) { print('$index ${show.visibleFraction * 100}'); }, ), ); } } <|start_filename|>lib/container/base_clip.dart<|end_filename|> import 'dart:math'; import 'package:flutter/material.dart'; class BaseClip extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('裁剪部件'), ), body: Center( child: _body2(), ), ); } Widget _body() { Widget avator = Container( width: 100, height: 100, color: Colors.blue, ); return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('ClipOval 剪切圆形'), ClipOval( child: avator, ), Text('ClipOval 圆角'), ClipRRect( borderRadius: BorderRadius.all(Radius.circular(10)), child: avator, ), Text('ClipOval 剪切为原来的1/4'), ClipRect( child: Align( alignment: Alignment.topRight, widthFactor: 0.5, heightFactor: 0.5, child: avator, ), ) ], ); } Widget _body2() { Widget avator = Container(height: 200,width: 200,child: Image.asset('img/1.jpeg',),); return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ClipPath( child: avator, clipper: BaseCustomPath(), ) ], ); } } class BaseCustomPath extends CustomClipper<Path> { @override Path getClip(Size size) { Path path = Path(); path.moveTo(size.width / 2, 40); path.lineTo(size.width - 15, size.height - 15); path.lineTo(15, size.height - 15); double p1 = 1 * pi; path.addArc(Rect.fromLTWH(30,30,30,30), p1, p1 + 2 * pi); path.lineTo(15, size.height - 15); path.addArc( Rect.fromLTWH(size.width - 30,30,30,30), p1, p1 + 2 * pi); path.lineTo(0, 0); return path; } @override bool shouldReclip(CustomClipper oldClipper) { return this != oldClipper; } } <|start_filename|>lib/tips/base_key.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/8/21. /// class BaseKeyPage extends StatefulWidget { BaseKeyPage({Key key}) : super(key: key); @override _BaseKeyPageState createState() => _BaseKeyPageState(); static String get routeName => '/BaseKeyPage'; } class _BaseKeyPageState extends State<BaseKeyPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('key'), ), body: _body(), floatingActionButton: FloatingActionButton( child: Icon(Icons.refresh), onPressed: () { setState(() { count += 1; }); }, ), ); } Student _student; int count = 0; Widget _body() { _student = Student('老王'); return Column( children: <Widget>[ Text('ValueKey 包含的值相等就判定为相等'), TextField( key: ValueKey(Student('老王1')), ), TextField( key: ValueKey(Student('老王2')), ), Text( 'objetKey 必须引用相同地址才判断为相等\n' '每次new 就生成不同地址的对象', textAlign: TextAlign.center, ), TextField( key: ObjectKey(Student('老王')), ), TextField( key: ObjectKey(Student('老王')), ), TextField( key: UniqueKey(), ), TextField( key: UniqueKey(), ), AnimatedSwitcher( duration: Duration(milliseconds: 1000), child: Container( key: UniqueKey(), height: 100, width: 100, color: Colors.primaries[count % Colors.primaries.length], ), ), SizedBox( height: 20, ), _Container(_key), OutlineButton( child: Text('global key 刷新'), onPressed: () { _key.currentState.setState(() {}); }, ) ], ); } GlobalKey _key = GlobalKey(); } class _Container extends StatefulWidget { /// 使用[StatefulWidget] 的[key]来获取[state] _Container(Key key) : super(key: key); @override State<StatefulWidget> createState() { return __ContainerState(); } } class __ContainerState extends State<_Container> { int count = 0; @override Widget build(BuildContext context) { count += 1; /// 每次build 都更换颜色 return Container( height: 100, width: 100, color: Colors.primaries[count % Colors.primaries.length], ); } } class Student { final String name; Student(this.name); @override int get hashCode => name.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is Student && runtimeType == other.runtimeType && name == other.name; } <|start_filename|>lib/tips/bloc/login_cubit/cubit/cubit.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; export 'base_login_cubit.dart'; /// /// Created by fgyong on 2020/8/20. /// <|start_filename|>lib/file_and_http/http_socket.dart<|end_filename|> import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; /// /// Created by fgyong on 2020/7/27. /// import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter_easyhub/flutter_easy_hub.dart'; /// /// Created by fgyong on 2020/7/27. /// class BaseSocketRoute extends StatefulWidget { BaseSocketRoute({Key key}) : super(key: key); @override _BaseHttpDioRouteState createState() => _BaseHttpDioRouteState(); } class _BaseHttpDioRouteState extends State<BaseSocketRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Socket'), ), body: _body(), ); } String _string = ''; Widget _body() { return Center( child: FlutterEasyHub( child: SingleChildScrollView( child: Row( children: <Widget>[ Expanded( child: Text(_string ?? ''), ) ], ), ), ), ); } @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { _getData(); }); } void _getData() async { var socket = await Socket.connect('github.com', 80); socket.write('GET / HTTP:/1.1'); socket.write('Host:github.com'); socket.write('Connection:close'); socket.writeln(); utf8.decoder.bind(socket).listen((event) { print(event); _string += event; setState(() {}); }); socket.flush(); await socket.close(); //关闭 } } <|start_filename|>lib/tips/bloc/login_cubit/page/base_login_page.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../base_login_cubit.dart'; /// /// Created by fgyong on 2020/8/19. /// class BaseLoginPageRoute extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider( create: (_) => LoginCubit(LoginModel()), child: BaseLoginPage(), ); } static String routeName = '/BaseLoginPageRoute'; MaterialPageRoute get route => MaterialPageRoute(builder: (_) => BaseLoginPageRoute()); } <|start_filename|>lib/file_and_http/fileAction.dart<|end_filename|> import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; /// /// Created by fgyong on 2020/7/27. /// class BaseFileRoute extends StatefulWidget { BaseFileRoute({Key key}) : super(key: key); @override _BaseFileRouteState createState() => _BaseFileRouteState(); } class _BaseFileRouteState extends State<BaseFileRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('文件读取'), ), body: _body(), floatingActionButton: FloatingActionButton( child: Text('+'), onPressed: () { setState(() { _count += 1; }); }, ), ); } int _count = 0; String _string = ''; String _error = ''; String _writeStr = ''; Widget _body() { return Center( child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: Text(_error), ), OutlineButton( child: Text('创建文件文件'), onPressed: _createFile, ), ], ), Row( children: <Widget>[ OutlineButton( child: Text('读取文件'), onPressed: _read, ), Expanded( child: Text(_string), ), ], ), Row( children: <Widget>[ OutlineButton( child: Text('写入文件'), onPressed: _write, ), Expanded( child: Text(_writeStr), ) ], ), Row( children: <Widget>[ OutlineButton( child: Text('清空文件内容'), onPressed: _clearData, ), Text(_count.toString()), ], ) ], ), ); } void _read() async { var file = new File(await _path()); var st = await file.readAsString(); setState(() { _string = st; }); } void _write() async { var file = new File(await _path()); var st = await file.readAsString(); st += ' $_count'; file.writeAsString( st, ); setState(() { _writeStr = '写入成功 $_count'; }); } void _clearData() async { var file = new File(await _path()); var st = await file.readAsString(); st += ' $_count'; file.writeAsString( '', ); setState(() { _writeStr = '文件已清空'; }); } Future<String> _path() async { var path = await getTemporaryDirectory(); var all = path.path + '/text.txt'; return all; } void _createFile() async { try { var path = await getTemporaryDirectory(); var all = path.path + '/text.txt'; var current = Directory(all); if (current.existsSync() == false) { var d = new File(all); var f = await d.create(); if (f.existsSync()) { print('创建成功 ${d.path}'); setState(() { _error = '创建成功 ${d.path}'; }); } else { setState(() { _error = '文件创建失败'; }); } } else { setState(() { _error = '文件已存在'; }); } } catch (e) { setState(() { _error = '${e.toString()}'; }); print(e.toString()); } } }
ifgyong/flutter-example
<|start_filename|>send.go<|end_filename|> package scratchbuild import ( "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "strings" digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" ) // Options contains configuration options for the client type Options struct { // Dir is the directory that we build the container from Dir string // Name is the name of the repository Name string // BaseURL is the base URL of the repository. For Docker this is https://index.docker.io // For GCR it is https://gcr.io BaseURL string // User string Password string // Token is the bearer token for the repository. For GCR you can use $(gcloud auth print-access-token). // For Docker, supply your Docker Hub username and password instead. Token func() string // Tag is the tag for the image. Set to "latest" if you're out of ideas Tag string } // Client lets you send a container up to a repository type Client struct { Options } // New creates a new Client func New(o *Options) *Client { return &Client{ Options: *o, } } func (c *Client) newRequest(method, url string, body io.Reader) (*http.Request, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, err } if c.Token != nil { req.Header.Set("Authorization", "Bearer "+c.Token()) } return req, nil } func (c *Client) sendBlob(digest digest.Digest, data []byte) error { uploaded, err := c.isBlobUploaded(digest) if err != nil { return errors.Wrap(err, "could not check if blob is already uploaded") } if uploaded { fmt.Printf("blob already uploaded\n") return nil } // The repository tells us where the blob should be uploaded to loc, err := c.getBlobUploadLocation() if err != nil { return errors.Wrap(err, "could not get location for blob upload") } if err := c.uploadBlob(loc, digest, data); err != nil { return errors.Wrap(err, "blob upload failed") } return nil } func (c *Client) isBlobUploaded(digest digest.Digest) (bool, error) { u := strings.Join([]string{c.BaseURL, "v2", c.Name, "blobs", digest.String()}, "/") req, err := c.newRequest(http.MethodHead, u, nil) if err != nil { return false, errors.Wrap(err, "could nto build request") } rsp, err := http.DefaultClient.Do(req) if err != nil { return false, errors.Wrap(err, "blob upload failed") } return rsp.StatusCode == http.StatusOK, nil } func (c *Client) getBlobUploadLocation() (*url.URL, error) { u := strings.Join([]string{c.BaseURL, "v2", c.Name, "blobs/uploads/"}, "/") req, err := c.newRequest(http.MethodPost, u, nil) if err != nil { return nil, errors.Wrap(err, "could not build request") } rsp, err := http.DefaultClient.Do(req) if err != nil { return nil, errors.Wrap(err, "blob upload failed") } defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) if err != nil { return nil, errors.Wrap(err, "failed to read body on blob upload response") } if rsp.StatusCode != http.StatusAccepted { return nil, errors.Errorf("unexpected status %s. %s", rsp.Status, string(body)) } return rsp.Location() } func (c *Client) uploadBlob(loc *url.URL, digest digest.Digest, data []byte) error { q := loc.Query() q.Set("digest", digest.String()) loc.RawQuery = q.Encode() r := bytes.NewReader(data) req, err := c.newRequest(http.MethodPut, loc.String(), r) if err != nil { return err } req.ContentLength = int64(len(data)) req.Header.Set("Content-Type", "application/octet-stream") rsp, err := http.DefaultClient.Do(req) if err != nil { return errors.Wrap(err, "blob upload failed") } defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) if err != nil { return errors.Wrap(err, "failed to read body on blob upload response") } if rsp.StatusCode != http.StatusCreated { return errors.Errorf("unexpected status %s. %s", rsp.Status, string(body)) } return nil } func (c *Client) sendManifest(digest digest.Digest, data []byte, mediaType string) error { u := strings.Join([]string{c.BaseURL, "v2", c.Name, "manifests", c.Tag}, "/") b := bytes.NewReader(data) req, err := c.newRequest(http.MethodPut, u, b) if err != nil { return err } req.Header.Set("Content-Type", mediaType) log.Printf("Sending %s", u) rsp, err := http.DefaultClient.Do(req) if err != nil { return errors.Wrap(err, "manifest upload failed") } defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) if err != nil { return errors.Wrap(err, "failed to read body on manifest upload response") } if rsp.StatusCode != http.StatusCreated && rsp.StatusCode != http.StatusOK { return errors.Errorf("unexpected status %s. %s", rsp.Status, string(body)) } return nil } <|start_filename|>cmd/scratch/main.go<|end_filename|> package main import ( "bytes" "flag" "fmt" "os" "strings" "github.com/philpearl/scratchbuild" ) func validate(o *scratchbuild.Options) error { if o.Name == "" { return fmt.Errorf("You must specify a name for the image") } return nil } func main() { var o scratchbuild.Options flag.StringVar(&o.Dir, "dir", "./", "Directory containing container content") flag.StringVar(&o.Name, "name", "", "Image name") // THe docker repository is https://index.docker.io flag.StringVar(&o.BaseURL, "regurl", "https://eu.gcr.io", "Registry URL") // If you don't have a token, pass in a user name and password and we'll go and // get one. For the docker repository this is your Docker Hub username & password. // Don't use these for the GCP repository flag.StringVar(&o.User, "user", "", "Registry user name") flag.StringVar(&o.Password, "password", "", "Registry password") flag.StringVar(&o.Token, "token", "", "Repository bearer token. For the GCP repository use this with $(gcloud auth print-access-token)") flag.StringVar(&o.Tag, "tag", "latest", "Image tag") var env multiString flag.Var(&env, "env", "Environment variables. Repeat to add more definitions, e.g. '-env PATH=/hat -env USER=postgras'") var volumes multiString flag.Var(&volumes, "vol", "Volumes. Repeat to add more definitions, e.g. '-vol /etc/myapp -env /var/myapp'") var entrypoint string flag.StringVar(&entrypoint, "entrypoint", "", "Entrypoint.") var labels multiPair flag.Var(&labels, "label", "Labels. Repeat to add more definitions, e.g. '-label label1=green -label label2=red'") flag.Parse() if err := validate(&o); err != nil { fmt.Fprintln(os.Stderr, err) flag.Usage() os.Exit(1) } c := scratchbuild.New(&o) if c.Token == "" { var err error c.Token, err = c.Auth() if err != nil { fmt.Fprintf(os.Stderr, "Failed to authenticate. %s\n", err) os.Exit(1) } } b := &bytes.Buffer{} if err := scratchbuild.TarDirectory(c.Dir, b); err != nil { fmt.Fprintf(os.Stderr, "Failed to build tar file. %s\n", err) os.Exit(1) } imageConfig := scratchbuild.ImageConfig{ Env: env, } if entrypoint != "" { imageConfig.Entrypoint = strings.Fields(entrypoint) } if len(labels) > 0 { imageConfig.Labels = make(map[string]string, len(labels)) for _, l := range labels { imageConfig.Labels[l[0]] = l[1] } } if len(volumes) > 0 { imageConfig.Volumes = make(map[string]struct{}, len(volumes)) for _, v := range volumes { imageConfig.Volumes[v] = struct{}{} } } if err := c.BuildImage(&imageConfig, b.Bytes()); err != nil { fmt.Fprintf(os.Stderr, "Failed to build image. %s\n", err) } } type multiString []string func (i *multiString) String() string { return "my string representation" } func (i *multiString) Set(value string) error { *i = append(*i, value) return nil } type pair [2]string type multiPair []pair func (i *multiPair) String() string { return "lalala" } func (i *multiPair) Set(value string) error { p := strings.SplitN(value, "=", 2) if len(p) != 2 { return fmt.Errorf("should contain an =") } *i = append(*i, pair{p[0], p[1]}) return nil }
BrendanThompson/scratchbuild
<|start_filename|>js/as/external/api/fuotaDeployment_pb.js<|end_filename|> /** * @fileoverview * @enhanceable * @public */ // GENERATED CODE -- DO NOT EDIT! var jspb = require('google-protobuf'); var goog = jspb; var global = Function('return this')(); var google_api_annotations_pb = require('../../../google/api/annotations_pb.js'); var google_protobuf_timestamp_pb = require('google-protobuf/google/protobuf/timestamp_pb.js'); var google_protobuf_duration_pb = require('google-protobuf/google/protobuf/duration_pb.js'); var as_external_api_multicastGroup_pb = require('../../../as/external/api/multicastGroup_pb.js'); goog.exportSymbol('proto.api.CreateFUOTADeploymentForDeviceRequest', null, global); goog.exportSymbol('proto.api.CreateFUOTADeploymentForDeviceResponse', null, global); goog.exportSymbol('proto.api.FUOTADeployment', null, global); goog.exportSymbol('proto.api.FUOTADeploymentDeviceListItem', null, global); goog.exportSymbol('proto.api.FUOTADeploymentDeviceState', null, global); goog.exportSymbol('proto.api.FUOTADeploymentListItem', null, global); goog.exportSymbol('proto.api.GetFUOTADeploymentDeviceRequest', null, global); goog.exportSymbol('proto.api.GetFUOTADeploymentDeviceResponse', null, global); goog.exportSymbol('proto.api.GetFUOTADeploymentRequest', null, global); goog.exportSymbol('proto.api.GetFUOTADeploymentResponse', null, global); goog.exportSymbol('proto.api.ListFUOTADeploymentDevicesRequest', null, global); goog.exportSymbol('proto.api.ListFUOTADeploymentDevicesResponse', null, global); goog.exportSymbol('proto.api.ListFUOTADeploymentRequest', null, global); goog.exportSymbol('proto.api.ListFUOTADeploymentResponse', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.FUOTADeployment = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.FUOTADeployment, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.FUOTADeployment.displayName = 'proto.api.FUOTADeployment'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.FUOTADeployment.prototype.toObject = function(opt_includeInstance) { return proto.api.FUOTADeployment.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.FUOTADeployment} msg The msg instance to transform. * @return {!Object} */ proto.api.FUOTADeployment.toObject = function(includeInstance, msg) { var f, obj = { id: msg.getId(), name: msg.getName(), groupType: msg.getGroupType(), dr: msg.getDr(), frequency: msg.getFrequency(), payload: msg.getPayload_asB64(), redundancy: msg.getRedundancy(), multicastTimeout: msg.getMulticastTimeout(), unicastTimeout: (f = msg.getUnicastTimeout()) && google_protobuf_duration_pb.Duration.toObject(includeInstance, f), state: msg.getState(), nextStepAfter: (f = msg.getNextStepAfter()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.FUOTADeployment} */ proto.api.FUOTADeployment.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.FUOTADeployment; return proto.api.FUOTADeployment.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.FUOTADeployment} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.FUOTADeployment} */ proto.api.FUOTADeployment.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setId(value); break; case 2: var value = /** @type {string} */ (reader.readString()); msg.setName(value); break; case 3: var value = /** @type {!proto.api.MulticastGroupType} */ (reader.readEnum()); msg.setGroupType(value); break; case 4: var value = /** @type {number} */ (reader.readUint32()); msg.setDr(value); break; case 5: var value = /** @type {number} */ (reader.readUint32()); msg.setFrequency(value); break; case 6: var value = /** @type {!Uint8Array} */ (reader.readBytes()); msg.setPayload(value); break; case 7: var value = /** @type {number} */ (reader.readUint32()); msg.setRedundancy(value); break; case 8: var value = /** @type {number} */ (reader.readUint32()); msg.setMulticastTimeout(value); break; case 9: var value = new google_protobuf_duration_pb.Duration; reader.readMessage(value,google_protobuf_duration_pb.Duration.deserializeBinaryFromReader); msg.setUnicastTimeout(value); break; case 10: var value = /** @type {string} */ (reader.readString()); msg.setState(value); break; case 11: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setNextStepAfter(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.FUOTADeployment} message * @param {!jspb.BinaryWriter} writer */ proto.api.FUOTADeployment.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.FUOTADeployment.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.FUOTADeployment.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getId(); if (f.length > 0) { writer.writeString( 1, f ); } f = this.getName(); if (f.length > 0) { writer.writeString( 2, f ); } f = this.getGroupType(); if (f !== 0.0) { writer.writeEnum( 3, f ); } f = this.getDr(); if (f !== 0) { writer.writeUint32( 4, f ); } f = this.getFrequency(); if (f !== 0) { writer.writeUint32( 5, f ); } f = this.getPayload_asU8(); if (f.length > 0) { writer.writeBytes( 6, f ); } f = this.getRedundancy(); if (f !== 0) { writer.writeUint32( 7, f ); } f = this.getMulticastTimeout(); if (f !== 0) { writer.writeUint32( 8, f ); } f = this.getUnicastTimeout(); if (f != null) { writer.writeMessage( 9, f, google_protobuf_duration_pb.Duration.serializeBinaryToWriter ); } f = this.getState(); if (f.length > 0) { writer.writeString( 10, f ); } f = this.getNextStepAfter(); if (f != null) { writer.writeMessage( 11, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.FUOTADeployment} The clone. */ proto.api.FUOTADeployment.prototype.cloneMessage = function() { return /** @type {!proto.api.FUOTADeployment} */ (jspb.Message.cloneMessage(this)); }; /** * optional string id = 1; * @return {string} */ proto.api.FUOTADeployment.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.FUOTADeployment.prototype.setId = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional string name = 2; * @return {string} */ proto.api.FUOTADeployment.prototype.getName = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 2, "")); }; /** @param {string} value */ proto.api.FUOTADeployment.prototype.setName = function(value) { jspb.Message.setField(this, 2, value); }; /** * optional MulticastGroupType group_type = 3; * @return {!proto.api.MulticastGroupType} */ proto.api.FUOTADeployment.prototype.getGroupType = function() { return /** @type {!proto.api.MulticastGroupType} */ (jspb.Message.getFieldProto3(this, 3, 0)); }; /** @param {!proto.api.MulticastGroupType} value */ proto.api.FUOTADeployment.prototype.setGroupType = function(value) { jspb.Message.setField(this, 3, value); }; /** * optional uint32 dr = 4; * @return {number} */ proto.api.FUOTADeployment.prototype.getDr = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 4, 0)); }; /** @param {number} value */ proto.api.FUOTADeployment.prototype.setDr = function(value) { jspb.Message.setField(this, 4, value); }; /** * optional uint32 frequency = 5; * @return {number} */ proto.api.FUOTADeployment.prototype.getFrequency = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 5, 0)); }; /** @param {number} value */ proto.api.FUOTADeployment.prototype.setFrequency = function(value) { jspb.Message.setField(this, 5, value); }; /** * optional bytes payload = 6; * @return {!(string|Uint8Array)} */ proto.api.FUOTADeployment.prototype.getPayload = function() { return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldProto3(this, 6, "")); }; /** * optional bytes payload = 6; * This is a type-conversion wrapper around `getPayload()` * @return {string} */ proto.api.FUOTADeployment.prototype.getPayload_asB64 = function() { return /** @type {string} */ (jspb.Message.bytesAsB64( this.getPayload())); }; /** * optional bytes payload = 6; * Note that Uint8Array is not supported on all browsers. * @see http://caniuse.com/Uint8Array * This is a type-conversion wrapper around `getPayload()` * @return {!Uint8Array} */ proto.api.FUOTADeployment.prototype.getPayload_asU8 = function() { return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( this.getPayload())); }; /** @param {!(string|Uint8Array)} value */ proto.api.FUOTADeployment.prototype.setPayload = function(value) { jspb.Message.setField(this, 6, value); }; /** * optional uint32 redundancy = 7; * @return {number} */ proto.api.FUOTADeployment.prototype.getRedundancy = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 7, 0)); }; /** @param {number} value */ proto.api.FUOTADeployment.prototype.setRedundancy = function(value) { jspb.Message.setField(this, 7, value); }; /** * optional uint32 multicast_timeout = 8; * @return {number} */ proto.api.FUOTADeployment.prototype.getMulticastTimeout = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 8, 0)); }; /** @param {number} value */ proto.api.FUOTADeployment.prototype.setMulticastTimeout = function(value) { jspb.Message.setField(this, 8, value); }; /** * optional google.protobuf.Duration unicast_timeout = 9; * @return {proto.google.protobuf.Duration} */ proto.api.FUOTADeployment.prototype.getUnicastTimeout = function() { return /** @type{proto.google.protobuf.Duration} */ ( jspb.Message.getWrapperField(this, google_protobuf_duration_pb.Duration, 9)); }; /** @param {proto.google.protobuf.Duration|undefined} value */ proto.api.FUOTADeployment.prototype.setUnicastTimeout = function(value) { jspb.Message.setWrapperField(this, 9, value); }; proto.api.FUOTADeployment.prototype.clearUnicastTimeout = function() { this.setUnicastTimeout(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeployment.prototype.hasUnicastTimeout = function() { return jspb.Message.getField(this, 9) != null; }; /** * optional string state = 10; * @return {string} */ proto.api.FUOTADeployment.prototype.getState = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 10, "")); }; /** @param {string} value */ proto.api.FUOTADeployment.prototype.setState = function(value) { jspb.Message.setField(this, 10, value); }; /** * optional google.protobuf.Timestamp next_step_after = 11; * @return {proto.google.protobuf.Timestamp} */ proto.api.FUOTADeployment.prototype.getNextStepAfter = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 11)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.FUOTADeployment.prototype.setNextStepAfter = function(value) { jspb.Message.setWrapperField(this, 11, value); }; proto.api.FUOTADeployment.prototype.clearNextStepAfter = function() { this.setNextStepAfter(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeployment.prototype.hasNextStepAfter = function() { return jspb.Message.getField(this, 11) != null; }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.FUOTADeploymentListItem = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.FUOTADeploymentListItem, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.FUOTADeploymentListItem.displayName = 'proto.api.FUOTADeploymentListItem'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.FUOTADeploymentListItem.prototype.toObject = function(opt_includeInstance) { return proto.api.FUOTADeploymentListItem.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.FUOTADeploymentListItem} msg The msg instance to transform. * @return {!Object} */ proto.api.FUOTADeploymentListItem.toObject = function(includeInstance, msg) { var f, obj = { id: msg.getId(), createdAt: (f = msg.getCreatedAt()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f), updatedAt: (f = msg.getUpdatedAt()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f), name: msg.getName(), state: msg.getState(), nextStepAfter: (f = msg.getNextStepAfter()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.FUOTADeploymentListItem} */ proto.api.FUOTADeploymentListItem.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.FUOTADeploymentListItem; return proto.api.FUOTADeploymentListItem.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.FUOTADeploymentListItem} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.FUOTADeploymentListItem} */ proto.api.FUOTADeploymentListItem.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setId(value); break; case 2: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setCreatedAt(value); break; case 3: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setUpdatedAt(value); break; case 4: var value = /** @type {string} */ (reader.readString()); msg.setName(value); break; case 5: var value = /** @type {string} */ (reader.readString()); msg.setState(value); break; case 6: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setNextStepAfter(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.FUOTADeploymentListItem} message * @param {!jspb.BinaryWriter} writer */ proto.api.FUOTADeploymentListItem.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.FUOTADeploymentListItem.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.FUOTADeploymentListItem.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getId(); if (f.length > 0) { writer.writeString( 1, f ); } f = this.getCreatedAt(); if (f != null) { writer.writeMessage( 2, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } f = this.getUpdatedAt(); if (f != null) { writer.writeMessage( 3, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } f = this.getName(); if (f.length > 0) { writer.writeString( 4, f ); } f = this.getState(); if (f.length > 0) { writer.writeString( 5, f ); } f = this.getNextStepAfter(); if (f != null) { writer.writeMessage( 6, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.FUOTADeploymentListItem} The clone. */ proto.api.FUOTADeploymentListItem.prototype.cloneMessage = function() { return /** @type {!proto.api.FUOTADeploymentListItem} */ (jspb.Message.cloneMessage(this)); }; /** * optional string id = 1; * @return {string} */ proto.api.FUOTADeploymentListItem.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.FUOTADeploymentListItem.prototype.setId = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional google.protobuf.Timestamp created_at = 2; * @return {proto.google.protobuf.Timestamp} */ proto.api.FUOTADeploymentListItem.prototype.getCreatedAt = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 2)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.FUOTADeploymentListItem.prototype.setCreatedAt = function(value) { jspb.Message.setWrapperField(this, 2, value); }; proto.api.FUOTADeploymentListItem.prototype.clearCreatedAt = function() { this.setCreatedAt(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeploymentListItem.prototype.hasCreatedAt = function() { return jspb.Message.getField(this, 2) != null; }; /** * optional google.protobuf.Timestamp updated_at = 3; * @return {proto.google.protobuf.Timestamp} */ proto.api.FUOTADeploymentListItem.prototype.getUpdatedAt = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 3)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.FUOTADeploymentListItem.prototype.setUpdatedAt = function(value) { jspb.Message.setWrapperField(this, 3, value); }; proto.api.FUOTADeploymentListItem.prototype.clearUpdatedAt = function() { this.setUpdatedAt(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeploymentListItem.prototype.hasUpdatedAt = function() { return jspb.Message.getField(this, 3) != null; }; /** * optional string name = 4; * @return {string} */ proto.api.FUOTADeploymentListItem.prototype.getName = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 4, "")); }; /** @param {string} value */ proto.api.FUOTADeploymentListItem.prototype.setName = function(value) { jspb.Message.setField(this, 4, value); }; /** * optional string state = 5; * @return {string} */ proto.api.FUOTADeploymentListItem.prototype.getState = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 5, "")); }; /** @param {string} value */ proto.api.FUOTADeploymentListItem.prototype.setState = function(value) { jspb.Message.setField(this, 5, value); }; /** * optional google.protobuf.Timestamp next_step_after = 6; * @return {proto.google.protobuf.Timestamp} */ proto.api.FUOTADeploymentListItem.prototype.getNextStepAfter = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 6)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.FUOTADeploymentListItem.prototype.setNextStepAfter = function(value) { jspb.Message.setWrapperField(this, 6, value); }; proto.api.FUOTADeploymentListItem.prototype.clearNextStepAfter = function() { this.setNextStepAfter(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeploymentListItem.prototype.hasNextStepAfter = function() { return jspb.Message.getField(this, 6) != null; }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.CreateFUOTADeploymentForDeviceRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.CreateFUOTADeploymentForDeviceRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.CreateFUOTADeploymentForDeviceRequest.displayName = 'proto.api.CreateFUOTADeploymentForDeviceRequest'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.toObject = function(opt_includeInstance) { return proto.api.CreateFUOTADeploymentForDeviceRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.CreateFUOTADeploymentForDeviceRequest} msg The msg instance to transform. * @return {!Object} */ proto.api.CreateFUOTADeploymentForDeviceRequest.toObject = function(includeInstance, msg) { var f, obj = { devEui: msg.getDevEui(), fuotaDeployment: (f = msg.getFuotaDeployment()) && proto.api.FUOTADeployment.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.CreateFUOTADeploymentForDeviceRequest} */ proto.api.CreateFUOTADeploymentForDeviceRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.CreateFUOTADeploymentForDeviceRequest; return proto.api.CreateFUOTADeploymentForDeviceRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.CreateFUOTADeploymentForDeviceRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.CreateFUOTADeploymentForDeviceRequest} */ proto.api.CreateFUOTADeploymentForDeviceRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setDevEui(value); break; case 2: var value = new proto.api.FUOTADeployment; reader.readMessage(value,proto.api.FUOTADeployment.deserializeBinaryFromReader); msg.setFuotaDeployment(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.CreateFUOTADeploymentForDeviceRequest} message * @param {!jspb.BinaryWriter} writer */ proto.api.CreateFUOTADeploymentForDeviceRequest.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getDevEui(); if (f.length > 0) { writer.writeString( 1, f ); } f = this.getFuotaDeployment(); if (f != null) { writer.writeMessage( 2, f, proto.api.FUOTADeployment.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.CreateFUOTADeploymentForDeviceRequest} The clone. */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.cloneMessage = function() { return /** @type {!proto.api.CreateFUOTADeploymentForDeviceRequest} */ (jspb.Message.cloneMessage(this)); }; /** * optional string dev_eui = 1; * @return {string} */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.getDevEui = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.setDevEui = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional FUOTADeployment fuota_deployment = 2; * @return {proto.api.FUOTADeployment} */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.getFuotaDeployment = function() { return /** @type{proto.api.FUOTADeployment} */ ( jspb.Message.getWrapperField(this, proto.api.FUOTADeployment, 2)); }; /** @param {proto.api.FUOTADeployment|undefined} value */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.setFuotaDeployment = function(value) { jspb.Message.setWrapperField(this, 2, value); }; proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.clearFuotaDeployment = function() { this.setFuotaDeployment(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.CreateFUOTADeploymentForDeviceRequest.prototype.hasFuotaDeployment = function() { return jspb.Message.getField(this, 2) != null; }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.CreateFUOTADeploymentForDeviceResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.CreateFUOTADeploymentForDeviceResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.CreateFUOTADeploymentForDeviceResponse.displayName = 'proto.api.CreateFUOTADeploymentForDeviceResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.CreateFUOTADeploymentForDeviceResponse.prototype.toObject = function(opt_includeInstance) { return proto.api.CreateFUOTADeploymentForDeviceResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.CreateFUOTADeploymentForDeviceResponse} msg The msg instance to transform. * @return {!Object} */ proto.api.CreateFUOTADeploymentForDeviceResponse.toObject = function(includeInstance, msg) { var f, obj = { id: msg.getId() }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.CreateFUOTADeploymentForDeviceResponse} */ proto.api.CreateFUOTADeploymentForDeviceResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.CreateFUOTADeploymentForDeviceResponse; return proto.api.CreateFUOTADeploymentForDeviceResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.CreateFUOTADeploymentForDeviceResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.CreateFUOTADeploymentForDeviceResponse} */ proto.api.CreateFUOTADeploymentForDeviceResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setId(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.CreateFUOTADeploymentForDeviceResponse} message * @param {!jspb.BinaryWriter} writer */ proto.api.CreateFUOTADeploymentForDeviceResponse.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.CreateFUOTADeploymentForDeviceResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.CreateFUOTADeploymentForDeviceResponse.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getId(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.CreateFUOTADeploymentForDeviceResponse} The clone. */ proto.api.CreateFUOTADeploymentForDeviceResponse.prototype.cloneMessage = function() { return /** @type {!proto.api.CreateFUOTADeploymentForDeviceResponse} */ (jspb.Message.cloneMessage(this)); }; /** * optional string id = 1; * @return {string} */ proto.api.CreateFUOTADeploymentForDeviceResponse.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.CreateFUOTADeploymentForDeviceResponse.prototype.setId = function(value) { jspb.Message.setField(this, 1, value); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.GetFUOTADeploymentRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.GetFUOTADeploymentRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.GetFUOTADeploymentRequest.displayName = 'proto.api.GetFUOTADeploymentRequest'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.GetFUOTADeploymentRequest.prototype.toObject = function(opt_includeInstance) { return proto.api.GetFUOTADeploymentRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.GetFUOTADeploymentRequest} msg The msg instance to transform. * @return {!Object} */ proto.api.GetFUOTADeploymentRequest.toObject = function(includeInstance, msg) { var f, obj = { id: msg.getId() }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.GetFUOTADeploymentRequest} */ proto.api.GetFUOTADeploymentRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.GetFUOTADeploymentRequest; return proto.api.GetFUOTADeploymentRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.GetFUOTADeploymentRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.GetFUOTADeploymentRequest} */ proto.api.GetFUOTADeploymentRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setId(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.GetFUOTADeploymentRequest} message * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentRequest.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.GetFUOTADeploymentRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentRequest.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getId(); if (f.length > 0) { writer.writeString( 1, f ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.GetFUOTADeploymentRequest} The clone. */ proto.api.GetFUOTADeploymentRequest.prototype.cloneMessage = function() { return /** @type {!proto.api.GetFUOTADeploymentRequest} */ (jspb.Message.cloneMessage(this)); }; /** * optional string id = 1; * @return {string} */ proto.api.GetFUOTADeploymentRequest.prototype.getId = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.GetFUOTADeploymentRequest.prototype.setId = function(value) { jspb.Message.setField(this, 1, value); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.GetFUOTADeploymentResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.GetFUOTADeploymentResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.GetFUOTADeploymentResponse.displayName = 'proto.api.GetFUOTADeploymentResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.GetFUOTADeploymentResponse.prototype.toObject = function(opt_includeInstance) { return proto.api.GetFUOTADeploymentResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.GetFUOTADeploymentResponse} msg The msg instance to transform. * @return {!Object} */ proto.api.GetFUOTADeploymentResponse.toObject = function(includeInstance, msg) { var f, obj = { fuotaDeployment: (f = msg.getFuotaDeployment()) && proto.api.FUOTADeployment.toObject(includeInstance, f), createdAt: (f = msg.getCreatedAt()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f), updatedAt: (f = msg.getUpdatedAt()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.GetFUOTADeploymentResponse} */ proto.api.GetFUOTADeploymentResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.GetFUOTADeploymentResponse; return proto.api.GetFUOTADeploymentResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.GetFUOTADeploymentResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.GetFUOTADeploymentResponse} */ proto.api.GetFUOTADeploymentResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.api.FUOTADeployment; reader.readMessage(value,proto.api.FUOTADeployment.deserializeBinaryFromReader); msg.setFuotaDeployment(value); break; case 2: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setCreatedAt(value); break; case 3: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setUpdatedAt(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.GetFUOTADeploymentResponse} message * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentResponse.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.GetFUOTADeploymentResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentResponse.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getFuotaDeployment(); if (f != null) { writer.writeMessage( 1, f, proto.api.FUOTADeployment.serializeBinaryToWriter ); } f = this.getCreatedAt(); if (f != null) { writer.writeMessage( 2, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } f = this.getUpdatedAt(); if (f != null) { writer.writeMessage( 3, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.GetFUOTADeploymentResponse} The clone. */ proto.api.GetFUOTADeploymentResponse.prototype.cloneMessage = function() { return /** @type {!proto.api.GetFUOTADeploymentResponse} */ (jspb.Message.cloneMessage(this)); }; /** * optional FUOTADeployment fuota_deployment = 1; * @return {proto.api.FUOTADeployment} */ proto.api.GetFUOTADeploymentResponse.prototype.getFuotaDeployment = function() { return /** @type{proto.api.FUOTADeployment} */ ( jspb.Message.getWrapperField(this, proto.api.FUOTADeployment, 1)); }; /** @param {proto.api.FUOTADeployment|undefined} value */ proto.api.GetFUOTADeploymentResponse.prototype.setFuotaDeployment = function(value) { jspb.Message.setWrapperField(this, 1, value); }; proto.api.GetFUOTADeploymentResponse.prototype.clearFuotaDeployment = function() { this.setFuotaDeployment(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.GetFUOTADeploymentResponse.prototype.hasFuotaDeployment = function() { return jspb.Message.getField(this, 1) != null; }; /** * optional google.protobuf.Timestamp created_at = 2; * @return {proto.google.protobuf.Timestamp} */ proto.api.GetFUOTADeploymentResponse.prototype.getCreatedAt = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 2)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.GetFUOTADeploymentResponse.prototype.setCreatedAt = function(value) { jspb.Message.setWrapperField(this, 2, value); }; proto.api.GetFUOTADeploymentResponse.prototype.clearCreatedAt = function() { this.setCreatedAt(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.GetFUOTADeploymentResponse.prototype.hasCreatedAt = function() { return jspb.Message.getField(this, 2) != null; }; /** * optional google.protobuf.Timestamp updated_at = 3; * @return {proto.google.protobuf.Timestamp} */ proto.api.GetFUOTADeploymentResponse.prototype.getUpdatedAt = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 3)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.GetFUOTADeploymentResponse.prototype.setUpdatedAt = function(value) { jspb.Message.setWrapperField(this, 3, value); }; proto.api.GetFUOTADeploymentResponse.prototype.clearUpdatedAt = function() { this.setUpdatedAt(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.GetFUOTADeploymentResponse.prototype.hasUpdatedAt = function() { return jspb.Message.getField(this, 3) != null; }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.ListFUOTADeploymentRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.ListFUOTADeploymentRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.ListFUOTADeploymentRequest.displayName = 'proto.api.ListFUOTADeploymentRequest'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.ListFUOTADeploymentRequest.prototype.toObject = function(opt_includeInstance) { return proto.api.ListFUOTADeploymentRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.ListFUOTADeploymentRequest} msg The msg instance to transform. * @return {!Object} */ proto.api.ListFUOTADeploymentRequest.toObject = function(includeInstance, msg) { var f, obj = { limit: msg.getLimit(), offset: msg.getOffset(), applicationId: msg.getApplicationId(), devEui: msg.getDevEui() }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.ListFUOTADeploymentRequest} */ proto.api.ListFUOTADeploymentRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.ListFUOTADeploymentRequest; return proto.api.ListFUOTADeploymentRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.ListFUOTADeploymentRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.ListFUOTADeploymentRequest} */ proto.api.ListFUOTADeploymentRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt64()); msg.setLimit(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setOffset(value); break; case 3: var value = /** @type {number} */ (reader.readInt64()); msg.setApplicationId(value); break; case 4: var value = /** @type {string} */ (reader.readString()); msg.setDevEui(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.ListFUOTADeploymentRequest} message * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentRequest.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.ListFUOTADeploymentRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentRequest.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getLimit(); if (f !== 0) { writer.writeInt64( 1, f ); } f = this.getOffset(); if (f !== 0) { writer.writeInt64( 2, f ); } f = this.getApplicationId(); if (f !== 0) { writer.writeInt64( 3, f ); } f = this.getDevEui(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.ListFUOTADeploymentRequest} The clone. */ proto.api.ListFUOTADeploymentRequest.prototype.cloneMessage = function() { return /** @type {!proto.api.ListFUOTADeploymentRequest} */ (jspb.Message.cloneMessage(this)); }; /** * optional int64 limit = 1; * @return {number} */ proto.api.ListFUOTADeploymentRequest.prototype.getLimit = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentRequest.prototype.setLimit = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional int64 offset = 2; * @return {number} */ proto.api.ListFUOTADeploymentRequest.prototype.getOffset = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 2, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentRequest.prototype.setOffset = function(value) { jspb.Message.setField(this, 2, value); }; /** * optional int64 application_id = 3; * @return {number} */ proto.api.ListFUOTADeploymentRequest.prototype.getApplicationId = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 3, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentRequest.prototype.setApplicationId = function(value) { jspb.Message.setField(this, 3, value); }; /** * optional string dev_eui = 4; * @return {string} */ proto.api.ListFUOTADeploymentRequest.prototype.getDevEui = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 4, "")); }; /** @param {string} value */ proto.api.ListFUOTADeploymentRequest.prototype.setDevEui = function(value) { jspb.Message.setField(this, 4, value); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.ListFUOTADeploymentResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.api.ListFUOTADeploymentResponse.repeatedFields_, null); }; goog.inherits(proto.api.ListFUOTADeploymentResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.ListFUOTADeploymentResponse.displayName = 'proto.api.ListFUOTADeploymentResponse'; } /** * List of repeated fields within this message type. * @private {!Array<number>} * @const */ proto.api.ListFUOTADeploymentResponse.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.ListFUOTADeploymentResponse.prototype.toObject = function(opt_includeInstance) { return proto.api.ListFUOTADeploymentResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.ListFUOTADeploymentResponse} msg The msg instance to transform. * @return {!Object} */ proto.api.ListFUOTADeploymentResponse.toObject = function(includeInstance, msg) { var f, obj = { totalCount: msg.getTotalCount(), resultList: jspb.Message.toObjectList(msg.getResultList(), proto.api.FUOTADeploymentListItem.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.ListFUOTADeploymentResponse} */ proto.api.ListFUOTADeploymentResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.ListFUOTADeploymentResponse; return proto.api.ListFUOTADeploymentResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.ListFUOTADeploymentResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.ListFUOTADeploymentResponse} */ proto.api.ListFUOTADeploymentResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt64()); msg.setTotalCount(value); break; case 2: var value = new proto.api.FUOTADeploymentListItem; reader.readMessage(value,proto.api.FUOTADeploymentListItem.deserializeBinaryFromReader); msg.getResultList().push(value); msg.setResultList(msg.getResultList()); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.ListFUOTADeploymentResponse} message * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentResponse.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.ListFUOTADeploymentResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentResponse.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getTotalCount(); if (f !== 0) { writer.writeInt64( 1, f ); } f = this.getResultList(); if (f.length > 0) { writer.writeRepeatedMessage( 2, f, proto.api.FUOTADeploymentListItem.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.ListFUOTADeploymentResponse} The clone. */ proto.api.ListFUOTADeploymentResponse.prototype.cloneMessage = function() { return /** @type {!proto.api.ListFUOTADeploymentResponse} */ (jspb.Message.cloneMessage(this)); }; /** * optional int64 total_count = 1; * @return {number} */ proto.api.ListFUOTADeploymentResponse.prototype.getTotalCount = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentResponse.prototype.setTotalCount = function(value) { jspb.Message.setField(this, 1, value); }; /** * repeated FUOTADeploymentListItem result = 2; * If you change this array by adding, removing or replacing elements, or if you * replace the array itself, then you must call the setter to update it. * @return {!Array.<!proto.api.FUOTADeploymentListItem>} */ proto.api.ListFUOTADeploymentResponse.prototype.getResultList = function() { return /** @type{!Array.<!proto.api.FUOTADeploymentListItem>} */ ( jspb.Message.getRepeatedWrapperField(this, proto.api.FUOTADeploymentListItem, 2)); }; /** @param {Array.<!proto.api.FUOTADeploymentListItem>} value */ proto.api.ListFUOTADeploymentResponse.prototype.setResultList = function(value) { jspb.Message.setRepeatedWrapperField(this, 2, value); }; proto.api.ListFUOTADeploymentResponse.prototype.clearResultList = function() { this.setResultList([]); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.ListFUOTADeploymentDevicesRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.ListFUOTADeploymentDevicesRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.ListFUOTADeploymentDevicesRequest.displayName = 'proto.api.ListFUOTADeploymentDevicesRequest'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.toObject = function(opt_includeInstance) { return proto.api.ListFUOTADeploymentDevicesRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.ListFUOTADeploymentDevicesRequest} msg The msg instance to transform. * @return {!Object} */ proto.api.ListFUOTADeploymentDevicesRequest.toObject = function(includeInstance, msg) { var f, obj = { fuotaDeploymentId: msg.getFuotaDeploymentId(), limit: msg.getLimit(), offset: msg.getOffset() }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.ListFUOTADeploymentDevicesRequest} */ proto.api.ListFUOTADeploymentDevicesRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.ListFUOTADeploymentDevicesRequest; return proto.api.ListFUOTADeploymentDevicesRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.ListFUOTADeploymentDevicesRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.ListFUOTADeploymentDevicesRequest} */ proto.api.ListFUOTADeploymentDevicesRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setFuotaDeploymentId(value); break; case 2: var value = /** @type {number} */ (reader.readInt64()); msg.setLimit(value); break; case 3: var value = /** @type {number} */ (reader.readInt64()); msg.setOffset(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.ListFUOTADeploymentDevicesRequest} message * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentDevicesRequest.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getFuotaDeploymentId(); if (f.length > 0) { writer.writeString( 1, f ); } f = this.getLimit(); if (f !== 0) { writer.writeInt64( 2, f ); } f = this.getOffset(); if (f !== 0) { writer.writeInt64( 3, f ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.ListFUOTADeploymentDevicesRequest} The clone. */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.cloneMessage = function() { return /** @type {!proto.api.ListFUOTADeploymentDevicesRequest} */ (jspb.Message.cloneMessage(this)); }; /** * optional string fuota_deployment_id = 1; * @return {string} */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.getFuotaDeploymentId = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.setFuotaDeploymentId = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional int64 limit = 2; * @return {number} */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.getLimit = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 2, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.setLimit = function(value) { jspb.Message.setField(this, 2, value); }; /** * optional int64 offset = 3; * @return {number} */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.getOffset = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 3, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentDevicesRequest.prototype.setOffset = function(value) { jspb.Message.setField(this, 3, value); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.GetFUOTADeploymentDeviceRequest = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.GetFUOTADeploymentDeviceRequest, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.GetFUOTADeploymentDeviceRequest.displayName = 'proto.api.GetFUOTADeploymentDeviceRequest'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.toObject = function(opt_includeInstance) { return proto.api.GetFUOTADeploymentDeviceRequest.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.GetFUOTADeploymentDeviceRequest} msg The msg instance to transform. * @return {!Object} */ proto.api.GetFUOTADeploymentDeviceRequest.toObject = function(includeInstance, msg) { var f, obj = { fuotaDeploymentId: msg.getFuotaDeploymentId(), devEui: msg.getDevEui() }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.GetFUOTADeploymentDeviceRequest} */ proto.api.GetFUOTADeploymentDeviceRequest.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.GetFUOTADeploymentDeviceRequest; return proto.api.GetFUOTADeploymentDeviceRequest.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.GetFUOTADeploymentDeviceRequest} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.GetFUOTADeploymentDeviceRequest} */ proto.api.GetFUOTADeploymentDeviceRequest.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setFuotaDeploymentId(value); break; case 2: var value = /** @type {string} */ (reader.readString()); msg.setDevEui(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.GetFUOTADeploymentDeviceRequest} message * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentDeviceRequest.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getFuotaDeploymentId(); if (f.length > 0) { writer.writeString( 1, f ); } f = this.getDevEui(); if (f.length > 0) { writer.writeString( 2, f ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.GetFUOTADeploymentDeviceRequest} The clone. */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.cloneMessage = function() { return /** @type {!proto.api.GetFUOTADeploymentDeviceRequest} */ (jspb.Message.cloneMessage(this)); }; /** * optional string fuota_deployment_id = 1; * @return {string} */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.getFuotaDeploymentId = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.setFuotaDeploymentId = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional string dev_eui = 2; * @return {string} */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.getDevEui = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 2, "")); }; /** @param {string} value */ proto.api.GetFUOTADeploymentDeviceRequest.prototype.setDevEui = function(value) { jspb.Message.setField(this, 2, value); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.GetFUOTADeploymentDeviceResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.GetFUOTADeploymentDeviceResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.GetFUOTADeploymentDeviceResponse.displayName = 'proto.api.GetFUOTADeploymentDeviceResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.toObject = function(opt_includeInstance) { return proto.api.GetFUOTADeploymentDeviceResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.GetFUOTADeploymentDeviceResponse} msg The msg instance to transform. * @return {!Object} */ proto.api.GetFUOTADeploymentDeviceResponse.toObject = function(includeInstance, msg) { var f, obj = { deploymentDevice: (f = msg.getDeploymentDevice()) && proto.api.FUOTADeploymentDeviceListItem.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.GetFUOTADeploymentDeviceResponse} */ proto.api.GetFUOTADeploymentDeviceResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.GetFUOTADeploymentDeviceResponse; return proto.api.GetFUOTADeploymentDeviceResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.GetFUOTADeploymentDeviceResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.GetFUOTADeploymentDeviceResponse} */ proto.api.GetFUOTADeploymentDeviceResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new proto.api.FUOTADeploymentDeviceListItem; reader.readMessage(value,proto.api.FUOTADeploymentDeviceListItem.deserializeBinaryFromReader); msg.setDeploymentDevice(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.GetFUOTADeploymentDeviceResponse} message * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentDeviceResponse.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getDeploymentDevice(); if (f != null) { writer.writeMessage( 1, f, proto.api.FUOTADeploymentDeviceListItem.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.GetFUOTADeploymentDeviceResponse} The clone. */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.cloneMessage = function() { return /** @type {!proto.api.GetFUOTADeploymentDeviceResponse} */ (jspb.Message.cloneMessage(this)); }; /** * optional FUOTADeploymentDeviceListItem deployment_device = 1; * @return {proto.api.FUOTADeploymentDeviceListItem} */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.getDeploymentDevice = function() { return /** @type{proto.api.FUOTADeploymentDeviceListItem} */ ( jspb.Message.getWrapperField(this, proto.api.FUOTADeploymentDeviceListItem, 1)); }; /** @param {proto.api.FUOTADeploymentDeviceListItem|undefined} value */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.setDeploymentDevice = function(value) { jspb.Message.setWrapperField(this, 1, value); }; proto.api.GetFUOTADeploymentDeviceResponse.prototype.clearDeploymentDevice = function() { this.setDeploymentDevice(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.GetFUOTADeploymentDeviceResponse.prototype.hasDeploymentDevice = function() { return jspb.Message.getField(this, 1) != null; }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.ListFUOTADeploymentDevicesResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, proto.api.ListFUOTADeploymentDevicesResponse.repeatedFields_, null); }; goog.inherits(proto.api.ListFUOTADeploymentDevicesResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.ListFUOTADeploymentDevicesResponse.displayName = 'proto.api.ListFUOTADeploymentDevicesResponse'; } /** * List of repeated fields within this message type. * @private {!Array<number>} * @const */ proto.api.ListFUOTADeploymentDevicesResponse.repeatedFields_ = [2]; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.toObject = function(opt_includeInstance) { return proto.api.ListFUOTADeploymentDevicesResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.ListFUOTADeploymentDevicesResponse} msg The msg instance to transform. * @return {!Object} */ proto.api.ListFUOTADeploymentDevicesResponse.toObject = function(includeInstance, msg) { var f, obj = { totalCount: msg.getTotalCount(), resultList: jspb.Message.toObjectList(msg.getResultList(), proto.api.FUOTADeploymentDeviceListItem.toObject, includeInstance) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.ListFUOTADeploymentDevicesResponse} */ proto.api.ListFUOTADeploymentDevicesResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.ListFUOTADeploymentDevicesResponse; return proto.api.ListFUOTADeploymentDevicesResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.ListFUOTADeploymentDevicesResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.ListFUOTADeploymentDevicesResponse} */ proto.api.ListFUOTADeploymentDevicesResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {number} */ (reader.readInt64()); msg.setTotalCount(value); break; case 2: var value = new proto.api.FUOTADeploymentDeviceListItem; reader.readMessage(value,proto.api.FUOTADeploymentDeviceListItem.deserializeBinaryFromReader); msg.getResultList().push(value); msg.setResultList(msg.getResultList()); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.ListFUOTADeploymentDevicesResponse} message * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentDevicesResponse.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getTotalCount(); if (f !== 0) { writer.writeInt64( 1, f ); } f = this.getResultList(); if (f.length > 0) { writer.writeRepeatedMessage( 2, f, proto.api.FUOTADeploymentDeviceListItem.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.ListFUOTADeploymentDevicesResponse} The clone. */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.cloneMessage = function() { return /** @type {!proto.api.ListFUOTADeploymentDevicesResponse} */ (jspb.Message.cloneMessage(this)); }; /** * optional int64 total_count = 1; * @return {number} */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.getTotalCount = function() { return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); }; /** @param {number} value */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.setTotalCount = function(value) { jspb.Message.setField(this, 1, value); }; /** * repeated FUOTADeploymentDeviceListItem result = 2; * If you change this array by adding, removing or replacing elements, or if you * replace the array itself, then you must call the setter to update it. * @return {!Array.<!proto.api.FUOTADeploymentDeviceListItem>} */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.getResultList = function() { return /** @type{!Array.<!proto.api.FUOTADeploymentDeviceListItem>} */ ( jspb.Message.getRepeatedWrapperField(this, proto.api.FUOTADeploymentDeviceListItem, 2)); }; /** @param {Array.<!proto.api.FUOTADeploymentDeviceListItem>} value */ proto.api.ListFUOTADeploymentDevicesResponse.prototype.setResultList = function(value) { jspb.Message.setRepeatedWrapperField(this, 2, value); }; proto.api.ListFUOTADeploymentDevicesResponse.prototype.clearResultList = function() { this.setResultList([]); }; /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.api.FUOTADeploymentDeviceListItem = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.api.FUOTADeploymentDeviceListItem, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.api.FUOTADeploymentDeviceListItem.displayName = 'proto.api.FUOTADeploymentDeviceListItem'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.api.FUOTADeploymentDeviceListItem.prototype.toObject = function(opt_includeInstance) { return proto.api.FUOTADeploymentDeviceListItem.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.api.FUOTADeploymentDeviceListItem} msg The msg instance to transform. * @return {!Object} */ proto.api.FUOTADeploymentDeviceListItem.toObject = function(includeInstance, msg) { var f, obj = { devEui: msg.getDevEui(), deviceName: msg.getDeviceName(), state: msg.getState(), errorMessage: msg.getErrorMessage(), createdAt: (f = msg.getCreatedAt()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f), updatedAt: (f = msg.getUpdatedAt()) && google_protobuf_timestamp_pb.Timestamp.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.api.FUOTADeploymentDeviceListItem} */ proto.api.FUOTADeploymentDeviceListItem.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.api.FUOTADeploymentDeviceListItem; return proto.api.FUOTADeploymentDeviceListItem.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.api.FUOTADeploymentDeviceListItem} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.api.FUOTADeploymentDeviceListItem} */ proto.api.FUOTADeploymentDeviceListItem.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setDevEui(value); break; case 2: var value = /** @type {string} */ (reader.readString()); msg.setDeviceName(value); break; case 3: var value = /** @type {!proto.api.FUOTADeploymentDeviceState} */ (reader.readEnum()); msg.setState(value); break; case 4: var value = /** @type {string} */ (reader.readString()); msg.setErrorMessage(value); break; case 5: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setCreatedAt(value); break; case 6: var value = new google_protobuf_timestamp_pb.Timestamp; reader.readMessage(value,google_protobuf_timestamp_pb.Timestamp.deserializeBinaryFromReader); msg.setUpdatedAt(value); break; default: reader.skipField(); break; } } return msg; }; /** * Class method variant: serializes the given message to binary data * (in protobuf wire format), writing to the given BinaryWriter. * @param {!proto.api.FUOTADeploymentDeviceListItem} message * @param {!jspb.BinaryWriter} writer */ proto.api.FUOTADeploymentDeviceListItem.serializeBinaryToWriter = function(message, writer) { message.serializeBinaryToWriter(writer); }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.api.FUOTADeploymentDeviceListItem.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; /** * Serializes the message to binary data (in protobuf wire format), * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ proto.api.FUOTADeploymentDeviceListItem.prototype.serializeBinaryToWriter = function (writer) { var f = undefined; f = this.getDevEui(); if (f.length > 0) { writer.writeString( 1, f ); } f = this.getDeviceName(); if (f.length > 0) { writer.writeString( 2, f ); } f = this.getState(); if (f !== 0.0) { writer.writeEnum( 3, f ); } f = this.getErrorMessage(); if (f.length > 0) { writer.writeString( 4, f ); } f = this.getCreatedAt(); if (f != null) { writer.writeMessage( 5, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } f = this.getUpdatedAt(); if (f != null) { writer.writeMessage( 6, f, google_protobuf_timestamp_pb.Timestamp.serializeBinaryToWriter ); } }; /** * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.api.FUOTADeploymentDeviceListItem} The clone. */ proto.api.FUOTADeploymentDeviceListItem.prototype.cloneMessage = function() { return /** @type {!proto.api.FUOTADeploymentDeviceListItem} */ (jspb.Message.cloneMessage(this)); }; /** * optional string dev_eui = 1; * @return {string} */ proto.api.FUOTADeploymentDeviceListItem.prototype.getDevEui = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); }; /** @param {string} value */ proto.api.FUOTADeploymentDeviceListItem.prototype.setDevEui = function(value) { jspb.Message.setField(this, 1, value); }; /** * optional string device_name = 2; * @return {string} */ proto.api.FUOTADeploymentDeviceListItem.prototype.getDeviceName = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 2, "")); }; /** @param {string} value */ proto.api.FUOTADeploymentDeviceListItem.prototype.setDeviceName = function(value) { jspb.Message.setField(this, 2, value); }; /** * optional FUOTADeploymentDeviceState state = 3; * @return {!proto.api.FUOTADeploymentDeviceState} */ proto.api.FUOTADeploymentDeviceListItem.prototype.getState = function() { return /** @type {!proto.api.FUOTADeploymentDeviceState} */ (jspb.Message.getFieldProto3(this, 3, 0)); }; /** @param {!proto.api.FUOTADeploymentDeviceState} value */ proto.api.FUOTADeploymentDeviceListItem.prototype.setState = function(value) { jspb.Message.setField(this, 3, value); }; /** * optional string error_message = 4; * @return {string} */ proto.api.FUOTADeploymentDeviceListItem.prototype.getErrorMessage = function() { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 4, "")); }; /** @param {string} value */ proto.api.FUOTADeploymentDeviceListItem.prototype.setErrorMessage = function(value) { jspb.Message.setField(this, 4, value); }; /** * optional google.protobuf.Timestamp created_at = 5; * @return {proto.google.protobuf.Timestamp} */ proto.api.FUOTADeploymentDeviceListItem.prototype.getCreatedAt = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 5)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.FUOTADeploymentDeviceListItem.prototype.setCreatedAt = function(value) { jspb.Message.setWrapperField(this, 5, value); }; proto.api.FUOTADeploymentDeviceListItem.prototype.clearCreatedAt = function() { this.setCreatedAt(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeploymentDeviceListItem.prototype.hasCreatedAt = function() { return jspb.Message.getField(this, 5) != null; }; /** * optional google.protobuf.Timestamp updated_at = 6; * @return {proto.google.protobuf.Timestamp} */ proto.api.FUOTADeploymentDeviceListItem.prototype.getUpdatedAt = function() { return /** @type{proto.google.protobuf.Timestamp} */ ( jspb.Message.getWrapperField(this, google_protobuf_timestamp_pb.Timestamp, 6)); }; /** @param {proto.google.protobuf.Timestamp|undefined} value */ proto.api.FUOTADeploymentDeviceListItem.prototype.setUpdatedAt = function(value) { jspb.Message.setWrapperField(this, 6, value); }; proto.api.FUOTADeploymentDeviceListItem.prototype.clearUpdatedAt = function() { this.setUpdatedAt(undefined); }; /** * Returns whether this field is set. * @return{!boolean} */ proto.api.FUOTADeploymentDeviceListItem.prototype.hasUpdatedAt = function() { return jspb.Message.getField(this, 6) != null; }; /** * @enum {number} */ proto.api.FUOTADeploymentDeviceState = { PENDING: 0, SUCCESS: 1, ERROR: 2 }; goog.object.extend(exports, proto.api); <|start_filename|>go/as/external/api/fuotaDeployment.pb.gw.go<|end_filename|> // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: as/external/api/fuotaDeployment.proto /* Package api is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package api import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage func request_FUOTADeploymentService_CreateForDevice_0(ctx context.Context, marshaler runtime.Marshaler, client FUOTADeploymentServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq CreateFUOTADeploymentForDeviceRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["dev_eui"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "dev_eui") } protoReq.DevEui, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "dev_eui", err) } msg, err := client.CreateForDevice(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FUOTADeploymentService_CreateForDevice_0(ctx context.Context, marshaler runtime.Marshaler, server FUOTADeploymentServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq CreateFUOTADeploymentForDeviceRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } var ( val string ok bool err error _ = err ) val, ok = pathParams["dev_eui"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "dev_eui") } protoReq.DevEui, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "dev_eui", err) } msg, err := server.CreateForDevice(ctx, &protoReq) return msg, metadata, err } func request_FUOTADeploymentService_Get_0(ctx context.Context, marshaler runtime.Marshaler, client FUOTADeploymentServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetFUOTADeploymentRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } msg, err := client.Get(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FUOTADeploymentService_Get_0(ctx context.Context, marshaler runtime.Marshaler, server FUOTADeploymentServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetFUOTADeploymentRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") } protoReq.Id, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) } msg, err := server.Get(ctx, &protoReq) return msg, metadata, err } var ( filter_FUOTADeploymentService_List_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) func request_FUOTADeploymentService_List_0(ctx context.Context, marshaler runtime.Marshaler, client FUOTADeploymentServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ListFUOTADeploymentRequest var metadata runtime.ServerMetadata if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FUOTADeploymentService_List_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.List(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FUOTADeploymentService_List_0(ctx context.Context, marshaler runtime.Marshaler, server FUOTADeploymentServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ListFUOTADeploymentRequest var metadata runtime.ServerMetadata if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FUOTADeploymentService_List_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.List(ctx, &protoReq) return msg, metadata, err } func request_FUOTADeploymentService_GetDeploymentDevice_0(ctx context.Context, marshaler runtime.Marshaler, client FUOTADeploymentServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetFUOTADeploymentDeviceRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["fuota_deployment_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fuota_deployment_id") } protoReq.FuotaDeploymentId, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fuota_deployment_id", err) } val, ok = pathParams["dev_eui"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "dev_eui") } protoReq.DevEui, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "dev_eui", err) } msg, err := client.GetDeploymentDevice(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FUOTADeploymentService_GetDeploymentDevice_0(ctx context.Context, marshaler runtime.Marshaler, server FUOTADeploymentServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetFUOTADeploymentDeviceRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["fuota_deployment_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fuota_deployment_id") } protoReq.FuotaDeploymentId, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fuota_deployment_id", err) } val, ok = pathParams["dev_eui"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "dev_eui") } protoReq.DevEui, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "dev_eui", err) } msg, err := server.GetDeploymentDevice(ctx, &protoReq) return msg, metadata, err } var ( filter_FUOTADeploymentService_ListDeploymentDevices_0 = &utilities.DoubleArray{Encoding: map[string]int{"fuota_deployment_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} ) func request_FUOTADeploymentService_ListDeploymentDevices_0(ctx context.Context, marshaler runtime.Marshaler, client FUOTADeploymentServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ListFUOTADeploymentDevicesRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["fuota_deployment_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fuota_deployment_id") } protoReq.FuotaDeploymentId, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fuota_deployment_id", err) } if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_FUOTADeploymentService_ListDeploymentDevices_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.ListDeploymentDevices(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_FUOTADeploymentService_ListDeploymentDevices_0(ctx context.Context, marshaler runtime.Marshaler, server FUOTADeploymentServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ListFUOTADeploymentDevicesRequest var metadata runtime.ServerMetadata var ( val string ok bool err error _ = err ) val, ok = pathParams["fuota_deployment_id"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fuota_deployment_id") } protoReq.FuotaDeploymentId, err = runtime.String(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fuota_deployment_id", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FUOTADeploymentService_ListDeploymentDevices_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.ListDeploymentDevices(ctx, &protoReq) return msg, metadata, err } // RegisterFUOTADeploymentServiceHandlerServer registers the http handlers for service FUOTADeploymentService to "mux". // UnaryRPC :call FUOTADeploymentServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. func RegisterFUOTADeploymentServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server FUOTADeploymentServiceServer) error { mux.Handle("POST", pattern_FUOTADeploymentService_CreateForDevice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FUOTADeploymentService_CreateForDevice_0(rctx, inboundMarshaler, server, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_CreateForDevice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FUOTADeploymentService_Get_0(rctx, inboundMarshaler, server, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FUOTADeploymentService_List_0(rctx, inboundMarshaler, server, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_GetDeploymentDevice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FUOTADeploymentService_GetDeploymentDevice_0(rctx, inboundMarshaler, server, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_GetDeploymentDevice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_ListDeploymentDevices_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_FUOTADeploymentService_ListDeploymentDevices_0(rctx, inboundMarshaler, server, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_ListDeploymentDevices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterFUOTADeploymentServiceHandlerFromEndpoint is same as RegisterFUOTADeploymentServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterFUOTADeploymentServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterFUOTADeploymentServiceHandler(ctx, mux, conn) } // RegisterFUOTADeploymentServiceHandler registers the http handlers for service FUOTADeploymentService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterFUOTADeploymentServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterFUOTADeploymentServiceHandlerClient(ctx, mux, NewFUOTADeploymentServiceClient(conn)) } // RegisterFUOTADeploymentServiceHandlerClient registers the http handlers for service FUOTADeploymentService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "FUOTADeploymentServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "FUOTADeploymentServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "FUOTADeploymentServiceClient" to call the correct interceptors. func RegisterFUOTADeploymentServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client FUOTADeploymentServiceClient) error { mux.Handle("POST", pattern_FUOTADeploymentService_CreateForDevice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FUOTADeploymentService_CreateForDevice_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_CreateForDevice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FUOTADeploymentService_Get_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FUOTADeploymentService_List_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_GetDeploymentDevice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FUOTADeploymentService_GetDeploymentDevice_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_GetDeploymentDevice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("GET", pattern_FUOTADeploymentService_ListDeploymentDevices_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_FUOTADeploymentService_ListDeploymentDevices_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_FUOTADeploymentService_ListDeploymentDevices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_FUOTADeploymentService_CreateForDevice_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"api", "devices", "dev_eui", "fuota-deployments"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FUOTADeploymentService_Get_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"api", "fuota-deployments", "id"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FUOTADeploymentService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"api", "fuota-deployments"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FUOTADeploymentService_GetDeploymentDevice_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"api", "fuota-deployments", "fuota_deployment_id", "devices", "dev_eui"}, "", runtime.AssumeColonVerbOpt(true))) pattern_FUOTADeploymentService_ListDeploymentDevices_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"api", "fuota-deployments", "fuota_deployment_id", "devices"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_FUOTADeploymentService_CreateForDevice_0 = runtime.ForwardResponseMessage forward_FUOTADeploymentService_Get_0 = runtime.ForwardResponseMessage forward_FUOTADeploymentService_List_0 = runtime.ForwardResponseMessage forward_FUOTADeploymentService_GetDeploymentDevice_0 = runtime.ForwardResponseMessage forward_FUOTADeploymentService_ListDeploymentDevices_0 = runtime.ForwardResponseMessage )
hoellejal/chirpstack-api
<|start_filename|>gulpfile.js<|end_filename|> 'use strict'; var gulp = require('gulp'); var minify = require('gulp-minify'); // compress js files gulp.task('compress', function () { gulp.src(['js/*.js', '!js/*.min.js']) .pipe(minify({ ext: '.min.js' })) .pipe(gulp.dest('js')) }); // gulp default task gulp.task('default', ['compress']);
uagrace/like-dislike.js
<|start_filename|>Makefile<|end_filename|> SERVER_BIN := bin/pirate-server SERVER_SRC := cmd/pirate-server/main.go $(shell find pirate -type f -name '*.go') CONFIG := config.yml DOCKERFILE := Dockerfile .PHONY: all all: $(SERVER_BIN) $(SERVER_BIN): $(SERVER_SRC) @echo "+ $@" go build -o $@ $< .PHONY: run run: $(SERVER_BIN) $(CONFIG) @echo "+ $@" $(SERVER_BIN) -config $(CONFIG) $(CONFIG): @echo "+ $@" cp example-config.yml $@ .PHONY: test test: @echo "+ $@" go test -count 1 github.com/innogames/pirate/... .PHONY: bench bench: @echo "+ $@" go test -count 1 github.com/innogames/pirate/... -bench=. .PHONY: docker docker: $(CONFIG) @echo "+ $@" docker build -t innogames/pirate:latest . .PHONY: clean clean: @echo "+ $@" rm -rf $(dir $(SERVER_BIN)) <|start_filename|>cmd/pirate-server/main.go<|end_filename|> package main import ( "flag" "fmt" "github.com/innogames/pirate/pirate" "github.com/op/go-logging" "os" "runtime" ) func main() { configFile := flag.String("config", "/etc/pirate/config.yml", "Path to config file") flag.Parse() cfg, err := pirate.LoadConfig(*configFile) if err != nil { fail("Failed to load configuration: %s\n", err) } logger := createLogger(cfg) cfg.Log(logger) chUdp := make(chan []byte, 100) chUdpDecomp := make(chan []byte, 100) chMsg := make(chan *pirate.Message, 100) chValidMsg := make(chan *pirate.Message, 100) chMetric := make(chan *pirate.Metric, 1000) stats := pirate.NewMonitoringStats() server, err := pirate.NewUdpServer(cfg.UdpAddress, cfg.PerIpRateLimit, logger, stats, chUdp) if err != nil { fail("Failed to initialize server: %s\n", err) } writer, err := pirate.NewWriter(cfg.GraphiteTarget, logger, stats) if err != nil { fail("Failed to initialize writer: %s", err) } decompressor := pirate.NewPlainDecompressor() if cfg.Gzip { decompressor = pirate.NewGzipDecompressor() } numCpus := runtime.NumCPU() go pirate.NewCompressionWorker(decompressor, logger, chUdp, chUdpDecomp).Run(numCpus) go pirate.NewParserWorker(logger, chUdpDecomp, chMsg).Run(numCpus) go pirate.NewValidatorWorker(cfg, logger, stats, chMsg, chValidMsg).Run(numCpus) go pirate.NewMetricWorker(cfg, logger, chValidMsg, chMetric).Run(numCpus) go pirate.NewWriterWorker(writer, logger, chMetric).Run(1) go pirate.NewMonitoringWorker(cfg, logger, chMetric, stats).Run() if err := server.Run(); err != nil { fail("UDP Server error: %s", err) } } func createLogger(cfg *pirate.Config) *logging.Logger { format := logging.MustStringFormatter(`%{time:2006-01-02 15:04:05.000} %{level:.4s} %{message}`) logger := logging.MustGetLogger("pirate") backend := logging.NewBackendFormatter(logging.NewLogBackend(os.Stdout, "", 0), format) leveledBackend := logging.AddModuleLevel(backend) leveledBackend.SetLevel(cfg.LogLevel, "pirate") logger.SetBackend(leveledBackend) return logger } func fail(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(1) } <|start_filename|>pirate/parser_test.go<|end_filename|> package pirate import ( "bytes" "github.com/stretchr/testify/assert" "testing" ) func TestHeaderNoEndOfLine(t *testing.T) { t.Run("empty", func(t *testing.T) { p := NewParser([]byte{}) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, MissingEndOfLine, err) }) t.Run("absent eol", func(t *testing.T) { p := NewParser([]byte("foo")) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, MissingEndOfLine, err) }) } func TestEndOfHeader(t *testing.T) { p := NewParser([]byte(" \n foobar")) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, EndOfHeader, err) assert.Equal(t, []byte(" foobar"), p.buf, "After end of header line break must be skipped") } func TestOneHeaderWithSemicolon(t *testing.T) { t.Run("without whitespace", func(t *testing.T) { p := NewParser([]byte("foo=bar;\n")) key, value, err := p.ReadHeader() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("bar"), value) assert.Nil(t, err) assert.Equal(t, []byte("\n"), p.buf) }) t.Run("with whitespace", func(t *testing.T) { p := NewParser([]byte(" foo = bar ; \n")) key, value, err := p.ReadHeader() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("bar"), value) assert.Nil(t, err) assert.Equal(t, []byte("\n"), p.buf) }) } func TestOneHeaderWithoutSemicolon(t *testing.T) { t.Run("without whitespace", func(t *testing.T) { p := NewParser([]byte("foo=bar\n")) key, value, err := p.ReadHeader() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("bar"), value) assert.Nil(t, err) assert.Equal(t, []byte("\n"), p.buf) }) t.Run("with whitespace", func(t *testing.T) { p := NewParser([]byte(" foo = bar \n")) key, value, err := p.ReadHeader() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("bar"), value) assert.Nil(t, err) assert.Equal(t, []byte("\n"), p.buf) }) } func TestMultipleHeaders(t *testing.T) { t.Run("without whitespace", func(t *testing.T) { p := NewParser([]byte("foo=bar;baz=1337\n")) // first header key, value, err := p.ReadHeader() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("bar"), value) assert.Nil(t, err) // second header key, value, err = p.ReadHeader() assert.Equal(t, []byte("baz"), key) assert.Equal(t, []byte("1337"), value) assert.Nil(t, err) assert.Equal(t, []byte("\n"), p.buf) }) t.Run("with whitespace", func(t *testing.T) { p := NewParser([]byte(" foo = bar ; baz = 1337 ; \n")) // first header key, value, err := p.ReadHeader() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("bar"), value) assert.Nil(t, err) assert.Equal(t, []byte("baz = 1337 ; \n"), p.buf) // second header key, value, err = p.ReadHeader() assert.Equal(t, []byte("baz"), key) assert.Equal(t, []byte("1337"), value) assert.Nil(t, err) assert.Equal(t, []byte("\n"), p.buf) }) } func TestInvalidHeaders(t *testing.T) { t.Run("invalid key", func(t *testing.T) { p := NewParser([]byte(" 1337 \n")) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, InvalidKey, err) }) t.Run("missing equals", func(t *testing.T) { p := NewParser([]byte(" foo bar \n")) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, IncompletePair, err) }) t.Run("missing value", func(t *testing.T) { p := NewParser([]byte(" foo =\n")) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, InvalidValue, err) }) t.Run("invalid value", func(t *testing.T) { p := NewParser([]byte(" foo = *** \n")) key, value, err := p.ReadHeader() assert.Nil(t, key) assert.Nil(t, value) assert.Equal(t, InvalidValue, err) }) } func TestEndOfMetrics(t *testing.T) { t.Run("empty", func(t *testing.T) { p := NewParser([]byte{}) key, ts, value, err := p.ReadMetric() assert.Nil(t, key) assert.Nil(t, value) assert.Nil(t, ts) assert.Equal(t, EndOfMetrics, err) assert.Equal(t, []byte{}, p.buf) }) t.Run("only white spaces", func(t *testing.T) { p := NewParser([]byte(" ")) key, ts, value, err := p.ReadMetric() assert.Nil(t, key) assert.Nil(t, value) assert.Nil(t, ts) assert.Equal(t, EndOfMetrics, err) assert.Equal(t, []byte{}, p.buf) }) t.Run("white with linebreak", func(t *testing.T) { p := NewParser([]byte(" \n")) key, ts, value, err := p.ReadMetric() assert.Nil(t, key) assert.Nil(t, value) assert.Nil(t, ts) assert.Equal(t, EndOfMetrics, err) assert.Equal(t, []byte{}, p.buf) }) } func TestSingleMetric(t *testing.T) { t.Run("without linebreak", func(t *testing.T) { p := NewParser([]byte(" foo 20.6 1234567890 ")) key, ts, value, err := p.ReadMetric() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("20.6"), value) assert.Equal(t, []byte("1234567890"), ts) assert.Nil(t, err) assert.Equal(t, []byte{}, p.buf) }) t.Run("with linebreak", func(t *testing.T) { p := NewParser([]byte(" foo 20.6 1234567890 \n")) key, ts, value, err := p.ReadMetric() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("20.6"), value) assert.Equal(t, []byte("1234567890"), ts) assert.Nil(t, err) assert.Equal(t, []byte{}, p.buf) }) } func TestMultipleMetrics(t *testing.T) { p := NewParser([]byte(" foo 20.6 1234567890 \n bar 17.999 12345\nbaz ... 1337")) // first metric key, ts, value, err := p.ReadMetric() assert.Equal(t, []byte("foo"), key) assert.Equal(t, []byte("20.6"), value) assert.Equal(t, []byte("1234567890"), ts) assert.Nil(t, err) assert.Equal(t, []byte(" bar 17.999 12345\nbaz ... 1337"), p.buf) // second metric key, ts, value, err = p.ReadMetric() assert.Equal(t, []byte("bar"), key) assert.Equal(t, []byte("17.999"), value) assert.Equal(t, []byte("12345"), ts) assert.Nil(t, err) assert.Equal(t, []byte("baz ... 1337"), p.buf) // third metric key, ts, value, err = p.ReadMetric() assert.Equal(t, []byte("baz"), key) assert.Equal(t, []byte("..."), value) // this is absolutely valid here, actual validation must be done outside of the parser assert.Equal(t, []byte("1337"), ts) assert.Nil(t, err) assert.Equal(t, []byte{}, p.buf) } func TestInvalidMetrics(t *testing.T) { t.Run("invalid key", func(t *testing.T) { p := NewParser([]byte(" *** 123 123")) key, ts, value, err := p.ReadMetric() assert.Nil(t, key) assert.Nil(t, value) assert.Nil(t, ts) assert.Equal(t, InvalidKey, err) }) t.Run("invalid timestamp", func(t *testing.T) { p := NewParser([]byte(" foo timestamp 123")) key, ts, value, err := p.ReadMetric() assert.Nil(t, key) assert.Nil(t, value) assert.Nil(t, ts) assert.Equal(t, InvalidValue, err) }) t.Run("invalid value", func(t *testing.T) { p := NewParser([]byte(" foo 123 value \n")) key, ts, value, err := p.ReadMetric() assert.Nil(t, key) assert.Nil(t, value) assert.Nil(t, ts) assert.Equal(t, InvalidValue, err) }) } func TestMessageDecoding(t *testing.T) { t.Run("empty message", func(t *testing.T) { var msg *Message err := DecodeMessage([]byte{}, msg) assert.Error(t, err) }) t.Run("invalid header", func(t *testing.T) { msg := &Message{} rawMsg := []byte("foo=bar; baz\nfps 30 1234567890\n") err := DecodeMessage(rawMsg, msg) assert.Equal(t, IncompletePair, err) }) t.Run("invalid metric", func(t *testing.T) { msg := &Message{} rawMsg := []byte("foo=bar;\nfps invalid 30\n") err := DecodeMessage(rawMsg, msg) assert.Equal(t, InvalidValue, err) }) t.Run("valid message", func(t *testing.T) { msg := &Message{} rawMsg := []byte("project=my_project; foo=bar\nfps 30 1234567890\nmemory_usage 102400 1234567891") err := DecodeMessage(rawMsg, msg) assert.Len(t, msg.Header, 2) assert.Len(t, msg.Metrics, 2) assert.Equal(t, []byte("my_project"), msg.Header["project"]) assert.Equal(t, []byte("bar"), msg.Header["foo"]) assert.Equal(t, &Metric{[]byte("fps"), []byte("30"), []byte("1234567890")}, msg.Metrics[0]) assert.Equal(t, &Metric{[]byte("memory_usage"), []byte("102400"), []byte("1234567891")}, msg.Metrics[1]) assert.Nil(t, err) }) } func benchmarkParseHeaders(n int, b *testing.B) { input := append(bytes.Repeat([]byte("some_key = some_value ; "), n), '\n') var p *Parser for i := 0; i < b.N; i++ { p = NewParser(input) for x := 0; x < n; x++ { p.ReadHeader() } } } func BenchmarkParse1Header(b *testing.B) { benchmarkParseHeaders(1, b) } func BenchmarkParse10Headers(b *testing.B) { benchmarkParseHeaders(10, b) } func BenchmarkParse100Headers(b *testing.B) { benchmarkParseHeaders(100, b) } func benchmarkParseMetrics(n int, b *testing.B) { input := bytes.Repeat([]byte("some_metric_name 1234567890 1234567890\n"), n) var p *Parser for i := 0; i < b.N; i++ { p = NewParser(input) for x := 0; x < n; x++ { p.ReadMetric() } } } func BenchmarkParse1Metric(b *testing.B) { benchmarkParseMetrics(1, b) } func BenchmarkParse10Metrics(b *testing.B) { benchmarkParseMetrics(10, b) } func BenchmarkParse100Metrics(b *testing.B) { benchmarkParseMetrics(100, b) } func BenchmarkParse1000Metrics(b *testing.B) { benchmarkParseMetrics(1000, b) } <|start_filename|>pirate/parser_worker.go<|end_filename|> package pirate import ( "github.com/op/go-logging" "sync" ) type ParserWorker struct { logger *logging.Logger chUdp <-chan []byte chMsg chan<- *Message } func NewParserWorker(logger *logging.Logger, chUdp <-chan []byte, chMsg chan<- *Message) *ParserWorker { return &ParserWorker{logger, chUdp, chMsg} } func (w *ParserWorker) Run(concurrency int) { wg := sync.WaitGroup{} w.logger.Infof("[Parser] Starting %d parser workers", concurrency) for i := 0; i < concurrency; i++ { wg.Add(1) go w.run(wg) } wg.Wait() } func (w *ParserWorker) run(wg sync.WaitGroup) { for udp := range w.chUdp { msg := &Message{} if err := DecodeMessage(udp, msg); err != nil { w.logger.Warningf("[Parser] Error: %s", err) continue } w.logger.Debugf("[Parser] Parsed %d bytes to %d headers and %d metrics", len(udp), len(msg.Header), len(msg.Metrics)) w.chMsg <- msg } wg.Done() } <|start_filename|>pirate/writer.go<|end_filename|> package pirate import ( "bytes" "fmt" "github.com/op/go-logging" "io" "net" "net/url" "os" "os/signal" "sync" "syscall" "time" ) func NewWriter(target string, logger *logging.Logger, stats *MonitoringStats) (MetricWriter, error) { parsed, err := url.Parse(target) if err != nil { return nil, fmt.Errorf("Failed to create Graphite writer: %s", err) } switch parsed.Scheme { case "file": return NewFileWriter(parsed.Path, logger, stats) case "tcp": return NewTcpWriter(parsed.Host, logger, stats) default: return nil, fmt.Errorf(`Unsupported graphite target (scheme must be "tcp" or "file"): %s`, parsed.Scheme) } } func NewFileWriter(filename string, logger *logging.Logger, stats *MonitoringStats) (*wrappedWriter, error) { file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) if err != nil { return nil, fmt.Errorf("Failed to open graphite target file %s: %s", filename, err) } reopen := func() error { file.Close() if file, err = os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644); err != nil { // Huston, we've got a problem! return fmt.Errorf("Failed to reopen file %s: %s\n", filename, err) } return nil } // reopen file handle on USR1 signal go func() { chSig := make(chan os.Signal, 1) signal.Notify(chSig, syscall.SIGUSR1) for { <-chSig logger.Debugf("[SignalHandler] Reopening grafsy file %s", filename) if err := reopen(); err != nil { logger.Errorf("[SignalHandler] %s", err) } } }() return &wrappedWriter{writer: file, reopen: reopen, logger: logger, stats: stats}, nil } func NewTcpWriter(addr string, logger *logging.Logger, stats *MonitoringStats) (*wrappedWriter, error) { conn, err := net.Dial("tcp", addr) if err != nil { return nil, fmt.Errorf("TCP error: %s", err) } writer := &wrappedWriter{writer: conn, logger: logger, stats: stats} writer.reopen = func() error { conn.Close() var newWriter net.Conn for { if newWriter, err = net.Dial("tcp", addr); err == nil { break } logger.Debug("[TCP Writer] Failed to reconnect, trying again in 500 ms") time.Sleep(500 * time.Millisecond) } writer.writer = newWriter logger.Info("[TCP Writer] Reconnected successfully") return nil } return writer, nil } type MetricWriter interface { Write(m *Metric) error WriteRaw(path []byte, value []byte, timestamp []byte) error } type wrappedWriter struct { writer io.Writer reopen func() error logger *logging.Logger mu sync.Mutex stats *MonitoringStats } func (w *wrappedWriter) Write(m *Metric) error { return w.WriteRaw(m.Name, m.Value, m.Timestamp) } func (w *wrappedWriter) WriteRaw(path []byte, value []byte, timestamp []byte) error { buf := bytes.Join([][]byte{path, []byte(" "), value, []byte(" "), timestamp, []byte("\n")}, []byte{}) w.logger.Debugf("[Writer] Writing: %s", buf) if _, err := w.writer.Write(buf); err != nil { w.mu.Lock() defer w.mu.Unlock() // try to write again within the lock (it might be, that another goroutine already reconnected successfully) if _, err := w.writer.Write(buf); err != nil { w.logger.Warningf("[Writer] Failed to write metric, trying to reopen") if err = w.reopen(); err != nil { return err } if _, err := w.writer.Write(buf); err != nil { return fmt.Errorf("[Metric Writer] Failed to write metric: %s", err) } } } w.stats.IncMetricsWritten() w.stats.IncBytesOut(len(buf)) return nil } <|start_filename|>cmd/pirate-client/main.go<|end_filename|> package main import ( "bytes" "compress/gzip" "flag" "fmt" "log" "math/rand" "net" "os" "time" ) func main() { addr := flag.String("addr", ":33333", "Server address to send UDP packages to") attr := flag.String("attr", "", "Attributes") name := flag.String("name", "", "Metric name") min := flag.Float64("min", 0, "Minimum for random value") max := flag.Float64("max", 0, "Maximum for random value") frequency := flag.Duration("freq", 500*time.Millisecond, "Frequency to generate metrics") compression := flag.Bool("gzip", false, "Use gzip compression") flag.Parse() type metric struct { Name string Timestamp int64 Value float64 } udpAddr, err := net.ResolveUDPAddr("udp", *addr) if err != nil { fail("Failed to resolve UDP address: %s", err) } // establish UDP connection conn, err := net.DialUDP("udp", nil, udpAddr) if err != nil { fail("Failed to dial UDP: %s", err) } defer conn.Close() for { startTime := time.Now() // generate metrics amount := int(time.Second / *frequency) metrics := make([]*metric, amount) for i := 0; i < amount; i++ { metrics[i] = &metric{*name, time.Now().Unix(), rand.Float64()*(*max-*min) + *min} } // write metrics to buffer buf := bytes.NewBuffer(make([]byte, 0, 1024*1024)) buf.Write([]byte(*attr)) buf.WriteByte('\n') for _, m := range metrics { buf.WriteString(fmt.Sprintf("%s %f %d\n", m.Name, m.Value, m.Timestamp)) } // compress buffer, if gzip enabled if *compression { gzBuf := bytes.NewBuffer(make([]byte, 0, 64*1024)) gzWriter := gzip.NewWriter(gzBuf) buf.WriteTo(gzWriter) gzWriter.Flush() gzWriter.Close() buf = gzBuf } log.Printf("Sending %d metrics\n", amount) // write buffer to UDP connection if _, err := buf.WriteTo(conn); err != nil { fail("Failed to send UDP package: %s", err) } time.Sleep(1*time.Second - (time.Now().Sub(startTime))) } } func fail(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(1) } <|start_filename|>pirate/validator_worker.go<|end_filename|> package pirate import ( "errors" "fmt" "github.com/op/go-logging" "strconv" "sync" "time" ) type validatorWorker struct { cfg *Config logger *logging.Logger stats *MonitoringStats chIn <-chan *Message chOut chan<- *Message } func NewValidatorWorker(cfg *Config, logger *logging.Logger, stats *MonitoringStats, chIn <-chan *Message, chOut chan<- *Message) *validatorWorker { return &validatorWorker{cfg, logger, stats, chIn, chOut} } func (w *validatorWorker) Run(concurrency int) { wg := sync.WaitGroup{} w.logger.Infof("[Validator] Starting %d validation workers", concurrency) for i := 0; i < concurrency; i++ { wg.Add(1) go w.run(wg) } wg.Wait() } func (w *validatorWorker) run(wg sync.WaitGroup) { for msg := range w.chIn { metricsBefore := len(msg.Metrics) w.stats.IncMsgReceived() w.stats.IncMetricsReceived(metricsBefore) if err := w.validateMsg(msg); err != nil { w.logger.Noticef("[Validator] Validation failed: %s", err) w.stats.IncMsgDropped() w.stats.IncMetricsDropped(metricsBefore) continue } w.logger.Debugf("[Validator] Validation succeeded with %d of %d metrics", len(msg.Metrics), metricsBefore) w.stats.IncMetricsDropped(metricsBefore - len(msg.Metrics)) w.chOut <- msg } wg.Done() } func (w *validatorWorker) validateMsg(msg *Message) error { // check, if project attribute is set pid, exists := msg.Header["project"] if !exists { return errors.New("Missing project attribute") } // check, if target project is configured projectCfg, exists := w.cfg.Projects[string(pid)] if !exists { return fmt.Errorf(`Unknown project ID "%s"`, pid) } // validate headers against regex for key, value := range msg.Header { // project is already valid by its existence in config if key == "project" { continue } attrRegexp, exists := projectCfg.AttributesRegex[key] if !exists { return fmt.Errorf(`Unknown attribute "%s" in project "%s"`, key, pid) } if !attrRegexp.Match(value) { return fmt.Errorf(`Attribute value "%s" does not match regexp for %s.%s`, value, pid, key) } } if len(msg.Metrics) == 0 { return errors.New("Missing metrics") } // validate metrics validIdx := 0 for _, metric := range msg.Metrics { if err := w.validateMetric(projectCfg, metric); err != nil { w.logger.Infof("[Validator] Validation failed for %s.%s: %s", pid, metric.Name, err) continue } // keep valid element msg.Metrics[validIdx] = metric validIdx++ } msg.Metrics = msg.Metrics[:validIdx] if len(msg.Metrics) == 0 { return errors.New("No valid metrics found") } return nil } func (w *validatorWorker) validateMetric(cfg *ProjectConfig, metric *Metric) error { // check, if metrics key is configured key := string(metric.Name) metricCfg, exists := cfg.Metrics[key] if !exists { return fmt.Errorf(`unknown metric key "%s"`, key) } // validate timestamp ts, err := strconv.ParseInt(string(metric.Timestamp), 10, 64) if err != nil { return errors.New("timestamp must be int64-compatible") } metricTime := time.Unix(ts, 0) if time.Now().Add(10 * time.Second).Truncate(time.Second).Before(metricTime) { // TODO: make max future time configurable return fmt.Errorf("future timestamp (%s ahead)", metricTime.Sub(time.Now())) } if time.Now().Add(-3 * time.Hour).Truncate(time.Second).After(metricTime) { // TODO: make max age configurable return fmt.Errorf("timestamp too old (%s behind)", metricTime.Truncate(time.Second).Sub(time.Now())) } // validate value value, err := strconv.ParseFloat(string(metric.Value), 64) if err != nil { return errors.New("value must be float64-compatible") } if value < metricCfg.Min { return errors.New("value lower than configured minimum") } if value > metricCfg.Max { return errors.New("value higher than configured maximum") } return nil } <|start_filename|>pirate/graphite_template_test.go<|end_filename|> package pirate import ( "errors" "github.com/stretchr/testify/assert" "testing" ) func TestEmptyTemplate(t *testing.T) { t.Run("parse", func(t *testing.T) { tpl, err := ParsePathTemplate([]byte("")) assert.Nil(t, tpl.parts) assert.Nil(t, err) }) t.Run("resolve", func(t *testing.T) { tpl := &pathTemplate{} resolved, err := tpl.Resolve(&Context{}) assert.Nil(t, resolved) assert.Nil(t, err) }) } func TestParseSimpleTemplate(t *testing.T) { t.Run("one static part", func(t *testing.T) { tpl, err := ParsePathTemplate([]byte("foo.bar.baz")) assert.Len(t, tpl.parts, 1) assert.Equal(t, &staticNode{[]byte("foo.bar.baz")}, tpl.parts[0]) assert.Nil(t, err) }) t.Run("one attr var", func(t *testing.T) { tpl, err := ParsePathTemplate([]byte("{attr.foo}")) assert.Len(t, tpl.parts, 1) assert.Equal(t, &attrNode{"foo"}, tpl.parts[0]) assert.Nil(t, err) }) t.Run("one metric var", func(t *testing.T) { tpl, err := ParsePathTemplate([]byte("{metric.foo}")) assert.Error(t, err) assert.Nil(t, tpl) }) } func TestParseMixedTemplate(t *testing.T) { t.Run("one attribute in between", func(t *testing.T) { tpl, err := ParsePathTemplate([]byte("foo.{attr.bar}.baz")) assert.Equal( t, []node{ &staticNode{[]byte("foo.")}, &attrNode{"bar"}, &staticNode{[]byte(".baz")}, }, tpl.parts, ) assert.Nil(t, err) }) t.Run("metric and attribute in between", func(t *testing.T) { tpl, err := ParsePathTemplate([]byte("foo.{attr.bar}.baz.{metric.name}.something.else")) assert.Equal( t, []node{ &staticNode{[]byte("foo.")}, &attrNode{"bar"}, &staticNode{[]byte(".baz.")}, &metricNameNode{}, &staticNode{[]byte(".something.else")}, }, tpl.parts, ) assert.Nil(t, err) }) } type testNode struct { f func(ctx *Context) ([]byte, error) } func (node *testNode) Resolve(ctx *Context) ([]byte, error) { return node.f(ctx) } func TestResolveTemplate(t *testing.T) { t.Run("successfull resolution", func(t *testing.T) { tpl := &pathTemplate{ parts: []node{ &testNode{func(ctx *Context) ([]byte, error) { return []byte("aa"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { return []byte("bb"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { return []byte("cc"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { return []byte("dd"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { return []byte("ee"), nil }}, }, } res, err := tpl.Resolve(&Context{}) assert.Equal(t, []byte("aabbccddee"), res) assert.Nil(t, err) }) t.Run("failing node", func(t *testing.T) { called := 0 tpl := &pathTemplate{ parts: []node{ &testNode{func(ctx *Context) ([]byte, error) { called++; return []byte("aa"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { called++; return []byte("bb"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { called++; return []byte("cc"), nil }}, &testNode{func(ctx *Context) ([]byte, error) { called++; return nil, errors.New("dummy") }}, &testNode{func(ctx *Context) ([]byte, error) { called++; return []byte("ee"), nil }}, }, } b, err := tpl.Resolve(&Context{}) assert.Nil(t, b, "primary result must be nil, when error occures") assert.Equal(t, 4, called, "only first 4 nodes until the error must be resolved") assert.Error(t, err) }) } func TestResolveNodes(t *testing.T) { t.Run("static node", func(t *testing.T) { node := &staticNode{[]byte("foo.bar.baz")} res, err := node.Resolve(&Context{}) assert.Equal(t, []byte("foo.bar.baz"), res) assert.Nil(t, err) }) t.Run("attr node with existing value", func(t *testing.T) { node := &attrNode{"foo"} ctx := &Context{attr: map[string][]byte{"foo": []byte("some_value")}} res, err := node.Resolve(ctx) assert.Equal(t, []byte("some_value"), res) assert.Nil(t, err) }) t.Run("attr node with dot in value", func(t *testing.T) { node := &attrNode{"version"} ctx := &Context{attr: map[string][]byte{"version": []byte("1.3.37")}} res, err := node.Resolve(ctx) assert.Equal(t, []byte("1_3_37"), res) assert.Nil(t, err) }) t.Run("attr node with unknown value", func(t *testing.T) { node := &attrNode{"bar"} ctx := &Context{attr: map[string][]byte{"foo": []byte("some_value")}} res, err := node.Resolve(ctx) assert.Nil(t, res) assert.Error(t, err) }) t.Run("metric node with existing value", func(t *testing.T) { node := &attrNode{"value"} ctx := &Context{attr: map[string][]byte{"value": []byte("1337")}} res, err := node.Resolve(ctx) assert.Equal(t, []byte("1337"), res) assert.Nil(t, err) }) t.Run("metric node with dot in value", func(t *testing.T) { node := &attrNode{"name"} ctx := &Context{attr: map[string][]byte{"name": []byte("something_60.0")}} res, err := node.Resolve(ctx) assert.Equal(t, []byte("something_60_0"), res) assert.Nil(t, err) }) t.Run("metric node with unknown value", func(t *testing.T) { node := &attrNode{"bar"} ctx := &Context{attr: map[string][]byte{"value": []byte("1337")}} res, err := node.Resolve(ctx) assert.Nil(t, res) assert.Error(t, err) }) } <|start_filename|>pirate/writer_worker.go<|end_filename|> package pirate import ( "github.com/op/go-logging" "sync" ) type writerWorker struct { writer MetricWriter logger *logging.Logger chMetric chan *Metric } func NewWriterWorker(writer MetricWriter, logger *logging.Logger, chMetric chan *Metric) *writerWorker { worker := new(writerWorker) worker.writer = writer worker.logger = logger worker.chMetric = chMetric return worker } func (w *writerWorker) Run(concurrency int) { var wg sync.WaitGroup w.logger.Infof("[Writer] Starting %d writer workers", concurrency) for i := 0; i < concurrency; i++ { wg.Add(1) go w.run(wg) } wg.Wait() } func (w *writerWorker) run(wg sync.WaitGroup) { for metric := range w.chMetric { if err := w.writer.Write(metric); err != nil { w.logger.Debugf("[Writer] Re-scheduling metric") w.chMetric <- metric } } wg.Done() } <|start_filename|>pirate/message.go<|end_filename|> package pirate import ( "strconv" "time" ) type Message struct { Header map[string][]byte Metrics []*Metric } type Metric struct { Name []byte Value []byte Timestamp []byte } func NewMetric(name string, value float32, timestamp time.Time) *Metric { return &Metric{ []byte(name), strconv.AppendFloat(nil, float64(value), 'g', -1, 32), strconv.AppendInt(nil, timestamp.Unix(), 10), } } <|start_filename|>pirate/parser.go<|end_filename|> package pirate import ( "bytes" "errors" ) var ( // errors EndOfHeader = errors.New("End of header line was reached") MissingEndOfLine = errors.New("End of line missing") InvalidKey = errors.New("Invalid key") InvalidValue = errors.New("Invalid value") IncompletePair = errors.New("Incomplete pair") EndOfMetrics = errors.New("End of metrics block was reached") // basic char sets num = []byte("0123456789") alphaLower = []byte("abcdefghijklmnopqrstuvwxyz") alphaUpper = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ") alpha = append(alphaLower, alphaUpper...) alphaNum = append(alpha, num...) // specific char sets headerKeyChars = append(alphaLower, '_') headerValueChars = append(alphaNum, []byte("+/-_.")...) metricKeyChars = append(alphaNum, '_') timestampChars = num metricValueChars = append(num, '.') ) type Parser struct { buf []byte } func NewParser(b []byte) *Parser { return &Parser{b} } func DecodeMessage(b []byte, msg *Message) error { if msg == nil { return errors.New("Message must not be nil") } msg.Header = make(map[string][]byte) msg.Metrics = make([]*Metric, 0, 10) p := NewParser(b) for { key, value, err := p.ReadHeader() if err == EndOfHeader { break } if err != nil { return err } msg.Header[string(key)] = value } for { key, ts, value, err := p.ReadMetric() if err == EndOfMetrics { break } if err != nil { return err } msg.Metrics = append(msg.Metrics, &Metric{key, value, ts}) } return nil } func (p *Parser) ReadHeader() (key []byte, value []byte, err error) { var ok bool if bytes.IndexByte(p.buf, '\n') == -1 { return nil, nil, MissingEndOfLine } p.skipSpaces() if p.skipByte('\n') { return nil, nil, EndOfHeader } if key, ok = p.readAny(headerKeyChars); !ok { return nil, nil, InvalidKey } p.skipSpaces() if !p.skipByte('=') { return nil, nil, IncompletePair } p.skipSpaces() if value, ok = p.readAny(headerValueChars); !ok { return nil, nil, InvalidValue } p.skipSpaces() if p.skipByte(';') { p.skipSpaces() } return } func (p *Parser) ReadMetric() (key []byte, ts []byte, value []byte, err error) { var ok bool p.skipSpaces() if len(p.buf) == 0 || p.skipByte('\n') { return nil, nil, nil, EndOfMetrics } // read key if key, ok = p.readAny(metricKeyChars); !ok { return nil, nil, nil, InvalidKey } p.skipSpaces() // read value if value, ok = p.readAny(metricValueChars); !ok { return nil, nil, nil, InvalidValue } p.skipSpaces() // read timestamp if ts, ok = p.readAny(timestampChars); !ok { return nil, nil, nil, InvalidValue } p.skipSpaces() p.skipByte('\n') return } func (p *Parser) skipSpaces() { var i int for i = 0; i < len(p.buf); i++ { if p.buf[i] != ' ' { break } } p.buf = p.buf[i:] } func (p *Parser) skipByte(b byte) bool { if len(p.buf) > 0 && p.buf[0] == b { p.buf = p.buf[1:] return true } return false } func (p *Parser) readAny(allowed []byte) ([]byte, bool) { if len(p.buf) == 0 { return nil, false } var i int for i = 0; i < len(p.buf); i++ { if !isAny(p.buf[i], allowed) { break } } b := p.buf[0:i] p.buf = p.buf[i:] return b, i > 0 } func isAny(b byte, chars []byte) bool { for _, c := range chars { if b == c { return true } } return false } <|start_filename|>pirate/graphite_template.go<|end_filename|> package pirate import ( "bytes" "fmt" "regexp" ) var ( attrRegexp = regexp.MustCompile(`\{([a-z]+)\.([a-zA-Z][a-zA-Z0-9_]*)}`) ) type Context struct { attr map[string][]byte metric *Metric } func NewCtx(attr map[string][]byte, metric *Metric) *Context { return &Context{attr, metric} } func NewMonitoringCtx(metric *Metric) *Context { return NewCtx(make(map[string][]byte), metric) } type pathTemplate struct { parts []node } func ParsePathTemplate(input []byte) (*pathTemplate, error) { tpl := &pathTemplate{} prev := 0 for _, match := range attrRegexp.FindAllSubmatchIndex(input, -1) { start, end := match[0], match[1] // everything between placeholders is static if start > prev { tpl.parts = append(tpl.parts, &staticNode{input[prev:start]}) } holder := input[match[2]:match[3]] name := input[match[4]:match[5]] switch string(holder) { case "attr": tpl.parts = append(tpl.parts, &attrNode{string(name)}) case "metric": if string(name) != "name" { return nil, fmt.Errorf(`Invalid member name "%s" on "metric", only "name" allowed`, name) } tpl.parts = append(tpl.parts, &metricNameNode{}) default: return nil, fmt.Errorf(`Invalid variable holder "%s", only "attr" and "metric" allowed`, holder) } prev = end } // remaining static part if rest := input[prev:]; len(rest) > 0 { tpl.parts = append(tpl.parts, &staticNode{rest}) } return tpl, nil } func (tpl *pathTemplate) Resolve(ctx *Context) ([]byte, error) { var buf []byte for _, p := range tpl.parts { b, err := p.Resolve(ctx) if err != nil { return nil, err } buf = append(buf, b...) } return buf, nil } type node interface { Resolve(ctx *Context) ([]byte, error) } type staticNode struct { value []byte } func (node *staticNode) Resolve(ctx *Context) ([]byte, error) { return node.value, nil } type attrNode struct { name string } func (node attrNode) Resolve(ctx *Context) ([]byte, error) { if value, ok := ctx.attr[node.name]; ok { if bytes.IndexByte(value, '.') != -1 { value = bytes.Replace(value, []byte{'.'}, []byte{'_'}, -1) } return value, nil } return nil, fmt.Errorf(`Failed to resolve attribute "%s"`, node.name) } type metricNameNode struct{} func (node metricNameNode) Resolve(ctx *Context) ([]byte, error) { return ctx.metric.Name, nil } <|start_filename|>pirate/config.go<|end_filename|> package pirate import ( "errors" "fmt" "github.com/op/go-logging" "gopkg.in/yaml.v2" "io/ioutil" "regexp" "time" ) type Config struct { UdpAddress string `yaml:"udp_address"` GraphiteTarget string `yaml:"graphite_target"` PerIpRateLimit *RateLimitConfig `yaml:"per_ip_ratelimit"` Gzip bool `yaml:"gzip"` LogLevelStr string `yaml:"log_level"` LogLevel logging.Level `yaml:"-"` MonitoringEnabled bool `yaml:"monitoring_enabled"` MonitoringPattern string `yaml:"monitoring_path"` MonitoringTemplate *pathTemplate `yaml:"-"` Projects map[string]*ProjectConfig } type ProjectConfig struct { GraphitePattern string `yaml:"graphite_path"` GraphiteTemplate *pathTemplate `yaml:"-"` Metrics map[string]*MetricConfig `yaml:"metrics"` Attributes map[string]string `yaml:"attributes"` AttributesRegex map[string]*regexp.Regexp `yaml:"-"` } type MetricConfig struct { GraphitePattern string `yaml:"graphite_path"` GraphiteTemplate *pathTemplate `yaml:"-"` Min float64 `yaml:"min"` Max float64 `yaml:"max"` } type RateLimitConfig struct { Enabled bool `yaml:"enabled"` Amount int `yaml:"amount"` Interval time.Duration `yaml:"interval"` } var DefaultConfig = Config{ UdpAddress: "0.0.0.0:33333", GraphiteTarget: "tcp://127.0.0.1:3002", MonitoringEnabled: true, MonitoringPattern: "pirate.{metric.name}", Gzip: true, LogLevelStr: "info", PerIpRateLimit: &RateLimitConfig{ Enabled: true, Amount: 100, Interval: 1 * time.Minute, }, Projects: make(map[string]*ProjectConfig), } func LoadConfig(filename string) (*Config, error) { content, err := ioutil.ReadFile(filename) if err != nil { return nil, fmt.Errorf("Failed to load config file from %s: %s", filename, err) } cfg := &DefaultConfig if err := yaml.Unmarshal(content, cfg); err != nil { return nil, fmt.Errorf("Failed to parse configuration file: %s", err) } // initialize monitoring template if cfg.MonitoringEnabled { if cfg.MonitoringTemplate, err = ParsePathTemplate([]byte(cfg.MonitoringPattern)); err != nil { return nil, fmt.Errorf(`Invalid path for "monitoring_path": %s`, err) } } // initialize regexps and templates for pid, project := range cfg.Projects { // initialize graphite path templates if project.GraphiteTemplate, err = ParsePathTemplate([]byte(project.GraphitePattern)); err != nil { return nil, fmt.Errorf(`Invalid path for "projects.%s.graphite_path": %s`, pid, err) } // initialize attribute regexps project.AttributesRegex = make(map[string]*regexp.Regexp) for aid, attr := range project.Attributes { if cfg.Projects[pid].AttributesRegex[aid], err = regexp.Compile(attr); err != nil { return nil, fmt.Errorf(`Invalid regexp for "projects.%s.attributes.%s": %s`, pid, aid, err) } } // initialize graphite path templates for metrics for mid, metric := range project.Metrics { // use same template from project, if not overridden if metric.GraphitePattern == "" { metric.GraphitePattern = project.GraphitePattern metric.GraphiteTemplate = project.GraphiteTemplate } else { // compile custom template for metric if metric.GraphiteTemplate, err = ParsePathTemplate([]byte(metric.GraphitePattern)); err != nil { return nil, fmt.Errorf(`Invalid path for "projects.%s.%s.graphite_path": %s`, pid, mid, err) } } } } // initialize log level cfg.LogLevel = logging.WARNING if cfg.LogLevelStr != "" { cfg.LogLevel, err = logging.LogLevel(cfg.LogLevelStr) if err != nil { return nil, errors.New("Invalid log level. Allowed levels are: DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL") } } return cfg, nil } func (cfg *Config) Log(logger *logging.Logger) { logger.Infof("[Config] UDP Address: %s", cfg.UdpAddress) logger.Infof("[Config] Graphite Target: %s", cfg.GraphiteTarget) logger.Infof("[Config] UDP Rate Limit: %d metrics per %s per IP", cfg.PerIpRateLimit.Amount, cfg.PerIpRateLimit.Interval) logger.Infof("[Config] Projects:") for pid, project := range cfg.Projects { logger.Infof("[Config] - %s", pid) for mid, metric := range project.Metrics { logger.Infof("[Config] - %s [min=%.0f max=%.0f path=%s]", mid, metric.Min, metric.Max, metric.GraphitePattern) } } } <|start_filename|>pirate/ratelimit.go<|end_filename|> package pirate import ( "net" "sync" "time" ) const ( LimiterGcInterval = 5 * time.Minute ) type LimitInfo struct { startedAt time.Time count int } type IpLimiter struct { max int interval time.Duration lookup map[string]*LimitInfo mu sync.Mutex } func NewIpLimiter(max int, interval time.Duration) *IpLimiter { limiter := new(IpLimiter) limiter.max = max limiter.interval = interval limiter.lookup = make(map[string]*LimitInfo) go limiter.runGcLoop() return limiter } func (l *IpLimiter) Allow(ip net.IP) bool { return l.AllowN(ip, 1) } func (l *IpLimiter) AllowN(ip net.IP, n int) bool { l.mu.Lock() ipStr := ip.String() info, ok := l.lookup[ipStr] now := time.Now() // make sure entry exists if !ok { if info, ok = l.lookup[ipStr]; !ok { info = &LimitInfo{now, 0} l.lookup[ipStr] = info } } // initialize current window if info.startedAt.Add(l.interval).Before(now) { info.startedAt = now info.count = 0 } info.count += n l.mu.Unlock() return info.count <= l.max } func (l *IpLimiter) runGcLoop() { for { time.Sleep(LimiterGcInterval) l.mu.Lock() clearTime := time.Now().Add(-l.interval) for ip, info := range l.lookup { if info.startedAt.Before(clearTime) { delete(l.lookup, ip) } } l.mu.Unlock() } } type Limiter struct { max int interval time.Duration info *LimitInfo mu sync.Mutex } func NewLimiter(max int, interval time.Duration) *Limiter { limiter := new(Limiter) limiter.max = max limiter.interval = interval limiter.info = &LimitInfo{time.Unix(0, 0), 0} return limiter } func (l *Limiter) Allow() bool { return l.AllowN(1) } func (l *Limiter) AllowN(n int) bool { l.mu.Lock() now := time.Now() if l.info.startedAt.Add(l.interval).Before(now) { l.info.startedAt = now l.info.count = 0 } l.info.count += n l.mu.Unlock() return l.info.count <= l.max } <|start_filename|>pirate/metric_worker.go<|end_filename|> package pirate import ( "github.com/op/go-logging" "sync" ) type metricWorker struct { cfg *Config logger *logging.Logger chMsg <-chan *Message chMetric chan<- *Metric } func NewMetricWorker(cfg *Config, logger *logging.Logger, chMsg <-chan *Message, chMetric chan<- *Metric) *metricWorker { return &metricWorker{cfg, logger, chMsg, chMetric} } func (w *metricWorker) Run(concurrency int) { var wg sync.WaitGroup w.logger.Infof("[MetricResolver] Starting %d metric workers", concurrency) for i := 0; i < concurrency; i++ { wg.Add(1) go w.run(wg) } wg.Wait() } func (w *metricWorker) run(wg sync.WaitGroup) { var projectCfg *ProjectConfig var metricCfg *MetricConfig for msg := range w.chMsg { projectCfg = w.cfg.Projects[string(msg.Header["project"])] for _, metric := range msg.Metrics { metricCfg = projectCfg.Metrics[string(metric.Name)] path, err := metricCfg.GraphiteTemplate.Resolve(NewCtx(msg.Header, metric)) if err != nil { w.logger.Errorf("[MetricResolver] %s", err) continue } w.logger.Debugf("[MetricResolver] Resolved path of %s.%s to %s", msg.Header["project"], metric.Name, path) w.chMetric <- &Metric{path, metric.Value, metric.Timestamp} } } wg.Done() } <|start_filename|>pirate/monitoring.go<|end_filename|> package pirate import ( "github.com/op/go-logging" "sync" "time" ) type MonitoringStats struct { stats map[string]int mu sync.Mutex } func NewMonitoringStats() *MonitoringStats { return &MonitoringStats{stats: make(map[string]int)} } func (s *MonitoringStats) IncBytesIn(delta int) { s.add("bytes_in", delta) } func (s *MonitoringStats) IncBytesOut(delta int) { s.add("bytes_out", delta) } func (s *MonitoringStats) IncUdpReceived() { s.add("udp_received", 1) } func (s *MonitoringStats) IncUdpDropped() { s.add("udp_dropped", 1) } func (s *MonitoringStats) IncMsgReceived() { s.add("messages_received", 1) } func (s *MonitoringStats) IncMsgDropped() { s.add("messages_dropped", 1) } func (s *MonitoringStats) IncMetricsReceived(delta int) { s.add("metrics_received", delta) } func (s *MonitoringStats) IncMetricsDropped(delta int) { s.add("metrics_dropped", delta) } func (s *MonitoringStats) IncMetricsWritten() { s.add("metrics_written", 1) } func (s *MonitoringStats) add(key string, delta int) { s.mu.Lock() defer s.mu.Unlock() s.stats[key] = s.stats[key] + delta } func (s *MonitoringStats) Reset() map[string]int { s.mu.Lock() defer s.mu.Unlock() oldStats := s.stats s.stats = make(map[string]int) return oldStats } type MonitoringWorker struct { cfg *Config logger *logging.Logger chMetric chan<- *Metric stats *MonitoringStats } func NewMonitoringWorker(cfg *Config, logger *logging.Logger, chMetric chan<- *Metric, stats *MonitoringStats) *MonitoringWorker { return &MonitoringWorker{cfg, logger, chMetric, stats} } func (w *MonitoringWorker) Run() { w.logger.Info("[Monitoring] Starting monitoring worker") for { time.Sleep(1 * time.Minute) now := time.Now() for key, value := range w.stats.Reset() { w.logger.Infof("[Monitoring] %s = %d", key, value) if w.cfg.MonitoringEnabled { rawMetric := NewMetric(key, float32(value), now) path, err := w.cfg.MonitoringTemplate.Resolve(NewMonitoringCtx(rawMetric)) if err != nil { w.logger.Errorf("[Monitoring] Failed to resolve path: %s", err) continue } select { case w.chMetric <- NewMetric(string(path), float32(value), now): default: w.logger.Noticef("[Monitoring] Write buffer is full, failed to send monitoring metric %s", key) } } } } } <|start_filename|>pirate/compression.go<|end_filename|> package pirate import ( "bytes" "compress/gzip" "fmt" "github.com/op/go-logging" "io/ioutil" "sync" ) type DecompressFunc func(b []byte) ([]byte, error) type compressionWorker struct { decompress DecompressFunc logger *logging.Logger chIn <-chan []byte chOut chan<- []byte } func NewPlainDecompressor() DecompressFunc { return func(b []byte) ([]byte, error) { return b, nil } } func NewGzipDecompressor() DecompressFunc { return func(b []byte) ([]byte, error) { reader, err := gzip.NewReader(bytes.NewBuffer(b)) if err != nil { return nil, fmt.Errorf("Failed to initialize gzip reader: %s", err) } defer reader.Close() return ioutil.ReadAll(reader) } } func NewCompressionWorker(decomp DecompressFunc, logger *logging.Logger, chIn <-chan []byte, chOut chan<- []byte) *compressionWorker { return &compressionWorker{decomp, logger, chIn, chOut} } func (w *compressionWorker) Run(concurrency int) { var wg sync.WaitGroup w.logger.Infof("[Decompressor] Starting %d decompression workers", concurrency) for i := 0; i < concurrency; i++ { wg.Add(1) go w.run(wg) } wg.Wait() } func (w *compressionWorker) run(wg sync.WaitGroup) { for in := range w.chIn { out, err := w.decompress(in) if err != nil { w.logger.Warningf("[Decompressor] Failed to decompress: %s", err) continue } if w.logger.IsEnabledFor(logging.DEBUG) { w.logger.Debugf("[Decompressor] Decompressed %d bytes to %d bytes", len(in), len(out)) for _, row := range bytes.Split(bytes.TrimSpace(out), []byte("\n")) { w.logger.Debugf("[Decompressor] > %s", row) } } w.chOut <- out } wg.Done() } <|start_filename|>pirate/udp_server.go<|end_filename|> package pirate import ( "fmt" "github.com/op/go-logging" "net" ) const ( UdpBufferSize = 64 * 1024 ) type UdpServer struct { address *net.UDPAddr logger *logging.Logger stats *MonitoringStats limiter *IpLimiter chUdp chan<- []byte } func NewUdpServer(address string, ratelimit *RateLimitConfig, logger *logging.Logger, stats *MonitoringStats, chUdp chan<- []byte) (*UdpServer, error) { parsedAddr, err := net.ResolveUDPAddr("udp", address) if err != nil { return nil, fmt.Errorf("Unable to resolve UDP address %s: %s", address, err) } limiter := NewIpLimiter(ratelimit.Amount, ratelimit.Interval) return &UdpServer{parsedAddr, logger, stats, limiter, chUdp}, nil } func (s *UdpServer) Run() error { conn, err := net.ListenUDP("udp", s.address) if err != nil { return fmt.Errorf("Unable to start UDP server on %s: %s", s.address.String(), err) } defer conn.Close() buf := make([]byte, UdpBufferSize) for { // accept packet n, addr, err := conn.ReadFromUDP(buf) if err != nil { s.logger.Infof("[UDP] Failed to read packet: %s", err) continue } s.logger.Debugf("[UDP] Received %d bytes", n) s.stats.IncBytesIn(n) s.stats.IncUdpReceived() // check rate limit if !s.limiter.Allow(addr.IP) { s.logger.Infof("[UDP] Rate Limit reached for address: %s", addr.IP.String()) s.stats.IncUdpDropped() continue } // forward packet packet := make([]byte, n) copy(packet, buf) select { case s.chUdp <- packet: default: s.logger.Debug("[UDP] Buffer is full, packet got dropped") s.stats.IncUdpDropped() } } }
innogames/pirate
<|start_filename|>third_party/openfst/src/extensions/far/farcompilestrings.cc<|end_filename|> // farcompilestrings.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use new arc-type dispatching // // \file // Compiles a set of stings as FSTs and stores them in a finite-state // archive. // #include <fst/extensions/far/farscript.h> #include <fst/extensions/far/main.h> #include <iostream> #include <fstream> #include <sstream> DEFINE_string(key_prefix, "", "Prefix to append to keys"); DEFINE_string(key_suffix, "", "Suffix to append to keys"); DEFINE_int32(generate_keys, 0, "Generate N digit numeric keys (def: use file basenames)"); DEFINE_string(far_type, "default", "FAR file format type: one of: \"default\", \"fst\", " "\"stlist\", \"sttable\""); DEFINE_bool(allow_negative_labels, false, "Allow negative labels (not recommended; may cause conflicts)"); DEFINE_string(arc_type, "standard", "Output arc type"); DEFINE_string(entry_type, "line", "Entry type: one of : " "\"file\" (one FST per file), \"line\" (one FST per line)"); DEFINE_string(fst_type, "vector", "Output FST type"); DEFINE_string(token_type, "symbol", "Token type: one of : " "\"symbol\", \"byte\", \"utf8\""); DEFINE_string(symbols, "", "Label symbol table"); DEFINE_string(unknown_symbol, "", ""); DEFINE_bool(file_list_input, false, "Each input files contains a list of files to be processed"); DEFINE_bool(keep_symbols, false, "Store symbol table in Far file"); DEFINE_bool(initial_symbols, true, "When keep_symbols==true, stores symbol table only for the first" " Fst in archive."); int main(int argc, char **argv) { namespace s = fst::script; string usage = "Compiles a set of strings as FSTs and stores them in"; usage += " a finite-state archive.\n\n Usage:"; usage += argv[0]; usage += " [in1.txt [[in2.txt ...] out.far]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); vector<string> in_fnames; for (unsigned i = 1; i < argc - 1; ++i) in_fnames.push_back(strcmp(argv[i], "") != 0 ? argv[i] : ""); if (in_fnames.empty()) in_fnames.push_back(argc == 2 && strcmp(argv[1], "-") != 0 ? argv[1] : ""); string out_fname = argc > 2 && strcmp(argv[argc - 1], "-") != 0 ? argv[argc - 1] : ""; fst::FarEntryType fet = fst::StringToFarEntryType(FLAGS_entry_type); fst::FarTokenType ftt = fst::StringToFarTokenType(FLAGS_token_type); fst::FarType far_type = fst::FarTypeFromString(FLAGS_far_type); s::FarCompileStrings(in_fnames, out_fname, FLAGS_arc_type, FLAGS_fst_type, far_type, FLAGS_generate_keys, fet, ftt, FLAGS_symbols, FLAGS_unknown_symbol, FLAGS_keep_symbols, FLAGS_initial_symbols, FLAGS_allow_negative_labels, FLAGS_file_list_input, FLAGS_key_prefix, FLAGS_key_suffix); return 0; } <|start_filename|>third_party/openfst/src/include/fst/map.h<|end_filename|> // map.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Compatability file for old-style Map() functions and MapFst class // that have been renamed to ArcMap (cf. StateMap). #ifndef FST_LIB_MAP_H__ #define FST_LIB_MAP_H__ #include <fst/arc-map.h> namespace fst { template<class A, class C> void Map(MutableFst<A> *fst, C* mapper) { ArcMap(fst, mapper); } template<class A, class C> void Map(MutableFst<A> *fst, C mapper) { ArcMap(fst, mapper); } template<class A, class B, class C> void Map(const Fst<A> &ifst, MutableFst<B> *ofst, C* mapper) { ArcMap(ifst, ofst, mapper); } template<class A, class B, class C> void Map(const Fst<A> &ifst, MutableFst<B> *ofst, C mapper) { ArcMap(ifst, ofst, mapper); } typedef ArcMapFstOptions MapFstOptions; template <class A, class B, class C> class MapFst : public ArcMapFst<A, B, C> { public: typedef B Arc; typedef typename B::Weight Weight; typedef typename B::StateId StateId; typedef CacheState<B> State; MapFst(const Fst<A> &fst, const C &mapper, const MapFstOptions& opts) : ArcMapFst<A, B, C>(fst, mapper, opts) {} MapFst(const Fst<A> &fst, C* mapper, const MapFstOptions& opts) : ArcMapFst<A, B, C>(fst, mapper, opts) {} MapFst(const Fst<A> &fst, const C &mapper) : ArcMapFst<A, B, C>(fst, mapper) {} MapFst(const Fst<A> &fst, C* mapper) : ArcMapFst<A, B, C>(fst, mapper) {} // See Fst<>::Copy() for doc. MapFst(const ArcMapFst<A, B, C> &fst, bool safe = false) : ArcMapFst<A, B, C>(fst, safe) {} // Get a copy of this MapFst. See Fst<>::Copy() for further doc. virtual MapFst<A, B, C> *Copy(bool safe = false) const { return new MapFst(*this, safe); } }; // Specialization for MapFst. template <class A, class B, class C> class StateIterator< MapFst<A, B, C> > : public StateIterator< ArcMapFst<A, B, C> > { public: explicit StateIterator(const ArcMapFst<A, B, C> &fst) : StateIterator< ArcMapFst<A, B, C> >(fst) {} }; // Specialization for MapFst. template <class A, class B, class C> class ArcIterator< MapFst<A, B, C> > : public ArcIterator< ArcMapFst<A, B, C> > { public: ArcIterator(const ArcMapFst<A, B, C> &fst, typename A::StateId s) : ArcIterator< ArcMapFst<A, B, C> >(fst, s) {} }; template <class A> struct IdentityMapper { typedef A FromArc; typedef A ToArc; A operator()(const A &arc) const { return arc; } MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } MapSymbolsAction InputSymbolsAction() const { return MAP_COPY_SYMBOLS; } MapSymbolsAction OutputSymbolsAction() const { return MAP_COPY_SYMBOLS;} uint64 Properties(uint64 props) const { return props; } }; } // namespace fst #endif // FST_LIB_MAP_H__ <|start_filename|>third_party/openfst/src/include/fst/extensions/far/equal.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_EXTENSIONS_FAR_EQUAL_H_ #define FST_EXTENSIONS_FAR_EQUAL_H_ #include <string> #include <fst/extensions/far/far.h> #include <fst/equal.h> namespace fst { template <class Arc> bool FarEqual(const string &filename1, const string &filename2, float delta = kDelta, const string &begin_key = string(), const string &end_key = string()) { FarReader<Arc> *reader1 = FarReader<Arc>::Open(filename1); FarReader<Arc> *reader2 = FarReader<Arc>::Open(filename2); if (!reader1 || !reader2) { delete reader1; delete reader2; VLOG(1) << "FarEqual: cannot open input Far file(s)"; return false; } if (!begin_key.empty()) { bool find_begin1 = reader1->Find(begin_key); bool find_begin2 = reader2->Find(begin_key); if (!find_begin1 || !find_begin2) { bool ret = !find_begin1 && !find_begin2; if (!ret) { VLOG(1) << "FarEqual: key \"" << begin_key << "\" missing from " << (find_begin1 ? "second" : "first") << " archive."; } delete reader1; delete reader2; return ret; } } for(; !reader1->Done() && !reader2->Done(); reader1->Next(), reader2->Next()) { const string key1 = reader1->GetKey(); const string key2 = reader2->GetKey(); if (!end_key.empty() && end_key < key1 && end_key < key2) { delete reader1; delete reader2; return true; } if (key1 != key2) { VLOG(1) << "FarEqual: mismatched keys \"" << key1 << "\" <> \"" << key2 << "\"."; delete reader1; delete reader2; return false; } if (!Equal(reader1->GetFst(), reader2->GetFst(), delta)) { VLOG(1) << "FarEqual: Fsts for key \"" << key1 << "\" are not equal."; delete reader1; delete reader2; return false; } } if (!reader1->Done() || !reader2->Done()) { VLOG(1) << "FarEqual: key \"" << (reader1->Done() ? reader2->GetKey() : reader1->GetKey()) << "\" missing form " << (reader2->Done() ? "first" : "second") << " archive."; delete reader1; delete reader2; return false; } delete reader1; delete reader2; return true; } } // namespace fst #endif // FST_EXTENSIONS_FAR_EQUAL_H_ <|start_filename|>third_party/openfst/src/include/fst/state-map.h<|end_filename|> // map.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to map over/transform states e.g., sort transitions // Consider using when operation does not change the number of states. #ifndef FST_LIB_STATE_MAP_H__ #define FST_LIB_STATE_MAP_H__ #include <algorithm> #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <string> #include <utility> using std::pair; using std::make_pair; #include <fst/cache.h> #include <fst/arc-map.h> #include <fst/mutable-fst.h> namespace fst { // StateMapper Interface - class determinies how states are mapped. // Useful for implementing operations that do not change the number of states. // // class StateMapper { // public: // typedef A FromArc; // typedef B ToArc; // // // Typical constructor // StateMapper(const Fst<A> &fst); // // Required copy constructor that allows updating Fst argument; // // pass only if relevant and changed. // StateMapper(const StateMapper &mapper, const Fst<A> *fst = 0); // // // Specifies initial state of result // B::StateId Start() const; // // Specifies state's final weight in result // B::Weight Final(B::StateId s) const; // // // These methods iterate through a state's arcs in result // // Specifies state to iterate over // void SetState(B::StateId s); // // End of arcs? // bool Done() const; // // Current arc // const B &Value() const; // // Advance to next arc (when !Done) // void Next(); // // // Specifies input symbol table action the mapper requires (see above). // MapSymbolsAction InputSymbolsAction() const; // // Specifies output symbol table action the mapper requires (see above). // MapSymbolsAction OutputSymbolsAction() const; // // This specifies the known properties of an Fst mapped by this // // mapper. It takes as argument the input Fst's known properties. // uint64 Properties(uint64 props) const; // }; // // We include a various state map versions below. One dimension of // variation is whether the mapping mutates its input, writes to a // new result Fst, or is an on-the-fly Fst. Another dimension is how // we pass the mapper. We allow passing the mapper by pointer // for cases that we need to change the state of the user's mapper. // We also include map versions that pass the mapper // by value or const reference when this suffices. // Maps an arc type A using a mapper function object C, passed // by pointer. This version modifies its Fst input. template<class A, class C> void StateMap(MutableFst<A> *fst, C* mapper) { typedef typename A::StateId StateId; typedef typename A::Weight Weight; if (mapper->InputSymbolsAction() == MAP_CLEAR_SYMBOLS) fst->SetInputSymbols(0); if (mapper->OutputSymbolsAction() == MAP_CLEAR_SYMBOLS) fst->SetOutputSymbols(0); if (fst->Start() == kNoStateId) return; uint64 props = fst->Properties(kFstProperties, false); fst->SetStart(mapper->Start()); for (StateId s = 0; s < fst->NumStates(); ++s) { mapper->SetState(s); fst->DeleteArcs(s); for (; !mapper->Done(); mapper->Next()) fst->AddArc(s, mapper->Value()); fst->SetFinal(s, mapper->Final(s)); } fst->SetProperties(mapper->Properties(props), kFstProperties); } // Maps an arc type A using a mapper function object C, passed // by value. This version modifies its Fst input. template<class A, class C> void StateMap(MutableFst<A> *fst, C mapper) { StateMap(fst, &mapper); } // Maps an arc type A to an arc type B using mapper function // object C, passed by pointer. This version writes the mapped // input Fst to an output MutableFst. template<class A, class B, class C> void StateMap(const Fst<A> &ifst, MutableFst<B> *ofst, C* mapper) { typedef typename A::StateId StateId; typedef typename A::Weight Weight; ofst->DeleteStates(); if (mapper->InputSymbolsAction() == MAP_COPY_SYMBOLS) ofst->SetInputSymbols(ifst.InputSymbols()); else if (mapper->InputSymbolsAction() == MAP_CLEAR_SYMBOLS) ofst->SetInputSymbols(0); if (mapper->OutputSymbolsAction() == MAP_COPY_SYMBOLS) ofst->SetOutputSymbols(ifst.OutputSymbols()); else if (mapper->OutputSymbolsAction() == MAP_CLEAR_SYMBOLS) ofst->SetOutputSymbols(0); uint64 iprops = ifst.Properties(kCopyProperties, false); if (ifst.Start() == kNoStateId) { if (iprops & kError) ofst->SetProperties(kError, kError); return; } // Add all states. if (ifst.Properties(kExpanded, false)) ofst->ReserveStates(CountStates(ifst)); for (StateIterator< Fst<A> > siter(ifst); !siter.Done(); siter.Next()) ofst->AddState(); ofst->SetStart(mapper->Start()); for (StateIterator< Fst<A> > siter(ifst); !siter.Done(); siter.Next()) { StateId s = siter.Value(); mapper->SetState(s); for (; !mapper->Done(); mapper->Next()) ofst->AddArc(s, mapper->Value()); ofst->SetFinal(s, mapper->Final(s)); } uint64 oprops = ofst->Properties(kFstProperties, false); ofst->SetProperties(mapper->Properties(iprops) | oprops, kFstProperties); } // Maps an arc type A to an arc type B using mapper function // object C, passed by value. This version writes the mapped input // Fst to an output MutableFst. template<class A, class B, class C> void StateMap(const Fst<A> &ifst, MutableFst<B> *ofst, C mapper) { StateMap(ifst, ofst, &mapper); } typedef CacheOptions StateMapFstOptions; template <class A, class B, class C> class StateMapFst; // Implementation of delayed StateMapFst. template <class A, class B, class C> class StateMapFstImpl : public CacheImpl<B> { public: using FstImpl<B>::SetType; using FstImpl<B>::SetProperties; using FstImpl<B>::SetInputSymbols; using FstImpl<B>::SetOutputSymbols; using CacheImpl<B>::PushArc; using CacheImpl<B>::HasArcs; using CacheImpl<B>::HasFinal; using CacheImpl<B>::HasStart; using CacheImpl<B>::SetArcs; using CacheImpl<B>::SetFinal; using CacheImpl<B>::SetStart; friend class StateIterator< StateMapFst<A, B, C> >; typedef B Arc; typedef typename B::Weight Weight; typedef typename B::StateId StateId; StateMapFstImpl(const Fst<A> &fst, const C &mapper, const StateMapFstOptions& opts) : CacheImpl<B>(opts), fst_(fst.Copy()), mapper_(new C(mapper, fst_)), own_mapper_(true) { Init(); } StateMapFstImpl(const Fst<A> &fst, C *mapper, const StateMapFstOptions& opts) : CacheImpl<B>(opts), fst_(fst.Copy()), mapper_(mapper), own_mapper_(false) { Init(); } StateMapFstImpl(const StateMapFstImpl<A, B, C> &impl) : CacheImpl<B>(impl), fst_(impl.fst_->Copy(true)), mapper_(new C(*impl.mapper_, fst_)), own_mapper_(true) { Init(); } ~StateMapFstImpl() { delete fst_; if (own_mapper_) delete mapper_; } StateId Start() { if (!HasStart()) SetStart(mapper_->Start()); return CacheImpl<B>::Start(); } Weight Final(StateId s) { if (!HasFinal(s)) SetFinal(s, mapper_->Final(s)); return CacheImpl<B>::Final(s); } size_t NumArcs(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<B>::NumArcs(s); } size_t NumInputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<B>::NumInputEpsilons(s); } size_t NumOutputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<B>::NumOutputEpsilons(s); } void InitStateIterator(StateIteratorData<A> *data) const { fst_->InitStateIterator(data); } void InitArcIterator(StateId s, ArcIteratorData<B> *data) { if (!HasArcs(s)) Expand(s); CacheImpl<B>::InitArcIterator(s, data); } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if ((mask & kError) && (fst_->Properties(kError, false) || (mapper_->Properties(0) & kError))) SetProperties(kError, kError); return FstImpl<Arc>::Properties(mask); } void Expand(StateId s) { // Add exiting arcs. for (mapper_->SetState(s); !mapper_->Done(); mapper_->Next()) PushArc(s, mapper_->Value()); SetArcs(s); } const Fst<A> &GetFst() const { return *fst_; } private: void Init() { SetType("statemap"); if (mapper_->InputSymbolsAction() == MAP_COPY_SYMBOLS) SetInputSymbols(fst_->InputSymbols()); else if (mapper_->InputSymbolsAction() == MAP_CLEAR_SYMBOLS) SetInputSymbols(0); if (mapper_->OutputSymbolsAction() == MAP_COPY_SYMBOLS) SetOutputSymbols(fst_->OutputSymbols()); else if (mapper_->OutputSymbolsAction() == MAP_CLEAR_SYMBOLS) SetOutputSymbols(0); uint64 props = fst_->Properties(kCopyProperties, false); SetProperties(mapper_->Properties(props)); } const Fst<A> *fst_; C* mapper_; bool own_mapper_; void operator=(const StateMapFstImpl<A, B, C> &); // disallow }; // Maps an arc type A to an arc type B using Mapper function object // C. This version is a delayed Fst. template <class A, class B, class C> class StateMapFst : public ImplToFst< StateMapFstImpl<A, B, C> > { public: friend class ArcIterator< StateMapFst<A, B, C> >; typedef B Arc; typedef typename B::Weight Weight; typedef typename B::StateId StateId; typedef DefaultCacheStore<B> Store; typedef typename Store::State State; typedef StateMapFstImpl<A, B, C> Impl; StateMapFst(const Fst<A> &fst, const C &mapper, const StateMapFstOptions& opts) : ImplToFst<Impl>(new Impl(fst, mapper, opts)) {} StateMapFst(const Fst<A> &fst, C* mapper, const StateMapFstOptions& opts) : ImplToFst<Impl>(new Impl(fst, mapper, opts)) {} StateMapFst(const Fst<A> &fst, const C &mapper) : ImplToFst<Impl>(new Impl(fst, mapper, StateMapFstOptions())) {} StateMapFst(const Fst<A> &fst, C* mapper) : ImplToFst<Impl>(new Impl(fst, mapper, StateMapFstOptions())) {} // See Fst<>::Copy() for doc. StateMapFst(const StateMapFst<A, B, C> &fst, bool safe = false) : ImplToFst<Impl>(fst, safe) {} // Get a copy of this StateMapFst. See Fst<>::Copy() for further doc. virtual StateMapFst<A, B, C> *Copy(bool safe = false) const { return new StateMapFst<A, B, C>(*this, safe); } virtual void InitStateIterator(StateIteratorData<A> *data) const { GetImpl()->InitStateIterator(data); } virtual void InitArcIterator(StateId s, ArcIteratorData<B> *data) const { GetImpl()->InitArcIterator(s, data); } protected: Impl *GetImpl() const { return ImplToFst<Impl>::GetImpl(); } private: void operator=(const StateMapFst<A, B, C> &fst); // disallow }; // Specialization for StateMapFst. template <class A, class B, class C> class ArcIterator< StateMapFst<A, B, C> > : public CacheArcIterator< StateMapFst<A, B, C> > { public: typedef typename A::StateId StateId; ArcIterator(const StateMapFst<A, B, C> &fst, StateId s) : CacheArcIterator< StateMapFst<A, B, C> >(fst.GetImpl(), s) { if (!fst.GetImpl()->HasArcs(s)) fst.GetImpl()->Expand(s); } private: DISALLOW_COPY_AND_ASSIGN(ArcIterator); }; // // Utility Mappers // // Mapper that returns its input. template <class A> class IdentityStateMapper { public: typedef A FromArc; typedef A ToArc; typedef typename A::StateId StateId; typedef typename A::Weight Weight; explicit IdentityStateMapper(const Fst<A> &fst) : fst_(fst), aiter_(0) {} // Allows updating Fst argument; pass only if changed. IdentityStateMapper(const IdentityStateMapper<A> &mapper, const Fst<A> *fst = 0) : fst_(fst ? *fst : mapper.fst_), aiter_(0) {} ~IdentityStateMapper() { delete aiter_; } StateId Start() const { return fst_.Start(); } Weight Final(StateId s) const { return fst_.Final(s); } void SetState(StateId s) { if (aiter_) delete aiter_; aiter_ = new ArcIterator< Fst<A> >(fst_, s); } bool Done() const { return aiter_->Done(); } const A &Value() const { return aiter_->Value(); } void Next() { aiter_->Next(); } MapSymbolsAction InputSymbolsAction() const { return MAP_COPY_SYMBOLS; } MapSymbolsAction OutputSymbolsAction() const { return MAP_COPY_SYMBOLS;} uint64 Properties(uint64 props) const { return props; } private: const Fst<A> &fst_; ArcIterator< Fst<A> > *aiter_; }; template <class A> class ArcSumMapper { public: typedef A FromArc; typedef A ToArc; typedef typename A::StateId StateId; typedef typename A::Weight Weight; explicit ArcSumMapper(const Fst<A> &fst) : fst_(fst), i_(0) {} // Allows updating Fst argument; pass only if changed. ArcSumMapper(const ArcSumMapper<A> &mapper, const Fst<A> *fst = 0) : fst_(fst ? *fst : mapper.fst_), i_(0) {} StateId Start() const { return fst_.Start(); } Weight Final(StateId s) const { return fst_.Final(s); } void SetState(StateId s) { i_ = 0; arcs_.clear(); arcs_.reserve(fst_.NumArcs(s)); for (ArcIterator<Fst<A> > aiter(fst_, s); !aiter.Done(); aiter.Next()) arcs_.push_back(aiter.Value()); // First sorts the exiting arcs by input label, output label // and destination state and then sums weights of arcs with // the same input label, output label, and destination state. sort(arcs_.begin(), arcs_.end(), comp_); size_t narcs = 0; for (size_t i = 0; i < arcs_.size(); ++i) { if (narcs > 0 && equal_(arcs_[i], arcs_[narcs - 1])) { arcs_[narcs - 1].weight = Plus(arcs_[narcs - 1].weight, arcs_[i].weight); } else { arcs_[narcs++] = arcs_[i]; } } arcs_.resize(narcs); } bool Done() const { return i_ >= arcs_.size(); } const A &Value() const { return arcs_[i_]; } void Next() { ++i_; } MapSymbolsAction InputSymbolsAction() const { return MAP_COPY_SYMBOLS; } MapSymbolsAction OutputSymbolsAction() const { return MAP_COPY_SYMBOLS; } uint64 Properties(uint64 props) const { return props & kArcSortProperties & kDeleteArcsProperties & kWeightInvariantProperties; } private: struct Compare { bool operator()(const A &x, const A &y) const { if (x.ilabel < y.ilabel) return true; if (x.ilabel > y.ilabel) return false; if (x.olabel < y.olabel) return true; if (x.olabel > y.olabel) return false; if (x.nextstate < y.nextstate) return true; if (x.nextstate > y.nextstate) return false; return false; } }; struct Equal { bool operator()(const A& x, const A& y) { return (x.ilabel == y.ilabel && x.olabel == y.olabel && x.nextstate == y.nextstate); } }; const Fst<A> &fst_; Compare comp_; Equal equal_; vector<A> arcs_; ssize_t i_; // current arc position void operator=(const ArcSumMapper<A> &); // disallow }; template <class A> class ArcUniqueMapper { public: typedef A FromArc; typedef A ToArc; typedef typename A::StateId StateId; typedef typename A::Weight Weight; explicit ArcUniqueMapper(const Fst<A> &fst) : fst_(fst), i_(0) {} // Allows updating Fst argument; pass only if changed. ArcUniqueMapper(const ArcUniqueMapper<A> &mapper, const Fst<A> *fst = 0) : fst_(fst ? *fst : mapper.fst_), i_(0) {} StateId Start() const { return fst_.Start(); } Weight Final(StateId s) const { return fst_.Final(s); } void SetState(StateId s) { i_ = 0; arcs_.clear(); arcs_.reserve(fst_.NumArcs(s)); for (ArcIterator<Fst<A> > aiter(fst_, s); !aiter.Done(); aiter.Next()) arcs_.push_back(aiter.Value()); // First sorts the exiting arcs by input label, output label // and destination state and then uniques identical arcs sort(arcs_.begin(), arcs_.end(), comp_); typename vector<A>::iterator unique_end = unique(arcs_.begin(), arcs_.end(), equal_); arcs_.resize(unique_end - arcs_.begin()); } bool Done() const { return i_ >= arcs_.size(); } const A &Value() const { return arcs_[i_]; } void Next() { ++i_; } MapSymbolsAction InputSymbolsAction() const { return MAP_COPY_SYMBOLS; } MapSymbolsAction OutputSymbolsAction() const { return MAP_COPY_SYMBOLS; } uint64 Properties(uint64 props) const { return props & kArcSortProperties & kDeleteArcsProperties; } private: struct Compare { bool operator()(const A &x, const A &y) const { if (x.ilabel < y.ilabel) return true; if (x.ilabel > y.ilabel) return false; if (x.olabel < y.olabel) return true; if (x.olabel > y.olabel) return false; if (x.nextstate < y.nextstate) return true; if (x.nextstate > y.nextstate) return false; return false; } }; struct Equal { bool operator()(const A &x, const A &y) const { return (x.ilabel == y.ilabel && x.olabel == y.olabel && x.nextstate == y.nextstate && x.weight == y.weight); } }; const Fst<A> &fst_; Compare comp_; Equal equal_; vector<A> arcs_; ssize_t i_; // current arc position void operator=(const ArcUniqueMapper<A> &); // disallow }; } // namespace fst #endif // FST_LIB_STATE_MAP_H__ <|start_filename|>third_party/openfst/src/extensions/far/strings.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/extensions/far/compile-strings.h> #include <iostream> #include <fstream> #include <sstream> DEFINE_string(far_field_separator, "\t", "Set of characters used as a separator between printed fields"); namespace fst { // Compute the minimal length required to // encode each line number as a decimal number int KeySize(const char *filename) { ifstream istrm(filename); istrm.seekg(0); string s; int nline = 0; while (getline(istrm, s)) ++nline; istrm.seekg(0); return nline ? ceil(log10(nline + 1)) : 1; } } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/script/register.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_SCRIPT_REGISTER_H_ #define FST_SCRIPT_REGISTER_H_ #include <string> #include <fst/generic-register.h> #include <fst/script/fst-class.h> #include <fst/script/weight-class.h> // Holds methods and classes responsible for maintaining // the register for FstClass arc types. namespace fst { namespace script { // // Registers for reading and converting various kinds of FST classes. // // This class definition is to avoid a nested class definition inside // the IORegistration struct. template<class Reader, class Creator, class Converter> struct FstClassRegEntry { Reader reader; Creator creator; Converter converter; FstClassRegEntry(Reader r, Creator cr, Converter co) : reader(r), creator(cr), converter(co) { } FstClassRegEntry() : reader(0), creator(0), converter(0) { } }; template<class Reader, class Creator, class Converter> class FstClassIORegister : public GenericRegister<string, FstClassRegEntry<Reader, Creator, Converter>, FstClassIORegister<Reader, Creator, Converter> > { public: Reader GetReader(const string &arc_type) const { return this->GetEntry(arc_type).reader; } Creator GetCreator(const string &arc_type) const { return this->GetEntry(arc_type).creator; } Converter GetConverter(const string &arc_type) const { return this->GetEntry(arc_type).converter; } protected: virtual string ConvertKeyToSoFilename( const string& key) const { string legal_type(key); ConvertToLegalCSymbol(&legal_type); return legal_type + "-arc.so"; } }; // // Struct containing everything needed to register a particular type // of FST class (e.g. a plain FstClass, or a MutableFstClass, etc) // template<class FstClassType> struct IORegistration { typedef FstClassType *(*Reader)(istream &stream, const FstReadOptions &opts); typedef FstClassImplBase *(*Creator)(); typedef FstClassImplBase *(*Converter)(const FstClass &other); typedef FstClassRegEntry<Reader, Creator, Converter> Entry; // FST class Register typedef FstClassIORegister<Reader, Creator, Converter> Register; // FST class Register-er typedef GenericRegisterer<FstClassIORegister<Reader, Creator, Converter> > Registerer; }; // // REGISTRATION MACROS // #define REGISTER_FST_CLASS(Class, Arc) \ static IORegistration<Class>::Registerer Class ## _ ## Arc ## _registerer( \ Arc::Type(), \ IORegistration<Class>::Entry(Class::Read<Arc>, \ Class::Create<Arc>, \ Class::Convert<Arc>)) #define REGISTER_FST_CLASSES(Arc) \ REGISTER_FST_CLASS(FstClass, Arc); \ REGISTER_FST_CLASS(MutableFstClass, Arc); \ REGISTER_FST_CLASS(VectorFstClass, Arc); } // namespace script } // namespace fst #endif // FST_SCRIPT_REGISTER_H_ <|start_filename|>third_party/openfst/src/include/fst/arcfilter.h<|end_filename|> // arcfilter.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Function objects to restrict which arcs are traversed in an FST. #ifndef FST_LIB_ARCFILTER_H__ #define FST_LIB_ARCFILTER_H__ #include <fst/fst.h> #include <fst/util.h> namespace fst { // True for all arcs. template <class A> class AnyArcFilter { public: bool operator()(const A &arc) const { return true; } }; // True for (input/output) epsilon arcs. template <class A> class EpsilonArcFilter { public: bool operator()(const A &arc) const { return arc.ilabel == 0 && arc.olabel == 0; } }; // True for input epsilon arcs. template <class A> class InputEpsilonArcFilter { public: bool operator()(const A &arc) const { return arc.ilabel == 0; } }; // True for output epsilon arcs. template <class A> class OutputEpsilonArcFilter { public: bool operator()(const A &arc) const { return arc.olabel == 0; } }; // True if specified labels match (don't match) when keep_match is // true (false). template <class A> class MultiLabelArcFilter { public: typedef typename A::Label Label; MultiLabelArcFilter(bool match_input = true, bool keep_match = true) : match_input_(match_input), keep_match_(keep_match) {} bool operator()(const A &arc) const { Label label = match_input_ ? arc.ilabel : arc.olabel; bool match = labels_.Find(label) != labels_.End(); return keep_match_ ? match : !match; } void AddLabel(Label label) { labels_.Insert(label); } private: CompactSet<Label, kNoLabel> labels_; bool match_input_; bool keep_match_; }; } // namespace fst #endif // FST_LIB_ARCFILTER_H__ <|start_filename|>third_party/openfst/src/include/fst/script/text-io.h<|end_filename|> // text-io.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to work with generic WeightClass // // \file // Utilities for reading and writing textual strings representing // states, labels, and weights and files specifying label-label pairs // and potentials (state-weight pairs). // #ifndef FST_SCRIPT_TEXT_IO_H__ #define FST_SCRIPT_TEXT_IO_H__ #include <string> #include <vector> using std::vector; #include <iostream> #include <fstream> #include <sstream> #include <fst/script/weight-class.h> namespace fst { namespace script { bool ReadPotentials(const string &weight_type, const string& filename, vector<WeightClass>* potential); bool WritePotentials(const string& filename, const vector<WeightClass>& potential); } // namespace script } // namespace fst #endif // FST_SCRIPT_TEXT_IO_H__ <|start_filename|>third_party/openfst/src/include/fst/icu.h<|end_filename|> // icu.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // <EMAIL> (<NAME>) // // This library implements an unrestricted Thompson/Pike UTF-8 parser and // serializer. UTF-8 is a restricted subset of this byte stream encoding. See // http://en.wikipedia.org/wiki/UTF-8 for a good description of the encoding // details. #ifndef FST_LIB_ICU_H_ #define FST_LIB_ICU_H_ #include <iostream> #include <fstream> #include <sstream> namespace fst { template <class Label> bool UTF8StringToLabels(const string &str, vector<Label> *labels) { const char *data = str.data(); size_t length = str.size(); for (int i = 0; i < length; /* no update */) { int c = data[i++] & 0xff; if ((c & 0x80) == 0) { labels->push_back(c); } else { if ((c & 0xc0) == 0x80) { LOG(ERROR) << "UTF8StringToLabels: continuation byte as lead byte"; return false; } int count = (c >= 0xc0) + (c >= 0xe0) + (c >= 0xf0) + (c >= 0xf8) + (c >= 0xfc); int code = c & ((1 << (6 - count)) - 1); while (count != 0) { if (i == length) { LOG(ERROR) << "UTF8StringToLabels: truncated utf-8 byte sequence"; return false; } char cb = data[i++]; if ((cb & 0xc0) != 0x80) { LOG(ERROR) << "UTF8StringToLabels: missing/invalid continuation byte"; return false; } code = (code << 6) | (cb & 0x3f); count--; } if (code < 0) { // This should not be able to happen. LOG(ERROR) << "UTF8StringToLabels: Invalid character found: " << c; return false; } labels->push_back(code); } } return true; } template <class Label> bool LabelsToUTF8String(const vector<Label> &labels, string *str) { ostringstream ostr; for (size_t i = 0; i < labels.size(); ++i) { int32_t code = labels[i]; if (code < 0) { LOG(ERROR) << "LabelsToUTF8String: Invalid character found: " << code; return false; } else if (code < 0x80) { ostr << static_cast<char>(code); } else if (code < 0x800) { ostr << static_cast<char>((code >> 6) | 0xc0); ostr << static_cast<char>((code & 0x3f) | 0x80); } else if (code < 0x10000) { ostr << static_cast<char>((code >> 12) | 0xe0); ostr << static_cast<char>(((code >> 6) & 0x3f) | 0x80); ostr << static_cast<char>((code & 0x3f) | 0x80); } else if (code < 0x200000) { ostr << static_cast<char>((code >> 18) | 0xf0); ostr << static_cast<char>(((code >> 12) & 0x3f) | 0x80); ostr << static_cast<char>(((code >> 6) & 0x3f) | 0x80); ostr << static_cast<char>((code & 0x3f) | 0x80); } else if (code < 0x4000000) { ostr << static_cast<char>((code >> 24) | 0xf8); ostr << static_cast<char>(((code >> 18) & 0x3f) | 0x80); ostr << static_cast<char>(((code >> 12) & 0x3f) | 0x80); ostr << static_cast<char>(((code >> 6) & 0x3f) | 0x80); ostr << static_cast<char>((code & 0x3f) | 0x80); } else { ostr << static_cast<char>((code >> 30) | 0xfc); ostr << static_cast<char>(((code >> 24) & 0x3f) | 0x80); ostr << static_cast<char>(((code >> 18) & 0x3f) | 0x80); ostr << static_cast<char>(((code >> 12) & 0x3f) | 0x80); ostr << static_cast<char>(((code >> 6) & 0x3f) | 0x80); ostr << static_cast<char>((code & 0x3f) | 0x80); } } *str = ostr.str(); return true; } } // namespace fst #endif // FST_LIB_ICU_H_ <|start_filename|>third_party/openfst/src/script/compile.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <string> #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/compile.h> namespace fst { namespace script { void CompileFst(istream &istrm, const string &source, const string &dest, const string &fst_type, const string &arc_type, const SymbolTable *isyms, const SymbolTable *osyms, const SymbolTable *ssyms, bool accep, bool ikeep, bool okeep, bool nkeep, bool allow_negative_labels) { FstCompileArgs args(istrm, source, dest, fst_type, isyms, osyms, ssyms, accep, ikeep, okeep, nkeep, allow_negative_labels); Apply<Operation<FstCompileArgs> >("CompileFst", arc_type, &args); } REGISTER_FST_OPERATION(CompileFst, StdArc, FstCompileArgs); REGISTER_FST_OPERATION(CompileFst, LogArc, FstCompileArgs); REGISTER_FST_OPERATION(CompileFst, Log64Arc, FstCompileArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/bin/fstdraw.cc<|end_filename|> // fstdraw.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Draws a binary FSTs in the Graphviz dot text format #include <fst/script/draw.h> DEFINE_bool(acceptor, false, "Input in acceptor format"); DEFINE_string(isymbols, "", "Input label symbol table"); DEFINE_string(osymbols, "", "Output label symbol table"); DEFINE_string(ssymbols, "", "State label symbol table"); DEFINE_bool(numeric, false, "Print numeric labels"); DEFINE_int32(precision, 5, "Set precision (number of char/float)"); DEFINE_bool(show_weight_one, false, "Print/draw arc weights and final weights equal to Weight::One()"); DEFINE_string(title, "", "Set figure title"); DEFINE_bool(portrait, false, "Portrait mode (def: landscape)"); DEFINE_bool(vertical, false, "Draw bottom-to-top instead of left-to-right"); DEFINE_int32(fontsize, 14, "Set fontsize"); DEFINE_double(height, 11, "Set height"); DEFINE_double(width, 8.5, "Set width"); DEFINE_double(nodesep, 0.25, "Set minimum separation between nodes (see dot documentation)"); DEFINE_double(ranksep, 0.40, "Set minimum separation between ranks (see dot documentation)"); DEFINE_bool(allow_negative_labels, false, "Allow negative labels (not recommended; may cause conflicts)"); int main(int argc, char **argv) { namespace s = fst::script; using fst::ostream; using fst::SymbolTable; string usage = "Prints out binary FSTs in dot text format.\n\n Usage: "; usage += argv[0]; usage += " [binary.fst [text.dot]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; s::FstClass *fst = s::FstClass::Read(in_name); if (!fst) return 1; ostream *ostrm = &cout; string dest = "stdout"; if (argc == 3) { dest = argv[2]; ostrm = new fst::ofstream(argv[2]); if (!*ostrm) { LOG(ERROR) << argv[0] << ": Open failed, file = " << argv[2]; return 1; } } ostrm->precision(FLAGS_precision); const SymbolTable *isyms = 0, *osyms = 0, *ssyms = 0; fst::SymbolTableTextOptions opts; opts.allow_negative = FLAGS_allow_negative_labels; if (!FLAGS_isymbols.empty() && !FLAGS_numeric) { isyms = SymbolTable::ReadText(FLAGS_isymbols, opts); if (!isyms) exit(1); } if (!FLAGS_osymbols.empty() && !FLAGS_numeric) { osyms = SymbolTable::ReadText(FLAGS_osymbols, opts); if (!osyms) exit(1); } if (!FLAGS_ssymbols.empty() && !FLAGS_numeric) { ssyms = SymbolTable::ReadText(FLAGS_ssymbols); if (!ssyms) exit(1); } if (!isyms && !FLAGS_numeric) isyms = fst->InputSymbols(); if (!osyms && !FLAGS_numeric) osyms = fst->OutputSymbols(); s::DrawFst(*fst, isyms, osyms, ssyms, FLAGS_acceptor, FLAGS_title, FLAGS_width, FLAGS_height, FLAGS_portrait, FLAGS_vertical, FLAGS_ranksep, FLAGS_nodesep, FLAGS_fontsize, FLAGS_precision, FLAGS_show_weight_one, ostrm, dest); if (ostrm != &cout) delete ostrm; return 0; } <|start_filename|>third_party/openfst/src/include/fst/product-weight.h<|end_filename|> // product-weight.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Product weight set and associated semiring operation definitions. #ifndef FST_LIB_PRODUCT_WEIGHT_H__ #define FST_LIB_PRODUCT_WEIGHT_H__ #include <stack> #include <string> #include <fst/pair-weight.h> #include <fst/weight.h> namespace fst { // Product semiring: W1 * W2 template<class W1, class W2> class ProductWeight : public PairWeight<W1, W2> { public: using PairWeight<W1, W2>::Zero; using PairWeight<W1, W2>::One; using PairWeight<W1, W2>::NoWeight; using PairWeight<W1, W2>::Quantize; using PairWeight<W1, W2>::Reverse; typedef ProductWeight<typename W1::ReverseWeight, typename W2::ReverseWeight> ReverseWeight; ProductWeight() {} ProductWeight(const PairWeight<W1, W2>& w) : PairWeight<W1, W2>(w) {} ProductWeight(W1 w1, W2 w2) : PairWeight<W1, W2>(w1, w2) {} static const ProductWeight<W1, W2> &Zero() { static const ProductWeight<W1, W2> zero(PairWeight<W1, W2>::Zero()); return zero; } static const ProductWeight<W1, W2> &One() { static const ProductWeight<W1, W2> one(PairWeight<W1, W2>::One()); return one; } static const ProductWeight<W1, W2> &NoWeight() { static const ProductWeight<W1, W2> no_weight( PairWeight<W1, W2>::NoWeight()); return no_weight; } static const string &Type() { static const string type = W1::Type() + "_X_" + W2::Type(); return type; } static uint64 Properties() { uint64 props1 = W1::Properties(); uint64 props2 = W2::Properties(); return props1 & props2 & (kLeftSemiring | kRightSemiring | kCommutative | kIdempotent); } ProductWeight<W1, W2> Quantize(float delta = kDelta) const { return PairWeight<W1, W2>::Quantize(delta); } ReverseWeight Reverse() const { return PairWeight<W1, W2>::Reverse(); } }; template <class W1, class W2> inline ProductWeight<W1, W2> Plus(const ProductWeight<W1, W2> &w, const ProductWeight<W1, W2> &v) { return ProductWeight<W1, W2>(Plus(w.Value1(), v.Value1()), Plus(w.Value2(), v.Value2())); } template <class W1, class W2> inline ProductWeight<W1, W2> Times(const ProductWeight<W1, W2> &w, const ProductWeight<W1, W2> &v) { return ProductWeight<W1, W2>(Times(w.Value1(), v.Value1()), Times(w.Value2(), v.Value2())); } template <class W1, class W2> inline ProductWeight<W1, W2> Divide(const ProductWeight<W1, W2> &w, const ProductWeight<W1, W2> &v, DivideType typ = DIVIDE_ANY) { return ProductWeight<W1, W2>(Divide(w.Value1(), v.Value1(), typ), Divide(w.Value2(), v.Value2(), typ)); } } // namespace fst #endif // FST_LIB_PRODUCT_WEIGHT_H__ <|start_filename|>third_party/openfst/src/include/fst/dfs-visit.h<|end_filename|> // dfs-visit.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Depth-first search visitation. See visit.h for more general // search queue disciplines. #ifndef FST_LIB_DFS_VISIT_H__ #define FST_LIB_DFS_VISIT_H__ #include <stack> #include <vector> using std::vector; #include <fst/arcfilter.h> #include <fst/fst.h> namespace fst { // Visitor Interface - class determines actions taken during a Dfs. // If any of the boolean member functions return false, the DFS is // aborted by first calling FinishState() on all currently grey states // and then calling FinishVisit(). // // Note this is similar to the more general visitor interface in visit.h // except that FinishState returns additional information appropriate only for // a DFS and some methods names here are better suited to a DFS. // // template <class Arc> // class Visitor { // public: // typedef typename Arc::StateId StateId; // // Visitor(T *return_data); // // Invoked before DFS visit // void InitVisit(const Fst<Arc> &fst); // // Invoked when state discovered (2nd arg is DFS tree root) // bool InitState(StateId s, StateId root); // // Invoked when tree arc examined (to white/undiscovered state) // bool TreeArc(StateId s, const Arc &a); // // Invoked when back arc examined (to grey/unfinished state) // bool BackArc(StateId s, const Arc &a); // // Invoked when forward or cross arc examined (to black/finished state) // bool ForwardOrCrossArc(StateId s, const Arc &a); // // Invoked when state finished (PARENT is kNoStateID and ARC == NULL // // when S is tree root) // void FinishState(StateId s, StateId parent, const Arc *parent_arc); // // Invoked after DFS visit // void FinishVisit(); // }; // An Fst state's DFS status const int kDfsWhite = 0; // Undiscovered const int kDfsGrey = 1; // Discovered & unfinished const int kDfsBlack = 2; // Finished // An Fst state's DFS stack state template <class Arc> struct DfsState { typedef typename Arc::StateId StateId; DfsState(const Fst<Arc> &fst, StateId s): state_id(s), arc_iter(fst, s) {} void *operator new(size_t size, MemoryPool< DfsState<Arc> > *pool) { return pool->Allocate(); } static void Destroy(DfsState<Arc> *dfs_state, MemoryPool< DfsState<Arc> > *pool) { if (dfs_state) { dfs_state->~DfsState<Arc>(); pool->Free(dfs_state); } } StateId state_id; // Fst state ... ArcIterator< Fst<Arc> > arc_iter; // and its corresponding arcs }; // Performs depth-first visitation. Visitor class argument determines // actions and contains any return data. ArcFilter determines arcs // that are considered. If 'access_only' is true, performs visitation // only to states accessible from the initial state. // // Note this is similar to Visit() in visit.h called with a LIFO // queue except this version has a Visitor class specialized and // augmented for a DFS. template <class Arc, class V, class ArcFilter> void DfsVisit(const Fst<Arc> &fst, V *visitor, ArcFilter filter, bool access_only = false) { typedef typename Arc::StateId StateId; visitor->InitVisit(fst); StateId start = fst.Start(); if (start == kNoStateId) { visitor->FinishVisit(); return; } vector<char> state_color; // Fst state DFS status stack<DfsState<Arc> *> state_stack; // DFS execution stack MemoryPool< DfsState<Arc> > state_pool; // Pool for DFSStates StateId nstates = start + 1; // # of known states in general case bool expanded = false; if (fst.Properties(kExpanded, false)) { // tests if expanded case, then nstates = CountStates(fst); // uses ExpandedFst::NumStates(). expanded = true; } state_color.resize(nstates, kDfsWhite); StateIterator< Fst<Arc> > siter(fst); // Continue DFS while true bool dfs = true; // Iterate over trees in DFS forest. for (StateId root = start; dfs && root < nstates;) { state_color[root] = kDfsGrey; state_stack.push(new(&state_pool) DfsState<Arc>(fst, root)); dfs = visitor->InitState(root, root); while (!state_stack.empty()) { DfsState<Arc> *dfs_state = state_stack.top(); StateId s = dfs_state->state_id; if (s >= state_color.size()) { nstates = s + 1; state_color.resize(nstates, kDfsWhite); } ArcIterator< Fst<Arc> > &aiter = dfs_state->arc_iter; if (!dfs || aiter.Done()) { state_color[s] = kDfsBlack; DfsState<Arc>::Destroy(dfs_state, &state_pool); state_stack.pop(); if (!state_stack.empty()) { DfsState<Arc> *parent_state = state_stack.top(); StateId p = parent_state->state_id; ArcIterator< Fst<Arc> > &piter = parent_state->arc_iter; visitor->FinishState(s, p, &piter.Value()); piter.Next(); } else { visitor->FinishState(s, kNoStateId, 0); } continue; } const Arc &arc = aiter.Value(); if (arc.nextstate >= state_color.size()) { nstates = arc.nextstate + 1; state_color.resize(nstates, kDfsWhite); } if (!filter(arc)) { aiter.Next(); continue; } int next_color = state_color[arc.nextstate]; switch (next_color) { default: case kDfsWhite: dfs = visitor->TreeArc(s, arc); if (!dfs) break; state_color[arc.nextstate] = kDfsGrey; state_stack.push(new(&state_pool) DfsState<Arc>(fst, arc.nextstate)); dfs = visitor->InitState(arc.nextstate, root); break; case kDfsGrey: dfs = visitor->BackArc(s, arc); aiter.Next(); break; case kDfsBlack: dfs = visitor->ForwardOrCrossArc(s, arc); aiter.Next(); break; } } if (access_only) break; // Find next tree root for (root = root == start ? 0 : root + 1; root < nstates && state_color[root] != kDfsWhite; ++root) { } // Check for a state beyond the largest known state if (!expanded && root == nstates) { for (; !siter.Done(); siter.Next()) { if (siter.Value() == nstates) { ++nstates; state_color.push_back(kDfsWhite); break; } } } } visitor->FinishVisit(); } template <class Arc, class V> void DfsVisit(const Fst<Arc> &fst, V *visitor) { DfsVisit(fst, visitor, AnyArcFilter<Arc>()); } } // namespace fst #endif // FST_LIB_DFS_VISIT_H__ <|start_filename|>third_party/openfst/src/bin/fstconcat.cc<|end_filename|> // fstconcat.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Concatenates two FSTs. // #include <string> #include <fst/script/concat.h> int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::MutableFstClass; string usage = "Concatenates two FSTs.\n\n Usage: "; usage += argv[0]; usage += " in1.fst in2.fst [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 3 || argc > 4) { ShowUsage(); return 1; } string in1_name = strcmp(argv[1], "-") == 0 ? "" : argv[1]; string in2_name = strcmp(argv[2], "-") == 0 ? "" : argv[2]; string out_fname = argc > 3 ? argv[3] : ""; if (in1_name.empty() && in2_name.empty()) { LOG(ERROR) << argv[0] << ": Can't take both inputs from standard input."; return 1; } MutableFstClass *fst1 = MutableFstClass::Read(in1_name, true); if (!fst1) return 1; FstClass *fst2 = FstClass::Read(in2_name); if (!fst2) return 1; s::Concat(fst1, *fst2); fst1->Write(out_fname); return 0; } <|start_filename|>third_party/openfst/src/include/fst/replace.h<|end_filename|> // replace.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Functions and classes for the recursive replacement of Fsts. // #ifndef FST_LIB_REPLACE_H__ #define FST_LIB_REPLACE_H__ #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <set> #include <string> #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/cache.h> #include <fst/expanded-fst.h> #include <fst/fst.h> #include <fst/matcher.h> #include <fst/replace-util.h> #include <fst/state-table.h> #include <fst/test-properties.h> namespace fst { // // REPLACE STATE TUPLES AND TABLES // // The replace state table has the form // // template <class A, class P> // class ReplaceStateTable { // public: // typedef A Arc; // typedef P PrefixId; // typedef typename A::StateId StateId; // typedef ReplaceStateTuple<StateId, PrefixId> StateTuple; // typedef typename A::Label Label; // typedef ReplaceStackPrefix<Label, StateId> StackPrefix; // // // Required constuctor // ReplaceStateTable(const vector<pair<Label, const Fst<A>*> > &fst_tuples, // Label root); // // // Required copy constructor that does not copy state // ReplaceStateTable(const ReplaceStateTable<A,P> &table); // // // Lookup state ID by tuple. If it doesn't exist, then add it. // StateId FindState(const StateTuple &tuple); // // // Lookup state tuple by ID. // const StateTuple &Tuple(StateId id) const; // // // Lookup prefix ID by stack prefix. If it doesn't exist, then add it. // PrefixId FindPrefixId(const StackPrefix &stack_prefix); // // // Look stack prefix by ID. // const StackPrefix &GetStackPrefix(PrefixId id) const; // }; // // Replace State Tuples // // \struct ReplaceStateTuple // \brief Tuple of information that uniquely defines a state in replace template <class S, class P> struct ReplaceStateTuple { typedef S StateId; typedef P PrefixId; ReplaceStateTuple() : prefix_id(-1), fst_id(kNoStateId), fst_state(kNoStateId) {} ReplaceStateTuple(PrefixId p, StateId f, StateId s) : prefix_id(p), fst_id(f), fst_state(s) {} PrefixId prefix_id; // index in prefix table StateId fst_id; // current fst being walked StateId fst_state; // current state in fst being walked, not to be // confused with the state_id of the combined fst }; // Equality of replace state tuples. template <class S, class P> inline bool operator==(const ReplaceStateTuple<S, P>& x, const ReplaceStateTuple<S, P>& y) { return x.prefix_id == y.prefix_id && x.fst_id == y.fst_id && x.fst_state == y.fst_state; } // \class ReplaceRootSelector // Functor returning true for tuples corresponding to states in the root FST template <class S, class P> class ReplaceRootSelector { public: bool operator()(const ReplaceStateTuple<S, P> &tuple) const { return tuple.prefix_id == 0; } }; // \class ReplaceFingerprint // Fingerprint for general replace state tuples. template <class S, class P> class ReplaceFingerprint { public: explicit ReplaceFingerprint(const vector<uint64> *size_array) : cumulative_size_array_(size_array) {} uint64 operator()(const ReplaceStateTuple<S, P> &tuple) const { return tuple.prefix_id * (cumulative_size_array_->back()) + cumulative_size_array_->at(tuple.fst_id - 1) + tuple.fst_state; } private: const vector<uint64> *cumulative_size_array_; }; // \class ReplaceFstStateFingerprint // Useful when the fst_state uniquely define the tuple. template <class S, class P> class ReplaceFstStateFingerprint { public: uint64 operator()(const ReplaceStateTuple<S, P>& tuple) const { return tuple.fst_state; } }; // \class ReplaceHash // A generic hash function for replace state tuples. template <typename S, typename P> class ReplaceHash { public: size_t operator()(const ReplaceStateTuple<S, P>& t) const { return t.prefix_id + t.fst_id * kPrime0 + t.fst_state * kPrime1; } private: static const size_t kPrime0; static const size_t kPrime1; }; template <typename S, typename P> const size_t ReplaceHash<S, P>::kPrime0 = 7853; template <typename S, typename P> const size_t ReplaceHash<S, P>::kPrime1 = 7867; // // Replace Stack Prefix // // \class ReplaceStackPrefix // \brief Container for stack prefix. template <class L, class S> class ReplaceStackPrefix { public: typedef L Label; typedef S StateId; // \class PrefixTuple // \brief Tuple of fst_id and destination state (entry in stack prefix) struct PrefixTuple { PrefixTuple(Label f, StateId s) : fst_id(f), nextstate(s) {} PrefixTuple() : fst_id(kNoLabel), nextstate(kNoStateId) {} Label fst_id; StateId nextstate; }; ReplaceStackPrefix() {} // copy constructor ReplaceStackPrefix(const ReplaceStackPrefix& x) : prefix_(x.prefix_) { } void Push(StateId fst_id, StateId nextstate) { prefix_.push_back(PrefixTuple(fst_id, nextstate)); } void Pop() { prefix_.pop_back(); } const PrefixTuple& Top() const { return prefix_[prefix_.size()-1]; } size_t Depth() const { return prefix_.size(); } public: vector<PrefixTuple> prefix_; }; // Equality stack prefix classes template <class L, class S> inline bool operator==(const ReplaceStackPrefix<L, S>& x, const ReplaceStackPrefix<L, S>& y) { if (x.prefix_.size() != y.prefix_.size()) return false; for (size_t i = 0; i < x.prefix_.size(); ++i) { if (x.prefix_[i].fst_id != y.prefix_[i].fst_id || x.prefix_[i].nextstate != y.prefix_[i].nextstate) return false; } return true; } // // \class ReplaceStackPrefixHash // \brief Hash function for stack prefix to prefix id template <class L, class S> class ReplaceStackPrefixHash { public: size_t operator()(const ReplaceStackPrefix<L, S>& x) const { size_t sum = 0; for (size_t i = 0; i < x.prefix_.size(); ++i) { sum += x.prefix_[i].fst_id + x.prefix_[i].nextstate*kPrime0; } return sum; } private: static const size_t kPrime0; }; template <class L, class S> const size_t ReplaceStackPrefixHash<L, S>::kPrime0 = 7853; // // Replace State Tables // // \class VectorHashReplaceStateTable // A two-level state table for replace. // Warning: calls CountStates to compute the number of states of each // component Fst. template <class A, class P = ssize_t> class VectorHashReplaceStateTable { public: typedef A Arc; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef P PrefixId; typedef ReplaceStateTuple<StateId, P> StateTuple; typedef VectorHashStateTable<ReplaceStateTuple<StateId, P>, ReplaceRootSelector<StateId, P>, ReplaceFstStateFingerprint<StateId, P>, ReplaceFingerprint<StateId, P> > StateTable; typedef ReplaceStackPrefix<Label, StateId> StackPrefix; typedef CompactHashBiTable< PrefixId, StackPrefix, ReplaceStackPrefixHash<Label, StateId> > StackPrefixTable; VectorHashReplaceStateTable( const vector<pair<Label, const Fst<A>*> > &fst_tuples, Label root) : root_size_(0) { cumulative_size_array_.push_back(0); for (size_t i = 0; i < fst_tuples.size(); ++i) { if (fst_tuples[i].first == root) { root_size_ = CountStates(*(fst_tuples[i].second)); cumulative_size_array_.push_back(cumulative_size_array_.back()); } else { cumulative_size_array_.push_back(cumulative_size_array_.back() + CountStates(*(fst_tuples[i].second))); } } state_table_ = new StateTable( new ReplaceRootSelector<StateId, P>, new ReplaceFstStateFingerprint<StateId, P>, new ReplaceFingerprint<StateId, P>(&cumulative_size_array_), root_size_, root_size_ + cumulative_size_array_.back()); } VectorHashReplaceStateTable(const VectorHashReplaceStateTable<A, P> &table) : root_size_(table.root_size_), cumulative_size_array_(table.cumulative_size_array_), prefix_table_(table.prefix_table_) { state_table_ = new StateTable( new ReplaceRootSelector<StateId, P>, new ReplaceFstStateFingerprint<StateId, P>, new ReplaceFingerprint<StateId, P>(&cumulative_size_array_), root_size_, root_size_ + cumulative_size_array_.back()); } ~VectorHashReplaceStateTable() { delete state_table_; } StateId FindState(const StateTuple &tuple) { return state_table_->FindState(tuple); } const StateTuple &Tuple(StateId id) const { return state_table_->Tuple(id); } PrefixId FindPrefixId(const StackPrefix &prefix) { return prefix_table_.FindId(prefix); } const StackPrefix &GetStackPrefix(PrefixId id) const { return prefix_table_.FindEntry(id); } private: StateId root_size_; vector<uint64> cumulative_size_array_; StateTable *state_table_; StackPrefixTable prefix_table_; }; // \class DefaultReplaceStateTable // Default replace state table template <class A, class P = ssize_t> class DefaultReplaceStateTable : public CompactHashStateTable< ReplaceStateTuple<typename A::StateId, P>, ReplaceHash<typename A::StateId, P> > { public: typedef A Arc; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef P PrefixId; typedef ReplaceStateTuple<StateId, P> StateTuple; typedef CompactHashStateTable<StateTuple, ReplaceHash<StateId, PrefixId> > StateTable; typedef ReplaceStackPrefix<Label, StateId> StackPrefix; typedef CompactHashBiTable< PrefixId, StackPrefix, ReplaceStackPrefixHash<Label, StateId> > StackPrefixTable; using StateTable::FindState; using StateTable::Tuple; DefaultReplaceStateTable( const vector<pair<Label, const Fst<A>*> > &fst_tuples, Label root) {} DefaultReplaceStateTable(const DefaultReplaceStateTable<A, P> &table) : StateTable(), prefix_table_(table.prefix_table_) {} PrefixId FindPrefixId(const StackPrefix &prefix) { return prefix_table_.FindId(prefix); } const StackPrefix &GetStackPrefix(PrefixId id) const { return prefix_table_.FindEntry(id); } private: StackPrefixTable prefix_table_; }; // // REPLACE FST CLASS // // By default ReplaceFst will copy the input label of the 'replace arc'. // The call_label_type and return_label_type options specify how to manage // the labels of the call arc and the return arc of the replace FST template <class A, class T = DefaultReplaceStateTable<A>, class C = DefaultCacheStore<A> > struct ReplaceFstOptions : CacheImplOptions<C> { int64 root; // root rule for expansion ReplaceLabelType call_label_type; // how to label call arc ReplaceLabelType return_label_type; // how to label return arc int64 call_output_label; // specifies output label to put on call arc // if kNoLabel, use existing label on call arc // if 0, epsilon // otherwise, use this field as the output label int64 return_label; // specifies label to put on return arc bool take_ownership; // take ownership of input Fst(s) T* state_table; ReplaceFstOptions(const CacheImplOptions<C> &opts, int64 r) : CacheImplOptions<C>(opts), root(r), call_label_type(REPLACE_LABEL_INPUT), return_label_type(REPLACE_LABEL_NEITHER), call_output_label(kNoLabel), return_label(0), take_ownership(false), state_table(0) {} ReplaceFstOptions(const CacheOptions &opts, int64 r) : CacheImplOptions<C>(opts), root(r), call_label_type(REPLACE_LABEL_INPUT), return_label_type(REPLACE_LABEL_NEITHER), call_output_label(kNoLabel), return_label(0), take_ownership(false), state_table(0) {} explicit ReplaceFstOptions(const fst::ReplaceUtilOptions<A> &opts) : root(opts.root), call_label_type(opts.call_label_type), return_label_type(opts.return_label_type), call_output_label(kNoLabel), return_label(opts.return_label), take_ownership(false), state_table(0) {} explicit ReplaceFstOptions(int64 r) : root(r), call_label_type(REPLACE_LABEL_INPUT), return_label_type(REPLACE_LABEL_NEITHER), call_output_label(kNoLabel), return_label(0), take_ownership(false), state_table(0) {} ReplaceFstOptions(int64 r, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, int64 return_label) : root(r), call_label_type(call_label_type), return_label_type(return_label_type), call_output_label(kNoLabel), return_label(return_label), take_ownership(false), state_table(0) {} ReplaceFstOptions(int64 r, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, int64 call_output_label, int64 return_label) : root(r), call_label_type(call_label_type), return_label_type(return_label_type), call_output_label(call_output_label), return_label(return_label), take_ownership(false), state_table(0) {} ReplaceFstOptions(int64 r, bool epsilon_replace_arc) // b/w compatibility : root(r), call_label_type((epsilon_replace_arc) ? REPLACE_LABEL_NEITHER : REPLACE_LABEL_INPUT), return_label_type(REPLACE_LABEL_NEITHER), call_output_label((epsilon_replace_arc) ? 0 : kNoLabel), return_label(0), take_ownership(false), state_table(0) {} ReplaceFstOptions() : root(kNoLabel), call_label_type(REPLACE_LABEL_INPUT), return_label_type(REPLACE_LABEL_NEITHER), call_output_label(kNoLabel), return_label(0), take_ownership(false), state_table(0) {} }; // Forward declaration template <class A, class T, class C> class ReplaceFstMatcher; // \class ReplaceFstImpl // \brief Implementation class for replace class Fst // // The replace implementation class supports a dynamic // expansion of a recursive transition network represented as Fst // with dynamic replacable arcs. // template <class A, class T, class C> class ReplaceFstImpl : public CacheBaseImpl<typename C::State, C> { friend class ReplaceFstMatcher<A, T, C>; public: typedef A Arc; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef typename C::State State; typedef CacheBaseImpl<State, C> CImpl; typedef unordered_map<Label, Label> NonTerminalHash; typedef T StateTable; typedef typename T::PrefixId PrefixId; typedef ReplaceStateTuple<StateId, PrefixId> StateTuple; typedef ReplaceStackPrefix<Label, StateId> StackPrefix; using FstImpl<A>::SetType; using FstImpl<A>::SetProperties; using FstImpl<A>::WriteHeader; using FstImpl<A>::SetInputSymbols; using FstImpl<A>::SetOutputSymbols; using FstImpl<A>::InputSymbols; using FstImpl<A>::OutputSymbols; using CImpl::PushArc; using CImpl::HasArcs; using CImpl::HasFinal; using CImpl::HasStart; using CImpl::SetArcs; using CImpl::SetFinal; using CImpl::SetStart; // constructor for replace class implementation. // \param fst_tuples array of label/fst tuples, one for each non-terminal ReplaceFstImpl(const vector< pair<Label, const Fst<A>* > >& fst_tuples, const ReplaceFstOptions<A, T, C> &opts) : CImpl(opts), call_label_type_(opts.call_label_type), return_label_type_(opts.return_label_type), call_output_label_(opts.call_output_label), return_label_(opts.return_label), state_table_(opts.state_table ? opts.state_table : new StateTable(fst_tuples, opts.root)) { SetType("replace"); // if the label is epsilon, then all REPLACE_LABEL_* options equivalent. // Set the label_type to NEITHER for ease of setting properties later if (call_output_label_ == 0) call_label_type_ = REPLACE_LABEL_NEITHER; if (return_label_ == 0) return_label_type_ = REPLACE_LABEL_NEITHER; if (fst_tuples.size() > 0) { SetInputSymbols(fst_tuples[0].second->InputSymbols()); SetOutputSymbols(fst_tuples[0].second->OutputSymbols()); } bool all_negative = true; // all nonterminals are negative? bool dense_range = true; // all nonterminals are positive // and form a dense range containing 1? for (size_t i = 0; i < fst_tuples.size(); ++i) { Label nonterminal = fst_tuples[i].first; if (nonterminal >= 0) all_negative = false; if (nonterminal > fst_tuples.size() || nonterminal <= 0) dense_range = false; } vector<uint64> inprops; bool all_ilabel_sorted = true; bool all_olabel_sorted = true; bool all_non_empty = true; fst_array_.push_back(0); for (size_t i = 0; i < fst_tuples.size(); ++i) { Label label = fst_tuples[i].first; const Fst<A> *fst = fst_tuples[i].second; nonterminal_hash_[label] = fst_array_.size(); nonterminal_set_.insert(label); fst_array_.push_back(opts.take_ownership ? fst : fst->Copy()); if (fst->Start() == kNoStateId) all_non_empty = false; if (!fst->Properties(kILabelSorted, false)) all_ilabel_sorted = false; if (!fst->Properties(kOLabelSorted, false)) all_olabel_sorted = false; inprops.push_back(fst->Properties(kCopyProperties, false)); if (i) { if (!CompatSymbols(InputSymbols(), fst->InputSymbols())) { FSTERROR() << "ReplaceFstImpl: input symbols of Fst " << i << " does not match input symbols of base Fst (0'th fst)"; SetProperties(kError, kError); } if (!CompatSymbols(OutputSymbols(), fst->OutputSymbols())) { FSTERROR() << "ReplaceFstImpl: output symbols of Fst " << i << " does not match output symbols of base Fst " << "(0'th fst)"; SetProperties(kError, kError); } } } Label nonterminal = nonterminal_hash_[opts.root]; if ((nonterminal == 0) && (fst_array_.size() > 1)) { FSTERROR() << "ReplaceFstImpl: no Fst corresponding to root label '" << opts.root << "' in the input tuple vector"; SetProperties(kError, kError); } root_ = (nonterminal > 0) ? nonterminal : 1; SetProperties(ReplaceProperties(inprops, root_ - 1, EpsilonOnInput(call_label_type_), EpsilonOnInput(return_label_type_), ReplaceTransducer(), all_non_empty)); // We assume that all terminals are positive. The resulting // ReplaceFst is known to be kILabelSorted when: (1) all sub-FSTs are // kILabelSorted, (2) the input label of the return arc is epsilon, // and (3) one of the 3 following conditions is satisfied: // 1. the input label of the call arc is not epsilon // 2. all non-terminals are negative, or // 3. all non-terninals are positive and form a dense range containing 1. if (all_ilabel_sorted && EpsilonOnInput(return_label_type_) && (!EpsilonOnInput(call_label_type_) || all_negative || dense_range)) { SetProperties(kILabelSorted, kILabelSorted); } // Similarly, the resulting ReplaceFst is known to be // kOLabelSorted when: (1) all sub-FSTs are kOLabelSorted, (2) the output // label of the return arc is epsilon, and (3) one of the 3 following // conditions is satisfied: // 1. the output label of the call arc is not epsilon // 2. all non-terminals are negative, or // 3. all non-terninals are positive and form a dense range containing 1. if (all_olabel_sorted && EpsilonOnOutput(return_label_type_) && (!EpsilonOnOutput(call_label_type_) || all_negative || dense_range)) SetProperties(kOLabelSorted, kOLabelSorted); // Enable optional caching as long as sorted and all non empty. if (Properties(kILabelSorted | kOLabelSorted) && all_non_empty) always_cache_ = false; else always_cache_ = true; VLOG(2) << "ReplaceFstImpl::ReplaceFstImpl: always_cache = " << (always_cache_ ? "true" : "false"); } ReplaceFstImpl(const ReplaceFstImpl& impl) : CImpl(impl), call_label_type_(impl.call_label_type_), return_label_type_(impl.return_label_type_), call_output_label_(impl.call_output_label_), return_label_(impl.return_label_), always_cache_(impl.always_cache_), state_table_(new StateTable(*(impl.state_table_))), nonterminal_set_(impl.nonterminal_set_), nonterminal_hash_(impl.nonterminal_hash_), root_(impl.root_) { SetType("replace"); SetProperties(impl.Properties(), kCopyProperties); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); fst_array_.reserve(impl.fst_array_.size()); fst_array_.push_back(0); for (size_t i = 1; i < impl.fst_array_.size(); ++i) { fst_array_.push_back(impl.fst_array_[i]->Copy(true)); } } ~ReplaceFstImpl() { delete state_table_; for (size_t i = 1; i < fst_array_.size(); ++i) { delete fst_array_[i]; } } // Computes the dependency graph of the replace class and returns // true if the dependencies are cyclic. Cyclic dependencies will result // in an un-expandable replace fst. bool CyclicDependencies() const { ReplaceUtil<A> replace_util(fst_array_, nonterminal_hash_, fst::ReplaceUtilOptions<A>(root_)); return replace_util.CyclicDependencies(); } // Returns or computes start state of replace fst. StateId Start() { if (!HasStart()) { if (fst_array_.size() == 1) { // no fsts defined for replace SetStart(kNoStateId); return kNoStateId; } else { const Fst<A>* fst = fst_array_[root_]; StateId fst_start = fst->Start(); if (fst_start == kNoStateId) // root Fst is empty return kNoStateId; PrefixId prefix = GetPrefixId(StackPrefix()); StateId start = state_table_->FindState( StateTuple(prefix, root_, fst_start)); SetStart(start); return start; } } else { return CImpl::Start(); } } // Returns final weight of state (Weight::Zero() means state is not final). Weight Final(StateId s) { if (HasFinal(s)) { return CImpl::Final(s); } else { const StateTuple& tuple = state_table_->Tuple(s); Weight final = Weight::Zero(); if (tuple.prefix_id == 0) { const Fst<A>* fst = fst_array_[tuple.fst_id]; StateId fst_state = tuple.fst_state; final = fst->Final(fst_state); } if (always_cache_ || HasArcs(s)) SetFinal(s, final); return final; } } size_t NumArcs(StateId s) { if (HasArcs(s)) { // If state cached, use the cached value. return CImpl::NumArcs(s); } else if (always_cache_) { // If always caching, expand and cache state. Expand(s); return CImpl::NumArcs(s); } else { // Otherwise compute the number of arcs without expanding. StateTuple tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) return 0; const Fst<A>* fst = fst_array_[tuple.fst_id]; size_t num_arcs = fst->NumArcs(tuple.fst_state); if (ComputeFinalArc(tuple, 0)) num_arcs++; return num_arcs; } } // Returns whether a given label is a non terminal bool IsNonTerminal(Label l) const { if (l < *nonterminal_set_.begin() || l > *nonterminal_set_.rbegin()) return false; // TODO(allauzen): be smarter and take advantage of // all_dense or all_negative. // Use also in ComputeArc, this would require changes to replace // so that recursing into an empty fst lead to a non co-accessible // state instead of deleting the arc as done currently. // Current use correct, since i/olabel sorted iff all_non_empty. typename NonTerminalHash::const_iterator it = nonterminal_hash_.find(l); return it != nonterminal_hash_.end(); } size_t NumInputEpsilons(StateId s) { if (HasArcs(s)) { // If state cached, use the cached value. return CImpl::NumInputEpsilons(s); } else if (always_cache_ || !Properties(kILabelSorted)) { // If always caching or if the number of input epsilons is too expensive // to compute without caching (i.e. not ilabel sorted), // then expand and cache state. Expand(s); return CImpl::NumInputEpsilons(s); } else { // Otherwise, compute the number of input epsilons without caching. StateTuple tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) return 0; const Fst<A>* fst = fst_array_[tuple.fst_id]; size_t num = 0; if (!EpsilonOnInput(call_label_type_)) { // If EpsilonOnInput(c) is false, all input epsilon arcs // are also input epsilons arcs in the underlying machine. num = fst->NumInputEpsilons(tuple.fst_state); } else { // Otherwise, one need to consider that all non-terminal arcs // in the underlying machine also become input epsilon arc. ArcIterator<Fst<A> > aiter(*fst, tuple.fst_state); for (; !aiter.Done() && ((aiter.Value().ilabel == 0) || IsNonTerminal(aiter.Value().olabel)); aiter.Next()) ++num; } if (EpsilonOnInput(return_label_type_) && ComputeFinalArc(tuple, 0)) num++; return num; } } size_t NumOutputEpsilons(StateId s) { if (HasArcs(s)) { // If state cached, use the cached value. return CImpl::NumOutputEpsilons(s); } else if (always_cache_ || !Properties(kOLabelSorted)) { // If always caching or if the number of output epsilons is too expensive // to compute without caching (i.e. not olabel sorted), // then expand and cache state. Expand(s); return CImpl::NumOutputEpsilons(s); } else { // Otherwise, compute the number of output epsilons without caching. StateTuple tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) return 0; const Fst<A>* fst = fst_array_[tuple.fst_id]; size_t num = 0; if (!EpsilonOnOutput(call_label_type_)) { // If EpsilonOnOutput(c) is false, all output epsilon arcs // are also output epsilons arcs in the underlying machine. num = fst->NumOutputEpsilons(tuple.fst_state); } else { // Otherwise, one need to consider that all non-terminal arcs // in the underlying machine also become output epsilon arc. ArcIterator<Fst<A> > aiter(*fst, tuple.fst_state); for (; !aiter.Done() && ((aiter.Value().olabel == 0) || IsNonTerminal(aiter.Value().olabel)); aiter.Next()) ++num; } if (EpsilonOnOutput(return_label_type_) && ComputeFinalArc(tuple, 0)) num++; return num; } } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if (mask & kError) { for (size_t i = 1; i < fst_array_.size(); ++i) { if (fst_array_[i]->Properties(kError, false)) SetProperties(kError, kError); } } return FstImpl<Arc>::Properties(mask); } // return the base arc iterator, if arcs have not been computed yet, // extend/recurse for new arcs. void InitArcIterator(StateId s, ArcIteratorData<A> *data) { if (!HasArcs(s)) Expand(s); CImpl::InitArcIterator(s, data); // TODO(allauzen): Set behaviour of generic iterator // Warning: ArcIterator<ReplaceFst<A> >::InitCache() // relies on current behaviour. } // Extend current state (walk arcs one level deep) void Expand(StateId s) { StateTuple tuple = state_table_->Tuple(s); // If local fst is empty if (tuple.fst_state == kNoStateId) { SetArcs(s); return; } ArcIterator< Fst<A> > aiter( *(fst_array_[tuple.fst_id]), tuple.fst_state); Arc arc; // Create a final arc when needed if (ComputeFinalArc(tuple, &arc)) PushArc(s, arc); // Expand all arcs leaving the state for (; !aiter.Done(); aiter.Next()) { if (ComputeArc(tuple, aiter.Value(), &arc)) PushArc(s, arc); } SetArcs(s); } void Expand(StateId s, const StateTuple &tuple, const ArcIteratorData<A> &data) { // If local fst is empty if (tuple.fst_state == kNoStateId) { SetArcs(s); return; } ArcIterator< Fst<A> > aiter(data); Arc arc; // Create a final arc when needed if (ComputeFinalArc(tuple, &arc)) AddArc(s, arc); // Expand all arcs leaving the state for (; !aiter.Done(); aiter.Next()) { if (ComputeArc(tuple, aiter.Value(), &arc)) AddArc(s, arc); } SetArcs(s); } // If arcp == 0, only returns if a final arc is required, does not // actually compute it. bool ComputeFinalArc(const StateTuple &tuple, A* arcp, uint32 flags = kArcValueFlags) { const Fst<A>* fst = fst_array_[tuple.fst_id]; StateId fst_state = tuple.fst_state; if (fst_state == kNoStateId) return false; // if state is final, pop up stack if (fst->Final(fst_state) != Weight::Zero() && tuple.prefix_id) { if (arcp) { arcp->ilabel = (EpsilonOnInput(return_label_type_)) ? 0 : return_label_; arcp->olabel = (EpsilonOnOutput(return_label_type_)) ? 0 : return_label_; if (flags & kArcNextStateValue) { const StackPrefix& stack = state_table_->GetStackPrefix( tuple.prefix_id); PrefixId prefix_id = PopPrefix(stack); const typename StackPrefix::PrefixTuple& top = stack.Top(); arcp->nextstate = state_table_->FindState( StateTuple(prefix_id, top.fst_id, top.nextstate)); } if (flags & kArcWeightValue) arcp->weight = fst->Final(fst_state); } return true; } else { return false; } } // Compute the arc in the replace fst corresponding to a given // in the underlying machine. Returns false if the underlying arc // corresponds to no arc in the replace. bool ComputeArc(const StateTuple &tuple, const A &arc, A* arcp, uint32 flags = kArcValueFlags) { if (!EpsilonOnInput(call_label_type_) && (flags == (flags & (kArcILabelValue | kArcWeightValue)))) { *arcp = arc; return true; } if (arc.olabel == 0 || arc.olabel < *nonterminal_set_.begin() || arc.olabel > *nonterminal_set_.rbegin()) { // expand local fst StateId nextstate = flags & kArcNextStateValue ? state_table_->FindState( StateTuple(tuple.prefix_id, tuple.fst_id, arc.nextstate)) : kNoStateId; *arcp = A(arc.ilabel, arc.olabel, arc.weight, nextstate); } else { // check for non terminal typename NonTerminalHash::const_iterator it = nonterminal_hash_.find(arc.olabel); if (it != nonterminal_hash_.end()) { // recurse into non terminal Label nonterminal = it->second; const Fst<A>* nt_fst = fst_array_[nonterminal]; PrefixId nt_prefix = PushPrefix( state_table_->GetStackPrefix(tuple.prefix_id), tuple.fst_id, arc.nextstate); // if start state is valid replace, else arc is implicitly // deleted StateId nt_start = nt_fst->Start(); if (nt_start != kNoStateId) { StateId nt_nextstate = flags & kArcNextStateValue ? state_table_->FindState( StateTuple(nt_prefix, nonterminal, nt_start)) : kNoStateId; Label ilabel = (EpsilonOnInput(call_label_type_)) ? 0 : arc.ilabel; Label olabel = (EpsilonOnOutput(call_label_type_)) ? 0 : ((call_output_label_ == kNoLabel) ? arc.olabel : call_output_label_); *arcp = A(ilabel, olabel, arc.weight, nt_nextstate); } else { return false; } } else { StateId nextstate = flags & kArcNextStateValue ? state_table_->FindState( StateTuple(tuple.prefix_id, tuple.fst_id, arc.nextstate)) : kNoStateId; *arcp = A(arc.ilabel, arc.olabel, arc.weight, nextstate); } } return true; } // Returns the arc iterator flags supported by this Fst. uint32 ArcIteratorFlags() const { uint32 flags = kArcValueFlags; if (!always_cache_) flags |= kArcNoCache; return flags; } T* GetStateTable() const { return state_table_; } const Fst<A>* GetFst(Label fst_id) const { return fst_array_[fst_id]; } Label GetFstId(Label nonterminal) const { typename NonTerminalHash::const_iterator it = nonterminal_hash_.find(nonterminal); if (it == nonterminal_hash_.end()) { FSTERROR() << "ReplaceFstImpl::GetFstId: nonterminal not found: " << nonterminal; } return it->second; } // returns true if label type on call arc results in epsilon input label bool EpsilonOnCallInput() { return EpsilonOnInput(call_label_type_); } // private methods private: // hash stack prefix (return unique index into stackprefix table) PrefixId GetPrefixId(const StackPrefix& prefix) { return state_table_->FindPrefixId(prefix); } // prefix id after a stack pop PrefixId PopPrefix(StackPrefix prefix) { prefix.Pop(); return GetPrefixId(prefix); } // prefix id after a stack push PrefixId PushPrefix(StackPrefix prefix, Label fst_id, StateId nextstate) { prefix.Push(fst_id, nextstate); return GetPrefixId(prefix); } // returns true if label type on arc results in epsilon input label bool EpsilonOnInput(ReplaceLabelType label_type) { if (label_type == REPLACE_LABEL_NEITHER || label_type == REPLACE_LABEL_OUTPUT) return true; return false; } // returns true if label type on arc results in epsilon input label bool EpsilonOnOutput(ReplaceLabelType label_type) { if (label_type == REPLACE_LABEL_NEITHER || label_type == REPLACE_LABEL_INPUT) return true; return false; } // returns true if for either the call or return arc ilabel != olabel bool ReplaceTransducer() { if (call_label_type_ == REPLACE_LABEL_INPUT || call_label_type_ == REPLACE_LABEL_OUTPUT || (call_label_type_ == REPLACE_LABEL_BOTH && call_output_label_ != kNoLabel) || return_label_type_ == REPLACE_LABEL_INPUT || return_label_type_ == REPLACE_LABEL_OUTPUT) return true; return false; } // private data private: // runtime options ReplaceLabelType call_label_type_; // how to label call arc ReplaceLabelType return_label_type_; // how to label return arc int64 call_output_label_; // specifies output label to put on call arc int64 return_label_; // specifies label to put on return arc bool always_cache_; // Optionally caching arc iterator disabled when true // state table StateTable *state_table_; // replace components set<Label> nonterminal_set_; NonTerminalHash nonterminal_hash_; vector<const Fst<A>*> fst_array_; Label root_; void operator=(const ReplaceFstImpl<A, T, C> &); // disallow }; // // \class ReplaceFst // \brief Recursivively replaces arcs in the root Fst with other Fsts. // This version is a delayed Fst. // // ReplaceFst supports dynamic replacement of arcs in one Fst with // another Fst. This replacement is recursive. ReplaceFst can be used // to support a variety of delayed constructions such as recursive // transition networks, union, or closure. It is constructed with an // array of Fst(s). One Fst represents the root (or topology) // machine. The root Fst refers to other Fsts by recursively replacing // arcs labeled as non-terminals with the matching non-terminal // Fst. Currently the ReplaceFst uses the output symbols of the arcs // to determine whether the arc is a non-terminal arc or not. A // non-terminal can be any label that is not a non-zero terminal label // in the output alphabet. // // Note that the constructor uses a vector of pair<>. These correspond // to the tuple of non-terminal Label and corresponding Fst. For example // to implement the closure operation we need 2 Fsts. The first root // Fst is a single Arc on the start State that self loops, it references // the particular machine for which we are performing the closure operation. // // The ReplaceFst class supports an optionally caching arc iterator: // ArcIterator< ReplaceFst<A> > // The ReplaceFst need to be built such that it is known to be ilabel // or olabel sorted (see usage below). // // Observe that Matcher<Fst<A> > will use the optionally caching arc // iterator when available (Fst is ilabel sorted and matching on the // input, or Fst is olabel sorted and matching on the output). // In order to obtain the most efficient behaviour, it is recommended // to set call_label_type to REPLACE_LABEL_INPUT or REPLACE_LABEL_BOTH // and return_label_type to REPLACE_LABEL_OUTPUT or REPLACE_LABEL_NEITHER // (this means that the call arc does not have epsilon on the input side // and the return arc has epsilon on the input side) and matching on the // input side. // // This class attaches interface to implementation and handles // reference counting, delegating most methods to ImplToFst. template <class A, class T = DefaultReplaceStateTable<A>, class C /* = DefaultCacheStore<A> */ > class ReplaceFst : public ImplToFst< ReplaceFstImpl<A, T, C> > { public: friend class ArcIterator< ReplaceFst<A, T, C> >; friend class StateIterator< ReplaceFst<A, T, C> >; friend class ReplaceFstMatcher<A, T, C>; typedef A Arc; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef T StateTable; typedef C Store; typedef typename C::State State; typedef CacheBaseImpl<State, C> CImpl; typedef ReplaceFstImpl<A, T, C> Impl; using ImplToFst<Impl>::Properties; ReplaceFst(const vector<pair<Label, const Fst<A>* > >& fst_array, Label root) : ImplToFst<Impl>( new Impl(fst_array, ReplaceFstOptions<A, T, C>(root))) {} ReplaceFst(const vector<pair<Label, const Fst<A>* > >& fst_array, const ReplaceFstOptions<A, T, C> &opts) : ImplToFst<Impl>(new Impl(fst_array, opts)) {} // See Fst<>::Copy() for doc. ReplaceFst(const ReplaceFst<A, T, C>& fst, bool safe = false) : ImplToFst<Impl>(fst, safe) {} // Get a copy of this ReplaceFst. See Fst<>::Copy() for further doc. virtual ReplaceFst<A, T, C> *Copy(bool safe = false) const { return new ReplaceFst<A, T, C>(*this, safe); } virtual inline void InitStateIterator(StateIteratorData<A> *data) const; virtual void InitArcIterator(StateId s, ArcIteratorData<A> *data) const { GetImpl()->InitArcIterator(s, data); } virtual MatcherBase<A> *InitMatcher(MatchType match_type) const { if ((GetImpl()->ArcIteratorFlags() & kArcNoCache) && ((match_type == MATCH_INPUT && Properties(kILabelSorted, false)) || (match_type == MATCH_OUTPUT && Properties(kOLabelSorted, false)))) { return new ReplaceFstMatcher<A, T, C>(*this, match_type); } else { VLOG(2) << "Not using replace matcher"; return 0; } } bool CyclicDependencies() const { return GetImpl()->CyclicDependencies(); } const StateTable& GetStateTable() const { return *GetImpl()->GetStateTable(); } const Fst<A> &GetFst(Label nonterminal) const { return *GetImpl()->GetFst(GetImpl()->GetFstId(nonterminal)); } private: // Makes visible to friends. Impl *GetImpl() const { return ImplToFst<Impl>::GetImpl(); } void operator=(const ReplaceFst<A, T, C> &fst); // disallow }; // Specialization for ReplaceFst. template<class A, class T, class C> class StateIterator< ReplaceFst<A, T, C> > : public CacheStateIterator< ReplaceFst<A, T, C> > { public: explicit StateIterator(const ReplaceFst<A, T, C> &fst) : CacheStateIterator< ReplaceFst<A, T, C> >(fst, fst.GetImpl()) {} private: DISALLOW_COPY_AND_ASSIGN(StateIterator); }; // Specialization for ReplaceFst. // Implements optional caching. It can be used as follows: // // ReplaceFst<A> replace; // ArcIterator< ReplaceFst<A> > aiter(replace, s); // // Note: ArcIterator< Fst<A> > is always a caching arc iterator. // aiter.SetFlags(kArcNoCache, kArcNoCache); // // Use the arc iterator, no arc will be cached, no state will be expanded. // // The varied 'kArcValueFlags' can be used to decide which part // // of arc values needs to be computed. // aiter.SetFlags(kArcILabelValue, kArcValueFlags); // // Only want the ilabel for this arc // aiter.Value(); // Does not compute the destination state. // aiter.Next(); // aiter.SetFlags(kArcNextStateValue, kArcNextStateValue); // // Want both ilabel and nextstate for that arc // aiter.Value(); // Does compute the destination state and inserts it // // in the replace state table. // // No Arc has been cached at that point. // template <class A, class T, class C> class ArcIterator< ReplaceFst<A, T, C> > { public: typedef A Arc; typedef typename A::StateId StateId; ArcIterator(const ReplaceFst<A, T, C> &fst, StateId s) : fst_(fst), state_(s), pos_(0), offset_(0), flags_(kArcValueFlags), arcs_(0), data_flags_(0), final_flags_(0) { cache_data_.ref_count = 0; local_data_.ref_count = 0; // If FST does not support optional caching, force caching. if (!(fst_.GetImpl()->ArcIteratorFlags() & kArcNoCache) && !(fst_.GetImpl()->HasArcs(state_))) fst_.GetImpl()->Expand(state_); // If state is already cached, use cached arcs array. if (fst_.GetImpl()->HasArcs(state_)) { (fst_.GetImpl()) ->template CacheBaseImpl<typename C::State, C>::InitArcIterator( state_, &cache_data_); num_arcs_ = cache_data_.narcs; arcs_ = cache_data_.arcs; // 'arcs_' is a ptr to the cached arcs. data_flags_ = kArcValueFlags; // All the arc member values are valid. } else { // Otherwise delay decision until Value() is called. tuple_ = fst_.GetImpl()->GetStateTable()->Tuple(state_); if (tuple_.fst_state == kNoStateId) { num_arcs_ = 0; } else { // The decision to cache or not to cache has been defered // until Value() or SetFlags() is called. However, the arc // iterator is set up now to be ready for non-caching in order // to keep the Value() method simple and efficient. const Fst<A>* fst = fst_.GetImpl()->GetFst(tuple_.fst_id); fst->InitArcIterator(tuple_.fst_state, &local_data_); // 'arcs_' is a pointer to the arcs in the underlying machine. arcs_ = local_data_.arcs; // Compute the final arc (but not its destination state) // if a final arc is required. bool has_final_arc = fst_.GetImpl()->ComputeFinalArc( tuple_, &final_arc_, kArcValueFlags & ~kArcNextStateValue); // Set the arc value flags that hold for 'final_arc_'. final_flags_ = kArcValueFlags & ~kArcNextStateValue; // Compute the number of arcs. num_arcs_ = local_data_.narcs; if (has_final_arc) ++num_arcs_; // Set the offset between the underlying arc positions and // the positions in the arc iterator. offset_ = num_arcs_ - local_data_.narcs; // Defers the decision to cache or not until Value() or // SetFlags() is called. data_flags_ = 0; } } } ~ArcIterator() { if (cache_data_.ref_count) --(*cache_data_.ref_count); if (local_data_.ref_count) --(*local_data_.ref_count); } void ExpandAndCache() const { // TODO(allauzen): revisit this // fst_.GetImpl()->Expand(state_, tuple_, local_data_); // (fst_.GetImpl())->CacheImpl<A>*>::InitArcIterator(state_, // &cache_data_); // fst_.InitArcIterator(state_, &cache_data_); // Expand and cache state. arcs_ = cache_data_.arcs; // 'arcs_' is a pointer to the cached arcs. data_flags_ = kArcValueFlags; // All the arc member values are valid. offset_ = 0; // No offset } void Init() { if (flags_ & kArcNoCache) { // If caching is disabled // 'arcs_' is a pointer to the arcs in the underlying machine. arcs_ = local_data_.arcs; // Set the arcs value flags that hold for 'arcs_'. data_flags_ = kArcWeightValue; if (!fst_.GetImpl()->EpsilonOnCallInput()) data_flags_ |= kArcILabelValue; // Set the offset between the underlying arc positions and // the positions in the arc iterator. offset_ = num_arcs_ - local_data_.narcs; } else { // Otherwise, expand and cache ExpandAndCache(); } } bool Done() const { return pos_ >= num_arcs_; } const A& Value() const { // If 'data_flags_' was set to 0, non-caching was not requested if (!data_flags_) { // TODO(allauzen): revisit this. if (flags_ & kArcNoCache) { // Should never happen. FSTERROR() << "ReplaceFst: inconsistent arc iterator flags"; } ExpandAndCache(); // Expand and cache. } if (pos_ - offset_ >= 0) { // The requested arc is not the 'final' arc. const A& arc = arcs_[pos_ - offset_]; if ((data_flags_ & flags_) == (flags_ & kArcValueFlags)) { // If the value flags for 'arc' match the recquired value flags // then return 'arc'. return arc; } else { // Otherwise, compute the corresponding arc on-the-fly. fst_.GetImpl()->ComputeArc(tuple_, arc, &arc_, flags_ & kArcValueFlags); return arc_; } } else { // The requested arc is the 'final' arc. if ((final_flags_ & flags_) != (flags_ & kArcValueFlags)) { // If the arc value flags that hold for the final arc // do not match the requested value flags, then // 'final_arc_' needs to be updated. fst_.GetImpl()->ComputeFinalArc(tuple_, &final_arc_, flags_ & kArcValueFlags); final_flags_ = flags_ & kArcValueFlags; } return final_arc_; } } void Next() { ++pos_; } size_t Position() const { return pos_; } void Reset() { pos_ = 0; } void Seek(size_t pos) { pos_ = pos; } uint32 Flags() const { return flags_; } void SetFlags(uint32 f, uint32 mask) { // Update the flags taking into account what flags are supported // by the Fst. flags_ &= ~mask; flags_ |= (f & fst_.GetImpl()->ArcIteratorFlags()); // If non-caching is not requested (and caching has not already // been performed), then flush 'data_flags_' to request caching // during the next call to Value(). if (!(flags_ & kArcNoCache) && data_flags_ != kArcValueFlags) { if (!fst_.GetImpl()->HasArcs(state_)) data_flags_ = 0; } // If 'data_flags_' has been flushed but non-caching is requested // before calling Value(), then set up the iterator for non-caching. if ((f & kArcNoCache) && (!data_flags_)) Init(); } private: const ReplaceFst<A, T, C> &fst_; // Reference to the FST StateId state_; // State in the FST mutable typename T::StateTuple tuple_; // Tuple corresponding to state_ ssize_t pos_; // Current position mutable ssize_t offset_; // Offset between position in iterator and in arcs_ ssize_t num_arcs_; // Number of arcs at state_ uint32 flags_; // Behavorial flags for the arc iterator mutable Arc arc_; // Memory to temporarily store computed arcs mutable ArcIteratorData<Arc> cache_data_; // Arc iterator data in cache mutable ArcIteratorData<Arc> local_data_; // Arc iterator data in local fst mutable const A* arcs_; // Array of arcs mutable uint32 data_flags_; // Arc value flags valid for data in arcs_ mutable Arc final_arc_; // Final arc (when required) mutable uint32 final_flags_; // Arc value flags valid for final_arc_ DISALLOW_COPY_AND_ASSIGN(ArcIterator); }; template <class A, class T, class C> class ReplaceFstMatcher : public MatcherBase<A> { public: typedef ReplaceFst<A, T, C> FST; typedef A Arc; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef MultiEpsMatcher<Matcher<Fst<A> > > LocalMatcher; ReplaceFstMatcher(const ReplaceFst<A, T, C> &fst, fst::MatchType match_type) : fst_(fst), impl_(fst_.GetImpl()), s_(fst::kNoStateId), match_type_(match_type), current_loop_(false), final_arc_(false), loop_(fst::kNoLabel, 0, A::Weight::One(), fst::kNoStateId) { if (match_type_ == fst::MATCH_OUTPUT) swap(loop_.ilabel, loop_.olabel); InitMatchers(); } ReplaceFstMatcher(const ReplaceFstMatcher<A, T, C> &matcher, bool safe = false) : fst_(matcher.fst_), impl_(fst_.GetImpl()), s_(fst::kNoStateId), match_type_(matcher.match_type_), current_loop_(false), final_arc_(false), loop_(fst::kNoLabel, 0, A::Weight::One(), fst::kNoStateId) { if (match_type_ == fst::MATCH_OUTPUT) swap(loop_.ilabel, loop_.olabel); InitMatchers(); } // Create a local matcher for each component Fst of replace. // LocalMatcher is a multi epsilon wrapper matcher. MultiEpsilonMatcher // is used to match each non-terminal arc, since these non-terminal // turn into epsilons on recursion. void InitMatchers() { const vector<const Fst<A>*>& fst_array = impl_->fst_array_; matcher_.resize(fst_array.size(), 0); for (size_t i = 0; i < fst_array.size(); ++i) { if (fst_array[i]) { matcher_[i] = new LocalMatcher(*fst_array[i], match_type_, kMultiEpsList); typename set<Label>::iterator it = impl_->nonterminal_set_.begin(); for (; it != impl_->nonterminal_set_.end(); ++it) { matcher_[i]->AddMultiEpsLabel(*it); } } } } virtual ReplaceFstMatcher<A, T, C> *Copy(bool safe = false) const { return new ReplaceFstMatcher<A, T, C>(*this, safe); } virtual ~ReplaceFstMatcher() { for (size_t i = 0; i < matcher_.size(); ++i) delete matcher_[i]; } virtual MatchType Type(bool test) const { if (match_type_ == MATCH_NONE) return match_type_; uint64 true_prop = match_type_ == MATCH_INPUT ? kILabelSorted : kOLabelSorted; uint64 false_prop = match_type_ == MATCH_INPUT ? kNotILabelSorted : kNotOLabelSorted; uint64 props = fst_.Properties(true_prop | false_prop, test); if (props & true_prop) return match_type_; else if (props & false_prop) return MATCH_NONE; else return MATCH_UNKNOWN; } virtual const Fst<A> &GetFst() const { return fst_; } virtual uint64 Properties(uint64 props) const { return props; } private: // Set the sate from which our matching happens. virtual void SetState_(StateId s) { if (s_ == s) return; s_ = s; tuple_ = impl_->GetStateTable()->Tuple(s_); if (tuple_.fst_state == kNoStateId) { done_ = true; return; } // Get current matcher. Used for non epsilon matching current_matcher_ = matcher_[tuple_.fst_id]; current_matcher_->SetState(tuple_.fst_state); loop_.nextstate = s_; final_arc_ = false; } // Search for label, from previous set state. If label == 0, first // hallucinate and epsilon loop, else use the underlying matcher to // search for the label or epsilons. // - Note since the ReplaceFST recursion on non-terminal arcs causes // epsilon transitions to be created we use the MultiEpsilonMatcher // to search for possible matches of non terminals. // - If the component Fst reaches a final state we also need to add // the exiting final arc. virtual bool Find_(Label label) { bool found = false; label_ = label; if (label_ == 0 || label_ == kNoLabel) { // Compute loop directly, saving Replace::ComputeArc if (label_ == 0) { current_loop_ = true; found = true; } // Search for matching multi epsilons final_arc_ = impl_->ComputeFinalArc(tuple_, 0); found = current_matcher_->Find(kNoLabel) || final_arc_ || found; } else { // Search on sub machine directly using sub machine matcher. found = current_matcher_->Find(label_); } return found; } virtual bool Done_() const { return !current_loop_ && !final_arc_ && current_matcher_->Done(); } virtual const Arc& Value_() const { if (current_loop_) { return loop_; } if (final_arc_) { impl_->ComputeFinalArc(tuple_, &arc_); return arc_; } const Arc& component_arc = current_matcher_->Value(); impl_->ComputeArc(tuple_, component_arc, &arc_); return arc_; } virtual void Next_() { if (current_loop_) { current_loop_ = false; return; } if (final_arc_) { final_arc_ = false; return; } current_matcher_->Next(); } virtual ssize_t Priority_(StateId s) { return fst_.NumArcs(s); } const ReplaceFst<A, T, C>& fst_; ReplaceFstImpl<A, T, C> *impl_; LocalMatcher* current_matcher_; vector<LocalMatcher*> matcher_; StateId s_; // Current state Label label_; // Current label MatchType match_type_; // Supplied by caller mutable bool done_; mutable bool current_loop_; // Current arc is the implicit loop mutable bool final_arc_; // Current arc for exiting recursion mutable typename T::StateTuple tuple_; // Tuple corresponding to state_ mutable Arc arc_; Arc loop_; DISALLOW_COPY_AND_ASSIGN(ReplaceFstMatcher); }; template <class A, class T, class C> inline void ReplaceFst<A, T, C>::InitStateIterator(StateIteratorData<A> *data) const { data->base = new StateIterator< ReplaceFst<A, T, C> >(*this); } typedef ReplaceFst<StdArc> StdReplaceFst; // // Recursivively replaces arcs in the root Fst with other Fsts. // This version writes the result of replacement to an output MutableFst. // // Replace supports replacement of arcs in one Fst with another // Fst. This replacement is recursive. Replace takes an array of // Fst(s). One Fst represents the root (or topology) machine. The root // Fst refers to other Fsts by recursively replacing arcs labeled as // non-terminals with the matching non-terminal Fst. Currently Replace // uses the output symbols of the arcs to determine whether the arc is // a non-terminal arc or not. A non-terminal can be any label that is // not a non-zero terminal label in the output alphabet. Note that // input argument is a vector of pair<>. These correspond to the tuple // of non-terminal Label and corresponding Fst. template<class Arc> void Replace(const vector<pair<typename Arc::Label, const Fst<Arc>* > >& ifst_array, MutableFst<Arc> *ofst, ReplaceFstOptions<Arc> opts = ReplaceFstOptions<Arc>()) { opts.gc = true; opts.gc_limit = 0; // Cache only the last state for fastest copy. *ofst = ReplaceFst<Arc>(ifst_array, opts); } template<class Arc> void Replace(const vector<pair<typename Arc::Label, const Fst<Arc>* > >& ifst_array, MutableFst<Arc> *ofst, fst::ReplaceUtilOptions<Arc> opts) { Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(opts)); } // Included for backward compatibility with 'epsilon_on_replace' arguments template<class Arc> void Replace(const vector<pair<typename Arc::Label, const Fst<Arc>* > >& ifst_array, MutableFst<Arc> *ofst, typename Arc::Label root, bool epsilon_on_replace) { Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(root, epsilon_on_replace)); } template<class Arc> void Replace(const vector<pair<typename Arc::Label, const Fst<Arc>* > >& ifst_array, MutableFst<Arc> *ofst, typename Arc::Label root) { Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(root)); } } // namespace fst #endif // FST_LIB_REPLACE_H__ <|start_filename|>third_party/openfst/src/include/fst/lock.h<|end_filename|> // lock.h // // 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. // // Author: <EMAIL> (<NAME>) // // \file // Google-compatibility locking declarations and inline definitions // // Classes and functions here are no-ops (by design); proper locking requires // actual implementation. #ifndef FST_LIB_LOCK_H__ #define FST_LIB_LOCK_H__ #include <fst/compat.h> // for DISALLOW_COPY_AND_ASSIGN namespace fst { using namespace std; // // Single initialization - single-thread implementation // typedef int FstOnceType; static const int FST_ONCE_INIT = 1; inline int FstOnceInit(FstOnceType *once, void (*init)(void)) { if (*once) (*init)(); *once = 0; return 0; } // // Thread locking - single-thread (non-)implementation // class Mutex { public: Mutex() {} private: DISALLOW_COPY_AND_ASSIGN(Mutex); }; class MutexLock { public: MutexLock(Mutex *) {} private: DISALLOW_COPY_AND_ASSIGN(MutexLock); }; class ReaderMutexLock { public: ReaderMutexLock(Mutex *) {} private: DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock); }; // Reference counting - single-thread implementation class RefCounter { public: RefCounter() : count_(1) {} int count() const { return count_; } int Incr() const { return ++count_; } int Decr() const { return --count_; } private: mutable int count_; DISALLOW_COPY_AND_ASSIGN(RefCounter); }; } // namespace fst #endif // FST_LIB_LOCK_H__ <|start_filename|>third_party/openfst/src/include/fst/script/synchronize.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_SCRIPT_SYNCHRONIZE_H_ #define FST_SCRIPT_SYNCHRONIZE_H_ #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> #include <fst/synchronize.h> namespace fst { namespace script { typedef args::Package<const FstClass &, MutableFstClass *> SynchronizeArgs; template<class Arc> void Synchronize(SynchronizeArgs *args) { const Fst<Arc> &ifst = *(args->arg1.GetFst<Arc>()); MutableFst<Arc> *ofst = args->arg2->GetMutableFst<Arc>(); Synchronize(ifst, ofst); } void Synchronize(const FstClass &ifst, MutableFstClass *ofst); } // namespace script } // namespace fst #endif // FST_SCRIPT_SYNCHRONIZE_H_ <|start_filename|>third_party/openfst/src/include/fst/script/script-impl.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // This file defines the registration mechanism for new operations. // These operations are designed to enable scripts to work with FST classes // at a high level. // If you have a new arc type and want these operations to work with FSTs // with that arc type, see below for the registration steps // you must take. // These methods are only recommended for use in high-level scripting // applications. Most users should use the lower-level templated versions // corresponding to these. // If you have a new arc type you'd like these operations to work with, // use the REGISTER_FST_OPERATIONS macro defined in fstcsript.h // If you have a custom operation you'd like to define, you need four // components. In the following, assume you want to create a new operation // with the signature // // void Foo(const FstClass &ifst, MutableFstClass *ofst); // // You need: // // 1) A way to bundle the args that your new Foo operation will take, as // a single struct. The template structs in arg-packs.h provide a handy // way to do this. In Foo's case, that might look like this: // // typedef args::Package<const FstClass &, // MutableFstClass *> FooArgs; // // Note: this package of args is going to be passed by non-const pointer. // // 2) A function template that is able to perform Foo, given the args and // arc type. Yours might look like this: // // template<class Arc> // void Foo(FooArgs *args) { // // Pull out the actual, arc-templated FSTs // const Fst<Arc> &ifst = args->arg1.GetFst<Arc>(); // MutableFst<Arc> *ofst = args->arg2->GetMutableFst<Arc>(); // // // actually perform foo on ifst and ofst... // } // // 3) a client-facing function for your operation. This would look like // the following: // // void Foo(const FstClass &ifst, MutableFstClass *ofst) { // // Check that the arc types of the FSTs match // if (!ArcTypesMatch(ifst, *ofst, "Foo")) return; // // package the args // FooArgs args(ifst, ofst); // // Finally, call the operation // Apply<Operation<FooArgs> >("Foo", ifst->ArcType(), &args); // } // // The Apply<> function template takes care of the link between 2 and 3, // provided you also have: // // 4) A registration for your new operation, on the arc types you care about. // This can be provided easily by the REGISTER_FST_OPERATION macro in // operations.h: // // REGISTER_FST_OPERATION(Foo, StdArc, FooArgs); // REGISTER_FST_OPERATION(Foo, MyArc, FooArgs); // // .. etc // // // That's it! Now when you call Foo(const FstClass &, MutableFstClass *), // it dispatches (in #3) via the Apply<> function to the correct // instantiation of the template function in #2. // #ifndef FST_SCRIPT_SCRIPT_IMPL_H_ #define FST_SCRIPT_SCRIPT_IMPL_H_ // // This file contains general-purpose templates which are used in the // implementation of the operations. // #include <utility> using std::pair; using std::make_pair; #include <string> #include <fst/script/fst-class.h> #include <fst/generic-register.h> #include <fst/script/arg-packs.h> #include <fst/types.h> namespace fst { namespace script { // // A generic register for operations with various kinds of signatures. // Needed since every function signature requires a new registration class. // The pair<string, string> is understood to be the operation name and arc // type; subclasses (or typedefs) need only provide the operation signature. // template<class OperationSignature> class GenericOperationRegister : public GenericRegister<pair<string, string>, OperationSignature, GenericOperationRegister<OperationSignature> > { public: void RegisterOperation(const string &operation_name, const string &arc_type, OperationSignature op) { this->SetEntry(make_pair(operation_name, arc_type), op); } OperationSignature GetOperation( const string &operation_name, const string &arc_type) { return this->GetEntry(make_pair(operation_name, arc_type)); } protected: virtual string ConvertKeyToSoFilename( const pair<string, string>& key) const { // Just use the old-style FST for now. string legal_type(key.second); // the arc type ConvertToLegalCSymbol(&legal_type); return legal_type + "-arc.so"; } }; // Operation package - everything you need to register a new type of operation // The ArgPack should be the type that's passed into each wrapped function - // for instance, it might be a struct containing all the args. // It's always passed by pointer, so const members should be used to enforce // constness where it's needed. Return values should be implemented as a // member of ArgPack as well. template<class ArgPack> struct Operation { typedef ArgPack Args; typedef void (*OpType)(ArgPack *args); // The register (hash) type typedef GenericOperationRegister<OpType> Register; // The register-er type typedef GenericRegisterer<Register> Registerer; }; // Macro for registering new types of operations. #define REGISTER_FST_OPERATION(Op, Arc, ArgPack) \ static fst::script::Operation<ArgPack>::Registerer \ arc_dispatched_operation_##ArgPack##Op##Arc##_registerer \ (make_pair(#Op, Arc::Type()), Op<Arc>) // // Template function to apply an operation by name // template<class OpReg> void Apply(const string &op_name, const string &arc_type, typename OpReg::Args *args) { typename OpReg::Register *reg = OpReg::Register::GetRegister(); typename OpReg::OpType op = reg->GetOperation(op_name, arc_type); if (op == 0) { FSTERROR() << "No operation found for \"" << op_name << "\" on " << "arc type " << arc_type; return; } op(args); } // Helper that logs to ERROR if the arc types of a and b don't match. // The op_name is also printed. bool ArcTypesMatch(const FstClass &a, const FstClass &b, const string &op_name); } // namespace script } // namespace fst #endif // FST_SCRIPT_SCRIPT_IMPL_H_ <|start_filename|>third_party/openfst/src/include/fst/shortest-path.h<|end_filename|> // shortest-path.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Functions to find shortest paths in an FST. #ifndef FST_LIB_SHORTEST_PATH_H__ #define FST_LIB_SHORTEST_PATH_H__ #include <functional> #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/cache.h> #include <fst/determinize.h> #include <fst/queue.h> #include <fst/shortest-distance.h> #include <fst/test-properties.h> namespace fst { template <class Arc, class Queue, class ArcFilter> struct ShortestPathOptions : public ShortestDistanceOptions<Arc, Queue, ArcFilter> { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; size_t nshortest; // return n-shortest paths bool unique; // only return paths with distinct input strings bool has_distance; // distance vector already contains the // shortest distance from the initial state bool first_path; // Single shortest path stops after finding the first // path to a final state. That path is the shortest path // only when using the ShortestFirstQueue and // only when all the weights in the FST are between // One() and Zero() according to NaturalLess. Weight weight_threshold; // pruning weight threshold. StateId state_threshold; // pruning state threshold. ShortestPathOptions(Queue *q, ArcFilter filt, size_t n = 1, bool u = false, bool hasdist = false, float d = kDelta, bool fp = false, Weight w = Weight::Zero(), StateId s = kNoStateId) : ShortestDistanceOptions<Arc, Queue, ArcFilter>(q, filt, kNoStateId, d), nshortest(n), unique(u), has_distance(hasdist), first_path(fp), weight_threshold(w), state_threshold(s) {} }; // Shortest-path algorithm: normally not called directly; prefer // 'ShortestPath' below with n=1. 'ofst' contains the shortest path in // 'ifst'. 'distance' returns the shortest distances from the source // state to each state in 'ifst'. 'opts' is used to specify options // such as the queue discipline, the arc filter and delta. // // The shortest path is the lowest weight path w.r.t. the natural // semiring order. // // The weights need to be right distributive and have the path (kPath) // property. template<class Arc, class Queue, class ArcFilter> void SingleShortestPath(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, vector<typename Arc::Weight> *distance, ShortestPathOptions<Arc, Queue, ArcFilter> &opts) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; ofst->DeleteStates(); ofst->SetInputSymbols(ifst.InputSymbols()); ofst->SetOutputSymbols(ifst.OutputSymbols()); if (ifst.Start() == kNoStateId) { if (ifst.Properties(kError, false)) ofst->SetProperties(kError, kError); return; } vector<bool> enqueued; vector<StateId> parent; vector<Arc> arc_parent; Queue *state_queue = opts.state_queue; StateId source = opts.source == kNoStateId ? ifst.Start() : opts.source; Weight f_distance = Weight::Zero(); StateId f_parent = kNoStateId; distance->clear(); state_queue->Clear(); if (opts.nshortest != 1) { FSTERROR() << "SingleShortestPath: for nshortest > 1, use ShortestPath" << " instead"; ofst->SetProperties(kError, kError); return; } if (opts.weight_threshold != Weight::Zero() || opts.state_threshold != kNoStateId) { FSTERROR() << "SingleShortestPath: weight and state thresholds not applicable"; ofst->SetProperties(kError, kError); return; } if ((Weight::Properties() & (kPath | kRightSemiring)) != (kPath | kRightSemiring)) { FSTERROR() << "SingleShortestPath: Weight needs to have the path" << " property and be right distributive: " << Weight::Type(); ofst->SetProperties(kError, kError); return; } while (distance->size() < source) { distance->push_back(Weight::Zero()); enqueued.push_back(false); parent.push_back(kNoStateId); arc_parent.push_back(Arc(kNoLabel, kNoLabel, Weight::Zero(), kNoStateId)); } distance->push_back(Weight::One()); parent.push_back(kNoStateId); arc_parent.push_back(Arc(kNoLabel, kNoLabel, Weight::Zero(), kNoStateId)); state_queue->Enqueue(source); enqueued.push_back(true); while (!state_queue->Empty()) { StateId s = state_queue->Head(); state_queue->Dequeue(); enqueued[s] = false; Weight sd = (*distance)[s]; if (ifst.Final(s) != Weight::Zero()) { Weight w = Times(sd, ifst.Final(s)); if (f_distance != Plus(f_distance, w)) { f_distance = Plus(f_distance, w); f_parent = s; } if (!f_distance.Member()) { ofst->SetProperties(kError, kError); return; } if (opts.first_path) break; } for (ArcIterator< Fst<Arc> > aiter(ifst, s); !aiter.Done(); aiter.Next()) { const Arc &arc = aiter.Value(); while (distance->size() <= arc.nextstate) { distance->push_back(Weight::Zero()); enqueued.push_back(false); parent.push_back(kNoStateId); arc_parent.push_back(Arc(kNoLabel, kNoLabel, Weight::Zero(), kNoStateId)); } Weight &nd = (*distance)[arc.nextstate]; Weight w = Times(sd, arc.weight); if (nd != Plus(nd, w)) { nd = Plus(nd, w); if (!nd.Member()) { ofst->SetProperties(kError, kError); return; } parent[arc.nextstate] = s; arc_parent[arc.nextstate] = arc; if (!enqueued[arc.nextstate]) { state_queue->Enqueue(arc.nextstate); enqueued[arc.nextstate] = true; } else { state_queue->Update(arc.nextstate); } } } } StateId s_p = kNoStateId, d_p = kNoStateId; for (StateId s = f_parent, d = kNoStateId; s != kNoStateId; d = s, s = parent[s]) { d_p = s_p; s_p = ofst->AddState(); if (d == kNoStateId) { ofst->SetFinal(s_p, ifst.Final(f_parent)); } else { arc_parent[d].nextstate = d_p; ofst->AddArc(s_p, arc_parent[d]); } } ofst->SetStart(s_p); if (ifst.Properties(kError, false)) ofst->SetProperties(kError, kError); ofst->SetProperties( ShortestPathProperties(ofst->Properties(kFstProperties, false)), kFstProperties); } template <class S, class W> class ShortestPathCompare { public: typedef S StateId; typedef W Weight; typedef pair<StateId, Weight> Pair; ShortestPathCompare(const vector<Pair>& pairs, const vector<Weight>& distance, StateId sfinal, float d) : pairs_(pairs), distance_(distance), superfinal_(sfinal), delta_(d) {} bool operator()(const StateId x, const StateId y) const { const Pair &px = pairs_[x]; const Pair &py = pairs_[y]; Weight dx = px.first == superfinal_ ? Weight::One() : px.first < distance_.size() ? distance_[px.first] : Weight::Zero(); Weight dy = py.first == superfinal_ ? Weight::One() : py.first < distance_.size() ? distance_[py.first] : Weight::Zero(); Weight wx = Times(dx, px.second); Weight wy = Times(dy, py.second); // Penalize complete paths to ensure correct results with inexact weights. // This forms a strict weak order so long as ApproxEqual(a, b) => // ApproxEqual(a, c) for all c s.t. less_(a, c) && less_(c, b). if (px.first == superfinal_ && py.first != superfinal_) { return less_(wy, wx) || ApproxEqual(wx, wy, delta_); } else if (py.first == superfinal_ && px.first != superfinal_) { return less_(wy, wx) && !ApproxEqual(wx, wy, delta_); } else { return less_(wy, wx); } } private: const vector<Pair> &pairs_; const vector<Weight> &distance_; StateId superfinal_; float delta_; NaturalLess<Weight> less_; }; // N-Shortest-path algorithm: implements the core n-shortest path // algorithm. The output is built REVERSED. See below for versions with // more options and not reversed. // // 'ofst' contains the REVERSE of 'n'-shortest paths in 'ifst'. // 'distance' must contain the shortest distance from each state to a final // state in 'ifst'. 'delta' is the convergence delta. // // The n-shortest paths are the n-lowest weight paths w.r.t. the // natural semiring order. The single path that can be read from the // ith of at most n transitions leaving the initial state of 'ofst' is // the ith shortest path. Disregarding the initial state and initial // transitions, the n-shortest paths, in fact, form a tree rooted at // the single final state. // // The weights need to be left and right distributive (kSemiring) and // have the path (kPath) property. // // Arc weights must satisfy the property that the sum of the weights of one or // more paths from some state S to T is never Zero(). In particular, arc weights // are never Zero(). // // The algorithm is from <NAME> Riley, "An Efficient Algorithm for // the n-best-strings problem", ICSLP 2002. The algorithm relies on // the shortest-distance algorithm. There are some issues with the // pseudo-code as written in the paper (viz., line 11). // // IMPLEMENTATION NOTE: The input fst 'ifst' can be a delayed fst and // and at any state in its expansion the values of distance vector need only // be defined at that time for the states that are known to exist. template<class Arc, class RevArc> void NShortestPath(const Fst<RevArc> &ifst, MutableFst<Arc> *ofst, const vector<typename Arc::Weight> &distance, size_t n, float delta = kDelta, typename Arc::Weight weight_threshold = Arc::Weight::Zero(), typename Arc::StateId state_threshold = kNoStateId) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef pair<StateId, Weight> Pair; typedef typename RevArc::Weight RevWeight; if (n <= 0) return; if ((Weight::Properties() & (kPath | kSemiring)) != (kPath | kSemiring)) { FSTERROR() << "NShortestPath: Weight needs to have the " << "path property and be distributive: " << Weight::Type(); ofst->SetProperties(kError, kError); return; } ofst->DeleteStates(); ofst->SetInputSymbols(ifst.InputSymbols()); ofst->SetOutputSymbols(ifst.OutputSymbols()); // Each state in 'ofst' corresponds to a path with weight w from the // initial state of 'ifst' to a state s in 'ifst', that can be // characterized by a pair (s,w). The vector 'pairs' maps each // state in 'ofst' to the corresponding pair maps states in OFST to // the corresponding pair (s,w). vector<Pair> pairs; // The supefinal state is denoted by -1, 'compare' knows that the // distance from 'superfinal' to the final state is 'Weight::One()', // hence 'distance[superfinal]' is not needed. StateId superfinal = -1; ShortestPathCompare<StateId, Weight> compare(pairs, distance, superfinal, delta); vector<StateId> heap; // 'r[s + 1]', 's' state in 'fst', is the number of states in 'ofst' // which corresponding pair contains 's' ,i.e. , it is number of // paths computed so far to 's'. Valid for 's == -1' (superfinal). vector<int> r; NaturalLess<Weight> less; if (ifst.Start() == kNoStateId || distance.size() <= ifst.Start() || distance[ifst.Start()] == Weight::Zero() || less(weight_threshold, Weight::One()) || state_threshold == 0) { if (ifst.Properties(kError, false)) ofst->SetProperties(kError, kError); return; } ofst->SetStart(ofst->AddState()); StateId final = ofst->AddState(); ofst->SetFinal(final, Weight::One()); while (pairs.size() <= final) pairs.push_back(Pair(kNoStateId, Weight::Zero())); pairs[final] = Pair(ifst.Start(), Weight::One()); heap.push_back(final); Weight limit = Times(distance[ifst.Start()], weight_threshold); while (!heap.empty()) { pop_heap(heap.begin(), heap.end(), compare); StateId state = heap.back(); Pair p = pairs[state]; heap.pop_back(); Weight d = p.first == superfinal ? Weight::One() : p.first < distance.size() ? distance[p.first] : Weight::Zero(); if (less(limit, Times(d, p.second)) || (state_threshold != kNoStateId && ofst->NumStates() >= state_threshold)) continue; while (r.size() <= p.first + 1) r.push_back(0); ++r[p.first + 1]; if (p.first == superfinal) ofst->AddArc(ofst->Start(), Arc(0, 0, Weight::One(), state)); if ((p.first == superfinal) && (r[p.first + 1] == n)) break; if (r[p.first + 1] > n) continue; if (p.first == superfinal) continue; for (ArcIterator< Fst<RevArc> > aiter(ifst, p.first); !aiter.Done(); aiter.Next()) { const RevArc &rarc = aiter.Value(); Arc arc(rarc.ilabel, rarc.olabel, rarc.weight.Reverse(), rarc.nextstate); Weight w = Times(p.second, arc.weight); StateId next = ofst->AddState(); pairs.push_back(Pair(arc.nextstate, w)); arc.nextstate = state; ofst->AddArc(next, arc); heap.push_back(next); push_heap(heap.begin(), heap.end(), compare); } Weight finalw = ifst.Final(p.first).Reverse(); if (finalw != Weight::Zero()) { Weight w = Times(p.second, finalw); StateId next = ofst->AddState(); pairs.push_back(Pair(superfinal, w)); ofst->AddArc(next, Arc(0, 0, finalw, state)); heap.push_back(next); push_heap(heap.begin(), heap.end(), compare); } } Connect(ofst); if (ifst.Properties(kError, false)) ofst->SetProperties(kError, kError); ofst->SetProperties( ShortestPathProperties(ofst->Properties(kFstProperties, false)), kFstProperties); } // N-Shortest-path algorithm: this version allow fine control // via the options argument. See below for a simpler interface. // // 'ofst' contains the n-shortest paths in 'ifst'. 'distance' returns // the shortest distances from the source state to each state in // 'ifst'. 'opts' is used to specify options such as the number of // paths to return, whether they need to have distinct input // strings, the queue discipline, the arc filter and the convergence // delta. // // The n-shortest paths are the n-lowest weight paths w.r.t. the // natural semiring order. The single path that can be read from the // ith of at most n transitions leaving the initial state of 'ofst' is // the ith shortest path. Disregarding the initial state and initial // transitions, The n-shortest paths, in fact, form a tree rooted at // the single final state. // The weights need to be right distributive and have the path (kPath) // property. They need to be left distributive as well for nshortest // > 1. // // The algorithm is from Mohri and Riley, "An Efficient Algorithm for // the n-best-strings problem", ICSLP 2002. The algorithm relies on // the shortest-distance algorithm. There are some issues with the // pseudo-code as written in the paper (viz., line 11). template<class Arc, class Queue, class ArcFilter> void ShortestPath(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, vector<typename Arc::Weight> *distance, ShortestPathOptions<Arc, Queue, ArcFilter> &opts) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef ReverseArc<Arc> ReverseArc; size_t n = opts.nshortest; if (n == 1) { SingleShortestPath(ifst, ofst, distance, opts); return; } if (n <= 0) return; if ((Weight::Properties() & (kPath | kSemiring)) != (kPath | kSemiring)) { FSTERROR() << "ShortestPath: n-shortest: Weight needs to have the " << "path property and be distributive: " << Weight::Type(); ofst->SetProperties(kError, kError); return; } if (!opts.has_distance) { ShortestDistance(ifst, distance, opts); if (distance->size() == 1 && !(*distance)[0].Member()) { ofst->SetProperties(kError, kError); return; } } // Algorithm works on the reverse of 'fst' : 'rfst', 'distance' is // the distance to the final state in 'rfst', 'ofst' is built as the // reverse of the tree of n-shortest path in 'rfst'. VectorFst<ReverseArc> rfst; Reverse(ifst, &rfst); Weight d = Weight::Zero(); for (ArcIterator< VectorFst<ReverseArc> > aiter(rfst, 0); !aiter.Done(); aiter.Next()) { const ReverseArc &arc = aiter.Value(); StateId s = arc.nextstate - 1; if (s < distance->size()) d = Plus(d, Times(arc.weight.Reverse(), (*distance)[s])); } distance->insert(distance->begin(), d); if (!opts.unique) { NShortestPath(rfst, ofst, *distance, n, opts.delta, opts.weight_threshold, opts.state_threshold); } else { vector<Weight> ddistance; DeterminizeFstOptions<ReverseArc> dopts(opts.delta); DeterminizeFst<ReverseArc> dfst(rfst, distance, &ddistance, dopts); NShortestPath(dfst, ofst, ddistance, n, opts.delta, opts.weight_threshold, opts.state_threshold); } distance->erase(distance->begin()); } // Shortest-path algorithm: simplified interface. See above for a // version that allows finer control. // // 'ofst' contains the 'n'-shortest paths in 'ifst'. The queue // discipline is automatically selected. When 'unique' == true, only // paths with distinct input labels are returned. // // The n-shortest paths are the n-lowest weight paths w.r.t. the // natural semiring order. The single path that can be read from the // ith of at most n transitions leaving the initial state of 'ofst' is // the ith best path. // // The weights need to be right distributive and have the path // (kPath) property. template<class Arc> void ShortestPath(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, size_t n = 1, bool unique = false, bool first_path = false, typename Arc::Weight weight_threshold = Arc::Weight::Zero(), typename Arc::StateId state_threshold = kNoStateId) { vector<typename Arc::Weight> distance; AnyArcFilter<Arc> arc_filter; AutoQueue<typename Arc::StateId> state_queue(ifst, &distance, arc_filter); ShortestPathOptions< Arc, AutoQueue<typename Arc::StateId>, AnyArcFilter<Arc> > opts(&state_queue, arc_filter, n, unique, false, kDelta, first_path, weight_threshold, state_threshold); ShortestPath(ifst, ofst, &distance, opts); } } // namespace fst #endif // FST_LIB_SHORTEST_PATH_H__ <|start_filename|>third_party/openfst/src/bin/fstmap.cc<|end_filename|> // fstmap.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Applies an operation to each arc of an FST. // #include <string> #include <fst/script/map.h> DEFINE_double(delta, fst::kDelta, "Comparison/quantization delta"); DEFINE_string(map_type, "identity", "Map operation, one of: \"arc_sum\", \"identity\", \"invert\", " "\"plus (--weight)\", \"quantize (--delta)\", \"rmweight\", " "\"superfinal\", \"times (--weight)\", \"to_log\", \"to_log64\", " "\"to_standard\""); DEFINE_string(weight, "", "Weight parameter"); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::MutableFstClass; using fst::script::VectorFstClass; string usage = "Applies an operation to each arc of an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; string out_name = argc > 2 ? argv[2] : ""; FstClass *ifst = FstClass::Read(in_name); if (!ifst) return 1; s::WeightClass w = !FLAGS_weight.empty() ? s::WeightClass(ifst->WeightType(), FLAGS_weight) : (FLAGS_map_type == "times" ? s::WeightClass::One() : s::WeightClass::Zero()); s::MapType mt; if (FLAGS_map_type == "arc_sum") { mt = s::ARC_SUM_MAPPER; } else if (FLAGS_map_type == "identity") { mt = s::IDENTITY_MAPPER; } else if (FLAGS_map_type == "invert") { mt = s::INVERT_MAPPER; } else if (FLAGS_map_type == "plus") { mt = s::PLUS_MAPPER; } else if (FLAGS_map_type == "quantize") { mt = s::QUANTIZE_MAPPER; } else if (FLAGS_map_type == "rmweight") { mt = s::RMWEIGHT_MAPPER; } else if (FLAGS_map_type == "superfinal") { mt = s::SUPERFINAL_MAPPER; } else if (FLAGS_map_type == "times") { mt = s::TIMES_MAPPER; } else if (FLAGS_map_type == "to_log") { mt = s::TO_LOG_MAPPER; } else if (FLAGS_map_type == "to_log64") { mt = s::TO_LOG64_MAPPER; } else if (FLAGS_map_type == "to_standard") { mt = s::TO_STD_MAPPER; } else { LOG(ERROR) << argv[0] << ": Unknown map type \"" << FLAGS_map_type << "\"\n"; return 1; } FstClass *ofst = s::Map(*ifst, mt, FLAGS_delta, w); ofst->Write(out_name); return 0; } <|start_filename|>third_party/openfst/src/include/fst/compat.h<|end_filename|> // compat.h // // 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. // // Author: <EMAIL> (<NAME>) // // \file // Google compatibility declarations and inline definitions. #ifndef FST_LIB_COMPAT_H__ #define FST_LIB_COMPAT_H__ #include <dlfcn.h> #include <climits> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> // Makes copy constructor and operator= private #define DISALLOW_COPY_AND_ASSIGN(type) \ type(const type&); \ void operator=(const type&) #include <fst/config.h> #include <fst/types.h> #include <fst/lock.h> #include <fst/flags.h> #include <fst/log.h> #include <fst/icu.h> using std::cin; using std::cout; using std::cerr; using std::endl; using std::string; void FailedNewHandler(); namespace fst { using namespace std; // Downcasting template<typename To, typename From> inline To down_cast(From* f) { return static_cast<To>(f); } // Bitcasting template <class Dest, class Source> inline Dest bit_cast(const Source& source) { // Compile time assertion: sizeof(Dest) == sizeof(Source) // A compile error here means your Dest and Source have different sizes. typedef char VerifySizesAreEqual [sizeof(Dest) == sizeof(Source) ? 1 : -1]; Dest dest; memcpy(&dest, &source, sizeof(dest)); return dest; } // Check sums class CheckSummer { public: CheckSummer() : count_(0) { check_sum_.resize(kCheckSumLength, '\0'); } void Reset() { count_ = 0; for (int i = 0; i < kCheckSumLength; ++i) check_sum_[i] = '\0'; } void Update(void const *data, int size) { const char *p = reinterpret_cast<const char *>(data); for (int i = 0; i < size; ++i) check_sum_[(count_++) % kCheckSumLength] ^= p[i]; } void Update(string const &data) { for (int i = 0; i < data.size(); ++i) check_sum_[(count_++) % kCheckSumLength] ^= data[i]; } string Digest() { return check_sum_; } private: static const int kCheckSumLength = 32; int count_; string check_sum_; DISALLOW_COPY_AND_ASSIGN(CheckSummer); }; } // namespace fst #endif // FST_LIB_COMPAT_H__ <|start_filename|>third_party/openfst/src/include/fst/compact-fst.h<|end_filename|> // compact-fst.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // FST Class for memory-efficient representation of common types of // FSTs: linear automata, acceptors, unweighted FSTs, ... #ifndef FST_LIB_COMPACT_FST_H__ #define FST_LIB_COMPACT_FST_H__ #include <iterator> #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/cache.h> #include <fst/expanded-fst.h> #include <fst/fst-decl.h> // For optional argument declarations #include <fst/mapped-file.h> #include <fst/matcher.h> #include <fst/test-properties.h> #include <fst/util.h> namespace fst { struct CompactFstOptions : public CacheOptions { // CompactFst default caching behaviour is to do no caching. Most // compactors are cheap and therefore we save memory by not doing // caching. CompactFstOptions() : CacheOptions(true, 0) {} CompactFstOptions(const CacheOptions &opts) : CacheOptions(opts) {} }; // Compactor Interface - class determinies how arcs and final weights // are compacted and expanded. // // Final weights are treated as transitions to the superfinal state, // i.e. ilabel = olabel = kNoLabel and nextstate = kNoStateId. // // There are two types of compactors: // // * Fixed out-degree compactors: 'compactor.Size()' returns a // positive integer 's'. An FST can be compacted by this compactor // only if each state has exactly 's' outgoing transitions (counting a // non-Zero() final weight as a transition). A typical example is a // compactor for string FSTs, i.e. 's == 1'. // // * Variable out-degree compactors: 'compactor.Size() == -1'. There // are no out-degree restrictions for these compactors. // // // class Compactor { // public: // // Element is the type of the compacted transitions. // typedef ... Element; // // Return the compacted representation of a transition 'arc' // // at a state 's'. // Element Compact(StateId s, const Arc &arc); // // Return the transition at state 's' represented by the compacted // // transition 'e'. // Arc Expand(StateId s, const Element &e); // // Return -1 for variable out-degree compactors, and the mandatory // // out-degree otherwise. // ssize_t Size(); // // Test whether 'fst' can be compacted by this compactor. // bool Compatible(const Fst<A> &fst); // // Return the properties that are always true for an fst // // compacted using this compactor // uint64 Properties(); // // Return a string identifying the type of compactor. // static const string &Type(); // // Write a compactor to a file. // bool Write(ostream &strm); // // Read a compactor from a file. // static Compactor *Read(istream &strm); // // Default constructor (optional, see comment below). // Compactor(); // }; // // The default constructor is only required for FST_REGISTER to work // (i.e. enabling Convert() and the command-line utilities to work // with this new compactor). However, a default constructor always // needs to be specified for this code to compile, but one can have it // simply raise an error when called: // // Compactor::Compactor() { // FSTERROR() << "Compactor: no default constructor"; // } // Default implementation data for Compact Fst, which can shared // between otherwise independent copies. // // The implementation contains two arrays: 'states_' and 'compacts_'. // // For fixed out-degree compactors, the 'states_' array is unallocated. // The 'compacts_' contains the compacted transitions. Its size is // 'ncompacts_'. The outgoing transitions at a given state are stored // consecutively. For a given state 's', its 'compactor.Size()' outgoing // transitions (including superfinal transition when 's' is final), are // stored in position ['s*compactor.Size()', '(s+1)*compactor.Size()'). // // For variable out-degree compactors, the states_ array has size // 'nstates_ + 1' and contains pointers to positions into 'compacts_'. // For a given state 's', the compacted transitions of 's' are // stored in positions [ 'states_[s]', 'states_[s + 1]' ) in 'compacts_'. // By convention, 'states_[nstates_] == ncompacts_'. // // In both cases, the superfinal transitions (when 's' is final, i.e. // 'Final(s) != Weight::Zero()') are stored first. // // The unsigned type U is used to represent indices into the compacts_ // array. template <class E, class U> class DefaultCompactStore { public: typedef E CompactElement; typedef U Unsigned; DefaultCompactStore() : states_region_(0), compacts_region_(0), states_(0), compacts_(0), nstates_(0), ncompacts_(0), narcs_(0), start_(kNoStateId), error_(false) {} template <class A, class Compactor> DefaultCompactStore(const Fst<A> &fst, const Compactor &compactor); template <class Iterator, class Compactor> DefaultCompactStore(const Iterator &begin, const Iterator &end, const Compactor &compactor); ~DefaultCompactStore() { if (states_region_ == NULL) { delete [] states_; } delete states_region_; if (compacts_region_ == NULL) { delete [] compacts_; } delete compacts_region_; } template <class Compactor> static DefaultCompactStore<E, U> *Read(istream &strm, const FstReadOptions &opts, const FstHeader &hdr, const Compactor &compactor); bool Write(ostream &strm, const FstWriteOptions &opts) const; Unsigned States(ssize_t i) const { return states_[i]; } const CompactElement &Compacts(size_t i) const { return compacts_[i]; } size_t NumStates() const { return nstates_; } size_t NumCompacts() const { return ncompacts_; } size_t NumArcs() const { return narcs_; } ssize_t Start() const { return start_; } int RefCount() const { return ref_count_.count(); } int IncrRefCount() { return ref_count_.Incr(); } int DecrRefCount() { return ref_count_.Decr(); } bool Error() const { return error_; } // Returns a string identifying the type of data storage container. static const string &Type(); private: MappedFile *states_region_; MappedFile *compacts_region_; Unsigned *states_; CompactElement *compacts_; size_t nstates_; size_t ncompacts_; size_t narcs_; ssize_t start_; RefCounter ref_count_; bool error_; }; template <class E, class U> template <class A, class C> DefaultCompactStore<E, U>::DefaultCompactStore(const Fst<A> &fst, const C &compactor) : states_region_(0), compacts_region_(0), states_(0), compacts_(0), nstates_(0), ncompacts_(0), narcs_(0), start_(kNoStateId), error_(false) { typedef typename A::StateId StateId; typedef typename A::Weight Weight; start_ = fst.Start(); // Count # of states and arcs. StateId nfinals = 0; for (StateIterator< Fst<A> > siter(fst); !siter.Done(); siter.Next()) { ++nstates_; StateId s = siter.Value(); for (ArcIterator< Fst<A> > aiter(fst, s); !aiter.Done(); aiter.Next()) ++narcs_; if (fst.Final(s) != Weight::Zero()) ++nfinals; } if (compactor.Size() == -1) { states_ = new Unsigned[nstates_ + 1]; ncompacts_ = narcs_ + nfinals; compacts_ = new CompactElement[ncompacts_]; states_[nstates_] = ncompacts_; } else { states_ = 0; ncompacts_ = nstates_ * compactor.Size(); if ((narcs_ + nfinals) != ncompacts_) { FSTERROR() << "DefaultCompactStore: compactor incompatible with fst"; error_ = true; return; } compacts_ = new CompactElement[ncompacts_]; } size_t pos = 0, fpos = 0; for (StateId s = 0; s < nstates_; ++s) { fpos = pos; if (compactor.Size() == -1) states_[s] = pos; if (fst.Final(s) != Weight::Zero()) compacts_[pos++] = compactor.Compact(s, A(kNoLabel, kNoLabel, fst.Final(s), kNoStateId)); for (ArcIterator< Fst<A> > aiter(fst, s); !aiter.Done(); aiter.Next()) { compacts_[pos++] = compactor.Compact(s, aiter.Value()); } if ((compactor.Size() != -1) && ((pos - fpos) != compactor.Size())) { FSTERROR() << "DefaultCompactStore: compactor incompatible with fst"; error_ = true; return; } } if (pos != ncompacts_) { FSTERROR() << "DefaultCompactStore: compactor incompatible with fst"; error_ = true; return; } } template <class E, class U> template <class Iterator, class C> DefaultCompactStore<E, U>::DefaultCompactStore(const Iterator &begin, const Iterator &end, const C &compactor) : states_region_(0), compacts_region_(0), states_(0), compacts_(0), nstates_(0), ncompacts_(0), narcs_(0), start_(kNoStateId), error_(false) { typedef typename C::Arc Arc; typedef typename Arc::Weight Weight; if (compactor.Size() != -1) { ncompacts_ = distance(begin, end); if (compactor.Size() == 1) { // For strings, allow implicit final weight. // Empty input is the empty string. if (ncompacts_ == 0) { ++ncompacts_; } else { Arc arc = compactor.Expand(ncompacts_ - 1, *(begin + (ncompacts_ - 1))); if (arc.ilabel != kNoLabel) ++ncompacts_; } } if (ncompacts_ % compactor.Size()) { FSTERROR() << "DefaultCompactStore: size of input container incompatible" << " with compactor"; error_ = true; return; } if (ncompacts_ == 0) return; start_ = 0; nstates_ = ncompacts_ / compactor.Size(); compacts_ = new CompactElement[ncompacts_]; size_t i = 0; Iterator it = begin; for(; it != end; ++it, ++i){ compacts_[i] = *it; if (compactor.Expand(i, *it).ilabel != kNoLabel) ++narcs_; } if (i < ncompacts_) compacts_[i] = compactor.Compact(i, Arc(kNoLabel, kNoLabel, Weight::One(), kNoStateId)); } else { if (distance(begin, end) == 0) return; // Count # of states, arcs and compacts. Iterator it = begin; for(size_t i = 0; it != end; ++it, ++i) { Arc arc = compactor.Expand(i, *it); if (arc.ilabel != kNoLabel) { ++narcs_; ++ncompacts_; } else { ++nstates_; if (arc.weight != Weight::Zero()) ++ncompacts_; } } start_ = 0; compacts_ = new CompactElement[ncompacts_]; states_ = new Unsigned[nstates_ + 1]; states_[nstates_] = ncompacts_; size_t i = 0, s = 0; for(it = begin; it != end; ++it) { Arc arc = compactor.Expand(i, *it); if (arc.ilabel != kNoLabel) { compacts_[i++] = *it; } else { states_[s++] = i; if (arc.weight != Weight::Zero()) compacts_[i++] = *it; } } if ((s != nstates_) || (i != ncompacts_)) { FSTERROR() << "DefaultCompactStore: ill-formed input container"; error_ = true; return; } } } template <class E, class U> template <class C> DefaultCompactStore<E, U> *DefaultCompactStore<E, U>::Read( istream &strm, const FstReadOptions &opts, const FstHeader &hdr, const C &compactor) { DefaultCompactStore<E, U> *data = new DefaultCompactStore<E, U>(); data->start_ = hdr.Start(); data->nstates_ = hdr.NumStates(); data->narcs_ = hdr.NumArcs(); if (compactor.Size() == -1) { if ((hdr.GetFlags() & FstHeader::IS_ALIGNED) && !AlignInput(strm)) { LOG(ERROR) << "DefaultCompactStore::Read: Alignment failed: " << opts.source; delete data; return 0; } size_t b = (data->nstates_ + 1) * sizeof(Unsigned); data->states_region_ = MappedFile::Map( &strm, opts.mode == FstReadOptions::MAP, opts.source, b); if (!strm || data->states_region_ == NULL) { LOG(ERROR) << "DefaultCompactStore::Read: Read failed: " << opts.source; delete data; return 0; } data->states_ = static_cast<Unsigned *>( data->states_region_->mutable_data()); } else { data->states_ = 0; } data->ncompacts_ = compactor.Size() == -1 ? data->states_[data->nstates_] : data->nstates_ * compactor.Size(); if ((hdr.GetFlags() & FstHeader::IS_ALIGNED) && !AlignInput(strm)) { LOG(ERROR) << "DefaultCompactStore::Read: Alignment failed: " << opts.source; delete data; return 0; } size_t b = data->ncompacts_ * sizeof(CompactElement); data->compacts_region_ = MappedFile::Map( &strm, opts.mode == FstReadOptions::MAP, opts.source, b); if (!strm || data->compacts_region_ == NULL) { LOG(ERROR) << "DefaultCompactStore::Read: Read failed: " << opts.source; delete data; return 0; } data->compacts_ = static_cast<CompactElement *>( data->compacts_region_->mutable_data()); return data; } template<class E, class U> bool DefaultCompactStore<E, U>::Write(ostream &strm, const FstWriteOptions &opts) const { if (states_) { if (opts.align && !AlignOutput(strm)) { LOG(ERROR) << "DefaultCompactStore::Write: Alignment failed: " << opts.source; return false; } strm.write(reinterpret_cast<char *>(states_), (nstates_ + 1) * sizeof(Unsigned)); } if (opts.align && !AlignOutput(strm)) { LOG(ERROR) << "DefaultCompactStore::Write: Alignment failed: " << opts.source; return false; } strm.write(reinterpret_cast<char *>(compacts_), ncompacts_ * sizeof(CompactElement)); strm.flush(); if (!strm) { LOG(ERROR) << "DefaultCompactStore::Write: Write failed: " << opts.source; return false; } return true; } template <class E, class U> const string &DefaultCompactStore<E, U>::Type() { static const string type = "compact"; return type; } template <class A, class C, class U, class S> class CompactFst; template <class F, class G> void Cast(const F &, G *); // Implementation class for CompactFst, which contains parametrizeable // Fst data storage (DefaultCompactStore by default) and Fst cache. template <class A, class C, class U, class S = DefaultCompactStore<typename C::Element, U> > class CompactFstImpl : public CacheImpl<A> { public: using FstImpl<A>::SetType; using FstImpl<A>::SetProperties; using FstImpl<A>::Properties; using FstImpl<A>::SetInputSymbols; using FstImpl<A>::SetOutputSymbols; using FstImpl<A>::WriteHeader; using CacheImpl<A>::PushArc; using CacheImpl<A>::HasArcs; using CacheImpl<A>::HasFinal; using CacheImpl<A>::HasStart; using CacheImpl<A>::SetArcs; using CacheImpl<A>::SetFinal; using CacheImpl<A>::SetStart; typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef C Compactor; typedef typename C::Element CompactElement; typedef U Unsigned; typedef S DataStorage; CompactFstImpl() : CacheImpl<A>(CompactFstOptions()), compactor_(0), own_compactor_(false), data_(0) { string type = "compact"; if (sizeof(U) != sizeof(uint32)) { string size; Int64ToStr(8 * sizeof(U), &size); type += size; } type += "_"; type += C::Type(); if (DataStorage::Type() != "compact") { type += "_"; type += DataStorage::Type(); } SetType(type); SetProperties(kNullProperties | kStaticProperties); } CompactFstImpl(const Fst<Arc> &fst, const C &compactor, const CompactFstOptions &opts) : CacheImpl<A>(opts), compactor_(new C(compactor)), own_compactor_(true), data_(0) { Init(fst); } CompactFstImpl(const Fst<Arc> &fst, C *compactor, const CompactFstOptions &opts) : CacheImpl<A>(opts), compactor_(compactor), own_compactor_(false), data_(0) { Init(fst); } template <class Iterator> CompactFstImpl(const Iterator &b, const Iterator &e, const C &compactor, const CompactFstOptions &opts) : CacheImpl<A>(opts), compactor_(new C(compactor)), own_compactor_(true), data_(0) { Init(b, e); } template <class Iterator> CompactFstImpl(const Iterator &b, const Iterator &e, C *compactor, const CompactFstOptions &opts) : CacheImpl<A>(opts), compactor_(compactor), own_compactor_(false), data_(0) { Init(b, e); } CompactFstImpl(const CompactFstImpl<A, C, U, S> &impl) : CacheImpl<A>(impl), compactor_(new C(*impl.compactor_)), own_compactor_(true), data_(impl.data_) { if (data_) data_->IncrRefCount(); SetType(impl.Type()); SetProperties(impl.Properties()); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); } ~CompactFstImpl(){ if (own_compactor_) delete compactor_; if (data_ && !data_->DecrRefCount()) delete data_; } StateId Start() { if (!HasStart()) { SetStart(data_->Start()); } return CacheImpl<A>::Start(); } Weight Final(StateId s) { if (HasFinal(s)) return CacheImpl<A>::Final(s); Arc arc(kNoLabel, kNoLabel, Weight::Zero(), kNoStateId); if ((compactor_->Size() != -1) || (data_->States(s) != data_->States(s + 1))) arc = ComputeArc(s, compactor_->Size() == -1 ? data_->States(s) : s * compactor_->Size()); return arc.ilabel == kNoLabel ? arc.weight : Weight::Zero(); } StateId NumStates() const { if (Properties(kError)) return 0; return data_->NumStates(); } size_t NumArcs(StateId s) { if (HasArcs(s)) return CacheImpl<A>::NumArcs(s); Unsigned i, num_arcs; if (compactor_->Size() == -1) { i = data_->States(s); num_arcs = data_->States(s + 1) - i; } else { i = s * compactor_->Size(); num_arcs = compactor_->Size(); } if (num_arcs > 0) { const A &arc = ComputeArc(s, i, kArcILabelValue); if (arc.ilabel == kNoStateId) { --num_arcs; } } return num_arcs; } size_t NumInputEpsilons(StateId s) { if (!HasArcs(s) && !Properties(kILabelSorted)) Expand(s); if (HasArcs(s)) return CacheImpl<A>::NumInputEpsilons(s); return CountEpsilons(s, false); } size_t NumOutputEpsilons(StateId s) { if (!HasArcs(s) && !Properties(kOLabelSorted)) Expand(s); if (HasArcs(s)) return CacheImpl<A>::NumOutputEpsilons(s); return CountEpsilons(s, true); } size_t CountEpsilons(StateId s, bool output_epsilons) { size_t begin = compactor_->Size() == -1 ? data_->States(s) : s * compactor_->Size(); size_t end = compactor_->Size() == -1 ? data_->States(s + 1) : (s + 1) * compactor_->Size(); size_t num_eps = 0; for (size_t i = begin; i < end; ++i) { const A &arc = ComputeArc( s, i, output_epsilons ? kArcOLabelValue : kArcILabelValue); const typename A::Label &label = (output_epsilons ? arc.olabel : arc.ilabel); if (label == kNoLabel) continue; else if (label > 0) break; ++num_eps; } return num_eps; } static CompactFstImpl<A, C, U, S> *Read(istream &strm, const FstReadOptions &opts) { CompactFstImpl<A, C, U, S> *impl = new CompactFstImpl<A, C, U, S>(); FstHeader hdr; if (!impl->ReadHeader(strm, opts, kMinFileVersion, &hdr)) { delete impl; return 0; } // Ensures compatibility if (hdr.Version() == kAlignedFileVersion) hdr.SetFlags(hdr.GetFlags() | FstHeader::IS_ALIGNED); impl->compactor_ = C::Read(strm); if (!impl->compactor_) { delete impl; return 0; } impl->own_compactor_ = true; impl->data_ = DataStorage::Read(strm, opts, hdr, *impl->compactor_); if (!impl->data_) { delete impl; return 0; } return impl; } bool Write(ostream &strm, const FstWriteOptions &opts) const { FstHeader hdr; hdr.SetStart(data_->Start()); hdr.SetNumStates(data_->NumStates()); hdr.SetNumArcs(data_->NumArcs()); // Ensures compatibility int file_version = opts.align ? kAlignedFileVersion : kFileVersion; WriteHeader(strm, opts, file_version, &hdr); compactor_->Write(strm); return data_->Write(strm, opts); } // Provide information needed for generic state iterator void InitStateIterator(StateIteratorData<A> *data) const { data->base = 0; data->nstates = data_->NumStates(); } void InitArcIterator(StateId s, ArcIteratorData<A> *data) { if (!HasArcs(s)) Expand(s); CacheImpl<A>::InitArcIterator(s, data); } Arc ComputeArc(StateId s, Unsigned i, uint32 f = kArcValueFlags) const { return compactor_->Expand(s, data_->Compacts(i), f); } void Expand(StateId s) { size_t begin = compactor_->Size() == -1 ? data_->States(s) : s * compactor_->Size(); size_t end = compactor_->Size() == -1 ? data_->States(s + 1) : (s + 1) * compactor_->Size(); for (size_t i = begin; i < end; ++i) { const Arc &arc = ComputeArc(s, i); if (arc.ilabel == kNoLabel) SetFinal(s, arc.weight); else PushArc(s, arc); } if (!HasFinal(s)) SetFinal(s, Weight::Zero()); SetArcs(s); } template <class Iterator> void SetCompactElements(const Iterator &b, const Iterator &e) { if (data_ && !data_->DecrRefCount()) delete data_; data_ = new DataStorage(b, e, *compactor_); } C *GetCompactor() const { return compactor_; } DataStorage *Data() const { return data_; } // Properties always true of this Fst class static const uint64 kStaticProperties = kExpanded; protected: template <class OtherA, class OtherC> explicit CompactFstImpl(const CompactFstImpl<OtherA, OtherC, U, S> &impl) : CacheImpl<A>(CacheOptions(impl.GetCacheGc(), impl.GetCacheLimit())), compactor_(new C(*impl.GetCompactor())), own_compactor_(true), data_(impl.Data()) { if (data_) data_->IncrRefCount(); SetType(impl.Type()); SetProperties(impl.Properties()); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); } private: friend class CompactFst<A, C, U, S>; // allow access during write. void Init(const Fst<Arc> &fst) { string type = "compact"; if (sizeof(U) != sizeof(uint32)) { string size; Int64ToStr(8 * sizeof(U), &size); type += size; } type += "_"; type += compactor_->Type(); if (DataStorage::Type() != "compact") { type += "_"; type += DataStorage::Type(); } SetType(type); SetInputSymbols(fst.InputSymbols()); SetOutputSymbols(fst.OutputSymbols()); data_ = new DataStorage(fst, *compactor_); if (data_->Error()) SetProperties(kError, kError); uint64 copy_properties = fst.Properties(kCopyProperties, true); if ((copy_properties & kError) || !compactor_->Compatible(fst)) { FSTERROR() << "CompactFstImpl: input fst incompatible with compactor"; SetProperties(kError, kError); return; } SetProperties(copy_properties | kStaticProperties); } template <class Iterator> void Init(const Iterator &b, const Iterator &e) { string type = "compact"; if (sizeof(U) != sizeof(uint32)) { string size; Int64ToStr(8 * sizeof(U), &size); type += size; } type += "_"; type += compactor_->Type(); SetType(type); SetProperties(kStaticProperties | compactor_->Properties()); data_ = new DataStorage(b, e, *compactor_); if (data_->Error()) SetProperties(kError, kError); } // Current unaligned file format version static const int kFileVersion = 2; // Current aligned file format version static const int kAlignedFileVersion = 1; // Minimum file format version supported static const int kMinFileVersion = 1; C *compactor_; bool own_compactor_; DataStorage *data_; }; template <class A, class C, class U, class S> const uint64 CompactFstImpl<A, C, U, S>::kStaticProperties; template <class A, class C, class U, class S> const int CompactFstImpl<A, C, U, S>::kFileVersion; template <class A, class C, class U, class S> const int CompactFstImpl<A, C, U, S>::kAlignedFileVersion; template <class A, class C, class U, class S> const int CompactFstImpl<A, C, U, S>::kMinFileVersion; // CompactFst. This class attaches interface to implementation and // handles reference counting, delegating most methods to // ImplToExpandedFst. The unsigned type U is used to represent indices // into the compact arc array. Type S represents the data storage. // (Template arg defaults declared in fst-decl.h.) template <class A, class C, class U /* = uint32 */, class S /* = DefaultCompactStore<typename C::Element, U> */> class CompactFst : public ImplToExpandedFst< CompactFstImpl<A, C, U, S> > { public: friend class StateIterator< CompactFst<A, C, U, S> >; friend class ArcIterator< CompactFst<A, C, U, S> >; template <class F, class G> void friend Cast(const F &, G *); typedef A Arc; typedef typename A::StateId StateId; typedef CompactFstImpl<A, C, U, S> Impl; typedef DefaultCacheStore<A> Store; typedef typename Store::State State; typedef U Unsigned; CompactFst() : ImplToExpandedFst<Impl>(new Impl()) {} explicit CompactFst(const Fst<A> &fst, const C &compactor = C(), const CompactFstOptions &opts = CompactFstOptions()) : ImplToExpandedFst<Impl>(new Impl(fst, compactor, opts)) {} CompactFst(const Fst<A> &fst, C *compactor, const CompactFstOptions &opts = CompactFstOptions()) : ImplToExpandedFst<Impl>(new Impl(fst, compactor, opts)) {} // The following 2 constructors take as input two iterators delimiting // a set of (already) compacted transitions, starting with the // transitions out of the initial state. The format of the input // differs for fixed out-degree and variable out-degree compactors. // // - For fixed out-degree compactors, the final weight (encoded as a // compacted transition) needs to be given only for final // states. All strings (compactor of size 1) will be assume to be // terminated by a final state even when the final state is not // implicitely given. // // - For variable out-degree compactors, the final weight (encoded // as a compacted transition) needs to be given for all states and // must appeared first in the list (for state s, final weight of s, // followed by outgoing transitons in s). // // These 2 constructors allows the direct construction of a CompactFst // without first creating a more memory hungry 'regular' FST. This // is useful when memory usage is severely constrained. template <class Iterator> explicit CompactFst(const Iterator &begin, const Iterator &end, const C &compactor = C(), const CompactFstOptions &opts = CompactFstOptions()) : ImplToExpandedFst<Impl>(new Impl(begin, end, compactor, opts)) {} template <class Iterator> CompactFst(const Iterator &begin, const Iterator &end, C *compactor, const CompactFstOptions &opts = CompactFstOptions()) : ImplToExpandedFst<Impl>(new Impl(begin, end, compactor, opts)) {} // See Fst<>::Copy() for doc. CompactFst(const CompactFst<A, C, U, S> &fst, bool safe = false) : ImplToExpandedFst<Impl>(fst, safe) {} // Get a copy of this CompactFst. See Fst<>::Copy() for further doc. virtual CompactFst<A, C, U, S> *Copy(bool safe = false) const { return new CompactFst<A, C, U, S>(*this, safe); } // Read a CompactFst from an input stream; return NULL on error static CompactFst<A, C, U, S> *Read(istream &strm, const FstReadOptions &opts) { Impl* impl = Impl::Read(strm, opts); return impl ? new CompactFst<A, C, U, S>(impl) : 0; } // Read a CompactFst from a file; return NULL on error // Empty filename reads from standard input static CompactFst<A, C, U, S> *Read(const string &filename) { Impl* impl = ImplToExpandedFst<Impl>::Read(filename); return impl ? new CompactFst<A, C, U, S>(impl) : 0; } virtual bool Write(ostream &strm, const FstWriteOptions &opts) const { return GetImpl()->Write(strm, opts); } virtual bool Write(const string &filename) const { return Fst<A>::WriteFile(filename); } template <class F> static bool WriteFst(const F &fst, const C &compactor, ostream &strm, const FstWriteOptions &opts); virtual void InitStateIterator(StateIteratorData<A> *data) const { GetImpl()->InitStateIterator(data); } virtual void InitArcIterator(StateId s, ArcIteratorData<A> *data) const { GetImpl()->InitArcIterator(s, data); } virtual MatcherBase<A> *InitMatcher(MatchType match_type) const { return new SortedMatcher<CompactFst<A, C, U, S> >(*this, match_type); } template <class Iterator> void SetCompactElements(const Iterator &b, const Iterator &e) { GetImpl()->SetCompactElements(b, e); } private: CompactFst(Impl *impl) : ImplToExpandedFst<Impl>(impl) {} // Makes visible to friends. Impl *GetImpl() const { return ImplToFst<Impl, ExpandedFst<A> >::GetImpl(); } void SetImpl(Impl *impl, bool own_impl = false) { ImplToFst< Impl, ExpandedFst<A> >::SetImpl(impl, own_impl); } // Use overloading to extract the type of the argument. static Impl* GetImplIfCompactFst(const CompactFst<A, C, U, S> &compact_fst) { return compact_fst.GetImpl(); } // This does not give privileged treatment to subclasses of CompactFst. template<typename NonCompactFst> static Impl* GetImplIfCompactFst(const NonCompactFst& fst) { return NULL; } void operator=(const CompactFst<A, C, U, S> &fst); // disallow }; // Writes Fst in Compact format, potentially with a pass over the machine // before writing to compute the number of states and arcs. // template <class A, class C, class U, class S> template <class F> bool CompactFst<A, C, U, S>::WriteFst(const F &fst, const C &compactor, ostream &strm, const FstWriteOptions &opts) { typedef U Unsigned; typedef typename C::Element CompactElement; typedef typename A::Weight Weight; int file_version = opts.align ? Impl::kAlignedFileVersion : Impl::kFileVersion; size_t num_arcs = -1, num_states = -1; C first_pass_compactor = compactor; if (Impl* impl = GetImplIfCompactFst(fst)) { num_arcs = impl->Data()->NumArcs(); num_states = impl->Data()->NumStates(); first_pass_compactor = *impl->GetCompactor(); } else { // A first pass is needed to compute the state of the compactor, which // is saved ahead of the rest of the data structures. This unfortunately // means forcing a complete double compaction when writing in this format. // TODO(allauzen): eliminate mutable state from compactors. num_arcs = 0; num_states = 0; for (StateIterator<F> siter(fst); !siter.Done(); siter.Next()) { const StateId s = siter.Value(); ++num_states; if (fst.Final(s) != Weight::Zero()) { first_pass_compactor.Compact( s, A(kNoLabel, kNoLabel, fst.Final(s), kNoStateId)); } for (ArcIterator<F> aiter(fst, s); !aiter.Done(); aiter.Next()) { ++num_arcs; first_pass_compactor.Compact(s, aiter.Value()); } } } FstHeader hdr; hdr.SetStart(fst.Start()); hdr.SetNumStates(num_states); hdr.SetNumArcs(num_arcs); string type = "compact"; if (sizeof(U) != sizeof(uint32)) { string size; Int64ToStr(8 * sizeof(U), &size); type += size; } type += "_"; type += C::Type(); if (S::Type() != "compact") { type += "_"; type += S::Type(); } uint64 copy_properties = fst.Properties(kCopyProperties, true); if ((copy_properties & kError) || !compactor.Compatible(fst)) { LOG(ERROR) << "fst incompatible with compactor"; return false; } uint64 properties = copy_properties | Impl::kStaticProperties; FstImpl<A>::WriteFstHeader(fst, strm, opts, file_version, type, properties, &hdr); first_pass_compactor.Write(strm); if (first_pass_compactor.Size() == -1) { if (opts.align && !AlignOutput(strm)) { LOG(ERROR) << "CompactFst::Write: Alignment failed: " << opts.source; return false; } Unsigned compacts = 0; for (StateIterator<F> siter(fst); !siter.Done(); siter.Next()) { const StateId s = siter.Value(); strm.write(reinterpret_cast<const char *>(&compacts), sizeof(compacts)); if (fst.Final(s) != Weight::Zero()) { ++compacts; } compacts += fst.NumArcs(s); } strm.write(reinterpret_cast<const char *>(&compacts), sizeof(compacts)); } if (opts.align && !AlignOutput(strm)) { LOG(ERROR) << "Could not align file during write after writing states"; } C second_pass_compactor = compactor; CompactElement element; for (StateIterator<F> siter(fst); !siter.Done(); siter.Next()) { const StateId s = siter.Value(); if (fst.Final(s) != Weight::Zero()) { element = second_pass_compactor.Compact( s, A(kNoLabel, kNoLabel, fst.Final(s), kNoStateId)); strm.write(reinterpret_cast<const char *>(&element), sizeof(element)); } for (ArcIterator<F> aiter(fst, s); !aiter.Done(); aiter.Next()) { element = second_pass_compactor.Compact(s, aiter.Value()); strm.write(reinterpret_cast<const char *>(&element), sizeof(element)); } } strm.flush(); if (!strm) { LOG(ERROR) << "CompactFst write failed: " << opts.source; return false; } return true; } // Specialization for CompactFst; see generic version in fst.h // for sample usage (but use the CompactFst type!). This version // should inline. template <class A, class C, class U> class StateIterator< CompactFst<A, C, U> > { public: typedef typename A::StateId StateId; explicit StateIterator(const CompactFst<A, C, U> &fst) : nstates_(fst.GetImpl()->NumStates()), s_(0) {} bool Done() const { return s_ >= nstates_; } StateId Value() const { return s_; } void Next() { ++s_; } void Reset() { s_ = 0; } private: StateId nstates_; StateId s_; DISALLOW_COPY_AND_ASSIGN(StateIterator); }; // Specialization for CompactFst. // Never caches, always iterates over the underlying compact elements. template <class A, class C, class U> class ArcIterator< CompactFst<A, C, U> > { public: typedef typename A::StateId StateId; typedef typename C::Element CompactElement; ArcIterator(const CompactFst<A, C, U> &fst, StateId s) : compactor_(fst.GetImpl()->GetCompactor()), state_(s), compacts_(0), pos_(0), flags_(kArcValueFlags) { const DefaultCompactStore<CompactElement, U> *data = fst.GetImpl()->Data(); size_t offset; if (compactor_->Size() == -1) { // Variable out-degree compactor offset = data->States(s); num_arcs_ = data->States(s + 1) - offset; } else { // Fixed out-degree compactor offset = s * compactor_->Size(); num_arcs_ = compactor_->Size(); } if (num_arcs_ > 0) { compacts_ = &(data->Compacts(offset)); arc_ = compactor_->Expand(s, *compacts_, kArcILabelValue); if (arc_.ilabel == kNoStateId) { ++compacts_; --num_arcs_; } } } ~ArcIterator() {} bool Done() const { return pos_ >= num_arcs_; } const A& Value() const { arc_ = compactor_->Expand(state_, compacts_[pos_], flags_); return arc_; } void Next() { ++pos_; } size_t Position() const { return pos_; } void Reset() { pos_ = 0; } void Seek(size_t pos) { pos_ = pos; } uint32 Flags() const { return flags_; } void SetFlags(uint32 f, uint32 m) { flags_ &= ~m; flags_ |= (f & kArcValueFlags); } private: C *compactor_; StateId state_; const CompactElement *compacts_; size_t pos_; size_t num_arcs_; mutable A arc_; uint32 flags_; DISALLOW_COPY_AND_ASSIGN(ArcIterator); }; // // Specialization for CompactFst. // // This is an optionally caching arc iterator. // // TODO(allauzen): implements the kArcValueFlags, the current // // implementation only implements the kArcNoCache flag. // template <class A, class C, class U> // class ArcIterator< CompactFst<A, C, U> > { // public: // typedef typename A::StateId StateId; // ArcIterator(const CompactFst<A, C, U> &fst, StateId s) // : fst_(fst), state_(s), pos_(0), num_arcs_(0), offset_(0), // flags_(kArcValueFlags) { // cache_data_.ref_count = 0; // if (fst_.GetImpl()->HasArcs(state_)) { // fst_.GetImpl()->InitArcIterator(s, &cache_data_); // num_arcs_ = cache_data_.narcs; // return; // } // const C *compactor = fst_.GetImpl()->GetCompactor(); // const DefaultCompactStore<A, C, U> *data = fst_.GetImpl()->Data(); // if (compactor->Size() == -1) { // Variable out-degree compactor // offset_ = data->States(s); // num_arcs_ = data->States(s + 1) - offset_; // } else { // Fixed out-degree compactor // offset_ = s * compactor->Size(); // num_arcs_ = compactor->Size(); // } // if (num_arcs_ > 0) { // const A &arc = fst_.GetImpl()->ComputeArc(s, offset_); // if (arc.ilabel == kNoStateId) { // ++offset_; // --num_arcs_; // } // } // } // ~ArcIterator() { // if (cache_data_.ref_count) // --(*cache_data_.ref_count); // } // bool Done() const { return pos_ >= num_arcs_; } // const A& Value() const { // if (cache_data_.ref_count == 0) { // if (flags_ & kArcNoCache) { // arc_ = fst_.GetImpl()->ComputeArc(state_, pos_ + offset_); // return arc_; // } else { // fst_.GetImpl()->InitArcIterator(state_, &cache_data_); // } // } // return cache_data_.arcs[pos_]; // } // void Next() { ++pos_; } // size_t Position() const { return pos_; } // void Reset() { pos_ = 0; } // void Seek(size_t pos) { pos_ = pos; } // uint32 Flags() const { return flags_; } // void SetFlags(uint32 f, uint32 m) { // flags_ &= ~m; // flags_ |= f; // if (!(flags_ & kArcNoCache) && cache_data_.ref_count == 0) // fst_.GetImpl()->InitArcIterator(state_, &cache_data_); // } // private: // mutable const CompactFst<A, C, U> &fst_; // StateId state_; // size_t pos_; // size_t num_arcs_; // size_t offset_; // uint32 flags_; // mutable A arc_; // mutable ArcIteratorData<A> cache_data_; // DISALLOW_COPY_AND_ASSIGN(ArcIterator); // }; // // Utility Compactors // // Compactor for unweighted string FSTs template <class A> class StringCompactor { public: typedef A Arc; typedef typename A::Label Element; typedef typename A::Label Label; typedef typename A::StateId StateId; typedef typename A::Weight Weight; Element Compact(StateId s, const A &arc) const { return arc.ilabel; } Arc Expand(StateId s, const Element &p, uint32 f = kArcValueFlags) const { return Arc(p, p, Weight::One(), p != kNoLabel ? s + 1 : kNoStateId); } ssize_t Size() const { return 1; } uint64 Properties() const { return kString | kAcceptor | kUnweighted; } bool Compatible(const Fst<A> &fst) const { uint64 props = Properties(); return fst.Properties(props, true) == props; } static const string &Type() { static const string type = "string"; return type; } bool Write(ostream &strm) const { return true; } static StringCompactor *Read(istream &strm) { return new StringCompactor; } }; // Compactor for weighted string FSTs template <class A> class WeightedStringCompactor { public: typedef A Arc; typedef typename A::Label Label; typedef typename A::StateId StateId; typedef typename A::Weight Weight; typedef pair<Label, Weight> Element; Element Compact(StateId s, const A &arc) const { return make_pair(arc.ilabel, arc.weight); } Arc Expand(StateId s, const Element &p, uint32 f = kArcValueFlags) const { return Arc(p.first, p.first, p.second, p.first != kNoLabel ? s + 1 : kNoStateId); } ssize_t Size() const { return 1;} uint64 Properties() const { return kString | kAcceptor; } bool Compatible(const Fst<A> &fst) const { uint64 props = Properties(); return fst.Properties(props, true) == props; } static const string &Type() { static const string type = "weighted_string"; return type; } bool Write(ostream &strm) const { return true; } static WeightedStringCompactor *Read(istream &strm) { return new WeightedStringCompactor; } }; // Compactor for unweighted acceptor FSTs template <class A> class UnweightedAcceptorCompactor { public: typedef A Arc; typedef typename A::Label Label; typedef typename A::StateId StateId; typedef typename A::Weight Weight; typedef pair<Label, StateId> Element; Element Compact(StateId s, const A &arc) const { return make_pair(arc.ilabel, arc.nextstate); } Arc Expand(StateId s, const Element &p, uint32 f = kArcValueFlags) const { return Arc(p.first, p.first, Weight::One(), p.second); } ssize_t Size() const { return -1;} uint64 Properties() const { return kAcceptor | kUnweighted; } bool Compatible(const Fst<A> &fst) const { uint64 props = Properties(); return fst.Properties(props, true) == props; } static const string &Type() { static const string type = "unweighted_acceptor"; return type; } bool Write(ostream &strm) const { return true; } static UnweightedAcceptorCompactor *Read(istream &istrm) { return new UnweightedAcceptorCompactor; } }; // Compactor for weighted acceptor FSTs template <class A> class AcceptorCompactor { public: typedef A Arc; typedef typename A::Label Label; typedef typename A::StateId StateId; typedef typename A::Weight Weight; typedef pair< pair<Label, Weight>, StateId > Element; Element Compact(StateId s, const A &arc) const { return make_pair(make_pair(arc.ilabel, arc.weight), arc.nextstate); } Arc Expand(StateId s, const Element &p, uint32 f = kArcValueFlags) const { return Arc(p.first.first, p.first.first, p.first.second, p.second); } ssize_t Size() const { return -1;} uint64 Properties() const { return kAcceptor; } bool Compatible(const Fst<A> &fst) const { uint64 props = Properties(); return fst.Properties(props, true) == props; } static const string &Type() { static const string type = "acceptor"; return type; } bool Write(ostream &strm) const { return true; } static AcceptorCompactor *Read(istream &strm) { return new AcceptorCompactor; } }; // Compactor for unweighted FSTs template <class A> class UnweightedCompactor { public: typedef A Arc; typedef typename A::Label Label; typedef typename A::StateId StateId; typedef typename A::Weight Weight; typedef pair< pair<Label, Label>, StateId > Element; Element Compact(StateId s, const A &arc) const { return make_pair(make_pair(arc.ilabel, arc.olabel), arc.nextstate); } Arc Expand(StateId s, const Element &p, uint32 f = kArcValueFlags) const { return Arc(p.first.first, p.first.second, Weight::One(), p.second); } ssize_t Size() const { return -1; } uint64 Properties() const { return kUnweighted; } bool Compatible(const Fst<A> &fst) const { uint64 props = Properties(); return fst.Properties(props, true) == props; } static const string &Type() { static const string type = "unweighted"; return type; } bool Write(ostream &strm) const { return true; } static UnweightedCompactor *Read(istream &strm) { return new UnweightedCompactor; } }; // Useful aliases when using StdArc typedef CompactFst<StdArc, StringCompactor<StdArc> > StdCompactStringFst; typedef CompactFst<StdArc, WeightedStringCompactor<StdArc> > StdCompactWeightedStringFst; typedef CompactFst<StdArc, AcceptorCompactor<StdArc> > StdCompactAcceptorFst; typedef CompactFst<StdArc, UnweightedCompactor<StdArc> > StdCompactUnweightedFst; typedef CompactFst<StdArc, UnweightedAcceptorCompactor<StdArc> > StdCompactUnweightedAcceptorFst; } // namespace fst #endif // FST_LIB_COMPACT_FST_H__ <|start_filename|>third_party/openfst/src/script/difference.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/difference.h> namespace fst { namespace script { void Difference(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, ComposeFilter compose_filter) { if (!ArcTypesMatch(ifst1, ifst2, "Difference") || !ArcTypesMatch(*ofst, ifst1, "Difference")) return; DifferenceArgs1 args(ifst1, ifst2, ofst, compose_filter); Apply<Operation<DifferenceArgs1> >("Difference", ifst1.ArcType(), &args); } void Difference(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &copts) { if (!ArcTypesMatch(ifst1, ifst2, "Difference") || !ArcTypesMatch(*ofst, ifst1, "Difference")) return; DifferenceArgs2 args(ifst1, ifst2, ofst, copts); Apply<Operation<DifferenceArgs2> >("Difference", ifst1.ArcType(), &args); } REGISTER_FST_OPERATION(Difference, StdArc, DifferenceArgs1); REGISTER_FST_OPERATION(Difference, LogArc, DifferenceArgs1); REGISTER_FST_OPERATION(Difference, Log64Arc, DifferenceArgs1); REGISTER_FST_OPERATION(Difference, StdArc, DifferenceArgs2); REGISTER_FST_OPERATION(Difference, LogArc, DifferenceArgs2); REGISTER_FST_OPERATION(Difference, Log64Arc, DifferenceArgs2); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/heap.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // All Rights Reserved. // Author: <NAME> (<EMAIL>) // // \file // Implementation of a heap as in STL, but allows tracking positions // in heap using a key. The key can be used to do an in-place update of // values in the heap. #ifndef FST_LIB_HEAP_H__ #define FST_LIB_HEAP_H__ #include <vector> using std::vector; #include <functional> #include <fst/compat.h> namespace fst { // // \class Heap // \brief A templated heap implementation that support in-place update // of values. // // The templated heap implementation is a little different from the // STL priority_queue and the *_heap operations in STL. This heap // supports indexing of values in the heap via an associated key. // // Each value is internally associated with a key which is returned // to the calling functions on heap insert. This key can be used // to later update the specific value in the heap. // // \param T the element type of the hash, can be POD, Data or Ptr to Data // \param Compare Comparison class for determiningg min-heapness. // \param whether heap top should be max or min element w.r.t. Compare // static const int kNoKey = -1; template <class T, class Compare, bool max> class Heap { public: // Initialize with a specific comparator Heap(Compare comp) : comp_(comp), size_(0) { } // Create a heap with initial size of internal arrays of 0 Heap() : size_(0) { } ~Heap() { } // Insert a value into the heap int Insert(const T& val) { if (size_ < A_.size()) { A_[size_] = val; pos_[key_[size_]] = size_; } else { A_.push_back(val); pos_.push_back(size_); key_.push_back(size_); } ++size_; return Insert(val, size_ - 1); } // Update a value at position given by the key. The pos array is first // indexed by the key. The position gives the position in the heap array. // Once we have the position we can then use the standard heap operations // to calculate the parent and child positions. void Update(int key, const T& val) { int i = pos_[key]; if (Better(val, A_[Parent(i)])) { Insert(val, i); } else { A_[i] = val; Heapify(i); } } // Return the greatest (max=true) / least (max=false) value w.r.t. // from the heap. T Pop() { T top = A_[0]; Swap(0, size_-1); size_--; Heapify(0); return top; } // Return the greatest (max=true) / least (max=false) value w.r.t. // comp object from the heap. T Top() const { return A_[0]; } // Check if the heap is empty bool Empty() const { return size_ == 0; } void Clear() { size_ = 0; } // // The following protected routines are used in a supportive role // for managing the heap and keeping the heap properties. // private: // Compute left child of parent int Left(int i) { return 2*(i+1)-1; // 0 -> 1, 1 -> 3 } // Compute right child of parent int Right(int i) { return 2*(i+1); // 0 -> 2, 1 -> 4 } // Given a child compute parent int Parent(int i) { return (i-1)/2; // 1 -> 0, 2 -> 0, 3 -> 1, 4-> 1 } // Swap a child, parent. Use to move element up/down tree. // Note a little tricky here. When we swap we need to swap: // the value // the associated keys // the position of the value in the heap void Swap(int j, int k) { int tkey = key_[j]; pos_[key_[j] = key_[k]] = j; pos_[key_[k] = tkey] = k; T val = A_[j]; A_[j] = A_[k]; A_[k] = val; } // Returns the greater (max=true) / least (max=false) of two // elements. bool Better(const T& x, const T& y) { return max ? comp_(y, x) : comp_(x, y); } // Heapify subtree rooted at index i. void Heapify(int i) { int l = Left(i); int r = Right(i); int largest; if (l < size_ && Better(A_[l], A_[i]) ) largest = l; else largest = i; if (r < size_ && Better(A_[r], A_[largest]) ) largest = r; if (largest != i) { Swap(i, largest); Heapify(largest); } } // Insert (update) element at subtree rooted at index i int Insert(const T& val, int i) { int p; while (i > 0 && !Better(A_[p = Parent(i)], val)) { Swap(i, p); i = p; } return key_[i]; } private: Compare comp_; vector<int> pos_; vector<int> key_; vector<T> A_; int size_; // DISALLOW_COPY_AND_ASSIGN(Heap); }; } // namespace fst #endif // FST_LIB_HEAP_H__ <|start_filename|>third_party/openfst/src/include/fst/project.h<|end_filename|> // project.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Functions and classes to project an Fst on to its domain or range. #ifndef FST_LIB_PROJECT_H__ #define FST_LIB_PROJECT_H__ #include <fst/arc-map.h> #include <fst/mutable-fst.h> namespace fst { // This specifies whether to project on input or output. enum ProjectType { PROJECT_INPUT = 1, PROJECT_OUTPUT = 2 }; // Mapper to implement projection per arc. template <class A> class ProjectMapper { public: explicit ProjectMapper(ProjectType project_type) : project_type_(project_type) {} A operator()(const A &arc) { typename A::Label label = project_type_ == PROJECT_INPUT ? arc.ilabel : arc.olabel; return A(label, label, arc.weight, arc.nextstate); } MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } MapSymbolsAction InputSymbolsAction() const { return project_type_ == PROJECT_INPUT ? MAP_COPY_SYMBOLS : MAP_CLEAR_SYMBOLS; } MapSymbolsAction OutputSymbolsAction() const { return project_type_ == PROJECT_OUTPUT ? MAP_COPY_SYMBOLS : MAP_CLEAR_SYMBOLS; } uint64 Properties(uint64 props) { return ProjectProperties(props, project_type_ == PROJECT_INPUT); } private: ProjectType project_type_; }; // Projects an FST onto its domain or range by either copying each arcs' // input label to the output label or vice versa. This version modifies // its input. // // Complexity: // - Time: O(V + E) // - Space: O(1) // where V = # of states and E = # of arcs. template<class Arc> inline void Project(MutableFst<Arc> *fst, ProjectType project_type) { ArcMap(fst, ProjectMapper<Arc>(project_type)); if (project_type == PROJECT_INPUT) fst->SetOutputSymbols(fst->InputSymbols()); if (project_type == PROJECT_OUTPUT) fst->SetInputSymbols(fst->OutputSymbols()); } // Projects an FST onto its domain or range by either copying each arc's // input label to the output label or vice versa. This version is a delayed // Fst. // // Complexity: // - Time: O(v + e) // - Space: O(1) // where v = # of states visited, e = # of arcs visited. Constant // time and to visit an input state or arc is assumed and exclusive // of caching. template <class A> class ProjectFst : public ArcMapFst<A, A, ProjectMapper<A> > { public: typedef A Arc; typedef ProjectMapper<A> C; typedef ArcMapFstImpl< A, A, ProjectMapper<A> > Impl; using ImplToFst<Impl>::GetImpl; ProjectFst(const Fst<A> &fst, ProjectType project_type) : ArcMapFst<A, A, C>(fst, C(project_type)) { if (project_type == PROJECT_INPUT) GetImpl()->SetOutputSymbols(fst.InputSymbols()); if (project_type == PROJECT_OUTPUT) GetImpl()->SetInputSymbols(fst.OutputSymbols()); } // See Fst<>::Copy() for doc. ProjectFst(const ProjectFst<A> &fst, bool safe = false) : ArcMapFst<A, A, C>(fst, safe) {} // Get a copy of this ProjectFst. See Fst<>::Copy() for further doc. virtual ProjectFst<A> *Copy(bool safe = false) const { return new ProjectFst(*this, safe); } }; // Specialization for ProjectFst. template <class A> class StateIterator< ProjectFst<A> > : public StateIterator< ArcMapFst<A, A, ProjectMapper<A> > > { public: explicit StateIterator(const ProjectFst<A> &fst) : StateIterator< ArcMapFst<A, A, ProjectMapper<A> > >(fst) {} }; // Specialization for ProjectFst. template <class A> class ArcIterator< ProjectFst<A> > : public ArcIterator< ArcMapFst<A, A, ProjectMapper<A> > > { public: ArcIterator(const ProjectFst<A> &fst, typename A::StateId s) : ArcIterator< ArcMapFst<A, A, ProjectMapper<A> > >(fst, s) {} }; // Useful alias when using StdArc. typedef ProjectFst<StdArc> StdProjectFst; } // namespace fst #endif // FST_LIB_PROJECT_H__ <|start_filename|>third_party/openfst/src/include/fst/rational.h<|end_filename|> // rational.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // An Fst implementation and base interface for delayed unions, // concatenations and closures. #ifndef FST_LIB_RATIONAL_H__ #define FST_LIB_RATIONAL_H__ #include <algorithm> #include <string> #include <vector> using std::vector; #include <fst/mutable-fst.h> #include <fst/replace.h> #include <fst/test-properties.h> namespace fst { typedef CacheOptions RationalFstOptions; // This specifies whether to add the empty string. enum ClosureType { CLOSURE_STAR = 0, // T* -> add the empty string CLOSURE_PLUS = 1 }; // T+ -> don't add the empty string template <class A> class RationalFst; template <class A> void Union(RationalFst<A> *fst1, const Fst<A> &fst2); template <class A> void Concat(RationalFst<A> *fst1, const Fst<A> &fst2); template <class A> void Concat(const Fst<A> &fst1, RationalFst<A> *fst2); template <class A> void Closure(RationalFst<A> *fst, ClosureType closure_type); // Implementation class for delayed unions, concatenations and closures. template<class A> class RationalFstImpl : public FstImpl<A> { public: using FstImpl<A>::SetType; using FstImpl<A>::SetProperties; using FstImpl<A>::WriteHeader; using FstImpl<A>::SetInputSymbols; using FstImpl<A>::SetOutputSymbols; typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef typename A::Label Label; explicit RationalFstImpl(const RationalFstOptions &opts) : nonterminals_(0), replace_(0), replace_options_(opts, 0) { SetType("rational"); fst_tuples_.push_back(pair<Label, const Fst<A>*>(0, 0)); } RationalFstImpl(const RationalFstImpl<A> &impl) : rfst_(impl.rfst_), nonterminals_(impl.nonterminals_), replace_(impl.replace_ ? impl.replace_->Copy(true) : 0), replace_options_(impl.replace_options_) { SetType("rational"); fst_tuples_.reserve(impl.fst_tuples_.size()); for (size_t i = 0; i < impl.fst_tuples_.size(); ++i) fst_tuples_.push_back(make_pair(impl.fst_tuples_[i].first, impl.fst_tuples_[i].second ? impl.fst_tuples_[i].second->Copy(true) : 0)); } virtual ~RationalFstImpl() { for (size_t i = 0; i < fst_tuples_.size(); ++i) if (fst_tuples_[i].second) delete fst_tuples_[i].second; if (replace_) delete replace_; } StateId Start() { return Replace()->Start(); } Weight Final(StateId s) { return Replace()->Final(s); } size_t NumArcs(StateId s) { return Replace()->NumArcs(s); } size_t NumInputEpsilons(StateId s) { return Replace()->NumInputEpsilons(s); } size_t NumOutputEpsilons(StateId s) { return Replace()->NumOutputEpsilons(s); } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if ((mask & kError) && Replace()->Properties(kError, false)) SetProperties(kError, kError); return FstImpl<Arc>::Properties(mask); } // Implementation of UnionFst(fst1,fst2) void InitUnion(const Fst<A> &fst1, const Fst<A> &fst2) { if (replace_) delete replace_; uint64 props1 = fst1.Properties(kFstProperties, false); uint64 props2 = fst2.Properties(kFstProperties, false); SetInputSymbols(fst1.InputSymbols()); SetOutputSymbols(fst1.OutputSymbols()); rfst_.AddState(); rfst_.AddState(); rfst_.SetStart(0); rfst_.SetFinal(1, Weight::One()); rfst_.SetInputSymbols(fst1.InputSymbols()); rfst_.SetOutputSymbols(fst1.OutputSymbols()); nonterminals_ = 2; rfst_.AddArc(0, A(0, -1, Weight::One(), 1)); rfst_.AddArc(0, A(0, -2, Weight::One(), 1)); fst_tuples_.push_back(make_pair(-1, fst1.Copy())); fst_tuples_.push_back(make_pair(-2, fst2.Copy())); SetProperties(UnionProperties(props1, props2, true), kCopyProperties); } // Implementation of ConcatFst(fst1,fst2) void InitConcat(const Fst<A> &fst1, const Fst<A> &fst2) { if (replace_) delete replace_; uint64 props1 = fst1.Properties(kFstProperties, false); uint64 props2 = fst2.Properties(kFstProperties, false); SetInputSymbols(fst1.InputSymbols()); SetOutputSymbols(fst1.OutputSymbols()); rfst_.AddState(); rfst_.AddState(); rfst_.AddState(); rfst_.SetStart(0); rfst_.SetFinal(2, Weight::One()); rfst_.SetInputSymbols(fst1.InputSymbols()); rfst_.SetOutputSymbols(fst1.OutputSymbols()); nonterminals_ = 2; rfst_.AddArc(0, A(0, -1, Weight::One(), 1)); rfst_.AddArc(1, A(0, -2, Weight::One(), 2)); fst_tuples_.push_back(make_pair(-1, fst1.Copy())); fst_tuples_.push_back(make_pair(-2, fst2.Copy())); SetProperties(ConcatProperties(props1, props2, true), kCopyProperties); } // Implementation of ClosureFst(fst, closure_type) void InitClosure(const Fst<A> &fst, ClosureType closure_type) { if (replace_) delete replace_; uint64 props = fst.Properties(kFstProperties, false); SetInputSymbols(fst.InputSymbols()); SetOutputSymbols(fst.OutputSymbols()); if (closure_type == CLOSURE_STAR) { rfst_.AddState(); rfst_.SetStart(0); rfst_.SetFinal(0, Weight::One()); rfst_.AddArc(0, A(0, -1, Weight::One(), 0)); } else { rfst_.AddState(); rfst_.AddState(); rfst_.SetStart(0); rfst_.SetFinal(1, Weight::One()); rfst_.AddArc(0, A(0, -1, Weight::One(), 1)); rfst_.AddArc(1, A(0, 0, Weight::One(), 0)); } rfst_.SetInputSymbols(fst.InputSymbols()); rfst_.SetOutputSymbols(fst.OutputSymbols()); fst_tuples_.push_back(make_pair(-1, fst.Copy())); nonterminals_ = 1; SetProperties(ClosureProperties(props, closure_type == CLOSURE_STAR, true), kCopyProperties); } // Implementation of Union(Fst &, RationalFst *) void AddUnion(const Fst<A> &fst) { if (replace_) delete replace_; uint64 props1 = FstImpl<A>::Properties(); uint64 props2 = fst.Properties(kFstProperties, false); VectorFst<A> afst; afst.AddState(); afst.AddState(); afst.SetStart(0); afst.SetFinal(1, Weight::One()); ++nonterminals_; afst.AddArc(0, A(0, -nonterminals_, Weight::One(), 1)); Union(&rfst_, afst); fst_tuples_.push_back(make_pair(-nonterminals_, fst.Copy())); SetProperties(UnionProperties(props1, props2, true), kCopyProperties); } // Implementation of Concat(Fst &, RationalFst *) void AddConcat(const Fst<A> &fst, bool append) { if (replace_) delete replace_; uint64 props1 = FstImpl<A>::Properties(); uint64 props2 = fst.Properties(kFstProperties, false); VectorFst<A> afst; afst.AddState(); afst.AddState(); afst.SetStart(0); afst.SetFinal(1, Weight::One()); ++nonterminals_; afst.AddArc(0, A(0, -nonterminals_, Weight::One(), 1)); if (append) Concat(&rfst_, afst); else Concat(afst, &rfst_); fst_tuples_.push_back(make_pair(-nonterminals_, fst.Copy())); SetProperties(ConcatProperties(props1, props2, true), kCopyProperties); } // Implementation of Closure(RationalFst *, closure_type) void AddClosure(ClosureType closure_type) { if (replace_) delete replace_; uint64 props = FstImpl<A>::Properties(); Closure(&rfst_, closure_type); SetProperties(ClosureProperties(props, closure_type == CLOSURE_STAR, true), kCopyProperties); } // Returns the underlying ReplaceFst. ReplaceFst<A> *Replace() const { if (!replace_) { fst_tuples_[0].second = rfst_.Copy(); replace_ = new ReplaceFst<A>(fst_tuples_, replace_options_); } return replace_; } private: VectorFst<A> rfst_; // rational topology machine; uses neg. nonterminals Label nonterminals_; // # of nonterminals used // Contains the nonterminals and their corresponding FSTs. mutable vector<pair<Label, const Fst<A>*> > fst_tuples_; mutable ReplaceFst<A> *replace_; // Underlying ReplaceFst ReplaceFstOptions<A> replace_options_; // Options for creating 'replace_' void operator=(const RationalFstImpl<A> &impl); // disallow }; // Parent class for the delayed rational operations - delayed union, // concatenation, and closure. // // This class attaches interface to implementation and handles // reference counting, delegating most methods to ImplToFst. template <class A> class RationalFst : public ImplToFst< RationalFstImpl<A> > { public: friend class StateIterator< RationalFst<A> >; friend class ArcIterator< RationalFst<A> >; friend void Union<>(RationalFst<A> *fst1, const Fst<A> &fst2); friend void Concat<>(RationalFst<A> *fst1, const Fst<A> &fst2); friend void Concat<>(const Fst<A> &fst1, RationalFst<A> *fst2); friend void Closure<>(RationalFst<A> *fst, ClosureType closure_type); typedef A Arc; typedef typename A::StateId StateId; typedef RationalFstImpl<A> Impl; virtual void InitStateIterator(StateIteratorData<A> *data) const { GetImpl()->Replace()->InitStateIterator(data); } virtual void InitArcIterator(StateId s, ArcIteratorData<A> *data) const { GetImpl()->Replace()->InitArcIterator(s, data); } protected: RationalFst() : ImplToFst<Impl>(new Impl(RationalFstOptions())) {} explicit RationalFst(const RationalFstOptions &opts) : ImplToFst<Impl>(new Impl(opts)) {} // See Fst<>::Copy() for doc. RationalFst(const RationalFst<A> &fst , bool safe = false) : ImplToFst<Impl>(fst, safe) {} private: // Makes visible to friends. Impl *GetImpl() const { return ImplToFst<Impl>::GetImpl(); } void operator=(const RationalFst<A> &fst); // disallow }; // Specialization for RationalFst. template <class A> class StateIterator< RationalFst<A> > : public StateIterator< ReplaceFst<A> > { public: explicit StateIterator(const RationalFst<A> &fst) : StateIterator< ReplaceFst<A> >(*(fst.GetImpl()->Replace())) {} }; // Specialization for RationalFst. template <class A> class ArcIterator< RationalFst<A> > : public CacheArcIterator< ReplaceFst<A> > { public: typedef typename A::StateId StateId; ArcIterator(const RationalFst<A> &fst, StateId s) : ArcIterator< ReplaceFst<A> >(*(fst.GetImpl()->Replace()), s) {} }; } // namespace fst #endif // FST_LIB_RATIONAL_H__ <|start_filename|>third_party/openfst/src/script/draw.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <string> #include <fst/script/fst-class.h> #include <fst/script/draw.h> #include <fst/script/script-impl.h> namespace fst { namespace script { void DrawFst(const FstClass &fst, const SymbolTable *isyms, const SymbolTable *osyms, const SymbolTable *ssyms, bool accep, const string &title, float width, float height, bool portrait, bool vertical, float ranksep, float nodesep, int fontsize, int precision, bool show_weight_one, ostream *ostrm, const string &dest) { FstDrawerArgs args(fst, isyms, osyms, ssyms, accep, title, width, height, portrait, vertical, ranksep, nodesep, fontsize, precision, show_weight_one, ostrm, dest); Apply<Operation<FstDrawerArgs> >("DrawFst", fst.ArcType(), &args); } REGISTER_FST_OPERATION(DrawFst, StdArc, FstDrawerArgs); REGISTER_FST_OPERATION(DrawFst, LogArc, FstDrawerArgs); REGISTER_FST_OPERATION(DrawFst, Log64Arc, FstDrawerArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/extensions/linear/fstloglinearapply.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: wuke #include <fst/compat.h> #include <fst/extensions/linear/linear-fst.h> #include <fst/extensions/linear/loglinear-apply.h> #include <fst/vector-fst.h> DEFINE_bool(normalize, true, "Normalize to get posterior"); int main(int argc, char **argv) { string usage = "Applies an FST to another FST, treating the second as a log-linear " "model.\n\n " "Usage: "; usage += argv[0]; usage += " in.fst linear.fst [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 3 || argc > 4) { ShowUsage(); return 1; } string in_name = strcmp(argv[1], "-") != 0 ? argv[1] : ""; string linear_name = (argc > 2 && (strcmp(argv[2], "-") != 0)) ? argv[2] : ""; string out_name = argc > 3 ? argv[3] : ""; if (in_name.empty() && linear_name.empty()) { LOG(ERROR) << argv[0] << ": Can't take both inputs from standard input."; return 1; } fst::StdFst *ifst1 = fst::StdFst::Read(in_name); if (!ifst1) return 1; fst::StdFst *ifst2 = fst::StdFst::Read(linear_name); if (!ifst2) return 1; fst::StdVectorFst ofst; LogLinearApply(*ifst1, *ifst2, &ofst, FLAGS_normalize); ofst.Write(out_name); return 0; } <|start_filename|>third_party/openfst/src/extensions/far/farequal.cc<|end_filename|> // farequal.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Tests if two Far files contains the same (key,fst) pairs. #include <fst/extensions/far/main.h> #include <fst/extensions/far/farscript.h> DEFINE_string(begin_key, "", "First key to extract (def: first key in archive)"); DEFINE_string(end_key, "", "Last key to extract (def: last key in archive)"); DEFINE_double(delta, fst::kDelta, "Comparison/quantization delta"); int main(int argc, char **argv) { namespace s = fst::script; string usage = "Compares the FSTs in two FST archives for equality."; usage += "\n\n Usage:"; usage += argv[0]; usage += " in1.far in2.far\n"; usage += " Flags: begin_key end_key"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc != 3) { ShowUsage(); return 1; } string filename1(argv[1]), filename2(argv[2]); bool result = s::FarEqual( filename1, filename2, fst::LoadArcTypeFromFar(filename1), FLAGS_delta, FLAGS_begin_key, FLAGS_end_key); if (!result) VLOG(1) << "FARs are not equal."; return result ? 0 : 2; } <|start_filename|>third_party/openfst/src/bin/fstreplace.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // #include <fst/script/replace.h> DEFINE_string(call_arc_labeling, "input", "Which labels to make non-epsilon on the call arc. " "One of: \"input\" (default), \"output\", \"both\", \"neither\""); DEFINE_string(return_arc_labeling, "neither", "Which labels to make non-epsilon on the return arc. " "One of: \"input\", \"output\", \"both\", \"neither\" (default)"); DEFINE_int64(return_label, 0, "Label to put on return arc"); DEFINE_bool(epsilon_on_replace, false, "For backward compatability: call/return arcs are epsilon arcs"); // Assigns replace_label_type from enum values based on command line switches fst::ReplaceLabelType replace_type(string *arc_labeling, char *binname, string errmsg, bool epsilon_on_replace) { fst::ReplaceLabelType replace_label_type; if ((*arc_labeling) == "neither" || epsilon_on_replace) { replace_label_type = fst::REPLACE_LABEL_NEITHER; } else if ((*arc_labeling) == "input") { replace_label_type = fst::REPLACE_LABEL_INPUT; } else if ((*arc_labeling) == "output") { replace_label_type = fst::REPLACE_LABEL_OUTPUT; } else if ((*arc_labeling) == "both") { replace_label_type = fst::REPLACE_LABEL_BOTH; } else { LOG(ERROR) << binname << errmsg << "arc labeling option: " << (*arc_labeling); exit(1); } return replace_label_type; } int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::VectorFstClass; string usage = "Recursively replaces FST arcs with other FST(s).\n\n" " Usage: "; usage += argv[0]; usage += " root.fst rootlabel [rule1.fst label1 ...] [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 4) { ShowUsage(); return 1; } string in_fname = argv[1]; string out_fname = argc % 2 == 0 ? argv[argc - 1] : ""; FstClass *ifst = FstClass::Read(in_fname); if (!ifst) return 1; typedef int64 Label; typedef pair<Label, const s::FstClass* > FstTuple; vector<FstTuple> fst_tuples; Label root = atoll(argv[2]); fst_tuples.push_back(make_pair(root, ifst)); for (size_t i = 3; i < argc - 1; i += 2) { ifst = s::FstClass::Read(argv[i]); if (!ifst) return 1; Label lab = atoll(argv[i + 1]); fst_tuples.push_back(make_pair(lab, ifst)); } fst::ReplaceLabelType call_label_type = replace_type(&FLAGS_call_arc_labeling, argv[0], ": bad call ", FLAGS_epsilon_on_replace); fst::ReplaceLabelType return_label_type = replace_type(&FLAGS_return_arc_labeling, argv[0], ": bad return ", FLAGS_epsilon_on_replace); VectorFstClass ofst(ifst->ArcType()); s::ReplaceOptions opts(root, call_label_type, return_label_type, FLAGS_return_label); s::Replace(fst_tuples, &ofst, opts); ofst.Write(out_fname); return 0; } <|start_filename|>third_party/openfst/src/script/convert.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/convert.h> namespace fst { namespace script { FstClass *Convert(const FstClass &ifst, const string &new_type) { ConvertInnerArgs args(ifst, new_type); ConvertArgs args_with_retval(args); Apply<Operation<ConvertArgs> >("Convert", ifst.ArcType(), &args_with_retval); return args_with_retval.retval; } REGISTER_FST_OPERATION(Convert, StdArc, ConvertArgs); REGISTER_FST_OPERATION(Convert, LogArc, ConvertArgs); REGISTER_FST_OPERATION(Convert, Log64Arc, ConvertArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/union-find.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file Union-Find algorithm for dense sets of non-negative // integers. Implemented using disjoint tree forests with rank // heuristics and path compression. #ifndef __fst_union_find_inl_h__ #define __fst_union_find_inl_h__ #include <stack> #include <vector> using std::vector; #include <fst/types.h> namespace fst { // Union-Find algorithm for dense sets of non-negative integers // (exact type: T). template <class T> class UnionFind { public: // Ctor: creates a disjoint set forest for the range [0;max). // 'fail' is a value indicating that an element hasn't been // initialized using MakeSet(...). The upper bound of the range // can be reset (increased) using MakeSet(...). UnionFind(T max, T fail) : parent_(max, fail), rank_(max), fail_(fail) { } // Finds the representative of the set 'item' belongs to. // Performs path compression if needed. T FindSet(T item) { if (item >= parent_.size() || item == fail_ || parent_[item] == fail_) return fail_; T *p = &parent_[item]; for (; *p != item; item = *p, p = &parent_[item]) { exec_stack_.push(p); } for (; ! exec_stack_.empty(); exec_stack_.pop()) { *exec_stack_.top() = *p; } return *p; } // Creates the (destructive) union of the sets x and y belong to. void Union(T x, T y) { Link(FindSet(x), FindSet(y)); } // Initialization of an element: creates a singleton set containing // 'item'. The range [0;max) is reset if item >= max. T MakeSet(T item) { if (item >= parent_.size()) { // New value in parent_ should be initialized to fail_ size_t nitem = item > 0 ? 2 * item : 2; parent_.resize(nitem, fail_); rank_.resize(nitem); } parent_[item] = item; return item; } // Initialization of all elements starting from 0 to max - 1 to distinct sets void MakeAllSet(T max) { parent_.resize(max); for (T item = 0; item < max; ++item) { parent_[item] = item; } } private: vector<T> parent_; // Parent nodes. vector<int> rank_; // Rank of an element = min. depth in tree. T fail_; // Value indicating lookup failure. stack<T*> exec_stack_; // Used for path compression. // Links trees rooted in 'x' and 'y'. void Link(T x, T y) { if (x == y) return; if (rank_[x] > rank_[y]) { parent_[y] = x; } else { parent_[x] = y; if (rank_[x] == rank_[y]) { ++rank_[y]; } } } DISALLOW_COPY_AND_ASSIGN(UnionFind); }; } // namespace fst #endif // __fst_union_find_inl_h__ <|start_filename|>third_party/openfst/src/include/fst/difference.h<|end_filename|> // difference.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to compute the difference between two FSAs #ifndef FST_LIB_DIFFERENCE_H__ #define FST_LIB_DIFFERENCE_H__ #include <vector> using std::vector; #include <algorithm> #include <fst/cache.h> #include <fst/compose.h> #include <fst/complement.h> namespace fst { template <class A, class M = Matcher<Fst<A> >, class F = SequenceComposeFilter<M>, class T = GenericComposeStateTable<A, typename F::FilterState> > struct DifferenceFstOptions : public ComposeFstOptions<A, M, F, T> { explicit DifferenceFstOptions(const CacheOptions &opts, M *mat1 = 0, M *mat2 = 0, F *filt = 0, T *sttable= 0) : ComposeFstOptions<A, M, F, T>(mat1, mat2, filt, sttable) { } DifferenceFstOptions() {} }; // Computes the difference between two FSAs. This version is a delayed // Fst. Only strings that are in the first automaton but not in second // are retained in the result. // // The first argument must be an acceptor; the second argument must be // an unweighted, epsilon-free, deterministic acceptor. One of the // arguments must be label-sorted. // // Complexity: same as ComposeFst. // // Caveats: same as ComposeFst. template <class A> class DifferenceFst : public ComposeFst<A> { public: using ImplToFst< ComposeFstImplBase<A> >::SetImpl; using ImplToFst< ComposeFstImplBase<A> >::GetImpl; using ComposeFst<A>::CreateBase1; typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; // A - B = A ^ B'. DifferenceFst(const Fst<A> &fst1, const Fst<A> &fst2, const CacheOptions &opts = CacheOptions()) { typedef RhoMatcher< Matcher<Fst<A> > > R; ComplementFst<A> cfst(fst2); ComposeFstOptions<A, R> copts(CacheOptions(), new R(fst1, MATCH_NONE), new R(cfst, MATCH_INPUT, ComplementFst<A>::kRhoLabel)); SetImpl(CreateBase1(fst1, cfst, copts)); if (!fst1.Properties(kAcceptor, true)) { FSTERROR() << "DifferenceFst: 1st argument not an acceptor"; GetImpl()->SetProperties(kError, kError); } } template <class M, class F, class T> DifferenceFst(const Fst<A> &fst1, const Fst<A> &fst2, const DifferenceFstOptions<A, M, F, T> &opts) { typedef RhoMatcher<M> R; ComplementFst<A> cfst(fst2); ComposeFstOptions<A, R> copts(opts); copts.matcher1 = new R(fst1, MATCH_NONE, kNoLabel, MATCHER_REWRITE_ALWAYS, opts.matcher1); copts.matcher2 = new R(cfst, MATCH_INPUT, ComplementFst<A>::kRhoLabel, MATCHER_REWRITE_ALWAYS, opts.matcher2); SetImpl(CreateBase1(fst1, cfst, copts)); if (!fst1.Properties(kAcceptor, true)) { FSTERROR() << "DifferenceFst: 1st argument not an acceptor"; GetImpl()->SetProperties(kError, kError); } } // See Fst<>::Copy() for doc. DifferenceFst(const DifferenceFst<A> &fst, bool safe = false) : ComposeFst<A>(fst, safe) {} // Get a copy of this DifferenceFst. See Fst<>::Copy() for further doc. virtual DifferenceFst<A> *Copy(bool safe = false) const { return new DifferenceFst<A>(*this, safe); } }; // Specialization for DifferenceFst. template <class A> class StateIterator< DifferenceFst<A> > : public StateIterator< ComposeFst<A> > { public: explicit StateIterator(const DifferenceFst<A> &fst) : StateIterator< ComposeFst<A> >(fst) {} }; // Specialization for DifferenceFst. template <class A> class ArcIterator< DifferenceFst<A> > : public ArcIterator< ComposeFst<A> > { public: typedef typename A::StateId StateId; ArcIterator(const DifferenceFst<A> &fst, StateId s) : ArcIterator< ComposeFst<A> >(fst, s) {} }; // Useful alias when using StdArc. typedef DifferenceFst<StdArc> StdDifferenceFst; typedef ComposeOptions DifferenceOptions; // Computes the difference between two FSAs. This version is writes // the difference to an output MutableFst. Only strings that are in // the first automaton but not in second are retained in the result. // // The first argument must be an acceptor; the second argument must be // an unweighted, epsilon-free, deterministic acceptor. One of the // arguments must be label-sorted. // // Complexity: same as Compose. // // Caveats: same as Compose. template<class Arc> void Difference(const Fst<Arc> &ifst1, const Fst<Arc> &ifst2, MutableFst<Arc> *ofst, const DifferenceOptions &opts = DifferenceOptions()) { typedef Matcher< Fst<Arc> > M; if (opts.filter_type == AUTO_FILTER) { CacheOptions nopts; nopts.gc_limit = 0; // Cache only the last state for fastest copy. *ofst = DifferenceFst<Arc>(ifst1, ifst2, nopts); } else if (opts.filter_type == SEQUENCE_FILTER) { DifferenceFstOptions<Arc> dopts; dopts.gc_limit = 0; // Cache only the last state for fastest copy. *ofst = DifferenceFst<Arc>(ifst1, ifst2, dopts); } else if (opts.filter_type == ALT_SEQUENCE_FILTER) { DifferenceFstOptions<Arc, M, AltSequenceComposeFilter<M> > dopts; dopts.gc_limit = 0; // Cache only the last state for fastest copy. *ofst = DifferenceFst<Arc>(ifst1, ifst2, dopts); } else if (opts.filter_type == MATCH_FILTER) { DifferenceFstOptions<Arc, M, MatchComposeFilter<M> > dopts; dopts.gc_limit = 0; // Cache only the last state for fastest copy. *ofst = DifferenceFst<Arc>(ifst1, ifst2, dopts); } if (opts.connect) Connect(ofst); } } // namespace fst #endif // FST_LIB_DIFFERENCE_H__ <|start_filename|>third_party/openfst/src/extensions/far/farextract.cc<|end_filename|> // farextract.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use new arc dispatch // // \file // Extracts component FSTs from an finite-state archive. // #include <fst/extensions/far/main.h> #include <fst/extensions/far/farscript.h> DEFINE_string(filename_prefix, "", "Prefix to append to filenames"); DEFINE_string(filename_suffix, "", "Suffix to append to filenames"); DEFINE_int32(generate_filenames, 0, "Generate N digit numeric filenames (def: use keys)"); DEFINE_string(keys, "", "Extract set of keys separated by comma (default) " "including ranges delimited by dash (default)" ); DEFINE_string(key_separator, ",", "Separator for individual keys"); DEFINE_string(range_delimiter, "-", "Delimiter for ranges of keys"); int main(int argc, char **argv) { namespace s = fst::script; string usage = "Extracts FSTs from a finite-state archive.\n\n Usage:"; usage += argv[0]; usage += " [in1.far in2.far...]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); vector<string> ifilenames; for (int i = 1; i < argc; ++i) ifilenames.push_back(strcmp(argv[i], "") != 0 ? argv[i] : ""); if (ifilenames.empty()) ifilenames.push_back(""); const string &arc_type = fst::LoadArcTypeFromFar(ifilenames[0]); s::FarExtract(ifilenames, arc_type, FLAGS_generate_filenames, FLAGS_keys, FLAGS_key_separator, FLAGS_range_delimiter, FLAGS_filename_prefix, FLAGS_filename_suffix); return 0; } <|start_filename|>third_party/openfst/src/extensions/linear/linearscript.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: wuke #include <cstdio> #include <cctype> #include <set> #include <fst/compat.h> #include <fst/extensions/linear/linearscript.h> #include <fst/arc.h> #include <fst/script/script-impl.h> DEFINE_string(delimiter, "|", "Single non-white-space character delimiter inside sequences of " "feature symbols and output symbols"); DEFINE_string(empty_symbol, "<empty>", "Special symbol that designates an empty sequence"); DEFINE_string(start_symbol, "<s>", "Start of sentence symbol"); DEFINE_string(end_symbol, "</s>", "End of sentence symbol"); DEFINE_bool(classifier, false, "Treat input model as a classifier instead of a tagger"); namespace fst { namespace script { bool ValidateDelimiter() { if (FLAGS_delimiter.size() == 1 && !std::isspace(FLAGS_delimiter[0])) return true; return false; } bool ValidateEmptySymbol() { bool okay = !FLAGS_empty_symbol.empty(); for (size_t i = 0; i < FLAGS_empty_symbol.size(); ++i) { char c = FLAGS_empty_symbol[i]; if (std::isspace(c)) okay = false; } return okay; } void LinearCompile(const string &arc_type, const string &epsilon_symbol, const string &unknown_symbol, const string &vocab, char **models, int models_len, const string &out, const string &save_isymbols, const string &save_fsymbols, const string &save_osymbols) { LinearCompileArgs args(epsilon_symbol, unknown_symbol, vocab, models, models_len, out, save_isymbols, save_fsymbols, save_osymbols); Apply<Operation<LinearCompileArgs> >("LinearCompileTpl", arc_type, &args); } // Instantiate templates for common arc types REGISTER_FST_LINEAR_OPERATIONS(StdArc); REGISTER_FST_LINEAR_OPERATIONS(LogArc); void SplitByWhitespace(const string &str, vector<string> *out) { out->clear(); istringstream strm(str); string buf; while (strm >> buf) out->push_back(buf); } int ScanNumClasses(char **models, int models_len) { std::set<string> preds; for (int i = 0; i < models_len; ++i) { ifstream in(models[i]); if (!in) LOG(FATAL) << "Failed to open " << models[i]; string line; std::getline(in, line); size_t num_line = 1; while (std::getline(in, line)) { ++num_line; vector<string> fields; SplitByWhitespace(line, &fields); if (fields.size() != 3) LOG(FATAL) << "Wrong number of fields in source " << models[i] << ", line " << num_line; preds.insert(fields[1]); } } return preds.size(); } } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/test/fst_test.h<|end_filename|> // fst_test.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Regression test for FST classes. #ifndef FST_TEST_FST_TEST_H_ #define FST_TEST_FST_TEST_H_ #include <fst/equal.h> #include <fst/matcher.h> #include <fst/vector-fst.h> #include <fst/verify.h> DECLARE_string(tmpdir); namespace fst { // This tests an Fst F that is assumed to have a copy method from an // arbitrary Fst. Some test functions make further assumptions mostly // obvious from their name. These tests are written as member temple // functions that take a test fst as its argument so that different // Fsts in the interface hierarchy can be tested separately and so // that we can instantiate only those tests that make sense for a // particular Fst. template <class F> class FstTester { public: typedef typename F::Arc Arc; typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef typename Arc::Label Label; FstTester() { VectorFst<Arc> vfst; InitFst(&vfst, 128); testfst_ = new F(vfst); } explicit FstTester(F *testfst) : testfst_(testfst) { } ~FstTester() { delete testfst_; } // This verifies the contents described in InitFst() using // methods defined in a generic Fst. template <class G> void TestBase(const G &fst) const { CHECK(Verify(fst)); CHECK_EQ(fst.Start(), 0); StateId ns = 0; StateIterator<G> siter(fst); Matcher<G> matcher(fst, MATCH_INPUT); MatchType match_type = matcher.Type(true); for (; !siter.Done(); siter.Next()) {} for (siter.Reset(); !siter.Done(); siter.Next()) { StateId s = siter.Value(); matcher.SetState(s); CHECK_EQ(fst.Final(s), NthWeight(s)); size_t na = 0; ArcIterator<G> aiter(fst, s); for (; !aiter.Done(); aiter.Next()) {} for (aiter.Reset(); !aiter.Done(); aiter.Next()) { ++na; const Arc &arc = aiter.Value(); CHECK_EQ(arc.ilabel, na); CHECK_EQ(arc.olabel, 0); CHECK_EQ(arc.weight, NthWeight(na)); CHECK_EQ(arc.nextstate, s); if (match_type == MATCH_INPUT) { CHECK(matcher.Find(arc.ilabel)); CHECK_EQ(matcher.Value().ilabel, arc.ilabel); } } CHECK_EQ(na, s); CHECK_EQ(na, aiter.Position()); CHECK_EQ(fst.NumArcs(s), s); CHECK_EQ(fst.NumInputEpsilons(s), 0); CHECK_EQ(fst.NumOutputEpsilons(s), s); CHECK(!matcher.Find(s + 1)); // out-of-range CHECK(!matcher.Find(kNoLabel)); // no explicit epsilons CHECK(matcher.Find(0)); CHECK_EQ(matcher.Value().ilabel, kNoLabel); // implicit epsilon loop ++ns; } CHECK(fst.Properties(kNotAcceptor, true)); CHECK(fst.Properties(kOEpsilons, true)); } void TestBase() const { TestBase(*testfst_); } // This verifies methods specfic to an ExpandedFst. template <class G> void TestExpanded(const G &fst) const { StateId ns = 0; for (StateIterator<G> siter(fst); !siter.Done(); siter.Next()) { ++ns; } CHECK_EQ(fst.NumStates(), ns); CHECK(fst.Properties(kExpanded, false)); } void TestExpanded() const { TestExpanded(*testfst_); } // This verifies methods specific to a MutableFst. template <class G> void TestMutable(G *fst) const { for (StateIterator<G> siter(*fst); !siter.Done(); siter.Next()) { StateId s = siter.Value(); size_t na = 0; size_t ni = fst->NumInputEpsilons(s); MutableArcIterator<G> aiter(fst, s); for (; !aiter.Done(); aiter.Next()) {} for (aiter.Reset(); !aiter.Done(); aiter.Next()) { ++na; Arc arc = aiter.Value(); arc.ilabel = 0; aiter.SetValue(arc); arc = aiter.Value(); CHECK_EQ(arc.ilabel, 0); CHECK_EQ(fst->NumInputEpsilons(s), ni + 1); arc.ilabel = na; aiter.SetValue(arc); CHECK_EQ(fst->NumInputEpsilons(s), ni); } } G *cfst1 = fst->Copy(); cfst1->DeleteStates(); CHECK_EQ(cfst1->NumStates(), 0); delete cfst1; G *cfst2 = fst->Copy(); for (StateIterator<G> siter(*cfst2); !siter.Done(); siter.Next()) { StateId s = siter.Value(); cfst2->DeleteArcs(s); CHECK_EQ(cfst2->NumArcs(s), 0); CHECK_EQ(cfst2->NumInputEpsilons(s), 0); CHECK_EQ(cfst2->NumOutputEpsilons(s), 0); } delete cfst2; } void TestMutable() { TestMutable(testfst_); } // This verifies the copy methods. template <class G> void TestAssign(G *fst) const { // Assignment from G G afst1; afst1 = *fst; CHECK(Equal(*fst, afst1)); // Assignment from Fst G afst2; afst2 = *static_cast<const Fst<Arc> *>(fst); CHECK(Equal(*fst, afst2)); // Assignment from self afst2.operator=(afst2); CHECK(Equal(*fst, afst2)); } void TestAssign() { TestAssign(testfst_); } // This verifies the copy methods. template <class G> void TestCopy(const G &fst) const { // Copy from G G c1fst(fst); TestBase(c1fst); // Copy from Fst const G c2fst(static_cast<const Fst<Arc> &>(fst)); TestBase(c2fst); // Copy from self const G *c3fst = fst.Copy(); TestBase(*c3fst); delete c3fst; } void TestCopy() const { TestCopy(*testfst_); } // This verifies the read/write methods. template <class G> void TestIO(const G &fst) const { const string filename = FLAGS_tmpdir + "/test.fst"; const string aligned = FLAGS_tmpdir + "/aligned.fst"; { // write/read CHECK(fst.Write(filename)); G *ffst = G::Read(filename); CHECK(ffst); TestBase(*ffst); delete ffst; } { // generic read/cast/test Fst<Arc> *gfst = Fst<Arc>::Read(filename); CHECK(gfst); G *dfst = static_cast<G *>(gfst); TestBase(*dfst); // generic write/read/test CHECK(gfst->Write(filename)); Fst<Arc> *hfst = Fst<Arc>::Read(filename); CHECK(hfst); TestBase(*hfst); delete gfst; delete hfst; } { // check mmaping by first writing the file with the aligned attribute set { ofstream ostr(aligned.c_str()); FstWriteOptions opts; opts.source = aligned; opts.align = true; CHECK(fst.Write(ostr, opts)); } ifstream istr(aligned.c_str()); FstReadOptions opts; opts.mode = FstReadOptions::ReadMode("map"); opts.source = aligned; G *gfst = G::Read(istr, opts); CHECK(gfst); TestBase(*gfst); delete gfst; } // check mmaping of unaligned files to make sure it does not fail. { { ofstream ostr(aligned.c_str()); FstWriteOptions opts; opts.source = aligned; opts.align = false; CHECK(fst.Write(ostr, opts)); } ifstream istr(aligned.c_str()); FstReadOptions opts; opts.mode = FstReadOptions::ReadMode("map"); opts.source = aligned; G *gfst = G::Read(istr, opts); CHECK(gfst); TestBase(*gfst); delete gfst; } // expanded write/read/test if (fst.Properties(kExpanded, false)) { ExpandedFst<Arc> *efst = ExpandedFst<Arc>::Read(filename); CHECK(efst); TestBase(*efst); TestExpanded(*efst); delete efst; } // mutable write/read/test if (fst.Properties(kMutable, false)) { MutableFst<Arc> *mfst = MutableFst<Arc>::Read(filename); CHECK(mfst); TestBase(*mfst); TestExpanded(*mfst); TestMutable(mfst); delete mfst; } } void TestIO() const { TestIO(*testfst_); } private: // This constructs test FSTs. Given a mutable FST, will leave // the FST as follows: // (I) NumStates() = nstates // (II) Start() = 0 // (III) Final(s) = NthWeight(s) // (IV) For state s: // (a) NumArcs(s) == s // (b) For ith arc of s: // (1) ilabel = i // (2) olabel = 0 // (3) weight = NthWeight(i) // (4) nextstate = s void InitFst(MutableFst<Arc> *fst, size_t nstates) const { fst->DeleteStates(); CHECK_GT(nstates, 0); for (StateId s = 0; s < nstates; ++s) { fst->AddState(); fst->SetFinal(s, NthWeight(s)); for (size_t i = 1; i <= s; ++i) { Arc arc(i, 0, NthWeight(i), s); fst->AddArc(s, arc); } } fst->SetStart(0); } // Generates One() + ... + One() (n times) Weight NthWeight(int n) const { Weight w = Weight::Zero(); for (int i = 0; i < n; ++i) w = Plus(w, Weight::One()); return w; } F *testfst_; // what we're testing }; } // namespace fst #endif // FST_TEST_FST_TEST_H_ <|start_filename|>third_party/openfst/src/script/shortest-distance.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/shortest-distance.h> namespace fst { namespace script { // 1 void ShortestDistance(const FstClass &fst, vector<WeightClass> *distance, const ShortestDistanceOptions &opts) { ShortestDistanceArgs1 args(fst, distance, opts); Apply<Operation<ShortestDistanceArgs1> >("ShortestDistance", fst.ArcType(), &args); } // 2 void ShortestDistance(const FstClass &ifst, vector<WeightClass> *distance, bool reverse, double delta) { ShortestDistanceArgs2 args(ifst, distance, reverse, delta); Apply<Operation<ShortestDistanceArgs2> >("ShortestDistance", ifst.ArcType(), &args); } // 3 WeightClass ShortestDistance(const FstClass &ifst) { ShortestDistanceArgs3 args(ifst); Apply<Operation<ShortestDistanceArgs3> >("ShortestDistance", ifst.ArcType(), &args); return args.retval; } REGISTER_FST_OPERATION(ShortestDistance, StdArc, ShortestDistanceArgs1); REGISTER_FST_OPERATION(ShortestDistance, LogArc, ShortestDistanceArgs1); REGISTER_FST_OPERATION(ShortestDistance, Log64Arc, ShortestDistanceArgs1); REGISTER_FST_OPERATION(ShortestDistance, StdArc, ShortestDistanceArgs2); REGISTER_FST_OPERATION(ShortestDistance, LogArc, ShortestDistanceArgs2); REGISTER_FST_OPERATION(ShortestDistance, Log64Arc, ShortestDistanceArgs2); REGISTER_FST_OPERATION(ShortestDistance, StdArc, ShortestDistanceArgs3); REGISTER_FST_OPERATION(ShortestDistance, LogArc, ShortestDistanceArgs3); REGISTER_FST_OPERATION(ShortestDistance, Log64Arc, ShortestDistanceArgs3); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/extensions/ngram/nthbit.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME> #include <fst/extensions/ngram/nthbit.h> // // This table is generate using: // // unsigned int nth_bit_scan(uint64 v, unsigned int r) { // int i=0; // for (; i<64; i++) { // if ((r -= v & 1) == 0) return i; // v >>= 1; // } // return i; // } // // for (size_t i = 0; i < 256; ++i) { // uint32 offsets = 0; // for (size_t b = 1; b <= 8; ++b) { // uint32 offset = min<uint32>(nth_bit_scan(i, b), 8); // offsets |= (offset << ((b - 1) << 2)); // } // bit_offset = offsets; // printf("0x%x, ", bit_offset); // if (i % 4 == 3) printf("\n"); // } // uint32 nth_bit_bit_offset[] = { 0x88888888, 0x88888880, 0x88888881, 0x88888810, 0x88888882, 0x88888820, 0x88888821, 0x88888210, 0x88888883, 0x88888830, 0x88888831, 0x88888310, 0x88888832, 0x88888320, 0x88888321, 0x88883210, 0x88888884, 0x88888840, 0x88888841, 0x88888410, 0x88888842, 0x88888420, 0x88888421, 0x88884210, 0x88888843, 0x88888430, 0x88888431, 0x88884310, 0x88888432, 0x88884320, 0x88884321, 0x88843210, 0x88888885, 0x88888850, 0x88888851, 0x88888510, 0x88888852, 0x88888520, 0x88888521, 0x88885210, 0x88888853, 0x88888530, 0x88888531, 0x88885310, 0x88888532, 0x88885320, 0x88885321, 0x88853210, 0x88888854, 0x88888540, 0x88888541, 0x88885410, 0x88888542, 0x88885420, 0x88885421, 0x88854210, 0x88888543, 0x88885430, 0x88885431, 0x88854310, 0x88885432, 0x88854320, 0x88854321, 0x88543210, 0x88888886, 0x88888860, 0x88888861, 0x88888610, 0x88888862, 0x88888620, 0x88888621, 0x88886210, 0x88888863, 0x88888630, 0x88888631, 0x88886310, 0x88888632, 0x88886320, 0x88886321, 0x88863210, 0x88888864, 0x88888640, 0x88888641, 0x88886410, 0x88888642, 0x88886420, 0x88886421, 0x88864210, 0x88888643, 0x88886430, 0x88886431, 0x88864310, 0x88886432, 0x88864320, 0x88864321, 0x88643210, 0x88888865, 0x88888650, 0x88888651, 0x88886510, 0x88888652, 0x88886520, 0x88886521, 0x88865210, 0x88888653, 0x88886530, 0x88886531, 0x88865310, 0x88886532, 0x88865320, 0x88865321, 0x88653210, 0x88888654, 0x88886540, 0x88886541, 0x88865410, 0x88886542, 0x88865420, 0x88865421, 0x88654210, 0x88886543, 0x88865430, 0x88865431, 0x88654310, 0x88865432, 0x88654320, 0x88654321, 0x86543210, 0x88888887, 0x88888870, 0x88888871, 0x88888710, 0x88888872, 0x88888720, 0x88888721, 0x88887210, 0x88888873, 0x88888730, 0x88888731, 0x88887310, 0x88888732, 0x88887320, 0x88887321, 0x88873210, 0x88888874, 0x88888740, 0x88888741, 0x88887410, 0x88888742, 0x88887420, 0x88887421, 0x88874210, 0x88888743, 0x88887430, 0x88887431, 0x88874310, 0x88887432, 0x88874320, 0x88874321, 0x88743210, 0x88888875, 0x88888750, 0x88888751, 0x88887510, 0x88888752, 0x88887520, 0x88887521, 0x88875210, 0x88888753, 0x88887530, 0x88887531, 0x88875310, 0x88887532, 0x88875320, 0x88875321, 0x88753210, 0x88888754, 0x88887540, 0x88887541, 0x88875410, 0x88887542, 0x88875420, 0x88875421, 0x88754210, 0x88887543, 0x88875430, 0x88875431, 0x88754310, 0x88875432, 0x88754320, 0x88754321, 0x87543210, 0x88888876, 0x88888760, 0x88888761, 0x88887610, 0x88888762, 0x88887620, 0x88887621, 0x88876210, 0x88888763, 0x88887630, 0x88887631, 0x88876310, 0x88887632, 0x88876320, 0x88876321, 0x88763210, 0x88888764, 0x88887640, 0x88887641, 0x88876410, 0x88887642, 0x88876420, 0x88876421, 0x88764210, 0x88887643, 0x88876430, 0x88876431, 0x88764310, 0x88876432, 0x88764320, 0x88764321, 0x87643210, 0x88888765, 0x88887650, 0x88887651, 0x88876510, 0x88887652, 0x88876520, 0x88876521, 0x88765210, 0x88887653, 0x88876530, 0x88876531, 0x88765310, 0x88876532, 0x88765320, 0x88765321, 0x87653210, 0x88887654, 0x88876540, 0x88876541, 0x88765410, 0x88876542, 0x88765420, 0x88765421, 0x87654210, 0x88876543, 0x88765430, 0x88765431, 0x87654310, 0x88765432, 0x87654320, 0x87654321, 0x76543210, }; <|start_filename|>third_party/openfst/src/script/randgen.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/randgen.h> namespace fst { namespace script { void RandGen(const FstClass &ifst, MutableFstClass *ofst, int32 seed, const RandGenOptions<RandArcSelection> &opts) { if (!ArcTypesMatch(ifst, *ofst, "RandGen")) return; RandGenArgs args(ifst, ofst, seed, opts); Apply<Operation<RandGenArgs> >("RandGen", ifst.ArcType(), &args); } REGISTER_FST_OPERATION(RandGen, StdArc, RandGenArgs); REGISTER_FST_OPERATION(RandGen, LogArc, RandGenArgs); REGISTER_FST_OPERATION(RandGen, Log64Arc, RandGenArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/bin/fstintersect.cc<|end_filename|> // fstintersect.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Intersects two FSTs. // #include <fst/script/intersect.h> #include <fst/script/connect.h> DEFINE_string(compose_filter, "auto", "Composition filter, one of: \"alt_sequence\", \"auto\", " "\"match\", \"sequence\""); DEFINE_bool(connect, true, "Trim output"); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::VectorFstClass; string usage = "Intersects two FSAs.\n\n Usage: "; usage += argv[0]; usage += " in1.fst in2.fst [out.fst]\n"; usage += " Flags: connect\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 3 || argc > 4) { ShowUsage(); return 1; } string in1_name = strcmp(argv[1], "-") == 0 ? "" : argv[1]; string in2_name = strcmp(argv[2], "-") == 0 ? "" : argv[2]; string out_name = argc > 3 ? argv[3] : ""; if (in1_name.empty() && in2_name.empty()) { LOG(ERROR) << argv[0] << ": Can't take both inputs from standard input."; return 1; } FstClass *ifst1 = FstClass::Read(in1_name); if (!ifst1) return 1; FstClass *ifst2 = FstClass::Read(in2_name); if (!ifst2) return 1; VectorFstClass ofst(ifst1->ArcType()); fst::ComposeFilter compose_filter; if (FLAGS_compose_filter == "alt_sequence") { compose_filter = fst::ALT_SEQUENCE_FILTER; } else if (FLAGS_compose_filter == "auto") { compose_filter = fst::AUTO_FILTER; } else if (FLAGS_compose_filter == "match") { compose_filter = fst::MATCH_FILTER; } else if (FLAGS_compose_filter == "sequence") { compose_filter = fst::SEQUENCE_FILTER; } else { LOG(ERROR) << argv[0] << "Unknown compose filter type: " << FLAGS_compose_filter; return 1; } fst::IntersectOptions opts(FLAGS_connect, compose_filter); s::Intersect(*ifst1, *ifst2, &ofst, opts); ofst.Write(out_name); return 0; } <|start_filename|>third_party/openfst/src/include/fst/push.h<|end_filename|> // push.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to reweight/push an FST. #ifndef FST_LIB_PUSH_H__ #define FST_LIB_PUSH_H__ #include <vector> using std::vector; #include <fst/factor-weight.h> #include <fst/fst.h> #include <fst/arc-map.h> #include <fst/reweight.h> #include <fst/shortest-distance.h> namespace fst { // Private helper functions for Push namespace internal { // Compute the total weight (sum of the weights of all accepting paths) from // the output of ShortestDistance. 'distance' is the shortest distance from the // initial state when 'reverse == false' and to the final states when // 'reverse == true'. template <class Arc> typename Arc::Weight ComputeTotalWeight( const Fst<Arc> &fst, const vector<typename Arc::Weight> &distance, bool reverse) { if (reverse) return fst.Start() < distance.size() ? distance[fst.Start()] : Arc::Weight::Zero(); typename Arc::Weight sum = Arc::Weight::Zero(); for (typename Arc::StateId s = 0; s < distance.size(); ++s) sum = Plus(sum, Times(distance[s], fst.Final(s))); return sum; } // Divide the weight of every accepting path by 'w'. The weight 'w' is // divided at the final states if 'at_final == true' and at the // initial state otherwise. template <class Arc> void RemoveWeight(MutableFst<Arc> *fst, typename Arc::Weight w, bool at_final) { if ((w == Arc::Weight::One()) || (w == Arc::Weight::Zero())) return; if (at_final) { // Remove 'w' from the final states for (StateIterator< MutableFst<Arc> > sit(*fst); !sit.Done(); sit.Next()) fst->SetFinal(sit.Value(), Divide(fst->Final(sit.Value()), w, DIVIDE_RIGHT)); } else { // at_final == false // Remove 'w' from the initial state typename Arc::StateId start = fst->Start(); for (MutableArcIterator<MutableFst<Arc> > ait(fst, start); !ait.Done(); ait.Next()) { Arc arc = ait.Value(); arc.weight = Divide(arc.weight, w, DIVIDE_LEFT); ait.SetValue(arc); } fst->SetFinal(start, Divide(fst->Final(start), w, DIVIDE_LEFT)); } } } // namespace internal // Pushes the weights in FST in the direction defined by TYPE. If // pushing towards the initial state, the sum of the weight of the // outgoing transitions and final weight at a non-initial state is // equal to One() in the resulting machine. If pushing towards the // final state, the same property holds on the reverse machine. // // Weight needs to be left distributive when pushing towards the // initial state and right distributive when pushing towards the final // states. template <class Arc> void Push(MutableFst<Arc> *fst, ReweightType type, float delta = kDelta, bool remove_total_weight = false) { vector<typename Arc::Weight> distance; ShortestDistance(*fst, &distance, type == REWEIGHT_TO_INITIAL, delta); typename Arc::Weight total_weight = Arc::Weight::One(); if (remove_total_weight) total_weight = internal::ComputeTotalWeight(*fst, distance, type == REWEIGHT_TO_INITIAL); Reweight(fst, distance, type); if (remove_total_weight) internal::RemoveWeight(fst, total_weight, type == REWEIGHT_TO_FINAL); } const uint32 kPushWeights = 0x0001; const uint32 kPushLabels = 0x0002; const uint32 kPushRemoveTotalWeight = 0x0004; const uint32 kPushRemoveCommonAffix = 0x0008; // OFST obtained from IFST by pushing weights and/or labels according // to PTYPE in the direction defined by RTYPE. Weight needs to be // left distributive when pushing weights towards the initial state // and right distributive when pushing weights towards the final // states. template <class Arc, ReweightType rtype> void Push(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, uint32 ptype, float delta = kDelta) { if ((ptype & (kPushWeights | kPushLabels)) == kPushWeights) { *ofst = ifst; Push(ofst, rtype, delta, ptype & kPushRemoveTotalWeight); } else if (ptype & kPushLabels) { const GallicType gtype = rtype == REWEIGHT_TO_INITIAL ? GALLIC_LEFT : GALLIC_RIGHT; vector<typename GallicArc<Arc, gtype>::Weight> gdistance; VectorFst<GallicArc<Arc, gtype> > gfst; ArcMap(ifst, &gfst, ToGallicMapper<Arc, gtype>()); if (ptype & kPushWeights ) { ShortestDistance(gfst, &gdistance, rtype == REWEIGHT_TO_INITIAL, delta); } else { ArcMapFst<Arc, Arc, RmWeightMapper<Arc> > uwfst(ifst, RmWeightMapper<Arc>()); ArcMapFst<Arc, GallicArc<Arc, gtype>, ToGallicMapper<Arc, gtype> > guwfst(uwfst, ToGallicMapper<Arc, gtype>()); ShortestDistance(guwfst, &gdistance, rtype == REWEIGHT_TO_INITIAL, delta); } typename GallicArc<Arc, gtype>::Weight total_weight = GallicArc<Arc, gtype>::Weight::One(); if (ptype & (kPushRemoveTotalWeight | kPushRemoveCommonAffix)) { total_weight = internal::ComputeTotalWeight( gfst, gdistance, rtype == REWEIGHT_TO_INITIAL); total_weight = typename GallicArc<Arc, gtype>::Weight( ptype & kPushRemoveCommonAffix ? total_weight.Value1() : StringWeight<typename Arc::Label, GALLIC_STRING_TYPE(gtype)>::One(), ptype & kPushRemoveTotalWeight ? total_weight.Value2() : Arc::Weight::One()); } Reweight(&gfst, gdistance, rtype); if (ptype & (kPushRemoveTotalWeight | kPushRemoveCommonAffix)) internal::RemoveWeight(&gfst, total_weight, rtype == REWEIGHT_TO_FINAL); FactorWeightFst< GallicArc<Arc, gtype>, GallicFactor<typename Arc::Label, typename Arc::Weight, gtype> > fwfst(gfst); ArcMap(fwfst, ofst, FromGallicMapper<Arc, gtype>()); ofst->SetOutputSymbols(ifst.OutputSymbols()); } else { LOG(WARNING) << "Push: pushing type is set to 0: " << "pushing neither labels nor weights."; *ofst = ifst; } } } // namespace fst #endif /* FST_LIB_PUSH_H_ */ <|start_filename|>third_party/openfst/src/bin/fstshortestdistance.cc<|end_filename|> // fstshortestdistance.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Find shortest distances in an FST. #include <string> #include <vector> using std::vector; #include <fst/script/shortest-distance.h> #include <fst/script/text-io.h> DEFINE_bool(reverse, false, "Perform in the reverse direction"); DEFINE_double(delta, fst::kDelta, "Comparison/quantization delta"); DEFINE_int64(nstate, fst::kNoStateId, "State number threhold"); DEFINE_string(queue_type, "auto", "Queue type: one of: \"auto\", " "\"fifo\", \"lifo\", \"shortest\", \"state\", \"top\""); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; string usage = "Finds shortest distance(s) in an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [distance.txt]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } string in_fname = (argc > 1 && (strcmp(argv[1], "-") != 0)) ? argv[1] : ""; string out_fname = argc > 2 ? argv[2] : ""; FstClass *ifst = FstClass::Read(in_fname); if (!ifst) return 1; vector<s::WeightClass> distance; fst::QueueType qt; if (FLAGS_queue_type == "auto") { qt = fst::AUTO_QUEUE; } else if (FLAGS_queue_type == "fifo") { qt = fst::FIFO_QUEUE; } else if (FLAGS_queue_type == "lifo") { qt = fst::LIFO_QUEUE; } else if (FLAGS_queue_type == "shortest") { qt = fst::SHORTEST_FIRST_QUEUE; } else if (FLAGS_queue_type == "state") { qt = fst::STATE_ORDER_QUEUE; } else if (FLAGS_queue_type == "top") { qt = fst::TOP_ORDER_QUEUE; } else { LOG(ERROR) << "Unknown or unsupported queue type: " << FLAGS_queue_type; return 1; } if (FLAGS_reverse && qt != fst::AUTO_QUEUE) { LOG(ERROR) << "Specifying a non-default queue with reverse not supported."; return 1; } if (FLAGS_reverse) { s::ShortestDistance(*ifst, &distance, FLAGS_reverse, FLAGS_delta); } else { s::ShortestDistanceOptions opts(qt, s::ANY_ARC_FILTER, FLAGS_nstate, FLAGS_delta); s::ShortestDistance(*ifst, &distance, opts); } s::WritePotentials(out_fname, distance); return 0; } <|start_filename|>third_party/openfst/src/include/fst/queue.h<|end_filename|> // queue.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Functions and classes for various Fst state queues with // a unified interface. #ifndef FST_LIB_QUEUE_H__ #define FST_LIB_QUEUE_H__ #include <deque> using std::deque; #include <vector> using std::vector; #include <fst/arcfilter.h> #include <fst/connect.h> #include <fst/heap.h> #include <fst/topsort.h> namespace fst { // template <class S> // class Queue { // public: // typedef typename S StateId; // // // Ctr: may need args (e.g., Fst, comparator) for some queues // Queue(...); // // Returns the head of the queue // StateId Head() const; // // Inserts a state // void Enqueue(StateId s); // // Removes the head of the queue // void Dequeue(); // // Updates ordering of state s when weight changes, if necessary // void Update(StateId s); // // Does the queue contain no elements? // bool Empty() const; // // Remove all states from queue // void Clear(); // }; // State queue types. enum QueueType { TRIVIAL_QUEUE = 0, // Single state queue FIFO_QUEUE = 1, // First-in, first-out queue LIFO_QUEUE = 2, // Last-in, first-out queue SHORTEST_FIRST_QUEUE = 3, // Shortest-first queue TOP_ORDER_QUEUE = 4, // Topologically-ordered queue STATE_ORDER_QUEUE = 5, // State-ID ordered queue SCC_QUEUE = 6, // Component graph top-ordered meta-queue AUTO_QUEUE = 7, // Auto-selected queue OTHER_QUEUE = 8 }; // QueueBase, templated on the StateId, is the base class shared by the // queues considered by AutoQueue. template <class S> class QueueBase { public: typedef S StateId; QueueBase(QueueType type) : queue_type_(type), error_(false) {} virtual ~QueueBase() {} StateId Head() const { return Head_(); } void Enqueue(StateId s) { Enqueue_(s); } void Dequeue() { Dequeue_(); } void Update(StateId s) { Update_(s); } bool Empty() const { return Empty_(); } void Clear() { Clear_(); } QueueType Type() { return queue_type_; } bool Error() const { return error_; } void SetError(bool error) { error_ = error; } private: // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const = 0; virtual void Enqueue_(StateId s) = 0; virtual void Dequeue_() = 0; virtual void Update_(StateId s) = 0; virtual bool Empty_() const = 0; virtual void Clear_() = 0; QueueType queue_type_; bool error_; }; // Trivial queue discipline, templated on the StateId. You may enqueue // at most one state at a time. It is used for strongly connected components // with only one state and no self loops. template <class S> class TrivialQueue : public QueueBase<S> { public: typedef S StateId; TrivialQueue() : QueueBase<S>(TRIVIAL_QUEUE), front_(kNoStateId) {} StateId Head() const { return front_; } void Enqueue(StateId s) { front_ = s; } void Dequeue() { front_ = kNoStateId; } void Update(StateId s) {} bool Empty() const { return front_ == kNoStateId; } void Clear() { front_ = kNoStateId; } private: // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } StateId front_; }; // First-in, first-out queue discipline, templated on the StateId. template <class S> class FifoQueue : public QueueBase<S>, public deque<S> { public: using deque<S>::back; using deque<S>::push_front; using deque<S>::pop_back; using deque<S>::empty; using deque<S>::clear; typedef S StateId; FifoQueue() : QueueBase<S>(FIFO_QUEUE) {} StateId Head() const { return back(); } void Enqueue(StateId s) { push_front(s); } void Dequeue() { pop_back(); } void Update(StateId s) {} bool Empty() const { return empty(); } void Clear() { clear(); } private: // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } }; // Last-in, first-out queue discipline, templated on the StateId. template <class S> class LifoQueue : public QueueBase<S>, public deque<S> { public: using deque<S>::front; using deque<S>::push_front; using deque<S>::pop_front; using deque<S>::empty; using deque<S>::clear; typedef S StateId; LifoQueue() : QueueBase<S>(LIFO_QUEUE) {} StateId Head() const { return front(); } void Enqueue(StateId s) { push_front(s); } void Dequeue() { pop_front(); } void Update(StateId s) {} bool Empty() const { return empty(); } void Clear() { clear(); } private: // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } }; // Shortest-first queue discipline, templated on the StateId and // comparison function object. Comparison function object COMP is // used to compare two StateIds. If a (single) state's order changes, // it can be reordered in the queue with a call to Update(). // If 'update == false', call to Update() does not reorder the queue. template <typename S, typename C, bool update = true> class ShortestFirstQueue : public QueueBase<S> { public: typedef S StateId; typedef C Compare; ShortestFirstQueue(C comp) : QueueBase<S>(SHORTEST_FIRST_QUEUE), heap_(comp) {} StateId Head() const { return heap_.Top(); } void Enqueue(StateId s) { if (update) { for (StateId i = key_.size(); i <= s; ++i) key_.push_back(kNoKey); key_[s] = heap_.Insert(s); } else { heap_.Insert(s); } } void Dequeue() { if (update) key_[heap_.Pop()] = kNoKey; else heap_.Pop(); } void Update(StateId s) { if (!update) return; if (s >= key_.size() || key_[s] == kNoKey) { Enqueue(s); } else { heap_.Update(key_[s], s); } } bool Empty() const { return heap_.Empty(); } void Clear() { heap_.Clear(); if (update) key_.clear(); } private: Heap<S, C, false> heap_; vector<ssize_t> key_; // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } }; // Given a vector that maps from states to weights and a Less // comparison function object between weights, this class defines a // comparison function object between states. template <typename S, typename L> class StateWeightCompare { public: typedef L Less; typedef typename L::Weight Weight; typedef S StateId; StateWeightCompare(const vector<Weight>& weights, const L &less) : weights_(weights), less_(less) {} bool operator()(const S x, const S y) const { return less_(weights_[x], weights_[y]); } private: const vector<Weight>& weights_; L less_; }; // Shortest-first queue discipline, templated on the StateId and Weight, is // specialized to use the weight's natural order for the comparison function. template <typename S, typename W> class NaturalShortestFirstQueue : public ShortestFirstQueue<S, StateWeightCompare<S, NaturalLess<W> > > { public: typedef StateWeightCompare<S, NaturalLess<W> > C; NaturalShortestFirstQueue(const vector<W> &distance) : ShortestFirstQueue<S, C>(C(distance, less_)) {} private: NaturalLess<W> less_; }; // Topological-order queue discipline, templated on the StateId. // States are ordered in the queue topologically. The FST must be acyclic. template <class S> class TopOrderQueue : public QueueBase<S> { public: typedef S StateId; // This constructor computes the top. order. It accepts an arc filter // to limit the transitions considered in that computation (e.g., only // the epsilon graph). template <class Arc, class ArcFilter> TopOrderQueue(const Fst<Arc> &fst, ArcFilter filter) : QueueBase<S>(TOP_ORDER_QUEUE), front_(0), back_(kNoStateId), order_(0), state_(0) { bool acyclic; TopOrderVisitor<Arc> top_order_visitor(&order_, &acyclic); DfsVisit(fst, &top_order_visitor, filter); if (!acyclic) { FSTERROR() << "TopOrderQueue: fst is not acyclic."; QueueBase<S>::SetError(true); } state_.resize(order_.size(), kNoStateId); } // This constructor is passed the top. order, useful when we know it // beforehand. TopOrderQueue(const vector<StateId> &order) : QueueBase<S>(TOP_ORDER_QUEUE), front_(0), back_(kNoStateId), order_(order), state_(order.size(), kNoStateId) {} StateId Head() const { return state_[front_]; } void Enqueue(StateId s) { if (front_ > back_) front_ = back_ = order_[s]; else if (order_[s] > back_) back_ = order_[s]; else if (order_[s] < front_) front_ = order_[s]; state_[order_[s]] = s; } void Dequeue() { state_[front_] = kNoStateId; while ((front_ <= back_) && (state_[front_] == kNoStateId)) ++front_; } void Update(StateId s) {} bool Empty() const { return front_ > back_; } void Clear() { for (StateId i = front_; i <= back_; ++i) state_[i] = kNoStateId; back_ = kNoStateId; front_ = 0; } private: StateId front_; StateId back_; vector<StateId> order_; vector<StateId> state_; // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } }; // State order queue discipline, templated on the StateId. // States are ordered in the queue by state Id. template <class S> class StateOrderQueue : public QueueBase<S> { public: typedef S StateId; StateOrderQueue() : QueueBase<S>(STATE_ORDER_QUEUE), front_(0), back_(kNoStateId) {} StateId Head() const { return front_; } void Enqueue(StateId s) { if (front_ > back_) front_ = back_ = s; else if (s > back_) back_ = s; else if (s < front_) front_ = s; while (enqueued_.size() <= s) enqueued_.push_back(false); enqueued_[s] = true; } void Dequeue() { enqueued_[front_] = false; while ((front_ <= back_) && (enqueued_[front_] == false)) ++front_; } void Update(StateId s) {} bool Empty() const { return front_ > back_; } void Clear() { for (StateId i = front_; i <= back_; ++i) enqueued_[i] = false; front_ = 0; back_ = kNoStateId; } private: StateId front_; StateId back_; vector<bool> enqueued_; // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } }; // SCC topological-order meta-queue discipline, templated on the StateId S // and a queue Q, which is used inside each SCC. It visits the SCC's // of an FST in topological order. Its constructor is passed the queues to // to use within an SCC. template <class S, class Q> class SccQueue : public QueueBase<S> { public: typedef S StateId; typedef Q Queue; // Constructor takes a vector specifying the SCC number per state // and a vector giving the queue to use per SCC number. SccQueue(const vector<StateId> &scc, vector<Queue*> *queue) : QueueBase<S>(SCC_QUEUE), queue_(queue), scc_(scc), front_(0), back_(kNoStateId) {} StateId Head() const { while ((front_ <= back_) && (((*queue_)[front_] && (*queue_)[front_]->Empty()) || (((*queue_)[front_] == 0) && ((front_ >= trivial_queue_.size()) || (trivial_queue_[front_] == kNoStateId))))) ++front_; if ((*queue_)[front_]) return (*queue_)[front_]->Head(); else return trivial_queue_[front_]; } void Enqueue(StateId s) { if (front_ > back_) front_ = back_ = scc_[s]; else if (scc_[s] > back_) back_ = scc_[s]; else if (scc_[s] < front_) front_ = scc_[s]; if ((*queue_)[scc_[s]]) { (*queue_)[scc_[s]]->Enqueue(s); } else { while (trivial_queue_.size() <= scc_[s]) trivial_queue_.push_back(kNoStateId); trivial_queue_[scc_[s]] = s; } } void Dequeue() { if ((*queue_)[front_]) (*queue_)[front_]->Dequeue(); else if (front_ < trivial_queue_.size()) trivial_queue_[front_] = kNoStateId; } void Update(StateId s) { if ((*queue_)[scc_[s]]) (*queue_)[scc_[s]]->Update(s); } bool Empty() const { if (front_ < back_) // Queue scc # back_ not empty unless back_==front_ return false; else if (front_ > back_) return true; else if ((*queue_)[front_]) return (*queue_)[front_]->Empty(); else return (front_ >= trivial_queue_.size()) || (trivial_queue_[front_] == kNoStateId); } void Clear() { for (StateId i = front_; i <= back_; ++i) if ((*queue_)[i]) (*queue_)[i]->Clear(); else if (i < trivial_queue_.size()) trivial_queue_[i] = kNoStateId; front_ = 0; back_ = kNoStateId; } private: vector<Queue*> *queue_; const vector<StateId> &scc_; mutable StateId front_; StateId back_; vector<StateId> trivial_queue_; // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } DISALLOW_COPY_AND_ASSIGN(SccQueue); }; // Automatic queue discipline, templated on the StateId. It selects a // queue discipline for a given FST based on its properties. template <class S> class AutoQueue : public QueueBase<S> { public: typedef S StateId; // This constructor takes a state distance vector that, if non-null and if // the Weight type has the path property, will entertain the // shortest-first queue using the natural order w.r.t to the distance. template <class Arc, class ArcFilter> AutoQueue(const Fst<Arc> &fst, const vector<typename Arc::Weight> *distance, ArcFilter filter) : QueueBase<S>(AUTO_QUEUE) { typedef typename Arc::Weight Weight; typedef StateWeightCompare< StateId, NaturalLess<Weight> > Compare; // First check if the FST is known to have these properties. uint64 props = fst.Properties(kAcyclic | kCyclic | kTopSorted | kUnweighted, false); if ((props & kTopSorted) || fst.Start() == kNoStateId) { queue_ = new StateOrderQueue<StateId>(); VLOG(2) << "AutoQueue: using state-order discipline"; } else if (props & kAcyclic) { queue_ = new TopOrderQueue<StateId>(fst, filter); VLOG(2) << "AutoQueue: using top-order discipline"; } else if ((props & kUnweighted) && (Weight::Properties() & kIdempotent)) { queue_ = new LifoQueue<StateId>(); VLOG(2) << "AutoQueue: using LIFO discipline"; } else { uint64 properties; // Decompose into strongly-connected components. SccVisitor<Arc> scc_visitor(&scc_, 0, 0, &properties); DfsVisit(fst, &scc_visitor, filter); StateId nscc = *max_element(scc_.begin(), scc_.end()) + 1; vector<QueueType> queue_types(nscc); NaturalLess<Weight> *less = 0; Compare *comp = 0; if (distance && (Weight::Properties() & kPath)) { less = new NaturalLess<Weight>; comp = new Compare(*distance, *less); } // Find the queue type to use per SCC. bool unweighted; bool all_trivial; SccQueueType(fst, scc_, &queue_types, filter, less, &all_trivial, &unweighted); // If unweighted and semiring is idempotent, use lifo queue. if (unweighted) { queue_ = new LifoQueue<StateId>(); VLOG(2) << "AutoQueue: using LIFO discipline"; delete comp; delete less; return; } // If all the scc are trivial, FST is acyclic and the scc# gives // the topological order. if (all_trivial) { queue_ = new TopOrderQueue<StateId>(scc_); VLOG(2) << "AutoQueue: using top-order discipline"; delete comp; delete less; return; } VLOG(2) << "AutoQueue: using SCC meta-discipline"; queues_.resize(nscc); for (StateId i = 0; i < nscc; ++i) { switch(queue_types[i]) { case TRIVIAL_QUEUE: queues_[i] = 0; VLOG(3) << "AutoQueue: SCC #" << i << ": using trivial discipline"; break; case SHORTEST_FIRST_QUEUE: queues_[i] = new ShortestFirstQueue<StateId, Compare, false>(*comp); VLOG(3) << "AutoQueue: SCC #" << i << ": using shortest-first discipline"; break; case LIFO_QUEUE: queues_[i] = new LifoQueue<StateId>(); VLOG(3) << "AutoQueue: SCC #" << i << ": using LIFO disciplle"; break; case FIFO_QUEUE: default: queues_[i] = new FifoQueue<StateId>(); VLOG(3) << "AutoQueue: SCC #" << i << ": using FIFO disciplle"; break; } } queue_ = new SccQueue< StateId, QueueBase<StateId> >(scc_, &queues_); delete comp; delete less; } } ~AutoQueue() { for (StateId i = 0; i < queues_.size(); ++i) delete queues_[i]; delete queue_; } StateId Head() const { return queue_->Head(); } void Enqueue(StateId s) { queue_->Enqueue(s); } void Dequeue() { queue_->Dequeue(); } void Update(StateId s) { queue_->Update(s); } bool Empty() const { return queue_->Empty(); } void Clear() { queue_->Clear(); } private: QueueBase<StateId> *queue_; vector< QueueBase<StateId>* > queues_; vector<StateId> scc_; template <class Arc, class ArcFilter, class Less> static void SccQueueType(const Fst<Arc> &fst, const vector<StateId> &scc, vector<QueueType> *queue_types, ArcFilter filter, Less *less, bool *all_trivial, bool *unweighted); // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } DISALLOW_COPY_AND_ASSIGN(AutoQueue); }; // Examines the states in an Fst's strongly connected components and // determines which type of queue to use per SCC. Stores result in // vector QUEUE_TYPES, which is assumed to have length equal to the // number of SCCs. An arc filter is used to limit the transitions // considered (e.g., only the epsilon graph). ALL_TRIVIAL is set // to true if every queue is the trivial queue. UNWEIGHTED is set to // true if the semiring is idempotent and all the arc weights are equal to // Zero() or One(). template <class StateId> template <class A, class ArcFilter, class Less> void AutoQueue<StateId>::SccQueueType(const Fst<A> &fst, const vector<StateId> &scc, vector<QueueType> *queue_type, ArcFilter filter, Less *less, bool *all_trivial, bool *unweighted) { typedef A Arc; typedef typename A::StateId StateId; typedef typename A::Weight Weight; *all_trivial = true; *unweighted = true; for (StateId i = 0; i < queue_type->size(); ++i) (*queue_type)[i] = TRIVIAL_QUEUE; for (StateIterator< Fst<Arc> > sit(fst); !sit.Done(); sit.Next()) { StateId state = sit.Value(); for (ArcIterator< Fst<Arc> > ait(fst, state); !ait.Done(); ait.Next()) { const Arc &arc = ait.Value(); if (!filter(arc)) continue; if (scc[state] == scc[arc.nextstate]) { QueueType &type = (*queue_type)[scc[state]]; if (!less || ((*less)(arc.weight, Weight::One()))) type = FIFO_QUEUE; else if ((type == TRIVIAL_QUEUE) || (type == LIFO_QUEUE)) { if (!(Weight::Properties() & kIdempotent) || (arc.weight != Weight::Zero() && arc.weight != Weight::One())) type = SHORTEST_FIRST_QUEUE; else type = LIFO_QUEUE; } if (type != TRIVIAL_QUEUE) *all_trivial = false; } if (!(Weight::Properties() & kIdempotent) || (arc.weight != Weight::Zero() && arc.weight != Weight::One())) *unweighted = false; } } } // An A* estimate is a function object that maps from a state ID to a // an estimate of the shortest distance to the final states. // The trivial A* estimate is always One(). template <typename S, typename W> struct TrivialAStarEstimate { W operator()(S s) const { return W::One(); } }; // Given a vector that maps from states to weights representing the // shortest distance from the initial state, a Less comparison // function object between weights, and an estimate E of the // shortest distance to the final states, this class defines a // comparison function object between states. template <typename S, typename L, typename E> class AStarWeightCompare { public: typedef L Less; typedef typename L::Weight Weight; typedef S StateId; AStarWeightCompare(const vector<Weight>& weights, const L &less, const E &estimate) : weights_(weights), less_(less), estimate_(estimate) {} bool operator()(const S x, const S y) const { Weight wx = Times(weights_[x], estimate_(x)); Weight wy = Times(weights_[y], estimate_(y)); return less_(wx, wy); } private: const vector<Weight>& weights_; L less_; const E &estimate_; }; // A* queue discipline, templated on the StateId, Weight and an // estimate E of the shortest distance to the final states, is specialized // to use the weight's natural order for the comparison function. template <typename S, typename W, typename E> class NaturalAStarQueue : public ShortestFirstQueue<S, AStarWeightCompare<S, NaturalLess<W>, E> > { public: typedef AStarWeightCompare<S, NaturalLess<W>, E> C; NaturalAStarQueue(const vector<W> &distance, const E &estimate) : ShortestFirstQueue<S, C>(C(distance, less_, estimate)) {} private: NaturalLess<W> less_; }; // A state equivalence class is a function object that // maps from a state ID to an equivalence class (state) ID. // The trivial equivalence class maps a state to itself. template <typename S> struct TrivialStateEquivClass { S operator()(S s) const { return s; } }; // Distance-based pruning queue discipline: Enqueues a state 's' // only when its shortest distance (so far), as specified by // 'distance', is less than (as specified by 'comp') the shortest // distance Times() the 'threshold' to any state in the same // equivalence class, as specified by the function object // 'class_func'. The underlying queue discipline is specified by // 'queue'. The ownership of 'queue' is given to this class. template <typename Q, typename L, typename C> class PruneQueue : public QueueBase<typename Q::StateId> { public: typedef typename Q::StateId StateId; typedef typename L::Weight Weight; PruneQueue(const vector<Weight> &distance, Q *queue, L comp, const C &class_func, Weight threshold) : QueueBase<StateId>(OTHER_QUEUE), distance_(distance), queue_(queue), less_(comp), class_func_(class_func), threshold_(threshold) {} ~PruneQueue() { delete queue_; } StateId Head() const { return queue_->Head(); } void Enqueue(StateId s) { StateId c = class_func_(s); if (c >= class_distance_.size()) class_distance_.resize(c + 1, Weight::Zero()); if (less_(distance_[s], class_distance_[c])) class_distance_[c] = distance_[s]; // Enqueue only if below threshold limit Weight limit = Times(class_distance_[c], threshold_); if (less_(distance_[s], limit)) queue_->Enqueue(s); } void Dequeue() { queue_->Dequeue(); } void Update(StateId s) { StateId c = class_func_(s); if (less_(distance_[s], class_distance_[c])) class_distance_[c] = distance_[s]; queue_->Update(s); } bool Empty() const { return queue_->Empty(); } void Clear() { queue_->Clear(); } private: // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } const vector<Weight> &distance_; // shortest distance to state Q *queue_; L less_; const C &class_func_; // eqv. class function object Weight threshold_; // pruning weight threshold vector<Weight> class_distance_; // shortest distance to class DISALLOW_COPY_AND_ASSIGN(PruneQueue); }; // Pruning queue discipline (see above) using the weight's natural // order for the comparison function. The ownership of 'queue' is // given to this class. template <typename Q, typename W, typename C> class NaturalPruneQueue : public PruneQueue<Q, NaturalLess<W>, C> { public: typedef typename Q::StateId StateId; typedef W Weight; NaturalPruneQueue(const vector<W> &distance, Q *queue, const C &class_func_, Weight threshold) : PruneQueue<Q, NaturalLess<W>, C>(distance, queue, NaturalLess<W>(), class_func_, threshold) {} }; // Filter-based pruning queue discipline: Enqueues a state 's' only // if allowed by the filter, specified by the function object 'state_filter'. // The underlying queue discipline is specified by 'queue'. The ownership // of 'queue' is given to this class. template <typename Q, typename F> class FilterQueue : public QueueBase<typename Q::StateId> { public: typedef typename Q::StateId StateId; FilterQueue(Q *queue, const F &state_filter) : QueueBase<StateId>(OTHER_QUEUE), queue_(queue), state_filter_(state_filter) {} ~FilterQueue() { delete queue_; } StateId Head() const { return queue_->Head(); } // Enqueues only if allowed by state filter. void Enqueue(StateId s) { if (state_filter_(s)) { queue_->Enqueue(s); } } void Dequeue() { queue_->Dequeue(); } void Update(StateId s) {} bool Empty() const { return queue_->Empty(); } void Clear() { queue_->Clear(); } private: // This allows base-class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual StateId Head_() const { return Head(); } virtual void Enqueue_(StateId s) { Enqueue(s); } virtual void Dequeue_() { Dequeue(); } virtual void Update_(StateId s) { Update(s); } virtual bool Empty_() const { return Empty(); } virtual void Clear_() { return Clear(); } Q *queue_; const F &state_filter_; // Filter to prune states DISALLOW_COPY_AND_ASSIGN(FilterQueue); }; } // namespace fst #endif <|start_filename|>third_party/openfst/src/include/fst/complement.h<|end_filename|> // complement.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to complement an Fst. #ifndef FST_LIB_COMPLEMENT_H__ #define FST_LIB_COMPLEMENT_H__ #include <algorithm> #include <string> #include <vector> using std::vector; #include <fst/fst.h> #include <fst/test-properties.h> namespace fst { template <class A> class ComplementFst; // Implementation of delayed ComplementFst. The algorithm used // completes the (deterministic) FSA and then exchanges final and // non-final states. Completion, i.e. ensuring that all labels can be // read from every state, is accomplished by using RHO labels, which // match all labels that are otherwise not found leaving a state. The // first state in the output is reserved to be a new state that is the // destination of all RHO labels. Each remaining output state s // corresponds to input state s - 1. The first arc in the output at // these states is the rho label, the remaining arcs correspond to the // input arcs. template <class A> class ComplementFstImpl : public FstImpl<A> { public: using FstImpl<A>::SetType; using FstImpl<A>::SetProperties; using FstImpl<A>::SetInputSymbols; using FstImpl<A>::SetOutputSymbols; friend class StateIterator< ComplementFst<A> >; friend class ArcIterator< ComplementFst<A> >; typedef A Arc; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; explicit ComplementFstImpl(const Fst<A> &fst) : fst_(fst.Copy()) { SetType("complement"); uint64 props = fst.Properties(kILabelSorted, false); SetProperties(ComplementProperties(props), kCopyProperties); SetInputSymbols(fst.InputSymbols()); SetOutputSymbols(fst.OutputSymbols()); } ComplementFstImpl(const ComplementFstImpl<A> &impl) : fst_(impl.fst_->Copy()) { SetType("complement"); SetProperties(impl.Properties(), kCopyProperties); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); } ~ComplementFstImpl() { delete fst_; } StateId Start() const { if (Properties(kError)) return kNoStateId; StateId start = fst_->Start(); if (start != kNoStateId) return start + 1; else return 0; } // Exchange final and non-final states; make rho destination state final. Weight Final(StateId s) const { if (s == 0 || fst_->Final(s - 1) == Weight::Zero()) return Weight::One(); else return Weight::Zero(); } size_t NumArcs(StateId s) const { if (s == 0) return 1; else return fst_->NumArcs(s - 1) + 1; } size_t NumInputEpsilons(StateId s) const { return s == 0 ? 0 : fst_->NumInputEpsilons(s - 1); } size_t NumOutputEpsilons(StateId s) const { return s == 0 ? 0 : fst_->NumOutputEpsilons(s - 1); } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if ((mask & kError) && fst_->Properties(kError, false)) SetProperties(kError, kError); return FstImpl<Arc>::Properties(mask); } private: const Fst<A> *fst_; void operator=(const ComplementFstImpl<A> &fst); // Disallow }; // Complements an automaton. This is a library-internal operation that // introduces a (negative) 'rho' label; use Difference/DifferenceFst in // user code, which will not see this label. This version is a delayed Fst. // // This class attaches interface to implementation and handles // reference counting, delegating most methods to ImplToFst. template <class A> class ComplementFst : public ImplToFst< ComplementFstImpl<A> > { public: friend class StateIterator< ComplementFst<A> >; friend class ArcIterator< ComplementFst<A> >; using ImplToFst< ComplementFstImpl<A> >::GetImpl; typedef A Arc; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef ComplementFstImpl<A> Impl; explicit ComplementFst(const Fst<A> &fst) : ImplToFst<Impl>(new Impl(fst)) { uint64 props = kUnweighted | kNoEpsilons | kIDeterministic | kAcceptor; if (fst.Properties(props, true) != props) { FSTERROR() << "ComplementFst: argument not an unweighted " << "epsilon-free deterministic acceptor"; GetImpl()->SetProperties(kError, kError); } } // See Fst<>::Copy() for doc. ComplementFst(const ComplementFst<A> &fst, bool safe = false) : ImplToFst<Impl>(fst, safe) {} // Get a copy of this ComplementFst. See Fst<>::Copy() for further doc. virtual ComplementFst<A> *Copy(bool safe = false) const { return new ComplementFst<A>(*this, safe); } virtual inline void InitStateIterator(StateIteratorData<A> *data) const; virtual inline void InitArcIterator(StateId s, ArcIteratorData<A> *data) const; // Label that represents the rho transition. // We use a negative value, which is thus private to the library and // which will preserve FST label sort order. static const Label kRhoLabel = -2; private: // Makes visible to friends. Impl *GetImpl() const { return ImplToFst<Impl>::GetImpl(); } void operator=(const ComplementFst<A> &fst); // disallow }; template <class A> const typename A::Label ComplementFst<A>::kRhoLabel; // Specialization for ComplementFst. template <class A> class StateIterator< ComplementFst<A> > : public StateIteratorBase<A> { public: typedef typename A::StateId StateId; typedef typename A::Label Label; explicit StateIterator(const ComplementFst<A> &fst) : siter_(*fst.GetImpl()->fst_), s_(0) { } bool Done() const { return s_ > 0 && siter_.Done(); } StateId Value() const { return s_; } void Next() { if (s_ != 0) siter_.Next(); ++s_; } void Reset() { siter_.Reset(); s_ = 0; } private: // This allows base class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual bool Done_() const { return Done(); } virtual StateId Value_() const { return Value(); } virtual void Next_() { Next(); } virtual void Reset_() { Reset(); } StateIterator< Fst<A> > siter_; StateId s_; DISALLOW_COPY_AND_ASSIGN(StateIterator); }; // Specialization for ComplementFst. template <class A> class ArcIterator< ComplementFst<A> > : public ArcIteratorBase<A> { public: typedef typename A::StateId StateId; typedef typename A::Label Label; typedef typename A::Weight Weight; ArcIterator(const ComplementFst<A> &fst, StateId s) : aiter_(0), s_(s), pos_(0) { if (s_ != 0) aiter_ = new ArcIterator< Fst<A> >(*fst.GetImpl()->fst_, s - 1); } virtual ~ArcIterator() { delete aiter_; } bool Done() const { if (s_ != 0) return pos_ > 0 && aiter_->Done(); else return pos_ > 0; } // Adds the rho label to the rho destination state. const A& Value() const { if (pos_ == 0) { arc_.ilabel = arc_.olabel = ComplementFst<A>::kRhoLabel; arc_.weight = Weight::One(); arc_.nextstate = 0; } else { arc_ = aiter_->Value(); ++arc_.nextstate; } return arc_; } void Next() { if (s_ != 0 && pos_ > 0) aiter_->Next(); ++pos_; } size_t Position() const { return pos_; } void Reset() { if (s_ != 0) aiter_->Reset(); pos_ = 0; } void Seek(size_t a) { if (s_ != 0) { if (a == 0) { aiter_->Reset(); } else { aiter_->Seek(a - 1); } } pos_ = a; } uint32 Flags() const { return kArcValueFlags; } void SetFlags(uint32 f, uint32 m) {} private: // This allows base class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual bool Done_() const { return Done(); } virtual const A& Value_() const { return Value(); } virtual void Next_() { Next(); } virtual size_t Position_() const { return Position(); } virtual void Reset_() { Reset(); } virtual void Seek_(size_t a) { Seek(a); } uint32 Flags_() const { return Flags(); } void SetFlags_(uint32 f, uint32 m) { SetFlags(f, m); } ArcIterator< Fst<A> > *aiter_; StateId s_; size_t pos_; mutable A arc_; DISALLOW_COPY_AND_ASSIGN(ArcIterator); }; template <class A> inline void ComplementFst<A>::InitStateIterator(StateIteratorData<A> *data) const { data->base = new StateIterator< ComplementFst<A> >(*this); } template <class A> inline void ComplementFst<A>::InitArcIterator(StateId s, ArcIteratorData<A> *data) const { data->base = new ArcIterator< ComplementFst<A> >(*this, s); } // Useful alias when using StdArc. typedef ComplementFst<StdArc> StdComplementFst; } // namespace fst #endif // FST_LIB_COMPLEMENT_H__ <|start_filename|>third_party/openfst/src/include/fst/state-reachable.h<|end_filename|> // state-reachable.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to determine whether a given (final) state can be reached from some // other given state. #ifndef FST_LIB_STATE_REACHABLE_H__ #define FST_LIB_STATE_REACHABLE_H__ #include <vector> using std::vector; #include <fst/dfs-visit.h> #include <fst/connect.h> #include <fst/fst.h> #include <fst/interval-set.h> #include <fst/vector-fst.h> namespace fst { // Computes the (final) states reachable from a given state in an FST. // After this visitor has been called, a final state f can be reached // from a state s iff (*isets)[s].Member(state2index[f]) is true, where // (*isets[s]) is a set of half-open inteval of final state indices // and state2index[f] maps from a final state to its index. // // If state2index is empty, it is filled-in with suitable indices. // If it is non-empty, those indices are used; in this case, the // final states must have out-degree 0. template <class A, typename I = typename A::StateId> class IntervalReachVisitor { public: typedef typename A::StateId StateId; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename IntervalSet<I>::Interval Interval; IntervalReachVisitor(const Fst<A> &fst, vector< IntervalSet<I> > *isets, vector<I> *state2index) : fst_(fst), isets_(isets), state2index_(state2index), index_(state2index->empty() ? 1 : -1), error_(false) { isets_->clear(); } void InitVisit(const Fst<A> &fst) { error_ = false; } bool InitState(StateId s, StateId r) { while (isets_->size() <= s) isets_->push_back(IntervalSet<Label>()); while (state2index_->size() <= s) state2index_->push_back(-1); if (fst_.Final(s) != Weight::Zero()) { // Create tree interval vector<Interval> *intervals = (*isets_)[s].Intervals(); if (index_ < 0) { // Use state2index_ map to set index if (fst_.NumArcs(s) > 0) { FSTERROR() << "IntervalReachVisitor: state2index map must be empty " << "for this FST"; error_ = true; return false; } I index = (*state2index_)[s]; if (index < 0) { FSTERROR() << "IntervalReachVisitor: state2index map incomplete"; error_ = true; return false; } intervals->push_back(Interval(index, index + 1)); } else { // Use pre-order index intervals->push_back(Interval(index_, index_ + 1)); (*state2index_)[s] = index_++; } } return true; } bool TreeArc(StateId s, const A &arc) { return true; } bool BackArc(StateId s, const A &arc) { FSTERROR() << "IntervalReachVisitor: cyclic input"; error_ = true; return false; } bool ForwardOrCrossArc(StateId s, const A &arc) { // Non-tree interval (*isets_)[s].Union((*isets_)[arc.nextstate]); return true; } void FinishState(StateId s, StateId p, const A *arc) { if (index_ >= 0 && fst_.Final(s) != Weight::Zero()) { vector<Interval> *intervals = (*isets_)[s].Intervals(); (*intervals)[0].end = index_; // Update tree interval end } (*isets_)[s].Normalize(); if (p != kNoStateId) (*isets_)[p].Union((*isets_)[s]); // Propagate intervals to parent } void FinishVisit() {} bool Error() const { return error_; } private: const Fst<A> &fst_; vector< IntervalSet<I> > *isets_; vector<I> *state2index_; I index_; bool error_; }; // Tests reachability of final states from a given state. To test for // reachability from a state s, first do SetState(s). Then a final // state f can be reached from state s of FST iff Reach(f) is true. // The input can be cyclic, but no cycle may contain a final state. template <class A, typename I = typename A::StateId> class StateReachable { public: typedef A Arc; typedef I Index; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename IntervalSet<I>::Interval Interval; StateReachable(const Fst<A> &fst) : error_(false) { if (fst.Properties(kAcyclic, true)) { AcyclicStateReachable(fst); } else { CyclicStateReachable(fst); } } StateReachable(const StateReachable<A> &reachable) { FSTERROR() << "Copy constructor for state reachable class " << "not implemented."; error_ = true; } // Set current state. void SetState(StateId s) { s_ = s; } // Can reach this final state from current state? bool Reach(StateId s) { if (s >= state2index_.size()) return false; I i = state2index_[s]; if (i < 0) { FSTERROR() << "StateReachable: state non-final: " << s; error_ = true; return false; } return isets_[s_].Member(i); } // Access to the state-to-index mapping. Unassigned states have index -1. vector<I> &State2Index() { return state2index_; } // Access to the interval sets. These specify the reachability // to the final states as intervals of the final state indices. const vector< IntervalSet<I> > &IntervalSets() { return isets_; } bool Error() const { return error_; } private: void AcyclicStateReachable(const Fst<A> &fst) { IntervalReachVisitor<Arc> reach_visitor(fst, &isets_, &state2index_); DfsVisit(fst, &reach_visitor); if (reach_visitor.Error()) error_ = true; } void CyclicStateReachable(const Fst<A> &fst) { // Finds state reachability on the acyclic condensation FST VectorFst<Arc> cfst; vector<StateId> scc; Condense(fst, &cfst, &scc); StateReachable reachable(cfst); if (reachable.Error()) { error_ = true; return; } // Gets the number of states per SCC. vector<size_t> nscc; for (StateId s = 0; s < scc.size(); ++s) { StateId c = scc[s]; while (c >= nscc.size()) nscc.push_back(0); ++nscc[c]; } // Constructs the interval sets and state index mapping for // the original FST from the condensation FST. state2index_.resize(scc.size(), -1); isets_.resize(scc.size()); for (StateId s = 0; s < scc.size(); ++s) { StateId c = scc[s]; isets_[s] = reachable.IntervalSets()[c]; state2index_[s] = reachable.State2Index()[c]; // Checks that each final state in an input FST is not // contained in a cycle (i.e. not in a non-trivial SCC). if (cfst.Final(c) != Weight::Zero() && nscc[c] > 1) { FSTERROR() << "StateReachable: final state contained in a cycle"; error_ = true; return; } } } StateId s_; // Current state vector< IntervalSet<I> > isets_; // Interval sets per state vector<I> state2index_; // Finds index for a final state bool error_; void operator=(const StateReachable<A> &); // Disallow }; } // namespace fst #endif // FST_LIB_STATE_REACHABLE_H__ <|start_filename|>third_party/openfst/src/include/fst/extensions/far/extract.h<|end_filename|> // extract-main.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use the new arc-dispatch // \file // Extracts component FSTs from an finite-state archive. // #ifndef FST_EXTENSIONS_FAR_EXTRACT_H__ #define FST_EXTENSIONS_FAR_EXTRACT_H__ #include <string> #include <vector> using std::vector; #include <fst/extensions/far/far.h> namespace fst { template<class Arc> inline void FarWriteFst(const Fst<Arc>* fst, string key, string* okey, int* nrep, const int32 &generate_filenames, int i, const string &filename_prefix, const string &filename_suffix) { if (key == *okey) ++*nrep; else *nrep = 0; *okey = key; string ofilename; if (generate_filenames) { ostringstream tmp; tmp.width(generate_filenames); tmp.fill('0'); tmp << i; ofilename = tmp.str(); } else { if (*nrep > 0) { ostringstream tmp; tmp << '.' << nrep; key.append(tmp.str().data(), tmp.str().size()); } ofilename = key; } fst->Write(filename_prefix + ofilename + filename_suffix); } template<class Arc> void FarExtract(const vector<string> &ifilenames, const int32 &generate_filenames, const string &keys, const string &key_separator, const string &range_delimiter, const string &filename_prefix, const string &filename_suffix) { FarReader<Arc> *far_reader = FarReader<Arc>::Open(ifilenames); if (!far_reader) return; string okey; int nrep = 0; vector<char *> key_vector; // User has specified a set of fsts to extract, where some of the "fsts" could // be ranges. if (!keys.empty()) { char *keys_cstr = new char[keys.size()+1]; strcpy(keys_cstr, keys.c_str()); SplitToVector(keys_cstr, key_separator.c_str(), &key_vector, true); int i = 0; for (int k = 0; k < key_vector.size(); ++k, ++i) { string key = string(key_vector[k]); char *key_cstr = new char[key.size()+1]; strcpy(key_cstr, key.c_str()); vector<char *> range_vector; SplitToVector(key_cstr, range_delimiter.c_str(), &range_vector, false); if (range_vector.size() == 1) { // Not a range if (!far_reader->Find(key)) { LOG(ERROR) << "FarExtract: Cannot find key: " << key; return; } const Fst<Arc> &fst = far_reader->GetFst(); FarWriteFst(&fst, key, &okey, &nrep, generate_filenames, i, filename_prefix, filename_suffix); } else if (range_vector.size() == 2) { // A legal range string begin_key = string(range_vector[0]); string end_key = string(range_vector[1]); if (begin_key.empty() || end_key.empty()) { LOG(ERROR) << "FarExtract: Illegal range specification: " << key; return; } if (!far_reader->Find(begin_key)) { LOG(ERROR) << "FarExtract: Cannot find key: " << begin_key; return; } for ( ; !far_reader->Done(); far_reader->Next(), ++i) { string ikey = far_reader->GetKey(); if (end_key < ikey) break; const Fst<Arc> &fst = far_reader->GetFst(); FarWriteFst(&fst, ikey, &okey, &nrep, generate_filenames, i, filename_prefix, filename_suffix); } } else { LOG(ERROR) << "FarExtract: Illegal range specification: " << key; return; } delete [] key_cstr; } delete [] keys_cstr; return; } // Nothing specified: extract everything. for (int i = 1; !far_reader->Done(); far_reader->Next(), ++i) { string key = far_reader->GetKey(); const Fst<Arc> &fst = far_reader->GetFst(); FarWriteFst(&fst, key, &okey, &nrep, generate_filenames, i, filename_prefix, filename_suffix); } return; } } // namespace fst #endif // FST_EXTENSIONS_FAR_EXTRACT_H__ <|start_filename|>third_party/openfst/src/include/fst/cache.h<|end_filename|> // cache.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // An Fst implementation that caches FST elements of a delayed // computation. #ifndef FST_LIB_CACHE_H__ #define FST_LIB_CACHE_H__ #include <functional> #include <list> #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <vector> using std::vector; #include <fst/vector-fst.h> DECLARE_bool(fst_default_cache_gc); DECLARE_int64(fst_default_cache_gc_limit); namespace fst { // Options for controlling caching behavior; higher // level than CacheImplOptions. struct CacheOptions { bool gc; // enable GC size_t gc_limit; // # of bytes allowed before GC CacheOptions(bool g, size_t l) : gc(g), gc_limit(l) {} CacheOptions() : gc(FLAGS_fst_default_cache_gc), gc_limit(FLAGS_fst_default_cache_gc_limit) {} }; // Options for controlling caching behavior; lower // level than CacheOptions - templated on the // cache store and allows passing the store. template <class C> struct CacheImplOptions { bool gc; // enable GC size_t gc_limit; // # of bytes allowed before GC C *store; // cache store CacheImplOptions(bool g, size_t l, C s = 0) : gc(g), gc_limit(l), store(0) {} explicit CacheImplOptions(const CacheOptions &opts) : gc(opts.gc), gc_limit(opts.gc_limit), store(0) {} CacheImplOptions() : gc(FLAGS_fst_default_cache_gc), gc_limit(FLAGS_fst_default_cache_gc_limit), store(0) {} }; // CACHE FLAGS const uint32 kCacheFinal = 0x0001; // Final weight has been cached const uint32 kCacheArcs = 0x0002; // Arcs have been cached const uint32 kCacheInit = 0x0004; // Initialized by GC const uint32 kCacheRecent = 0x0008; // Visited since GC const uint32 kCacheFlags = kCacheFinal | kCacheArcs | kCacheInit | kCacheRecent; // CACHE STATE - Arcs implemented by an STL vector per state. template <class A, class M = PoolAllocator<A> > class CacheState { public: typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef M ArcAllocator; typedef typename ArcAllocator::template rebind<CacheState<A, M> >::other StateAllocator; // Provide STL allocator for arcs explicit CacheState(const ArcAllocator &alloc) : final_(Weight::Zero()), niepsilons_(0), noepsilons_(0), arcs_(alloc), flags_(0), ref_count_(0) {} CacheState(const CacheState<A> &state, const ArcAllocator &alloc) : final_(state.Final()), niepsilons_(state.NumInputEpsilons()), noepsilons_(state.NumOutputEpsilons()), arcs_(state.arcs_.begin(), state.arcs_.end(), alloc), flags_(state.Flags()), ref_count_(0) { } void Reset() { final_ = Weight::Zero(); niepsilons_ = 0; noepsilons_ = 0; ref_count_ = 0; flags_ = 0; arcs_.clear(); } Weight Final() const { return final_; } size_t NumInputEpsilons() const { return niepsilons_; } size_t NumOutputEpsilons() const { return noepsilons_; } size_t NumArcs() const { return arcs_.size(); } const A &GetArc(size_t n) const { return arcs_[n]; } // Used by the ArcIterator<Fst<A>> efficient implementation. const A *Arcs() const { return arcs_.size() > 0 ? &arcs_[0] : 0; } // Accesses flags; used by the caller uint32 Flags() const { return flags_; } // Accesses ref count; used by the caller int RefCount() const { return ref_count_; } void SetFinal(Weight final) { final_ = final; } void ReserveArcs(size_t n) { arcs_.reserve(n); } // Adds one arc at a time with all needed book-keeping. // Can use PushArc's and SetArcs instead as more efficient alternative. void AddArc(const A &arc) { arcs_.push_back(arc); if (arc.ilabel == 0) ++niepsilons_; if (arc.olabel == 0) ++noepsilons_; } // Adds one arc at a time with delayed book-keeping; finalize with SetArcs() void PushArc(const A &arc) { arcs_.push_back(arc); } // Finalizes arcs book-keeping; call only once void SetArcs() { for (size_t a = 0; a < arcs_.size(); ++a) { const Arc &arc = arcs_[a]; if (arc.ilabel == 0) ++niepsilons_; if (arc.olabel == 0) ++noepsilons_; } } // Modifies nth arc void SetArc(const A &arc, size_t n) { if (arcs_[n].ilabel == 0) --niepsilons_; if (arcs_[n].olabel == 0) --noepsilons_; if (arc.ilabel == 0) ++niepsilons_; if (arc.olabel == 0) ++noepsilons_; arcs_[n] = arc; } // Deletes all arcs void DeleteArcs() { niepsilons_ = 0; noepsilons_ = 0; arcs_.clear(); } void DeleteArcs(size_t n) { for (size_t i = 0; i < n; ++i) { if (arcs_.back().ilabel == 0) --niepsilons_; if (arcs_.back().olabel == 0) --noepsilons_; arcs_.pop_back(); } } // Sets status flags; used by the caller void SetFlags(uint32 flags, uint32 mask) const { flags_ &= ~mask; flags_ |= flags; } // Mutates ref counts; used by the caller int IncrRefCount() const { return ++ref_count_; } int DecrRefCount() const { return --ref_count_; } // Used by the ArcIterator<Fst<A>> efficient implementation. int *MutableRefCount() const { return &ref_count_; } // For state class allocation void *operator new(size_t size, StateAllocator *alloc) { return alloc->allocate(1); } // For state destruction and memory freeing static void Destroy(CacheState<A> *state, StateAllocator *alloc) { if (state) { state->~CacheState<A>(); alloc->deallocate(state, 1); } } private: Weight final_; // Final weight size_t niepsilons_; // # of input epsilons size_t noepsilons_; // # of output epsilons vector<A, ArcAllocator> arcs_; // Arcs represenation mutable uint32 flags_; mutable int ref_count_; // if 0, avail. for GC; used by arc iterators DISALLOW_COPY_AND_ASSIGN(CacheState); }; // CACHE STORE - these allocate and store states, provide a mapping // from state IDs to cached states and an iterator over // the states. The state template argument should be a CacheState // as above (or have the same interface). The state for StateId s // is constructed when requested by GetMutableState(s) if it not // yet stored. Initially a state has RefCount() = 0; the user may increment // and decrement to control the time of destruction. In particular, this state // is destroyed when: // (1) this class is destroyed or // (2) Clear() is called or Delete() for it is called or // (3) possibly when: // (a) opts.gc = true and // (b) the cache store size exceeds opts.gc_limit bytes and // (c) the state's RefCount() is zero and // (d) the state is not the most recently requested state. // The actual GC behavior is up to the specific store. // // template <class S> // class CacheStore { // public: // typedef S State; // typedef typename State::Arc Arc; // typedef typename Arc::StateId StateId; // // // Required constructors/assignment operators // explicit CacheStore(const CacheOptions &opts); // CacheStore(const CacheStore &store); // CacheStore<State> &operator=(const CacheStore<State> &store); // // // Returns 0 if state is not stored // const State *GetState(StateId s); // // // Creates state if state is not stored // State *GetMutableState(StateId s); // // // Similar to State::AddArc() but updates cache store book-keeping // void AddArc(StateId *state, const Arc &arc); // // // Similar to State::SetArcs() but updates cache store book-keeping // // Call only once. // void SetArcs(StateId *state); // // // Similar to State::DeleteArcs() but updates cache store book-keeping // void DeleteArcs(State *state); // void DeleteArcs(State *state, size_t n); // // // Deletes all cached states // void Clear(); // // // // Iterates over cached states (in an arbitrary order). // // Only needed if opts.gc is true // bool Done() const; // End of iteration // StateId Value() const; // Current state // void Next(); // Advances to next state (when !Done) // void Reset(); // Return to initial condition // void Delete(); // Deletes current state and advances to next // }; // // CONTAINER CACHE STORES - these simply hold states // // This class uses a vector of pointers to states to store cached states. template <class S> class VectorCacheStore { public: typedef S State; typedef typename State::Arc Arc; typedef typename Arc::StateId StateId; typedef list<StateId, PoolAllocator<StateId> > StateList; // Required constructors/assignment operators explicit VectorCacheStore(const CacheOptions &opts) : cache_gc_(opts.gc) { Clear(); Reset(); } VectorCacheStore(const VectorCacheStore<S> &store) : cache_gc_(store.cache_gc_) { CopyStates(store); Reset(); } ~VectorCacheStore() { Clear(); } VectorCacheStore<State> &operator=(const VectorCacheStore<State> &store) { if (this != &store) { CopyStates(store); Reset(); } return *this; } // Returns 0 if state is not stored const State *GetState(StateId s) const { return s < state_vec_.size() ? state_vec_[s] : 0; } // Creates state if state is not stored State *GetMutableState(StateId s) { State *state = 0; if (s >= state_vec_.size()) { state_vec_.resize(s + 1, 0); } else { state = state_vec_[s]; } if (state == 0) { state = new(&state_alloc_) State(arc_alloc_); state_vec_[s] = state; if (cache_gc_) state_list_.push_back(s); } return state; } // Similar to State::AddArc() but updates cache store book-keeping void AddArc(State *state, const Arc &arc) { state->AddArc(arc); } // Similar to State::SetArcs() but updates internal cache size. // Call only once. void SetArcs(State *state) { state->SetArcs(); } // Deletes all arcs void DeleteArcs(State *state) { state->DeleteArcs(); } // Deletes some arcs void DeleteArcs(State *state, size_t n) { state->DeleteArcs(n); } // Deletes all cached states void Clear() { for (StateId s = 0; s < state_vec_.size(); ++s) State::Destroy(state_vec_[s], &state_alloc_); state_vec_.clear(); state_list_.clear(); } // Iterates over cached states (in an arbitrary order). // Only works if GC is enabled (o.w. avoiding state_list_ overhead). bool Done() const { return iter_ == state_list_.end(); } StateId Value() const { return *iter_; } void Next() { ++iter_; } void Reset() { iter_ = state_list_.begin(); } // Deletes current state and advances to next. void Delete() { State::Destroy(state_vec_[*iter_], &state_alloc_); state_vec_[*iter_] = 0; state_list_.erase(iter_++); } private: void CopyStates(const VectorCacheStore<State> &store) { Clear(); state_vec_.reserve(store.state_vec_.size()); for (StateId s = 0; s < store.state_vec_.size(); ++s) { S *state = 0; const State *store_state = store.state_vec_[s]; if (store_state) { state = new(&state_alloc_) State(*store_state, arc_alloc_); if (cache_gc_) state_list_.push_back(s); } state_vec_.push_back(state); } } bool cache_gc_; // supports iteration when true vector<State *> state_vec_; // vector of states (NULL if empty) StateList state_list_; // list of states typename StateList::iterator iter_; // state list iterator typename State::StateAllocator state_alloc_; // for state allocation typename State::ArcAllocator arc_alloc_; // for arc allocation }; // This class uses a hash map from state Ids to pointers to states // to store cached states. template <class S> class HashCacheStore { public: typedef S State; typedef typename State::Arc Arc; typedef typename Arc::StateId StateId; typedef unordered_map<StateId, State *, std::hash<StateId>, std::equal_to<StateId>, PoolAllocator<pair<const StateId, State *> > > StateMap; // Required constructors/assignment operators explicit HashCacheStore(const CacheOptions &opts) { Clear(); Reset(); } HashCacheStore(const HashCacheStore<S> &store) { CopyStates(store); Reset(); } ~HashCacheStore() { Clear(); } HashCacheStore<State> &operator=(const HashCacheStore<State> &store) { if (this != &store) { CopyStates(store); Reset(); } return *this; } // Returns 0 if state is not stoed const State *GetState(StateId s) const { const typename StateMap::const_iterator it = state_map_.find(s); return it != state_map_.end() ? it->second : 0; } // Creates state if state is not stored State *GetMutableState(StateId s) { State* &state = state_map_[s]; if (state == 0) state = new(&state_alloc_) State(arc_alloc_); return state; } // Similar to State::AddArc() but updates cache store book-keeping void AddArc(State *state, const Arc &arc) { state->AddArc(arc); } // Similar to State::SetArcs() but updates internal cache size. // Call only once. void SetArcs(State *state) { state->SetArcs(); } // Deletes all arcs void DeleteArcs(State *state) { state->DeleteArcs(); } // Deletes some arcs void DeleteArcs(State *state, size_t n) { state->DeleteArcs(n); } // Deletes all cached states void Clear() { for (typename StateMap::iterator it = state_map_.begin(); it != state_map_.end(); ++it) { State::Destroy(it->second, &state_alloc_); } state_map_.clear(); } // Iterates over cached states (in an arbitrary order). bool Done() const { typename StateMap::const_iterator citer = iter_; return citer == state_map_.end(); } StateId Value() const { return iter_->first; } void Next() { ++iter_; } void Reset() { iter_ = state_map_.begin(); } // Deletes current state and advances to next. void Delete() { State::Destroy(iter_->second, &state_alloc_); state_map_.erase(iter_++); } private: void CopyStates(const HashCacheStore<State> &store) { Clear(); for (typename StateMap::const_iterator it = store.state_map_.begin(); it != store.state_map_.end(); ++it) { StateId s = it->first; const S *state = it->second; state_map_[s] = new(&state_alloc_) State(*state, arc_alloc_); } } StateMap state_map_; // map from State Id to state typename StateMap::iterator iter_; // state map iterator typename State::StateAllocator state_alloc_; // for state allocation typename State::ArcAllocator arc_alloc_; // for arc allocation }; // // GARBAGE COLLECTION CACHE STORES - these garbage collect underlying // container cache stores. // // This class implements a simple garbage collection scheme when // 'opts.gc_limit' is 0. In particular, the first cached state is reused // for each new state so long as the reference count is zero on // the to-be-reused state. Otherwise, the full underlying store is used. // The caller can increment the reference count to inhibit the // GC of in-use states (e.g., in an ArcIterator). // // The typical use case for this optimization is when a single pass over // a cached FST is performed with only one-state expanded at a time. template <class C> class FirstCacheStore { public: typedef typename C::State State; typedef typename State::Arc Arc; typedef typename Arc::StateId StateId; // Required constructors/assignment operators explicit FirstCacheStore(const CacheOptions &opts) : store_(opts), cache_gc_(opts.gc_limit == 0), // opts.gc ignored historically cache_first_state_id_(kNoStateId), cache_first_state_(0) { } FirstCacheStore(const FirstCacheStore<C> &store) : store_(store.store_), cache_gc_(store.cache_gc_), cache_first_state_id_(store.cache_first_state_id_), cache_first_state_(store.cache_first_state_id_ != kNoStateId ? store_.GetMutableState(0) : 0) { } FirstCacheStore<C> &operator=(const FirstCacheStore<C> &store) { if (this != &store) { store_ = store.store_; cache_gc_ = store.cache_gc_; cache_first_state_id_ = store.cache_first_state_id_; cache_first_state_ = store.cache_first_state_id_ != kNoStateId ? store_.GetMutableState(0) : 0; } return *this; } // Returns 0 if state is not stored const State *GetState(StateId s) const { // store_ state 0 may hold first cached state; rest shifted + 1 return s == cache_first_state_id_ ? cache_first_state_ : store_.GetState(s + 1); } // Creates state if state is not stored State *GetMutableState(StateId s) { // store_ state 0 used to hold first cached state; rest shifted + 1 if (cache_first_state_id_ == s) return cache_first_state_; // request for first cached state if (cache_gc_) { if (cache_first_state_id_ == kNoStateId) { cache_first_state_id_ = s; // sets first cached state cache_first_state_ = store_.GetMutableState(0); cache_first_state_->SetFlags(kCacheInit, kCacheInit); cache_first_state_->ReserveArcs(2 * kAllocSize); return cache_first_state_; } else if (cache_first_state_->RefCount() == 0) { cache_first_state_id_ = s; // updates first cached state cache_first_state_->Reset(); cache_first_state_->SetFlags(kCacheInit, kCacheInit); return cache_first_state_; } else { // keeps first cached state cache_first_state_->SetFlags(0, kCacheInit); // clears initialized bit cache_gc_ = false; // disable GC } } State *state = store_.GetMutableState(s + 1); return state; } // Similar to State::AddArc() but updates cache store book-keeping void AddArc(State *state, const Arc &arc) { store_.AddArc(state, arc); } // Similar to State::SetArcs() but updates internal cache size. // Call only once. void SetArcs(State *state) { store_.SetArcs(state); } // Deletes all arcs void DeleteArcs(State *state) { store_.DeleteArcs(state); } // Deletes some arcs void DeleteArcs(State *state, size_t n) { store_.DeleteArcs(state, n); } // Deletes all cached states void Clear() { store_.Clear(); cache_first_state_id_ = kNoStateId; cache_first_state_ = 0; } // Iterates over cached states (in an arbitrary order). // Only needed if GC is enabled. bool Done() const { return store_.Done(); } StateId Value() const { // store_ state 0 may hold first cached state; rest shifted + 1 StateId s = store_.Value(); return s == 0 ? cache_first_state_id_ : s - 1; } void Next() { store_.Next(); } void Reset() { store_.Reset(); } // Deletes current state and advances to next. void Delete() { if (Value() == cache_first_state_id_) { cache_first_state_id_ = kNoStateId; cache_first_state_ = 0; } store_.Delete(); } private: C store_; // Underlying store bool cache_gc_; // GC enabled StateId cache_first_state_id_; // First cached state ID State *cache_first_state_; // First cached state }; // This class implements mark-sweep garbage collection on an // underlying cache store. If the 'gc' option is 'true', garbage // collection of states is performed in a rough approximation of LRU // order, when 'gc_limit' bytes is reached - controlling memory // use. The caller can increment the reference count to inhibit the // GC of in-use states (e.g., in an ArcIterator). With GC enabled, // the 'gc_limit' parameter allows the caller to trade-off time vs space. template <class C> class GCCacheStore { public: typedef typename C::State State; typedef typename State::Arc Arc; typedef typename Arc::StateId StateId; // Required constructors/assignment operators explicit GCCacheStore(const CacheOptions &opts) : store_(opts), cache_gc_request_(opts.gc), cache_limit_(opts.gc_limit > kMinCacheLimit ? opts.gc_limit : kMinCacheLimit), cache_gc_(false), cache_size_(0) { } // Returns 0 if state is not stored const State *GetState(StateId s) const { return store_.GetState(s); } // Creates state if state is not stored State *GetMutableState(StateId s) { State *state = store_.GetMutableState(s); if (cache_gc_request_ && !(state->Flags() & kCacheInit)) { state->SetFlags(kCacheInit, kCacheInit); cache_size_ += sizeof(State) + state->NumArcs() * sizeof(Arc); // GC is enabled once an uninited state (from underlying store) is seen cache_gc_ = true; if (cache_size_ > cache_limit_) GC(state, false); } return state; } // Similar to State::AddArc() but updates cache store book-keeping void AddArc(State *state, const Arc &arc) { store_.AddArc(state, arc); if (cache_gc_ && (state->Flags() & kCacheInit)) { cache_size_ += sizeof(Arc); if (cache_size_ > cache_limit_) GC(state, false); } } // Similar to State::SetArcs() but updates internal cache size. // Call only once. void SetArcs(State *state) { store_.SetArcs(state); if (cache_gc_ && (state->Flags() & kCacheInit)) { cache_size_ += state->NumArcs() * sizeof(Arc); if (cache_size_ > cache_limit_) GC(state, false); } } // Deletes all arcs void DeleteArcs(State *state) { if (cache_gc_ && (state->Flags() & kCacheInit)) cache_size_ -= state->NumArcs() * sizeof(Arc); store_.DeleteArcs(state); } // Deletes some arcs void DeleteArcs(State *state, size_t n) { if (cache_gc_ && (state->Flags() & kCacheInit)) cache_size_ -= n * sizeof(Arc); store_.DeleteArcs(state, n); } // Deletes all cached states void Clear() { store_.Clear(); cache_size_ = 0; } // Iterates over cached states (in an arbitrary order). // Only needed if GC is enabled. bool Done() const { return store_.Done(); } StateId Value() const { return store_.Value(); } void Next() { store_.Next(); } void Reset() { store_.Reset(); } // Deletes current state and advances to next. void Delete() { if (cache_gc_) { const State *state = store_.GetState(Value()); if (state->Flags() & kCacheInit) cache_size_ -= sizeof(State) + state->NumArcs() * sizeof(Arc); } store_.Delete(); } // Removes from the cache store (not referenced-counted and not the // current) states that have not been accessed since the last GC // until at most cache_fraction * cache_limit_ bytes are cached. If // that fails to free enough, recurs uncaching recently visited // states as well. If still unable to free enough memory, then // widens cache_limit_ to fulfill condition. void GC(const State *current, bool free_recent, float cache_fraction = 0.666); private: static const size_t kMinCacheLimit = 8096; // Min. cache limit C store_; // Underlying store bool cache_gc_request_; // GC requested but possibly not yet enabled size_t cache_limit_; // # of bytes allowed before GC bool cache_gc_; // GC enabled size_t cache_size_; // # of bytes cached }; // Removes from the cache store (not referenced-counted and not the // current) states that have not been accessed since the last GC until // at most cache_fraction * cache_limit_ bytes are cached. If that // fails to free enough, recurs uncaching recently visited states as // well. If still unable to free enough memory, then widens // cache_limit_ to fulfill condition. template <class C> void GCCacheStore<C>::GC(const State *current, bool free_recent, float cache_fraction) { if (!cache_gc_) return; VLOG(2) << "GCCacheStore: Enter GC: object = " << "(" << this << "), free recently cached = " << free_recent << ", cache size = " << cache_size_ << ", cache frac = " << cache_fraction << ", cache limit = " << cache_limit_ << "\n"; size_t cache_target = cache_fraction * cache_limit_; store_.Reset(); while (!store_.Done()) { State* state = store_.GetMutableState(store_.Value()); if (cache_size_ > cache_target && state->RefCount() == 0 && (free_recent || !(state->Flags() & kCacheRecent)) && state != current) { if (state->Flags() & kCacheInit) { size_t size = sizeof(State) + state->NumArcs() * sizeof(Arc); CHECK_LE(size, cache_size_); cache_size_ -= size; } store_.Delete(); } else { state->SetFlags(0, kCacheRecent); store_.Next(); } } if (!free_recent && cache_size_ > cache_target) { // recurses on recent GC(current, true, cache_fraction); } else if (cache_target > 0) { // widens cache limit while (cache_size_ > cache_target) { cache_limit_ *= 2; cache_target *= 2; } } else if (cache_size_ > 0) { FSTERROR() << "GCCacheStore:GC: Unable to free all cached states"; } VLOG(2) << "GCCacheStore: Exit GC: object = " << "(" << this << "), free recently cached = " << free_recent << ", cache size = " << cache_size_ << ", cache frac = " << cache_fraction << ", cache limit = " << cache_limit_ << "\n"; } template <class C> const size_t GCCacheStore<C>::kMinCacheLimit; // This class is the default cache state and store used by CacheBaseImpl. // It uses VectorCacheStore for storage decorated by FirstCacheStore // and GCCacheStore to do (optional) garbage collection. template <class A> class DefaultCacheStore : public GCCacheStore<FirstCacheStore< VectorCacheStore<CacheState<A> > > > { public: explicit DefaultCacheStore(const CacheOptions &opts) : GCCacheStore<FirstCacheStore< VectorCacheStore<CacheState<A> > > >(opts) { } }; // This class is used to cache FST elements stored in states of type S // (see CacheState) with the flags used to indicate what has been // cached. Use HasStart() HasFinal(), and HasArcs() to determine if // cached and SetStart(), SetFinal(), AddArc(), (or PushArc() and // SetArcs()) to cache. Note you must set the final weight even if the // state is non-final to mark it as cached. The state storage method // and any garbage collection policy are determined by the cache store C. // If the store is passed in with the options, CacheBaseImpl takes ownership. template <class S, class C = DefaultCacheStore<typename S::Arc> > class CacheBaseImpl : public FstImpl<typename S::Arc> { public: typedef S State; typedef C Store; typedef typename State::Arc Arc; typedef typename Arc::Weight Weight; typedef typename Arc::StateId StateId; using FstImpl<Arc>::Type; using FstImpl<Arc>::Properties; CacheBaseImpl() : has_start_(false), cache_start_(kNoStateId), nknown_states_(0), min_unexpanded_state_id_(0), max_expanded_state_id_(-1), cache_gc_(FLAGS_fst_default_cache_gc), cache_limit_(FLAGS_fst_default_cache_gc_limit), cache_store_(new C(CacheOptions())), new_cache_store_(true) { } explicit CacheBaseImpl(const CacheOptions &opts) : has_start_(false), cache_start_(kNoStateId), nknown_states_(0), min_unexpanded_state_id_(0), max_expanded_state_id_(-1), cache_gc_(opts.gc), cache_limit_(opts.gc_limit), cache_store_(new C(opts)), new_cache_store_(true) { } explicit CacheBaseImpl(const CacheImplOptions<C> &opts) : has_start_(false), cache_start_(kNoStateId), nknown_states_(0), min_unexpanded_state_id_(0), max_expanded_state_id_(-1), cache_gc_(opts.gc), cache_limit_(opts.gc_limit), cache_store_(opts.store ? opts.store : new C(CacheOptions(opts.gc, opts.gc_limit))), new_cache_store_(!opts.store) { } // Preserve gc parameters. If preserve_cache true, also preserves // cache data. CacheBaseImpl(const CacheBaseImpl<S, C> &impl, bool preserve_cache = false) : FstImpl<Arc>(), has_start_(false), cache_start_(kNoStateId), nknown_states_(0), min_unexpanded_state_id_(0), max_expanded_state_id_(-1), cache_gc_(impl.cache_gc_), cache_limit_(impl.cache_limit_), cache_store_(new C(CacheOptions(cache_gc_, cache_limit_))), new_cache_store_(impl.new_cache_store_ || !preserve_cache) { if (preserve_cache) { *cache_store_ = *impl.cache_store_; has_start_ = impl.has_start_; cache_start_ = impl.cache_start_; nknown_states_ = impl.nknown_states_; expanded_states_ = impl.expanded_states_; min_unexpanded_state_id_ = impl.min_unexpanded_state_id_; max_expanded_state_id_ = impl.max_expanded_state_id_; } } ~CacheBaseImpl() { delete cache_store_; } void SetStart(StateId s) { cache_start_ = s; has_start_ = true; if (s >= nknown_states_) nknown_states_ = s + 1; } void SetFinal(StateId s, Weight w) { S *state = cache_store_->GetMutableState(s); state->SetFinal(w); int32 flags = kCacheFinal | kCacheRecent; state->SetFlags(flags, flags); } // Disabled to ensure PushArc not AddArc is used in existing code // TODO(sorenj): re-enable for backing store #if 0 // AddArc adds a single arc to state s and does incremental cache // book-keeping. For efficiency, prefer PushArc and SetArcs below // when possible. void AddArc(StateId s, const Arc &arc) { S *state = cache_store_->GetMutableState(s); cache_store_->AddArc(state, arc); if (arc.nextstate >= nknown_states_) nknown_states_ = arc.nextstate + 1; SetExpandedState(s); int32 flags = kCacheArcs | kCacheRecent; state->SetFlags(flags, flags); } #endif // Adds a single arc to state s but delays cache book-keeping. // SetArcs must be called when all PushArc calls at a state are // complete. Do not mix with calls to AddArc. void PushArc(StateId s, const Arc &arc) { S *state = cache_store_->GetMutableState(s); state->PushArc(arc); } // Marks arcs of state s as cached and does cache book-keeping after all // calls to PushArc have been completed. Do not mix with calls to AddArc. void SetArcs(StateId s) { S *state = cache_store_->GetMutableState(s); cache_store_->SetArcs(state); size_t narcs = state->NumArcs(); for (size_t a = 0; a < narcs; ++a) { const Arc &arc = state->GetArc(a); if (arc.nextstate >= nknown_states_) nknown_states_ = arc.nextstate + 1; } SetExpandedState(s); int32 flags = kCacheArcs | kCacheRecent; state->SetFlags(flags, flags); } void ReserveArcs(StateId s, size_t n) { S *state = cache_store_->GetMutableState(s); state->ReserveArcs(n); } void DeleteArcs(StateId s) { S *state = cache_store_->GetMutableState(s); cache_store_->DeleteArcs(state); } void DeleteArcs(StateId s, size_t n) { S *state = cache_store_->GetMutableState(s); cache_store_->DeleteArcs(state, n); } void Clear() { nknown_states_ = 0; min_unexpanded_state_id_ = 0; max_expanded_state_id_ = -1; has_start_ = false; cache_start_ = kNoStateId; cache_store_->Clear(); } // Is the start state cached? bool HasStart() const { if (!has_start_ && Properties(kError)) has_start_ = true; return has_start_; } // Is the final weight of state s cached? bool HasFinal(StateId s) const { const S *state = cache_store_->GetState(s); if (state && state->Flags() & kCacheFinal) { state->SetFlags(kCacheRecent, kCacheRecent); return true; } else { return false; } } // Are arcs of state s cached? bool HasArcs(StateId s) const { const S *state = cache_store_->GetState(s); if (state && state->Flags() & kCacheArcs) { state->SetFlags(kCacheRecent, kCacheRecent); return true; } else { return false; } } StateId Start() const { return cache_start_; } Weight Final(StateId s) const { const S *state = cache_store_->GetState(s); return state->Final(); } size_t NumArcs(StateId s) const { const S *state = cache_store_->GetState(s); return state->NumArcs(); } size_t NumInputEpsilons(StateId s) const { const S *state = cache_store_->GetState(s); return state->NumInputEpsilons(); } size_t NumOutputEpsilons(StateId s) const { const S *state = cache_store_->GetState(s); return state->NumOutputEpsilons(); } // Provides information needed for generic arc iterator. void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) const { const S *state = cache_store_->GetState(s); data->base = 0; data->narcs = state->NumArcs(); data->arcs = state->Arcs(); data->ref_count = state->MutableRefCount(); state->IncrRefCount(); } // Number of known states. StateId NumKnownStates() const { return nknown_states_; } // Update number of known states taking in account the existence of state s. void UpdateNumKnownStates(StateId s) { if (s >= nknown_states_) nknown_states_ = s + 1; } // Finds the mininum never-expanded state Id StateId MinUnexpandedState() const { while (min_unexpanded_state_id_ <= max_expanded_state_id_ && ExpandedState(min_unexpanded_state_id_)) ++min_unexpanded_state_id_; return min_unexpanded_state_id_; } // Returns maxinum ever-expanded state Id StateId MaxExpandedState() const { return max_expanded_state_id_; } void SetExpandedState(StateId s) { if (s > max_expanded_state_id_) max_expanded_state_id_ = s; if (s < min_unexpanded_state_id_) return; if (s == min_unexpanded_state_id_) ++min_unexpanded_state_id_; if (cache_gc_ || cache_limit_ == 0) { while (expanded_states_.size() <= s) expanded_states_.push_back(false); expanded_states_[s] = true; } } bool ExpandedState(StateId s) const { if (cache_gc_ || cache_limit_ == 0) { return expanded_states_[s]; } else if (new_cache_store_) { return cache_store_->GetState(s) != 0; } else { // If the cache was not created by this class (but provided as opt), // then the cached state needs to be inspected to update nknown_states_. return false; } } const C *GetCacheStore() const { return cache_store_; } C *GetCacheStore() { return cache_store_; } // Caching on/off switch, limit and size accessors. bool GetCacheGc() const { return cache_gc_; } size_t GetCacheLimit() const { return cache_limit_; } private: mutable bool has_start_; // Is the start state cached? StateId cache_start_; // State Id of start state StateId nknown_states_; // # of known states vector<bool> expanded_states_; // states that have been expanded mutable StateId min_unexpanded_state_id_; // minimum never-expanded state Id mutable StateId max_expanded_state_id_; // maximum ever-expanded state Id bool cache_gc_; // GC enabled size_t cache_limit_; // # of bytes allowed before GC Store *cache_store_; // store of cached states bool new_cache_store_; // store was created by class void operator=(const CacheBaseImpl<S, C> &impl); // disallow }; // A CacheBaseImpl with the default cache state type. template <class A> class CacheImpl : public CacheBaseImpl< CacheState<A> > { public: typedef CacheState<A> State; CacheImpl() {} explicit CacheImpl(const CacheOptions &opts) : CacheBaseImpl< CacheState<A> >(opts) {} CacheImpl(const CacheImpl<A> &impl, bool preserve_cache = false) : CacheBaseImpl<State>(impl, preserve_cache) {} private: void operator=(const CacheImpl<State> &impl); // disallow }; // Use this to make a state iterator for a CacheBaseImpl-derived Fst, // which must have types 'Arc' and 'Store' defined. Note this iterator only // returns those states reachable from the initial state, so consider // implementing a class-specific one. template <class F> class CacheStateIterator : public StateIteratorBase<typename F::Arc> { public: typedef typename F::Arc Arc; typedef typename F::Store Store; typedef typename Arc::StateId StateId; typedef typename Store::State State; typedef CacheBaseImpl<State, Store> Impl; CacheStateIterator(const F &fst, Impl *impl) : fst_(fst), impl_(impl), s_(0) { fst_.Start(); // force start state } bool Done() const { if (s_ < impl_->NumKnownStates()) return false; for (StateId u = impl_->MinUnexpandedState(); u < impl_->NumKnownStates(); u = impl_->MinUnexpandedState()) { // force state expansion ArcIterator<F> aiter(fst_, u); aiter.SetFlags(kArcValueFlags, kArcValueFlags | kArcNoCache); for (; !aiter.Done(); aiter.Next()) impl_->UpdateNumKnownStates(aiter.Value().nextstate); impl_->SetExpandedState(u); if (s_ < impl_->NumKnownStates()) return false; } return true; } StateId Value() const { return s_; } void Next() { ++s_; } void Reset() { s_ = 0; } private: // This allows base class virtual access to non-virtual derived- // class members of the same name. It makes the derived class more // efficient to use but unsafe to further derive. virtual bool Done_() const { return Done(); } virtual StateId Value_() const { return Value(); } virtual void Next_() { Next(); } virtual void Reset_() { Reset(); } const F &fst_; Impl *impl_; StateId s_; }; // Use this to make an arc iterator for a CacheBaseImpl-derived Fst, // which must have types 'Arc' and 'State' defined. template <class F> class CacheArcIterator { public: typedef typename F::Arc Arc; typedef typename F::Store Store; typedef typename Arc::StateId StateId; typedef typename Store::State State; typedef CacheBaseImpl<State, Store> Impl; CacheArcIterator(Impl *impl, StateId s) : i_(0) { state_ = impl->GetCacheStore()->GetMutableState(s); state_->IncrRefCount(); } ~CacheArcIterator() { state_->DecrRefCount(); } bool Done() const { return i_ >= state_->NumArcs(); } const Arc& Value() const { return state_->GetArc(i_); } void Next() { ++i_; } size_t Position() const { return i_; } void Reset() { i_ = 0; } void Seek(size_t a) { i_ = a; } uint32 Flags() const { return kArcValueFlags; } void SetFlags(uint32 flags, uint32 mask) {} private: const State *state_; size_t i_; DISALLOW_COPY_AND_ASSIGN(CacheArcIterator); }; // Use this to make a mutable arc iterator for a CacheBaseImpl-derived Fst, // which must have types 'Arc' and 'Store' defined. template <class F> class CacheMutableArcIterator : public MutableArcIteratorBase<typename F::Arc> { public: typedef typename F::Arc Arc; typedef typename F::Store Store; typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef typename Store::State State; typedef CacheBaseImpl<State, Store> Impl; // You will need to call MutateCheck() in the constructor. CacheMutableArcIterator(Impl *impl, StateId s) : i_(0), s_(s), impl_(impl) { state_ = impl_->GetCacheStore()->GetMutableState(s_); state_->IncrRefCount(); } ~CacheMutableArcIterator() { state_->DecrRefCount(); } bool Done() const { return i_ >= state_->NumArcs(); } const Arc& Value() const { return state_->GetArc(i_); } void Next() { ++i_; } size_t Position() const { return i_; } void Reset() { i_ = 0; } void Seek(size_t a) { i_ = a; } void SetValue(const Arc& arc) { state_->SetArc(arc, i_); } uint32 Flags() const { return kArcValueFlags; } void SetFlags(uint32 f, uint32 m) {} private: virtual bool Done_() const { return Done(); } virtual const Arc& Value_() const { return Value(); } virtual void Next_() { Next(); } virtual size_t Position_() const { return Position(); } virtual void Reset_() { Reset(); } virtual void Seek_(size_t a) { Seek(a); } virtual void SetValue_(const Arc &a) { SetValue(a); } uint32 Flags_() const { return Flags(); } void SetFlags_(uint32 f, uint32 m) { SetFlags(f, m); } size_t i_; StateId s_; Impl *impl_; State *state_; DISALLOW_COPY_AND_ASSIGN(CacheMutableArcIterator); }; } // namespace fst #endif // FST_LIB_CACHE_H__ <|start_filename|>third_party/openfst/src/include/fst/extensions/ngram/nthbit.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // <EMAIL> (<NAME>) #ifndef FST_EXTENSIONS_NGRAM_NTHBIT_H_ #define FST_EXTENSIONS_NGRAM_NTHBIT_H_ #include <fst/types.h> extern uint32 nth_bit_bit_offset[]; inline uint32 nth_bit(uint64 v, uint32 r) { uint32 shift = 0; uint32 c = __builtin_popcount(v & 0xffffffff); uint32 mask = -(r > c); r -= c & mask; shift += (32 & mask); c = __builtin_popcount((v >> shift) & 0xffff); mask = -(r > c); r -= c & mask; shift += (16 & mask); c = __builtin_popcount((v >> shift) & 0xff); mask = -(r > c); r -= c & mask; shift += (8 & mask); return shift + ((nth_bit_bit_offset[(v >> shift) & 0xff] >> ((r - 1) << 2)) & 0xf); } #endif // FST_EXTENSIONS_NGRAM_NTHBIT_H_ <|start_filename|>third_party/openfst/src/script/prune.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/prune.h> namespace fst { namespace script { // 1 void Prune(MutableFstClass *fst, const PruneOptions &opts) { PruneArgs1 args(fst, opts); Apply<Operation<PruneArgs1> >("Prune", fst->ArcType(), &args); } // 2 void Prune(const FstClass &ifst, MutableFstClass *fst, const PruneOptions &opts) { PruneArgs2 args(ifst, fst, opts); Apply<Operation<PruneArgs2> >("Prune", fst->ArcType(), &args); } // 3 void Prune(const FstClass &ifst, MutableFstClass *ofst, const WeightClass& weight_threshold, int64 state_threshold, float delta) { PruneArgs3 args(ifst, ofst, weight_threshold, state_threshold, delta); Apply<Operation<PruneArgs3> >("Prune", ifst.ArcType(), &args); } // 4 void Prune(MutableFstClass *fst, const WeightClass& weight_threshold, int64 state_threshold, float delta) { PruneArgs4 args(fst, weight_threshold, state_threshold, delta); Apply<Operation<PruneArgs4> >("Prune", fst->ArcType(), &args); } // 1 REGISTER_FST_OPERATION(Prune, StdArc, PruneArgs1); REGISTER_FST_OPERATION(Prune, LogArc, PruneArgs1); REGISTER_FST_OPERATION(Prune, Log64Arc, PruneArgs1); // 2 REGISTER_FST_OPERATION(Prune, StdArc, PruneArgs2); REGISTER_FST_OPERATION(Prune, LogArc, PruneArgs2); REGISTER_FST_OPERATION(Prune, Log64Arc, PruneArgs2); // 3 REGISTER_FST_OPERATION(Prune, StdArc, PruneArgs3); REGISTER_FST_OPERATION(Prune, LogArc, PruneArgs3); REGISTER_FST_OPERATION(Prune, Log64Arc, PruneArgs3); // 4 REGISTER_FST_OPERATION(Prune, StdArc, PruneArgs4); REGISTER_FST_OPERATION(Prune, LogArc, PruneArgs4); REGISTER_FST_OPERATION(Prune, Log64Arc, PruneArgs4); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/script/relabel.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/relabel.h> namespace fst { namespace script { // 1 void Relabel(MutableFstClass *ofst, const SymbolTable *old_isyms, const SymbolTable *relabel_isyms, bool attach_new_isyms, const SymbolTable *old_osyms, const SymbolTable *relabel_osyms, bool attach_new_osyms) { RelabelArgs1 args(ofst, old_isyms, relabel_isyms, attach_new_isyms, old_osyms, relabel_osyms, attach_new_osyms); Apply<Operation<RelabelArgs1> >("Relabel", ofst->ArcType(), &args); } // 2 void Relabel(MutableFstClass *ofst, const vector<pair<int64, int64> > &ipairs, const vector<pair<int64, int64> > &opairs) { RelabelArgs2 args(ofst, ipairs, opairs); Apply<Operation<RelabelArgs2> >("Relabel", ofst->ArcType(), &args); } // 3 void Relabel(MutableFstClass *fst, const SymbolTable *new_isymbols, const SymbolTable *new_osymbols) { RelabelArgs3 args(fst, new_isymbols, new_osymbols); Apply<Operation<RelabelArgs3> >("Relabel", fst->ArcType(), &args); } // 1 REGISTER_FST_OPERATION(Relabel, StdArc, RelabelArgs1); REGISTER_FST_OPERATION(Relabel, LogArc, RelabelArgs1); REGISTER_FST_OPERATION(Relabel, Log64Arc, RelabelArgs1); // 2 REGISTER_FST_OPERATION(Relabel, StdArc, RelabelArgs2); REGISTER_FST_OPERATION(Relabel, LogArc, RelabelArgs2); REGISTER_FST_OPERATION(Relabel, Log64Arc, RelabelArgs2); // 3 REGISTER_FST_OPERATION(Relabel, StdArc, RelabelArgs3); REGISTER_FST_OPERATION(Relabel, LogArc, RelabelArgs3); REGISTER_FST_OPERATION(Relabel, Log64Arc, RelabelArgs3); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/bin/fstencode.cc<|end_filename|> // fstencode.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Encode transducer labels and/or weights. // #include <fst/script/encode.h> #include <fst/script/decode.h> /// EncodeMain specific flag definitions DEFINE_bool(encode_labels, false, "Encode output labels"); DEFINE_bool(encode_weights, false, "Encode weights"); DEFINE_bool(encode_reuse, false, "Re-use existing codex"); DEFINE_bool(decode, false, "Decode labels and/or weights"); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::MutableFstClass; string usage = "Encodes transducer labels and/or weights.\n\n Usage: "; usage += argv[0]; usage += " in.fst codex [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 3 || argc > 4) { ShowUsage(); return 1; } string in_name = (strcmp(argv[1], "-") != 0) ? argv[1] : ""; string codex_name = argv[2]; string out_name = argc > 3 ? argv[3] : ""; MutableFstClass *fst = MutableFstClass::Read(in_name, true); if (!fst) return 1; if (FLAGS_decode == false) { uint32 flags = 0; flags |= FLAGS_encode_labels ? fst::kEncodeLabels : 0; flags |= FLAGS_encode_weights ? fst::kEncodeWeights : 0; s::Encode(fst, flags, FLAGS_encode_reuse, codex_name); fst->Write(out_name); } else { s::Decode(fst, codex_name); fst->Write(out_name); } delete fst; return 0; } <|start_filename|>third_party/openfst/src/include/fst/state-table.h<|end_filename|> // state-table.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Classes for representing the mapping between state tuples and state Ids. #ifndef FST_LIB_STATE_TABLE_H__ #define FST_LIB_STATE_TABLE_H__ #include <deque> using std::deque; #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/bi-table.h> #include <fst/expanded-fst.h> namespace fst { // STATE TABLES - these determine the bijective mapping between state // tuples (e.g. in composition triples of two FST states and a // composition filter state) and their corresponding state IDs. // They are classes, templated on state tuples, of the form: // // template <class T> // class StateTable { // public: // typedef typename T StateTuple; // // // Required constructors. // StateTable(); // StateTable(const StateTable &); // // // Lookup state ID by tuple. If it doesn't exist, then add it. // StateId FindState(const StateTuple &); // // Lookup state tuple by state ID. // const StateTuple<StateId> &Tuple(StateId) const; // // # of stored tuples. // StateId Size() const; // }; // // A state tuple has the form: // // template <class S> // struct StateTuple { // typedef typename S StateId; // // // Required constructors. // StateTuple(); // StateTuple(const StateTuple &); // }; // An implementation using a hash map for the tuple to state ID mapping. // The state tuple T must have == defined. H is the hash function. template <class T, class H> class HashStateTable : public HashBiTable<typename T::StateId, T, H> { public: typedef T StateTuple; typedef typename StateTuple::StateId StateId; using HashBiTable<StateId, T, H>::FindId; using HashBiTable<StateId, T, H>::FindEntry; using HashBiTable<StateId, T, H>::Size; HashStateTable() : HashBiTable<StateId, T, H>() {} // Reserves space for table_size elements. explicit HashStateTable(size_t table_size) : HashBiTable<StateId, T, H>(table_size) {} StateId FindState(const StateTuple &tuple) { return FindId(tuple); } const StateTuple &Tuple(StateId s) const { return FindEntry(s); } }; // An implementation using a hash map for the tuple to state ID mapping. // The state tuple T must have == defined. H is the hash function. template <class T, class H> class CompactHashStateTable : public CompactHashBiTable<typename T::StateId, T, H> { public: typedef T StateTuple; typedef typename StateTuple::StateId StateId; using CompactHashBiTable<StateId, T, H>::FindId; using CompactHashBiTable<StateId, T, H>::FindEntry; using CompactHashBiTable<StateId, T, H>::Size; CompactHashStateTable() : CompactHashBiTable<StateId, T, H>() {} // Reserves space for 'table_size' elements. explicit CompactHashStateTable(size_t table_size) : CompactHashBiTable<StateId, T, H>(table_size) {} StateId FindState(const StateTuple &tuple) { return FindId(tuple); } const StateTuple &Tuple(StateId s) const { return FindEntry(s); } }; // An implementation using a vector for the tuple to state mapping. // It is passed a function object FP that should fingerprint tuples // uniquely to an integer that can used as a vector index. Normally, // VectorStateTable constructs the FP object. The user can instead // pass in this object; in that case, VectorStateTable takes its // ownership. template <class T, class FP> class VectorStateTable : public VectorBiTable<typename T::StateId, T, FP> { public: typedef T StateTuple; typedef typename StateTuple::StateId StateId; using VectorBiTable<StateId, T, FP>::FindId; using VectorBiTable<StateId, T, FP>::FindEntry; using VectorBiTable<StateId, T, FP>::Size; using VectorBiTable<StateId, T, FP>::Fingerprint; // Reserves space for 'table_size' elements. explicit VectorStateTable(FP *fp = 0, size_t table_size = 0) : VectorBiTable<StateId, T, FP>(fp, table_size) {} StateId FindState(const StateTuple &tuple) { return FindId(tuple); } const StateTuple &Tuple(StateId s) const { return FindEntry(s); } }; // An implementation using a vector and a compact hash table. The // selecting functor S returns true for tuples to be hashed in the // vector. The fingerprinting functor FP returns a unique fingerprint // for each tuple to be hashed in the vector (these need to be // suitable for indexing in a vector). The hash functor H is used when // hashing tuple into the compact hash table. template <class T, class S, class FP, class H> class VectorHashStateTable : public VectorHashBiTable<typename T::StateId, T, S, FP, H> { public: typedef T StateTuple; typedef typename StateTuple::StateId StateId; using VectorHashBiTable<StateId, T, S, FP, H>::FindId; using VectorHashBiTable<StateId, T, S, FP, H>::FindEntry; using VectorHashBiTable<StateId, T, S, FP, H>::Size; using VectorHashBiTable<StateId, T, S, FP, H>::Selector; using VectorHashBiTable<StateId, T, S, FP, H>::Fingerprint; using VectorHashBiTable<StateId, T, S, FP, H>::Hash; VectorHashStateTable(S *s, FP *fp, H *h, size_t vector_size = 0, size_t tuple_size = 0) : VectorHashBiTable<StateId, T, S, FP, H>( s, fp, h, vector_size, tuple_size) {} StateId FindState(const StateTuple &tuple) { return FindId(tuple); } const StateTuple &Tuple(StateId s) const { return FindEntry(s); } }; // An implementation using a hash map for the tuple to state ID // mapping. This version permits erasing of states. The state tuple T // must have == defined and its default constructor must produce a // tuple that will never be seen. F is the hash function. template <class T, class F> class ErasableStateTable : public ErasableBiTable<typename T::StateId, T, F> { public: typedef T StateTuple; typedef typename StateTuple::StateId StateId; using ErasableBiTable<StateId, T, F>::FindId; using ErasableBiTable<StateId, T, F>::FindEntry; using ErasableBiTable<StateId, T, F>::Size; using ErasableBiTable<StateId, T, F>::Erase; ErasableStateTable() : ErasableBiTable<StateId, T, F>() {} StateId FindState(const StateTuple &tuple) { return FindId(tuple); } const StateTuple &Tuple(StateId s) const { return FindEntry(s); } }; // // COMPOSITION STATE TUPLES AND TABLES // // The composition state table has the form: // // template <class A, class F> // class ComposeStateTable { // public: // typedef A Arc; // typedef F FilterState; // typedef typename A::StateId StateId; // typedef ComposeStateTuple<StateId> StateTuple; // // // Required constructors. // ComposeStateTable(const Fst<Arc> &fst1, const Fst<Arc> &fst2); // ComposeStateTable(const ComposeStateTable<A, F> &table); // // Lookup state ID by tuple. If it doesn't exist, then add it. // StateId FindState(const StateTuple &); // // Lookup state tuple by state ID. // const StateTuple<StateId> &Tuple(StateId) const; // // # of stored tuples. // StateId Size() const; // // Return true if error encountered // bool Error() const; // }; // Represents the composition state. // // template <class S, class F> // class StateTuple { // public: // typedef S StateId; // typedef F FilterState; // // Required constructors. // StateTuple(); // StateTuple(StateId s1, StateId s2, const FilterState &f); // StateId StateId1() const; // StateId StateId2() const; // FilterState GetFilterState() const; // pair<StateId, StateId> StatePair() const; // size_t Hash() const; // friend bool operator==(const StateTuple& x, const StateTuple &y); // } // template <typename S, typename F> class DefaultComposeStateTuple { public: typedef S StateId; typedef F FilterState; DefaultComposeStateTuple() : state_pair_(kNoStateId, kNoStateId), filter_state_(FilterState::NoState()) {} DefaultComposeStateTuple(StateId s1, StateId s2, const FilterState &f) : state_pair_(s1, s2), filter_state_(f) {} StateId StateId1() const { return state_pair_.first; } StateId StateId2() const { return state_pair_.second; } FilterState GetFilterState() const { return filter_state_; } const pair<StateId, StateId>& StatePair() const { return state_pair_; } friend bool operator==(const DefaultComposeStateTuple& x, const DefaultComposeStateTuple& y) { return (&x == &y) || (x.state_pair_ == y.state_pair_ && x.filter_state_ == y.filter_state_); } size_t Hash() const { return StateId1() + StateId2() * 7853 + GetFilterState().Hash() * 7867; } private: pair<StateId, StateId> state_pair_; FilterState filter_state_; // State of composition filter }; // Hashing of composition state tuples. template <typename T> class ComposeHash { public: size_t operator()(const T& t) const { return t.Hash(); } }; // A HashStateTable over composition tuples. template <typename A, typename FS, typename T = DefaultComposeStateTuple<typename A::StateId, FS>, typename H = CompactHashStateTable<T, ComposeHash<T> > > class GenericComposeStateTable : public H { public: typedef A Arc; typedef FS FilterState; typedef typename A::StateId StateId; typedef T StateTuple; GenericComposeStateTable(const Fst<A> &fst1, const Fst<A> &fst2) {} // Reserves space for 'table_size' elements. GenericComposeStateTable(const Fst<A> &fst1, const Fst<A> &fst2, size_t table_size) : H(table_size) {} bool Error() const { return false; } private: void operator=( const GenericComposeStateTable<A, FS, T, H> &table); // disallow }; // Fingerprint for general composition tuples. template <typename T> class ComposeFingerprint { public: typedef T StateTuple; typedef typename StateTuple::StateId StateId; // Required but suboptimal constructor. ComposeFingerprint() : mult1_(8192), mult2_(8192) { LOG(WARNING) << "TupleFingerprint: # of FST states should be provided."; } // Constructor is provided the sizes of the input FSTs ComposeFingerprint(StateId nstates1, StateId nstates2) : mult1_(nstates1), mult2_(nstates1 * nstates2) { } size_t operator()(const StateTuple &tuple) { return tuple.StateId1() + tuple.StateId2() * mult1_ + tuple.GetFilterState().Hash() * mult2_; } private: ssize_t mult1_; ssize_t mult2_; }; // Useful when the first composition state determines the tuple. template <typename T> class ComposeState1Fingerprint { public: typedef T StateTuple; size_t operator()(const StateTuple &tuple) { return tuple.StateId1(); } }; // Useful when the second composition state determines the tuple. template <typename T> class ComposeState2Fingerprint { public: typedef T StateTuple; size_t operator()(const StateTuple &tuple) { return tuple.StateId2(); } }; // A VectorStateTable over composition tuples. This can be used when // the product of number of states in FST1 and FST2 (and the // composition filter state hash) is manageable. If the FSTs are not // expanded Fsts, they will first have their states counted. template <typename A, typename T> class ProductComposeStateTable : public VectorStateTable<T, ComposeFingerprint<T> > { public: typedef A Arc; typedef typename A::StateId StateId; typedef T StateTuple; typedef VectorStateTable< StateTuple, ComposeFingerprint<StateTuple> > StateTable; // Reserves space for 'table_size' elements. ProductComposeStateTable(const Fst<A> &fst1, const Fst<A> &fst2, size_t table_size = 0) : StateTable( new ComposeFingerprint<StateTuple>(CountStates(fst1), CountStates(fst2)), table_size) {} ProductComposeStateTable(const ProductComposeStateTable<A, T> &table) : StateTable( new ComposeFingerprint<StateTuple>(table.Fingerprint())) { } bool Error() const { return false; } private: void operator=( const ProductComposeStateTable<A, T> &table); // disallow }; // A VectorStateTable over composition tuples. This can be used when // FST1 is a string (satisfies kStringProperties) and FST2 is // epsilon-free and deterministic. It should be used with a // composition filter that creates at most one filter state per tuple // under these conditions (e.g. SequenceComposeFilter or // MatchComposeFilter). template <typename A, typename T> class StringDetComposeStateTable : public VectorStateTable<T, ComposeState1Fingerprint<T> > { public: typedef A Arc; typedef typename A::StateId StateId; typedef T StateTuple; typedef VectorStateTable<StateTuple, ComposeState1Fingerprint<StateTuple> > StateTable; StringDetComposeStateTable(const Fst<A> &fst1, const Fst<A> &fst2) : error_(false) { uint64 props1 = kString; uint64 props2 = kIDeterministic | kNoIEpsilons; if (fst1.Properties(props1, true) != props1 || fst2.Properties(props2, true) != props2) { FSTERROR() << "StringDetComposeStateTable: fst1 not a string or" << " fst2 not input deterministic and epsilon-free"; error_ = true; } } StringDetComposeStateTable(const StringDetComposeStateTable<A, T> &table) : StateTable(table), error_(table.error_) {} bool Error() const { return error_; } private: bool error_; void operator=( const StringDetComposeStateTable<A, T> &table); // disallow }; // A VectorStateTable over composition tuples. This can be used when // FST2 is a string (satisfies kStringProperties) and FST1 is // epsilon-free and deterministic. It should be used with a // composition filter that creates at most one filter state per tuple // under these conditions (e.g. SequenceComposeFilter or // MatchComposeFilter). template <typename A, typename T> class DetStringComposeStateTable : public VectorStateTable<T, ComposeState2Fingerprint<T> > { public: typedef A Arc; typedef typename A::StateId StateId; typedef T StateTuple; typedef VectorStateTable<StateTuple, ComposeState2Fingerprint<StateTuple> > StateTable; DetStringComposeStateTable(const Fst<A> &fst1, const Fst<A> &fst2) :error_(false) { uint64 props1 = kODeterministic | kNoOEpsilons; uint64 props2 = kString; if (fst1.Properties(props1, true) != props1 || fst2.Properties(props2, true) != props2) { FSTERROR() << "StringDetComposeStateTable: fst2 not a string or" << " fst1 not output deterministic and epsilon-free"; error_ = true; } } DetStringComposeStateTable(const DetStringComposeStateTable<A, T> &table) : StateTable(table), error_(table.error_) {} bool Error() const { return error_; } private: bool error_; void operator=(const DetStringComposeStateTable<A, T> &table); // disallow }; // An ErasableStateTable over composition tuples. The Erase(StateId) method // can be called if the user either is sure that composition will never return // to that tuple or doesn't care that if it does, it is assigned a new // state ID. template <typename A, typename T> class ErasableComposeStateTable : public ErasableStateTable<T, ComposeHash<T> > { public: typedef A Arc; typedef typename A::StateId StateId; typedef T StateTuple; ErasableComposeStateTable(const Fst<A> &fst1, const Fst<A> &fst2) {} bool Error() const { return false; } private: void operator=(const ErasableComposeStateTable<A, T> &table); // disallow }; } // namespace fst #endif // FST_LIB_STATE_TABLE_H__ <|start_filename|>third_party/openfst/src/script/union.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/union.h> namespace fst { namespace script { void Union(MutableFstClass *fst1, const FstClass &fst2) { if (!ArcTypesMatch(*fst1, fst2, "Union")) return; UnionArgs args(fst1, fst2); Apply<Operation<UnionArgs> >("Union", fst1->ArcType(), &args); } REGISTER_FST_OPERATION(Union, StdArc, UnionArgs); REGISTER_FST_OPERATION(Union, LogArc, UnionArgs); REGISTER_FST_OPERATION(Union, Log64Arc, UnionArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/script/replace.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_SCRIPT_REPLACE_H_ #define FST_SCRIPT_REPLACE_H_ #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> #include <fst/replace.h> namespace fst { namespace script { struct ReplaceOptions { int64 root; // root rule for expansion fst::ReplaceLabelType call_label_type; // how to label call arc fst::ReplaceLabelType return_label_type; // how to label return arc int64 return_label; // specifies label to put on return arc ReplaceOptions(int64 r, fst::ReplaceLabelType c = fst::REPLACE_LABEL_INPUT, fst::ReplaceLabelType t = fst::REPLACE_LABEL_NEITHER, int64 l = 0) : root(r), call_label_type(c), return_label_type(t), return_label(l) {} }; typedef args::Package<const vector<pair<int64, const FstClass *> > &, MutableFstClass *, const ReplaceOptions &> ReplaceArgs; template<class Arc> void Replace(ReplaceArgs *args) { // Now that we know the arc type, we construct a vector of // pair<real label, real fst> that the real Replace will use const vector<pair<int64, const FstClass *> >& untyped_tuples = args->arg1; vector<pair<typename Arc::Label, const Fst<Arc> *> > fst_tuples( untyped_tuples.size()); for (unsigned i = 0; i < untyped_tuples.size(); ++i) { fst_tuples[i].first = untyped_tuples[i].first; // convert label fst_tuples[i].second = untyped_tuples[i].second->GetFst<Arc>(); } MutableFst<Arc> *ofst = args->arg2->GetMutableFst<Arc>(); const ReplaceOptions &opts = args->arg3; fst::ReplaceFstOptions<Arc> repargs(opts.root, opts.call_label_type, opts.return_label_type, opts.return_label); Replace(fst_tuples, ofst, repargs); } void Replace(const vector<pair<int64, const FstClass *> > &tuples, MutableFstClass *ofst, const ReplaceOptions &opts); } // namespace script } // namespace fst #endif // FST_SCRIPT_REPLACE_H_ <|start_filename|>third_party/openfst/src/script/shortest-path.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/shortest-path.h> namespace fst { namespace script { void ShortestPath(const FstClass &ifst, MutableFstClass *ofst, vector<WeightClass> *distance, const ShortestPathOptions &opts) { if (!ArcTypesMatch(ifst, *ofst, "ShortestPath")) return; ShortestPathArgs1 args(ifst, ofst, distance, opts); Apply<Operation<ShortestPathArgs1> >("ShortestPath", ifst.ArcType(), &args); } void ShortestPath(const FstClass &ifst, MutableFstClass *ofst, size_t n, bool unique, bool first_path, WeightClass weight_threshold, int64 state_threshold) { if (!ArcTypesMatch(ifst, *ofst, "ShortestPath")) return; ShortestPathArgs2 args(ifst, ofst, n, unique, first_path, weight_threshold, state_threshold); Apply<Operation<ShortestPathArgs2> >("ShortestPath", ifst.ArcType(), &args); } REGISTER_FST_OPERATION(ShortestPath, StdArc, ShortestPathArgs1); REGISTER_FST_OPERATION(ShortestPath, LogArc, ShortestPathArgs1); REGISTER_FST_OPERATION(ShortestPath, Log64Arc, ShortestPathArgs1); REGISTER_FST_OPERATION(ShortestPath, StdArc, ShortestPathArgs2); REGISTER_FST_OPERATION(ShortestPath, LogArc, ShortestPathArgs2); REGISTER_FST_OPERATION(ShortestPath, Log64Arc, ShortestPathArgs2); } // namespace script } // namespace fst <|start_filename|>third_party/re2/util/atomicops.h<|end_filename|> // Copyright 2006-2008 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_UTIL_ATOMICOPS_H__ #define RE2_UTIL_ATOMICOPS_H__ // The memory ordering constraints resemble the ones in C11. // RELAXED - no memory ordering, just an atomic operation. // CONSUME - data-dependent ordering. // ACQUIRE - prevents memory accesses from hoisting above the operation. // RELEASE - prevents memory accesses from sinking below the operation. #if (__clang_major__ * 100 + __clang_minor__ >= 303) || \ (__GNUC__ * 1000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >= 40801) #define ATOMIC_LOAD_RELAXED(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_RELAXED); } while (0) #define ATOMIC_LOAD_CONSUME(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_CONSUME); } while (0) #define ATOMIC_LOAD_ACQUIRE(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_ACQUIRE); } while (0) #define ATOMIC_STORE_RELAXED(p, v) __atomic_store_n((p), (v), __ATOMIC_RELAXED) #define ATOMIC_STORE_RELEASE(p, v) __atomic_store_n((p), (v), __ATOMIC_RELEASE) #else // old compiler #define ATOMIC_LOAD_RELAXED(x, p) do { (x) = *(p); } while (0) #define ATOMIC_LOAD_CONSUME(x, p) do { (x) = *(p); MaybeReadMemoryBarrier(); } while (0) #define ATOMIC_LOAD_ACQUIRE(x, p) do { (x) = *(p); ReadMemoryBarrier(); } while (0) #define ATOMIC_STORE_RELAXED(p, v) do { *(p) = (v); } while (0) #define ATOMIC_STORE_RELEASE(p, v) do { WriteMemoryBarrier(); *(p) = (v); } while (0) // WriteMemoryBarrier(), ReadMemoryBarrier() and MaybeReadMemoryBarrier() // are an implementation detail and must not be used in the rest of the code. #if defined(__i386__) static inline void WriteMemoryBarrier() { int x; __asm__ __volatile__("xchgl (%0),%0" // The lock prefix is implicit for xchg. :: "r" (&x)); } #elif defined(__x86_64__) // 64-bit implementations of memory barrier can be simpler, because // "sfence" is guaranteed to exist. static inline void WriteMemoryBarrier() { __asm__ __volatile__("sfence" : : : "memory"); } #elif defined(__ppc__) static inline void WriteMemoryBarrier() { __asm__ __volatile__("eieio" : : : "memory"); } #elif defined(__alpha__) static inline void WriteMemoryBarrier() { __asm__ __volatile__("wmb" : : : "memory"); } #else #include "util/mutex.h" static inline void WriteMemoryBarrier() { // Slight overkill, but good enough: // any mutex implementation must have // a read barrier after the lock operation and // a write barrier before the unlock operation. // // It may be worthwhile to write architecture-specific // barriers for the common platforms, as above, but // this is a correct fallback. re2::Mutex mu; re2::MutexLock l(&mu); } /* #error Need WriteMemoryBarrier for architecture. // Windows inline void WriteMemoryBarrier() { LONG x; ::InterlockedExchange(&x, 0); } */ #endif // Alpha has very weak memory ordering. If relying on WriteBarriers, one must // use read barriers for the readers too. #if defined(__alpha__) static inline void MaybeReadMemoryBarrier() { __asm__ __volatile__("mb" : : : "memory"); } static inline void ReadMemoryBarrier() { __asm__ __volatile__("mb" : : : "memory"); } #else static inline void MaybeReadMemoryBarrier() {} static inline void ReadMemoryBarrier() {} #endif // __alpha__ #endif // old compiler #ifndef NO_THREAD_SAFETY_ANALYSIS #define NO_THREAD_SAFETY_ANALYSIS #endif #endif // RE2_UTIL_ATOMICOPS_H__ <|start_filename|>third_party/openfst/src/include/fst/script/compile.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_SCRIPT_COMPILE_H_ #define FST_SCRIPT_COMPILE_H_ #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> #include <fst/script/compile-impl.h> namespace fst { namespace script { // Note: it is safe to pass these strings as references because // this struct is only used to pass them deeper in the call graph. // Be sure you understand why this is so before using this struct // for anything else! struct FstCompileArgs { fst::istream &istrm; const string &source; const string &dest; const string &fst_type; const fst::SymbolTable *isyms; const fst::SymbolTable *osyms; const fst::SymbolTable *ssyms; const bool accep; const bool ikeep; const bool okeep; const bool nkeep; const bool allow_negative_labels; FstCompileArgs(istream &istrm, const string &source, const string &dest, const string &fst_type, const fst::SymbolTable *isyms, const fst::SymbolTable *osyms, const fst::SymbolTable *ssyms, bool accep, bool ikeep, bool okeep, bool nkeep, bool allow_negative_labels = false) : istrm(istrm), source(source), dest(dest), fst_type(fst_type), isyms(isyms), osyms(osyms), ssyms(ssyms), accep(accep), ikeep(ikeep), okeep(okeep), nkeep(nkeep), allow_negative_labels(allow_negative_labels) { } }; template<class Arc> void CompileFst(FstCompileArgs *args) { using fst::FstCompiler; using fst::Convert; using fst::Fst; FstCompiler<Arc> fstcompiler(args->istrm, args->source, args->isyms, args->osyms, args->ssyms, args->accep, args->ikeep, args->okeep, args->nkeep, args->allow_negative_labels); const Fst<Arc> *fst = &fstcompiler.Fst(); if (args->fst_type != "vector") { fst = Convert<Arc>(*fst, args->fst_type); if (!fst) { FSTERROR() << "Failed to convert FST to desired type: " << args->fst_type; return; } } fst->Write(args->dest); } void CompileFst(istream &istrm, const string &source, const string &dest, const string &fst_type, const string &arc_type, const SymbolTable *isyms, const SymbolTable *osyms, const SymbolTable *ssyms, bool accep, bool ikeep, bool okeep, bool nkeep, bool allow_negative_labels); } // namespace script } // namespace fst #endif // FST_SCRIPT_COMPILE_H_ <|start_filename|>third_party/openfst/src/bin/fstrelabel.cc<|end_filename|> // fstrelabel.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Relabel input or output space of Fst // #include <string> #include <vector> using std::vector; #include <utility> using std::pair; using std::make_pair; #include <fst/script/relabel.h> #include <fst/script/weight-class.h> #include <fst/util.h> DEFINE_string(isymbols, "", "Input label symbol table"); DEFINE_string(osymbols, "", "Output label symbol table"); DEFINE_string(relabel_isymbols, "", "Input symbol set to relabel to"); DEFINE_string(relabel_osymbols, "", "Ouput symbol set to relabel to"); DEFINE_string(relabel_ipairs, "", "Input relabel pairs (numeric)"); DEFINE_string(relabel_opairs, "", "Output relabel pairs (numeric)"); DEFINE_bool(allow_negative_labels, false, "Allow negative labels (not recommended; may cause conflicts)"); int main(int argc, char **argv) { namespace s = fst::script; using fst::SymbolTable; using fst::SymbolTableTextOptions; using fst::script::FstClass; using fst::script::MutableFstClass; string usage = "Relabels the input and/or the output labels of the FST.\n\n" " Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; usage += " Using SymbolTables flags:\n"; usage += " -relabel_isymbols isyms.txt\n"; usage += " -relabel_osymbols osyms.txt\n"; usage += " Using numeric labels flags:\n"; usage += " -relabel_ipairs ipairs.txt\n"; usage += " -relabel_opairs opairs.txts\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } string in_name = (argc > 1 && (strcmp(argv[1], "-") != 0)) ? argv[1] : ""; string out_name = argc > 2 ? argv[2] : ""; MutableFstClass *fst = MutableFstClass::Read(in_name, true); if (!fst) return 1; // Relabel with symbol tables SymbolTableTextOptions opts; opts.allow_negative = FLAGS_allow_negative_labels; if (!FLAGS_relabel_isymbols.empty() || !FLAGS_relabel_osymbols.empty()) { bool attach_new_isymbols = (fst->InputSymbols() != 0); const SymbolTable* old_isymbols = FLAGS_isymbols.empty() ? fst->InputSymbols() : SymbolTable::ReadText(FLAGS_isymbols, opts); const SymbolTable* relabel_isymbols = FLAGS_relabel_isymbols.empty() ? NULL : SymbolTable::ReadText(FLAGS_relabel_isymbols, opts); bool attach_new_osymbols = (fst->OutputSymbols() != 0); const SymbolTable* old_osymbols = FLAGS_osymbols.empty() ? fst->OutputSymbols() : SymbolTable::ReadText(FLAGS_osymbols, opts); const SymbolTable* relabel_osymbols = FLAGS_relabel_osymbols.empty() ? NULL : SymbolTable::ReadText(FLAGS_relabel_osymbols, opts); s::Relabel(fst, old_isymbols, relabel_isymbols, attach_new_isymbols, old_osymbols, relabel_osymbols, attach_new_osymbols); } else { // read in relabel pairs and parse typedef int64 Label; vector<pair<Label, Label> > ipairs; vector<pair<Label, Label> > opairs; if (!FLAGS_relabel_ipairs.empty()) { if(!fst::ReadLabelPairs(FLAGS_relabel_ipairs, &ipairs, FLAGS_allow_negative_labels)) return 1; } if (!FLAGS_relabel_opairs.empty()) { if (!fst::ReadLabelPairs(FLAGS_relabel_opairs, &opairs, FLAGS_allow_negative_labels)) return 1; } s::Relabel(fst, ipairs, opairs); } fst->Write(out_name); return 0; } <|start_filename|>third_party/openfst/src/include/fst/string-weight.h<|end_filename|> // string-weight.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // String weight set and associated semiring operation definitions. #ifndef FST_LIB_STRING_WEIGHT_H__ #define FST_LIB_STRING_WEIGHT_H__ #include <list> #include <string> #include <fst/product-weight.h> #include <fst/weight.h> namespace fst { const int kStringInfinity = -1; // Label for the infinite string const int kStringBad = -2; // Label for a non-string const char kStringSeparator = '_'; // Label separator in strings // Determines whether to use left or right string semiring. Includes // 'restricted' versions that signal an error if proper prefixes // (suffixes) would otherwise be returned by Plus, useful with various // algorithms that require functional transducer input with the // string semirings. enum StringType { STRING_LEFT = 0, STRING_RIGHT = 1 , STRING_LEFT_RESTRICT = 2, STRING_RIGHT_RESTRICT = 3, }; #define REVERSE_STRING_TYPE(S) \ ((S) == STRING_LEFT ? STRING_RIGHT : \ ((S) == STRING_RIGHT ? STRING_LEFT : \ ((S) == STRING_LEFT_RESTRICT ? STRING_RIGHT_RESTRICT : \ STRING_LEFT_RESTRICT))) template <typename L, StringType S = STRING_LEFT> class StringWeight; template <typename L, StringType S = STRING_LEFT> class StringWeightIterator; template <typename L, StringType S = STRING_LEFT> class StringWeightReverseIterator; template <typename L, StringType S> bool operator==(const StringWeight<L, S> &, const StringWeight<L, S> &); // String semiring: (longest_common_prefix/suffix, ., Infinity, Epsilon) template <typename L, StringType S> class StringWeight { public: typedef L Label; typedef StringWeight<L, REVERSE_STRING_TYPE(S)> ReverseWeight; friend class StringWeightIterator<L, S>; friend class StringWeightReverseIterator<L, S>; friend bool operator==<>(const StringWeight<L, S> &, const StringWeight<L, S> &); StringWeight() { Init(); } template <typename Iter> StringWeight(const Iter &begin, const Iter &end) { Init(); for (Iter iter = begin; iter != end; ++iter) PushBack(*iter); } explicit StringWeight(L l) { Init(); PushBack(l); } static const StringWeight<L, S> &Zero() { static const StringWeight<L, S> zero(kStringInfinity); return zero; } static const StringWeight<L, S> &One() { static const StringWeight<L, S> one; return one; } static const StringWeight<L, S> &NoWeight() { static const StringWeight<L, S> no_weight(kStringBad); return no_weight; } static const string &Type() { static const string type = S == STRING_LEFT ? "string" : (S == STRING_RIGHT ? "right_string" : (S == STRING_LEFT_RESTRICT ? "restricted_string" : "right_restricted_string")); return type; } bool Member() const; istream &Read(istream &strm); ostream &Write(ostream &strm) const; size_t Hash() const; StringWeight<L, S> Quantize(float delta = kDelta) const { return *this; } ReverseWeight Reverse() const; static uint64 Properties() { return (S == STRING_LEFT || S == STRING_LEFT_RESTRICT ? kLeftSemiring : kRightSemiring) | kIdempotent; } // NB: This needs to be uncommented only if default fails for this impl. // StringWeight<L, S> &operator=(const StringWeight<L, S> &w); // These operations combined with the StringWeightIterator and // StringWeightReverseIterator provide the access and mutation of // the string internal elements. // Common initializer among constructors. void Init() { first_ = 0; } // Clear existing StringWeight. void Clear() { first_ = 0; rest_.clear(); } size_t Size() const { return first_ ? rest_.size() + 1 : 0; } void PushFront(L l) { if (first_) rest_.push_front(first_); first_ = l; } void PushBack(L l) { if (!first_) first_ = l; else rest_.push_back(l); } private: L first_; // first label in string (0 if empty) list<L> rest_; // remaining labels in string }; // Traverses string in forward direction. template <typename L, StringType S> class StringWeightIterator { public: explicit StringWeightIterator(const StringWeight<L, S>& w) : first_(w.first_), rest_(w.rest_), init_(true), iter_(rest_.begin()) {} bool Done() const { if (init_) return first_ == 0; else return iter_ == rest_.end(); } const L& Value() const { return init_ ? first_ : *iter_; } void Next() { if (init_) init_ = false; else ++iter_; } void Reset() { init_ = true; iter_ = rest_.begin(); } private: const L &first_; const list<L> &rest_; bool init_; // in the initialized state? typename list<L>::const_iterator iter_; DISALLOW_COPY_AND_ASSIGN(StringWeightIterator); }; // Traverses string in backward direction. template <typename L, StringType S> class StringWeightReverseIterator { public: explicit StringWeightReverseIterator(const StringWeight<L, S>& w) : first_(w.first_), rest_(w.rest_), fin_(first_ == 0), iter_(rest_.rbegin()) {} bool Done() const { return fin_; } const L& Value() const { return iter_ == rest_.rend() ? first_ : *iter_; } void Next() { if (iter_ == rest_.rend()) fin_ = true; else ++iter_; } void Reset() { fin_ = false; iter_ = rest_.rbegin(); } private: const L &first_; const list<L> &rest_; bool fin_; // in the final state? typename list<L>::const_reverse_iterator iter_; DISALLOW_COPY_AND_ASSIGN(StringWeightReverseIterator); }; // StringWeight member functions follow that require // StringWeightIterator or StringWeightReverseIterator. template <typename L, StringType S> inline istream &StringWeight<L, S>::Read(istream &strm) { Clear(); int32 size; ReadType(strm, &size); for (int i = 0; i < size; ++i) { L label; ReadType(strm, &label); PushBack(label); } return strm; } template <typename L, StringType S> inline ostream &StringWeight<L, S>::Write(ostream &strm) const { int32 size = Size(); WriteType(strm, size); for (StringWeightIterator<L, S> iter(*this); !iter.Done(); iter.Next()) { L label = iter.Value(); WriteType(strm, label); } return strm; } template <typename L, StringType S> inline bool StringWeight<L, S>::Member() const { if (Size() != 1) return true; StringWeightIterator<L, S> iter(*this); return iter.Value() != kStringBad; } template <typename L, StringType S> inline typename StringWeight<L, S>::ReverseWeight StringWeight<L, S>::Reverse() const { ReverseWeight rw; for (StringWeightIterator<L, S> iter(*this); !iter.Done(); iter.Next()) rw.PushFront(iter.Value()); return rw; } template <typename L, StringType S> inline size_t StringWeight<L, S>::Hash() const { size_t h = 0; for (StringWeightIterator<L, S> iter(*this); !iter.Done(); iter.Next()) h ^= h<<1 ^ iter.Value(); return h; } // NB: This needs to be uncommented only if default fails for this the impl. // // template <typename L, StringType S> // inline StringWeight<L, S> // &StringWeight<L, S>::operator=(const StringWeight<L, S> &w) { // if (this != &w) { // Clear(); // for (StringWeightIterator<L, S> iter(w); !iter.Done(); iter.Next()) // PushBack(iter.Value()); // } // return *this; // } template <typename L, StringType S> inline bool operator==(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2) { if (w1.Size() != w2.Size()) return false; StringWeightIterator<L, S> iter1(w1); StringWeightIterator<L, S> iter2(w2); for (; !iter1.Done() ; iter1.Next(), iter2.Next()) if (iter1.Value() != iter2.Value()) return false; return true; } template <typename L, StringType S> inline bool operator!=(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2) { return !(w1 == w2); } template <typename L, StringType S> inline bool ApproxEqual(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2, float delta = kDelta) { return w1 == w2; } template <typename L, StringType S> inline ostream &operator<<(ostream &strm, const StringWeight<L, S> &w) { StringWeightIterator<L, S> iter(w); if (iter.Done()) return strm << "Epsilon"; else if (iter.Value() == kStringInfinity) return strm << "Infinity"; else if (iter.Value() == kStringBad) return strm << "BadString"; else for (size_t i = 0; !iter.Done(); ++i, iter.Next()) { if (i > 0) strm << kStringSeparator; strm << iter.Value(); } return strm; } template <typename L, StringType S> inline istream &operator>>(istream &strm, StringWeight<L, S> &w) { string s; strm >> s; if (s == "Infinity") { w = StringWeight<L, S>::Zero(); } else if (s == "Epsilon") { w = StringWeight<L, S>::One(); } else { w.Clear(); char *p = 0; for (const char *cs = s.c_str(); !p || *p != '\0'; cs = p + 1) { int l = strtoll(cs, &p, 10); if (p == cs || (*p != 0 && *p != kStringSeparator)) { strm.clear(std::ios::badbit); break; } w.PushBack(l); } } return strm; } // Default is for the restricted left and right semirings. String // equality is required (for non-Zero() input. The restriction // is used in e.g. Determinize to ensure functional input. template <typename L, StringType S> inline StringWeight<L, S> Plus(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2) { if (!w1.Member() || !w2.Member()) return StringWeight<L, S>::NoWeight(); if (w1 == StringWeight<L, S>::Zero()) return w2; if (w2 == StringWeight<L, S>::Zero()) return w1; if (w1 != w2) { FSTERROR() << "StringWeight::Plus: unequal arguments " << "(non-functional FST?)" << " w1 = " << w1 << " w2 = " << w2; return StringWeight<L, S>::NoWeight(); } return w1; } // Longest common prefix for left string semiring. template <typename L> inline StringWeight<L, STRING_LEFT> Plus(const StringWeight<L, STRING_LEFT> &w1, const StringWeight<L, STRING_LEFT> &w2) { if (!w1.Member() || !w2.Member()) return StringWeight<L, STRING_LEFT>::NoWeight(); if (w1 == StringWeight<L, STRING_LEFT>::Zero()) return w2; if (w2 == StringWeight<L, STRING_LEFT>::Zero()) return w1; StringWeight<L, STRING_LEFT> sum; StringWeightIterator<L, STRING_LEFT> iter1(w1); StringWeightIterator<L, STRING_LEFT> iter2(w2); for (; !iter1.Done() && !iter2.Done() && iter1.Value() == iter2.Value(); iter1.Next(), iter2.Next()) sum.PushBack(iter1.Value()); return sum; } // Longest common suffix for right string semiring. template <typename L> inline StringWeight<L, STRING_RIGHT> Plus(const StringWeight<L, STRING_RIGHT> &w1, const StringWeight<L, STRING_RIGHT> &w2) { if (!w1.Member() || !w2.Member()) return StringWeight<L, STRING_RIGHT>::NoWeight(); if (w1 == StringWeight<L, STRING_RIGHT>::Zero()) return w2; if (w2 == StringWeight<L, STRING_RIGHT>::Zero()) return w1; StringWeight<L, STRING_RIGHT> sum; StringWeightReverseIterator<L, STRING_RIGHT> iter1(w1); StringWeightReverseIterator<L, STRING_RIGHT> iter2(w2); for (; !iter1.Done() && !iter2.Done() && iter1.Value() == iter2.Value(); iter1.Next(), iter2.Next()) sum.PushFront(iter1.Value()); return sum; } template <typename L, StringType S> inline StringWeight<L, S> Times(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2) { if (!w1.Member() || !w2.Member()) return StringWeight<L, S>::NoWeight(); if (w1 == StringWeight<L, S>::Zero() || w2 == StringWeight<L, S>::Zero()) return StringWeight<L, S>::Zero(); StringWeight<L, S> prod(w1); for (StringWeightIterator<L, S> iter(w2); !iter.Done(); iter.Next()) prod.PushBack(iter.Value()); return prod; } // Default is for left division in the left string semirings. template <typename L, StringType S> inline StringWeight<L, S> Divide(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2, DivideType typ) { if (typ != DIVIDE_LEFT) { FSTERROR() << "StringWeight::Divide: only left division is defined " << "for the " << StringWeight<L, S>::Type() << " semiring"; return StringWeight<L, S>::NoWeight(); } if (!w1.Member() || !w2.Member()) return StringWeight<L, S>::NoWeight(); if (w2 == StringWeight<L, S>::Zero()) return StringWeight<L, S>(kStringBad); else if (w1 == StringWeight<L, S>::Zero()) return StringWeight<L, S>::Zero(); StringWeight<L, S> div; StringWeightIterator<L, S> iter(w1); for (int i = 0; !iter.Done(); iter.Next(), ++i) { if (i >= w2.Size()) div.PushBack(iter.Value()); } return div; } // Right division in the right string semiring. template <typename L> inline StringWeight<L, STRING_RIGHT> Divide(const StringWeight<L, STRING_RIGHT> &w1, const StringWeight<L, STRING_RIGHT> &w2, DivideType typ) { return DivideRight(w1, w2, typ); } // Right division in the right restricted string semiring. template <typename L> inline StringWeight<L, STRING_RIGHT_RESTRICT> Divide(const StringWeight<L, STRING_RIGHT_RESTRICT> &w1, const StringWeight<L, STRING_RIGHT_RESTRICT> &w2, DivideType typ) { return DivideRight(w1, w2, typ); } // Right division in a right string semiring. template <typename L, StringType S> inline StringWeight<L, S> DivideRight(const StringWeight<L, S> &w1, const StringWeight<L, S> &w2, DivideType typ) { if (typ != DIVIDE_RIGHT) { FSTERROR() << "StringWeight::Divide: only right division is defined " << "for a right semiring"; return StringWeight<L, S>::NoWeight(); } if (!w1.Member() || !w2.Member()) return StringWeight<L, S>::NoWeight(); if (w2 == StringWeight<L, S>::Zero()) return StringWeight<L, S>(kStringBad); else if (w1 == StringWeight<L, S>::Zero()) return StringWeight<L, S>::Zero(); StringWeight<L, S> div; StringWeightReverseIterator<L, S> iter(w1); for (int i = 0; !iter.Done(); iter.Next(), ++i) { if (i >= w2.Size()) div.PushFront(iter.Value()); } return div; } // Determines whether to use left or right gallic semiring. Includes // 'restricted' versions that signal an error if proper string // prefixes (suffixes) would otherwise be returned by string Plus, // useful with various algorithms that require functional transducer // input. Also includes 'min' versions that change the Plus to keep // only the lowest W weight string. enum GallicType { GALLIC_LEFT = 0, GALLIC_RIGHT = 1 , GALLIC_LEFT_RESTRICT = 2, GALLIC_RIGHT_RESTRICT = 3, GALLIC_LEFT_MIN = 4, GALLIC_RIGHT_MIN = 5, }; #define GALLIC_STRING_TYPE(G) \ ((G) == GALLIC_LEFT ? STRING_LEFT : \ ((G) == GALLIC_RIGHT ? STRING_RIGHT : \ (((G) == GALLIC_LEFT_RESTRICT || (G) == GALLIC_LEFT_MIN) ? \ STRING_LEFT_RESTRICT : STRING_RIGHT_RESTRICT))) #define REVERSE_GALLIC_TYPE(G) \ ((G) == GALLIC_LEFT ? GALLIC_RIGHT : \ ((G) == GALLIC_RIGHT ? GALLIC_LEFT : \ ((G) == GALLIC_LEFT_RESTRICT ? GALLIC_RIGHT_RESTRICT : \ ((G) == GALLIC_RIGHT_RESTRICT ? GALLIC_LEFT_RESTRICT : \ ((G) == GALLIC_LEFT_MIN ? GALLIC_RIGHT_MIN : \ GALLIC_LEFT_MIN))))) // Product of string weight and an arbitray weight. template <class L, class W, GallicType G = GALLIC_LEFT> struct GallicWeight : public ProductWeight<StringWeight<L, GALLIC_STRING_TYPE(G)>, W> { typedef StringWeight<L, GALLIC_STRING_TYPE(G)> SW; typedef GallicWeight<L, typename W::ReverseWeight, REVERSE_GALLIC_TYPE(G)> ReverseWeight; using ProductWeight<SW, W>::Zero; using ProductWeight<SW, W>::One; using ProductWeight<SW, W>::NoWeight; using ProductWeight<SW, W>::Quantize; using ProductWeight<SW, W>::Reverse; GallicWeight() {} GallicWeight(SW w1, W w2) : ProductWeight<SW, W>(w1, w2) {} explicit GallicWeight(const string &s, int *nread = 0) : ProductWeight<SW, W>(s, nread) {} static const GallicWeight<L, W, G> &Zero() { static const GallicWeight<L, W, G> zero(ProductWeight<SW, W>::Zero()); return zero; } static const GallicWeight<L, W, G> &One() { static const GallicWeight<L, W, G> one(ProductWeight<SW, W>::One()); return one; } static const GallicWeight<L, W, G> &NoWeight() { static const GallicWeight<L, W, G> no_weight( ProductWeight<SW, W>::NoWeight()); return no_weight; } static const string &Type() { static const string type = G == GALLIC_LEFT ? "gallic" : (G == GALLIC_RIGHT ? "right_gallic" : (G == GALLIC_LEFT_RESTRICT ? "restricted_gallic" : (G == GALLIC_RIGHT_RESTRICT ? "right_restricted_gallic" : (G == GALLIC_LEFT_MIN ? "min_gallic" : "right_min_gallic")))); return type; } GallicWeight<L, W, G> Quantize(float delta = kDelta) const { return ProductWeight<SW, W>::Quantize(delta); } ReverseWeight Reverse() const { return ProductWeight<SW, W>::Reverse(); } GallicWeight(const ProductWeight<SW, W> &w) : ProductWeight<SW, W>(w) {} }; // Default plus template <class L, class W, GallicType G> inline GallicWeight<L, W, G> Plus(const GallicWeight<L, W, G> &w, const GallicWeight<L, W, G> &v) { return GallicWeight<L, W, G>(Plus(w.Value1(), v.Value1()), Plus(w.Value2(), v.Value2())); } // Left min gallic plus template <class L, class W> inline GallicWeight<L, W, GALLIC_LEFT_MIN> Plus(const GallicWeight<L, W, GALLIC_LEFT_MIN> &w1, const GallicWeight<L, W, GALLIC_LEFT_MIN> &w2) { NaturalLess<W> less; return less(w1.Value2(), w2.Value2()) ? w1 : w2; } // Right min gallic plus template <class L, class W> inline GallicWeight<L, W, GALLIC_RIGHT_MIN> Plus(const GallicWeight<L, W, GALLIC_RIGHT_MIN> &w1, const GallicWeight<L, W, GALLIC_RIGHT_MIN> &w2) { NaturalLess<W> less; return less(w1.Value2(), w2.Value2()) ? w1 : w2; } template <class L, class W, GallicType G> inline GallicWeight<L, W, G> Times(const GallicWeight<L, W, G> &w, const GallicWeight<L, W, G> &v) { return GallicWeight<L, W, G>(Times(w.Value1(), v.Value1()), Times(w.Value2(), v.Value2())); } template <class L, class W, GallicType G> inline GallicWeight<L, W, G> Divide(const GallicWeight<L, W, G> &w, const GallicWeight<L, W, G> &v, DivideType typ = DIVIDE_ANY) { return GallicWeight<L, W, G>(Divide(w.Value1(), v.Value1(), typ), Divide(w.Value2(), v.Value2(), typ)); } } // namespace fst #endif // FST_LIB_STRING_WEIGHT_H__ <|start_filename|>third_party/openfst/src/include/fst/script/compose.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_SCRIPT_COMPOSE_H_ #define FST_SCRIPT_COMPOSE_H_ #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> #include <fst/compose.h> namespace fst { namespace script { typedef args::Package<const FstClass&, const FstClass&, MutableFstClass*, ComposeFilter> ComposeArgs1; template<class Arc> void Compose(ComposeArgs1 *args) { const Fst<Arc> &ifst1 = *(args->arg1.GetFst<Arc>()); const Fst<Arc> &ifst2 = *(args->arg2.GetFst<Arc>()); MutableFst<Arc> *ofst = args->arg3->GetMutableFst<Arc>(); Compose(ifst1, ifst2, ofst, args->arg4); } typedef fst::ComposeOptions ComposeOptions; typedef args::Package<const FstClass&, const FstClass&, MutableFstClass*, const ComposeOptions &> ComposeArgs2; template<class Arc> void Compose(ComposeArgs2 *args) { const Fst<Arc> &ifst1 = *(args->arg1.GetFst<Arc>()); const Fst<Arc> &ifst2 = *(args->arg2.GetFst<Arc>()); MutableFst<Arc> *ofst = args->arg3->GetMutableFst<Arc>(); Compose(ifst1, ifst2, ofst, args->arg4); } void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &opts = fst::script::ComposeOptions()); void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, ComposeFilter compose_filter); } // namespace script } // namespace fst #endif // FST_SCRIPT_COMPOSE_H_ <|start_filename|>third_party/openfst/src/include/fst/determinize.h<|end_filename|> // determinize.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Functions and classes to determinize an FST. #ifndef FST_LIB_DETERMINIZE_H__ #define FST_LIB_DETERMINIZE_H__ #include <algorithm> #include <climits> #include <forward_list> using std::forward_list; #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <map> #include <string> #include <vector> using std::vector; #include <fst/arc-map.h> #include <fst/cache.h> #include <fst/bi-table.h> #include <fst/factor-weight.h> #include <fst/filter-state.h> #include <fst/prune.h> #include <fst/test-properties.h> namespace fst { // // COMMON DIVISORS - these are used in determinization to compute // the transition weights. In the simplest case, it is just the same // as the semiring Plus(). However, other choices permit more efficient // determinization when the output contains strings. // // The default common divisor uses the semiring Plus. template <class W> class DefaultCommonDivisor { public: typedef W Weight; W operator()(const W &w1, const W &w2) const { return Plus(w1, w2); } }; // The label common divisor for a (left) string semiring selects a // single letter common prefix or the empty string. This is used in // the determinization of output strings so that at most a single // letter will appear in the output of a transtion. template <typename L, StringType S> class LabelCommonDivisor { public: typedef StringWeight<L, S> Weight; Weight operator()(const Weight &w1, const Weight &w2) const { StringWeightIterator<L, S> iter1(w1); StringWeightIterator<L, S> iter2(w2); if (!(StringWeight<L, S>::Properties() & kLeftSemiring)) { FSTERROR() << "LabelCommonDivisor: Weight needs to be left semiring"; return Weight::NoWeight(); } else if (w1.Size() == 0 || w2.Size() == 0) { return Weight::One(); } else if (w1 == Weight::Zero()) { return Weight(iter2.Value()); } else if (w2 == Weight::Zero()) { return Weight(iter1.Value()); } else if (iter1.Value() == iter2.Value()) { return Weight(iter1.Value()); } else { return Weight::One(); } } }; // The gallic common divisor uses the label common divisor on the // string component and the template argument D common divisor on the // weight component, which defaults to the default common divisor. template <class L, class W, GallicType G, class D = DefaultCommonDivisor<W> > class GallicCommonDivisor { public: typedef GallicWeight<L, W, G> Weight; Weight operator()(const Weight &w1, const Weight &w2) const { return Weight(label_common_divisor_(w1.Value1(), w2.Value1()), weight_common_divisor_(w1.Value2(), w2.Value2())); } private: LabelCommonDivisor<L, GALLIC_STRING_TYPE(G)> label_common_divisor_; D weight_common_divisor_; }; // Represents an element in a subset template <class A> struct DeterminizeElement { typedef typename A::StateId StateId; typedef typename A::Weight Weight; DeterminizeElement() {} DeterminizeElement(StateId s, Weight w) : state_id(s), weight(w) {} bool operator==(const DeterminizeElement<A> & element) const { return state_id == element.state_id && weight == element.weight; } bool operator!=(const DeterminizeElement<A> & element) const { return !(*this == element); } bool operator<(const DeterminizeElement<A> & element) const { return state_id < element.state_id; } StateId state_id; // Input state Id Weight weight; // Residual weight }; // Represents a weighted subset and determinization filter state template <typename A, typename F> struct DeterminizeStateTuple { typedef A Arc; typedef F FilterState; typedef DeterminizeElement<Arc> Element; typedef std::forward_list<Element> Subset; DeterminizeStateTuple() : filter_state(FilterState::NoState()) { } bool operator==(const DeterminizeStateTuple<A, F> &tuple) const { return (tuple.filter_state == filter_state) && (tuple.subset == subset); } bool operator!=(const DeterminizeStateTuple<A, F> &tuple) const { return (tuple.filter_state != filter_state) || (tuple.subset != subset); } Subset subset; FilterState filter_state; }; // Proto-transition for determinization template <class S> struct DeterminizeArc { typedef S StateTuple; typedef typename S::Arc Arc; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; DeterminizeArc() : label(kNoLabel), weight(Weight::Zero()), dest_tuple(0) {} explicit DeterminizeArc(const Arc &arc) : label(arc.ilabel), weight(Weight::Zero()), dest_tuple(new S) { } Label label; // arc label Weight weight; // arc weight StateTuple *dest_tuple; // destination subset and filter state }; // // DETERMINIZE FILTERS - these are used in determinization to compute // destination state tuples based on the source tuple, transition, and // destination element or on similar super-final transition // information. The filter operates on a map between a label and the // corresponding destination state tuples. It must define the map type // LabelMap. The default filter is used for weighted determinization. // // A determinize filter for implementing weighted determinization. template <class Arc> class DefaultDeterminizeFilter { public: typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; typedef CharFilterState FilterState; typedef DeterminizeElement<Arc> Element; typedef DeterminizeStateTuple<Arc, FilterState> StateTuple; typedef map<Label, DeterminizeArc<StateTuple> > LabelMap; // This is needed e.g. to go into the gallic domain for transducers. template <class A> struct rebind { typedef DefaultDeterminizeFilter<A> other; }; DefaultDeterminizeFilter(const Fst<Arc> &fst) : fst_(fst.Copy()) { } // This is needed e.g. to go into the gallic domain for transducers. // Ownership of the templated filter argument is given to this class. template <class F> DefaultDeterminizeFilter(const Fst<Arc> &fst, F* filter) : fst_(fst.Copy()) { delete filter; } // Copy ctr. The FST can be passed if it has been e.g. (deep) copied. explicit DefaultDeterminizeFilter( const DefaultDeterminizeFilter<Arc> &filter, const Fst<Arc> *fst = 0) : fst_(fst ? fst->Copy() : filter.fst_->Copy()) { } ~DefaultDeterminizeFilter() { delete fst_; } FilterState Start() const { return FilterState(0); } void SetState(StateId s, const StateTuple &tuple) { } // Filters transition, possibly modifying label map. Returns // true if arc is added to label map. bool FilterArc(const Arc &arc, const Element &src_element, const Element &dest_element, LabelMap *label_map) const { // Adds element to unique state tuple for arc label; create if necessary DeterminizeArc<StateTuple> &det_arc = (*label_map)[arc.ilabel]; if (det_arc.label == kNoLabel) { det_arc = DeterminizeArc<StateTuple>(arc); det_arc.dest_tuple->filter_state = FilterState(0); } det_arc.dest_tuple->subset.push_front(dest_element); return true; } // Filters super-final transition, returning new final weight Weight FilterFinal(Weight final_weight, const Element &element) { return final_weight; } static uint64 Properties(uint64 props) { return props; } private: Fst<Arc> *fst_; void operator=(const DefaultDeterminizeFilter<Arc> &); // disallow }; // // DETERMINIZATION STATE TABLES // // The determinization state table has the form: // // template <class A, class F> // class DeterminizeStateTable { // public: // typename A Arc; // typename F FilterState; // typedef typename Arc::StateId StateId; // typedef DeterminizeStateTuple<Arc, FilterState> StateTuple; // // // Required sub-class. This is needed e.g. to go into the gallic domain. // template <class B, class G> // struct rebind { typedef DeterminizeStateTable<B, G> other; }; // // // Required constuctor // DeterminizeStateTable(); // // // Required copy constructor that does not copy state // DeterminizeStateTable(const DeterminizeStateTable<A,F> &table); // // // Lookup state ID by state tuple. // // If it doesn't exist, then add it. FindState takes ownership // // of the state tuple argument (so that it doesn't have to // // copy it if it creates a new state). // StateId FindState(StateTuple *tuple); // // // Lookup state tuple by ID. // const StateTuple *Tuple(StateId id) const; // }; // The default determinization state table based on the // compact hash bi-table. template <class A, class F> class DefaultDeterminizeStateTable { public: typedef A Arc; typedef F FilterState; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; typedef DeterminizeStateTuple<Arc, FilterState> StateTuple; typedef typename StateTuple::Subset Subset; typedef typename StateTuple::Element Element; template <class B, class G> struct rebind { typedef DefaultDeterminizeStateTable<B, G> other; }; explicit DefaultDeterminizeStateTable(size_t table_size = 0) : table_size_(table_size), tuples_(table_size_) { } DefaultDeterminizeStateTable(const DefaultDeterminizeStateTable<A, F> &table) : table_size_(table.table_size_), tuples_(table_size_) { } ~DefaultDeterminizeStateTable() { for (StateId s = 0; s < tuples_.Size(); ++s) delete tuples_.FindEntry(s); } // Finds the state corresponding to a state tuple. Only creates a new // state if the tuple is not found. FindState takes ownership of // the tuple argument (so that it doesn't have to copy it if it // creates a new state). StateId FindState(StateTuple *tuple) { StateId ns = tuples_.Size(); StateId s = tuples_.FindId(tuple); if (s != ns) delete tuple; // tuple found return s; } const StateTuple* Tuple(StateId s) { return tuples_.FindEntry(s); } private: // Comparison object for StateTuples. class StateTupleEqual { public: bool operator()(const StateTuple* tuple1, const StateTuple* tuple2) const { return *tuple1 == *tuple2; } }; // Hash function for StateTuples. class StateTupleKey { public: size_t operator()(const StateTuple* tuple) const { size_t h = tuple->filter_state.Hash(); for (typename Subset::const_iterator iter = tuple->subset.begin(); iter != tuple->subset.end(); ++iter) { const Element &element = *iter; size_t h1 = element.state_id; size_t h2 = element.weight.Hash(); const int lshift = 5; const int rshift = CHAR_BIT * sizeof(size_t) - 5; h ^= h << 1 ^ h1 << lshift ^ h1 >> rshift ^ h2; } return h; } }; size_t table_size_; typedef CompactHashBiTable<StateId, StateTuple *, StateTupleKey, StateTupleEqual, HS_STL> StateTupleTable; StateTupleTable tuples_; void operator=(const DefaultDeterminizeStateTable<A, F> &); // disallow }; // Options for finite-state transducer determinization templated on // the arc type, common divisor, the determinization filter and the // state table. DeterminizeFst takes ownership of the determinization // filter and state table if provided. template <class Arc, class D = DefaultCommonDivisor<typename Arc::Weight>, class F = DefaultDeterminizeFilter<Arc>, class T = DefaultDeterminizeStateTable<Arc, typename F::FilterState> > struct DeterminizeFstOptions : CacheOptions { typedef typename Arc::Label Label; float delta; // Quantization delta for subset weights Label subsequential_label; // Label used for residual final output // when producing subsequential transducers. bool disambiguate_output; // Keep only the min of ambiguous output F *filter; // Determinization filter T *state_table; // Determinization state table explicit DeterminizeFstOptions(const CacheOptions &opts, float del = kDelta, Label lab = 0, bool disamb = false, F *filt = 0, T *table = 0) : CacheOptions(opts), delta(del), subsequential_label(lab), disambiguate_output(disamb), filter(filt), state_table(table) {} explicit DeterminizeFstOptions(float del = kDelta, Label lab = 0, bool disamb = false, F *filt = 0, T *table = 0) : delta(del), subsequential_label(lab), disambiguate_output(disamb), filter(filt), state_table(table) {} }; // Implementation of delayed DeterminizeFst. This base class is // common to the variants that implement acceptor and transducer // determinization. template <class A> class DeterminizeFstImplBase : public CacheImpl<A> { public: using FstImpl<A>::SetType; using FstImpl<A>::SetProperties; using FstImpl<A>::Properties; using FstImpl<A>::SetInputSymbols; using FstImpl<A>::SetOutputSymbols; using CacheBaseImpl< CacheState<A> >::HasStart; using CacheBaseImpl< CacheState<A> >::HasFinal; using CacheBaseImpl< CacheState<A> >::HasArcs; using CacheBaseImpl< CacheState<A> >::SetFinal; using CacheBaseImpl< CacheState<A> >::SetStart; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef DefaultCacheStore<A> Store; typedef typename Store::State State; template <class D, class F, class T> DeterminizeFstImplBase(const Fst<A> &fst, const DeterminizeFstOptions<A, D, F, T> &opts) : CacheImpl<A>(opts), fst_(fst.Copy()) { SetType("determinize"); uint64 iprops = fst.Properties(kFstProperties, false); uint64 dprops = DeterminizeProperties(iprops, opts.subsequential_label != 0); SetProperties(F::Properties(dprops), kCopyProperties); SetInputSymbols(fst.InputSymbols()); SetOutputSymbols(fst.OutputSymbols()); } DeterminizeFstImplBase(const DeterminizeFstImplBase<A> &impl) : CacheImpl<A>(impl), fst_(impl.fst_->Copy(true)) { SetType("determinize"); SetProperties(impl.Properties(), kCopyProperties); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); } virtual ~DeterminizeFstImplBase() { delete fst_; } virtual DeterminizeFstImplBase<A> *Copy() = 0; StateId Start() { if (!HasStart()) { StateId start = ComputeStart(); if (start != kNoStateId) { SetStart(start); } } return CacheImpl<A>::Start(); } Weight Final(StateId s) { if (!HasFinal(s)) { Weight final = ComputeFinal(s); SetFinal(s, final); } return CacheImpl<A>::Final(s); } virtual void Expand(StateId s) = 0; size_t NumArcs(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<A>::NumArcs(s); } size_t NumInputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<A>::NumInputEpsilons(s); } size_t NumOutputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<A>::NumOutputEpsilons(s); } void InitArcIterator(StateId s, ArcIteratorData<A> *data) { if (!HasArcs(s)) Expand(s); CacheImpl<A>::InitArcIterator(s, data); } virtual StateId ComputeStart() = 0; virtual Weight ComputeFinal(StateId s) = 0; const Fst<A> &GetFst() const { return *fst_; } private: const Fst<A> *fst_; // Input Fst void operator=(const DeterminizeFstImplBase<A> &); // disallow }; // Implementation of delayed determinization for weighted acceptors. // It is templated on the arc type A and the common divisor D. template <class A, class D, class F, class T> class DeterminizeFsaImpl : public DeterminizeFstImplBase<A> { public: using FstImpl<A>::SetProperties; using DeterminizeFstImplBase<A>::GetFst; using DeterminizeFstImplBase<A>::SetArcs; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef typename F::FilterState FilterState; typedef DeterminizeStateTuple<A, FilterState> StateTuple; typedef typename StateTuple::Element Element; typedef typename StateTuple::Subset Subset; typedef typename F::LabelMap LabelMap; DeterminizeFsaImpl(const Fst<A> &fst, const vector<Weight> *in_dist, vector<Weight> *out_dist, const DeterminizeFstOptions<A, D, F, T> &opts) : DeterminizeFstImplBase<A>(fst, opts), delta_(opts.delta), in_dist_(in_dist), out_dist_(out_dist), filter_(opts.filter ? opts.filter : new F(fst)), state_table_(opts.state_table ? opts.state_table : new T()) { if (!fst.Properties(kAcceptor, true)) { FSTERROR() << "DeterminizeFst: argument not an acceptor"; SetProperties(kError, kError); } if (!(Weight::Properties() & kLeftSemiring)) { FSTERROR() << "DeterminizeFst: Weight needs to be left distributive: " << Weight::Type(); SetProperties(kError, kError); } if (out_dist_) out_dist_->clear(); } DeterminizeFsaImpl(const DeterminizeFsaImpl<A, D, F, T> &impl) : DeterminizeFstImplBase<A>(impl), delta_(impl.delta_), in_dist_(0), out_dist_(0), filter_(new F(*impl.filter_, &GetFst())), state_table_(new T(*impl.state_table_)) { if (impl.out_dist_) { FSTERROR() << "DeterminizeFsaImpl: cannot copy with out_dist vector"; SetProperties(kError, kError); } } virtual ~DeterminizeFsaImpl() { delete filter_; delete state_table_; } virtual DeterminizeFsaImpl<A, D, F, T> *Copy() { return new DeterminizeFsaImpl<A, D, F, T>(*this); } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if ((mask & kError) && (GetFst().Properties(kError, false))) SetProperties(kError, kError); return FstImpl<A>::Properties(mask); } virtual StateId ComputeStart() { StateId s = GetFst().Start(); if (s == kNoStateId) return kNoStateId; Element element(s, Weight::One()); StateTuple *tuple = new StateTuple; tuple->subset.push_front(element); tuple->filter_state = filter_->Start(); return FindState(tuple); } virtual Weight ComputeFinal(StateId s) { const StateTuple *tuple = state_table_->Tuple(s); filter_->SetState(s, *tuple); Weight final = Weight::Zero(); for (typename Subset::const_iterator siter = tuple->subset.begin(); siter != tuple->subset.end(); ++siter) { const Element &element = *siter; final = Plus(final, Times(element.weight, GetFst().Final(element.state_id))); final = filter_->FilterFinal(final, element); if (!final.Member()) SetProperties(kError, kError); } return final; } StateId FindState(StateTuple *tuple) { StateId s = state_table_->FindState(tuple); if (in_dist_ && out_dist_->size() <= s) out_dist_->push_back(ComputeDistance(tuple->subset)); return s; } // Compute distance from a state to the final states in the DFA // given the distances in the NFA. Weight ComputeDistance(const Subset &subset) { Weight outd = Weight::Zero(); for (typename Subset::const_iterator siter = subset.begin(); siter != subset.end(); ++siter) { const Element &element = *siter; Weight ind = element.state_id < in_dist_->size() ? (*in_dist_)[element.state_id] : Weight::Zero(); outd = Plus(outd, Times(element.weight, ind)); } return outd; } // Computes the outgoing transitions from a state, creating new destination // states as needed. virtual void Expand(StateId s) { LabelMap label_map; GetLabelMap(s, &label_map); for (typename LabelMap::iterator liter = label_map.begin(); liter != label_map.end(); ++liter) { AddArc(s, liter->second); } SetArcs(s); } private: // Constructs proto determinization transition, including // destination subset, per label. void GetLabelMap(StateId s, LabelMap *label_map) { const StateTuple *src_tuple = state_table_->Tuple(s); filter_->SetState(s, *src_tuple); for (typename Subset::const_iterator siter = src_tuple->subset.begin(); siter != src_tuple->subset.end(); ++siter) { const Element &src_element = *siter; for (ArcIterator< Fst<A> > aiter(GetFst(), src_element.state_id); !aiter.Done(); aiter.Next()) { const A &arc = aiter.Value(); Element dest_element(arc.nextstate, Times(src_element.weight, arc.weight)); filter_->FilterArc(arc, src_element, dest_element, label_map); } } for (typename LabelMap::iterator liter = label_map->begin(); liter != label_map->end(); ++liter) { NormArc(&liter->second); } } // Sorts subsets and removes duplicate elements. // Normalizes transition and subset weights. void NormArc(DeterminizeArc<StateTuple> *det_arc) { StateTuple *dest_tuple = det_arc->dest_tuple; dest_tuple->subset.sort(); typename Subset::iterator piter = dest_tuple->subset.begin(); for (typename Subset::iterator diter = dest_tuple->subset.begin(); diter != dest_tuple->subset.end();) { Element &dest_element = *diter; Element &prev_element = *piter; // Computes arc weight. det_arc->weight = common_divisor_(det_arc->weight, dest_element.weight); if (piter != diter && dest_element.state_id == prev_element.state_id) { // Found duplicate state: sums state weight and deletes dup. prev_element.weight = Plus(prev_element.weight, dest_element.weight); if (!prev_element.weight.Member()) SetProperties(kError, kError); ++diter; dest_tuple->subset.erase_after(piter); } else { piter = diter; ++diter; } } // Divides out label weight from destination subset elements. // Quantizes to ensure comparisons are effective. for (typename Subset::iterator diter = dest_tuple->subset.begin(); diter != dest_tuple->subset.end(); ++diter) { Element &dest_element = *diter; dest_element.weight = Divide(dest_element.weight, det_arc->weight, DIVIDE_LEFT); dest_element.weight = dest_element.weight.Quantize(delta_); } } // Adds an arc from state S to the destination state associated // with state tuple in DET_ARC (as created by GetLabelMap). void AddArc(StateId s, const DeterminizeArc<StateTuple> &det_arc) { A arc; arc.ilabel = det_arc.label; arc.olabel = det_arc.label; arc.weight = det_arc.weight; arc.nextstate = FindState(det_arc.dest_tuple); CacheImpl<A>::PushArc(s, arc); } float delta_; // Quantization delta for subset weights const vector<Weight> *in_dist_; // Distance to final NFA states vector<Weight> *out_dist_; // Distance to final DFA states D common_divisor_; F *filter_; T *state_table_; void operator=(const DeterminizeFsaImpl<A, D, F, T> &); // disallow }; // Implementation of delayed determinization for transducers. // Transducer determinization is implemented by mapping the input to // the Gallic semiring as an acceptor whose weights contain the output // strings and using acceptor determinization above to determinize // that acceptor. template <class A, GallicType G, class D, class F, class T> class DeterminizeFstImpl : public DeterminizeFstImplBase<A> { public: using FstImpl<A>::SetProperties; using DeterminizeFstImplBase<A>::GetFst; using CacheBaseImpl< CacheState<A> >::GetCacheGc; using CacheBaseImpl< CacheState<A> >::GetCacheLimit; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef ToGallicMapper<A, G> ToMapper; typedef FromGallicMapper<A, G> FromMapper; typedef typename ToMapper::ToArc ToArc; typedef ArcMapFst<A, ToArc, ToMapper> ToFst; typedef ArcMapFst<ToArc, A, FromMapper> FromFst; typedef GallicCommonDivisor<Label, Weight, G, D> ToD; typedef typename F::template rebind<ToArc>::other ToF; typedef typename ToF::FilterState ToFilterState; typedef typename T::template rebind<ToArc, ToFilterState>::other ToT; typedef GallicFactor<Label, Weight, G> FactorIterator; DeterminizeFstImpl(const Fst<A> &fst, const DeterminizeFstOptions<A, D, F, T> &opts) : DeterminizeFstImplBase<A>(fst, opts), delta_(opts.delta), subsequential_label_(opts.subsequential_label) { if (opts.state_table) { FSTERROR() << "DeterminizeFst: " << "a state table can not be passed with transducer input"; SetProperties(kError, kError); return; } Init(GetFst(), opts.filter); } DeterminizeFstImpl(const DeterminizeFstImpl<A, G, D, F, T> &impl) : DeterminizeFstImplBase<A>(impl), delta_(impl.delta_), subsequential_label_(impl.subsequential_label_) { Init(GetFst(), 0); } ~DeterminizeFstImpl() { delete from_fst_; } virtual DeterminizeFstImpl<A, G, D, F, T> *Copy() { return new DeterminizeFstImpl<A, G, D, F, T>(*this); } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if ((mask & kError) && (GetFst().Properties(kError, false) || from_fst_->Properties(kError, false))) SetProperties(kError, kError); return FstImpl<A>::Properties(mask); } virtual StateId ComputeStart() { return from_fst_->Start(); } virtual Weight ComputeFinal(StateId s) { return from_fst_->Final(s); } virtual void Expand(StateId s) { for (ArcIterator<FromFst> aiter(*from_fst_, s); !aiter.Done(); aiter.Next()) CacheImpl<A>::PushArc(s, aiter.Value()); CacheImpl<A>::SetArcs(s); } private: // Initialization of transducer determinization implementation, which // is defined after DeterminizeFst since it calls it. void Init(const Fst<A> &fst, F *filter); float delta_; Label subsequential_label_; FromFst *from_fst_; void operator=(const DeterminizeFstImpl<A, G, D, F, T> &); // disallow }; // Determinizes a weighted transducer. This version is a delayed // Fst. The result will be an equivalent FST that has the property // that no state has two transitions with the same input label. // For this algorithm, epsilon transitions are treated as regular // symbols (cf. RmEpsilon). // // The transducer must be functional. The weights must be (weakly) // left divisible (valid for TropicalWeight and LogWeight for instance) // and be zero-sum-free if for all a,b: (Plus(a, b) = 0 => a = b = 0. // // Complexity: // - Determinizable: exponential (polynomial in the size of the output) // - Non-determinizable) does not terminate // // The determinizable automata include all unweighted and all acyclic input. // // References: // - <NAME>, "Finite-State Transducers in Language and Speech // Processing". Computational Linguistics, 23:2, 1997. // // This class attaches interface to implementation and handles // reference counting, delegating most methods to ImplToFst. template <class A> class DeterminizeFst : public ImplToFst< DeterminizeFstImplBase<A> > { public: friend class ArcIterator< DeterminizeFst<A> >; friend class StateIterator< DeterminizeFst<A> >; template <class B, GallicType G, class D, class F, class T> friend class DeterminizeFstImpl; typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef DefaultCacheStore<A> Store; typedef typename Store::State State; typedef DeterminizeFstImplBase<A> Impl; using ImplToFst<Impl>::SetImpl; explicit DeterminizeFst(const Fst<A> &fst) { typedef DefaultCommonDivisor<Weight> D; typedef DefaultDeterminizeFilter<A> F; typedef typename F::FilterState FilterState; typedef DefaultDeterminizeStateTable<A, FilterState> T; DeterminizeFstOptions<A, D, F, T> opts; Init(fst, opts); } template <class D, class F, class T> DeterminizeFst(const Fst<A> &fst, const DeterminizeFstOptions<A, D, F, T> &opts) { Init(fst, opts); } // This acceptor-only version additionally computes the distance to // final states in the output if provided with those distances for the // input. Useful for e.g. unique N-shortest paths. template <class D, class F, class T> DeterminizeFst(const Fst<A> &fst, const vector<Weight> *in_dist, vector<Weight> *out_dist, const DeterminizeFstOptions<A, D, F, T> &opts) { if (!fst.Properties(kAcceptor, true)) { FSTERROR() << "DeterminizeFst:" << " distance to final states computed for acceptors only"; GetImpl()->SetProperties(kError, kError); } SetImpl(new DeterminizeFsaImpl<A, D, F, T>(fst, in_dist, out_dist, opts)); } // See Fst<>::Copy() for doc. DeterminizeFst(const DeterminizeFst<A> &fst, bool safe = false) : ImplToFst<Impl>() { if (safe) SetImpl(fst.GetImpl()->Copy()); else SetImpl(fst.GetImpl(), false); } // Get a copy of this DeterminizeFst. See Fst<>::Copy() for further doc. virtual DeterminizeFst<A> *Copy(bool safe = false) const { return new DeterminizeFst<A>(*this, safe); } virtual inline void InitStateIterator(StateIteratorData<A> *data) const; virtual void InitArcIterator(StateId s, ArcIteratorData<A> *data) const { GetImpl()->InitArcIterator(s, data); } private: template <class D, class F, class T> void Init(const Fst<Arc> &fst, const DeterminizeFstOptions<A, D, F, T> &opts) { if (fst.Properties(kAcceptor, true)) { // Calls implementation for acceptors. SetImpl(new DeterminizeFsaImpl<A, D, F, T>(fst, 0, 0, opts)); } else if (opts.disambiguate_output) { if (!(Weight::Properties() & kPath)) { FSTERROR() << "DeterminizeFst: Weight needs to have the " << "path property to disambiguate output: " << Weight::Type(); GetImpl()->SetProperties(kError, kError); } // Calls disambiguating implementation for non-functional transducers. SetImpl(new DeterminizeFstImpl<A, GALLIC_LEFT_MIN, D, F, T>(fst, opts)); } else { // Calls implementation for functional transducers. SetImpl(new DeterminizeFstImpl<A, GALLIC_LEFT_RESTRICT, D, F, T>(fst, opts)); } } // Makes visible to friends. Impl *GetImpl() const { return ImplToFst<Impl>::GetImpl(); } void operator=(const DeterminizeFst<A> &fst); // Disallow }; // Initialization of transducer determinization implementation, which // is defined after DeterminizeFst since it calls it. template <class A, GallicType G, class D, class F, class T> void DeterminizeFstImpl<A, G, D, F, T>::Init(const Fst<A> &fst, F *filter) { // Mapper to an acceptor. ToFst to_fst(fst, ToMapper()); ToF *to_filter = filter ? new ToF(to_fst, filter) : 0; // Determinizes acceptor. // This recursive call terminates since it is to a (non-recursive) // different constructor. CacheOptions copts(GetCacheGc(), GetCacheLimit()); DeterminizeFstOptions<ToArc, ToD, ToF, ToT> dopts(copts, delta_, 0, false, to_filter); // Uses acceptor-only constructor to avoid template recursion DeterminizeFst<ToArc> det_fsa(to_fst, 0, 0, dopts); // Mapper back to transducer. FactorWeightOptions<ToArc> fopts(CacheOptions(true, 0), delta_, kFactorFinalWeights, subsequential_label_, subsequential_label_); FactorWeightFst<ToArc, FactorIterator> factored_fst(det_fsa, fopts); from_fst_ = new FromFst(factored_fst, FromMapper(subsequential_label_)); } // Specialization for DeterminizeFst. template <class A> class StateIterator< DeterminizeFst<A> > : public CacheStateIterator< DeterminizeFst<A> > { public: explicit StateIterator(const DeterminizeFst<A> &fst) : CacheStateIterator< DeterminizeFst<A> >(fst, fst.GetImpl()) {} }; // Specialization for DeterminizeFst. template <class A> class ArcIterator< DeterminizeFst<A> > : public CacheArcIterator< DeterminizeFst<A> > { public: typedef typename A::StateId StateId; ArcIterator(const DeterminizeFst<A> &fst, StateId s) : CacheArcIterator< DeterminizeFst<A> >(fst.GetImpl(), s) { if (!fst.GetImpl()->HasArcs(s)) fst.GetImpl()->Expand(s); } private: DISALLOW_COPY_AND_ASSIGN(ArcIterator); }; template <class A> inline void DeterminizeFst<A>::InitStateIterator(StateIteratorData<A> *data) const { data->base = new StateIterator< DeterminizeFst<A> >(*this); } // Useful aliases when using StdArc. typedef DeterminizeFst<StdArc> StdDeterminizeFst; template <class Arc> struct DeterminizeOptions { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef typename Arc::Label Label; float delta; // Quantization delta for subset weights. Weight weight_threshold; // Pruning weight threshold. StateId state_threshold; // Pruning state threshold. Label subsequential_label; // Label used for residual final output // when producing subsequential transducers. bool disambiguate_output; // Ensure functionality by summing ambig. outputs explicit DeterminizeOptions(float d = kDelta, Weight w = Weight::Zero(), StateId n = kNoStateId, Label l = 0, bool o = false) : delta(d), weight_threshold(w), state_threshold(n), subsequential_label(l), disambiguate_output(o) {} }; // Determinizes a weighted transducer. This version writes the // determinized Fst to an output MutableFst. The result will be an // equivalent FST that has the property that no state has two // transitions with the same input label. For this algorithm, epsilon // transitions are treated as regular symbols (cf. RmEpsilon). // // The transducer must be functional. The weights must be (weakly) // left divisible (valid for TropicalWeight and LogWeight). // // Complexity: // - Determinizable: exponential (polynomial in the size of the output) // - Non-determinizable: does not terminate // // The determinizable automata include all unweighted and all acyclic input. // // References: // - <NAME>, "Finite-State Transducers in Language and Speech // Processing". Computational Linguistics, 23:2, 1997. template <class Arc> void Determinize(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, const DeterminizeOptions<Arc> &opts = DeterminizeOptions<Arc>()) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; DeterminizeFstOptions<Arc> nopts; nopts.delta = opts.delta; nopts.subsequential_label = opts.subsequential_label; nopts.disambiguate_output = opts.disambiguate_output; nopts.gc_limit = 0; // Cache only the last state for fastest copy. if (opts.weight_threshold != Weight::Zero() || opts.state_threshold != kNoStateId) { if (ifst.Properties(kAcceptor, false)) { vector<Weight> idistance, odistance; ShortestDistance(ifst, &idistance, true); DeterminizeFst<Arc> dfst(ifst, &idistance, &odistance, nopts); PruneOptions< Arc, AnyArcFilter<Arc> > popts(opts.weight_threshold, opts.state_threshold, AnyArcFilter<Arc>(), &odistance); Prune(dfst, ofst, popts); } else { *ofst = DeterminizeFst<Arc>(ifst, nopts); Prune(ofst, opts.weight_threshold, opts.state_threshold); } } else { *ofst = DeterminizeFst<Arc>(ifst, nopts); } } } // namespace fst #endif // FST_LIB_DETERMINIZE_H__ <|start_filename|>third_party/openfst/src/script/rmepsilon.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/rmepsilon.h> namespace fst { namespace script { void RmEpsilon(const FstClass &ifst, MutableFstClass *ofst, bool reverse, const RmEpsilonOptions &opts) { if (!ArcTypesMatch(ifst, *ofst, "RmEpsilon")) return; RmEpsilonArgs1 args(ifst, ofst, reverse, opts); Apply<Operation<RmEpsilonArgs1> >("RmEpsilon", ifst.ArcType(), &args); } void RmEpsilon(MutableFstClass *fst, bool connect, const WeightClass &weight_threshold, int64 state_threshold, float delta) { RmEpsilonArgs2 args(fst, connect, weight_threshold, state_threshold, delta); Apply<Operation<RmEpsilonArgs2> >("RmEpsilon", fst->ArcType(), &args); } void RmEpsilon(MutableFstClass *fst, vector<WeightClass> *distance, const RmEpsilonOptions &opts) { RmEpsilonArgs3 args(fst, distance, opts); Apply<Operation<RmEpsilonArgs3> >("RmEpsilon", fst->ArcType(), &args); } REGISTER_FST_OPERATION(RmEpsilon, StdArc, RmEpsilonArgs1); REGISTER_FST_OPERATION(RmEpsilon, LogArc, RmEpsilonArgs1); REGISTER_FST_OPERATION(RmEpsilon, Log64Arc, RmEpsilonArgs1); REGISTER_FST_OPERATION(RmEpsilon, StdArc, RmEpsilonArgs2); REGISTER_FST_OPERATION(RmEpsilon, LogArc, RmEpsilonArgs2); REGISTER_FST_OPERATION(RmEpsilon, Log64Arc, RmEpsilonArgs2); REGISTER_FST_OPERATION(RmEpsilon, StdArc, RmEpsilonArgs3); REGISTER_FST_OPERATION(RmEpsilon, LogArc, RmEpsilonArgs3); REGISTER_FST_OPERATION(RmEpsilon, Log64Arc, RmEpsilonArgs3); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/connect.h<|end_filename|> // connect.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Classes and functions to remove unsuccessful paths from an Fst. #ifndef FST_LIB_CONNECT_H__ #define FST_LIB_CONNECT_H__ #include <vector> using std::vector; #include <fst/dfs-visit.h> #include <fst/union-find.h> #include <fst/mutable-fst.h> namespace fst { // Finds and returns connected components. Use with Visit(). template <class A> class CcVisitor { public: typedef A Arc; typedef typename Arc::Weight Weight; typedef typename A::StateId StateId; // cc[i]: connected component number for state i. CcVisitor(vector<StateId> *cc) : comps_(new UnionFind<StateId>(0, kNoStateId)), cc_(cc), nstates_(0) { } // comps: connected components equiv classes. CcVisitor(UnionFind<StateId> *comps) : comps_(comps), cc_(0), nstates_(0) { } ~CcVisitor() { if (cc_) // own comps_? delete comps_; } void InitVisit(const Fst<A> &fst) { } bool InitState(StateId s, StateId root) { ++nstates_; if (comps_->FindSet(s) == kNoStateId) comps_->MakeSet(s); return true; } bool WhiteArc(StateId s, const A &arc) { comps_->MakeSet(arc.nextstate); comps_->Union(s, arc.nextstate); return true; } bool GreyArc(StateId s, const A &arc) { comps_->Union(s, arc.nextstate); return true; } bool BlackArc(StateId s, const A &arc) { comps_->Union(s, arc.nextstate); return true; } void FinishState(StateId s) { } void FinishVisit() { if (cc_) GetCcVector(cc_); } // cc[i]: connected component number for state i. // Returns number of components. int GetCcVector(vector<StateId> *cc) { cc->clear(); cc->resize(nstates_, kNoStateId); StateId ncomp = 0; for (StateId i = 0; i < nstates_; ++i) { StateId rep = comps_->FindSet(i); StateId &comp = (*cc)[rep]; if (comp == kNoStateId) { comp = ncomp; ++ncomp; } (*cc)[i] = comp; } return ncomp; } private: UnionFind<StateId> *comps_; // Components vector<StateId> *cc_; // State's cc number StateId nstates_; // State count }; // Finds and returns strongly-connected components, accessible and // coaccessible states and related properties. Uses Tarjan's single // DFS SCC algorithm (see Aho, et al, "Design and Analysis of Computer // Algorithms", 189pp). Use with DfsVisit(); template <class A> class SccVisitor { public: typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; // scc[i]: strongly-connected component number for state i. // SCC numbers will be in topological order for acyclic input. // access[i]: accessibility of state i. // coaccess[i]: coaccessibility of state i. // Any of above can be NULL. // props: related property bits (cyclicity, initial cyclicity, // accessibility, coaccessibility) set/cleared (o.w. unchanged). SccVisitor(vector<StateId> *scc, vector<bool> *access, vector<bool> *coaccess, uint64 *props) : scc_(scc), access_(access), coaccess_(coaccess), props_(props) {} SccVisitor(uint64 *props) : scc_(0), access_(0), coaccess_(0), props_(props) {} void InitVisit(const Fst<A> &fst); bool InitState(StateId s, StateId root); bool TreeArc(StateId s, const A &arc) { return true; } bool BackArc(StateId s, const A &arc) { StateId t = arc.nextstate; if ((*dfnumber_)[t] < (*lowlink_)[s]) (*lowlink_)[s] = (*dfnumber_)[t]; if ((*coaccess_)[t]) (*coaccess_)[s] = true; *props_ |= kCyclic; *props_ &= ~kAcyclic; if (arc.nextstate == start_) { *props_ |= kInitialCyclic; *props_ &= ~kInitialAcyclic; } return true; } bool ForwardOrCrossArc(StateId s, const A &arc) { StateId t = arc.nextstate; if ((*dfnumber_)[t] < (*dfnumber_)[s] /* cross edge */ && (*onstack_)[t] && (*dfnumber_)[t] < (*lowlink_)[s]) (*lowlink_)[s] = (*dfnumber_)[t]; if ((*coaccess_)[t]) (*coaccess_)[s] = true; return true; } void FinishState(StateId s, StateId p, const A *); void FinishVisit() { // Numbers SCC's in topological order when acyclic. if (scc_) for (StateId i = 0; i < scc_->size(); ++i) (*scc_)[i] = nscc_ - 1 - (*scc_)[i]; if (coaccess_internal_) delete coaccess_; delete dfnumber_; delete lowlink_; delete onstack_; delete scc_stack_; } private: vector<StateId> *scc_; // State's scc number vector<bool> *access_; // State's accessibility vector<bool> *coaccess_; // State's coaccessibility uint64 *props_; const Fst<A> *fst_; StateId start_; StateId nstates_; // State count StateId nscc_; // SCC count bool coaccess_internal_; vector<StateId> *dfnumber_; // state discovery times vector<StateId> *lowlink_; // lowlink[s] == dfnumber[s] => SCC root vector<bool> *onstack_; // is a state on the SCC stack vector<StateId> *scc_stack_; // SCC stack (w/ random access) }; template <class A> inline void SccVisitor<A>::InitVisit(const Fst<A> &fst) { if (scc_) scc_->clear(); if (access_) access_->clear(); if (coaccess_) { coaccess_->clear(); coaccess_internal_ = false; } else { coaccess_ = new vector<bool>; coaccess_internal_ = true; } *props_ |= kAcyclic | kInitialAcyclic | kAccessible | kCoAccessible; *props_ &= ~(kCyclic | kInitialCyclic | kNotAccessible | kNotCoAccessible); fst_ = &fst; start_ = fst.Start(); nstates_ = 0; nscc_ = 0; dfnumber_ = new vector<StateId>; lowlink_ = new vector<StateId>; onstack_ = new vector<bool>; scc_stack_ = new vector<StateId>; } template <class A> inline bool SccVisitor<A>::InitState(StateId s, StateId root) { scc_stack_->push_back(s); while (dfnumber_->size() <= s) { if (scc_) scc_->push_back(-1); if (access_) access_->push_back(false); coaccess_->push_back(false); dfnumber_->push_back(-1); lowlink_->push_back(-1); onstack_->push_back(false); } (*dfnumber_)[s] = nstates_; (*lowlink_)[s] = nstates_; (*onstack_)[s] = true; if (root == start_) { if (access_) (*access_)[s] = true; } else { if (access_) (*access_)[s] = false; *props_ |= kNotAccessible; *props_ &= ~kAccessible; } ++nstates_; return true; } template <class A> inline void SccVisitor<A>::FinishState(StateId s, StateId p, const A *) { if (fst_->Final(s) != Weight::Zero()) (*coaccess_)[s] = true; if ((*dfnumber_)[s] == (*lowlink_)[s]) { // root of new SCC bool scc_coaccess = false; size_t i = scc_stack_->size(); StateId t; do { t = (*scc_stack_)[--i]; if ((*coaccess_)[t]) scc_coaccess = true; } while (s != t); do { t = scc_stack_->back(); if (scc_) (*scc_)[t] = nscc_; if (scc_coaccess) (*coaccess_)[t] = true; (*onstack_)[t] = false; scc_stack_->pop_back(); } while (s != t); if (!scc_coaccess) { *props_ |= kNotCoAccessible; *props_ &= ~kCoAccessible; } ++nscc_; } if (p != kNoStateId) { if ((*coaccess_)[s]) (*coaccess_)[p] = true; if ((*lowlink_)[s] < (*lowlink_)[p]) (*lowlink_)[p] = (*lowlink_)[s]; } } // Trims an FST, removing states and arcs that are not on successful // paths. This version modifies its input. // // Complexity: // - Time: O(V + E) // - Space: O(V + E) // where V = # of states and E = # of arcs. template<class Arc> void Connect(MutableFst<Arc> *fst) { typedef typename Arc::StateId StateId; vector<bool> access; vector<bool> coaccess; uint64 props = 0; SccVisitor<Arc> scc_visitor(0, &access, &coaccess, &props); DfsVisit(*fst, &scc_visitor); vector<StateId> dstates; for (StateId s = 0; s < access.size(); ++s) if (!access[s] || !coaccess[s]) dstates.push_back(s); fst->DeleteStates(dstates); fst->SetProperties(kAccessible | kCoAccessible, kAccessible | kCoAccessible); } // Returns an acyclic FST where each SCC in the input FST has been // condensed to a single state with transitions between SCCs retained // and within SCCs dropped. Also returns the mapping from an input // state 's' to an output state 'scc[s]'. template<class Arc> void Condense(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, vector<typename Arc::StateId> *scc) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; ofst->DeleteStates(); uint64 props = 0; SccVisitor<Arc> scc_visitor(scc, 0, 0, &props); DfsVisit(ifst, &scc_visitor); for (StateId s = 0; s < scc->size(); ++s) { StateId c = (*scc)[s]; while (c >= ofst->NumStates()) ofst->AddState(); if (s == ifst.Start()) ofst->SetStart(c); Weight final = ifst.Final(s); if (final != Weight::Zero()) ofst->SetFinal(c, Plus(ofst->Final(c), final)); for (ArcIterator< Fst<Arc> > aiter(ifst, s); !aiter.Done(); aiter.Next()) { Arc arc = aiter.Value(); StateId nextc = (*scc)[arc.nextstate]; if (nextc != c) { while (nextc >= ofst->NumStates()) ofst->AddState(); arc.nextstate = nextc; ofst->AddArc(c, arc); } } } ofst->SetProperties(kAcyclic | kInitialAcyclic, kAcyclic | kInitialAcyclic); } } // namespace fst #endif // FST_LIB_CONNECT_H__ <|start_filename|>third_party/openfst/src/include/fst/script/arg-packs.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Convenience templates for defining arg packs for the FstClass operations. // See operation-templates.h for a discussion about why these are needed; the // short story is that all FstClass operations must be implemented by a version // that takes one argument, most likely a struct bundling all the // logical arguments together. These template structs provide convenient ways // to specify these bundles (e.g. by means of appropriate typedefs). // The ArgPack template is sufficient for bundling together all the args for // a particular function. The function is assumed to be void-returning. If // you want a space for a return value, use the WithReturnValue template // as follows: // WithReturnValue<bool, ArgPack<...> > #ifndef FST_SCRIPT_ARG_PACKS_H_ #define FST_SCRIPT_ARG_PACKS_H_ namespace fst { namespace script { namespace args { // Sentinel value that means "no arg here." class none_type { }; // Base arg pack template class. Specializations follow that allow // fewer numbers of arguments (down to 2). If the maximum number of arguments // increases, you will need to change three things: // 1) Add more template parameters to this template // 2) Add more specializations to allow fewer numbers of parameters than // the new max. // 3) Add extra none_types to all existing specializations to fill // the new slots. // 9 args (max) template<class T1, class T2 = none_type, class T3 = none_type, class T4 = none_type, class T5 = none_type, class T6 = none_type, class T7 = none_type, class T8 = none_type, class T9 = none_type> struct Package { T1 arg1; T2 arg2; T3 arg3; T4 arg4; T5 arg5; T6 arg6; T7 arg7; T8 arg8; T9 arg9; Package(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) : arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6), arg7(arg7), arg8(arg8), arg9(arg9) { } }; // 8 args template<class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> struct Package<T1, T2, T3, T4, T5, T6, T7, T8, none_type> { T1 arg1; T2 arg2; T3 arg3; T4 arg4; T5 arg5; T6 arg6; T7 arg7; T8 arg8; Package(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) : arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6), arg7(arg7), arg8(arg8) { } }; // 7 args template<class T1, class T2, class T3, class T4, class T5, class T6, class T7> struct Package<T1, T2, T3, T4, T5, T6, T7, none_type, none_type> { T1 arg1; T2 arg2; T3 arg3; T4 arg4; T5 arg5; T6 arg6; T7 arg7; Package(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) : arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6), arg7(arg7) { } }; // 6 args template<class T1, class T2, class T3, class T4, class T5, class T6> struct Package<T1, T2, T3, T4, T5, T6, none_type, none_type, none_type> { T1 arg1; T2 arg2; T3 arg3; T4 arg4; T5 arg5; T6 arg6; Package(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) : arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6) { } }; // 5 args template<class T1, class T2, class T3, class T4, class T5> struct Package<T1, T2, T3, T4, T5, none_type, none_type, none_type, none_type> { T1 arg1; T2 arg2; T3 arg3; T4 arg4; T5 arg5; Package(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) : arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5) { } }; // 4 args template<class T1, class T2, class T3, class T4> struct Package<T1, T2, T3, T4, none_type, none_type, none_type, none_type, none_type> { T1 arg1; T2 arg2; T3 arg3; T4 arg4; Package(T1 arg1, T2 arg2, T3 arg3, T4 arg4) : arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4) { } }; // 3 args template<class T1, class T2, class T3> struct Package<T1, T2, T3, none_type, none_type, none_type, none_type, none_type, none_type> { T1 arg1; T2 arg2; T3 arg3; Package(T1 arg1, T2 arg2, T3 arg3) : arg1(arg1), arg2(arg2), arg3(arg3) { } }; // 2 args (minimum) template<class T1, class T2> struct Package<T1, T2, none_type, none_type, none_type, none_type, none_type, none_type, none_type> { T1 arg1; T2 arg2; Package(T1 arg1, T2 arg2) : arg1(arg1), arg2(arg2) { } }; // Tack this on to an existing arg pack to add a return value. // The syntax for accessing the args is then slightly more stilted, // as you must do an extra member access (since the args are stored // as a member of this class). // The alternative is to declare another slew of templates for functions // that return a value, analogous to the above. template<class Retval, class ArgPackage> struct WithReturnValue { Retval retval; const ArgPackage &args; explicit WithReturnValue(const ArgPackage &args) : args(args) { } }; // We don't want to store a reference to a reference, if ArgPackage is // already some reference type. template<class Retval, class ArgPackage> struct WithReturnValue<Retval, ArgPackage&> { Retval retval; const ArgPackage &args; explicit WithReturnValue(const ArgPackage &args) : args(args) { } }; } // namespace args } // namespace script } // namespace fst #endif // FST_SCRIPT_ARG_PACKS_H_ <|start_filename|>third_party/openfst/src/script/connect.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/connect.h> namespace fst { namespace script { void Connect(MutableFstClass *fst) { Apply<Operation<MutableFstClass> >("Connect", fst->ArcType(), fst); } REGISTER_FST_OPERATION(Connect, StdArc, MutableFstClass); REGISTER_FST_OPERATION(Connect, LogArc, MutableFstClass); REGISTER_FST_OPERATION(Connect, Log64Arc, MutableFstClass); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/matcher-fst.h<|end_filename|> // matcher-fst.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to add a matcher to an FST. #ifndef FST_LIB_MATCHER_FST_FST_H__ #define FST_LIB_MATCHER_FST_FST_H__ #include <fst/add-on.h> #include <fst/const-fst.h> #include <fst/lookahead-matcher.h> namespace fst { // WRITABLE MATCHERS - these have the interface of Matchers (see // matcher.h) and these additional methods: // // template <class F> // class Matcher { // public: // typedef ... MatcherData; // Initialization data // ... // // Constructor with additional argument for external initialization // // data; matcher increments its reference count on construction and // // decrements the reference count, and if 0 deletes, on destruction. // Matcher(const F &fst, MatchType type, MatcherData *data); // // // Returns pointer to initialization data that can be // // passed to a Matcher constructor. // MatcherData *GetData() const; // }; // The matcher initialization data class must have the form: // class MatcherData { // public: // // Required copy constructor. // MatcherData(const MatcherData &); // // // // Required I/O methods. // static MatcherData *Read(istream &istrm); // bool Write(ostream &ostrm); // // // Required reference counting. // int RefCount() const; // int IncrRefCount(); // int DecrRefCount(); // }; // Default MatcherFst initializer - does nothing. template <class M> class NullMatcherFstInit { public: typedef AddOnPair<typename M::MatcherData, typename M::MatcherData> D; typedef AddOnImpl<typename M::FST, D> Impl; NullMatcherFstInit(Impl **) {} }; // Class to add a matcher M to an Fst F. Creates a new Fst of type name N. // Optional function object I can be used to initialize the Fst. // Parameter A allows defining the kind of add-on to use. template <class F, class M, const char* N, class I = NullMatcherFstInit<M>, class A = AddOnPair<typename M::MatcherData, typename M::MatcherData> > class MatcherFst : public ImplToExpandedFst<AddOnImpl<F, A> > { public: friend class StateIterator< MatcherFst<F, M, N, I, A> >; friend class ArcIterator< MatcherFst<F, M, N, I, A> >; typedef F FST; typedef M FstMatcher; typedef typename F::Arc Arc; typedef typename Arc::StateId StateId; typedef A D; typedef AddOnImpl<F, D> Impl; MatcherFst() : ImplToExpandedFst<Impl>(new Impl(F(), N)) {} explicit MatcherFst(const F &fst) : ImplToExpandedFst<Impl>(CreateImpl(fst, N)) {} explicit MatcherFst(const Fst<Arc> &fst) : ImplToExpandedFst<Impl>(CreateImpl(fst, N)) {} // See Fst<>::Copy() for doc. MatcherFst(const MatcherFst<F, M, N, I, A> &fst, bool safe = false) : ImplToExpandedFst<Impl>(fst, safe) {} // Get a copy of this MatcherFst. See Fst<>::Copy() for further doc. virtual MatcherFst<F, M, N, I, A> *Copy(bool safe = false) const { return new MatcherFst<F, M, N, I, A>(*this, safe); } // Read a MatcherFst from an input stream; return NULL on error static MatcherFst<F, M, N, I, A> *Read(istream &strm, const FstReadOptions &opts) { Impl *impl = Impl::Read(strm, opts); return impl ? new MatcherFst<F, M, N, I, A>(impl) : 0; } // Read a MatcherFst from a file; return NULL on error // Empty filename reads from standard input static MatcherFst<F, M, N, I, A> *Read(const string &filename) { Impl *impl = ImplToExpandedFst<Impl>::Read(filename); return impl ? new MatcherFst<F, M, N, I, A>(impl) : 0; } virtual bool Write(ostream &strm, const FstWriteOptions &opts) const { return GetImpl()->Write(strm, opts); } virtual bool Write(const string &filename) const { return Fst<Arc>::WriteFile(filename); } virtual void InitStateIterator(StateIteratorData<Arc> *data) const { return GetImpl()->InitStateIterator(data); } virtual void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) const { return GetImpl()->InitArcIterator(s, data); } virtual M *InitMatcher(MatchType match_type) const { return new M(GetFst(), match_type, GetData(match_type)); } // Allows access to MatcherFst components. Impl *GetImpl() const { return ImplToFst<Impl, ExpandedFst<Arc> >::GetImpl(); } F& GetFst() const { return GetImpl()->GetFst(); } typename M::MatcherData *GetData(MatchType match_type) const { D *data = GetImpl()->GetAddOn(); return match_type == MATCH_INPUT ? data->First() : data->Second(); } private: static Impl *CreateImpl(const F &fst, const string &name) { M imatcher(fst, MATCH_INPUT); M omatcher(fst, MATCH_OUTPUT); D *data = new D(imatcher.GetData(), omatcher.GetData()); Impl *impl = new Impl(fst, name); impl->SetAddOn(data); I init(&impl); data->DecrRefCount(); return impl; } static Impl *CreateImpl(const Fst<Arc> &fst, const string &name) { F ffst(fst); return CreateImpl(ffst, name); } explicit MatcherFst(Impl *impl) : ImplToExpandedFst<Impl>(impl) {} // Makes visible to friends. void SetImpl(Impl *impl, bool own_impl = true) { ImplToFst< Impl, ExpandedFst<Arc> >::SetImpl(impl, own_impl); } void operator=(const MatcherFst<F, M, N, I, A> &fst); // disallow }; // Specialization fo MatcherFst. template <class F, class M, const char* N, class I> class StateIterator< MatcherFst<F, M, N, I> > : public StateIterator<F> { public: explicit StateIterator(const MatcherFst<F, M, N, I> &fst) : StateIterator<F>(fst.GetImpl()->GetFst()) {} }; // Specialization for MatcherFst. template <class F, class M, const char* N, class I> class ArcIterator< MatcherFst<F, M, N, I> > : public ArcIterator<F> { public: ArcIterator(const MatcherFst<F, M, N, I> &fst, typename F::Arc::StateId s) : ArcIterator<F>(fst.GetImpl()->GetFst(), s) {} }; // Specialization for MatcherFst template <class F, class M, const char* N, class I> class Matcher< MatcherFst<F, M, N, I> > { public: typedef MatcherFst<F, M, N, I> FST; typedef typename F::Arc Arc; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; Matcher(const FST &fst, MatchType match_type) { matcher_ = fst.InitMatcher(match_type); } Matcher(const Matcher<FST> &matcher) { matcher_ = matcher.matcher_->Copy(); } ~Matcher() { delete matcher_; } Matcher<FST> *Copy() const { return new Matcher<FST>(*this); } MatchType Type(bool test) const { return matcher_->Type(test); } void SetState(StateId s) { matcher_->SetState(s); } bool Find(Label label) { return matcher_->Find(label); } bool Done() const { return matcher_->Done(); } const Arc& Value() const { return matcher_->Value(); } void Next() { matcher_->Next(); } uint64 Properties(uint64 props) const { return matcher_->Properties(props); } uint32 Flags() const { return matcher_->Flags(); } private: M *matcher_; void operator=(const Matcher<Arc> &); // disallow }; // Specialization for MatcherFst template <class F, class M, const char* N, class I> class LookAheadMatcher< MatcherFst<F, M, N, I> > { public: typedef MatcherFst<F, M, N, I> FST; typedef typename F::Arc Arc; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; LookAheadMatcher(const FST &fst, MatchType match_type) { matcher_ = fst.InitMatcher(match_type); } LookAheadMatcher(const LookAheadMatcher<FST> &matcher, bool safe = false) { matcher_ = matcher.matcher_->Copy(safe); } ~LookAheadMatcher() { delete matcher_; } // General matcher methods LookAheadMatcher<FST> *Copy(bool safe = false) const { return new LookAheadMatcher<FST>(*this, safe); } MatchType Type(bool test) const { return matcher_->Type(test); } void SetState(StateId s) { matcher_->SetState(s); } bool Find(Label label) { return matcher_->Find(label); } bool Done() const { return matcher_->Done(); } const Arc& Value() const { return matcher_->Value(); } void Next() { matcher_->Next(); } const FST &GetFst() const { return matcher_->GetFst(); } uint64 Properties(uint64 props) const { return matcher_->Properties(props); } uint32 Flags() const { return matcher_->Flags(); } // Look-ahead methods bool LookAheadLabel(Label label) const { return matcher_->LookAheadLabel(label); } bool LookAheadFst(const Fst<Arc> &fst, StateId s) { return matcher_->LookAheadFst(fst, s); } Weight LookAheadWeight() const { return matcher_->LookAheadWeight(); } bool LookAheadPrefix(Arc *arc) const { return matcher_->LookAheadPrefix(arc); } void InitLookAheadFst(const Fst<Arc>& fst, bool copy = false) { matcher_->InitLookAheadFst(fst, copy); } private: M *matcher_; void operator=(const LookAheadMatcher<FST> &); // disallow }; // // Useful aliases when using StdArc and LogArc. // // Arc look-ahead matchers extern const char arc_lookahead_fst_type[]; typedef MatcherFst<ConstFst<StdArc>, ArcLookAheadMatcher<SortedMatcher<ConstFst<StdArc> > >, arc_lookahead_fst_type> StdArcLookAheadFst; typedef MatcherFst<ConstFst<LogArc>, ArcLookAheadMatcher<SortedMatcher<ConstFst<LogArc> > >, arc_lookahead_fst_type> LogArcLookAheadFst; // Label look-ahead matchers extern const char ilabel_lookahead_fst_type[]; extern const char olabel_lookahead_fst_type[]; static const uint32 ilabel_lookahead_flags = kInputLookAheadMatcher | kLookAheadWeight | kLookAheadPrefix | kLookAheadEpsilons | kLookAheadNonEpsilonPrefix; static const uint32 olabel_lookahead_flags = kOutputLookAheadMatcher | kLookAheadWeight | kLookAheadPrefix | kLookAheadEpsilons | kLookAheadNonEpsilonPrefix; typedef MatcherFst<ConstFst<StdArc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<StdArc> >, ilabel_lookahead_flags, FastLogAccumulator<StdArc> >, ilabel_lookahead_fst_type, LabelLookAheadRelabeler<StdArc> > StdILabelLookAheadFst; typedef MatcherFst<ConstFst<LogArc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<LogArc> >, ilabel_lookahead_flags, FastLogAccumulator<LogArc> >, ilabel_lookahead_fst_type, LabelLookAheadRelabeler<LogArc> > LogILabelLookAheadFst; typedef MatcherFst<ConstFst<StdArc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<StdArc> >, olabel_lookahead_flags, FastLogAccumulator<StdArc> >, olabel_lookahead_fst_type, LabelLookAheadRelabeler<StdArc> > StdOLabelLookAheadFst; typedef MatcherFst<ConstFst<LogArc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<LogArc> >, olabel_lookahead_flags, FastLogAccumulator<LogArc> >, olabel_lookahead_fst_type, LabelLookAheadRelabeler<LogArc> > LogOLabelLookAheadFst; } // namespace fst #endif // FST_LIB_MATCHER_FST_FST_H__ <|start_filename|>third_party/openfst/src/extensions/linear/fstlinear.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: wuke #include <fst/extensions/linear/linearscript.h> DEFINE_string(arc_type, "standard", "Output arc type"); DEFINE_string(epsilon_symbol, "<eps>", "Epsilon symbol"); DEFINE_string(unknown_symbol, "<unk>", "Unknown word symbol"); DEFINE_string(vocab, "", "Path to the vocabulary file"); DEFINE_string(out, "", "Path to the output binary"); DEFINE_string(save_isymbols, "", "Save input symbol table to file"); DEFINE_string(save_fsymbols, "", "Save feature symbol table to file"); DEFINE_string(save_osymbols, "", "Save output symbol table to file"); int main(int argc, char **argv) { // TODO(wuke): more detailed usage std::set_new_handler(FailedNewHandler); SET_FLAGS(argv[0], &argc, &argv, true); fst::script::ValidateDelimiter(); fst::script::ValidateEmptySymbol(); if (argc == 1) { ShowUsage(); return 1; } fst::script::LinearCompile(FLAGS_arc_type, FLAGS_epsilon_symbol, FLAGS_unknown_symbol, FLAGS_vocab, argv + 1, argc - 1, FLAGS_out, FLAGS_save_isymbols, FLAGS_save_fsymbols, FLAGS_save_osymbols); } <|start_filename|>third_party/openfst/src/include/fst/compose-filter.h<|end_filename|> // compose-filter.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Classes for filtering the composition matches, e.g. for correct epsilon // handling. #ifndef FST_LIB_COMPOSE_FILTER_H__ #define FST_LIB_COMPOSE_FILTER_H__ #include <fst/fst.h> #include <fst/fst-decl.h> // For optional argument declarations #include <fst/filter-state.h> #include <fst/matcher.h> namespace fst { // COMPOSITION FILTERS - these determine which matches are allowed to // proceed. The filter's state is represented by the type // ComposeFilter::FilterState. The basic filters handle correct // epsilon matching. Their interface is: // // template <class M1, class M2> // class ComposeFilter { // public: // typedef typename M1::FST1 FST1; // typedef typename M1::FST2 FST2; // typedef typename FST1::Arc Arc; // typedef ... FilterState; // typedef ... Matcher1; // typedef ... Matcher2; // // // Required constructors. // ComposeFilter(const FST1 &fst1, const FST2 &fst2, // // M1 *matcher1 = 0, M2 *matcher2 = 0); // // If safe=true, the copy is thread-safe. See Fst<>::Copy() // // for further doc. // ComposeFilter(const ComposeFilter<M1, M2> &filter, // // bool safe = false); // // Return start state of filter. // FilterState Start() const; // // Specifies current composition state. // void SetState(StateId s1, StateId s2, const FilterState &f); // // // Apply filter at current composition state to these transitions. // // If an arc label to be matched is kNolabel, then that side // // does not consume a symbol. Returns the new filter state or, // // if disallowed, FilterState::NoState(). The filter is permitted to // // modify its inputs, e.g. for optimizations. // FilterState FilterArc(Arc *arc1, Arc *arc2) const; // // Apply filter at current composition state to these final weights // // (cf. superfinal transitions). The filter may modify its inputs, // // e.g. for optimizations. // void FilterFinal(Weight *final1, Weight *final2) const; // // // Return resp matchers. Ownership stays with filter. These // // methods allow the filter to access and possibly modify // // the composition matchers (useful e.g. with lookahead). // Matcher1 *GetMatcher1(); // Matcher2 *GetMatcher2(); // // // This specifies how the filter affects the composition result // // properties. It takes as argument the properties that would // // apply with a trivial composition fitler. // uint64 Properties(uint64 props) const; // }; // This filter allows only exact matching of symbols from FST1 with on // FST2; e.g. no special interpretation of epsilons. (Template arg // default declared in fst-decl.h.) template <class M1, class M2 /* = M1 */> class NullComposeFilter { public: typedef typename M1::FST FST1; typedef typename M2::FST FST2; typedef typename FST1::Arc Arc; typedef CharFilterState FilterState; typedef M1 Matcher1; typedef M2 Matcher2; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; NullComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1 = 0, M2 *matcher2 = 0) : matcher1_(matcher1 ? matcher1 : new M1(fst1, MATCH_OUTPUT)), matcher2_(matcher2 ? matcher2 : new M2(fst2, MATCH_INPUT)), fst1_(matcher1_->GetFst()), fst2_(matcher2_->GetFst()) {} NullComposeFilter(const NullComposeFilter<M1, M2> &filter, bool safe = false) : matcher1_(filter.matcher1_->Copy(safe)), matcher2_(filter.matcher2_->Copy(safe)), fst1_(matcher1_->GetFst()), fst2_(matcher2_->GetFst()) {} ~NullComposeFilter() { delete matcher1_; delete matcher2_; } FilterState Start() const { return FilterState(0); } void SetState(StateId, StateId, const FilterState &) { } FilterState FilterArc(Arc *arc1, Arc *arc2) const { return (arc1->olabel == kNoLabel || arc2->ilabel == kNoLabel) ? FilterState::NoState() : FilterState(0); } void FilterFinal(Weight *, Weight *) const {} // Return resp matchers. Ownership stays with filter. Matcher1 *GetMatcher1() { return matcher1_; } Matcher2 *GetMatcher2() { return matcher2_; } uint64 Properties(uint64 props) const { return props; } private: Matcher1 *matcher1_; Matcher2 *matcher2_; const FST1 &fst1_; const FST2 &fst2_; void operator=(const NullComposeFilter<M1, M2> &); // disallow }; // This filter requires epsilons on FST1 to be read before epsilons on FST2. // (Template arg default declared in fst-decl.h.) template <class M1, class M2 /* = M1 */> class SequenceComposeFilter { public: typedef typename M1::FST FST1; typedef typename M2::FST FST2; typedef typename FST1::Arc Arc; typedef CharFilterState FilterState; typedef M1 Matcher1; typedef M2 Matcher2; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; SequenceComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1 = 0, M2 *matcher2 = 0) : matcher1_(matcher1 ? matcher1 : new M1(fst1, MATCH_OUTPUT)), matcher2_(matcher2 ? matcher2 : new M2(fst2, MATCH_INPUT)), fst1_(matcher1_->GetFst()), s1_(kNoStateId), s2_(kNoStateId), f_(kNoStateId) {} SequenceComposeFilter(const SequenceComposeFilter<M1, M2> &filter, bool safe = false) : matcher1_(filter.matcher1_->Copy(safe)), matcher2_(filter.matcher2_->Copy(safe)), fst1_(matcher1_->GetFst()), s1_(kNoStateId), s2_(kNoStateId), f_(kNoStateId) {} ~SequenceComposeFilter() { delete matcher1_; delete matcher2_; } FilterState Start() const { return FilterState(0); } void SetState(StateId s1, StateId s2, const FilterState &f) { if (s1_ == s1 && s2_ == s2 && f == f_) return; s1_ = s1; s2_ = s2; f_ = f; size_t na1 = internal::NumArcs(fst1_, s1); size_t ne1 = internal::NumOutputEpsilons(fst1_, s1); bool fin1 = internal::Final(fst1_, s1) != Weight::Zero(); alleps1_ = na1 == ne1 && !fin1; noeps1_ = ne1 == 0; } FilterState FilterArc(Arc *arc1, Arc *arc2) const { if (arc1->olabel == kNoLabel) return alleps1_ ? FilterState::NoState() : noeps1_ ? FilterState(0) : FilterState(1); else if (arc2->ilabel == kNoLabel) return f_ != FilterState(0) ? FilterState::NoState() : FilterState(0); else return arc1->olabel == 0 ? FilterState::NoState() : FilterState(0); } void FilterFinal(Weight *, Weight *) const {} // Return resp matchers. Ownership stays with filter. Matcher1 *GetMatcher1() { return matcher1_; } Matcher2 *GetMatcher2() { return matcher2_; } uint64 Properties(uint64 props) const { return props; } private: Matcher1 *matcher1_; Matcher2 *matcher2_; const FST1 &fst1_; StateId s1_; // Current fst1_ state; StateId s2_; // Current fst2_ state; FilterState f_; // Current filter state bool alleps1_; // Only epsilons (and non-final) leaving s1_? bool noeps1_; // No epsilons leaving s1_? void operator=(const SequenceComposeFilter<M1, M2> &); // disallow }; // This filter requires epsilons on FST2 to be read before epsilons on FST1. // (Template arg default declared in fst-decl.h.) template <class M1, class M2 /* = M1 */> class AltSequenceComposeFilter { public: typedef typename M1::FST FST1; typedef typename M2::FST FST2; typedef typename FST1::Arc Arc; typedef CharFilterState FilterState; typedef M1 Matcher1; typedef M2 Matcher2; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; AltSequenceComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1 = 0, M2 *matcher2 = 0) : matcher1_(matcher1 ? matcher1 : new M1(fst1, MATCH_OUTPUT)), matcher2_(matcher2 ? matcher2 : new M2(fst2, MATCH_INPUT)), fst2_(matcher2_->GetFst()), s1_(kNoStateId), s2_(kNoStateId), f_(kNoStateId) {} AltSequenceComposeFilter(const AltSequenceComposeFilter<M1, M2> &filter, bool safe = false) : matcher1_(filter.matcher1_->Copy(safe)), matcher2_(filter.matcher2_->Copy(safe)), fst2_(matcher2_->GetFst()), s1_(kNoStateId), s2_(kNoStateId), f_(kNoStateId) {} ~AltSequenceComposeFilter() { delete matcher1_; delete matcher2_; } FilterState Start() const { return FilterState(0); } void SetState(StateId s1, StateId s2, const FilterState &f) { if (s1_ == s1 && s2_ == s2 && f == f_) return; s1_ = s1; s2_ = s2; f_ = f; size_t na2 = internal::NumArcs(fst2_, s2); size_t ne2 = internal::NumInputEpsilons(fst2_, s2); bool fin2 = internal::Final(fst2_, s2) != Weight::Zero(); alleps2_ = na2 == ne2 && !fin2; noeps2_ = ne2 == 0; } FilterState FilterArc(Arc *arc1, Arc *arc2) const { if (arc2->ilabel == kNoLabel) return alleps2_ ? FilterState::NoState() : noeps2_ ? FilterState(0) : FilterState(1); else if (arc1->olabel == kNoLabel) return f_ == FilterState(1) ? FilterState::NoState() : FilterState(0); else return arc1->olabel == 0 ? FilterState::NoState() : FilterState(0); } void FilterFinal(Weight *, Weight *) const {} // Return resp matchers. Ownership stays with filter. Matcher1 *GetMatcher1() { return matcher1_; } Matcher2 *GetMatcher2() { return matcher2_; } uint64 Properties(uint64 props) const { return props; } private: Matcher1 *matcher1_; Matcher2 *matcher2_; const FST2 &fst2_; StateId s1_; // Current fst1_ state; StateId s2_; // Current fst2_ state; FilterState f_; // Current filter state bool alleps2_; // Only epsilons (and non-final) leaving s2_? bool noeps2_; // No epsilons leaving s2_? void operator=(const AltSequenceComposeFilter<M1, M2> &); // disallow }; // This filter requires epsilons on FST1 to be matched with epsilons on FST2 // whenever possible. (Template arg default declared in fst-decl.h.) template <class M1, class M2 /* = M1 */> class MatchComposeFilter { public: typedef typename M1::FST FST1; typedef typename M2::FST FST2; typedef typename FST1::Arc Arc; typedef CharFilterState FilterState; typedef M1 Matcher1; typedef M2 Matcher2; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; MatchComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1 = 0, M2 *matcher2 = 0) : matcher1_(matcher1 ? matcher1 : new M1(fst1, MATCH_OUTPUT)), matcher2_(matcher2 ? matcher2 : new M2(fst2, MATCH_INPUT)), fst1_(matcher1_->GetFst()), fst2_(matcher2_->GetFst()), s1_(kNoStateId), s2_(kNoStateId), f_(kNoStateId) {} MatchComposeFilter(const MatchComposeFilter<M1, M2> &filter, bool safe = false) : matcher1_(filter.matcher1_->Copy(safe)), matcher2_(filter.matcher2_->Copy(safe)), fst1_(matcher1_->GetFst()), fst2_(matcher2_->GetFst()), s1_(kNoStateId), s2_(kNoStateId), f_(kNoStateId) {} ~MatchComposeFilter() { delete matcher1_; delete matcher2_; } FilterState Start() const { return FilterState(0); } void SetState(StateId s1, StateId s2, const FilterState &f) { if (s1_ == s1 && s2_ == s2 && f == f_) return; s1_ = s1; s2_ = s2; f_ = f; size_t na1 = internal::NumArcs(fst1_, s1); size_t ne1 = internal::NumOutputEpsilons(fst1_, s1); bool f1 = internal::Final(fst1_, s1) != Weight::Zero(); alleps1_ = na1 == ne1 && !f1; noeps1_ = ne1 == 0; size_t na2 = internal::NumArcs(fst2_, s2); size_t ne2 = internal::NumInputEpsilons(fst2_, s2); bool f2 = internal::Final(fst2_, s2) != Weight::Zero(); alleps2_ = na2 == ne2 && !f2; noeps2_ = ne2 == 0; } FilterState FilterArc(Arc *arc1, Arc *arc2) const { if (arc2->ilabel == kNoLabel) // Epsilon on Fst1 return f_ == FilterState(0) ? (noeps2_ ? FilterState(0) : (alleps2_ ? FilterState::NoState(): FilterState(1))) : (f_ == FilterState(1) ? FilterState(1) : FilterState::NoState()); else if (arc1->olabel == kNoLabel) // Epsilon on Fst2 return f_ == FilterState(0) ? (noeps1_ ? FilterState(0) : (alleps1_ ? FilterState::NoState() : FilterState(2))) : (f_ == FilterState(2) ? FilterState(2) : FilterState::NoState()); else if (arc1->olabel == 0) // Epsilon on both return f_ == FilterState(0) ? FilterState(0) : FilterState::NoState(); else // Both are non-epsilons return FilterState(0); } void FilterFinal(Weight *, Weight *) const {} // Return resp matchers. Ownership stays with filter. Matcher1 *GetMatcher1() { return matcher1_; } Matcher2 *GetMatcher2() { return matcher2_; } uint64 Properties(uint64 props) const { return props; } private: Matcher1 *matcher1_; Matcher2 *matcher2_; const FST1 &fst1_; const FST2 &fst2_; StateId s1_; // Current fst1_ state; StateId s2_; // Current fst2_ state; FilterState f_; // Current filter state ID bool alleps1_, alleps2_; // Only epsilons (and non-final) leaving s1, s2? bool noeps1_, noeps2_; // No epsilons leaving s1, s2? void operator=(const MatchComposeFilter<M1, M2> &); // disallow }; // This filter works with the MultiEpsMatcher to determine if // 'multi-epsilons' are preserved in the composition output // (rather than rewritten as 0) and ensures correct properties. template <class F> class MultiEpsFilter { public: typedef typename F::FST1 FST1; typedef typename F::FST2 FST2; typedef typename F::Arc Arc; typedef typename F::Matcher1 Matcher1; typedef typename F::Matcher2 Matcher2; typedef typename F::FilterState FilterState; typedef MultiEpsFilter<F> Filter; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; MultiEpsFilter(const FST1 &fst1, const FST2 &fst2, Matcher1 *matcher1 = 0, Matcher2 *matcher2 = 0, bool keep_multi_eps = false) : filter_(fst1, fst2, matcher1, matcher2), keep_multi_eps_(keep_multi_eps) {} MultiEpsFilter(const Filter &filter, bool safe = false) : filter_(filter.filter_, safe), keep_multi_eps_(filter.keep_multi_eps_) {} FilterState Start() const { return filter_.Start(); } void SetState(StateId s1, StateId s2, const FilterState &f) { return filter_.SetState(s1, s2, f); } FilterState FilterArc(Arc *arc1, Arc *arc2) const { FilterState f = filter_.FilterArc(arc1, arc2); if (keep_multi_eps_) { if (arc1->olabel == kNoLabel) arc1->ilabel = arc2->ilabel; if (arc2->ilabel == kNoLabel) arc2->olabel = arc1->olabel; } return f; } void FilterFinal(Weight *w1, Weight *w2) const { return filter_.FilterFinal(w1, w2); } // Return resp matchers. Ownership stays with filter. Matcher1 *GetMatcher1() { return filter_.GetMatcher1(); } Matcher2 *GetMatcher2() { return filter_.GetMatcher2(); } uint64 Properties(uint64 iprops) const { uint64 oprops = filter_.Properties(iprops); return oprops & kILabelInvariantProperties & kOLabelInvariantProperties; } private: F filter_; bool keep_multi_eps_; }; } // namespace fst #endif // FST_LIB_COMPOSE_FILTER_H__ <|start_filename|>third_party/openfst/src/script/equivalent.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/equivalent.h> namespace fst { namespace script { bool Equivalent(const FstClass &fst1, const FstClass &fst2, float delta) { if (!ArcTypesMatch(fst1, fst2, "Equivalent")) return false; EquivalentInnerArgs args(fst1, fst2, delta); EquivalentArgs args_with_retval(args); Apply<Operation<EquivalentArgs> >("Equivalent", fst1.ArcType(), &args_with_retval); return args_with_retval.retval; } REGISTER_FST_OPERATION(Equivalent, StdArc, EquivalentArgs); REGISTER_FST_OPERATION(Equivalent, LogArc, EquivalentArgs); REGISTER_FST_OPERATION(Equivalent, Log64Arc, EquivalentArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/script/compose.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/compose.h> namespace fst { namespace script { void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, ComposeFilter compose_filter) { if (!ArcTypesMatch(ifst1, ifst2, "Compose") || !ArcTypesMatch(*ofst, ifst1, "Compose")) return; ComposeArgs1 args(ifst1, ifst2, ofst, compose_filter); Apply<Operation<ComposeArgs1> >("Compose", ifst1.ArcType(), &args); } void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &copts) { if (!ArcTypesMatch(ifst1, ifst2, "Compose") || !ArcTypesMatch(*ofst, ifst1, "Compose")) return; ComposeArgs2 args(ifst1, ifst2, ofst, copts); Apply<Operation<ComposeArgs2> >("Compose", ifst1.ArcType(), &args); } REGISTER_FST_OPERATION(Compose, StdArc, ComposeArgs1); REGISTER_FST_OPERATION(Compose, LogArc, ComposeArgs1); REGISTER_FST_OPERATION(Compose, Log64Arc, ComposeArgs1); REGISTER_FST_OPERATION(Compose, StdArc, ComposeArgs2); REGISTER_FST_OPERATION(Compose, LogArc, ComposeArgs2); REGISTER_FST_OPERATION(Compose, Log64Arc, ComposeArgs2); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/lookahead-filter.h<|end_filename|> // lookahead-filter.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Composition filters to support lookahead matchers, useful for improving // composition efficiency with certain inputs. #ifndef FST_LIB_LOOKAHEAD_FILTER_H__ #define FST_LIB_LOOKAHEAD_FILTER_H__ #include <vector> using std::vector; #include <fst/filter-state.h> #include <fst/fst.h> #include <fst/lookahead-matcher.h> namespace fst { // Identifies and verifies the capabilities of the matcher to be used for // lookahead with the composition filters below. This version is passed // the matchers. template <class M1, class M2> MatchType LookAheadMatchType(const M1 &m1, const M2 &m2) { MatchType type1 = m1.Type(false); MatchType type2 = m2.Type(false); if (type1 == MATCH_OUTPUT && m1.Flags() & kOutputLookAheadMatcher) return MATCH_OUTPUT; else if (type2 == MATCH_INPUT && m2.Flags() & kInputLookAheadMatcher) return MATCH_INPUT; else if (m1.Flags() & kOutputLookAheadMatcher && m1.Type(true) == MATCH_OUTPUT) return MATCH_OUTPUT; else if (m2.Flags() & kInputLookAheadMatcher && m2.Type(true) == MATCH_INPUT) return MATCH_INPUT; else return MATCH_NONE; } // Identifies and verifies the capabilities of the matcher to be used for // lookahead with the composition filters below. This version uses the // Fst's default matchers. template <class Arc> MatchType LookAheadMatchType(const Fst<Arc> &fst1, const Fst<Arc> &fst2) { LookAheadMatcher< Fst <Arc> > matcher1(fst1, MATCH_OUTPUT); LookAheadMatcher< Fst <Arc> > matcher2(fst2, MATCH_INPUT); return LookAheadMatchType(matcher1, matcher2); } // // LookAheadSelector - a helper class for selecting among possibly // distinct FST and matcher types w/o using a common base class. This // lets us avoid virtual function calls. // // Stores and returns the appropriate FST and matcher for lookahead. // It is templated on the matcher types. General case has no methods // since not currently supported. template <class M1, class M2, MatchType MT> class LookAheadSelector { }; // Stores and returns the appropriate FST and matcher for lookahead. // Specialized for two matchers of same type with the (match) 'type' // arg determining which is used for lookahead. template <class M, MatchType MT> class LookAheadSelector<M, M, MT> { public: typedef typename M::Arc Arc; typedef typename M::FST F; LookAheadSelector(M *lmatcher1, M *lmatcher2, MatchType type) : lmatcher1_(lmatcher1->Copy()), lmatcher2_(lmatcher2->Copy()), type_(type) {} LookAheadSelector(const LookAheadSelector<M, M, MT> &selector) : lmatcher1_(selector.lmatcher1_->Copy()), lmatcher2_(selector.lmatcher2_->Copy()), type_(selector.type_) {} ~LookAheadSelector() { delete lmatcher1_; delete lmatcher2_; } const F &GetFst() const { return type_ == MATCH_OUTPUT ? lmatcher2_->GetFst() : lmatcher1_->GetFst(); } M *GetMatcher() const { return type_ == MATCH_OUTPUT ? lmatcher1_ : lmatcher2_; } private: M *lmatcher1_; M *lmatcher2_; MatchType type_; void operator=(const LookAheadSelector<M, M, MT> &); // disallow }; // Stores and returns the appropriate FST and matcher for lookahead. // Specialized for lookahead on input labels. template <class M1, class M2> class LookAheadSelector<M1, M2, MATCH_INPUT> { public: typedef typename M1::FST F1; LookAheadSelector(M1 *lmatcher1, M2 *lmatcher2, MatchType) : fst_(lmatcher1->GetFst().Copy()), lmatcher_(lmatcher2->Copy()) {} LookAheadSelector(const LookAheadSelector<M1, M2, MATCH_INPUT> &selector) : fst_(selector.fst_->Copy()), lmatcher_(selector.lmatcher_->Copy()) {} ~LookAheadSelector() { delete lmatcher_; delete fst_; } const F1 &GetFst() const { return *fst_; } M2 *GetMatcher() const { return lmatcher_; } private: const F1 *fst_; M2 *lmatcher_; void operator=(const LookAheadSelector<M1, M2, MATCH_INPUT> &); // disallow }; // Stores and returns the appropriate FST and matcher for lookahead. // Specialized for lookahead on output labels. template <class M1, class M2> class LookAheadSelector<M1, M2, MATCH_OUTPUT> { public: typedef typename M2::FST F2; LookAheadSelector(M1 *lmatcher1, M2 *lmatcher2, MatchType) : fst_(lmatcher2->GetFst().Copy()), lmatcher_(lmatcher1->Copy()) {} LookAheadSelector(const LookAheadSelector<M1, M2, MATCH_OUTPUT> &selector) : fst_(selector.fst_->Copy()), lmatcher_(selector.lmatcher_->Copy()) {} ~LookAheadSelector() { delete lmatcher_; delete fst_; } const F2 &GetFst() const { return *fst_; } M1 *GetMatcher() const { return lmatcher_; } private: const F2 *fst_; M1 *lmatcher_; void operator=(const LookAheadSelector<M1, M2, MATCH_OUTPUT> &); // disallow }; // This filter uses a lookahead matcher in FilterArc(arc1, arc2) to // examine the future of the composition state (arc1.nextstate, // arc2.nextstate), blocking moving forward when its determined to be // non-coaccessible. It is templated on an underlying filter, // typically the epsilon filter. Which matcher is the lookahead // matcher is determined by the template argument MT unless it is // MATCH_BOTH. In that case, both matcher arguments must be lookahead // matchers of the same type and one will be selected by // LookAheadMatchType() based on their capability. template <class F, class M1 = LookAheadMatcher<typename F::FST1>, class M2 = M1, MatchType MT = MATCH_BOTH> class LookAheadComposeFilter { public: typedef typename F::FST1 FST1; typedef typename F::FST2 FST2; typedef typename F::Arc Arc; typedef typename F::Matcher1 Matcher1; typedef typename F::Matcher2 Matcher2; typedef typename F::FilterState FilterState; typedef LookAheadComposeFilter<F, M1, M2, MT> Filter; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; LookAheadComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1, M2 *matcher2) : filter_(fst1, fst2, matcher1, matcher2), lookahead_type_(MT == MATCH_BOTH ? LookAheadMatchType(*filter_.GetMatcher1(), *filter_.GetMatcher2()) : MT), selector_(filter_.GetMatcher1(), filter_.GetMatcher2(), lookahead_type_), flags_(lookahead_type_ == MATCH_OUTPUT ? filter_.GetMatcher1()->Flags() : filter_.GetMatcher2()->Flags()) { if (lookahead_type_ == MATCH_NONE) { FSTERROR() << "LookAheadComposeFilter: 1st argument cannot " << "match/look-ahead on output labels and 2nd argument " << "cannot match/look-ahead on input labels."; } selector_.GetMatcher()->InitLookAheadFst(selector_.GetFst()); } LookAheadComposeFilter(const LookAheadComposeFilter<F, M1, M2, MT> &filter, bool safe = false) : filter_(filter.filter_, safe), lookahead_type_(filter.lookahead_type_), selector_(filter_.GetMatcher1(), filter_.GetMatcher2(), lookahead_type_), flags_(filter.flags_) { selector_.GetMatcher()->InitLookAheadFst(selector_.GetFst(), true); } FilterState Start() const { return filter_.Start(); } void SetState(StateId s1, StateId s2, const FilterState &f) { filter_.SetState(s1, s2, f); } FilterState FilterArc(Arc *arc1, Arc *arc2) const { lookahead_arc_ = false; const FilterState &f = filter_.FilterArc(arc1, arc2); if (f == FilterState::NoState()) return FilterState::NoState(); return LookAheadOutput() ? LookAheadFilterArc(arc1, arc2, f) : LookAheadFilterArc(arc2, arc1, f); } void FilterFinal(Weight *weight1, Weight *weight2) const { filter_.FilterFinal(weight1, weight2); } // Return resp matchers. Ownership stays with filter. Matcher1 *GetMatcher1() { return filter_.GetMatcher1(); } Matcher2 *GetMatcher2() { return filter_.GetMatcher2(); } const LookAheadSelector<Matcher1, Matcher2, MT> &Selector() const { return selector_; } uint64 Properties(uint64 inprops) const { uint64 outprops = filter_.Properties(inprops); if (lookahead_type_ == MATCH_NONE) outprops |= kError; return outprops; } uint32 LookAheadFlags() const { return flags_; } bool LookAheadArc() const { return lookahead_arc_; } bool LookAheadOutput() const { if (MT == MATCH_OUTPUT) return true; else if (MT == MATCH_INPUT) return false; else if (lookahead_type_ == MATCH_OUTPUT) return true; else return false; } private: FilterState LookAheadFilterArc(Arc *arca, Arc *arcb, const FilterState &f) const { Label &labela = LookAheadOutput() ? arca->olabel : arca->ilabel; if (labela != 0 && !(flags_ & kLookAheadNonEpsilons)) return f; if (labela == 0 && !(flags_ & kLookAheadEpsilons)) return f; lookahead_arc_ = true; selector_.GetMatcher()->SetState(arca->nextstate); return selector_.GetMatcher()->LookAheadFst(selector_.GetFst(), arcb->nextstate) ? f : FilterState::NoState(); } F filter_; // Underlying filter MatchType lookahead_type_; // Lookahead match type LookAheadSelector<Matcher1, Matcher2, MT> selector_; uint32 flags_; // Lookahead flags mutable bool lookahead_arc_; // Look-ahead performed at last FilterArc()? void operator=(const LookAheadComposeFilter<F, M1, M2> &); // disallow }; // This filter adds weight-pushing to a lookahead composition filter // using the LookAheadWeight() method of matcher argument. It is // templated on an underlying lookahead filter, typically the basic // lookahead filter. Weight-pushing in composition brings weights // forward as much as possible based on the lookahead information. template <class F, class M1 = LookAheadMatcher<typename F::FST1>, class M2 = M1, MatchType MT = MATCH_BOTH> class PushWeightsComposeFilter { public: typedef typename F::FST1 FST1; typedef typename F::FST2 FST2; typedef typename F::Arc Arc; typedef typename F::Matcher1 Matcher1; typedef typename F::Matcher2 Matcher2; typedef typename F::FilterState FilterState1; typedef WeightFilterState<typename Arc::Weight> FilterState2; typedef PairFilterState<FilterState1, FilterState2> FilterState; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; PushWeightsComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1, M2 *matcher2) : filter_(fst1, fst2, matcher1, matcher2), f_(FilterState::NoState()) {} PushWeightsComposeFilter(const PushWeightsComposeFilter<F, M1, M2, MT> &filter, bool safe = false) : filter_(filter.filter_, safe), f_(FilterState::NoState()) {} FilterState Start() const { return FilterState(filter_.Start(), FilterState2(Weight::One())); } void SetState(StateId s1, StateId s2, const FilterState &f) { f_ = f; filter_.SetState(s1, s2, f.GetState1()); } FilterState FilterArc(Arc *arc1, Arc *arc2) const { const FilterState1 &f1 = filter_.FilterArc(arc1, arc2); if (f1 == FilterState1::NoState()) return FilterState::NoState(); if (!(LookAheadFlags() & kLookAheadWeight)) return FilterState(f1, FilterState2(Weight::One())); const Weight &lweight = filter_.LookAheadArc() ? Selector().GetMatcher()->LookAheadWeight() : Weight::One(); const FilterState2 &f2 = f_.GetState2(); const Weight &fweight = f2.GetWeight(); arc2->weight = Divide(Times(arc2->weight, lweight), fweight); return FilterState(f1, FilterState2(lweight.Quantize())); } void FilterFinal(Weight *weight1, Weight *weight2) const { filter_.FilterFinal(weight1, weight2); if (!(LookAheadFlags() & kLookAheadWeight) || *weight1 == Weight::Zero()) return; const FilterState2 &f2 = f_.GetState2(); const Weight &fweight = f2.GetWeight(); *weight1 = Divide(*weight1, fweight); } // Return resp matchers. Ownership states with filter. Matcher1 *GetMatcher1() { return filter_.GetMatcher1(); } Matcher2 *GetMatcher2() { return filter_.GetMatcher2(); } const LookAheadSelector<Matcher1, Matcher2, MT> &Selector() const { return filter_.Selector(); } uint32 LookAheadFlags() const { return filter_.LookAheadFlags(); } bool LookAheadArc() const { return filter_.LookAheadArc(); } bool LookAheadOutput() const { return filter_.LookAheadOutput(); } uint64 Properties(uint64 props) const { return filter_.Properties(props) & kWeightInvariantProperties; } private: F filter_; // Underlying filter FilterState f_; // Current filter state void operator=(const PushWeightsComposeFilter<F, M1, M2, MT> &); // disallow }; // This filter adds label-pushing to a lookahead composition filter // using the LookAheadPrefix() method of the matcher argument. It is // templated on an underlying filter, typically the basic lookahead // or weight-pushing lookahead filter. Label-pushing in composition // matches labels as early as possible based on the lookahead // information. template <class F, class M1 = LookAheadMatcher<typename F::FST1>, class M2 = M1, MatchType MT = MATCH_BOTH> class PushLabelsComposeFilter { public: typedef typename F::FST1 FST1; typedef typename F::FST2 FST2; typedef typename F::Arc Arc; typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; typedef MultiEpsMatcher<typename F::Matcher1> Matcher1; typedef MultiEpsMatcher<typename F::Matcher2> Matcher2; typedef typename F::FilterState FilterState1; typedef IntegerFilterState<typename Arc::Label> FilterState2; typedef PairFilterState<FilterState1, FilterState2> FilterState; PushLabelsComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1, M2 *matcher2) : filter_(fst1, fst2, matcher1, matcher2), f_(FilterState::NoState()), fst1_(filter_.GetMatcher1()->GetFst()), fst2_(filter_.GetMatcher2()->GetFst()), matcher1_(fst1_, MATCH_OUTPUT, filter_.LookAheadOutput() ? kMultiEpsList : kMultiEpsLoop, filter_.GetMatcher1(), false), matcher2_(fst2_, MATCH_INPUT, filter_.LookAheadOutput() ? kMultiEpsLoop : kMultiEpsList, filter_.GetMatcher2(), false) {} PushLabelsComposeFilter(const PushLabelsComposeFilter<F, M1, M2, MT> &filter, bool safe = false) : filter_(filter.filter_, safe), f_(FilterState::NoState()), fst1_(filter_.GetMatcher1()->GetFst()), fst2_(filter_.GetMatcher2()->GetFst()), matcher1_(fst1_, MATCH_OUTPUT, filter_.LookAheadOutput() ? kMultiEpsList : kMultiEpsLoop, filter_.GetMatcher1(), false), matcher2_(fst2_, MATCH_INPUT, filter_.LookAheadOutput() ? kMultiEpsLoop : kMultiEpsList, filter_.GetMatcher2(), false) { } FilterState Start() const { return FilterState(filter_.Start(), FilterState2(kNoLabel)); } void SetState(StateId s1, StateId s2, const FilterState &f) { f_ = f; filter_.SetState(s1, s2, f.GetState1()); if (!(LookAheadFlags() & kLookAheadPrefix)) return; narcsa_ = LookAheadOutput() ? internal::NumArcs(fst1_, s1) : internal::NumArcs(fst2_, s2); const FilterState2 &f2 = f_.GetState2(); const Label &flabel = f2.GetState(); GetMatcher1()->ClearMultiEpsLabels(); GetMatcher2()->ClearMultiEpsLabels(); if (flabel != kNoLabel) { // Have a lookahead label? GetMatcher1()->AddMultiEpsLabel(flabel); // Yes, make it a multi-epsilon GetMatcher2()->AddMultiEpsLabel(flabel); // label so that it matches the } // implicit epsilon arc to be } // modified below when pushing. FilterState FilterArc(Arc *arc1, Arc *arc2) const { if (!(LookAheadFlags() & kLookAheadPrefix)) return FilterState(filter_.FilterArc(arc1, arc2), FilterState2(kNoLabel)); const FilterState2 &f2 = f_.GetState2(); const Label &flabel = f2.GetState(); if (flabel != kNoLabel) // Have a lookahead label? return LookAheadOutput() ? PushedLabelFilterArc(arc1, arc2, flabel) : PushedLabelFilterArc(arc2, arc1, flabel); const FilterState1 &f1 = filter_.FilterArc(arc1, arc2); if (f1 == FilterState1::NoState()) return FilterState::NoState(); if (!filter_.LookAheadArc()) return FilterState(f1, FilterState2(kNoLabel)); return LookAheadOutput() ? PushLabelFilterArc(arc1, arc2, f1) : PushLabelFilterArc(arc2, arc1, f1); } void FilterFinal(Weight *weight1, Weight *weight2) const { filter_.FilterFinal(weight1, weight2); if (!(LookAheadFlags() & kLookAheadPrefix) || *weight1 == Weight::Zero()) return; const FilterState2 &f2 = f_.GetState2(); const Label &flabel = f2.GetState(); if (flabel != kNoLabel) *weight1 = Weight::Zero(); } // Return resp matchers. Ownership states with filter. Matcher1 *GetMatcher1() { return &matcher1_; } Matcher2 *GetMatcher2() { return &matcher2_; } uint64 Properties(uint64 iprops) const { uint64 oprops = filter_.Properties(iprops); if (LookAheadOutput()) return oprops & kOLabelInvariantProperties; else return oprops & kILabelInvariantProperties; } private: const LookAheadSelector<typename F::Matcher1, typename F::Matcher2, MT> &Selector() const { return filter_.Selector(); } // Consumes an already pushed label. FilterState PushedLabelFilterArc(Arc *arca, Arc *arcb, Label flabel) const { Label &labela = LookAheadOutput() ? arca->olabel : arca->ilabel; const Label &labelb = LookAheadOutput() ? arcb->ilabel : arcb->olabel; if (labelb != kNoLabel) { return FilterState::NoState(); // Block non- (multi-) epsilon label } else if (labela == flabel) { labela = 0; // Convert match to multi-eps to eps return Start(); } else if (labela == 0) { if (narcsa_ == 1) return f_; // Take eps; keep state w/ label Selector().GetMatcher()->SetState(arca->nextstate); if (Selector().GetMatcher()->LookAheadLabel(flabel)) return f_; // Take eps; keep state w/ label else return FilterState::NoState(); // Block non-coaccessible path } else { return FilterState::NoState(); // Block mismatch to multi-eps label } } // Pushes a label forward when possible. FilterState PushLabelFilterArc(Arc *arca, Arc *arcb, const FilterState1 &f1) const { Label &labela = LookAheadOutput() ? arca->olabel : arca->ilabel; const Label &labelb = LookAheadOutput() ? arcb->olabel : arcb->ilabel; if (labelb != 0) // No place to push. return FilterState(f1, FilterState2(kNoLabel)); if (labela != 0 && // Wrong lookahead prefix type? LookAheadFlags() & kLookAheadNonEpsilonPrefix) return FilterState(f1, FilterState2(kNoLabel)); Arc larc(kNoLabel, kNoLabel, Weight::Zero(), kNoStateId); if (Selector().GetMatcher()->LookAheadPrefix(&larc)) { // Have prefix arc? labela = LookAheadOutput() ? larc.ilabel : larc.olabel; arcb->ilabel = larc.ilabel; // Yes, go forward on that arc, arcb->olabel = larc.olabel; // thus pushing the label. arcb->weight = Times(arcb->weight, larc.weight); arcb->nextstate = larc.nextstate; return FilterState(f1, FilterState2(labela)); } else { return FilterState(f1, FilterState2(kNoLabel)); } } uint32 LookAheadFlags() const { return filter_.LookAheadFlags(); } bool LookAheadArc() const { return filter_.LookAheadArc(); } bool LookAheadOutput() const { return filter_.LookAheadOutput(); } F filter_; // Underlying filter FilterState f_ ; // Current filter state const FST1 &fst1_; const FST2 &fst2_; Matcher1 matcher1_; // Multi-epsilon matcher for fst1 Matcher2 matcher2_; // Multi-epsilon matcher for fst2 ssize_t narcsa_; // Number of arcs leaving look-ahead match FST void operator=(const PushLabelsComposeFilter<F, M1, M2, MT> &); // disallow }; // // CONVENIENCE CLASS useful for setting up composition with a default // look-ahead matcher and filter. // template <class A, MatchType type> // MATCH_NONE class DefaultLookAhead { public: typedef Matcher< Fst<A> > M; typedef SequenceComposeFilter<M> ComposeFilter; typedef M FstMatcher; }; // Specializes for MATCH_INPUT to allow lookahead. template <class A> class DefaultLookAhead<A, MATCH_INPUT> { public: typedef LookAheadMatcher< Fst<A> > M; typedef SequenceComposeFilter<M> SF; typedef LookAheadComposeFilter<SF, M> ComposeFilter; typedef M FstMatcher; }; // Specializes for MATCH_OUTPUT to allow lookahead. template <class A> class DefaultLookAhead<A, MATCH_OUTPUT> { public: typedef LookAheadMatcher< Fst<A> > M; typedef AltSequenceComposeFilter<M> SF; typedef LookAheadComposeFilter<SF, M> ComposeFilter; typedef M FstMatcher; }; // Specializes for StdArc to allow weight and label pushing. template <> class DefaultLookAhead<StdArc, MATCH_INPUT> { public: typedef StdArc A; typedef LookAheadMatcher< Fst<A> > M; typedef SequenceComposeFilter<M> SF; typedef LookAheadComposeFilter<SF, M> LF; typedef PushWeightsComposeFilter<LF, M> WF; typedef PushLabelsComposeFilter<WF, M> ComposeFilter; typedef M FstMatcher; }; // Specializes for StdArc to allow weight and label pushing. template <> class DefaultLookAhead<StdArc, MATCH_OUTPUT> { public: typedef StdArc A; typedef LookAheadMatcher< Fst<A> > M; typedef AltSequenceComposeFilter<M> SF; typedef LookAheadComposeFilter<SF, M> LF; typedef PushWeightsComposeFilter<LF, M> WF; typedef PushLabelsComposeFilter<WF, M> ComposeFilter; typedef M FstMatcher; }; // Specializes for LogArc to allow weight and label pushing. template <> class DefaultLookAhead<LogArc, MATCH_INPUT> { public: typedef LogArc A; typedef LookAheadMatcher< Fst<A> > M; typedef SequenceComposeFilter<M> SF; typedef LookAheadComposeFilter<SF, M> LF; typedef PushWeightsComposeFilter<LF, M> WF; typedef PushLabelsComposeFilter<WF, M> ComposeFilter; typedef M FstMatcher; }; // Specializes for LogArc to allow weight and label pushing. template <> class DefaultLookAhead<LogArc, MATCH_OUTPUT> { public: typedef LogArc A; typedef LookAheadMatcher< Fst<A> > M; typedef AltSequenceComposeFilter<M> SF; typedef LookAheadComposeFilter<SF, M> LF; typedef PushWeightsComposeFilter<LF, M> WF; typedef PushLabelsComposeFilter<WF, M> ComposeFilter; typedef M FstMatcher; }; } // namespace fst #endif // FST_LIB_LOOKAHEAD_FILTER_H__ <|start_filename|>third_party/openfst/src/script/weight-class.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <string> #include <fst/arc.h> #include <fst/script/weight-class.h> namespace fst { namespace script { REGISTER_FST_WEIGHT(StdArc::Weight); REGISTER_FST_WEIGHT(LogArc::Weight); REGISTER_FST_WEIGHT(Log64Arc::Weight); WeightClass::WeightClass(const string &weight_type, const string &weight_str) : element_type_(OTHER) { WeightClassRegister *reg = WeightClassRegister::GetRegister(); StrToWeightImplBaseT stw = reg->GetEntry(weight_type); impl_ = stw(weight_str, "WeightClass", 0); } ostream& operator << (ostream &o, const WeightClass &c) { c.impl_->Print(&o); return o; } } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/script/randequivalent.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/randequivalent.h> namespace fst { namespace script { // 1 bool RandEquivalent(const FstClass &fst1, const FstClass &fst2, int32 seed, ssize_t num_paths, float delta, int path_length) { if (!ArcTypesMatch(fst1, fst2, "RandEquivalent")) return false; RandEquivalentInnerArgs1 args(fst1, fst2, seed, num_paths, delta, path_length); RandEquivalentArgs1 args_with_retval(args); Apply<Operation<RandEquivalentArgs1> >("RandEquivalent", fst1.ArcType(), &args_with_retval); return args_with_retval.retval; } // 2 bool RandEquivalent(const FstClass &fst1, const FstClass &fst2, int32 seed, ssize_t num_paths, float delta, const RandGenOptions<RandArcSelection> &opts) { if (!ArcTypesMatch(fst1, fst2, "RandEquivalent")) return false; RandEquivalentInnerArgs2 args(fst1, fst2, seed, num_paths, delta, opts); RandEquivalentArgs2 args_with_retval(args); Apply<Operation<RandEquivalentArgs2> >( "RandEquivalent", fst1.ArcType(), &args_with_retval); return args_with_retval.retval; } REGISTER_FST_OPERATION(RandEquivalent, StdArc, RandEquivalentArgs1); REGISTER_FST_OPERATION(RandEquivalent, LogArc, RandEquivalentArgs1); REGISTER_FST_OPERATION(RandEquivalent, Log64Arc, RandEquivalentArgs1); REGISTER_FST_OPERATION(RandEquivalent, StdArc, RandEquivalentArgs2); REGISTER_FST_OPERATION(RandEquivalent, LogArc, RandEquivalentArgs2); REGISTER_FST_OPERATION(RandEquivalent, Log64Arc, RandEquivalentArgs2); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/extensions/ngram/ngram-fst.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/extensions/ngram/ngram-fst.h> #include <sys/types.h> #include <fst/fstlib.h> using fst::NGramFst; using fst::StdArc; using fst::LogArc; REGISTER_FST(NGramFst, StdArc); REGISTER_FST(NGramFst, LogArc); <|start_filename|>third_party/openfst/src/bin/fstrandgen.cc<|end_filename|> // fstrandgen.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Generates random paths through an FST. #include <fst/script/randgen.h> DEFINE_int32(max_length, INT_MAX, "Maximum path length"); DEFINE_int64(npath, 1, "Number of paths to generate"); DEFINE_int32(seed, time(0), "Random seed"); DEFINE_string(select, "uniform", "Selection type: one of: " " \"uniform\", \"log_prob\" (when appropriate)," " \"fast_log_prob\" (when appropriate)"); DEFINE_bool(weighted, false, "Output tree weighted by path count vs. unweighted paths"); DEFINE_bool(remove_total_weight, false, "Remove total weight when output weighted"); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::VectorFstClass; string usage = "Generates random paths through an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } VLOG(1) << argv[0] << ": Seed = " << FLAGS_seed; string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; string out_name = argc > 2 ? argv[2] : ""; FstClass *ifst = FstClass::Read(in_name); if (!ifst) return 1; VectorFstClass ofst(ifst->ArcType()); s::RandArcSelection ras; if (FLAGS_select == "uniform") { ras = s::UNIFORM_ARC_SELECTOR; } else if (FLAGS_select == "log_prob") { ras = s::LOG_PROB_ARC_SELECTOR; } else if (FLAGS_select == "fast_log_prob") { ras = s::FAST_LOG_PROB_ARC_SELECTOR; } else { LOG(ERROR) << argv[0] << ": Unknown selection type \"" << FLAGS_select << "\"\n"; return 1; } s::RandGen(*ifst, &ofst, FLAGS_seed, fst::RandGenOptions<s::RandArcSelection>( ras, FLAGS_max_length, FLAGS_npath, FLAGS_weighted, FLAGS_remove_total_weight)); ofst.Write(out_name); return 0; } <|start_filename|>third_party/openfst/src/include/fst/extensions/far/print-strings.h<|end_filename|> // printstrings-main.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified by: <EMAIL> (<NAME>) // // \file // Output as strings the string FSTs in a finite-state archive. #ifndef FST_EXTENSIONS_FAR_PRINT_STRINGS_H__ #define FST_EXTENSIONS_FAR_PRINT_STRINGS_H__ #include <string> #include <vector> using std::vector; #include <fst/extensions/far/far.h> #include <fst/shortest-distance.h> #include <fst/string.h> DECLARE_string(far_field_separator); namespace fst { template <class Arc> void FarPrintStrings( const vector<string> &ifilenames, const FarEntryType entry_type, const FarTokenType far_token_type, const string &begin_key, const string &end_key, const bool print_key, const bool print_weight, const string &symbols_fname, const bool initial_symbols, const int32 generate_filenames, const string &filename_prefix, const string &filename_suffix) { typename StringPrinter<Arc>::TokenType token_type; if (far_token_type == FTT_SYMBOL) { token_type = StringPrinter<Arc>::SYMBOL; } else if (far_token_type == FTT_BYTE) { token_type = StringPrinter<Arc>::BYTE; } else if (far_token_type == FTT_UTF8) { token_type = StringPrinter<Arc>::UTF8; } else { FSTERROR() << "FarPrintStrings: unknown token type"; return; } const SymbolTable *syms = 0; if (!symbols_fname.empty()) { // allow negative flag? SymbolTableTextOptions opts; opts.allow_negative = true; syms = SymbolTable::ReadText(symbols_fname, opts); if (!syms) { FSTERROR() << "FarPrintStrings: error reading symbol table: " << symbols_fname; return; } } FarReader<Arc> *far_reader = FarReader<Arc>::Open(ifilenames); if (!far_reader) return; if (!begin_key.empty()) far_reader->Find(begin_key); string okey; int nrep = 0; for (int i = 1; !far_reader->Done(); far_reader->Next(), ++i) { string key = far_reader->GetKey(); if (!end_key.empty() && end_key < key) break; if (okey == key) ++nrep; else nrep = 0; okey = key; const Fst<Arc> &fst = far_reader->GetFst(); if (i == 1 && initial_symbols && syms == 0 && fst.InputSymbols() != 0) syms = fst.InputSymbols()->Copy(); string str; VLOG(2) << "Handling key: " << key; StringPrinter<Arc> string_printer( token_type, syms ? syms : fst.InputSymbols()); string_printer(fst, &str); if (entry_type == FET_LINE) { if (print_key) cout << key << FLAGS_far_field_separator[0]; cout << str; if (print_weight) cout << FLAGS_far_field_separator[0] << ShortestDistance(fst); cout << endl; } else if (entry_type == FET_FILE) { stringstream sstrm; if (generate_filenames) { sstrm.fill('0'); sstrm << std::right << setw(generate_filenames) << i; } else { sstrm << key; if (nrep > 0) sstrm << "." << nrep; } string filename; filename = filename_prefix + sstrm.str() + filename_suffix; ofstream ostrm(filename.c_str()); if (!ostrm) { FSTERROR() << "FarPrintStrings: Can't open file:" << filename; delete syms; delete far_reader; return; } ostrm << str; if (token_type == StringPrinter<Arc>::SYMBOL) ostrm << "\n"; } } delete syms; } } // namespace fst #endif // FST_EXTENSIONS_FAR_PRINT_STRINGS_H__ <|start_filename|>third_party/openfst/src/extensions/far/stlist.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/extensions/far/stlist.h> namespace fst { bool IsSTList(const string &filename) { ifstream strm(filename.c_str()); if (!strm) return false; int32 magic_number = 0; ReadType(strm, &magic_number); return magic_number == kSTListMagicNumber; } } // namespace fst <|start_filename|>fte/rank_unrank.h<|end_filename|> /* * Please see Appendix A of "Protocol Misidentification Made Easy with Format-Transforming Encryption" * url: http://dl.acm.org/citation.cfm?id=2516657 * * and * * "Compression and ranking" * url: http://dl.acm.org/citation.cfm?id=22194 * * for details about (un)ranking for regular languages. */ #ifndef _RANK_UNRANK_H #define _RANK_UNRANK_H #include <map> #include <vector> #include <stdint.h> #include <gmpxx.h> typedef std::vector<char> array_type_char_t1; typedef std::vector<bool> array_type_bool_t1; typedef std::vector<uint32_t> array_type_uint32_t1; typedef std::vector< std::vector<uint32_t> > array_type_uint32_t2; typedef std::vector< std::vector<mpz_class> > array_type_mpz_t2; typedef std::vector< std::string > array_type_string_t1; class DFA { private: // the maximum value for which buildTable is computed uint32_t _fixed_slice; // our DFA start state uint32_t _start_state; // the number of states in our DFA uint32_t _num_states; // the number of symbols in our DFA alphabet uint32_t _num_symbols; // the symbols of our DFA alphabet array_type_uint32_t1 _symbols; // our mapping between integers and the symbols in our alphabet; ints -> chars std::map<uint32_t, char> _sigma; // the reverse mapping of sigma, chars -> ints std::map<char, uint32_t> _sigma_reverse; // the states in our DFA array_type_uint32_t1 _states; // our transitions table array_type_uint32_t2 _delta; // a lookup table used for additional performance gain // for each state we detect if all outgoing transitions are to the same state array_type_bool_t1 _delta_dense; // the set of final states in our DFA array_type_uint32_t1 _final_states; // buildTable builds a mapping from [q, i] -> n // q: a state in our DFA // i: an integer // n: the number of words in our language that have a path to a final // state that is exactly length i void _buildTable(); // Checks the properties of our DFA, to ensure that we meet all constraints. // Throws an exception upon failure. void _validate(); // _T is our cached table, the output of buildTable // For a state q and integer i, the value _T[q][i] is the number of unique // accepting paths of length exactly i from state q. array_type_mpz_t2 _T; public: // The constructor of our rank/urank DFA class DFA( const std::string, const uint32_t ); // our unrank function an int -> str mapping // given an integer i, return the ith lexicographically ordered string in // the language accepted by the DFA std::string unrank( const mpz_class ); // our rank function performs the inverse operation of unrank mpz_class rank( const std::string ); // given integers [n,m] returns the number of words accepted by the // DFA that are at least length n and no greater than length m mpz_class getNumWordsInLanguage( const uint32_t, const uint32_t ); }; #endif /* _RANK_UNRANK_H */ <|start_filename|>third_party/openfst/src/include/fst/extensions/pdt/pdtlib.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // This is an experimental push-down transducer(PDT) library. A PDT is // encoded as an FST, where some transitions are labeled with open or close // parentheses. To be interpreted as a PDT, the parentheses must balance on a // path. #ifndef FST_EXTENSIONS_PDT_PDTLIB_H_ #define FST_EXTENSIONS_PDT_PDTLIB_H_ #include <fst/extensions/pdt/pdt.h> #include <fst/extensions/pdt/compose.h> #include <fst/extensions/pdt/expand.h> #include <fst/extensions/pdt/replace.h> #endif // FST_EXTENSIONS_PDT_PDTLIB_H_ <|start_filename|>third_party/openfst/src/bin/fstreweight.cc<|end_filename|> // fstreweight.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Reweights an FST. // #include <fst/script/reweight.h> #include <fst/script/text-io.h> DEFINE_bool(to_final, false, "Push/reweight to final (vs. to initial) states"); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::MutableFstClass; string usage = "Reweights an FST.\n\n Usage: "; usage += argv[0]; usage += " in.fst potential.txt [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 3 || argc > 4) { ShowUsage(); return 1; } string in_fname = argv[1]; string potentials_fname = argv[2]; string out_fname = argc > 3 ? argv[3] : ""; MutableFstClass *fst = MutableFstClass::Read(in_fname, true); if (!fst) return 1; vector<s::WeightClass> potential; if (!s::ReadPotentials(fst->WeightType(), potentials_fname, &potential)) return 1; fst::ReweightType reweight_type = FLAGS_to_final ? fst::REWEIGHT_TO_FINAL : fst::REWEIGHT_TO_INITIAL; s::Reweight(fst, potential, reweight_type); fst->Write(out_fname); return 0; } <|start_filename|>third_party/openfst/src/script/concat.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/concat.h> namespace fst { namespace script { void Concat(MutableFstClass *ofst, const FstClass &ifst) { if (!ArcTypesMatch(*ofst, ifst, "Concat")) return; ConcatArgs1 args(ofst, ifst); Apply<Operation<ConcatArgs1> >("Concat", ofst->ArcType(), &args); } void Concat(const FstClass &ifst, MutableFstClass *ofst) { if (!ArcTypesMatch(ifst, *ofst, "Concat")) return; ConcatArgs2 args(ifst, ofst); Apply<Operation<ConcatArgs2> >("Concat", ofst->ArcType(), &args); } REGISTER_FST_OPERATION(Concat, StdArc, ConcatArgs1); REGISTER_FST_OPERATION(Concat, LogArc, ConcatArgs1); REGISTER_FST_OPERATION(Concat, Log64Arc, ConcatArgs1); REGISTER_FST_OPERATION(Concat, StdArc, ConcatArgs2); REGISTER_FST_OPERATION(Concat, LogArc, ConcatArgs2); REGISTER_FST_OPERATION(Concat, Log64Arc, ConcatArgs2); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/script/intersect.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/intersect.h> namespace fst { namespace script { void Intersect(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, ComposeFilter compose_filter) { if (!ArcTypesMatch(ifst1, ifst2, "Intersect") || !ArcTypesMatch(*ofst, ifst1, "Intersect")) return; IntersectArgs1 args(ifst1, ifst2, ofst, compose_filter); Apply<Operation<IntersectArgs1> >("Intersect", ifst1.ArcType(), &args); } void Intersect(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &copts) { if (!ArcTypesMatch(ifst1, ifst2, "Intersect") || !ArcTypesMatch(*ofst, ifst1, "Intersect")) return; IntersectArgs2 args(ifst1, ifst2, ofst, copts); Apply<Operation<IntersectArgs2> >("Intersect", ifst1.ArcType(), &args); } REGISTER_FST_OPERATION(Intersect, StdArc, IntersectArgs1); REGISTER_FST_OPERATION(Intersect, LogArc, IntersectArgs1); REGISTER_FST_OPERATION(Intersect, Log64Arc, IntersectArgs1); REGISTER_FST_OPERATION(Intersect, StdArc, IntersectArgs2); REGISTER_FST_OPERATION(Intersect, LogArc, IntersectArgs2); REGISTER_FST_OPERATION(Intersect, Log64Arc, IntersectArgs2); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/include/fst/tuple-weight.h<|end_filename|> // tuple-weight.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Tuple weight set operation definitions. #ifndef FST_LIB_TUPLE_WEIGHT_H__ #define FST_LIB_TUPLE_WEIGHT_H__ #include <string> #include <vector> using std::vector; #include <fst/weight.h> DECLARE_string(fst_weight_parentheses); DECLARE_string(fst_weight_separator); namespace fst { template<class W, unsigned int n> class TupleWeight; template <class W, unsigned int n> istream &operator>>(istream &strm, TupleWeight<W, n> &w); // n-tuple weight, element of the n-th catersian power of W template <class W, unsigned int n> class TupleWeight { public: typedef TupleWeight<typename W::ReverseWeight, n> ReverseWeight; TupleWeight() {} TupleWeight(const TupleWeight &w) { for (size_t i = 0; i < n; ++i) values_[i] = w.values_[i]; } template <class Iterator> TupleWeight(Iterator begin, Iterator end) { for (Iterator iter = begin; iter != end; ++iter) values_[iter - begin] = *iter; } TupleWeight(const W &w) { for (size_t i = 0; i < n; ++i) values_[i] = w; } static const TupleWeight<W, n> &Zero() { static const TupleWeight<W, n> zero(W::Zero()); return zero; } static const TupleWeight<W, n> &One() { static const TupleWeight<W, n> one(W::One()); return one; } static const TupleWeight<W, n> &NoWeight() { static const TupleWeight<W, n> no_weight(W::NoWeight()); return no_weight; } static unsigned int Length() { return n; } istream &Read(istream &strm) { for (size_t i = 0; i < n; ++i) values_[i].Read(strm); return strm; } ostream &Write(ostream &strm) const { for (size_t i = 0; i < n; ++i) values_[i].Write(strm); return strm; } TupleWeight<W, n> &operator=(const TupleWeight<W, n> &w) { for (size_t i = 0; i < n; ++i) values_[i] = w.values_[i]; return *this; } bool Member() const { bool member = true; for (size_t i = 0; i < n; ++i) member = member && values_[i].Member(); return member; } size_t Hash() const { uint64 hash = 0; for (size_t i = 0; i < n; ++i) hash = 5 * hash + values_[i].Hash(); return size_t(hash); } TupleWeight<W, n> Quantize(float delta = kDelta) const { TupleWeight<W, n> w; for (size_t i = 0; i < n; ++i) w.values_[i] = values_[i].Quantize(delta); return w; } ReverseWeight Reverse() const { TupleWeight<W, n> w; for (size_t i = 0; i < n; ++i) w.values_[i] = values_[i].Reverse(); return w; } const W& Value(size_t i) const { return values_[i]; } void SetValue(size_t i, const W &w) { values_[i] = w; } protected: // Reads TupleWeight when there are no parentheses around tuple terms inline static istream &ReadNoParen(istream &strm, TupleWeight<W, n> &w, char separator) { int c; do { c = strm.get(); } while (isspace(c)); for (size_t i = 0; i < n - 1; ++i) { string s; if (i) c = strm.get(); while (c != separator) { if (c == EOF) { strm.clear(std::ios::badbit); return strm; } s += c; c = strm.get(); } // read (i+1)-th element istringstream sstrm(s); W r = W::Zero(); sstrm >> r; w.SetValue(i, r); } // read n-th element W r = W::Zero(); strm >> r; w.SetValue(n - 1, r); return strm; } // Reads TupleWeight when there are parentheses around tuple terms inline static istream &ReadWithParen(istream &strm, TupleWeight<W, n> &w, char separator, char open_paren, char close_paren) { int c; do { c = strm.get(); } while (isspace(c)); if (c != open_paren) { FSTERROR() << " is fst_weight_parentheses flag set correcty? "; strm.clear(std::ios::badbit); return strm; } for (size_t i = 0; i < n - 1; ++i) { // read (i+1)-th element stack<int> parens; string s; c = strm.get(); while (c != separator || !parens.empty()) { if (c == EOF) { strm.clear(std::ios::badbit); return strm; } s += c; // if parens encountered before separator, they must be matched if (c == open_paren) { parens.push(1); } else if (c == close_paren) { // Fail for mismatched parens if (parens.empty()) { strm.clear(std::ios::failbit); return strm; } parens.pop(); } c = strm.get(); } istringstream sstrm(s); W r = W::Zero(); sstrm >> r; w.SetValue(i, r); } // read n-th element string s; c = strm.get(); while (c != EOF) { s += c; c = strm.get(); } if (s.empty() || *s.rbegin() != close_paren) { FSTERROR() << " is fst_weight_parentheses flag set correcty? "; strm.clear(std::ios::failbit); return strm; } s.erase(s.size() - 1, 1); istringstream sstrm(s); W r = W::Zero(); sstrm >> r; w.SetValue(n - 1, r); return strm; } private: W values_[n]; friend istream &operator>><W, n>(istream&, TupleWeight<W, n>&); }; template <class W, unsigned int n> inline bool operator==(const TupleWeight<W, n> &w1, const TupleWeight<W, n> &w2) { bool equal = true; for (size_t i = 0; i < n; ++i) equal = equal && (w1.Value(i) == w2.Value(i)); return equal; } template <class W, unsigned int n> inline bool operator!=(const TupleWeight<W, n> &w1, const TupleWeight<W, n> &w2) { bool not_equal = false; for (size_t i = 0; (i < n) && !not_equal; ++i) not_equal = not_equal || (w1.Value(i) != w2.Value(i)); return not_equal; } template <class W, unsigned int n> inline bool ApproxEqual(const TupleWeight<W, n> &w1, const TupleWeight<W, n> &w2, float delta = kDelta) { bool approx_equal = true; for (size_t i = 0; i < n; ++i) approx_equal = approx_equal && ApproxEqual(w1.Value(i), w2.Value(i), delta); return approx_equal; } template <class W, unsigned int n> inline ostream &operator<<(ostream &strm, const TupleWeight<W, n> &w) { if(FLAGS_fst_weight_separator.size() != 1) { FSTERROR() << "FLAGS_fst_weight_separator.size() is not equal to 1"; strm.clear(std::ios::badbit); return strm; } char separator = FLAGS_fst_weight_separator[0]; bool write_parens = false; if (!FLAGS_fst_weight_parentheses.empty()) { if (FLAGS_fst_weight_parentheses.size() != 2) { FSTERROR() << "FLAGS_fst_weight_parentheses.size() is not equal to 2"; strm.clear(std::ios::badbit); return strm; } write_parens = true; } if (write_parens) strm << FLAGS_fst_weight_parentheses[0]; for (size_t i = 0; i < n; ++i) { if(i) strm << separator; strm << w.Value(i); } if (write_parens) strm << FLAGS_fst_weight_parentheses[1]; return strm; } template <class W, unsigned int n> inline istream &operator>>(istream &strm, TupleWeight<W, n> &w) { if(FLAGS_fst_weight_separator.size() != 1) { FSTERROR() << "FLAGS_fst_weight_separator.size() is not equal to 1"; strm.clear(std::ios::badbit); return strm; } char separator = FLAGS_fst_weight_separator[0]; if (!FLAGS_fst_weight_parentheses.empty()) { if (FLAGS_fst_weight_parentheses.size() != 2) { FSTERROR() << "FLAGS_fst_weight_parentheses.size() is not equal to 2"; strm.clear(std::ios::badbit); return strm; } return TupleWeight<W, n>::ReadWithParen( strm, w, separator, FLAGS_fst_weight_parentheses[0], FLAGS_fst_weight_parentheses[1]); } else { return TupleWeight<W, n>::ReadNoParen(strm, w, separator); } } } // namespace fst #endif // FST_LIB_TUPLE_WEIGHT_H__ <|start_filename|>third_party/openfst/src/include/fst/label-reachable.h<|end_filename|> // label_reachable.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Class to determine if a non-epsilon label can be read as the // first non-epsilon symbol along some path from a given state. #ifndef FST_LIB_LABEL_REACHABLE_H__ #define FST_LIB_LABEL_REACHABLE_H__ #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <vector> using std::vector; #include <fst/accumulator.h> #include <fst/arcsort.h> #include <fst/interval-set.h> #include <fst/state-reachable.h> #include <fst/util.h> #include <fst/vector-fst.h> namespace fst { // Stores shareable data for label reachable class copies. template <typename L> class LabelReachableData { public: typedef L Label; typedef typename IntervalSet<L>::Interval Interval; explicit LabelReachableData(bool reach_input, bool keep_relabel_data = true) : reach_input_(reach_input), keep_relabel_data_(keep_relabel_data), have_relabel_data_(true), final_label_(kNoLabel) {} ~LabelReachableData() {} bool ReachInput() const { return reach_input_; } vector< IntervalSet<L> > *IntervalSets() { return &isets_; } unordered_map<L, L> *Label2Index() { if (!have_relabel_data_) FSTERROR() << "LabelReachableData: no relabeling data"; return &label2index_; } Label FinalLabel() { if (final_label_ == kNoLabel) final_label_ = label2index_[kNoLabel]; return final_label_; } static LabelReachableData<L> *Read(istream &istrm) { LabelReachableData<L> *data = new LabelReachableData<L>(); ReadType(istrm, &data->reach_input_); ReadType(istrm, &data->keep_relabel_data_); data->have_relabel_data_ = data->keep_relabel_data_; if (data->keep_relabel_data_) ReadType(istrm, &data->label2index_); ReadType(istrm, &data->final_label_); ReadType(istrm, &data->isets_); return data; } bool Write(ostream &ostrm) { WriteType(ostrm, reach_input_); WriteType(ostrm, keep_relabel_data_); if (keep_relabel_data_) WriteType(ostrm, label2index_); WriteType(ostrm, FinalLabel()); WriteType(ostrm, isets_); return true; } int RefCount() const { return ref_count_.count(); } int IncrRefCount() { return ref_count_.Incr(); } int DecrRefCount() { return ref_count_.Decr(); } private: LabelReachableData() {} bool reach_input_; // Input or output labels considered? bool keep_relabel_data_; // Save label2index_ to file? bool have_relabel_data_; // Using label2index_? Label final_label_; // Final label RefCounter ref_count_; // Reference count. unordered_map<L, L> label2index_; // Finds index for a label. vector<IntervalSet <L> > isets_; // Interval sets per state. DISALLOW_COPY_AND_ASSIGN(LabelReachableData); }; // Tests reachability of labels from a given state. If reach_input = // true, then input labels are considered, o.w. output labels are // considered. To test for reachability from a state s, first do // SetState(s). Then a label l can be reached from state s of FST f // iff Reach(r) is true where r = Relabel(l). The relabeling is // required to ensure a compact representation of the reachable // labels. // The whole FST can be relabeled instead with Relabel(&f, // reach_input) so that the test Reach(r) applies directly to the // labels of the transformed FST f. The relabeled FST will also be // sorted appropriately for composition. // // Reachablity of a final state from state s (via an epsilon path) // can be tested with ReachFinal(); // // Reachability can also be tested on the set of labels specified by // an arc iterator, useful for FST composition. In particular, // Reach(aiter, ...) is true if labels on the input (output) side of // the transitions of the arc iterator, when iter_input is true // (false), can be reached from the state s. The iterator labels must // have already been relabeled. // // With the arc iterator test of reachability, the begin position, end // position and accumulated arc weight of the matches can be // returned. The optional template argument controls how reachable arc // weights are accumulated. The default uses the semiring // Plus(). Alternative ones can be used to distribute the weights in // composition in various ways. template <class A, class S = DefaultAccumulator<A>, class D = LabelReachableData<typename A::Label> > class LabelReachable { public: typedef A Arc; typedef D Data; typedef typename A::StateId StateId; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename IntervalSet<Label>::Interval Interval; LabelReachable(const Fst<A> &fst, bool reach_input, S *s = 0, bool keep_relabel_data = true) : fst_(new VectorFst<Arc>(fst)), s_(kNoStateId), data_(new D(reach_input, keep_relabel_data)), accumulator_(s ? s : new S()), ncalls_(0), nintervals_(0), reach_fst_input_(false), error_(false) { StateId ins = fst_->NumStates(); TransformFst(); FindIntervals(ins); delete fst_; } explicit LabelReachable(D *data, S *s = 0) : fst_(0), s_(kNoStateId), data_(data), accumulator_(s ? s : new S()), ncalls_(0), nintervals_(0), reach_fst_input_(false), error_(false) { data_->IncrRefCount(); } LabelReachable(const LabelReachable<A, S, D> &reachable, bool safe = false) : fst_(0), s_(kNoStateId), data_(reachable.data_), accumulator_(new S(*reachable.accumulator_, safe)), ncalls_(0), nintervals_(0), reach_fst_input_(reachable.reach_fst_input_), error_(reachable.error_) { data_->IncrRefCount(); } ~LabelReachable() { if (!data_->DecrRefCount()) delete data_; delete accumulator_; if (ncalls_ > 0) { VLOG(2) << "# of calls: " << ncalls_; VLOG(2) << "# of intervals/call: " << (nintervals_ / ncalls_); } } // Relabels w.r.t labels that give compact label sets. Label Relabel(Label label) { if (label == 0 || error_) return label; unordered_map<Label, Label> &label2index = *data_->Label2Index(); Label &relabel = label2index[label]; if (!relabel) // Add new label relabel = label2index.size() + 1; return relabel; } // Relabels Fst w.r.t to labels that give compact label sets. void Relabel(MutableFst<Arc> *fst, bool relabel_input) { for (StateIterator< MutableFst<Arc> > siter(*fst); !siter.Done(); siter.Next()) { StateId s = siter.Value(); for (MutableArcIterator< MutableFst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) { Arc arc = aiter.Value(); if (relabel_input) arc.ilabel = Relabel(arc.ilabel); else arc.olabel = Relabel(arc.olabel); aiter.SetValue(arc); } } if (relabel_input) { ArcSort(fst, ILabelCompare<Arc>()); fst->SetInputSymbols(0); } else { ArcSort(fst, OLabelCompare<Arc>()); fst->SetOutputSymbols(0); } } // Returns relabeling pairs (cf. relabel.h::Relabel()). // If 'avoid_collisions' is true, extra pairs are added to // ensure no collisions when relabeling automata that have // labels unseen here. void RelabelPairs(vector<pair<Label, Label> > *pairs, bool avoid_collisions = false) { pairs->clear(); unordered_map<Label, Label> &label2index = *data_->Label2Index(); // Maps labels to their new values in [1, label2index().size()] for (typename unordered_map<Label, Label>::const_iterator it = label2index.begin(); it != label2index.end(); ++it) if (it->second != data_->FinalLabel()) pairs->push_back(pair<Label, Label>(it->first, it->second)); if (avoid_collisions) { // Ensures any label in [1, label2index().size()] is mapped either // by the above step or to label2index() + 1 (to avoid collisions). for (int i = 1; i <= label2index.size(); ++i) { typename unordered_map<Label, Label>::const_iterator it = label2index.find(i); if (it == label2index.end() || it->second == data_->FinalLabel()) pairs->push_back(pair<Label, Label>(i, label2index.size() + 1)); } } } // Set current state. Optionally set state associated // with arc iterator to be passed to Reach. void SetState(StateId s, StateId aiter_s = kNoStateId) { s_ = s; if (aiter_s != kNoStateId) { accumulator_->SetState(aiter_s); if (accumulator_->Error()) error_ = true; } } // Can reach this label from current state? // Original labels must be transformed by the Relabel methods above. bool Reach(Label label) { if (label == 0 || error_) return false; vector< IntervalSet<Label> > &isets = *data_->IntervalSets(); return isets[s_].Member(label); } // Can reach final state (via epsilon transitions) from this state? bool ReachFinal() { if (error_) return false; vector< IntervalSet<Label> > &isets = *data_->IntervalSets(); return isets[s_].Member(data_->FinalLabel()); } // Initialize with secondary FST to be used with Reach(Iterator,...). // If reach_input = true, then arc input labels are considered in // Reach(aiter, ...), o.w. output labels are considered. // If copy is true, then 'fst' is a copy of the FST used in the // previous call to this method (useful to avoid unnecessary updates). template <class F> void ReachInit(const F &fst, bool reach_input, bool copy = false) { reach_fst_input_ = reach_input; if (!fst.Properties( reach_fst_input_ ? kILabelSorted : kOLabelSorted, true)) { FSTERROR() << "LabelReachable::ReachInit: fst is not sorted"; error_ = true; } accumulator_->Init(fst, copy); if (accumulator_->Error()) error_ = true; } // Can reach any arc iterator label between iterator positions // aiter_begin and aiter_end? // Arc iterator labels must be transformed by the Relabel methods // above. If compute_weight is true, user may call ReachWeight(). template <class Iterator> bool Reach(Iterator *aiter, ssize_t aiter_begin, ssize_t aiter_end, bool compute_weight) { if (error_) return false; vector< IntervalSet<Label> > &isets = *data_->IntervalSets(); const vector<Interval> *intervals = isets[s_].Intervals(); ++ncalls_; nintervals_ += intervals->size(); reach_begin_ = -1; reach_end_ = -1; reach_weight_ = Weight::Zero(); uint32 flags = aiter->Flags(); // save flags to restore them on exit aiter->SetFlags(kArcNoCache, kArcNoCache); // make caching optional aiter->Seek(aiter_begin); if (2 * (aiter_end - aiter_begin) < intervals->size()) { // Check each arc against intervals. // Set arc iterator flags to only compute the ilabel or olabel values, // since they are the only values required for most of the arcs processed. aiter->SetFlags(reach_fst_input_ ? kArcILabelValue : kArcOLabelValue, kArcValueFlags); Label reach_label = kNoLabel; for (ssize_t aiter_pos = aiter_begin; aiter_pos < aiter_end; aiter->Next(), ++aiter_pos) { const A &arc = aiter->Value(); Label label = reach_fst_input_ ? arc.ilabel : arc.olabel; if (label == reach_label || Reach(label)) { reach_label = label; if (reach_begin_ < 0) reach_begin_ = aiter_pos; reach_end_ = aiter_pos + 1; if (compute_weight) { if (!(aiter->Flags() & kArcWeightValue)) { // If the 'arc.weight' wasn't computed by the call // to 'aiter->Value()' above, we need to call // 'aiter->Value()' again after having set the arc iterator // flags to compute the arc weight value. aiter->SetFlags(kArcWeightValue, kArcValueFlags); const A &arcb = aiter->Value(); // Call the accumulator. reach_weight_ = accumulator_->Sum(reach_weight_, arcb.weight); // Only ilabel or olabel required to process the following // arcs. aiter->SetFlags(reach_fst_input_ ? kArcILabelValue : kArcOLabelValue, kArcValueFlags); } else { // Call the accumulator. reach_weight_ = accumulator_->Sum(reach_weight_, arc.weight); } } } } } else { // Check each interval against arcs ssize_t begin_low, end_low = aiter_begin; for (typename vector<Interval>::const_iterator iiter = intervals->begin(); iiter != intervals->end(); ++iiter) { begin_low = LowerBound(aiter, end_low, aiter_end, iiter->begin); end_low = LowerBound(aiter, begin_low, aiter_end, iiter->end); if (end_low - begin_low > 0) { if (reach_begin_ < 0) reach_begin_ = begin_low; reach_end_ = end_low; if (compute_weight) { aiter->SetFlags(kArcWeightValue, kArcValueFlags); reach_weight_ = accumulator_->Sum(reach_weight_, aiter, begin_low, end_low); } } } } aiter->SetFlags(flags, kArcFlags); // restore original flag values return reach_begin_ >= 0; } // Returns iterator position of first matching arc. ssize_t ReachBegin() const { return reach_begin_; } // Returns iterator position one past last matching arc. ssize_t ReachEnd() const { return reach_end_; } // Return the sum of the weights for matching arcs. // Valid only if compute_weight was true in Reach() call. Weight ReachWeight() const { return reach_weight_; } // Access to the relabeling map. Excludes epsilon (0) label but // includes kNoLabel that is used internally for super-final // transitons. const unordered_map<Label, Label>& Label2Index() const { return *data_->Label2Index(); } D *GetData() const { return data_; } bool Error() const { return error_ || accumulator_->Error(); } private: // Redirects labeled arcs (input or output labels determined by // ReachInput()) to new label-specific final states. Each original // final state is redirected via a transition labeled with kNoLabel // to a new kNoLabel-specific final state. Creates super-initial // state for all states with zero in-degree. void TransformFst() { StateId ins = fst_->NumStates(); StateId ons = ins; vector<ssize_t> indeg(ins, 0); // Redirects labeled arcs to new final states. for (StateId s = 0; s < ins; ++s) { for (MutableArcIterator< VectorFst<Arc> > aiter(fst_, s); !aiter.Done(); aiter.Next()) { Arc arc = aiter.Value(); Label label = data_->ReachInput() ? arc.ilabel : arc.olabel; if (label) { if (label2state_.find(label) == label2state_.end()) { label2state_[label] = ons; indeg.push_back(0); ++ons; } arc.nextstate = label2state_[label]; aiter.SetValue(arc); } ++indeg[arc.nextstate]; // Finds in-degrees for next step. } // Redirects final weights to new final state. Weight final = fst_->Final(s); if (final != Weight::Zero()) { if (label2state_.find(kNoLabel) == label2state_.end()) { label2state_[kNoLabel] = ons; indeg.push_back(0); ++ons; } Arc arc(kNoLabel, kNoLabel, final, label2state_[kNoLabel]); fst_->AddArc(s, arc); ++indeg[arc.nextstate]; // Finds in-degrees for next step. fst_->SetFinal(s, Weight::Zero()); } } // Add new final states to Fst. while (fst_->NumStates() < ons) { StateId s = fst_->AddState(); fst_->SetFinal(s, Weight::One()); } // Creates a super-initial state for all states with zero in-degree. StateId start = fst_->AddState(); fst_->SetStart(start); for (StateId s = 0; s < start; ++s) { if (indeg[s] == 0) { Arc arc(0, 0, Weight::One(), s); fst_->AddArc(start, arc); } } } void FindIntervals(StateId ins) { StateReachable<A, Label> state_reachable(*fst_); if (state_reachable.Error()) { error_ = true; return; } vector<Label> &state2index = state_reachable.State2Index(); vector< IntervalSet<Label> > &isets = *data_->IntervalSets(); isets = state_reachable.IntervalSets(); isets.resize(ins); unordered_map<Label, Label> &label2index = *data_->Label2Index(); for (typename unordered_map<Label, StateId>::const_iterator it = label2state_.begin(); it != label2state_.end(); ++it) { Label l = it->first; StateId s = it->second; Label i = state2index[s]; label2index[l] = i; } label2state_.clear(); double nintervals = 0; ssize_t non_intervals = 0; for (ssize_t s = 0; s < ins; ++s) { nintervals += isets[s].Size(); if (isets[s].Size() > 1) { ++non_intervals; VLOG(3) << "state: " << s << " # of intervals: " << isets[s].Size(); } } VLOG(2) << "# of states: " << ins; VLOG(2) << "# of intervals: " << nintervals; VLOG(2) << "# of intervals/state: " << nintervals/ins; VLOG(2) << "# of non-interval states: " << non_intervals; } template <class Iterator> ssize_t LowerBound(Iterator *aiter, ssize_t aiter_begin, ssize_t aiter_end, Label match_label) const { // Only need to compute the ilabel or olabel of arcs when // performing the binary search. aiter->SetFlags(reach_fst_input_ ? kArcILabelValue : kArcOLabelValue, kArcValueFlags); ssize_t low = aiter_begin; ssize_t high = aiter_end; while (low < high) { ssize_t mid = (low + high) / 2; aiter->Seek(mid); Label label = reach_fst_input_ ? aiter->Value().ilabel : aiter->Value().olabel; if (label > match_label) { high = mid; } else if (label < match_label) { low = mid + 1; } else { // Find first matching label (when non-deterministic) for (ssize_t i = mid; i > low; --i) { aiter->Seek(i - 1); label = reach_fst_input_ ? aiter->Value().ilabel : aiter->Value().olabel; if (label != match_label) { aiter->Seek(i); aiter->SetFlags(kArcValueFlags, kArcValueFlags); return i; } } aiter->SetFlags(kArcValueFlags, kArcValueFlags); return low; } } aiter->Seek(low); aiter->SetFlags(kArcValueFlags, kArcValueFlags); return low; } VectorFst<Arc> *fst_; StateId s_; // Current state unordered_map<Label, StateId> label2state_; // Finds final state for a label ssize_t reach_begin_; // Iterator pos of first match ssize_t reach_end_; // Iterator pos after last match Weight reach_weight_; // Gives weight sum of arc iterator // arcs with reachable labels. D *data_; // Shareable data between copies S *accumulator_; // Sums arc weights double ncalls_; double nintervals_; bool reach_fst_input_; bool error_; void operator=(const LabelReachable<A, S, D> &); // Disallow }; } // namespace fst #endif // FST_LIB_LABEL_REACHABLE_H__ <|start_filename|>third_party/openfst/src/include/fst/script/verify.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #ifndef FST_SCRIPT_VERIFY_H_ #define FST_SCRIPT_VERIFY_H_ #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> #include <fst/verify.h> namespace fst { namespace script { typedef args::WithReturnValue<bool, const FstClass *> VerifyArgs; template<class Arc> void Verify(VerifyArgs *args) { const Fst<Arc> *fst = args->args->GetFst<Arc>(); args->retval = Verify(*fst); } bool Verify(const FstClass &fst1); } // namespace script } // namespace fst #endif // FST_SCRIPT_VERIFY_H_ <|start_filename|>third_party/openfst/src/lib/fst.cc<|end_filename|> // fst.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // FST definitions. #include <fst/fst.h> // Include these so they are registered #include <fst/compact-fst.h> #include <fst/const-fst.h> #include <fst/matcher-fst.h> #include <fst/vector-fst.h> #include <fst/edit-fst.h> // FST flag definitions DEFINE_bool(fst_verify_properties, false, "Verify fst properties queried by TestProperties"); DEFINE_string(fst_weight_separator, ",", "Character separator between printed composite weights; " "must be a single character"); DEFINE_string(fst_weight_parentheses, "", "Characters enclosing the first weight of a printed composite " "weight (e.g. pair weight, tuple weight and derived classes) to " "ensure proper I/O of nested composite weights; " "must have size 0 (none) or 2 (open and close parenthesis)"); DEFINE_bool(fst_default_cache_gc, true, "Enable garbage collection of cache"); DEFINE_int64(fst_default_cache_gc_limit, 1<<20LL, "Cache byte size that triggers garbage collection"); DEFINE_bool(fst_align, false, "Write FST data aligned where appropriate"); DEFINE_string(save_relabel_ipairs, "", "Save input relabel pairs to file"); DEFINE_string(save_relabel_opairs, "", "Save output relabel pairs to file"); DEFINE_string(fst_read_mode, "read", "Default file reading mode for mappable files"); namespace fst { // Register VectorFst, ConstFst and EditFst for common arcs types REGISTER_FST(VectorFst, StdArc); REGISTER_FST(VectorFst, LogArc); REGISTER_FST(VectorFst, Log64Arc); REGISTER_FST(ConstFst, StdArc); REGISTER_FST(ConstFst, LogArc); REGISTER_FST(ConstFst, Log64Arc); REGISTER_FST(EditFst, StdArc); REGISTER_FST(EditFst, LogArc); REGISTER_FST(EditFst, Log64Arc); // Register CompactFst for common arcs with the default (uint32) size type static FstRegisterer< CompactFst<StdArc, StringCompactor<StdArc> > > CompactFst_StdArc_StringCompactor_registerer; static FstRegisterer< CompactFst<LogArc, StringCompactor<LogArc> > > CompactFst_LogArc_StringCompactor_registerer; static FstRegisterer< CompactFst<StdArc, WeightedStringCompactor<StdArc> > > CompactFst_StdArc_WeightedStringCompactor_registerer; static FstRegisterer< CompactFst<LogArc, WeightedStringCompactor<LogArc> > > CompactFst_LogArc_WeightedStringCompactor_registerer; static FstRegisterer< CompactFst<StdArc, AcceptorCompactor<StdArc> > > CompactFst_StdArc_AcceptorCompactor_registerer; static FstRegisterer< CompactFst<LogArc, AcceptorCompactor<LogArc> > > CompactFst_LogArc_AcceptorCompactor_registerer; static FstRegisterer< CompactFst<StdArc, UnweightedCompactor<StdArc> > > CompactFst_StdArc_UnweightedCompactor_registerer; static FstRegisterer< CompactFst<LogArc, UnweightedCompactor<LogArc> > > CompactFst_LogArc_UnweightedCompactor_registerer; static FstRegisterer< CompactFst<StdArc, UnweightedAcceptorCompactor<StdArc> > > CompactFst_StdArc_UnweightedAcceptorCompactor_registerer; static FstRegisterer< CompactFst<LogArc, UnweightedAcceptorCompactor<LogArc> > > CompactFst_LogArc_UnweightedAcceptorCompactor_registerer; // Fst type definitions for lookahead Fsts. extern const char arc_lookahead_fst_type[] = "arc_lookahead"; extern const char ilabel_lookahead_fst_type[] = "ilabel_lookahead"; extern const char olabel_lookahead_fst_type[] = "olabel_lookahead"; // Identifies stream data as an FST (and its endianity) static const int32 kFstMagicNumber = 2125659606; // Check for Fst magic number in stream, to indicate // caller function that the stream content is an Fst header; bool IsFstHeader(istream &strm, const string &source) { int64 pos = strm.tellg(); bool match = true; int32 magic_number = 0; ReadType(strm, &magic_number); if (magic_number != kFstMagicNumber ) { match = false; } strm.seekg(pos); return match; } // Check Fst magic number and read in Fst header. // If rewind = true, reposition stream to before call (if possible). bool FstHeader::Read(istream &strm, const string &source, bool rewind) { int64 pos = 0; if (rewind) pos = strm.tellg(); int32 magic_number = 0; ReadType(strm, &magic_number); if (magic_number != kFstMagicNumber ) { LOG(ERROR) << "FstHeader::Read: Bad FST header: " << source; if (rewind) strm.seekg(pos); return false; } ReadType(strm, &fsttype_); ReadType(strm, &arctype_); ReadType(strm, &version_); ReadType(strm, &flags_); ReadType(strm, &properties_); ReadType(strm, &start_); ReadType(strm, &numstates_); ReadType(strm, &numarcs_); if (!strm) { LOG(ERROR) << "FstHeader::Read: read failed: " << source; return false; } if (rewind) strm.seekg(pos); return true; } // Write Fst magic number and Fst header. bool FstHeader::Write(ostream &strm, const string &source) const { WriteType(strm, kFstMagicNumber); WriteType(strm, fsttype_); WriteType(strm, arctype_); WriteType(strm, version_); WriteType(strm, flags_); WriteType(strm, properties_); WriteType(strm, start_); WriteType(strm, numstates_); WriteType(strm, numarcs_); return true; } FstReadOptions::FstReadOptions(const string& src, const FstHeader *hdr, const SymbolTable* isym, const SymbolTable* osym) : source(src), header(hdr), isymbols(isym), osymbols(osym), read_isymbols(true), read_osymbols(true) { mode = ReadMode(FLAGS_fst_read_mode); } FstReadOptions::FstReadOptions(const string& src, const SymbolTable* isym, const SymbolTable* osym) : source(src), header(0), isymbols(isym), osymbols(osym), read_isymbols(true), read_osymbols(true) { mode = ReadMode(FLAGS_fst_read_mode); } FstReadOptions::FileReadMode FstReadOptions::ReadMode(const string &mode) { if (mode == "read") { return READ; } if (mode == "map") { return MAP; } LOG(ERROR) << "Unknown file read mode " << mode; return READ; } } // namespace fst <|start_filename|>third_party/openfst/src/script/disambiguate.cc<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/disambiguate.h> namespace fst { namespace script { void Disambiguate(const FstClass &ifst, MutableFstClass *ofst, const DisambiguateOptions& opts) { if (!ArcTypesMatch(ifst, *ofst, "Disambiguate")) return; DisambiguateArgs args(ifst, ofst, opts); Apply<Operation<DisambiguateArgs> >("Disambiguate", ifst.ArcType(), &args); } REGISTER_FST_OPERATION(Disambiguate, StdArc, DisambiguateArgs); REGISTER_FST_OPERATION(Disambiguate, LogArc, DisambiguateArgs); REGISTER_FST_OPERATION(Disambiguate, Log64Arc, DisambiguateArgs); } // namespace script } // namespace fst <|start_filename|>third_party/openfst/src/bin/fstclosure.cc<|end_filename|> // fstclosure.cc // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Modified: <EMAIL> (<NAME>) to use FstClass // // \file // Creates the Kleene closure of an FST. // #include <fst/script/closure.h> DEFINE_bool(closure_plus, false, "Do not add the empty path (T+ instead of T*)"); int main(int argc, char **argv) { using fst::script::FstClass; using fst::script::MutableFstClass; string usage = "Creates the Kleene closure of an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } string in_fname = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; string out_fname = argc > 2 ? argv[2] : ""; MutableFstClass *fst = MutableFstClass::Read(in_fname, true); if (!fst) return 1; fst::ClosureType closure_type = FLAGS_closure_plus ? fst::CLOSURE_PLUS : fst::CLOSURE_STAR; fst::script::Closure(fst, closure_type); fst->Write(out_fname); return 0; } <|start_filename|>third_party/openfst/src/include/fst/extensions/pdt/replace.h<|end_filename|> // replace.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Recursively replace Fst arcs with other Fst(s) returning a PDT. #ifndef FST_EXTENSIONS_PDT_REPLACE_H__ #define FST_EXTENSIONS_PDT_REPLACE_H__ #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <fst/replace.h> namespace fst { // Hash to paren IDs template <typename S> struct ReplaceParenHash { size_t operator()(const pair<size_t, S> &p) const { return p.first + p.second * kPrime; } private: static const size_t kPrime = 7853; }; template <typename S> const size_t ReplaceParenHash<S>::kPrime; // Builds a pushdown transducer (PDT) from an RTN specification // identical to that in fst/lib/replace.h. The result is a PDT // encoded as the FST 'ofst' where some transitions are labeled with // open or close parentheses. To be interpreted as a PDT, the parens // must balance on a path (see PdtExpand()). The open/close // parenthesis label pairs are returned in 'parens'. template <class Arc> void Replace(const vector<pair<typename Arc::Label, const Fst<Arc>* > >& ifst_array, MutableFst<Arc> *ofst, vector<pair<typename Arc::Label, typename Arc::Label> > *parens, typename Arc::Label root) { typedef typename Arc::Label Label; typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; ofst->DeleteStates(); parens->clear(); // Builds map from non-terminal label to FST id. unordered_map<Label, size_t> label2id; for (size_t i = 0; i < ifst_array.size(); ++i) label2id[ifst_array[i].first] = i; Label max_label = kNoLabel; // Queue of non-terminals to replace deque<size_t> non_term_queue; non_term_queue.push_back(root); // PDT state corr. to ith replace FST start state. vector<StateId> fst_start(ifst_array.size(), kNoStateId); // PDT state, weight pairs corr. to ith replace FST final state & weights. vector< vector<pair<StateId, Weight> > > fst_final(ifst_array.size()); typedef unordered_map<pair<size_t, StateId>, size_t, ReplaceParenHash<StateId> > ParenMap; // Map that gives the paren ID for a (non-terminal, dest. state) pair // (which can be unique). ParenMap paren_map; // # of distinct parenthesis pairs per fst. vector<size_t> nparens(ifst_array.size(), 0); // # of distinct parenthesis pairs overall. size_t total_nparens = 0; // Builds single Fst combining all referenced input Fsts. Leaves in the // non-termnals for now. Tabulate the PDT states that correspond to // the start and final states of the input Fsts. For each non-terminal // assigns an paren ID to each instance starting at 0; they are distinct // IDs unless the instances have the same destination state. for (StateId soff = 0; !non_term_queue.empty(); soff = ofst->NumStates()) { Label label = non_term_queue.front(); non_term_queue.pop_front(); size_t fst_id = label2id[label]; const Fst<Arc> *ifst = ifst_array[fst_id].second; for (StateIterator< Fst<Arc> > siter(*ifst); !siter.Done(); siter.Next()) { StateId is = siter.Value(); StateId os = ofst->AddState(); if (is == ifst->Start()) { fst_start[fst_id] = os; if (label == root) ofst->SetStart(os); } if (ifst->Final(is) != Weight::Zero()) { if (label == root) ofst->SetFinal(os, ifst->Final(is)); fst_final[fst_id].push_back(make_pair(os, ifst->Final(is))); } for (ArcIterator< Fst<Arc> > aiter(*ifst, is); !aiter.Done(); aiter.Next()) { Arc arc = aiter.Value(); arc.nextstate += soff; if (max_label == kNoLabel || arc.olabel > max_label) max_label = arc.olabel; typename unordered_map<Label, size_t>::const_iterator it = label2id.find(arc.olabel); if (it != label2id.end()) { size_t nfst_id = it->second; if (ifst_array[nfst_id].second->Start() == kNoStateId) continue; if (arc.olabel != root && nparens[nfst_id] == 0) non_term_queue.push_back(arc.olabel); pair<size_t, StateId> paren_key(nfst_id, arc.nextstate); typename ParenMap::const_iterator pit = paren_map.find(paren_key); if (pit == paren_map.end()) { paren_map[paren_key] = nparens[nfst_id]++; if (nparens[nfst_id] > total_nparens) total_nparens = nparens[nfst_id]; } } ofst->AddArc(os, arc); } } } // Assigns parenthesis labels for (size_t paren_id = 0; paren_id < total_nparens; ++paren_id) { Label open_paren = max_label + paren_id + 1; Label close_paren = open_paren + total_nparens; parens->push_back(make_pair(open_paren, close_paren)); } // Changes each non-terminal transition to an open parenthesis // transition redirected to the PDT state that corresponds to the // start state of the input FST for the non-terminal. Adds close parenthesis // transitions from the PDT states corr. to the final states of the // input FST for the non-terminal to the former destination state of the // non-terminal transition. typedef MutableArcIterator< MutableFst<Arc> > MIter; for (StateIterator< Fst<Arc> > siter(*ofst); !siter.Done(); siter.Next()) { StateId os = siter.Value(); MIter *aiter = new MIter(ofst, os); for (size_t n = 0; !aiter->Done(); aiter->Next(), ++n) { Arc arc = aiter->Value(); typename unordered_map<Label, size_t>::const_iterator lit = label2id.find(arc.olabel); if (lit != label2id.end()) { size_t nfst_id = lit->second; // Get parentheses. pair<size_t, StateId> paren_key(nfst_id, arc.nextstate); typename ParenMap::const_iterator pit = paren_map.find(paren_key); size_t paren_id = pit->second; Label open_paren = (*parens)[paren_id].first; Label close_paren = (*parens)[paren_id].second; // Sets open parenthesis. Arc sarc(open_paren, open_paren, arc.weight, fst_start[nfst_id]); aiter->SetValue(sarc); // Adds close parentheses. for (size_t i = 0; i < fst_final[nfst_id].size(); ++i) { pair<StateId, Weight> &p = fst_final[nfst_id][i]; Arc farc(close_paren, close_paren, p.second, arc.nextstate); ofst->AddArc(p.first, farc); if (os == p.first) { // Invalidated iterator delete aiter; aiter = new MIter(ofst, os); aiter->Seek(n); } } } } delete aiter; } } } // namespace fst #endif // FST_EXTENSIONS_PDT_REPLACE_H__ <|start_filename|>third_party/openfst/src/include/fst/synchronize.h<|end_filename|> // synchronize.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Synchronize an FST with bounded delay. #ifndef FST_LIB_SYNCHRONIZE_H__ #define FST_LIB_SYNCHRONIZE_H__ #include <algorithm> #include <unordered_map> using std::unordered_map; using std::unordered_multimap; #include <unordered_set> using std::unordered_set; using std::unordered_multiset; #include <string> #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/cache.h> #include <fst/test-properties.h> namespace fst { typedef CacheOptions SynchronizeFstOptions; // Implementation class for SynchronizeFst template <class A> class SynchronizeFstImpl : public CacheImpl<A> { public: using FstImpl<A>::SetType; using FstImpl<A>::SetProperties; using FstImpl<A>::SetInputSymbols; using FstImpl<A>::SetOutputSymbols; using CacheBaseImpl< CacheState<A> >::PushArc; using CacheBaseImpl< CacheState<A> >::HasArcs; using CacheBaseImpl< CacheState<A> >::HasFinal; using CacheBaseImpl< CacheState<A> >::HasStart; using CacheBaseImpl< CacheState<A> >::SetArcs; using CacheBaseImpl< CacheState<A> >::SetFinal; using CacheBaseImpl< CacheState<A> >::SetStart; typedef A Arc; typedef typename A::Label Label; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef basic_string<Label> String; struct Element { Element() {} Element(StateId s, const String *i, const String *o) : state(s), istring(i), ostring(o) {} StateId state; // Input state Id const String *istring; // Residual input labels const String *ostring; // Residual output labels // Residual strings are represented by const pointers to // basic_string<Label> and are stored in a hash_set. The pointed // memory is owned by the hash_set string_set_. }; SynchronizeFstImpl(const Fst<A> &fst, const SynchronizeFstOptions &opts) : CacheImpl<A>(opts), fst_(fst.Copy()) { SetType("synchronize"); uint64 props = fst.Properties(kFstProperties, false); SetProperties(SynchronizeProperties(props), kCopyProperties); SetInputSymbols(fst.InputSymbols()); SetOutputSymbols(fst.OutputSymbols()); } SynchronizeFstImpl(const SynchronizeFstImpl &impl) : CacheImpl<A>(impl), fst_(impl.fst_->Copy(true)) { SetType("synchronize"); SetProperties(impl.Properties(), kCopyProperties); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); } ~SynchronizeFstImpl() { delete fst_; // Extract pointers from the hash set vector<const String*> strings; typename StringSet::iterator it = string_set_.begin(); for (; it != string_set_.end(); ++it) strings.push_back(*it); // Free the extracted pointers for (size_t i = 0; i < strings.size(); ++i) delete strings[i]; } StateId Start() { if (!HasStart()) { StateId s = fst_->Start(); if (s == kNoStateId) return kNoStateId; const String *empty = FindString(new String()); StateId start = FindState(Element(fst_->Start(), empty, empty)); SetStart(start); } return CacheImpl<A>::Start(); } Weight Final(StateId s) { if (!HasFinal(s)) { const Element &e = elements_[s]; Weight w = e.state == kNoStateId ? Weight::One() : fst_->Final(e.state); if ((w != Weight::Zero()) && (e.istring)->empty() && (e.ostring)->empty()) SetFinal(s, w); else SetFinal(s, Weight::Zero()); } return CacheImpl<A>::Final(s); } size_t NumArcs(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<A>::NumArcs(s); } size_t NumInputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<A>::NumInputEpsilons(s); } size_t NumOutputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<A>::NumOutputEpsilons(s); } uint64 Properties() const { return Properties(kFstProperties); } // Set error if found; return FST impl properties. uint64 Properties(uint64 mask) const { if ((mask & kError) && fst_->Properties(kError, false)) SetProperties(kError, kError); return FstImpl<Arc>::Properties(mask); } void InitArcIterator(StateId s, ArcIteratorData<A> *data) { if (!HasArcs(s)) Expand(s); CacheImpl<A>::InitArcIterator(s, data); } // Returns the first character of the string obtained by // concatenating s and l. Label Car(const String *s, Label l = 0) const { if (!s->empty()) return (*s)[0]; else return l; } // Computes the residual string obtained by removing the first // character in the concatenation of s and l. const String *Cdr(const String *s, Label l = 0) { String *r = new String(); for (int i = 1; i < s->size(); ++i) r->push_back((*s)[i]); if (l && !(s->empty())) r->push_back(l); return FindString(r); } // Computes the concatenation of s and l. const String *Concat(const String *s, Label l = 0) { String *r = new String(); for (int i = 0; i < s->size(); ++i) r->push_back((*s)[i]); if (l) r->push_back(l); return FindString(r); } // Tests if the concatenation of s and l is empty bool Empty(const String *s, Label l = 0) const { if (s->empty()) return l == 0; else return false; } // Finds the string pointed by s in the hash set. Transfers the // pointer ownership to the hash set. const String *FindString(const String *s) { typename StringSet::iterator it = string_set_.find(s); if (it != string_set_.end()) { delete s; return (*it); } else { string_set_.insert(s); return s; } } // Finds state corresponding to an element. Creates new state // if element not found. StateId FindState(const Element &e) { typename ElementMap::iterator eit = element_map_.find(e); if (eit != element_map_.end()) { return (*eit).second; } else { StateId s = elements_.size(); elements_.push_back(e); element_map_.insert(pair<const Element, StateId>(e, s)); return s; } } // Computes the outgoing transitions from a state, creating new destination // states as needed. void Expand(StateId s) { Element e = elements_[s]; if (e.state != kNoStateId) for (ArcIterator< Fst<A> > ait(*fst_, e.state); !ait.Done(); ait.Next()) { const A &arc = ait.Value(); if (!Empty(e.istring, arc.ilabel) && !Empty(e.ostring, arc.olabel)) { const String *istring = Cdr(e.istring, arc.ilabel); const String *ostring = Cdr(e.ostring, arc.olabel); StateId d = FindState(Element(arc.nextstate, istring, ostring)); PushArc(s, Arc(Car(e.istring, arc.ilabel), Car(e.ostring, arc.olabel), arc.weight, d)); } else { const String *istring = Concat(e.istring, arc.ilabel); const String *ostring = Concat(e.ostring, arc.olabel); StateId d = FindState(Element(arc.nextstate, istring, ostring)); PushArc(s, Arc(0 , 0, arc.weight, d)); } } Weight w = e.state == kNoStateId ? Weight::One() : fst_->Final(e.state); if ((w != Weight::Zero()) && ((e.istring)->size() + (e.ostring)->size() > 0)) { const String *istring = Cdr(e.istring); const String *ostring = Cdr(e.ostring); StateId d = FindState(Element(kNoStateId, istring, ostring)); PushArc(s, Arc(Car(e.istring), Car(e.ostring), w, d)); } SetArcs(s); } private: // Equality function for Elements, assume strings have been hashed. class ElementEqual { public: bool operator()(const Element &x, const Element &y) const { return x.state == y.state && x.istring == y.istring && x.ostring == y.ostring; } }; // Hash function for Elements to Fst states. class ElementKey { public: size_t operator()(const Element &x) const { size_t key = x.state; key = (key << 1) ^ (x.istring)->size(); for (size_t i = 0; i < (x.istring)->size(); ++i) key = (key << 1) ^ (*x.istring)[i]; key = (key << 1) ^ (x.ostring)->size(); for (size_t i = 0; i < (x.ostring)->size(); ++i) key = (key << 1) ^ (*x.ostring)[i]; return key; } }; // Equality function for strings class StringEqual { public: bool operator()(const String * const &x, const String * const &y) const { if (x->size() != y->size()) return false; for (size_t i = 0; i < x->size(); ++i) if ((*x)[i] != (*y)[i]) return false; return true; } }; // Hash function for set of strings class StringKey{ public: size_t operator()(const String * const & x) const { size_t key = x->size(); for (size_t i = 0; i < x->size(); ++i) key = (key << 1) ^ (*x)[i]; return key; } }; typedef unordered_map<Element, StateId, ElementKey, ElementEqual> ElementMap; typedef unordered_set<const String*, StringKey, StringEqual> StringSet; const Fst<A> *fst_; vector<Element> elements_; // mapping Fst state to Elements ElementMap element_map_; // mapping Elements to Fst state StringSet string_set_; void operator=(const SynchronizeFstImpl<A> &); // disallow }; // Synchronizes a transducer. This version is a delayed Fst. The // result will be an equivalent FST that has the property that during // the traversal of a path, the delay is either zero or strictly // increasing, where the delay is the difference between the number of // non-epsilon output labels and input labels along the path. // // For the algorithm to terminate, the input transducer must have // bounded delay, i.e., the delay of every cycle must be zero. // // Complexity: // - A has bounded delay: exponential // - A does not have bounded delay: does not terminate // // References: // - <NAME>. Edit-Distance of Weighted Automata: General // Definitions and Algorithms, International Journal of Computer // Science, 14(6): 957-982 (2003). // // This class attaches interface to implementation and handles // reference counting, delegating most methods to ImplToFst. template <class A> class SynchronizeFst : public ImplToFst< SynchronizeFstImpl<A> > { public: friend class ArcIterator< SynchronizeFst<A> >; friend class StateIterator< SynchronizeFst<A> >; typedef A Arc; typedef typename A::Weight Weight; typedef typename A::StateId StateId; typedef DefaultCacheStore<A> Store; typedef typename Store::State State; typedef SynchronizeFstImpl<A> Impl; SynchronizeFst(const Fst<A> &fst) : ImplToFst<Impl>(new Impl(fst, SynchronizeFstOptions())) {} SynchronizeFst(const Fst<A> &fst, const SynchronizeFstOptions &opts) : ImplToFst<Impl>(new Impl(fst, opts)) {} // See Fst<>::Copy() for doc. SynchronizeFst(const SynchronizeFst<A> &fst, bool safe = false) : ImplToFst<Impl>(fst, safe) {} // Get a copy of this SynchronizeFst. See Fst<>::Copy() for further doc. virtual SynchronizeFst<A> *Copy(bool safe = false) const { return new SynchronizeFst<A>(*this, safe); } virtual inline void InitStateIterator(StateIteratorData<A> *data) const; virtual void InitArcIterator(StateId s, ArcIteratorData<A> *data) const { GetImpl()->InitArcIterator(s, data); } private: // Makes visible to friends. Impl *GetImpl() const { return ImplToFst<Impl>::GetImpl(); } void operator=(const SynchronizeFst<A> &fst); // Disallow }; // Specialization for SynchronizeFst. template<class A> class StateIterator< SynchronizeFst<A> > : public CacheStateIterator< SynchronizeFst<A> > { public: explicit StateIterator(const SynchronizeFst<A> &fst) : CacheStateIterator< SynchronizeFst<A> >(fst, fst.GetImpl()) {} }; // Specialization for SynchronizeFst. template <class A> class ArcIterator< SynchronizeFst<A> > : public CacheArcIterator< SynchronizeFst<A> > { public: typedef typename A::StateId StateId; ArcIterator(const SynchronizeFst<A> &fst, StateId s) : CacheArcIterator< SynchronizeFst<A> >(fst.GetImpl(), s) { if (!fst.GetImpl()->HasArcs(s)) fst.GetImpl()->Expand(s); } private: DISALLOW_COPY_AND_ASSIGN(ArcIterator); }; template <class A> inline void SynchronizeFst<A>::InitStateIterator(StateIteratorData<A> *data) const { data->base = new StateIterator< SynchronizeFst<A> >(*this); } // Synchronizes a transducer. This version writes the synchronized // result to a MutableFst. The result will be an equivalent FST that // has the property that during the traversal of a path, the delay is // either zero or strictly increasing, where the delay is the // difference between the number of non-epsilon output labels and // input labels along the path. // // For the algorithm to terminate, the input transducer must have // bounded delay, i.e., the delay of every cycle must be zero. // // Complexity: // - A has bounded delay: exponential // - A does not have bounded delay: does not terminate // // References: // - <NAME>. Edit-Distance of Weighted Automata: General // Definitions and Algorithms, International Journal of Computer // Science, 14(6): 957-982 (2003). template<class Arc> void Synchronize(const Fst<Arc> &ifst, MutableFst<Arc> *ofst) { SynchronizeFstOptions opts; opts.gc_limit = 0; // Cache only the last state for fastest copy. *ofst = SynchronizeFst<Arc>(ifst, opts); } } // namespace fst #endif // FST_LIB_SYNCHRONIZE_H__ <|start_filename|>third_party/openfst/src/include/fst/extensions/far/farscript.h<|end_filename|> // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // Convenience file for including all of the FAR operations, // or registering them for new arc types. #ifndef FST_EXTENSIONS_FAR_FARSCRIPT_H_ #define FST_EXTENSIONS_FAR_FARSCRIPT_H_ #include <vector> using std::vector; #include <string> #include <fst/script/arg-packs.h> #include <fst/extensions/far/compile-strings.h> #include <fst/extensions/far/create.h> #include <fst/extensions/far/equal.h> #include <fst/extensions/far/extract.h> #include <fst/extensions/far/info.h> #include <fst/extensions/far/print-strings.h> #include <fst/extensions/far/far.h> #include <fst/types.h> namespace fst { namespace script { // Note: it is safe to pass these strings as references because // this struct is only used to pass them deeper in the call graph. // Be sure you understand why this is so before using this struct // for anything else! struct FarCompileStringsArgs { const vector<string> &in_fnames; const string &out_fname; const string &fst_type; const FarType &far_type; const int32 generate_keys; const FarEntryType fet; const FarTokenType tt; const string &symbols_fname; const string &unknown_symbol; const bool keep_symbols; const bool initial_symbols; const bool allow_negative_labels; const bool file_list_input; const string &key_prefix; const string &key_suffix; FarCompileStringsArgs(const vector<string> &in_fnames, const string &out_fname, const string &fst_type, const FarType &far_type, int32 generate_keys, FarEntryType fet, FarTokenType tt, const string &symbols_fname, const string &unknown_symbol, bool keep_symbols, bool initial_symbols, bool allow_negative_labels, bool file_list_input, const string &key_prefix, const string &key_suffix) : in_fnames(in_fnames), out_fname(out_fname), fst_type(fst_type), far_type(far_type), generate_keys(generate_keys), fet(fet), tt(tt), symbols_fname(symbols_fname), unknown_symbol(unknown_symbol), keep_symbols(keep_symbols), initial_symbols(initial_symbols), allow_negative_labels(allow_negative_labels), file_list_input(file_list_input), key_prefix(key_prefix), key_suffix(key_suffix) { } }; template <class Arc> void FarCompileStrings(FarCompileStringsArgs *args) { fst::FarCompileStrings<Arc>( args->in_fnames, args->out_fname, args->fst_type, args->far_type, args->generate_keys, args->fet, args->tt, args->symbols_fname, args->unknown_symbol, args->keep_symbols, args->initial_symbols, args->allow_negative_labels, args->file_list_input, args->key_prefix, args->key_suffix); } void FarCompileStrings( const vector<string> &in_fnames, const string &out_fname, const string &arc_type, const string &fst_type, const FarType &far_type, int32 generate_keys, FarEntryType fet, FarTokenType tt, const string &symbols_fname, const string &unknown_symbol, bool keep_symbols, bool initial_symbols, bool allow_negative_labels, bool file_list_input, const string &key_prefix, const string &key_suffix); // Note: it is safe to pass these strings as references because // this struct is only used to pass them deeper in the call graph. // Be sure you understand why this is so before using this struct // for anything else! struct FarCreateArgs { const vector<string> &in_fnames; const string &out_fname; const int32 generate_keys; const bool file_list_input; const FarType &far_type; const string &key_prefix; const string &key_suffix; FarCreateArgs( const vector<string> &in_fnames, const string &out_fname, const int32 generate_keys, const bool file_list_input, const FarType &far_type, const string &key_prefix, const string &key_suffix) : in_fnames(in_fnames), out_fname(out_fname), generate_keys(generate_keys), file_list_input(file_list_input), far_type(far_type), key_prefix(key_prefix), key_suffix(key_suffix) { } }; template<class Arc> void FarCreate(FarCreateArgs *args) { fst::FarCreate<Arc>(args->in_fnames, args->out_fname, args->generate_keys, args->file_list_input, args->far_type, args->key_prefix, args->key_suffix); } void FarCreate(const vector<string> &in_fnames, const string &out_fname, const string &arc_type, const int32 generate_keys, const bool file_list_input, const FarType &far_type, const string &key_prefix, const string &key_suffix); typedef args::Package<const string &, const string &, float, const string &, const string &> FarEqualInnerArgs; typedef args::WithReturnValue<bool, FarEqualInnerArgs> FarEqualArgs; template <class Arc> void FarEqual(FarEqualArgs *args) { args->retval = fst::FarEqual<Arc>( args->args.arg1, args->args.arg2, args->args.arg3, args->args.arg4, args->args.arg5); } bool FarEqual(const string &filename1, const string &filename2, const string &arc_type, float delta = kDelta, const string &begin_key = string(), const string &end_key = string()); typedef args::Package<const vector<string> &, int32, const string&, const string&, const string&, const string&, const string&> FarExtractArgs; template<class Arc> void FarExtract(FarExtractArgs *args) { fst::FarExtract<Arc>( args->arg1, args->arg2, args->arg3, args->arg4, args->arg5, args->arg6, args->arg7); } void FarExtract(const vector<string> &ifilenames, const string &arc_type, int32 generate_filenames, const string &keys, const string &key_separator, const string &range_delimiter, const string &filename_prefix, const string &filename_suffix); typedef args::Package<const vector<string> &, const string &, const string &, const bool> FarInfoArgs; template <class Arc> void FarInfo(FarInfoArgs *args) { fst::FarInfo<Arc>(args->arg1, args->arg2, args->arg3, args->arg4); } void FarInfo(const vector<string> &filenames, const string &arc_type, const string &begin_key, const string &end_key, const bool list_fsts); struct FarPrintStringsArgs { const vector<string> &ifilenames; const FarEntryType entry_type; const FarTokenType token_type; const string &begin_key; const string &end_key; const bool print_key; const bool print_weight; const string &symbols_fname; const bool initial_symbols; const int32 generate_filenames; const string &filename_prefix; const string &filename_suffix; FarPrintStringsArgs( const vector<string> &ifilenames, const FarEntryType entry_type, const FarTokenType token_type, const string &begin_key, const string &end_key, const bool print_key, const bool print_weight, const string &symbols_fname, const bool initial_symbols, const int32 generate_filenames, const string &filename_prefix, const string &filename_suffix) : ifilenames(ifilenames), entry_type(entry_type), token_type(token_type), begin_key(begin_key), end_key(end_key), print_key(print_key), print_weight(print_weight), symbols_fname(symbols_fname), initial_symbols(initial_symbols), generate_filenames(generate_filenames), filename_prefix(filename_prefix), filename_suffix(filename_suffix) { } }; template <class Arc> void FarPrintStrings(FarPrintStringsArgs *args) { fst::FarPrintStrings<Arc>( args->ifilenames, args->entry_type, args->token_type, args->begin_key, args->end_key, args->print_key, args->print_weight, args->symbols_fname, args->initial_symbols, args->generate_filenames, args->filename_prefix, args->filename_suffix); } void FarPrintStrings(const vector<string> &ifilenames, const string &arc_type, const FarEntryType entry_type, const FarTokenType token_type, const string &begin_key, const string &end_key, const bool print_key, const bool print_weight, const string &symbols_fname, const bool initial_symbols, const int32 generate_filenames, const string &filename_prefix, const string &filename_suffix); } // namespace script } // namespace fst #define REGISTER_FST_FAR_OPERATIONS(ArcType) \ REGISTER_FST_OPERATION(FarCompileStrings, ArcType, FarCompileStringsArgs); \ REGISTER_FST_OPERATION(FarCreate, ArcType, FarCreateArgs); \ REGISTER_FST_OPERATION(FarEqual, ArcType, FarEqualArgs); \ REGISTER_FST_OPERATION(FarExtract, ArcType, FarExtractArgs); \ REGISTER_FST_OPERATION(FarInfo, ArcType, FarInfoArgs); \ REGISTER_FST_OPERATION(FarPrintStrings, ArcType, FarPrintStringsArgs) #endif // FST_EXTENSIONS_FAR_FARSCRIPT_H_ <|start_filename|>third_party/openfst/src/include/fst/reverse.h<|end_filename|> // reverse.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Functions and classes to sort arcs in an FST. #ifndef FST_LIB_REVERSE_H__ #define FST_LIB_REVERSE_H__ #include <algorithm> #include <vector> using std::vector; #include <fst/cache.h> namespace fst { // Reverses an FST. The reversed result is written to an output // MutableFst. If A transduces string x to y with weight a, then the // reverse of A transduces the reverse of x to the reverse of y with // weight a.Reverse(). // // Typically, a = a.Reverse() and Arc = RevArc (e.g. for // TropicalWeight or LogWeight). In general, e.g. when the weights // only form a left or right semiring, the output arc type must match // the input arc type except having the reversed Weight type. // // When 'require_superinitial == false', a superinitial state is // *not* created in the reversed Fst iff the input Fst has exactly // 1 final state (which becomes the initial state of the reversed Fst) // that has a final weight of Weight::One() *or* does not belong to // any cycle. // When 'require_superinitial == true', a superinitial state is // always created. template<class Arc, class RevArc> void Reverse(const Fst<Arc> &ifst, MutableFst<RevArc> *ofst, bool require_superinitial = true) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef typename RevArc::Weight RevWeight; ofst->DeleteStates(); ofst->SetInputSymbols(ifst.InputSymbols()); ofst->SetOutputSymbols(ifst.OutputSymbols()); if (ifst.Properties(kExpanded, false)) ofst->ReserveStates(CountStates(ifst) + 1); StateId istart = ifst.Start(); StateId ostart = kNoStateId; StateId offset = 0; uint64 dfs_iprops = 0, dfs_oprops = 0; if (!require_superinitial) { for (StateIterator<Fst<Arc> > siter(ifst); !siter.Done(); siter.Next()) { StateId is = siter.Value(); if (ifst.Final(is) == Weight::Zero()) continue; if (ostart != kNoStateId) { ostart = kNoStateId; break; } else { ostart = is; } } if (ostart != kNoStateId && ifst.Final(ostart) != Weight::One()) { vector<StateId> scc; SccVisitor<Arc> scc_visitor(&scc, 0, 0, &dfs_iprops); DfsVisit(ifst, &scc_visitor); if (count(scc.begin(), scc.end(), scc[ostart]) > 1) { ostart = kNoStateId; } else { for (ArcIterator<Fst<Arc> > aiter(ifst, ostart); !aiter.Done(); aiter.Next()) { if (aiter.Value().nextstate == ostart) { ostart = kNoStateId; break; } } } if (ostart != kNoStateId) dfs_oprops = kInitialAcyclic; } } if (ostart == kNoStateId) { // Super-initial requested or needed. ostart = ofst->AddState(); offset = 1; } for (StateIterator<Fst<Arc> > siter(ifst); !siter.Done(); siter.Next()) { StateId is = siter.Value(); StateId os = is + offset; while (ofst->NumStates() <= os) ofst->AddState(); if (is == istart) ofst->SetFinal(os, RevWeight::One()); Weight final = ifst.Final(is); if ((final != Weight::Zero()) && (offset == 1)) { RevArc oarc(0, 0, final.Reverse(), os); ofst->AddArc(0, oarc); } for (ArcIterator<Fst<Arc> > aiter(ifst, is); !aiter.Done(); aiter.Next()) { const Arc &iarc = aiter.Value(); StateId nos = iarc.nextstate + offset; typename RevArc::Weight weight = iarc.weight.Reverse(); if (!offset && (nos == ostart)) weight = Times(ifst.Final(ostart).Reverse(), weight); RevArc oarc(iarc.ilabel, iarc.olabel, weight, os); while (ofst->NumStates() <= nos) ofst->AddState(); ofst->AddArc(nos, oarc); } } ofst->SetStart(ostart); if (offset == 0 && ostart == istart) ofst->SetFinal(ostart, ifst.Final(ostart).Reverse()); uint64 iprops = ifst.Properties(kCopyProperties, false) | dfs_iprops; uint64 oprops = ofst->Properties(kFstProperties, false) | dfs_oprops; ofst->SetProperties(ReverseProperties(iprops, offset == 1) | oprops, kFstProperties); } } // namespace fst #endif // FST_LIB_REVERSE_H__ <|start_filename|>third_party/openfst/src/include/fst/statesort.h<|end_filename|> // statesort.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Function to sort states of an Fst. #ifndef FST_LIB_STATESORT_H__ #define FST_LIB_STATESORT_H__ #include <vector> using std::vector; #include <algorithm> #include <fst/mutable-fst.h> namespace fst { // Sorts the input states of an FST, modifying it. ORDER[i] gives the // the state Id after sorting that corresponds to state Id i before // sorting. ORDER must be a permutation of FST's states ID sequence: // (0, 1, 2, ..., fst->NumStates() - 1). template <class Arc> void StateSort(MutableFst<Arc> *fst, const vector<typename Arc::StateId> &order) { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; if (order.size() != fst->NumStates()) { FSTERROR() << "StateSort: bad order vector size: " << order.size(); fst->SetProperties(kError, kError); return; } if (fst->Start() == kNoStateId) return; uint64 props = fst->Properties(kStateSortProperties, false); vector<bool> done(order.size(), false); vector<Arc> arcsa, arcsb; vector<Arc> *arcs1 = &arcsa, *arcs2 = &arcsb; fst->SetStart(order[fst->Start()]); for (StateIterator< MutableFst<Arc> > siter(*fst); !siter.Done(); siter.Next()) { StateId s1 = siter.Value(), s2; if (done[s1]) continue; Weight final1 = fst->Final(s1), final2 = Weight::Zero(); arcs1->clear(); for (ArcIterator< MutableFst<Arc> > aiter(*fst, s1); !aiter.Done(); aiter.Next()) arcs1->push_back(aiter.Value()); for (; !done[s1]; s1 = s2, final1 = final2, swap(arcs1, arcs2)) { s2 = order[s1]; if (!done[s2]) { final2 = fst->Final(s2); arcs2->clear(); for (ArcIterator< MutableFst<Arc> > aiter(*fst, s2); !aiter.Done(); aiter.Next()) arcs2->push_back(aiter.Value()); } fst->SetFinal(s2, final1); fst->DeleteArcs(s2); for (size_t i = 0; i < arcs1->size(); ++i) { Arc arc = (*arcs1)[i]; arc.nextstate = order[arc.nextstate]; fst->AddArc(s2, arc); } done[s1] = true; } } fst->SetProperties(props, kFstProperties); } } // namespace fst #endif // FST_LIB_STATESORT_H__ <|start_filename|>third_party/openfst/src/include/fst/topsort.h<|end_filename|> // topsort.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: <EMAIL> (<NAME>) // // \file // Topological sort of FSTs #ifndef FST_LIB_TOPSORT_H__ #define FST_LIB_TOPSORT_H__ #include <algorithm> #include <vector> using std::vector; #include <fst/dfs-visit.h> #include <fst/fst.h> #include <fst/statesort.h> namespace fst { // DFS visitor class to return topological ordering. template <class A> class TopOrderVisitor { public: typedef A Arc; typedef typename A::StateId StateId; // If acyclic, ORDER[i] gives the topological position of state Id i; // otherwise unchanged. ACYCLIC will be true iff the FST has // no cycles. TopOrderVisitor(vector<StateId> *order, bool *acyclic) : order_(order), acyclic_(acyclic) {} void InitVisit(const Fst<A> &fst) { finish_ = new vector<StateId>; *acyclic_ = true; } bool InitState(StateId s, StateId r) { return true; } bool TreeArc(StateId s, const A &arc) { return true; } bool BackArc(StateId s, const A &arc) { return (*acyclic_ = false); } bool ForwardOrCrossArc(StateId s, const A &arc) { return true; } void FinishState(StateId s, StateId p, const A *) { finish_->push_back(s); } void FinishVisit() { if (*acyclic_) { order_->clear(); for (StateId s = 0; s < finish_->size(); ++s) order_->push_back(kNoStateId); for (StateId s = 0; s < finish_->size(); ++s) (*order_)[(*finish_)[finish_->size() - s - 1]] = s; } delete finish_; } private: vector<StateId> *order_; bool *acyclic_; vector<StateId> *finish_; // states in finishing-time order }; // Topologically sorts its input if acyclic, modifying it. Otherwise, // the input is unchanged. When sorted, all transitions are from // lower to higher state IDs. // // Complexity: // - Time: O(V + E) // - Space: O(V + E) // where V = # of states and E = # of arcs. template <class Arc> bool TopSort(MutableFst<Arc> *fst) { typedef typename Arc::StateId StateId; vector<StateId> order; bool acyclic; TopOrderVisitor<Arc> top_order_visitor(&order, &acyclic); DfsVisit(*fst, &top_order_visitor); if (acyclic) { StateSort(fst, order); fst->SetProperties(kAcyclic | kInitialAcyclic | kTopSorted, kAcyclic | kInitialAcyclic | kTopSorted); } else { fst->SetProperties(kCyclic | kNotTopSorted, kCyclic | kNotTopSorted); } return acyclic; } } // namespace fst #endif // FST_LIB_TOPSORT_H__
hellais/marionette
<|start_filename|>feature-queries/step2.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Feature Queries: step 2</title> <link rel="stylesheet" href="../learn/styles.css"> <style> * { box-sizing: border-box; } .wrapper { overflow: auto; } </style> <style class="editable"> .box { float: left; width: 33%; border: 2px solid rgb(95, 97, 110); border-radius: .5em; padding: 20px; } .wrapper { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; } </style> </head> <body> <section class="preview"> <div class="wrapper"> <div class="box"> Box 1 <br>Has more content <br>than the other boxes. </div> <div class="box"> Box 2 </div> <div class="box"> Box 3 </div> </div> </section> <textarea class="playable playable-css" style="height: 260px;"> .box { float: left; width: 33%; border: 2px solid rgb(95, 97, 110); border-radius: .5em; padding: 20px; } .wrapper { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; } </textarea> <textarea class="playable playable-html" style="height: 240px;"> <div class="wrapper"> <div class="box"> Box 1 <br>Has more content <br>than the other boxes. </div> <div class="box"> Box 2 </div> <div class="box"> Box 3 </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../learn/playable.js"></script> </html> <|start_filename|>logical/padding-longhands.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Padding Longhands</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .container { display: flex; } .box { border: 2px solid rgb(96, 139, 168); border-radius: 5px; background-color: rgba(96, 139, 168, .2); margin: 10px; width: 220px; height:220px; } </style> <style class="editable"> .box { writing-mode: horizontal-tb; direction: ltr; } .physical { padding-top: 5px; padding-right: 0; padding-bottom: 2em; padding-left: 50px; } .logical { padding-block-start: 5px; padding-inline-end: 0; padding-block-end: 2em; padding-inline-start: 50px; } </style> </head> <body> <section class="preview"> <div class="container"> <div class="physical box"> padding-top: 5px<br> padding-right: 0<br> padding-bottom: 2em<br> padding-left: 50px </div> <div class="logical box"> padding-block-start: 5px<br> padding-inline-end: 0<br> padding-block-end: 2em<br> padding-inline-start: 50px </div> </div> </section> <textarea class="playable playable-css" style="height: 320px;"> .box { writing-mode: horizontal-tb; direction: ltr; } .physical { padding-top: 5px; padding-right: 0; padding-bottom: 2em; padding-left: 50px; } .logical { padding-block-start: 5px; padding-inline-end: 0; padding-block-end: 2em; padding-inline-start: 50px; }</textarea> <textarea class="playable playable-html" style="height: 340px;"> <div class="container"> <div class="physical box"> padding-top: 5px<br> padding-right: 0<br> padding-bottom: 2em<br> padding-left: 50px </div> <div class="logical box"> padding-block-start: 5px<br> padding-inline-end: 0<br> padding-block-end: 2em<br> padding-inline-start: 50px </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>learn/tasks/flexbox/flexbox2.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Flexbox: task 2</title> <link rel="stylesheet" href="../styles.css"> <style> ul { max-width: 700px; list-style:none; padding: 0; margin: 0; } li { background-color: #4D7298; border: 2px solid #77A6B6; border-radius: .5em; color: #fff; padding: .5em; } </style> <style class="editable"> ul { } li { } </style> </head> <body> <section class="preview"> <ul> <li>I am small</li> <li>I have more content than the very small item.</li> <li>I have lots of content. So much content that I don't know where it is all going to go. I'm glad that CSS is pretty good at dealing with situations where we end up with more words than expected!</li> </ul> </section> <textarea class="playable playable-css" style="height: 150px;"> ul { } li { } </textarea> <textarea class="playable playable-html"> <ul> <li>I am small</li> <li>I have more content than the very small item.</li> <li>I have lots of content. So much content that I don't know where it is all going to go. I'm glad that CSS is pretty good at dealing with situations where we end up with more words than expected!</li> </ul> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/rwd/liquid-width.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>A liquid layout</title> <style> body { font: 1.2em Helvetica, Arial, sans-serif; margin: 20px; padding: 0; background-color: #eee; } .wrapper { width: 90%; margin: 2em auto; } .col1 { width: 25%; float: left; background-color: #fff; } .col2 { width: 70%; float: right; background-color: #fff; } </style> </head> <body> <div class="wrapper"> <div class="col1"> <p>This layout is liquid. See what happens if you make the browser window wider or narrow.</p> </div> <div class="col2"> <p>One November night in the year 1782, so the story runs, two brothers sat over their winter fire in the little French town of Annonay, watching the grey smoke-wreaths from the hearth curl up the wide chimney. Their names were Stephen and <NAME>, they were papermakers by trade, and were noted as possessing thoughtful minds and a deep interest in all scientific knowledge and new discovery.</p> <p>Before that night—a memorable night, as it was to prove—hundreds of millions of people had watched the rising smoke-wreaths of their fires without drawing any special inspiration from the fact.”</p> </div> </div> </body> </html> <|start_filename|>editable-samples/css/editable-old.css<|end_filename|> body { background-color: #EAEFF2; padding: 0; margin: 0; } #buttons { margin: 0.5em; } #output { width: 100%; height: 200px; background-color: white; padding: 1em; box-sizing: border-box; } <|start_filename|>overscroll-behavior/main.js<|end_filename|> // Generate fake contacts let mainElem = document.querySelector('main'); for(var i = 1; i < 51; i++) { let divElem = document.createElement('div'); let pElem = document.createElement('p'); pElem.textContent = 'Contact ' + i; mainElem.appendChild(divElem); divElem.appendChild(pElem); } // Allow submission of chat messages let form = document.querySelector('form'); let input = document.querySelector('input'); let messages = document.querySelector('.messages'); messages.scrollTop = messages.scrollHeight; form.addEventListener('submit', e => { e.preventDefault(); if(input.value !== '') { let pElem = document.createElement('p'); pElem.setAttribute('class', 'me'); pElem.textContent = 'Chris: ' + input.value; messages.appendChild(pElem); messages.scrollTop = messages.scrollHeight; input.value = ''; input.focus(); } }); <|start_filename|>editable-samples-2/css/editable.css<|end_filename|> * { box-sizing: border-box; } body { background-color: #EAEFF2; padding: 0; margin: 0; } #output { width: 100%; height: 200px; background-color: white; padding: 1em 0; box-shadow: 0px 2px 5px -2px rgba(0,0,0,0.1); } #example-element { max-width: 80%; max-height: 80%; display: block; margin: 0 auto 0 auto; } #output { overflow: hidden; } #example-element { display: block; color: #C13832; } .example-choice { font-size: 14px; transition: background-color .2s ease-out; cursor: pointer; padding: 0.25em; display: inline-block; width: 100%; position: relative; } .example-choice:hover { background-color: whitesmoke; } .example-choice.selected { background-color: white; transition: background-color .2s ease-in; box-shadow: inset 0px 2px 2px -2px rgba(0,0,0,0.2); cursor: text; } .example-choice>code { width: 90%; display: inline-block; } .reset { display: none; position: absolute; top: .75em; right: 1em; } .example-choice.selected>.reset { display: unset; } .error { max-height: 1em; position: absolute; top: .75em; right: 5.5em; cursor: pointer; } .hidden { display: none; } [contenteditable]:focus { outline: 0px solid transparent; } /* Disable responsive mode, as it doesn't work properly inside an iframe @media (min-width: 800px) { #example-choice-list, #output { float: left; } #example-choice-list { width: 70%; } #output { width: 30%; } } */ <|start_filename|>editable-samples/js/editable.js<|end_filename|> var element = document.getElementById("example-element"); var input = document.getElementById("input"); var editor = document.getElementById("editor"); var editorContent = document.getElementById("editor-content"); var reset = document.getElementById("reset"); var cmOptions = { mode: "css", theme: "eclipse", lineNumbers: true, showCursorWhenSelecting: true } var cmEditor = CodeMirror.fromTextArea(editorContent, cmOptions); cmEditor.setSize("100%", 50); cmEditor.focus(); cmEditor.doc.setCursor({line:0, pos: -1}); function applyCode() { element.style.cssText = cmEditor.doc.getValue(); } reset.addEventListener("click", function() { cmEditor.doc.setValue(cmInitContent); applyCode(); reset.classList.add("hidden"); }); cmEditor.on("change", function() { reset.classList.remove("hidden"); applyCode(); }); window.addEventListener("load", function() { applyCode(); }); <|start_filename|>editable-samples/pages/border-top-color/css/element.css<|end_filename|> #example-element { border: solid 0.3em gold; } <|start_filename|>logical/border-longhands.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Border Properties</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .container { display: flex; } .box { border-radius: 5px; background-color: rgba(96, 139, 168, .2); margin: 10px; width: 220px; height:220px; } </style> <style class="editable"> .box { writing-mode: horizontal-tb; direction: ltr; } .physical { border-top: 2px solid hotpink; border-right-style: dotted; border-right-color: goldenrod; border-right-width: 5px; border-bottom: 4px double black; border-left: none; } .logical { border-block-start: 2px solid hotpink; border-inline-end-style: dotted; border-inline-end-color: goldenrod; border-inline-end-width: 5px; border-block-end: 4px double black; border-inline-start: none; } </style> </head> <body> <section class="preview"> <div class="container"> <div class="physical box"> Borders use physical properties. </div> <div class="logical box"> Borders use logical properties. </div> </div> </section> <textarea class="playable playable-css" style="height: 30px;"> .box { writing-mode: horizontal-tb; direction: ltr; } .physical { border-top: 2px solid hotpink; border-right-style: dotted; border-right-color: goldenrod; border-right-width: 5px; border-bottom: 4px double black; border-left: none; } .logical { border-block-start: 2px solid hotpink; border-inline-end-style: dotted; border-inline-end-color: goldenrod; border-inline-end-width: 5px; border-block-end: 4px double black; border-inline-start: none; }</textarea> <textarea class="playable playable-html" style="height: 180px;"> <div class="container"> <div class="physical box"> Borders use physical properties. </div> <div class="logical box"> Borders use logical properties. </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>editable-samples/pages/font/css/element.css<|end_filename|> #output { overflow: hidden; } #example-element { display: block; color: #C13832; } <|start_filename|>editable-samples/pages/border-top-color/js/border-top-color.js<|end_filename|> var cmInitContent = 'border-top-color: red;\n\n'; <|start_filename|>learn/cascade/inheritance-simple.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Inheritance: simple example</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> body { color: blue; } span { color: black; } </style> </head> <body> <section class="preview"> <p>As the body has been set to have a color of blue this is inherited through the descendants.</p> <p>We can change the color by targetting the element with a selector, such as this <span>span</span>.</p> </section> <textarea class="playable playable-css" style="height: 140px;"> body { color: blue; } span { color: black; } </textarea> <textarea class="playable playable-html" style="height: 100px;"> <p>As the body has been set to have a color of blue this is inherited through the descendants.</p> <p>We can change the color by targetting the element with a selector, such as this <span>span</span>.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>is-where/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>:is() and :where(), examples and differences</title> <style> html { font-family: sans-serif; font-size: 200%; } :is(section.is-styling, aside.is-styling, footer.is-styling) a { color: red; } :where(section.where-styling, aside.where-styling, footer.where-styling) a { color: orange; } footer a { color: blue; } </style> </head> <body> <article> <h2>:is()-styled links</h2> <section class="is-styling"> <p>Here is my main content. This <a href="https://mozilla.org">contains a link</a>. </section> <aside class="is-styling"> <p>Here is my aside content. This <a href="https://developer.mozilla.org">also contains a link</a>. </aside> <footer class="is-styling"> <p>This is my footer, also containing <a href="https://github.com/mdn">a link</a>. </footer> </article> <article> <h2>:where()-styled links</h2> <section class="where-styling"> <p>Here is my main content. This <a href="https://mozilla.org">contains a link</a>. </section> <aside class="where-styling"> <p>Here is my aside content. This <a href="https://developer.mozilla.org">also contains a link</a>. </aside> <footer class="where-styling"> <p>This is my footer, also containing <a href="https://github.com/mdn">a link</a>. </footer> </article> </body> </html> <|start_filename|>learn/tasks/multicol/multicol1.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Multiple-column Layout: Task 1</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } </style> <style class="editable"> .container { } </style> </head> <body> <section class="preview"> <div class="container"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. </p> </div> </section> <textarea class="playable playable-css" style="height: 120px;"> .container { } </textarea> <textarea class="playable playable-html" style="height: 130px;"> <div class="container"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. </p> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/cascade/important.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>!important</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> #winning { background-color: red; border: 1px solid black; } .better { background-color: gray; border: none !important; } p { background-color: blue; color: white; padding: 5px; } </style> </head> <body> <section class="preview"> <p class="better">This is a paragraph.</p> <p class="better" id="winning">One selector to rule them all!</p> </section> <textarea class="playable playable-css" style="height: 280px;"> #winning { background-color: red; border: 1px solid black; } .better { background-color: gray; border: none !important; } p { background-color: blue; color: white; padding: 5px; } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <p class="better">This is a paragraph.</p> <p class="better" id="winning">One selector to rule them all!</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/tasks/sizing/height-min-height.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sizing Task 1: height and min-height</title> <link rel="stylesheet" href="../styles.css" /> <style> .box { border: 5px solid #000; width: 400px; margin-bottom: 1em; } .preview { min-height: 400px; } </style> <style class="editable"> .box1 { } .box2 { } </style> </head> <body> <section class="preview"> <div class="box box1"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. </p> </div> <div class="box box2"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. </p> </div> </section> <textarea class="playable playable-css" style="height: 180px;"> .box1 { } .box2 { } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <div class="box box1"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. </p> </div> <div class="box box2"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. </p> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/getting-started/biog.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Formatting a biography</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> body { font-family: Arial, Helvetica, sans-serif; } h1 { color: #375e97; font-size: 2em; font-family: Georgia, 'Times New Roman', Times, serif; border-bottom: 1px solid #375e97; } h2 { font-size: 1.5em; } .job-title { color: #999999; font-weight: bold; } a:link, a:visited { color: #fb6542; } a:hover { text-decoration: none; } </style> </head> <body> <section class="preview"> <h1><NAME></h1> <div class="job-title">Web Developer</div> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.</p> <p>A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. </p> <h2>Contact information</h2> <ul> <li>Email: <a href="mailto:<EMAIL>"><EMAIL></a></li> <li>Web: <a href="http://example.com">http://example.com</a></li> <li>Tel: 123 45678</li> </ul> </section> <textarea class="playable playable-css" style="height: 500px;"> body { font-family: Arial, Helvetica, sans-serif; } h1 { color: #375e97; font-size: 2em; font-family: Georgia, 'Times New Roman', Times, serif; border-bottom: 1px solid #375e97; } h2 { font-size: 1.5em; } .job-title { color: #999999; font-weight: bold; } a:link, a:visited { color: #fb6542; } a:hover { text-decoration: none; } </textarea> <textarea class="playable playable-html" style="height: 300px;"> <h1><NAME></h1> <div class="job-title">Web Developer</div> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.</p> <p>A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. </p> <h2>Contact information</h2> <ul> <li>Email: <a href="mailto:<EMAIL>"><EMAIL></a></li> <li>Web: <a href="http://example.com">http://example.com</a></li> <li>Tel: 123 45678</li> </ul> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/box-model/inline.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Box Model: Inline</title> <link rel="stylesheet" href="../styles.css" /> <style></style> <style class="editable"> p, ul { border: 2px solid rebeccapurple; } span, li { border: 2px solid blue; } ul { display: inline-flex; list-style: none; padding: 0; } .inline { display: inline; } </style> </head> <body> <section class="preview"> <p> I am a paragraph. Some of the <span>words</span> have been wrapped in a <span>span element</span>. </p> <ul> <li>Item One</li> <li>Item Two</li> <li>Item Three</li> </ul> <p class="inline">I am a paragraph. A short one.</p> <p class="inline">I am another paragraph. Also a short one.</p> </section> <textarea class="playable playable-css" style="height: 380px;"> p, ul { border: 2px solid rebeccapurple; } span, li { border: 2px solid blue; } ul { display: inline-flex; list-style: none; padding: 0; } .inline { display: inline; } </textarea> <textarea class="playable playable-html" style="height: 280px;"> <p> I am a paragraph. Some of the <span>words</span> have been wrapped in a <span>span element</span>. </p> <ul> <li>Item One</li> <li>Item Two</li> <li>Item Three</li> </ul> <p class="inline">I am a paragraph. A short one.</p> <p class="inline">I am another paragraph. Also a short one.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/tasks/box-model/inline-block.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Box Model Task 3: Inline Block</title> <link rel="stylesheet" href="../styles.css" /> <style></style> <style class="editable"> .box span { background-color: pink; border: 5px solid black; padding: 1em; } </style> </head> <body> <section class="preview"> <div class="box"> <p>Veggies es bonus vobis, <span>proinde vos postulo</span> essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </div> </section> <textarea class="playable playable-css" style="height: 280px;"> .box span { background-color: pink; border: 5px solid black; padding: 1em; } </textarea> <textarea class="playable playable-html" style="height: 80px;"> <div class="box"> <p>Veggies es bonus vobis, <span>proinde vos postulo</span> essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/values-units/em-rem.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Values and Units: ems and rems</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } </style> <style class="editable"> html { font-size: 16px; } .ems li { font-size: 1.3em; } .rems li { font-size: 1.3rem; } </style> </head> <body> <section class="preview"> <ul class="ems"> <li>One</li> <li>Two</li> <li> Three <ul> <li>Three A</li> <li> Three B <ul> <li>Three B i</li> </ul> </li> </ul> </li> </ul> <ul class="rems"> <li>One</li> <li>Two</li> <li> Three <ul> <li>Three A</li> <li> Three B <ul> <li>Three B i</li> </ul> </li> </ul> </li> </ul> </section> <textarea class="playable playable-css" style="height: 280px;"> html { font-size: 16px; } .ems li { font-size: 1.3em; } .rems li { font-size: 1.3rem; } </textarea> <textarea class="playable playable-html" style="height: 130px;"> <ul class="ems"> <li>One</li> <li>Two</li> <li>Three <ul> <li>Three A</li> <li>Three B <ul> <li>Three B 2</li> </ul> </li> </ul> </li> </ul> <ul class="rems"> <li>One</li> <li>Two</li> <li>Three <ul> <li>Three A</li> <li>Three B <ul> <li>Three B 2</li> </ul> </li> </ul> </li> </ul> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>object-fit-basics/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width"> <title>Object-fit basics</title> <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="style.css"> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <h1>Object fit basics</h1> <p>This page illustrates different object-fit settings. It is part of the <a href="http://hacks.mozilla.org/2015/01/exploring-object-fit/">Exploring object-fit</a> Mozilla Hacks post. For the following examples to work, you'll need to be using a fairly new browser — Firefox 36+, Chrome 31+, Opera 26+ or Safari 8+. The latter supports <code>object-fit</code>, but not <code>object-position</code>.</p> <h2 id="contain">object-fit: contain</h2> <p>with <code>object-fit: contain</code>, the image is letterboxed inside the image element, retaining its aspect ratio.</p> <img src="flowers.jpg" class="contain" alt="with object-fit contain, the image is trapped inside the image element, retaining aspect ratio."> <h2 id="cover">object-fit: cover</h2> <p>with <code>object-fit: cover</code>, the image completely covers the image element — it is shown completely along the shortest dimension, and will be cut off in the other direction.</p> <img src="flowers.jpg" class="cover" alt="with object-fit cover, the image completely covers the image element and is cropped along the longest dimension"> <h2 id="fill">object-fit: fill</h2> <p><code>Object-fill: fill</code> can override a video’s intrinsic aspect ratio, forcing it to completely fill the <code>&lt;video&gt;</code> element. This is good for correcting videos with broken aspect ratios.</p> <video controls="controls" src="windowsill.webm" width="426" height="240" class="fill"> <p>HTML5 video not supported?</p> </video> <p><button>Turn object-fit: fill off</button></p> <h2 id="none">object-fit: none</h2> <p>Combining <code>object-fit</code> and <code>object-position</code> with CSS transitions can lead to some pretty interesting effects for image or video galleries.</p> <img src="flowers.jpg" class="none" alt="when hovered over the image element expands to reveal more of the image" tabindex="0"> <h2 id="position">object-position</h2> <p>The three images below have <code>object-fit: cover</code>, and three different <code>object-position</code> values set on them: <code>0 0</code>, <code>bottom</code>, and <code>100px 100px</code> respectively.</p> <img src="flowers.jpg" class="objpos pos1" alt="when hovered over the image element expands to reveal more of the image"> <img src="flowers.jpg" class="objpos pos2" alt="when hovered over the image element expands to reveal more of the image"> <img src="flowers.jpg" class="objpos pos3" alt="when hovered over the image element expands to reveal more of the image"> </body> <script> var button = document.querySelector('button'); var video = document.querySelector('video'); button.onclick = function() { if(video.className === 'fill') { video.className = ''; button.textContent = 'Turn object-fit: fill on'; } else { video.className = 'fill'; button.textContent = 'Turn object-fit: fill off'; } } </script> </html> <|start_filename|>logical/text-align.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>text-align logical values</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .container { display: flex; } .inner { width: 200px; border: 2px dotted grey; padding: 10px; } </style> <style class="editable"> .inner { direction: ltr; } .physical { text-align:right; } .logical { text-align: end; } </style> </head> <body> <section class="preview"> <div class="container"> <div class="inner physical"> Aligned text </div> <div class="inner logical"> Aligned text </div> </div> </section> <textarea class="playable playable-css" style="height: 240px;"> .inner { direction: ltr; } .physical { text-align:right; } .logical { text-align: end; }</textarea> <textarea class="playable playable-html" style="height: 180px;"> <div class="container"> <div class="inner physical"> Aligned text </div> <div class="inner logical"> Aligned text </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>css-cookbook/card--download.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <!-- this is an example from the MDN Layout Cookbook --> <title>CSS Cookbook: card component</title> <style> /* body rules included when showing the example as a live example */ body { background-color: #fff; color: #333; font: 1.2em / 1.5 Helvetica Neue, Helvetica, Arial, sans-serif; padding: 0; margin: 0; } img { max-width: 100%; } .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); grid-gap: 20px; max-width: 800px; margin: 1em auto; } .card { display: grid; grid-template-rows: max-content 200px 1fr; border: 1px solid #999; border-radius: 3px; } .card img { object-fit: cover; width: 100%; height: 100%; } .card h2 { margin: 0; padding: .5rem; } .card .content { padding: .5rem; } .card footer { background-color: #333; color: #fff; padding: .5rem; } </style> </head> <body> <div class="cards"> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons.jpg" alt="Hot air balloons"> <div class="content"> <p> The idea of reaching the North Pole by means of balloons appears to have been entertained many years ago. </p> </div> </article> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons2.jpg" alt="Hot air balloons"> <div class="content"> <p>Short content.</p> </div> <footer>I have a footer!</footer> </article> <article class="card"> <header> <h2>A longer heading in this card</h2> </header> <img src="balloons.jpg" alt="Hot air balloons"> <div class="content"> <p>In a curious work, published in Paris in 1863 by Delaville Dedreux, there is a suggestion for reaching the North Pole by an aerostat.</p> </div> <footer>I have a footer!</footer> </article> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons2.jpg" alt="Hot air balloons"> <div class="content"> <p> The idea of reaching the North Pole by means of balloons appears to have been entertained many years ago. </p> </div> </article> </div> </body> </html> <|start_filename|>flexbox/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Flexbox Examples</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Flexbox Examples</h1> <p>These examples are to accompany the Flexbox articles on MDN.</p> <h2>Basic concepts of flexbox</h2> <ol> <li><a href="basics/the-flex-container.html">The flex container</a></li> <li><a href="basics/flex-direction.html">The flex-direction property</a></li> <li><a href="basics/flex-wrap.html">Multi-line flex containers</a></li> <li><a href="basics/flex-flow.html">The flex-flow shorthand</a></li> <li><a href="basics/flex-properties.html">The flex properties</a></li> <li><a href="basics/flex-shorthands.html">Flex shorthands</a></li> <li><a href="basics/align-items.html">Align items</a></li> <li><a href="basics/justify-content.html">Justify content</a></li> </ol> <h2>Relationship to other layout methods</h2> <ol> <li><a href="relationship/writing-modes.html">Writing Modes</a></li> <li><a href="relationship/floats.html">Floated layout</a></li> <li><a href="relationship/flex-layout.html">Simple flex layout</a></li> <li><a href="relationship/grid-layout.html">Simple grid layout</a></li> <li><a href="relationship/display-contents.html">Demo of display: contents</a></li> </ol> <h2>Alignment</h2> <ol> <li><a href="alignment/intro.html">Centering a box</a></li> <li><a href="alignment/align-items.html">Alignment on the cross axis with align-items</a></li> <li><a href="alignment/align-self.html">Aligning individual items with align-self</a></li> <li><a href="alignment/align-self-column.html">Changing the main axis to column and aligning items</a></li> <li><a href="alignment/align-content.html">Aligning content on the cross axis</a></li> <li><a href="alignment/align-content-column.html">Changing the main axis to column</a></li> <li><a href="alignment/justify-content.html">Main axis alignment with justify-content</a></li> <li><a href="alignment/justify-content-column.html">Main axis alignment with flex-direction column</a></li> <li><a href="alignment/justify-content-writing-mode.html">Main axis alignment in RTL writing mode</a></li> <li><a href="alignment/justify-content-reverse.html">Main axis alignment with reversed row</a></li> <li><a href="alignment/auto-margins.html">Alignment with auto margins</a></li> </ol> <h2>Order</h2> <ol> <li><a href="order/flex-direction.html">The flex-direction property</a></li> <li><a href="order/order.html">The order property</a></li> <li><a href="order/negative-order.html">Using negative values for order</a></li> <li><a href="order/usecase-order.html">A usecase for the order property</a></li> </ol> <h2>Ratios on the main axis</h2> <ol> <li><a href="ratios/min-max-content.html">Concepts of min and max-content</a></li> <li><a href="ratios/flex-basis.html">The flex-basis property</a></li> <li><a href="ratios/flex-grow.html">The flex-grow property</a></li> <li><a href="ratios/flex-grow-ratios.html">Ratios and the flex-grow property</a></li> <li><a href="ratios/flex-shrink.html">The flex-shrink property</a></li> <li><a href="ratios/flex-shrink-min-content.html">min-content sizing and the flex-shrink property</a></li> <li><a href="ratios/flex-shrink-ratios.html">Ratios and the flex-shrink property</a></li> </ol> <h2>Mastering wrapping of flex items</h2> <ol> <li><a href="wrapping/row-wrap.html">Wrapping when flex-direction is row</a></li> <li><a href="wrapping/column-wrap.html">Wrapping when flex-direction is column</a></li> <li><a href="wrapping/row-reverse-wrap.html">Wrapping when flex-direction is row-reverse</a></li> <li><a href="wrapping/grid-example.html">Grid and two-dimensions</a></li> <li><a href="wrapping/flex-grid.html">A flexbox grid</a></li> <li><a href="wrapping/gaps.html">Gaps between flex items</a></li> <li><a href="wrapping/visibility-collapse.html">Setting an item to visibility: collapse</a></li> <li><a href="wrapping/wrapped-visibility-collapse.html">Wrapped items with visibility: collapse</a></li> </ol> <h2>Common Use Cases of Flexbox</h2> <ol> <li><a href="use-cases/navigation.html">Navigation</a></li> <li><a href="use-cases/navigation-flex.html">Navigation distributing space to items</a></li> <li><a href="use-cases/navigation-split.html">Split navigation</a></li> <li><a href="use-cases/center.html">Centering an item</a></li> <li><a href="use-cases/cards.html">Card layout</a></li> <li><a href="use-cases/media.html">Media object</a></li> <li><a href="use-cases/media-flipped.html">Flipped media object</a></li> <li><a href="use-cases/input-button.html">Input element and button</a></li> <li><a href="use-cases/label-input-button.html">Adding a label to the input and button</a></li> </ol> <h2>Backwards compatibility of flexbox</h2> <ol> <li><a href="browsers/float.html">With floats as a fallback</a></li> <li><a href="browsers/inline-block.html">With inline-block as a fallback</a></li> <li><a href="browsers/table-cell.html">With table-cell as a fallback</a></li> <li><a href="browsers/vertical-align.html">With the vertical-align property as a fallback for alignment</a></li> </ol> </body> </html> <|start_filename|>counter-style-demo/css/style.css<|end_filename|> body { background: #EEEEEE; margin: 0; padding: 0; } .list-container { float: left; width: 40%; margin-left: 20px; } .list-controls { width: 40%; margin-left: 10px; border: 1px solid #4D4E53; float: left; padding: 10px; background: white; } .code { border-left: 6px solid #558ABB; background: url("https://developer.cdn.mozilla.net/media/redesign/img/blueprint-dark.png"); padding: 12px; } .header h1 { margin: 0; padding: 0; font-family: Ubuntu, Arial, Tahoma, 'Sans Serif'; } .header { background: #27547E; margin: 0 0 10px 0; padding: 5px; color: white; } .notes-section { margin: 10px; color: #4D4E53; font-family: Ubuntu, Arial, Tahoma, 'Sans Serif'; float: left; } /* Demo styles */ @counter-style demo-cyclic { system: cyclic; symbols: ◆ ◇; suffix: " "; } .demo-cyclic { list-style: demo-cyclic; } @counter-style cs-fixed { system: fixed; symbols:          ; suffix: " "; } .demo-fixed { list-style: cs-fixed; } @counter-style cs-symbolic { system: symbolic; symbols: '*' ⁑ † ‡; range: 1 15; suffix: " "; } .demo-symbolic { list-style: cs-symbolic; } @counter-style cs-alphabetic { system: alphabetic; symbols: A B C D E; suffix: " "; } .demo-alphabetic { list-style: cs-alphabetic; } @counter-style cs-numeric { system: numeric; symbols: A B C D E; } .demo-numeric { list-style: cs-numeric; } @counter-style cs-additive-roman { system: additive; range: 1 100; additive-symbols: 1000 M, 900 CM, 500 D, 400 CD, 100 C, 90 XC, 50 L, 40 XL, 10 X, 9 IX, 5 V, 4 IV, 1 I; } .demo-additive { list-style: cs-additive-roman; } @counter-style cs-extends { system: extends decimal; prefix: '('; suffix: ') '; } .demo-extends { list-style: cs-extends; } /* Predefined styles */ .demo-decimal { list-style: decimal; } .demo-decimal-leading-zero { list-style: decimal-leading-zero; } .demo-arabic-indic { list-style: arabic-indic; } .demo-armenian { list-style: armenian; } .demo-upper-armenian { list-style: upper-armenian; } .demo-lower-armenian { list-style: lower-armenian; } .demo-bengali { list-style: bengali; } .demo-cambodian { list-style: cambodian; } .demo-khmer { list-style: khmer; } .demo-cjk-decimal { list-style: cjk-decimal; } .demo-devanagiri { list-style: devanagiri; } .demo-georgian { list-style: georgian; } .demo-gujarati { list-style: gujarati; } .demo-gurmukhi { list-style: gurmukhi; } .demo-hebrew { list-style: hebrew; } .demo-kannada { list-style: kannada; } .demo-lao { list-style: lao; } .demo-malayalam { list-style: malayalam; } .demo-mongolian { list-style: mongolian; } .demo-myanmar { list-style: myanmar; } .demo-oriya { list-style: oriya; } .demo-persian { list-style: persian; } .demo-lower-roman { list-style: lower-roman; } .demo-upper-roman { list-style: upper-roman; } .demo-telugu { list-style: telugu; } .demo-thai { list-style: thai; } .demo-tibetan { list-style: tibetan; } .demo-lower-alpha { list-style: lower-alpha; } .demo-lower-latin { list-style: lower-latin; } .demo-upper-alpha { list-style: upper-alpha; } .demo-upper-latin { list-style: upper-latin; } .demo-cjk-earthly-branch { list-style: cjk-earthly-branch; } .demo-cjk-heavenly-stem { list-style: cjk-heavenly-stem; } .demo-lower-greek { list-style: lower-greek; } .demo-hiragana { list-style: hiragana; } .demo-hiragana-iroha { list-style: hiragana-iroha; } .demo-katakana { list-style: katakana; } .demo-katakana-iroha { list-style: katakana-iroha; } .demo-disc { list-style: disc; } .demo-circle { list-style: circle; } .demo-square { list-style: square; } .demo-disclosure-open { list-style: disclosure-open; } .demo-disclosure-closed { list-style: disclosure-closed; } .demo-japanese-informal { list-style: japanese-informal; } .demo-japanese-formal { list-style: japanese-formal; } .demo-korean-hangul-formal { list-style: korean-hangul-formal; } .demo-korean-hanja-informal { list-style: korean-hanja-informal; } .demo-korean-hanja-formal { list-style: korean-hanja-formal; } .demo-simp-chinese-informal { list-style: simp-chinese-informal; } .demo-simp-chinese-formal { list-style: simp-chinese-formal; } .demo-trad-chinese-informal { list-style: trad-chinese-informal; } .demo-trad-chinese-formal { list-style: trad-chinese-formal; } .demo-cjk-ideographic { list-style: cjk-ideographic; } .demo-ethiopic-numeric { list-style: ethiopic-numeric; } <|start_filename|>learn/cascade/keywords.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Keyword values</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> body { color: green; } .my-class-1 a { color: inherit; } .my-class-2 a { color: initial; } .my-class-3 a { color: unset; } </style> </head> <body> <section class="preview"> <ul> <li>Default <a href="#">link</a> color</li> <li class="my-class-1">Inherit the <a href="#">link</a> color</li> <li class="my-class-2">Reset the <a href="#">link</a> color</li> <li class="my-class-3">Unset the <a href="#">link</a> color</li> </ul> </section> <textarea class="playable playable-css" style="height: 280px;"> body { color: green; } .my-class-1 a { color: inherit; } .my-class-2 a { color: initial; } .my-class-3 a { color: unset; } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <ul> <li>Default <a href="#">link</a> color</li> <li class="my-class-1">Inherit the <a href="#">link</a> color</li> <li class="my-class-2">Reset the <a href="#">link</a> color</li> <li class="my-class-3">Unset the <a href="#">link</a> color</li> </ul> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/selectors/adjacent.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Selectors: Adjacent Combinator </title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> h1 + p { font-weight: bold; background-color: #333; color: #fff; padding: .5em; } </style> </head> <body> <section class="preview"> <article> <h1>A heading</h1> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </article> </section> <textarea class="playable playable-css" style="height: 100px;"> h1 + p { font-weight: bold; background-color: #333; color: #fff; padding: .5em; } </textarea> <textarea class="playable playable-html" style="height: 200px;"> <article> <h1>A heading</h1> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </article> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>editable-samples/pages/transform/js/transform.js<|end_filename|> var cmInitContent = 'transform: skew(30deg, 20deg);\n\n'; <|start_filename|>learn/images/form.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Images and other unusual elements: forms</title> <link rel="stylesheet" href="../styles.css" /> <style> form > div { display: flex; } label { width: 10em; } .buttons { justify-content: center; } </style> <style class="editable"> input[type="text"], input[type="email"] { border: 2px solid #000; margin: 0 0 1em 0; padding: 10px; } input[type="submit"] { border: 3px solid #333; background-color: #999; border-radius: 5px; padding: 10px 2em; font-weight: bold; color: #fff; } input[type="submit"]:hover { background-color: #333; } </style> </head> <body> <section class="preview"> <form> <div><label for="name">Name</label> <input type="text" id="name"></div> <div><label for="email">Email</label> <input type="email" id="email"></div> <div class="buttons"><input type="submit" value="Submit"></div> </form> </section> <textarea class="playable playable-css" style="height: 420px;"> input[type="text"], input[type="email"] { border: 2px solid #000; margin: 0 0 1em 0; padding: 10px; width: 100%; } input[type="submit"] { border: 3px solid #333; background-color: #999; border-radius: 5px; padding: 10px 2em; font-weight: bold; color: #fff; } input[type="submit"]:hover { background-color: #333; } </textarea> <textarea class="playable playable-html" style="height: 200px;"> <form> <div><label for="name">Name</label> <input type="text" id="name"></div> <div><label for="email">Email</label> <input type="email" id="email"></div> <div class="buttons"><input type="submit" value="Submit"></div> </form> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>contain/contain-fix.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Float interference</title> <style> img { float: left; border: 3px solid black; } article { border: 1px solid black; contain: content; } </style> </head> <body> <h1>My blog</h1> <article> <h2>Heading of a nice article</h2> <p>Content here.</p> <img src="placeholder-2.jpg" alt="I just showed up"> </article> <article> <h2>Another heading of another article</h2> <img src="placeholder-1.jpg" alt="placeholder"> <p>More content here.</p> </article> </body> </html> <|start_filename|>editable-samples/js/editable-old.js<|end_filename|> var element = document.getElementById("example-element"); var input = document.getElementById("input"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var cmOptions = { mode: "css", theme: "mdn-like" } var cmEditor = CodeMirror(document.body, cmOptions); cmEditor.setSize("100%", 50); cmEditor.doc.setValue(cmInitContent); CodeMirror.hint.css = function(cm) { var inner = {from: cm.getCursor(), to: cm.getCursor(), list: []}; var currentPos = cm.getCursor(); var preceding = cm.getRange({line: currentPos.line, ch: 0}, currentPos); if (preceding == cmMatchToShowCompletions) { inner.list = cmCompletionChoices; } return inner; }; function applyCode() { element.style.cssText = cmEditor.doc.getValue(); } reset.addEventListener("click", function() { cmEditor.doc.setValue(cmInitContent); applyCode(); }); function selectValue() { var value = cmEditor.doc.getValue(); var start = value.indexOf(":") + 1; if ((value.length > start) && (value[start] === " ")) { start++; } var end = value.length - 1; if ((value.length > 0) && (value[end-1] === ";")) { end--; } cmEditor.doc.setSelection( {line: 0, ch: start}, {line: 0, ch: end}); } edit.addEventListener("click", function() { cmEditor.focus(); selectValue(); }); cmEditor.on("change", applyCode); window.addEventListener("load", applyCode); function showCompletions(cm, event) { var popupKeyCodes = { "9": "tab", "13": "enter", "27": "escape", "33": "pageup", "34": "pagedown", "35": "end", "36": "home", "38": "up", "40": "down" } if(!popupKeyCodes[(event.keyCode || event.which).toString()]) { CodeMirror.showHint(cm, CodeMirror.hint.css, {completeSingle: false, closeOnUnfocus:false}); } } cmEditor.on("keyup", showCompletions); <|start_filename|>learn/selectors/first-child2.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Selectors: :first-child </title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> article p:first-child { font-size: 120%; font-weight: bold; } </style> </head> <body> <section class="preview"> <article> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </article> </section> <textarea class="playable playable-css" style="height: 80px;"> article p:first-child { font-size: 120%; font-weight: bold; } </textarea> <textarea class="playable playable-html" style="height: 160px;"> <article> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </article> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>editable-samples-2/js/editable.js<|end_filename|> var element = document.getElementById("example-element"); var originalChoices = []; var initialChoice = 0; function applyCode(code, choice) { element.style.cssText = code; var errorIcon = choice.querySelector(".error"); if (!element.style.cssText) { errorIcon.classList.remove("hidden"); } else { errorIcon.classList.add("hidden"); } } var exampleChoices = document.querySelectorAll(".example-choice"); function indexOf(exampleChoices, choice) { for (var i = 0; i < exampleChoices.length; i++) { if (exampleChoices[i] === choice) { return i; } } return -1; } function choose(choice) { choice.classList.add("selected"); choice.firstChild.setAttribute("contentEditable", true); choice.firstChild.setAttribute("spellcheck", false); choice.firstChild.focus(); applyCode(choice.textContent, choice); } function onChoose(e) { // highlght the code we are leaving var selected = document.querySelector(".selected"); if (selected && (e.currentTarget != selected)) { var highlighted = Prism.highlight(selected.firstChild.textContent, Prism.languages.css); selected.firstChild.innerHTML = highlighted; } if (selected) { var errorIcon = selected.querySelector(".error"); if (errorIcon) { errorIcon.classList.add("hidden"); } } for (exampleChoice of exampleChoices) { exampleChoice.classList.remove("selected"); } choose(e.currentTarget); } function onEdit(e) { applyCode(e.currentTarget.textContent, e.currentTarget.parentNode); } function copyTextOnly(e) { var selection = window.getSelection(); var range = selection.getRangeAt(0); e.clipboardData.setData('text/plain', range.toString()); e.clipboardData.setData('text/html', range.toString()); e.preventDefault(); e.stopPropagation(); } document.addEventListener('cut', copyTextOnly); document.addEventListener('copy', copyTextOnly); for (exampleChoice of exampleChoices) { originalChoices.push(exampleChoice.textContent); if (exampleChoice.getAttribute("initial-choice")) { initialChoice = indexOf(exampleChoices, exampleChoice); } exampleChoice.addEventListener("click", onChoose); exampleChoice.firstChild.addEventListener("keyup", onEdit); exampleChoice.querySelector(".reset").addEventListener("click", function(e) { var choice = e.target.parentNode; var replacementText = originalChoices[indexOf(exampleChoices, choice)]; var highlighted = Prism.highlight(replacementText, Prism.languages.css); choice.firstChild.innerHTML = highlighted; }); } choose(exampleChoices[initialChoice]); <|start_filename|>object-fit-basics/style.css<|end_filename|> html { font-family: 'Open Sans Condensed', sans-serif; } body { width: 70%; max-width: 800px; margin: 0 auto; } img { width: 480px; height: 320px; background: gray; border: 2px solid black; display: block; margin: 0 auto; } video { margin: 0 auto; display: block; border: 2px solid black; } .contain { object-fit: contain; } .cover { object-fit: cover; } .fill { object-fit: fill; } .none { width: 200px; height: 200px; overflow: hidden; object-fit: none; object-position: 25% 50%; transition: 1s width, 1s height; } .none:hover, .none:focus { height: 350px; width: 350px; } .objpos { object-fit: cover; margin-bottom: 10px; } .pos1 { object-position: 0 0; } .pos2 { object-position: bottom; } .pos3 { object-position: 100px 100px; } <|start_filename|>logical/float.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>logical values for float</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .container { display: flex; } .box { border: 2px solid rgb(96, 139, 168); border-radius: 5px; background-color: rgba(96, 139, 168, .2); padding: 10px; margin: 10px; width: 100px; height: 100px; } </style> <style class="editable"> .inner { writing-mode: horizontal-tb; } .physical { float: left; } .logical { float: inline-start; } </style> </head> <body> <section class="preview"> <div class="container"> <div class="inner"> <div class="physical box"></div> Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. <div class="inner"> <div class="logical box"></div> Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. </div> </div> </section> <textarea class="playable playable-css" style="height: 240px;"> .inner { writing-mode: horizontal-tb; } .physical { float: left; } .logical { float: inline-start; }</textarea> <textarea class="playable playable-html" style="height: 180px;"> <div class="container"> <div class="inner"> <div class="physical box"></div> Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. </div> <div class="inner"> <div class="logical box"></div> Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>learn/selectors/id.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Selectors: id</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> #one { background-color: yellow; } h1#heading { color: rebeccapurple; } </style> </head> <body> <section class="preview"> <h1 id="heading">ID selector</h1> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p id="one">Gumbo beet greens corn soko <strong>endive</strong> gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </section> <textarea class="playable playable-css" style="height: 140px;"> #one { background-color: yellow; } h1#heading { color: rebeccapurple; } </textarea> <textarea class="playable playable-html" style="height: 160px;"> <h1 id="heading">ID selector</h1> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p id="one">Gumbo beet greens corn soko <strong>endive</strong> gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>scroll-snap/align.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>CSS Scroll Snap - scroll-snap-align</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .scroller { border: 4px solid #333; width: 300px; } .scroller section { min-height: 100%; padding: 10px; } .scroller section:nth-child(odd) { background-color: #ccc; } </style> <style class="editable"> .scroller { height: 200px; overflow-y: scroll; scroll-snap-type: y mandatory; } .scroller section { scroll-snap-align: start; } </style> </head> <body> <section class="preview"> <article class="scroller"> <section> <h2>Section one</h2> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko.</p> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard.</p> </section> <section> <h2>Section two</h2> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. </p> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard.</p> </section> <section> <h2>Section three</h2> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko.</p> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard.</p> </section> </article> </section> <textarea class="playable playable-css" style="height: 170px;">.scroller { height: 200px; overflow-y: scroll; scroll-snap-type: y mandatory; } .scroller section { scroll-snap-align: start; }</textarea> <textarea class="playable playable-html" style="height: 230px;"> <article class="scroller"> <section> <h2>Section one</h2> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko.</p> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard.</p> </section> <section> <h2>Section two</h2> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko.</p> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard.</p> </section> <section> <h2>Section three</h2> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko.</p> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard.</p> </section> </article> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>learn/writing-modes/logical-mbp.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Backgrounds and Borders: logical MBP</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } .wrapper { display: flex; border: 5px solid #ccc; } .box { margin-right: 30px; } </style> <style class="editable"> .box { inline-size: 200px; writing-mode: horizontal-tb; } .logical { margin-block-start: 20px; padding-inline-end: 2em; padding-block-start: 2px; border-block-start: 5px solid pink; border-inline-end: 10px dotted rebeccapurple; border-block-end: 1em double orange; border-inline-start: 1px solid black; } .physical { margin-top: 20px; padding-right: 2em; padding-top: 2px; border-top: 5px solid pink; border-right: 10px dotted rebeccapurple; border-bottom: 1em double orange; border-left: 1px solid black; } h2 { border-bottom: 5px solid black; } </style> </head> <body> <section class="preview"> <div class="wrapper"> <div class="box physical"> <h2>Physical Properties</h2> <p>A paragraph. Demonstrating Logical Properties in CSS.</p> </div> <div class="box logical"> <h2>Logical Properties</h2> <p>A paragraph. Demonstrating Logical Properties in CSS.</p> </div> </div> </section> <textarea class="playable playable-css" style="height: 500px;"> .box { inline-size: 200px; writing-mode: horizontal-tb; } .logical { margin-block-start: 20px; padding-inline-end: 2em; padding-block-start: 2px; border-block-start: 5px solid pink; border-inline-end: 10px dotted rebeccapurple; border-block-end: 1em double orange; border-inline-start: 1px solid black; } .physical { margin-top: 20px; padding-right: 2em; padding-top: 2px; border-top: 5px solid pink; border-right: 10px dotted rebeccapurple; border-bottom: 1em double orange; border-left: 1px solid black; } h2 { border-bottom: 5px solid black; } </textarea> <textarea class="playable playable-html" style="height: 230px;"> <div class="wrapper"> <div class="box physical"> <h2>Physical Properties</h2> <p>A paragraph. Demonstrating Logical Properties in CSS.</p> </div> <div class="box logical"> <h2>Logical Properties</h2> <p>A paragraph. Demonstrating Logical Properties in CSS.</p> </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>editable-samples/pages/filter/js/filter.js<|end_filename|> var cmInitContent = 'filter: hue-rotate(180deg);\n\n'; <|start_filename|>learn/tasks/sizing/height-min-height-download.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sizing Task 1: height and min-height</title> <style> body { background-color: #fff; color: #333; font: 1.2em / 1.5 Helvetica Neue, Helvetica, Arial, sans-serif; padding: 1em; margin: 0; } .box { border: 5px solid #000; width: 400px; margin-bottom: 1em; } .preview { min-height: 400px; } .box1 { } .box2 { } </style> </head> <body> <div class="box box1"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. </p> </div> <div class="box box2"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. </p> </div> </body> </html> <|start_filename|>learn/media-queries/grid.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Media Queries: a simple mobile first design, adding a grid component</title> <style> * { box-sizing: border-box; } body { width: 90%; margin: 2em auto; font: 1em/1.3 Arial, Helvetica, sans-serif; } a:link, a:visited { color: #333; } nav ul, aside ul { list-style: none; padding: 0; } nav a:link, nav a:visited { background-color: rgba(207, 232, 220, 0.2); border: 2px solid rgb(79, 185, 227); text-decoration: none; display: block; padding: 10px; color: #333; font-weight: bold; } nav a:hover { background-color: rgba(207, 232, 220, 0.7); } .related { background-color: rgba(79, 185, 227, 0.3); border: 1px solid rgb(79, 185, 227); padding: 10px; } .sidebar { background-color: rgba(207, 232, 220, 0.5); padding: 10px; } article { margin-bottom: 1em; } .grid { list-style: none; margin: 0; padding: 0; display: grid; gap: 20px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); } .grid li { border: 1px solid #666; padding: 10px; } @media screen and (min-width: 40em) { article { display: grid; grid-template-columns: 3fr 1fr; column-gap: 20px; } nav ul { display: flex; } nav li { flex: 1; } } @media screen and (min-width: 70em) { main { display: grid; grid-template-columns: 3fr 1fr; column-gap: 20px; } article { margin-bottom: 0; } footer { border-top: 1px solid #ccc; margin-top: 2em; } } </style> </head> <body> <div class="wrapper"> <header> <nav> <ul> <li><a href="">About</a></li> <li><a href="">Contact</a></li> <li><a href="">Meet the team</a></li> <li><a href="">Blog</a></li> </ul> </nav> </header> <main> <article> <div class="content"> <h1>Veggies!</h1> <p> Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. </p> <p> Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini. </p> <ul class="grid"> <li> <h2>Card 1</h2> <p> Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. </p> </li> <li> <h2>Card 2</h2> <p> Celery potato scallion desert raisin horseradish spinach carrot soko. </p> </li> <li> <h2>Card 3</h2> <p> Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. </p> </li> <li> <h2>Card 4</h2> <p> Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. </p> </li> <li> <h2>Card 5</h2> <p> Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. </p> </li> </ul> </div> <aside class="related"> <p> All these veggies are brought to you by the <a href="https://veggieipsum.com/">Veggie Ipsum generator</a>. </p> </aside> </article> <aside class="sidebar"> <h2>External vegetable-based links</h2> <ul> <li> <a href="https://www.thekitchn.com/how-to-cook-broccoli-5-ways-167323" >How to cook broccoli</a > </li> <li> <a href="https://www.bbcgoodfood.com/glossary/swiss-chard" >Swiss Chard</a > </li> <li> <a href="https://www.bbcgoodfood.com/recipes/collection/christmas-parsnip" >Christmas Parsnip Recipes</a > </li> </ul> </aside> </main> <footer><p>&copy;2019</p></footer> </div> </body> </html> <|start_filename|>learn/values-units/color-hsla.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Values and Units: color hsl codes</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } .wrapper { background-image: url(balloons.jpg); padding: 40px 20px; } .box { padding: 10px; margin: 1em 0; border-radius: 0.5em; } </style> <style class="editable"> .one { background-color: hsla(188, 97%, 28%, 0.3); } .two { background-color: hsla(321, 47%, 57%, 0.7); } .three { background-color: hsla(174, 77%, 31%, 0.9); } </style> </head> <body> <section class="preview"> <div class="wrapper"> <div class="box one">hsla(188, 97%, 28%, .3)</div> <div class="box two">hsla(321, 47%, 57%, .7)</div> <div class="box three">hsla(174, 77%, 31%, .9)</div> </div> </section> <textarea class="playable playable-css" style="height: 240px;"> .one { background-color: hsla(188, 97%, 28%, .3); } .two { background-color: hsla(321, 47%, 57%, .7); } .three { background-color: hsla(174, 77%, 31%, .9); } </textarea> <textarea class="playable playable-html" style="height: 130px;"> <div class="wrapper"> <div class="box one">hsla(188, 97%, 28%, .3)</div> <div class="box two">hsla(321, 47%, 57%, .7)</div> <div class="box three">hsla(174, 77%, 31%, .9)</div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/sizing/percent-mp.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sizing: percentage margins and padding</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } </style> <style class="editable"> .box { border: 5px solid darkblue; width: 300px; margin: 10%; padding: 10%; } </style> </head> <body> <section class="preview"> <div class="box"> I have margin and padding set to 10% on all sides. </div> </section> <textarea class="playable playable-css" style="height: 120px;"> .box { border: 5px solid darkblue; width: 300px; margin: 10%; padding: 10%; } </textarea> <textarea class="playable playable-html" style="height: 120px;"> <div class="box"> I have margin and padding set to 10% on all sides. </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>logical/size-resize.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Size: the resize property</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .container { display: flex; } .box { border: 2px solid rgb(96, 139, 168); border-radius: 5px; background-color: rgba(96, 139, 168, .2); padding: 10px; margin: 10px; overflow: scroll; } </style> <style class="editable"> .box { writing-mode: horizontal-tb; } .physical { width: 200px; height: 100px; resize: horizontal; } .logical { inline-size: 200px; block-size: 100px; resize: inline; } </style> </head> <body> <section class="preview"> <div class="container"> <div class="physical box"> I have a width of 200px and a height of 100px. I can be resized horizontally. </div> <div class="logical box"> I have an inline-size of 200px and a block-size of 100px. I can be resized in the inline direction. </div> </div> </section> <textarea class="playable playable-css" style="height: 240px;"> .box { writing-mode: horizontal-tb; } .physical { width: 200px; height: 100px; resize: horizontal; } .logical { inline-size: 200px; block-size: 100px; resize: inline; }</textarea> <textarea class="playable playable-html" style="height: 180px;"> <div class="container"> <div class="physical box"> I have a width of 200px and a height of 100px. I can be resized horizontally. </div> <div class="logical box"> I have an inline-size of 200px and a block-size of 100px. I can be resized in the inline direction. </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>css-cookbook/grid-wrapper.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>CSS Cookbook: Grid Wrapper</title> <link rel="stylesheet" href="styles.css"> <style> .grid { display: grid; grid-template-columns: minmax(20px, 1fr) repeat(6, minmax(0, 60px)) minmax(20px, 1fr); grid-auto-rows: minmax(100px, auto); grid-gap: 10px; } .grid > * { border: 2px solid rgb(95, 97, 110); border-radius: .5em; padding: 20px; } .full-width { grid-column: 1 / -1; } .wrapper { grid-column: 2 / -2; } .left-edge { grid-column: 1 / -2; } .right-wrapper { grid-column: 4 / -2; } </style> <style class="editable"> .grid { display: grid; grid-template-columns: minmax(20px, 1fr) repeat(6, minmax(0, 60px)) minmax(20px, 1fr); grid-gap: 10px; } .full-width { grid-column: 1 / -1; } .wrapper { grid-column: 2 / -2; } .left-edge { grid-column: 1 / -2; } .right-wrapper { grid-column: 4 / -2; } </style> </head> <body> <section class="preview"> <div class="grid"> <div class="wrapper"> <p>This item aligns to a central “wrapper” – columns that have a maximum width.</p> </div> <div class="full-width"> <p>This item aligns to the edge of the grid container.</p> </div> <div class="left-edge"> <p>This item aligns to the left edge of the grid container and the right edge of the wrapper.</p> </div> <div class="right-wrapper"> <p>This item aligns to the right edge of the “wrapper” columns.</p> </div> </div> </section> <textarea class="playable playable-css" style="height: 170px;"> .grid { display: grid; grid-template-columns: minmax(20px, 1fr) repeat(6, minmax(0, 60px)) minmax(20px, 1fr); grid-gap: 10px; } .full-width { grid-column: 1 / -1; } .wrapper { grid-column: 2 / -2; } .left-edge { grid-column: 1 / -2; } .right-wrapper { grid-column: 4 / -2; } </textarea> <textarea class="playable playable-html" style="height: 170px;"> <div class="grid"> <div class="wrapper"> <p>This item aligns to a central “wrapper” – columns that have a maximum width.</p> </div> <div class="full-width"> <p>This item aligns to the edge of the grid container.</p> </div> <div class="left-edge"> <p>This item aligns to the left edge of the grid container and the right edge of the wrapper.</p> </div> <div class="right-wrapper"> <p>This item aligns to the right edge of the “wrapper” columns.</p> </div> </div> </textarea> <!-- leave everything below here alone --> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="playable.js"></script> </html> <|start_filename|>learn/cascade/inheritance.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Inheritance</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> .main { color: rebeccapurple; border: 2px solid #ccc; padding: 0 2em; } .special { color: black; font-weight: bold; } </style> </head> <body> <section class="preview"> <ul class="main"> <li>Item One</li> <li>Item Two <ul> <li>2.1</li> <li>2.2</li> </ul> </li> <li>Item Three <ul class="special"> <li>3.1 <ul> <li>3.1.1</li> <li>3.1.2</li> </ul> </li> <li>3.2</li> </ul> </li> </ul> </section> <textarea class="playable playable-css" style="height: 180px;"> .main { color: rebeccapurple; border: 2px solid #ccc; padding: 1em; } .special { color: black; font-weight: bold; } </textarea> <textarea class="playable playable-html" style="height: 330px;"> <ul class="main"> <li>Item One</li> <li>Item Two <ul> <li>2.1</li> <li>2.2</li> </ul> </li> <li>Item Three <ul class="special"> <li>3.1 <ul> <li>3.1.1</li> <li>3.1.2</li> </ul> </li> <li>3.2</li> </ul> </li> </ul> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/backgrounds-borders/background-blend-mode.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Backgrounds and Borders: background-blend-mode</title> <link rel="stylesheet" href="../styles.css" /> <style> .box { width: 250px; height: 130px; padding: 10px; margin: 10px; display: inline-block; } </style> <style class="editable"> .box { background: url(https://mdn.mozillademos.org/files/13090/colorful-heart.png) no-repeat center 20px; background-color: green; } .multiply { background-blend-mode: multiply; } </style> </head> <body> <section class="preview"> <div class="box"></div> <div class="box multiply"></div> </section> <textarea class="playable playable-css" style="height: 220px;"> .box { background: url(https://mdn.mozillademos.org/files/13090/colorful-heart.png) no-repeat center 20px; background-color: green; } .multiply { background-blend-mode: multiply; } </textarea> <textarea class="playable playable-html" style="height: 90px;"> <div class="box"></div> <div class="box multiply"></div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/box-model/inline-block-nav.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Box Model: Inline block for navigation items</title> <link rel="stylesheet" href="../styles.css" /> <style> ul { display: flex; list-style: none; margin: 0; padding: 0; border:1px solid #000; } li { margin: 5px; } </style> <style class="editable"> .links-list a { background-color: rgb(179,57,81); color: #fff; padding: 1em 2em; } .links-list a:hover { background-color: rgb(66, 28, 40); color: #fff; } </style> </head> <body> <section class="preview"> <nav> <ul class="links-list"> <li><a href="">Link one</a></li> <li><a href="">Link two</a></li> <li><a href="">Link three</a></li> </ul> </nav> </section> <textarea class="playable playable-css" style="height: 240px;"> .links-list a { background-color: rgb(179,57,81); color: #fff; text-decoration: none; padding: 1em 2em; } .links-list a:hover { background-color: rgb(66, 28, 40); color: #fff; } </textarea> <textarea class="playable playable-html" style="height: 180px;"> <nav> <ul class="links-list"> <li><a href="">Link one</a></li> <li><a href="">Link two</a></li> <li><a href="">Link three</a></li> </ul> </nav> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/images/shapes.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Images and other unusual elements: shapes</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } </style> <style class="editable"> img { float: left; shape-outside: circle(50%); } </style> </head> <body> <section class="preview"> <div class="wrapper"> <img src="round-balloon.png" alt="balloon"> <p>One November night in the year 1782, so the story runs, two brothers sat over their winter fire in the little French town of Annonay, watching the grey smoke-wreaths from the hearth curl up the wide chimney. Their names were Stephen and <NAME>, they were papermakers by trade, and were noted as possessing thoughtful minds and a deep interest in all scientific knowledge and new discovery. Before that night—a memorable night, as it was to prove—hundreds of millions of people had watched the rising smoke-wreaths of their fires without drawing any special inspiration from the fact.</p> </div> </section> <textarea class="playable playable-css" style="height: 120px;"> img { float: left; shape-outside: circle(50%); } </textarea> <textarea class="playable playable-html" style="height: 220px;"> <div class="wrapper"> <img src="round-balloon.png" alt="balloon"> <p>One November night in the year 1782, so the story runs, two brothers sat over their winter fire in the little French town of Annonay, watching the grey smoke-wreaths from the hearth curl up the wide chimney. Their names were Stephen and <NAME>, they were papermakers by trade, and were noted as possessing thoughtful minds and a deep interest in all scientific knowledge and new discovery. Before that night—a memorable night, as it was to prove—hundreds of millions of people had watched the rising smoke-wreaths of their fires without drawing any special inspiration from the fact.</p> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/box-model/inline-block.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Box Model: Inline boxes</title> <link rel="stylesheet" href="../styles.css" /> <style> p { border: 2px solid rebeccapurple; width: 300px; } </style> <style class="editable"> span { margin: 20px; padding: 20px; width: 80px; height: 50px; background-color: lightblue; border: 2px solid blue; display: inline-block; } </style> </head> <body> <section class="preview"> <p> I am a paragraph and this is a <span>span</span> inside that paragraph. A span is an inline element and so does not respect width and height. </p> </section> <textarea class="playable playable-css" style="height: 180px;"> span { margin: 20px; padding: 20px; width: 80px; height: 50px; background-color: lightblue; border: 2px solid blue; display: inline-block; } </textarea> <textarea class="playable playable-html" style="height: 120px;"> <p> I am a paragraph and this is a <span>span</span> inside that paragraph. A span is an inline element and so does not respect width and height. </p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/getting-started/started3.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Styling based on state</title> <link rel="stylesheet" href="../styles.css"> <style class="editable"> a:link { color: pink; } a:visited { color: green; } a:hover { text-decoration: none; } </style> </head> <body> <section class="preview"> <h1>I am a level one heading</h1> <p>This is a paragraph of text. In the text is a <span>span element</span> and also a <a href="http://example.com">link</a>.</p> <p>This is the second paragraph. It contains an <em>emphasized</em> element.</p> <ul> <li>Item one</li> <li>Item two</li> <li>Item <em>three</em></li> </ul> </section> <textarea class="playable playable-css" style="height: 200px;"> a:link { color: pink; } a:visited { color: green; } a:hover { text-decoration: none; } </textarea> <textarea class="playable playable-html" style="height: 250px;"> <h1>I am a level one heading</h1> <p>This is a paragraph of text. In the text is a <span>span element</span> and also a <a href="http://example.com">link</a>.</p> <p>This is the second paragraph. It contains an <em>emphasized</em> element.</p> <ul> <li>Item one</li> <li>Item two</li> <li>Item <em>three</em></li> </ul> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>feature-queries/not.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Feature Queries: not</title> <link rel="stylesheet" href="../learn/styles.css"> <style> </style> <style class="editable"> .box { border: 4px solid blue; color: blue; } @supports not (row-gap: 10px) { .box { border: 4px solid red; color: red; } } </style> </head> <body> <section class="preview"> <div class="box"> If your browser does not support row-gap, the text and border will be red. </div> </section> <textarea class="playable playable-css" style="height: 200px;"> .box { border: 4px solid blue; color: blue; } @supports not (row-gap: 10px) { .box { border: 4px solid red; color: red; } } </textarea> <textarea class="playable playable-html" style="height: 120px;"> <div class="box"> If your browser does not support row-gap, the text and border will be red. </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../learn/playable.js"></script> </html> <|start_filename|>learn/overflow/hidden.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Overflow: hidden</title> <link rel="stylesheet" href="../styles.css" /> <style> </style> <style class="editable"> .box { border: 1px solid #333333; width: 200px; height: 100px; overflow: hidden; } </style> </head> <body> <section class="preview"> <div class="box">This box has a height and a width. This means that if there is too much content to be displayed within the assigned height, there will be an overflow situation. If overflow is set to hidden then any overflow will not be visible.</div> </section> <textarea class="playable playable-css" style="height: 120px;"> .box { border: 1px solid #333333; width: 200px; height: 100px; overflow: hidden; } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <div class="box">This box has a height and a width. This means that if there is too much content to be displayed within the assigned height, there will be an overflow situation. If overflow is set to hidden then any overflow will not be visible.</div> <p>This content is outside of the box.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/media-queries/orientation.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Media Queries: orientation</title> <style> html { font-size: 1em; } @media(orientation: landscape) { body { color: rebeccapurple; } } </style> </head> <body> <p>One November night in the year 1782, so the story runs, two brothers sat over their winter fire in the little French town of Annonay, watching the grey smoke-wreaths from the hearth curl up the wide chimney. Their names were Stephen and <NAME>, they were papermakers by trade, and were noted as possessing thoughtful minds and a deep interest in all scientific knowledge and new discovery.</p> <p>Before that night—a memorable night, as it was to prove—hundreds of millions of people had watched the rising smoke-wreaths of their fires without drawing any special inspiration from the fact.”</p> </body> </html> <|start_filename|>editable-samples/pages/font/js/font.js<|end_filename|> var cmInitContent = 'font: italic 1.5em cursive;\n\n'; <|start_filename|>learn/backgrounds-borders/mix-blend-mode.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Backgrounds and Borders: mix-blend-mode</title> <link rel="stylesheet" href="../styles.css" /> <style> .container { width: 280px; height: 180px; margin: 10px; position: relative; display: inline-block; } .box { width: 250px; height: 130px; padding: 10px; margin: 10px; } .box:first-child { position: absolute; top: 10px; left: 0; } .box:last-child { position: absolute; bottom: -10px; right: 0; z-index: -1; } </style> <style class="editable"> .box:first-child { background: url(https://mdn.mozillademos.org/files/13090/colorful-heart.png) no-repeat center 20px; background-color: green; } .box:last-child { background-color: purple; } .multiply-mix { mix-blend-mode: multiply; } </style> </head> <body> <section class="preview"> <div class="container"> No mix blend mode <div class="box"></div> <div class="box"></div> </div> <div class="container"> Multiply mix <div class="box multiply-mix"></div> <div class="box"></div> </div> </section> <textarea class="playable playable-css" style="height: 280px;"> .box:first-child { background: url(https://mdn.mozillademos.org/files/13090/colorful-heart.png) no-repeat center 20px; background-color: green; } .box:last-child { background-color: purple; } .multiply-mix { mix-blend-mode: multiply; } </textarea> <textarea class="playable playable-html" style="height: 200px;"> <div class="container"> No mix blend mode <div class="box"></div> <div class="box"></div> </div> <div class="container"> Multiply mix <div class="box multiply-mix"></div> <div class="box"></div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/tasks/selectors/combinators.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Selectors: Combinators</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } h2 { margin: 0; } </style> <style class="editable"> </style> </head> <body> <section class="preview"> <div class="container"> <h2>This is a heading</h2> <p>This paragraph comes after the heading.</p> <p>This is the second paragraph.</p> <h2>Another heading</h2> <p>This paragraph comes after the heading.</p> <ul class="list"> <li>One</li> <li>Two <ul> <li>2.1</li> <li>2.2</li> </ul> </li> <li>Three</li> </ul> </div> </section> <textarea class="playable playable-css" style="height: 120px;"> </textarea> <textarea class="playable playable-html" style="height: 130px;"> <div class="container"> <h2>This is a heading</h2> <p>This paragraph comes after the heading.</p> <p>This is the second paragraph.</p> <h2>Another heading</h2> <p>This paragraph comes after the heading.</p> <ul class="list"> <li>One</li> <li>Two <ul> <li>2.1</li> <li>2.2</li> </ul> </li> <li>Three</li> </ul> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/tasks/selectors/pseudo.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Selectors: Pseudo-class and Pseudo-element Selectors</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } table { border-collapse: collapse; width: 300px; } td, th { padding: .2em; text-align: left; } </style> <style class="editable"> </style> </head> <body> <section class="preview"> <div class="container"> <p>Veggies es <a href="http://example.com">bonus vobis</a>, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <table> <tr> <th>Fruits</th> <th>Vegetables</th> </tr> <tr> <td>Apple</td> <td>Potato</td> </tr> <tr> <td>Orange</td> <td>Carrot</td> </tr> <tr> <td>Tomato</td> <td>Parsnip</td> </tr> <tr> <td>Kiwi</td> <td>Onion</td> </tr> <tr> <td>Banana</td> <td>Beet</td> </tr> </table> </div> </section> <textarea class="playable playable-css" style="height: 220px;"> </textarea> <textarea class="playable playable-html" style="height: 230px;"> <div class="container"> <p>Veggies es <a href="http://example.com">bonus vobis</a>, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <table> <tr> <th>Fruits</th> <th>Vegetables</th> </tr> <tr> <td>Apple</td> <td>Potato</td> </tr> <tr> <td>Orange</td> <td>Carrot</td> </tr> <tr> <td>Tomato</td> <td>Parsnip</td> </tr> <tr> <td>Kiwi</td> <td>Onion</td> </tr> <tr> <td>Banana</td> <td>Beet</td> </tr> </table> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>grid/subgrid/gap.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Subgrid: gap inherited</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } .grid { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .item { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; color: #d9480f; } .subitem { background-color: rgb(40, 240, 83); } </style> <style class="editable"> .grid { display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(4, minmax(100px, auto)); gap: 20px; } .item { display: grid; grid-column: 2 / 7; grid-row: 2 / 4; grid-template-columns: subgrid; grid-template-rows: subgrid; } .subitem { grid-column: 3 / 6; grid-row: 1 / 3; } .subitem2 { background-color: rgba(0,0,0,.5); grid-column: 2; grid-row: 1; } </style> </head> <body> <section class="preview"> <div class="grid"> <div class="item"> <div class="subitem"></div> <div class="subitem2"></div> </div> </div> </section> <textarea class="playable playable-css" style="height: 350px;"> .grid { display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(4, minmax(100px, auto)); gap: 20px; } .item { display: grid; grid-column: 2 / 7; grid-row: 2 / 4; grid-template-columns: subgrid; grid-template-rows: subgrid; row-gap: 0; } .subitem { grid-column: 3 / 6; grid-row: 1 / 3; } .subitem2 { background-color: rgba(0,0,0,.5); grid-column: 2; grid-row: 1; } </textarea> <textarea class="playable playable-html" style="height: 200px;"> <div class="grid"> <div class="item"> <div class="subitem"></div> <div class="subitem2"></div> </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>editable-samples/pages/transform/css/element.css<|end_filename|> #example-element { max-width: 80%; max-height: 80%; display: block; margin: 1em auto 0 auto; } <|start_filename|>learn/tasks/writing-modes/logical-mbp.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Writing Modes Task 3: Logical Margin, Border, Padding</title> <link rel="stylesheet" href="../styles.css" /> <style> .vertical { writing-mode: vertical-rl; } </style> <style class="editable"> .box { width: 150px; height: 150px; border-top: 5px solid rebeccapurple; border-right: 5px solid grey; border-bottom: 5px dotted red; border-left: 5px dotted blue; padding-top: 40px; margin-bottom: 30px; } </style> </head> <body> <section class="preview"> <div class="box">Horizontal.</div> <div class="box vertical">Vertical.</div> </section> <textarea class="playable playable-css" style="height: 180px;"> .box { width: 150px; height: 150px; border-top: 5px solid rebeccapurple; border-right: 5px solid grey; border-bottom: 5px dotted red; border-left: 5px dotted blue; padding-top: 40px; margin-bottom: 30px; } </textarea> <textarea class="playable playable-html" style="height: 180px;"> <div class="box">Horizontal.</div> <div class="box vertical">Vertical.</div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/box-model/block.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Box Model: Block</title> <link rel="stylesheet" href="../styles.css" /> <style></style> <style class="editable"> p, ul { border: 2px solid rebeccapurple; padding: 0.5em; } .block, li { border: 2px solid blue; padding: 0.5em; } ul { display: flex; list-style: none; } .block { display: block; } </style> </head> <body> <section class="preview"> <p>I am a paragraph. A short one.</p> <ul> <li>Item One</li> <li>Item Two</li> <li>Item Three</li> </ul> <p> I am another paragraph. Some of the <span class="block">words</span> have been wrapped in a <span>span element</span>. </p> </section> <textarea class="playable playable-css" style="height: 400px;"> p, ul { border: 2px solid rebeccapurple; padding: .5em; } .block, li { border: 2px solid blue; padding: .5em; } ul { display: flex; list-style: none; } .block { display: block; } </textarea> <textarea class="playable playable-html" style="height: 180px;"> <p>I am a paragraph. A short one.</p> <ul> <li>Item One</li> <li>Item Two</li> <li>Item Three</li> </ul> <p>I am another paragraph. Some of the <span class="block">words</span> have been wrapped in a <span>span element</span>.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>logical/size-max.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Size: max-inline-size</title> <link rel="stylesheet" href="../css-cookbook/styles.css"> <style> .container { display: flex; } .box { border: 2px solid rgb(96, 139, 168); border-radius: 5px; background-color: rgba(96, 139, 168, .2); padding: 10px; margin: 10px; } </style> <style class="editable"> .box { writing-mode: horizontal-tb; } .physical { max-width: 200px; } .logical { max-inline-size: 200px; } </style> </head> <body> <section class="preview"> <div class="container"> <div class="physical box"> I have a max-width of 200px. </div> <div class="logical box"> I have an max-inline-size of 200px. </div> </div> </section> <textarea class="playable playable-css" style="height: 240px;"> .box { writing-mode: horizontal-tb; } .physical { max-width: 200px; } .logical { max-inline-size: 200px; }</textarea> <textarea class="playable playable-html" style="height: 180px;"> <div class="container"> <div class="physical box"> I have a max-width of 200px. </div> <div class="logical box"> I have an max-inline-size of 200px. </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../css-cookbook/playable.js"></script> </html> <|start_filename|>css-cookbook/card.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>CSS Cookbook: card component</title> <link rel="stylesheet" href="styles.css"> <style> img { max-width: 100%; } .cards { max-width: 800px; margin: 1em auto; } .card { border: 1px solid #999; border-radius: 3px; } .card img { object-fit: cover; width: 100%; height: 100%; } .card h2 { margin: 0; padding: .5rem; } .card .content { padding: .5rem; } .card footer { background-color: #333; color: #fff; padding: .5rem; } </style> <style class="editable"> .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); grid-gap: 20px; } .card { display: grid; grid-template-rows: max-content 200px 1fr; } .card img { object-fit: cover; width: 100%; height: 100%; } </style> </head> <body> <section class="preview"> <div class="cards"> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons.jpg" alt="Hot air balloons"> <div class="content"> <p> The idea of reaching the North Pole by means of balloons appears to have been entertained many years ago. </p> </div> </article> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons2.jpg" alt="Hot air balloons"> <div class="content"> <p>Short content.</p> </div> <footer>I have a footer!</footer> </article> <article class="card"> <header> <h2>A longer heading in this card</h2> </header> <img src="balloons.jpg" alt="Hot air balloons"> <div class="content"> <p>In a curious work, published in Paris in 1863 by <NAME>, there is a suggestion for reaching the North Pole by an aerostat.</p> </div> <footer>I have a footer!</footer> </article> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons2.jpg" alt="Hot air balloons"> <div class="content"> <p> The idea of reaching the North Pole by means of balloons appears to have been entertained many years ago. </p> </div> </article> </div> </section> <textarea class="playable playable-css" style="height: 300px;"> .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); grid-gap: 20px; } .card { display: grid; grid-template-rows: max-content 200px 1fr; } .card img { object-fit: cover; width: 100%; height: 100%; } </textarea> <textarea class="playable playable-html" style="height: 270px;"> <div class="cards"> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons.jpg" alt="Hot air balloons"> <div class="content"> <p> The idea of reaching the North Pole by means of balloons appears to have been entertained many years ago. </p> </div> </article> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons2.jpg" alt="Hot air balloons"> <div class="content"> <p>Short content.</p> </div> <footer>I have a footer!</footer> </article> <article class="card"> <header> <h2>A longer heading in this card</h2> </header> <img src="balloons.jpg" alt="Hot air balloons"> <div class="content"> <p>In a curious work, published in Paris in 1863 by Delaville Dedreux, there is a suggestion for reaching the North Pole by an aerostat.</p> </div> <footer>I have a footer!</footer> </article> <article class="card"> <header> <h2>A short heading</h2> </header> <img src="balloons2.jpg" alt="Hot air balloons"> <div class="content"> <p> The idea of reaching the North Pole by means of balloons appears to have been entertained many years ago. </p> </div> </article> </div> </textarea> <!-- leave everything below here alone --> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="playable.js"></script> </html> <|start_filename|>css-cookbook/columns-grid--download.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <!-- this is an example from the MDN Layout Cookbook --> <title>CSS Cookbook: columns with grid</title> <style> body { background-color: #fff; color: #333; font: 1.2em / 1.5 Helvetica Neue, Helvetica, Arial, sans-serif; padding: 0; margin: 0; } .container { border: 2px solid rgb(75, 70, 74); border-radius: .5em; padding: 20px; width: 500px; display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .container>* { padding: 10px; border: 2px solid rgb(95, 97, 110); border-radius: .5em; margin: 0; } </style> </head> <body> <div class="container"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens.</p> <p>Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Bunya nuts black-eyed pea prairie turnip leek lentil turnip greens parsnip. .</p> </div> </body> </html> <|start_filename|>learn/tasks/rwd/rwd-download.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Responsive Web Design Task: Task</title> <link rel="stylesheet" href="../styles.css"/> <style> * { box-sizing: border-box; } html { font: 1.2em/1.4 Arial, Helvetica, sans-serif; } body { padding: 0 0 1em; } header { background-color: #333; color: #fff; border: 5px solid #000; } header ul { list-style: none; margin: 0; padding: 0; } header a { color: #fff; text-decoration: none; display: block; padding: 0.5em 1em; border-top: 1px solid #999; } header .title { font-size: 150%; font-style: italic; font-weight: bold; padding: 1em; } main { padding: 0 1em; } .cards { list-style: none; margin: 0; padding: 0; } .cards li { border: 5px solid #000; margin-bottom: 1em; } .cards h2 { background-color: #333; color: #fff; margin: 0; padding: 0.5em 1em; } .cards .inner { padding: 0.5em 1em; } .sidebar { background-color: #333; border: 5px solid #000; padding: 0.5em 1em; color: #fff; } </style> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <header> <div class="title">My Website</div> <nav> <ul> <li> <a href="">Link 1</a> </li> <li> <a href="">Link 2</a> </li> <li> <a href="">Link 3</a> </li> </ul> </nav> </header> <main> <article> <h1>This is the main heading</h1> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <ul class="cards"> <li> <h2>Card One</h2> <div class="inner"> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado.</p> </div> </li> <li> <h2>Card Two</h2> <div class="inner"> <p>Daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko.</p> </div> </li> <li> <h2>Card Three</h2> <div class="inner"> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea.</p> </div> </li> <li> <h2>Card Four</h2> <div class="inner"> <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea.</p> </div> </li> <li> <h2>Card Five</h2> <div class="inner"> <p>Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Bunya nuts black-eyed pea prairie turnip leek lentil turnip greens parsnip.</p> </div> </li> </ul> </article> <aside class="sidebar"> <p>Have you discovered all of the other excellent content on this website?</p> </aside> </main> </body> </html> <|start_filename|>learn/selectors/general.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Selectors: General Sibling Combinator </title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> h1 ~ p { font-weight: bold; background-color: #333; color: #fff; padding: .5em; } </style> </head> <body> <section class="preview"> <article> <h1>A heading</h1> <p>I am a paragraph.</p> <div>I am a div</div> <p>I am another paragraph.</p> </article> </section> <textarea class="playable playable-css" style="height: 100px;"> h1 ~ p { font-weight: bold; background-color: #333; color: #fff; padding: .5em; }</textarea> <textarea class="playable playable-html" style="height: 140px;"> <article> <h1>A heading</h1> <p>I am a paragraph.</p> <div>I am a div</div> <p>I am another paragraph.</p> </article> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/values-units/color-rgba.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Values and Units: color rgba codes</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } .wrapper { background-image: url(balloons.jpg); padding: 40px 20px; } .box { padding: 10px; margin: 1em 0; border-radius: 0.5em; } </style> <style class="editable"> .one { background-color: rgba(2, 121, 139, 0.3); } .two { background-color: rgba(197, 93, 161, 0.7); } .three { background-color: rgba(18, 138, 125, 0.9); } </style> </head> <body> <section class="preview"> <div class="wrapper"> <div class="box one">rgba(2, 121, 139, .3)</div> <div class="box two">rgba(197, 93, 161, .7)</div> <div class="box three">rgba(18, 138, 125, .9)</div> </div> </section> <textarea class="playable playable-css" style="height: 240px;"> .one { background-color: rgba(2, 121, 139, .3); } .two { background-color: rgba(197, 93, 161, .7); } .three { background-color: rgba(18, 138, 125, .9); } </textarea> <textarea class="playable playable-html" style="height: 130px;"> <div class="wrapper"> <div class="box one">rgba(2, 121, 139, .3)</div> <div class="box two">rgba(197, 93, 161, .7)</div> <div class="box three">rgba(18, 138, 125, .9)</div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>editable-samples-2/pages/border-top-color/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link href="../../css/editable.css" rel="stylesheet"></link> <link href="css/element.css" rel="stylesheet"></link> </head> <body> <div id="output"> <div id="example-element"> <p>This is a box with a border around it. Note which side of the box is red.</p> </div> </div> <p>Try editing the selected example, or select a different example:</p> <pre class="prettyprint lang-css" id="example-choice-list"><div class=" example-choice">border-top-color: red;</div><div class=" example-choice">border-top-color: rgb(255, 128, 0);</div><div class=" example-choice">border-top-color: hsla(240, 50%, 25%, 0.75);</div><div class=" example-choice">border-top-color: #ffbb00;</div><div class=" example-choice">border-top-color: currentColor;</div><div class=" example-choice">border-top-color: transparent;</div></pre> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> <script type="text/javascript" src="../../js/editable.js"></script> </body> </html> <|start_filename|>learn/cascade/mixing-rules.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>mixing rules</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> h2 { font-size: 2em; color: #000; font-family: Georgia, 'Times New Roman', Times, serif; } .small { font-size: 1em; } .bright { color: rebeccapurple; } </style> </head> <body> <section class="preview"> <h2>Heading with no class</h2> <h2 class="small">Heading with class of small</h2> <h2 class="bright">Heading with class of bright</h2> </section> <textarea class="playable playable-css" style="height: 280px;"> h2 { font-size: 2em; color: #000; font-family: Georgia, 'Times New Roman', Times, serif; } .small { font-size: 1em; } .bright { color: rebeccapurple; } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <h2>Heading with no class</h2> <h2 class="small">Heading with class of small</h2> <h2 class="bright">Heading with class of bright</h2> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>min-max-clamp/index.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>min(), max(), clamp() playground</title> <style> html { font-family: sans-serif; } body { margin: 0 auto; width: min(1000px, calc(70% + 100px)); } h1 { letter-spacing: 2px; font-size: clamp(1.8rem, 2.5vw, 2.8rem) } p { line-height: 1.5; font-size: max(1.2rem, 1.2vw); } </style> </head> <body> <h1>Simple responsive test</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. In orci orci, eleifend id risus nec, mattis rutrum velit. Suspendisse fringilla egestas erat eu convallis. Phasellus eu velit ut magna dapibus elementum cursus at ligula. Ut tempus varius nibh, nec auctor sapien iaculis sit amet. Fusce iaculis, libero quis elementum viverra, nulla ante accumsan lectus, sit amet convallis lacus ipsum vel est. Curabitur et urna non est consectetur pulvinar vel id risus. Ut vestibulum, sem in semper aliquet, felis arcu euismod sapien, ac imperdiet massa nisl quis sem. Vestibulum ac elementum felis, in tempor velit. Pellentesque purus ex, mattis at ornare quis, porta condimentum mi. Donec vestibulum ligula vel nulla blandit, quis euismod nulla vestibulum. Suspendisse potenti. Nunc neque mauris, tempor sed facilisis at, ultrices eget nulla. Pellentesque convallis ante nec augue porttitor, id tempus ante luctus.</p> <p>Integer rutrum sollicitudin tellus, quis cursus nulla scelerisque nec. Nunc eu facilisis lorem. Maecenas faucibus sapien eleifend, semper tellus at, pharetra quam. Cras feugiat vulputate tortor at rhoncus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam non felis quis sem lobortis sodales vel id libero. Phasellus sit amet placerat lorem. </p> </body> </html> <|start_filename|>shapes/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Shapes Examples</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Shapes Examples</h1> <p>These examples are to accompany the Shapes articles on MDN.</p> <h2>Basic concepts</h2> <ol> <li><a href="overview/circle.html">circle()</a></li> <li><a href="overview/box.html">Box values</a></li> <li><a href="overview/image.html">Images</a></li> <li><a href="overview/shape-margin.html">shape-margin</a></li> <li><a href="overview/threshold.html">shape-image-threshold</a></li> <li><a href="overview/generated-content.html">Generated Content</a></li> <li><a href="overview/clip-path.html">clip-path</a></li> </ol> <h2>Box Values</h2> <ol> <li><a href="box/content-box.html">Content Box</a></li> <li><a href="box/padding-box.html">Padding Box</a></li> <li><a href="box/border-box.html">Border Box</a></li> <li><a href="box/margin-box.html">Margin Box</a></li> <li><a href="box/bottom-margin-box.html">Two floated elements, bottom margin</a></li> </ol> <h2>Basic Shapes</h2> <ol> <li><a href="basic-shape/circle.html">circle()</a></li> <li><a href="basic-shape/inset.html">inset()</a></li> <li><a href="basic-shape/inset-box.html">inset() and box values</a></li> <li><a href="basic-shape/circle-generated.html">circle() and generated content</a></li> <li><a href="basic-shape/ellipse.html">ellipse()</a></li> <li><a href="basic-shape/ellipse-keywords.html">ellipse() and keywords</a></li> <li><a href="basic-shape/polygon.html">polygon()</a></li> </ol> <h2>Shapes from Images and Gradients</h2> <ol> <li><a href="image/simple-example.html">Simple image example</a></li> <li><a href="image/threshold.html">shape-image-threshold</a></li> <li><a href="image/margin.html">Image margins</a></li> <li><a href="image/gradient.html">Gradient</a></li> <li><a href="image/radial-gradient.html">Radial Gradients</a></li> <li><a href="image/generated-content.html">With generated content</a></li> </ol> </body> </html> <|start_filename|>css-cookbook/columns-flexbox.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>CSS Cookbook: columns with flexbox</title> <link rel="stylesheet" href="styles.css"> <style> .container { border: 2px solid rgb(75, 70, 74); border-radius: .5em; padding: 20px 10px; } .container>* { padding: 10px; border: 2px solid rgb(95, 97, 110); border-radius: .5em; } </style> <style class="editable"> .container { display: flex; } .container>* { margin: 0 10px; flex: 1; } </style> </head> <body> <section class="preview"> <div class="container"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. </p> </div> </section> <textarea class="playable playable-css"> .container { display: flex; } .container>* { margin: 0 10px; flex: 1; } </textarea> <textarea class="playable playable-html"> <div class="container"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach.</p> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="playable.js"></script> </html> <|start_filename|>learn/images/layout.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Images and other unusual elements: layout</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } </style> <style class="editable"> .wrapper { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 200px 200px; gap: 20px; } .wrapper > div { background-color: rebeccapurple; border-radius: .5em; } </style> </head> <body> <section class="preview"> <div class="wrapper"> <img src="star.png" alt="star"> <div></div> <div></div> <div></div> </div> </section> <textarea class="playable playable-css" style="height: 220px;"> .wrapper { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 200px 200px; gap: 20px; } .wrapper > div { background-color: rebeccapurple; border-radius: .5em; } </textarea> <textarea class="playable playable-html" style="height: 150px;"> <div class="wrapper"> <img src="star.png" alt="star"> <div></div> <div></div> <div></div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/cascade/all.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>all</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> blockquote { background-color: red; border: 2px solid green; } .fix-this { all: unset; } </style> </head> <body> <section class="preview"> <blockquote> <p>This blockquote is styled</p> </blockquote> <blockquote class="fix-this"> <p>This blockquote is not styled</p> </blockquote> </section> <textarea class="playable playable-css" style="height: 280px;"> blockquote { background-color: red; border: 2px solid green; } .fix-this { all: unset; } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <blockquote> <p>This blockquote is styled</p> </blockquote> <blockquote class="fix-this"> <p>This blockquote is not styled</p> </blockquote> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>learn/inspecting/inspecting.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Inspecting CSS</title> <style> body { background-color: #fff; color: #333; font: 1.2em / 1.5 Helvetica Neue, Helvetica, Arial, sans-serif; padding: 0; margin: 0; } .container { padding: 20px 10px; max-width: 900px; margin: 40px auto; } .box1 { width: 400px; margin: 0 0 40px 0; padding: 20px; border: 5px solid rgb(75, 70, 74); border-radius: .5em; } .box2 { box-sizing: border-box; width: 400px; margin: 0 0 40px 0; padding: 20px; border: 5px solid rgb(78, 17, 66); border-radius: .5em; } .special { color: orange; } em { color: hotpink; font-weight: bold; } </style> </head> <body> <div class="container"> <div class="box1"> <p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.</p> </div> <div class="box2"> <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p> </div> <p>Turnip <em class="special">greens</em> yarrow ricebean rutabaga endive cauliflower <em>sea lettuce</em> kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. </p> </div> </body> </html> <|start_filename|>learn/writing-modes/inline-size.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Backgrounds and Borders: inline-size</title> <link rel="stylesheet" href="../styles.css" /> <style> * { box-sizing: border-box; } .wrapper { display: flex; } .box { border: 1px solid #ccc; padding: .5em; margin: 10px; } </style> <style class="editable"> .box { inline-size: 150px; } .horizontal { writing-mode: horizontal-tb; } .vertical { writing-mode: vertical-rl; } </style> </head> <body> <section class="preview"> <div class="wrapper"> <div class="box horizontal"> <h2>Heading</h2> <p>A paragraph. Demonstrating Writing Modes in CSS.</p> <p>These boxes have inline-size.</p> </div> <div class="box vertical"> <h2>Heading</h2> <p>A paragraph. Demonstrating Writing Modes in CSS.</p> <p>These boxes have inline-size.</p> </div> </div> </section> <textarea class="playable playable-css" style="height: 200px;"> .box { inline-size: 150px; } .horizontal { writing-mode: horizontal-tb; } .vertical { writing-mode: vertical-rl; } </textarea> <textarea class="playable playable-html" style="height: 230px;"> <div class="wrapper"> <div class="box horizontal"> <h2>Heading</h2> <p>A paragraph. Demonstrating Writing Modes in CSS.</p> <p>These boxes have inline-size.</p> </div> <div class="box vertical"> <h2>Heading</h2> <p>A paragraph. Demonstrating Writing Modes in CSS.</p> <p>These boxes have inline-size.</p> </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset" /> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>backdrop/script.js<|end_filename|> // Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ window.addEventListener("load", doStartup, false); function doStartup(event) { document.fullscreenElement = document.fullscreenElement || document.mozFullscreenElement || document.msFullscreenElement || document.webkitFullscreenDocument; document.exitFullscreen = document.exitFullscreen || document.mozExitFullscreen || document.msExitFullscreen || document.webkitExitFullscreen; document.addEventListener("keypress", handleKeypress, false); } function handleKeypress(event) { if (event.keyCode === 13) { toggleFullscreen(); } } function toggleFullscreen() { let elem = document.querySelector("video"); elem.requestFullscreen = elem.requestFullscreen || elem.mozRequestFullscreen || elem.msRequestFullscreen || elem.webkitRequestFullscreen; if (!document.fullscreenElement) { elem.requestFullscreen().then({}).catch(err => { alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } } <|start_filename|>learn/cascade/specificity-boxes.html<|end_filename|> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>specificity demo</title> <link rel="stylesheet" href="../styles.css"> <style> </style> <style class="editable"> /* specificity: 0101 */ #outer a { background-color: red; } /* specificity: 0201 */ #outer #inner a { background-color: blue; } /* specificity: 0104 */ #outer div ul li a { color: yellow; } /* specificity: 0113 */ #outer div ul .nav a { color: white; } /* specificity: 0024 */ div div li:nth-child(2) a:hover { border: 10px solid black; } /* specificity: 0023 */ div li:nth-child(2) a:hover { border: 10px dashed black; } /* specificity: 0033 */ div div .nav:nth-child(2) a:hover { border: 10px double black; } a { display: inline-block; line-height: 40px; font-size: 20px; text-decoration: none; text-align: center; width: 200px; margin-bottom: 10px; } ul { padding: 0; } li { list-style-type: none; } </style> </head> <body> <section class="preview"> <div id="outer" class="container"> <div id="inner" class="container"> <ul> <li class="nav"><a href="#">One</a></li> <li class="nav"><a href="#">Two</a></li> </ul> </div> </div> </section> <textarea class="playable playable-css" style="height: 280px;"> /* specificity: 0101 */ #outer a { background-color: red; } /* specificity: 0201 */ #outer #inner a { background-color: blue; } /* specificity: 0104 */ #outer div ul li a { color: yellow; } /* specificity: 0113 */ #outer div ul .nav a { color: white; } /* specificity: 0024 */ div div li:nth-child(2) a:hover { border: 10px solid black; } /* specificity: 0023 */ div li:nth-child(2) a:hover { border: 10px dashed black; } /* specificity: 0033 */ div div .nav:nth-child(2) a:hover { border: 10px double black; } a { display: inline-block; line-height: 40px; font-size: 20px; text-decoration: none; text-align: center; width: 200px; margin-bottom: 10px; } ul { padding: 0; } li { list-style-type: none; } </textarea> <textarea class="playable playable-html" style="height: 140px;"> <div id="outer" class="container"> <div id="inner" class="container"> <ul> <li class="nav"><a href="#">One</a></li> <li class="nav"><a href="#">Two</a></li> </ul> </div> </div> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> </div> </body> <script src="../playable.js"></script> </html> <|start_filename|>overscroll-behavior/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>overscroll-behavior demo</title> <link href="style.css" rel="stylesheet"> <script src="main.js" defer></script> </head> <body> <header> <h1>overscroll-behavior demo</h1> </header> <main> </main> <section class="chatbox"> <header> <h2>Active chat</h2> </header> <div class="messages"> <p class="me">Chris: Hello!</p> <p class="you">Bob: I am well — how are you?</p> <p class="me">Chris: Fine thanks, just documenting overscroll-behavior</p> <p class="you">Bob: Oooh, sounds hard!</p> <p class="me">Chris: Nah, it's OK really. It is a useful property to have for mobile apps especially.</p> <p class="you">Bob: Cool, where can I learn more?</p> </div> <form> <input type="text" aria-label="Enter your chat message here" autofocus> <button>Send</button> </form> </section> <footer> <p>Copyright nobody; inspired by <a href="https://ebidel.github.io/demos/chatbox.html">ebidel's chatbox demo</a>.</p> </footer> </body> </html> <|start_filename|>counter-style-demo/js/script.js<|end_filename|> (function () { var $styleSelect = document.querySelector('#style-select'), $demoList = document.querySelector('#demo-list'), $codeContainer = document.querySelector('#code'); var examples = { 'cyclic': { code: [ '@counter-style blacknwhite {\n', ' system: cyclic;\n', ' symbols: ◆ ◇;\n', ' suffix: " ";\n', '}\n\n', 'ul {\n', ' list-style: blacknwhite;\n', '}' ].join('') }, 'fixed': { code: [ '@counter-style circled-digits {\n', ' system: fixed;\n', ' symbols:          ;\n', ' suffix: " ";\n', '}\n\n', 'ul {\n', ' list-style: circled-digits;\n', '}' ].join('') }, 'symbolic': { code: [ '@counter-style cs-symbolic {\n', ' system: symbolic;\n', " symbols: '0' '1' '2' '3' '4' '5' '6' '7' '8' '9';\n", ' range: 1 15;\n', ' suffix: " ";\n', '}\n\n', 'ul {\n', ' list-style: cs-symbolic;\n', '}' ].join('') }, 'alphabetic': { code: [ '@counter-style cs-alphabetic {\n', ' system: alphabetic;\n', " symbols: A B C D E;\n", ' suffix: " ";\n', '}\n\n', 'ul {\n', ' list-style: cs-alphabetic;\n', '}' ].join('') }, 'numeric': { code: [ '@counter-style cs-numeric {\n', ' system: numeric;\n', " symbols: A B C D E;\n", ' suffix: " ";\n', '}\n\n', 'ul {\n', ' list-style: cs-numeric;\n', '}' ].join('') }, 'additive': { code: [ '@counter-style cs-additive-roman {\n', ' system: additive;\n', " range: 1 100;\n", ' additive-symbols: 100 C, 90 XC, 50 L, 40 XL, 10 X, 9 IX, 5 V, 4 IV, 1 I;\n', '}\n\n', 'ul {\n', ' list-style: cs-additive-roman;\n', '}' ].join('') }, 'extends': { code: [ '@counter-style cs-extends {\n', ' system: extends decimal;\n', " prefix: '(';\n", " suffix: ') ';\n", '}\n\n', 'ul {\n', ' list-style: cs-extends;\n', '}' ].join('') }, 'decimal': { code: [ 'ul {\n', ' list-style: decimal;\n', '}', ].join('') }, 'decimal-leading-zero': { code: [ 'ul {\n', ' list-style: decimal-leading-zero;\n', '}', ].join('') }, 'arabic-indic': { code: [ 'ul {\n', ' list-style: arabic-indic;\n', '}', ].join('') }, 'armenian': { code: [ 'ul {\n', ' list-style: armenian;\n', '}', ].join('') }, 'upper-armenian': { code: [ 'ul {\n', ' list-style: upper-armenian;\n', '}', ].join('') }, 'lower-armenian': { code: [ 'ul {\n', ' list-style: lower-armenian;\n', '}', ].join('') }, 'bengali': { code: [ 'ul {\n', ' list-style: bengali;\n', '}', ].join('') }, 'cambodian': { code: [ 'ul {\n', ' list-style: cambodian;\n', '}', ].join('') }, 'khmer': { code: [ 'ul {\n', ' list-style: khmer;\n', '}', ].join('') }, 'cjk-decimal': { code: [ 'ul {\n', ' list-style: cjk-decimal;\n', '}', ].join('') }, 'devanagiri': { code: [ 'ul {\n', ' list-style: devanagiri;\n', '}', ].join('') }, 'georgian': { code: [ 'ul {\n', ' list-style: georgian;\n', '}', ].join('') }, 'gujarati': { code: [ 'ul {\n', ' list-style: gujarati;\n', '}', ].join('') }, 'gurmukhi': { code: [ 'ul {\n', ' list-style: gurmukhi;\n', '}', ].join('') }, 'hebrew': { code: [ 'ul {\n', ' list-style: hebrew;\n', '}', ].join('') }, 'kannada': { code: [ 'ul {\n', ' list-style: kannada;\n', '}', ].join('') }, 'lao': { code: [ 'ul {\n', ' list-style: lao;\n', '}', ].join('') }, 'malayalam': { code: [ 'ul {\n', ' list-style: malayalam;\n', '}', ].join('') }, 'mongolian': { code: [ 'ul {\n', ' list-style: mongolian;\n', '}', ].join('') }, 'myanmar': { code: [ 'ul {\n', ' list-style: myanmar;\n', '}', ].join('') }, 'oriya': { code: [ 'ul {\n', ' list-style: oriya;\n', '}', ].join('') }, 'persian': { code: [ 'ul {\n', ' list-style: persian;\n', '}', ].join('') }, 'lower-roman': { code: [ 'ul {\n', ' list-style: lower-roman;\n', '}', ].join('') }, 'upper-roman': { code: [ 'ul {\n', ' list-style: upper-roman;\n', '}', ].join('') }, 'telugu': { code: [ 'ul {\n', ' list-style: telugu;\n', '}', ].join('') }, 'thai': { code: [ 'ul {\n', ' list-style: thai;\n', '}', ].join('') }, 'tibetan': { code: [ 'ul {\n', ' list-style: tibetan;\n', '}', ].join('') }, 'lower-alpha': { code: [ 'ul {\n', ' list-style: lower-alpha;\n', '}', ].join('') }, 'lower-latin': { code: [ 'ul {\n', ' list-style: lower-latin;\n', '}', ].join('') }, 'upper-alpha': { code: [ 'ul {\n', ' list-style: upper-alpha;\n', '}', ].join('') }, 'upper-latin': { code: [ 'ul {\n', ' list-style: upper-latin;\n', '}', ].join('') }, 'cjk-earthly-branch': { code: [ 'ul {\n', ' list-style: cjk-earthly-branch;\n', '}', ].join('') }, 'cjk-heavenly-stem': { code: [ 'ul {\n', ' list-style: cjk-heavenly-stem;\n', '}', ].join('') }, 'lower-greek': { code: [ 'ul {\n', ' list-style: lower-greek;\n', '}', ].join('') }, 'hiragana': { code: [ 'ul {\n', ' list-style: hiragana;\n', '}', ].join('') }, 'hiragana-iroha': { code: [ 'ul {\n', ' list-style: hiragana-iroha;\n', '}', ].join('') }, 'katakana': { code: [ 'ul {\n', ' list-style: katakana;\n', '}', ].join('') }, 'katakana-iroha': { code: [ 'ul {\n', ' list-style: katakana-iroha;\n', '}', ].join('') }, 'disc': { code: [ 'ul {\n', ' list-style: disc;\n', '}', ].join('') }, 'circle': { code: [ 'ul {\n', ' list-style: circle;\n', '}', ].join('') }, 'square': { code: [ 'ul {\n', ' list-style: square;\n', '}', ].join('') }, 'disclosure-open': { code: [ 'ul {\n', ' list-style: disclosure-open;\n', '}', ].join('') }, 'disclosure-closed': { code: [ 'ul {\n', ' list-style: disclosure-closed;\n', '}', ].join('') }, 'japanese-informal': { code: [ 'ul {\n', ' list-style: japanese-informal;\n', '}', ].join('') }, 'japanese-formal': { code: [ 'ul {\n', ' list-style: japanese-formal;\n', '}', ].join('') }, 'korean-hangul-formal': { code: [ 'ul {\n', ' list-style: korean-hangul-formal;\n', '}', ].join('') }, 'korean-hanja-informal': { code: [ 'ul {\n', ' list-style: korean-hanja-informal;\n', '}', ].join('') }, 'korean-hanja-formal': { code: [ 'ul {\n', ' list-style: korean-hanja-formal;\n', '}', ].join('') }, 'simp-chinese-informal': { code: [ 'ul {\n', ' list-style: simp-chinese-informal;\n', '}', ].join('') }, 'simp-chinese-formal': { code: [ 'ul {\n', ' list-style: simp-chinese-formal;\n', '}', ].join('') }, 'trad-chinese-informal': { code: [ 'ul {\n', ' list-style: trad-chinese-informal;\n', '}', ].join('') }, 'trad-chinese-formal': { code: [ 'ul {\n', ' list-style: trad-chinese-formal;\n', '}', ].join('') }, 'cjk-ideographic': { code: [ 'ul {\n', ' list-style: cjk-ideographic;\n', '}', ].join('') }, 'ethiopic-numeric': { code: [ 'ul {\n', ' list-style: ethiopic-numeric;\n', '}', ].join('') } }; $styleSelect.value = 'cyclic'; $styleSelect.addEventListener('change', function (e) { var selectedKey = $styleSelect.value; $codeContainer.innerHTML = examples[selectedKey].code; $demoList.className = 'demo-' + selectedKey; }); })(); <|start_filename|>counter-style-demo/index.html<|end_filename|> <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>CSS @counter-style Demo</title> <link rel="stylesheet" href="css/style.css"/> </head> <body> <div class="header"> <h1>CSS @counter-style Demo</h1> </div> <div class="list-container"> <ul id="demo-list" class="demo-cyclic"> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> <li>Six</li> <li>Seven</li> <li>Eight</li> <li>Nine</li> <li>Ten</li> <li>Eleven</li> <li>Twelve</li> <li>Thirteen</li> <li>Fourteen</li> <li>Fifteen</li> <li>Sixteen</li> <li>Seventeen</li> <li>Eighteen</li> <li>Nineteen</li> <li>Twenty</li> <li>Twenty One</li> <li>Twenty Two</li> <li>Twenty Three</li> <li>Twenty Four</li> <li>Twenty Five</li> <li>Twenty Six</li> <li>Twenty Seven</li> <li>Twenty Eight</li> <li>Twenty Nine</li> <li>Thirty</li> </ul> </div> <div class="list-controls"> <h3>Select a counter style from the list</h3> <select id="style-select"> <optgroup label="@counter-style system"> <option value="cyclic">cyclic</option> <option value="fixed">fixed</option> <option value="symbolic">symbolic</option> <option value="alphabetic">alphabetic</option> <option value="numeric">numeric</option> <option value="additive">additive</option> <option value="extends">extends</option> </optgroup> <optgroup label="Predefined styles"> <option disabled>Numeric ▼</option> <option value="decimal">decimal</option> <option value="decimal-leading-zero">decimal-leading-zero</option> <option value="arabic-indic">arabic-indic</option> <option value="armenian">armenian</option> <option value="upper-armenian">upper-armenian</option> <option value="lower-armenian">lower-armenian</option> <option value="bengali">bengali</option> <option value="cambodian">cambodian</option> <option value="khmer">khmer</option> <option value="cjk-decimal">cjk-decimal</option> <option value="devanagiri">devanagiri</option> <option value="georgian">georgian</option> <option value="gujarati">gujarati</option> <option value="gurmukhi">gurmukhi</option> <option value="hebrew">hebrew</option> <option value="kannada">kannada</option> <option value="lao">lao</option> <option value="malayalam">malayalam</option> <option value="mongolian">mongolian</option> <option value="myanmar">myanmar</option> <option value="oriya">oriya</option> <option value="persian">persian</option> <option value="lower-roman">lower-roman</option> <option value="upper-roman">upper-roman</option> <option value="telugu">telugu</option> <option value="thai">thai</option> <option value="tibetan">tibetan</option> <option value="lower-alpha">lower-alpha</option> <option value="upper-alpha">upper-alpha</option> <option disabled>Alphabetic ▼</option> <option value="lower-alpha">lower-alpha</option> <option value="lower-latin">lower-latin</option> <option value="upper-alpha">upper-alpha</option> <option value="upper-latin">upper-latin</option> <option value="cjk-earthly-branch">cjk-earthly-branch</option> <option value="cjk-heavenly-stem">cjk-heavenly-stem</option> <option value="lower-greek">lower-greek</option> <option value="hiragana">hiragana</option> <option value="hiragana-iroha">hiragana-iroha</option> <option value="katakana">katakana</option> <option value="katakana-iroha">katakana-iroha</option> <option disabled>Symbolic ▼</option> <option value="disc">disc</option> <option value="circle">circle</option> <option value="square">square</option> <option value="disclosure-open">disclosure-open</option> <option value="disclosure-closed">disclosure-closed</option> <option disabled>Predefined complex styles ▼</option> <option value="japanese-informal">japanese-informal</option> <option value="japanese-formal">japanese-formal</option> <option value="korean-hangul-formal">korean-hangul-formal</option> <option value="korean-hanja-informal">korean-hanja-informal</option> <option value="korean-hanja-formal">korean-hanja-formal</option> <option value="simp-chinese-informal">simp-chinese-informal</option> <option value="simp-chinese-formal">simp-chinese-formal</option> <option value="trad-chinese-informal">trad-chinese-informal</option> <option value="trad-chinese-formal">trad-chinese-formal</option> <option value="cjk-ideographic">cjk-ideographic</option> <option value="ethiopic-numeric">ethiopic-numeric</option> </optgroup> </select> <pre class="code" id="code"> @counter-style blacknwhite { system: cyclic; symbols: ◆ ◇; suffix: " "; } ul { list-style: blacknwhite; }</pre> </div> <div class="notes-section"> <i>Read more about <code>@counter-style</code> on <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style">Mozilla Developer Network</a></i> </div> <script src="js/script.js"></script> </body> </html>
doc22940/css-examples
<|start_filename|>src/seabolt/src/bolt/communication-plain-posix.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "communication-plain.h" #include "status-private.h" #include <pthread.h> #include <errno.h> int socket_last_error(BoltCommunication* comm) { UNUSED(comm); return errno; } int socket_transform_error(BoltCommunication* comm, int error_code) { UNUSED(comm); switch (error_code) { case EACCES: case EPERM: return BOLT_PERMISSION_DENIED; case EAFNOSUPPORT: case EINVAL: case EPROTONOSUPPORT: return BOLT_UNSUPPORTED; case EMFILE: case ENFILE: return BOLT_OUT_OF_FILES; case ENOBUFS: case ENOMEM: return BOLT_OUT_OF_MEMORY; case ECONNREFUSED: return BOLT_CONNECTION_REFUSED; case ECONNRESET: return BOLT_CONNECTION_RESET; case EPIPE: return BOLT_CONNECTION_RESET; case EINTR: return BOLT_INTERRUPTED; case ENETUNREACH: return BOLT_NETWORK_UNREACHABLE; case EAGAIN: case ETIMEDOUT: return BOLT_TIMED_OUT; default: return BOLT_UNKNOWN_ERROR; } } int socket_ignore_sigpipe(void** replaced_action) { #if !defined(SO_NOSIGPIPE) sigset_t sig_block, sig_restore, sig_pending; sigemptyset(&sig_block); sigaddset(&sig_block, SIGPIPE); int result = pthread_sigmask(SIG_BLOCK, &sig_block, &sig_restore); if (result!=0) { return result; } int sigpipe_pending = -1; if (sigpending(&sig_pending)!=-1) { sigpipe_pending = sigismember(&sig_pending, SIGPIPE); } if (sigpipe_pending==-1) { pthread_sigmask(SIG_SETMASK, &sig_restore, NULL); return -1; } if (*replaced_action==NULL) { *replaced_action = malloc(sizeof(sigset_t)); } memcpy(*replaced_action, &sig_restore, sizeof(sigset_t)); return 0; #endif UNUSED(replaced_action); return BOLT_SUCCESS; } int socket_restore_sigpipe(void** action_to_restore) { #if !defined(SO_NOSIGPIPE) if (action_to_restore!=NULL) { sigset_t sig_block; sigemptyset(&sig_block); sigaddset(&sig_block, SIGPIPE); struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 0; while (sigtimedwait(&sig_block, 0, &ts)==-1) { if (errno!=EINTR) { break; } } pthread_sigmask(SIG_SETMASK, (sigset_t*) *action_to_restore, NULL); free(*action_to_restore); *action_to_restore = NULL; return 0; } #endif UNUSED(action_to_restore); return BOLT_SUCCESS; } int socket_disable_sigpipe(int sockfd) { #if defined(SO_NOSIGPIPE) int no = 0; return setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &no, sizeof(no)); #else UNUSED(sockfd); return 0; #endif } int socket_set_blocking_mode(int sockfd, int blocking) { const int flags = fcntl(sockfd, F_GETFL, 0); if ((flags & O_NONBLOCK) && !blocking) { return 0; } if (!(flags & O_NONBLOCK) && blocking) { return 0; } return fcntl(sockfd, F_SETFL, blocking ? flags ^ O_NONBLOCK : flags | O_NONBLOCK); } int socket_set_recv_timeout(int sockfd, int timeout) { struct timeval recv_timeout; socklen_t recv_timeout_size = sizeof(struct timeval); recv_timeout.tv_sec = timeout/1000; recv_timeout.tv_usec = (timeout%1000)*1000; return setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &recv_timeout, recv_timeout_size); } int socket_set_keepalive(int sockfd, int keepalive) { return setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)); } int socket_set_nodelay(int sockfd, int nodelay) { return setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)); } int socket_open(int domain, int type, int protocol) { return socket(domain, type, protocol); } int socket_shutdown(int sockfd) { return shutdown(sockfd, SHUT_RDWR); } int socket_close(int sockfd) { return close(sockfd); } int socket_connect(int sockfd, const struct sockaddr* addr, socklen_t addrlen, int* in_progress) { int status = connect(sockfd, addr, addrlen); *in_progress = status==-1 && errno==EINPROGRESS; return status; } int socket_send(int sockfd, const void* buf, int len, int flags) { return (int) send(sockfd, buf, len, flags); } int socket_recv(int sockfd, void* buf, int len, int flags) { return (int) recv(sockfd, buf, len, flags); } int socket_get_local_addr(int sockfd, struct sockaddr_storage* address, socklen_t* address_size) { return getsockname(sockfd, (struct sockaddr*) address, address_size); } int socket_select(int sockfd, int timeout) { // connection in progress fd_set write_set; FD_ZERO(&write_set); FD_SET(sockfd, &write_set); struct timeval select_timeout; select_timeout.tv_sec = timeout/1000; select_timeout.tv_usec = (timeout%1000)*1000; int status = select(FD_SETSIZE, NULL, &write_set, NULL, &select_timeout); if (status==1) { int so_error = 0; socklen_t so_error_len = sizeof(int); getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &so_error_len); if (so_error!=0) { errno = so_error; return -1; } } return status; } int socket_lifecycle_startup() { return 0; } int socket_lifecycle_shutdown() { return 0; } <|start_filename|>src/seabolt/src/bolt/no-pool.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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. */ /** * @file */ #ifndef SEABOLT_NO_POOL_H #define SEABOLT_NO_POOL_H #include "communication-secure.h" #include "connector.h" #include "sync.h" /** * Pooling contract for a no-pooling connection acquisition */ struct BoltNoPool { mutex_t mutex; char* id; struct BoltAddress* address; const struct BoltValue* auth_token; const struct BoltConfig* config; volatile int size; volatile BoltConnection** connections; }; #define SIZE_OF_NO_POOL sizeof(struct BoltNoPool) #define SIZE_OF_NO_POOL_PTR sizeof(struct BoltNoPool*) struct BoltNoPool* BoltNoPool_create(const struct BoltAddress* address, const struct BoltValue* auth_token, const struct BoltConfig* config); void BoltNoPool_destroy(struct BoltNoPool* pool); BoltConnection* BoltNoPool_acquire(struct BoltNoPool* pool, BoltStatus* status); int BoltNoPool_release(struct BoltNoPool* pool, struct BoltConnection* connection); #endif //SEABOLT_POOLING_H <|start_filename|>src/seabolt/src/bolt/address-set-private.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ADDRESS_SET_PRIVATE_H #define SEABOLT_ADDRESS_SET_PRIVATE_H #include "address-set.h" struct BoltAddressSet { volatile int32_t size; volatile BoltAddress** elements; }; #define SIZE_OF_ADDRESS_SET sizeof(struct BoltAddressSet) #define SIZE_OF_ADDRESS_SET_PTR sizeof(struct BoltAddressSet*) volatile BoltAddressSet* BoltAddressSet_create(); void BoltAddressSet_destroy(volatile BoltAddressSet* set); int32_t BoltAddressSet_size(volatile BoltAddressSet* set); int32_t BoltAddressSet_index_of(volatile BoltAddressSet* set, volatile const BoltAddress* address); int32_t BoltAddressSet_remove(volatile BoltAddressSet* set, volatile const BoltAddress* address); void BoltAddressSet_replace(volatile BoltAddressSet* destination, volatile BoltAddressSet* source); void BoltAddressSet_add_all(volatile BoltAddressSet* destination, volatile BoltAddressSet* source); #endif //SEABOLT_ADDRESS_SET_PRIVATE_H <|start_filename|>src/seabolt/src/bolt/address-private.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ADDRESS_PRIVATE_H #define SEABOLT_ADDRESS_PRIVATE_H #include "address.h" #include "sync.h" struct BoltAddress { /// Original host name or IP address string const char* host; /// Original service name or port number string const char* port; /// Number of resolved IP addresses volatile int n_resolved_hosts; /// Resolved IP address data volatile struct sockaddr_storage* resolved_hosts; /// Resolved port number uint16_t resolved_port; // Lock to protect DNS resolution process rwlock_t lock; }; #ifdef __cplusplus #define BoltAddress_of(host, port) { (const char *)host, (const char *)port, 0, nullptr, 0, nullptr } #else #define BoltAddress_of(host, port) (BoltAddress) { (const char *)host, (const char *)port, 0, NULL, 0, NULL } #endif BoltAddress* BoltAddress_create_with_lock(const char* host, const char* port); BoltAddress* BoltAddress_create_from_string(const char* endpoint_str, uint64_t endpoint_len); /** * Resolves the original host and port into one or more IP addresses and * a port number. * * This can be carried out more than once on the same * address. Any newly-resolved addresses will replace any previously stored. * * The name resolution is a synchronized operation, i.e. concurrent resolution requests on the same * instance are protected by a mutex. * * @param address the instance to be resolved. * @param n_resolved number of resolved addresses that will be set upon successful resolution. * @param log an optional \ref BoltLog instance to be used for logging purposes. * @returns 0 for success, and non-zero error codes returned from getaddrinfo call on error. */ int32_t BoltAddress_resolve(BoltAddress* address, int32_t* n_resolved, BoltLog* log); /** * Copies the textual representation of the resolved IP address at the specified index into an already * allocated buffer. * * If successful, AF_INET or AF_INET6 is returned depending on the address family. If unsuccessful, -1 is returned. * Failure may be a result of a system problem or because the supplied buffer is too small for the address. * * @param address the instance to be queried. * @param index index of the resolved IP address * @param buffer destination buffer to write the IP address's string representation * @param buffer_size size of the buffer * @return address family (AF_INET or AF_INET6) or -1 on error */ int32_t BoltAddress_copy_resolved_host(BoltAddress* address, int32_t index, char* buffer, int32_t buffer_size); /** * Returns the number of resolved addresses after call to BoltAddress_resolve. * * @param address the instance to be queried. * @return number of resolved entities. */ int32_t BoltAddress_resolved_count(BoltAddress* address); /** * Copies the resolved address entity at index to the passed in target. * * @param address the instance to be queried. * @param index the index of the component to get. * @param target the target memory where the entity will be copied. * @return 1 on success, 0 otherwise. */ int BoltAddress_resolved_addr(BoltAddress* address, int32_t index, struct sockaddr_storage* target); #endif //SEABOLT_ADDRESS_PRIVATE_H <|start_filename|>src/seabolt/src/bolt/address-set.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ALL_ADDRESS_SET_H #define SEABOLT_ALL_ADDRESS_SET_H #include "bolt-public.h" #include "address.h" /** * The type that represents a set of \ref BoltAddress instances. * * It is the destination data structure for a custom \ref BoltAddressResolver to provide its resolved * addresses. */ typedef struct BoltAddressSet BoltAddressSet; /** * Adds a \ref BoltAddress instance to the set, if it's not present. * * @param set the target set instance. * @param address the address instance to be added to the set. * @returns -1 if the provided address is already a member of the set, or the index at which the given address * is added. */ SEABOLT_EXPORT int32_t BoltAddressSet_add(volatile BoltAddressSet* set, volatile const BoltAddress* address); #endif //SEABOLT_ALL_ADDRESS_SET_H <|start_filename|>src/seabolt/src/bolt/string-builder.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_STRING_BUILDER_H #define SEABOLT_STRING_BUILDER_H #include <stdint.h> struct StringBuilder { char* buffer; int buffer_size; int buffer_pos; }; struct StringBuilder* StringBuilder_create(); void StringBuilder_destroy(struct StringBuilder* builder); void StringBuilder_append(struct StringBuilder* builder, const char* string); void StringBuilder_append_n(struct StringBuilder* builder, const char* string, const int len); void StringBuilder_append_f(struct StringBuilder* builder, const char* format, ...); char* StringBuilder_get_string(struct StringBuilder* builder); int StringBuilder_get_length(struct StringBuilder* builder); #endif //SEABOLT_STRING_BUILDER_H <|start_filename|>src/seabolt/src/bolt/values.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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. */ /** * @file */ #ifndef SEABOLT_VALUES #define SEABOLT_VALUES #include <limits.h> #include <stdio.h> #include <stdint.h> #include "bolt-public.h" #if CHAR_BIT!=8 #error "Cannot compile if `char` is not 8-bit" #endif /** * The list of types available in the Bolt type system. */ enum BoltType { BOLT_NULL = 0, BOLT_BOOLEAN = 1, BOLT_INTEGER = 2, BOLT_FLOAT = 3, BOLT_STRING = 4, BOLT_DICTIONARY = 5, BOLT_LIST = 6, BOLT_BYTES = 7, BOLT_STRUCTURE = 8, }; /** * The type that holds one of the supported values as defined by \ref BoltType. */ typedef struct BoltValue BoltValue; /** * Creates a new instance of \ref BoltValue. * * @return the pointer to the newly allocated \ref BoltValue instance. */ SEABOLT_EXPORT BoltValue* BoltValue_create(); /** * Destroys the passed \ref BoltValue instance. * * @param value the instance to be destroyed. */ SEABOLT_EXPORT void BoltValue_destroy(BoltValue* value); /** * Duplicates the passed \ref BoltValue instance. * * It's the caller's responsibility to destroy the returned instance. * * @param value the instance to be duplicated. * @returns a pointer to the newly allocated and populated \ref BoltValue instance. */ SEABOLT_EXPORT BoltValue* BoltValue_duplicate(const BoltValue* value); /** * Deep copies the passed \ref BoltValue instance to another one. * * Any existing information present in the _dest_ instance will be cleared out. * * @param dest the destination instance. * @param src the source instance. */ SEABOLT_EXPORT void BoltValue_copy(BoltValue* dest, const BoltValue* src); /** * Returns the size of the passed \ref BoltValue instance. * * @param value the instance to be queried. * @returns the size. */ SEABOLT_EXPORT int32_t BoltValue_size(const BoltValue* value); /** * Returns the type of the passed \ref BoltValue instance. * * @param value the instance to be queried. * @returns the type. */ SEABOLT_EXPORT enum BoltType BoltValue_type(const BoltValue* value); /** * Copies the string representation of the passed \ref BoltValue instance to the provided buffers. * * @param value the instance to be stringified. * @param dest the destination buffer to copy the string representation. If no truncation occurs due to the * buffer size being smaller than required, the string written will be terminated by '\0'. * @param length the length of the destination buffer. * @param connection the optional connection instance related with this \ref BoltValue. This is only useful for * \ref BOLT_STRUCTURE typed values and the known pretty names (Node, Relation, Duration, etc.) will be * printed rather than its type code. * @return the number of characters written to the destination buffer. If returned value is > length, it means that * the string representation is truncated and not terminated by '\0'. Another call with an adequate sized * buffer will ensure the full string represention to be available to the caller. */ SEABOLT_EXPORT int32_t BoltValue_to_string(const BoltValue* value, char* dest, int32_t length, BoltConnection* connection); /** * Sets the passed \ref BoltValue instance to null. * * @param value the instance to be updated */ SEABOLT_EXPORT void BoltValue_format_as_Null(BoltValue* value); /** * Sets the passed \ref BoltValue instance to \ref BOLT_BOOLEAN. * * @param value the instance to be updated * @param data the boolean value to set, 1 for TRUE, 0 for FALSE. */ SEABOLT_EXPORT void BoltValue_format_as_Boolean(BoltValue* value, char data); /** * Gets the boolean value stored in the passed \ref BoltValue instance. * * @param value the instance to be queried * @returns 1 for TRUE, 0 for FALSE. */ SEABOLT_EXPORT char BoltBoolean_get(const BoltValue* value); /** * Sets the passed \ref BoltValue instance to \ref BOLT_INTEGER. * * @param value the instance to be updated * @param data the integer value to set. */ SEABOLT_EXPORT void BoltValue_format_as_Integer(BoltValue* value, int64_t data); /** * Gets the integer value stored in the passed \ref BoltValue instance. * * @param value the instance to be queried * @returns the integer value stored. */ SEABOLT_EXPORT int64_t BoltInteger_get(const BoltValue* value); /** * Sets the passed \ref BoltValue instance to \ref BOLT_FLOAT. * * @param value the instance to be updated * @param data the float value to set. */ SEABOLT_EXPORT void BoltValue_format_as_Float(BoltValue* value, double data); /** * Gets the float value stored in the passed \ref BoltValue instance. * * @param value the instance to be queried * @returns the float value stored. */ SEABOLT_EXPORT double BoltFloat_get(const BoltValue* value); /** * Sets the passed \ref BoltValue instance to \ref BOLT_STRING. * * @param value the instance to be updated * @param data the string buffer containing the value to be set. * @param length the length of the string buffer. */ SEABOLT_EXPORT void BoltValue_format_as_String(BoltValue* value, const char* data, int32_t length); /** * Gets the string buffer stored in the passed \ref BoltValue instance. * * @param value the instance to be queried * @returns the string buffer. Actual length of the string can be queried by a call to \ref BoltValue_size. */ SEABOLT_EXPORT char* BoltString_get(const BoltValue* value); /** * Sets the passed \ref BoltValue instance to \ref BOLT_DICTIONARY. * * @param value the instance to be updated * @param length the number of entries. */ SEABOLT_EXPORT void BoltValue_format_as_Dictionary(BoltValue* value, int32_t length); /** * Returns an instance to a \ref BoltValue identifying the _key_ at _index_. * * @param value the instance to be queried * @param index the index of the key. * @returns \ref BoltValue instance identifying the key. */ SEABOLT_EXPORT BoltValue* BoltDictionary_key(const BoltValue* value, int32_t index); /** * Returns the string buffer identifying the _key_ at _index_. * * @param value the instance to be queried * @param index the index of the key. * @returns the string buffer identifying the key. */ SEABOLT_EXPORT const char* BoltDictionary_get_key(const BoltValue* value, int32_t index); /** * Returns the size of the string buffer identifying the _key_ at _index_. * * @param value the instance to be queried * @param index the index of the key. * @returns size of the string buffer identifying the key. */ SEABOLT_EXPORT int32_t BoltDictionary_get_key_size(const BoltValue* value, int32_t index); /** * Returns the index of a _key_ if it is present in the passed \ref BoltValue instance. * * @param value the instance to be queried. * @param key the string buffer identifying the key to be searched for. * @param key_size the size of the string buffer identifying the key to be searched for. * @param start_index the start index of the actual search. * @returns the index of the key found, or -1 if not found. */ SEABOLT_EXPORT int32_t BoltDictionary_get_key_index(const BoltValue* value, const char* key, int32_t key_size, int32_t start_index); /** * Sets the _key_ value at _index_ from the passed in string buffer. * * @param value the instance to be updated. * @param index the index of the key to be set. * @param key the string buffer identifying the key to be set. * @param key_size the size of the string buffer identifying the key to be set. * @return 0 if successful, -1 if index is larger than the maximum value (INT32_MAX). */ SEABOLT_EXPORT int32_t BoltDictionary_set_key(BoltValue* value, int32_t index, const char* key, int32_t key_size); /** * Returns an instance to a \ref BoltValue identifying the _value_ at _index_. * * @param value the instance to be queried * @param index the index of the value. * @returns \ref BoltValue instance identifying the value, NULL if the index is out of bounds. */ SEABOLT_EXPORT BoltValue* BoltDictionary_value(const BoltValue* value, int32_t index); /** * Returns an instance to a \ref BoltValue identifying the _value_ corresponding to the key passed as a * string buffer. * * @param value the instance to be queried * @param key the string buffer identifying the key to be searched. * @param key_size the size of the string buffer identifying the key to be searched. * @returns \ref BoltValue instance identifying the value, NULL if the key is not found. */ SEABOLT_EXPORT BoltValue* BoltDictionary_value_by_key(const BoltValue* value, const char* key, int32_t key_size); /** * Sets the passed \ref BoltValue instance to \ref BOLT_LIST. * * @param value the instance to be updated * @param length the number of entries. */ SEABOLT_EXPORT void BoltValue_format_as_List(BoltValue* value, int32_t length); /** * Resizes the passed \ref BoltValue "list" instance. * * @param value the instance to be resized. * @param size the new size to be set. If it is smaller than the instance's current size, the * elements at indices larger than size will be trimmed. */ SEABOLT_EXPORT void BoltList_resize(BoltValue* value, int32_t size); /** * Returns an instance to a \ref BoltValue identifying the _value_ at _index_. * * @param value the instance to be queried * @param index the index of the value. * @returns \ref BoltValue instance identifying the value, NULL if the index is out of bounds. */ SEABOLT_EXPORT BoltValue* BoltList_value(const BoltValue* value, int32_t index); /** * Sets the passed \ref BoltValue instance to \ref BOLT_BYTES. * * @param value the instance to be updated * @param data the byte buffer containing the value to be set. * @param length the length of the byte buffer. */ SEABOLT_EXPORT void BoltValue_format_as_Bytes(BoltValue* value, char* data, int32_t length); /** * Returns the byte _value_ at _index_. * * @param value the instance to be queried * @param index the index of the byte to be queried * @returns the byte value (undefined if _index_ is out of bounds). */ SEABOLT_EXPORT char BoltBytes_get(const BoltValue* value, int32_t index); /** * Returns the whole byte buffer stored in the passed \ref BoltValue. * * @param value the instance to be queried * @returns the stored byte buffer. Actual length of the byte buffer can be queried by a call * to \ref BoltValue_size. */ SEABOLT_EXPORT char* BoltBytes_get_all(const BoltValue* value); /** * Sets the passed \ref BoltValue instance to \ref BOLT_STRUCTURE. * * @param value the instance to be updated * @param code the code of the structure. * @param length the number of entries to be placed in the structure. */ SEABOLT_EXPORT void BoltValue_format_as_Structure(BoltValue* value, int16_t code, int32_t length); /** * Returns the code of the structure. * * @param value the instance to be queried. * @return the code of the structure. */ SEABOLT_EXPORT int16_t BoltStructure_code(const BoltValue* value); /** * Returns an instance to a \ref BoltValue identifying the _entry_ at _index_. * * @param value the instance to be queried * @param index the index of the entry. * @returns \ref BoltValue instance identifying the entry at _index_, NULL if the index is out of bounds. */ SEABOLT_EXPORT BoltValue* BoltStructure_value(const BoltValue* value, int32_t index); #endif // SEABOLT_VALUES <|start_filename|>src/seabolt/src/bolt/v3.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ALL_V3_H #define SEABOLT_ALL_V3_H #include "connection.h" #define BOLT_V3_HELLO 0x01 #define BOLT_V3_GOODBYE 0x02 #define BOLT_V3_RUN 0x10 #define BOLT_V3_BEGIN 0x11 #define BOLT_V3_COMMIT 0x12 #define BOLT_V3_ROLLBACK 0x13 #define BOLT_V3_DISCARD_ALL 0x2F #define BOLT_V3_PULL_ALL 0x3F #define BOLT_V3_RESET 0x0F #define BOLT_V3_SUCCESS 0x70 #define BOLT_V3_RECORD 0x71 #define BOLT_V3_IGNORED 0x7E #define BOLT_V3_FAILURE 0x7F #define BOLT_V3_NODE 'N' #define BOLT_V3_RELATIONSHIP 'R' #define BOLT_V3_UNBOUND_RELATIONSHIP 'r' #define BOLT_V3_PATH 'P' #define BOLT_V3_POINT_2D 'X' #define BOLT_V3_POINT_3D 'Y' #define BOLT_V3_LOCAL_DATE 'D' #define BOLT_V3_LOCAL_TIME 't' #define BOLT_V3_LOCAL_DATE_TIME 'd' #define BOLT_V3_OFFSET_TIME 'T' #define BOLT_V3_OFFSET_DATE_TIME 'F' #define BOLT_V3_ZONED_DATE_TIME 'f' #define BOLT_V3_DURATION 'E' void BoltProtocolV3_extract_metadata(struct BoltConnection* connection, struct BoltValue* metadata); struct BoltProtocol* BoltProtocolV3_create_protocol(); void BoltProtocolV3_destroy_protocol(struct BoltProtocol* protocol); #endif //SEABOLT_ALL_V3_H <|start_filename|>src/seabolt/src/bolt/communication.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "communication.h" #include "mem.h" #include "name.h" #include "address-private.h" #include "config.h" #include "config-private.h" #include "log-private.h" #include "protocol.h" #include "status-private.h" #define TRY_COMM(code, status, error_ctx_fmt, file, line) { \ int status_try = (code); \ if (status_try != BOLT_SUCCESS) { \ if (status_try == BOLT_STATUS_SET) { \ return BOLT_STATUS_SET; \ } else { \ BoltStatus_set_error_with_ctx(status, status_try, error_ctx_fmt, file, line, -1); \ } \ return status_try; \ } \ } void _set_error_with_ctx(BoltStatus* status, int error, const char* error_ctx_format, ...) { status->error = error; status->error_ctx[0] = '\0'; if (error_ctx_format!=NULL) { va_list args; va_start(args, error_ctx_format); vsnprintf(status->error_ctx, status->error_ctx_size, error_ctx_format, args); va_end(args); } } int _open(BoltCommunication* comm, const struct sockaddr_storage* address, const char* id) { switch (address->ss_family) { case AF_INET: case AF_INET6: { char host_string[NI_MAXHOST]; char port_string[NI_MAXSERV]; int status = get_address_components(address, host_string, NI_MAXHOST, port_string, NI_MAXSERV); if (status==0) { BoltLog_info(comm->log, "[%s]: Opening %s connection to %s at port %s", id, address->ss_family==AF_INET ? "IPv4" : "IPv6", &host_string, &port_string); } break; } default: BoltLog_error(comm->log, "[%s]: Unsupported address family %d", id, address->ss_family); return BOLT_UNSUPPORTED; } TRY_COMM(comm->open(comm, address), comm->status, "_open(%s:%d): unable to establish connection", __FILE__, __LINE__); return BOLT_SUCCESS; } int BoltCommunication_open(BoltCommunication* comm, BoltAddress* address, const char* id) { if (BoltAddress_resolved_count(address)==0) { return BOLT_ADDRESS_NOT_RESOLVED; } int status = BOLT_SUCCESS; int resolved_hosts = (int) BoltAddress_resolved_count(address); struct sockaddr_storage resolved_host; for (int i = 0; i<resolved_hosts; i++) { BoltAddress_resolved_addr(address, i, &resolved_host); status = _open(comm, &resolved_host, id); if (status==BOLT_SUCCESS) { BoltAddress* remote = comm->get_remote_endpoint(comm); BoltLog_info(comm->log, "[%s]: Remote endpoint is %s:%s", id, remote->host, remote->port); BoltAddress* local = comm->get_local_endpoint(comm); BoltLog_info(comm->log, "[%s]: Local endpoint is %s:%s", id, local->host, local->port); BoltStatus_set_error(comm->status, BOLT_SUCCESS); break; } } return status; } int BoltCommunication_close(BoltCommunication* comm, const char* id) { TRY_COMM(comm->ignore_sigpipe(comm), comm->status, "BoltCommunication_close(%s:%d): unable to ignore SIGPIPE: %d", __FILE__, __LINE__); BoltLog_debug(comm->log, "[%s]: Closing socket", id); int status = comm->close(comm); if (status!=BOLT_SUCCESS) { _set_error_with_ctx(comm->status, status, "BoltCommunication_close(%s:%d), unable to close: %d", __FILE__, __LINE__, status); BoltLog_warning(comm->log, "[%s]: Unable to close socket, return code is %d", id, status); } TRY_COMM(comm->restore_sigpipe(comm), comm->status, "BoltCommunication_close(%s:%d): unable to restore SIGPIPE handler: %d", __FILE__, __LINE__); return status; } int BoltCommunication_send(BoltCommunication* comm, char* buffer, int size, const char* id) { if (size==0) { return BOLT_SUCCESS; } TRY_COMM(comm->ignore_sigpipe(comm), comm->status, "BoltCommunication_close(%s:%d): unable to ignore SIGPIPE: %d", __FILE__, __LINE__); int status = BOLT_SUCCESS; int remaining = size; int total_sent = 0; int sent = 0; while (total_sent<size) { status = comm->send(comm, buffer+total_sent, remaining, &sent); if (status==BOLT_SUCCESS) { total_sent += sent; remaining -= sent; } else { if (status!=BOLT_STATUS_SET) { _set_error_with_ctx(comm->status, status, "BoltCommunication_send(%s:%d), unable to send data: %d", __FILE__, __LINE__, status); status = BOLT_STATUS_SET; } break; } } if (status==BOLT_SUCCESS) { BoltLog_info(comm->log, "[%s]: (Sent %d of %d bytes)", id, total_sent, size); } TRY_COMM(comm->restore_sigpipe(comm), comm->status, "BoltCommunication_close(%s:%d): unable to restore SIGPIPE handler: %d", __FILE__, __LINE__); return status; } int BoltCommunication_receive(BoltCommunication* comm, char* buffer, int min_size, int max_size, int* received, const char* id) { if (min_size==0) { return BOLT_SUCCESS; } TRY_COMM(comm->ignore_sigpipe(comm), comm->status, "BoltCommunication_close(%s:%d): unable to ignore SIGPIPE: %d", __FILE__, __LINE__); int status = BOLT_SUCCESS; int max_remaining = max_size; int total_received = 0; int single_received = 0; while (total_received<min_size) { status = comm->recv(comm, buffer+total_received, max_remaining, &single_received); if (status==BOLT_SUCCESS) { total_received += single_received; max_remaining -= single_received; } else { if (status!=BOLT_STATUS_SET) { _set_error_with_ctx(comm->status, status, "BoltCommunication_receive(%s:%d), unable to receive data: %d", __FILE__, __LINE__, status); status = BOLT_STATUS_SET; } break; } } if (status==BOLT_SUCCESS) { if (min_size==max_size) { BoltLog_info(comm->log, "[%s]: Received %d of %d bytes", id, total_received, max_size); } else { BoltLog_info(comm->log, "[%s]: Received %d of %d..%d bytes", id, total_received, min_size, max_size); } } *received = total_received; TRY_COMM(comm->restore_sigpipe(comm), comm->status, "BoltCommunication_close(%s:%d): unable to restore SIGPIPE handler: %d", __FILE__, __LINE__); return status; } void BoltCommunication_destroy(BoltCommunication* comm) { if (comm->context!=NULL) { comm->destroy(comm); comm->context = NULL; } if (comm->status!=NULL && comm->status_owned) { BoltStatus_destroy(comm->status); } if (comm->sock_opts!=NULL && comm->sock_opts_owned) { BoltSocketOptions_destroy(comm->sock_opts); } BoltMem_deallocate(comm, sizeof(BoltCommunication)); } BoltAddress* BoltCommunication_local_endpoint(BoltCommunication* comm) { return comm->get_local_endpoint(comm); } BoltAddress* BoltCommunication_remote_endpoint(BoltCommunication* comm) { return comm->get_remote_endpoint(comm); } <|start_filename|>src/seabolt/src/bolt/packstream.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "log-private.h" #include "packstream.h" #include "values-private.h" #define TRY(code) { int status_try = (code); if (status_try != BOLT_SUCCESS) { return status_try; } } int load_null(struct BoltBuffer* buffer) { BoltBuffer_load_u8(buffer, 0xC0); return BOLT_SUCCESS; } int load_boolean(struct BoltBuffer* buffer, int value) { BoltBuffer_load_u8(buffer, (value==0) ? (uint8_t) (0xC2) : (uint8_t) (0xC3)); return BOLT_SUCCESS; } int load_integer(struct BoltBuffer* buffer, int64_t value) { if (value>=-0x10 && value<0x80) { BoltBuffer_load_i8(buffer, (int8_t) (value)); } else if (value>=INT8_MIN && value<=INT8_MAX) { BoltBuffer_load_u8(buffer, 0xC8); BoltBuffer_load_i8(buffer, (int8_t) (value)); } else if (value>=INT16_MIN && value<=INT16_MAX) { BoltBuffer_load_u8(buffer, 0xC9); BoltBuffer_load_i16be(buffer, (int16_t) (value)); } else if (value>=INT32_MIN && value<=INT32_MAX) { BoltBuffer_load_u8(buffer, 0xCA); BoltBuffer_load_i32be(buffer, (int32_t) (value)); } else { BoltBuffer_load_u8(buffer, 0xCB); BoltBuffer_load_i64be(buffer, value); } return BOLT_SUCCESS; } int load_float(struct BoltBuffer* buffer, double value) { BoltBuffer_load_u8(buffer, 0xC1); BoltBuffer_load_f64be(buffer, value); return BOLT_SUCCESS; } int load_bytes(struct BoltBuffer* buffer, const char* string, int32_t size) { if (size<0) { return BOLT_PROTOCOL_VIOLATION; } if (size<0x100) { BoltBuffer_load_u8(buffer, 0xCC); BoltBuffer_load_u8(buffer, (uint8_t) (size)); BoltBuffer_load(buffer, string, size); } else if (size<0x10000) { BoltBuffer_load_u8(buffer, 0xCD); BoltBuffer_load_u16be(buffer, (uint16_t) (size)); BoltBuffer_load(buffer, string, size); } else { BoltBuffer_load_u8(buffer, 0xCE); BoltBuffer_load_i32be(buffer, size); BoltBuffer_load(buffer, string, size); } return BOLT_SUCCESS; } int load_string_header(struct BoltBuffer* buffer, int32_t size) { if (size<0) { return BOLT_PROTOCOL_VIOLATION; } if (size<0x10) { BoltBuffer_load_u8(buffer, (uint8_t) (0x80+size)); } else if (size<0x100) { BoltBuffer_load_u8(buffer, 0xD0); BoltBuffer_load_u8(buffer, (uint8_t) (size)); } else if (size<0x10000) { BoltBuffer_load_u8(buffer, 0xD1); BoltBuffer_load_u16be(buffer, (uint16_t) (size)); } else { BoltBuffer_load_u8(buffer, 0xD2); BoltBuffer_load_i32be(buffer, size); } return BOLT_SUCCESS; } int load_string(struct BoltBuffer* buffer, const char* string, int32_t size) { int status = load_string_header(buffer, size); if (status!=BOLT_SUCCESS) return status; BoltBuffer_load(buffer, string, size); return BOLT_SUCCESS; } int load_list_header(struct BoltBuffer* buffer, int32_t size) { if (size<0) { return BOLT_PROTOCOL_VIOLATION; } if (size<0x10) { BoltBuffer_load_u8(buffer, (uint8_t) (0x90+size)); } else if (size<0x100) { BoltBuffer_load_u8(buffer, 0xD4); BoltBuffer_load_u8(buffer, (uint8_t) (size)); } else if (size<0x10000) { BoltBuffer_load_u8(buffer, 0xD5); BoltBuffer_load_u16be(buffer, (uint16_t) (size)); } else { BoltBuffer_load_u8(buffer, 0xD6); BoltBuffer_load_i32be(buffer, size); } return BOLT_SUCCESS; } int load_map_header(struct BoltBuffer* buffer, int32_t size) { if (size<0) { return BOLT_PROTOCOL_VIOLATION; } if (size<0x10) { BoltBuffer_load_u8(buffer, (uint8_t) (0xA0+size)); } else if (size<0x100) { BoltBuffer_load_u8(buffer, 0xD8); BoltBuffer_load_u8(buffer, (uint8_t) (size)); } else if (size<0x10000) { BoltBuffer_load_u8(buffer, 0xD9); BoltBuffer_load_u16be(buffer, (uint16_t) (size)); } else { BoltBuffer_load_u8(buffer, 0xDA); BoltBuffer_load_i32be(buffer, size); } return BOLT_SUCCESS; } int load_structure_header(struct BoltBuffer* buffer, int16_t code, int8_t size) { if (code<0 || size<0 || size>=0x10) { return BOLT_PROTOCOL_VIOLATION; } BoltBuffer_load_u8(buffer, (uint8_t) (0xB0+size)); BoltBuffer_load_i8(buffer, (int8_t) (code)); return BOLT_SUCCESS; } int load(check_struct_signature_func check_struct_type, struct BoltBuffer* buffer, struct BoltValue* value, const struct BoltLog* log) { switch (BoltValue_type(value)) { case BOLT_NULL: return load_null(buffer); case BOLT_LIST: { TRY(load_list_header(buffer, value->size)); for (int32_t i = 0; i<value->size; i++) { TRY(load(check_struct_type, buffer, BoltList_value(value, i), log)); } return 0; } case BOLT_BOOLEAN: return load_boolean(buffer, BoltBoolean_get(value)); case BOLT_BYTES: return load_bytes(buffer, BoltBytes_get_all(value), value->size); case BOLT_STRING: return load_string(buffer, BoltString_get(value), value->size); case BOLT_DICTIONARY: { TRY(load_map_header(buffer, value->size)); for (int32_t i = 0; i<value->size; i++) { const char* key = BoltDictionary_get_key(value, i); if (key!=NULL) { TRY(load_string(buffer, key, BoltDictionary_get_key_size(value, i))); TRY(load(check_struct_type, buffer, BoltDictionary_value(value, i), log)); } } return BOLT_SUCCESS; } case BOLT_INTEGER: return load_integer(buffer, BoltInteger_get(value)); case BOLT_FLOAT: return load_float(buffer, BoltFloat_get(value)); case BOLT_STRUCTURE: { if (check_struct_type(BoltStructure_code(value))) { TRY(load_structure_header(buffer, BoltStructure_code(value), (int8_t) value->size)); for (int32_t i = 0; i<value->size; i++) { TRY(load(check_struct_type, buffer, BoltStructure_value(value, i), log)); } return BOLT_SUCCESS; } return BOLT_PROTOCOL_UNSUPPORTED_TYPE; } default: return BOLT_PROTOCOL_NOT_IMPLEMENTED_TYPE; } } enum PackStreamType marker_type(uint8_t marker) { if (marker<0x80 || (marker>=0xC8 && marker<=0xCB) || marker>=0xF0) { return PACKSTREAM_INTEGER; } if ((marker>=0x80 && marker<=0x8F) || (marker>=0xD0 && marker<=0xD2)) { return PACKSTREAM_STRING; } if ((marker>=0x90 && marker<=0x9F) || (marker>=0xD4 && marker<=0xD6)) { return PACKSTREAM_LIST; } if ((marker>=0xA0 && marker<=0xAF) || (marker>=0xD8 && marker<=0xDA)) { return PACKSTREAM_MAP; } if ((marker>=0xB0 && marker<=0xBF) || (marker>=0xDC && marker<=0xDD)) { return PACKSTREAM_STRUCTURE; } switch (marker) { case 0xC0: return PACKSTREAM_NULL; case 0xC1: return PACKSTREAM_FLOAT; case 0xC2: case 0xC3: return PACKSTREAM_BOOLEAN; case 0xCC: case 0xCD: case 0xCE: return PACKSTREAM_BYTES; default: return PACKSTREAM_RESERVED; } } int unload_null(struct BoltBuffer* recv_buffer, struct BoltValue* value) { uint8_t marker; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker==0xC0) { BoltValue_format_as_Null(value); } else { return BOLT_PROTOCOL_UNEXPECTED_MARKER; } return BOLT_SUCCESS; } int unload_boolean(struct BoltBuffer* recv_buffer, struct BoltValue* value) { uint8_t marker; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker==0xC3) { BoltValue_format_as_Boolean(value, 1); } else if (marker==0xC2) { BoltValue_format_as_Boolean(value, 0); } else { return BOLT_PROTOCOL_UNEXPECTED_MARKER; } return BOLT_SUCCESS; } int unload_integer(struct BoltBuffer* recv_buffer, struct BoltValue* value) { uint8_t marker; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker<0x80) { BoltValue_format_as_Integer(value, marker); } else if (marker>=0xF0) { BoltValue_format_as_Integer(value, marker-0x100); } else if (marker==0xC8) { int8_t x; BoltBuffer_unload_i8(recv_buffer, &x); BoltValue_format_as_Integer(value, x); } else if (marker==0xC9) { int16_t x; BoltBuffer_unload_i16be(recv_buffer, &x); BoltValue_format_as_Integer(value, x); } else if (marker==0xCA) { int32_t x; BoltBuffer_unload_i32be(recv_buffer, &x); BoltValue_format_as_Integer(value, x); } else if (marker==0xCB) { int64_t x; BoltBuffer_unload_i64be(recv_buffer, &x); BoltValue_format_as_Integer(value, x); } else { return BOLT_PROTOCOL_UNEXPECTED_MARKER; // BOLT_ERROR_WRONG_TYPE } return BOLT_SUCCESS; } int unload_float(struct BoltBuffer* recv_buffer, struct BoltValue* value) { uint8_t marker; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker==0xC1) { double x; BoltBuffer_unload_f64be(recv_buffer, &x); BoltValue_format_as_Float(value, x); } else { return BOLT_PROTOCOL_UNEXPECTED_MARKER; // BOLT_ERROR_WRONG_TYPE } return BOLT_SUCCESS; } int unload_string(struct BoltBuffer* recv_buffer, struct BoltValue* value, const struct BoltLog* log) { uint8_t marker; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker>=0x80 && marker<=0x8F) { int32_t size; size = marker & 0x0F; BoltValue_format_as_String(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltString_get(value), size); return BOLT_SUCCESS; } if (marker==0xD0) { uint8_t size; BoltBuffer_unload_u8(recv_buffer, &size); BoltValue_format_as_String(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltString_get(value), size); return BOLT_SUCCESS; } if (marker==0xD1) { uint16_t size; BoltBuffer_unload_u16be(recv_buffer, &size); BoltValue_format_as_String(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltString_get(value), size); return BOLT_SUCCESS; } if (marker==0xD2) { int32_t size; BoltBuffer_unload_i32be(recv_buffer, &size); BoltValue_format_as_String(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltString_get(value), size); return BOLT_SUCCESS; } BoltLog_error(log, "Unknown marker: %d", marker); return BOLT_PROTOCOL_UNEXPECTED_MARKER; } int unload_bytes(struct BoltBuffer* recv_buffer, struct BoltValue* value, const struct BoltLog* log) { uint8_t marker; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker==0xCC) { uint8_t size; BoltBuffer_unload_u8(recv_buffer, &size); BoltValue_format_as_Bytes(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltBytes_get_all(value), size); return BOLT_SUCCESS; } if (marker==0xCD) { uint16_t size; BoltBuffer_unload_u16be(recv_buffer, &size); BoltValue_format_as_Bytes(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltBytes_get_all(value), size); return BOLT_SUCCESS; } if (marker==0xCE) { int32_t size; BoltBuffer_unload_i32be(recv_buffer, &size); BoltValue_format_as_Bytes(value, NULL, size); BoltBuffer_unload(recv_buffer, BoltBytes_get_all(value), size); return BOLT_SUCCESS; } BoltLog_error(log, "Unknown marker: %d", marker); return BOLT_PROTOCOL_UNEXPECTED_MARKER; } int unload_list(check_struct_signature_func check_struct_type, struct BoltBuffer* recv_buffer, struct BoltValue* value, const struct BoltLog* log) { uint8_t marker; int32_t size; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker>=0x90 && marker<=0x9F) { size = marker & 0x0F; } else if (marker==0xD4) { uint8_t size_; BoltBuffer_unload_u8(recv_buffer, &size_); size = size_; } else if (marker==0xD5) { uint16_t size_; BoltBuffer_unload_u16be(recv_buffer, &size_); size = size_; } else if (marker==0xD6) { int32_t size_; BoltBuffer_unload_i32be(recv_buffer, &size_); size = size_; } else { return BOLT_PROTOCOL_UNEXPECTED_MARKER; } if (size<0) { return BOLT_PROTOCOL_VIOLATION; } BoltValue_format_as_List(value, size); for (int i = 0; i<size; i++) { TRY(unload(check_struct_type, recv_buffer, BoltList_value(value, i), log)); } return BOLT_SUCCESS; } int unload_map(check_struct_signature_func check_struct_type, struct BoltBuffer* recv_buffer, struct BoltValue* value, const struct BoltLog* log) { uint8_t marker; int32_t size; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker>=0xA0 && marker<=0xAF) { size = marker & 0x0F; } else if (marker==0xD8) { uint8_t size_; BoltBuffer_unload_u8(recv_buffer, &size_); size = size_; } else if (marker==0xD9) { uint16_t size_; BoltBuffer_unload_u16be(recv_buffer, &size_); size = size_; } else if (marker==0xDA) { int32_t size_; BoltBuffer_unload_i32be(recv_buffer, &size_); size = size_; } else { return BOLT_PROTOCOL_UNEXPECTED_MARKER; } if (size<0) { return BOLT_PROTOCOL_VIOLATION; } BoltValue_format_as_Dictionary(value, size); for (int i = 0; i<size; i++) { TRY(unload(check_struct_type, recv_buffer, BoltDictionary_key(value, i), log)); TRY(unload(check_struct_type, recv_buffer, BoltDictionary_value(value, i), log)); } return BOLT_SUCCESS; } int unload_structure(check_struct_signature_func check_struct_type, struct BoltBuffer* recv_buffer, struct BoltValue* value, const struct BoltLog* log) { uint8_t marker; int8_t code; int32_t size; BoltBuffer_unload_u8(recv_buffer, &marker); if (marker>=0xB0 && marker<=0xBF) { size = marker & 0x0F; BoltBuffer_unload_i8(recv_buffer, &code); if (check_struct_type(code)) { BoltValue_format_as_Structure(value, code, size); for (int i = 0; i<size; i++) { unload(check_struct_type, recv_buffer, BoltStructure_value(value, i), log); } return BOLT_SUCCESS; } } return BOLT_PROTOCOL_UNEXPECTED_MARKER; } int unload(check_struct_signature_func check_struct_type, struct BoltBuffer* buffer, struct BoltValue* value, const struct BoltLog* log) { uint8_t marker; BoltBuffer_peek_u8(buffer, &marker); switch (marker_type(marker)) { case PACKSTREAM_NULL: return unload_null(buffer, value); case PACKSTREAM_BOOLEAN: return unload_boolean(buffer, value); case PACKSTREAM_INTEGER: return unload_integer(buffer, value); case PACKSTREAM_FLOAT: return unload_float(buffer, value); case PACKSTREAM_STRING: return unload_string(buffer, value, log); case PACKSTREAM_BYTES: return unload_bytes(buffer, value, log); case PACKSTREAM_LIST: return unload_list(check_struct_type, buffer, value, log); case PACKSTREAM_MAP: return unload_map(check_struct_type, buffer, value, log); case PACKSTREAM_STRUCTURE: return unload_structure(check_struct_type, buffer, value, log); default: BoltLog_error(log, "Unknown marker: %d", marker); return BOLT_PROTOCOL_UNEXPECTED_MARKER; } } <|start_filename|>src/seabolt/tests/test-direct.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "integration.hpp" #include "catch.hpp" SCENARIO("Test basic secure connection (IPv4)", "[integration][ipv4][secure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV4_HOST, BOLT_PORT); WHEN("a secure connection is opened") { struct BoltTrust trust{nullptr, 0, 1, 1}; struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test basic secure connection (IPv6)", "[integration][ipv6][secure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV6_HOST, BOLT_PORT); WHEN("a secure connection is opened") { struct BoltTrust trust{nullptr, 0, 1, 1}; struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test basic insecure connection (IPv4)", "[integration][ipv4][insecure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV4_HOST, BOLT_PORT); WHEN("an insecure connection is opened") { struct BoltTrust trust{nullptr, 0, 1, 1}; struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_PLAINTEXT, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test basic insecure connection (IPv6)", "[integration][ipv6][insecure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV6_HOST, BOLT_PORT); WHEN("an insecure connection is opened") { struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_PLAINTEXT, address, nullptr, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test secure connection to dead port", "[integration][ipv6][secure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV6_HOST, "9999"); WHEN("a secure connection attempt is made") { struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, nullptr, nullptr, nullptr); THEN("a DEFUNCT connection should be returned") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_DEFUNCT); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test insecure connection to dead port", "[integration][ipv6][insecure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV6_HOST, "9999"); WHEN("an insecure connection attempt is made") { struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_PLAINTEXT, address, nullptr, nullptr, nullptr); THEN("a DEFUNCT connection should be returned") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_DEFUNCT); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test connection reuse after graceful shutdown", "[integration][ipv6][secure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV6_HOST, BOLT_PORT); WHEN("a secure connection is opened") { struct BoltTrust trust{nullptr, 0, 1, 1}; struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); THEN("the connection should be disconnected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_DISCONNECTED); } BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test connection reuse after graceless shutdown", "[integration][ipv6][secure]") { GIVEN("a local server address") { struct BoltAddress* address = bolt_get_address(BOLT_IPV6_HOST, BOLT_PORT); WHEN("a secure connection is opened") { struct BoltTrust trust{nullptr, 0, 1, 1}; struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } connection->status->state = BOLT_CONNECTION_STATE_DEFUNCT; BoltConnection_open(connection, BOLT_TRANSPORT_ENCRYPTED, address, &trust, nullptr, nullptr); THEN("the connection should be connected") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); } BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltAddress_destroy(address); } } SCENARIO("Test init with valid credentials", "[integration][ipv6][secure]") { GIVEN("an open connection") { const auto auth_token = BoltAuth_basic(BOLT_USER, BOLT_PASSWORD, NULL); struct BoltConnection* connection = bolt_open_b(BOLT_TRANSPORT_ENCRYPTED, BOLT_IPV6_HOST, BOLT_PORT); WHEN("successfully initialised") { int rv = BoltConnection_init(connection, BOLT_USER_AGENT, auth_token); THEN("return value should be 0") { REQUIRE(rv==0); } THEN("status should change to READY") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_READY); } } BoltConnection_close(connection); BoltConnection_destroy(connection); BoltValue_destroy(auth_token); } } SCENARIO("Test init with invalid credentials", "[integration][ipv6][secure]") { GIVEN("an open connection") { struct BoltConnection* connection = bolt_open_b(BOLT_TRANSPORT_ENCRYPTED, BOLT_IPV6_HOST, BOLT_PORT); WHEN("unsuccessfully initialised") { REQUIRE(strcmp(BOLT_PASSWORD, "X")!=0); const auto auth_token = BoltAuth_basic(BOLT_USER, "X", NULL); int rv = BoltConnection_init(connection, BOLT_USER_AGENT, auth_token); THEN("return value should not be 0") { REQUIRE(rv!=0); } THEN("status should change to DEFUNCT") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_DEFUNCT); } BoltValue_destroy(auth_token); } BoltConnection_close(connection); BoltConnection_destroy(connection); } } SCENARIO("Test execution of simple Cypher statement", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN 1"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 0); BoltConnection_load_run_request(connection); BoltRequest run = BoltConnection_last_request(connection); BoltConnection_load_pull_request(connection, -1); BoltRequest pull = BoltConnection_last_request(connection); BoltConnection_send(connection); int records = BoltConnection_fetch_summary(connection, run); REQUIRE(records==0); records = BoltConnection_fetch_summary(connection, pull); REQUIRE(records==1); } BoltConnection_close(connection); } } SCENARIO("Test field names returned from Cypher execution", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN 1 AS first, true AS second, 3.14 AS third"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 0); BoltConnection_load_run_request(connection); BoltRequest run = BoltConnection_last_request(connection); BoltConnection_load_pull_request(connection, -1); BoltConnection_send(connection); BoltRequest last = BoltConnection_last_request(connection); BoltConnection_fetch_summary(connection, run); const struct BoltValue* fields = BoltConnection_field_names(connection); REQUIRE(BoltValue_size(fields)==3); struct BoltValue* field_name_value = BoltList_value(fields, 0); const char* field_name = BoltString_get(field_name_value); int field_name_size = BoltValue_size(field_name_value); REQUIRE(strncmp(field_name, "first", field_name_size)==0); field_name_value = BoltList_value(fields, 1); field_name = BoltString_get(field_name_value); field_name_size = BoltValue_size(field_name_value); REQUIRE(strncmp(field_name, "second", field_name_size)==0); field_name_value = BoltList_value(fields, 2); field_name = BoltString_get(field_name_value); field_name_size = BoltValue_size(field_name_value); REQUIRE(strncmp(field_name, "third", field_name_size)==0); REQUIRE(field_name_size==5); BoltConnection_fetch_summary(connection, last); } BoltConnection_close(connection); } } SCENARIO("Test parameterised Cypher statements", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Integer(x, 42); BoltConnection_load_run_request(connection); BoltRequest run = BoltConnection_last_request(connection); BoltConnection_load_pull_request(connection, -1); BoltRequest pull = BoltConnection_last_request(connection); BoltConnection_send(connection); int records = BoltConnection_fetch_summary(connection, run); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==1); while (BoltConnection_fetch(connection, pull)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE(BoltValue_type(value)==BOLT_INTEGER); REQUIRE(BoltInteger_get(value)==42); records += 1; } REQUIRE(BoltConnection_summary_success(connection)==1); REQUIRE(records==1); } BoltConnection_close(connection); } } SCENARIO("Test execution of multiple Cypher statements transmitted together", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Integer(x, 1); BoltConnection_load_run_request(connection); BoltConnection_load_discard_request(connection, -1); BoltValue_format_as_Integer(x, 2); BoltConnection_load_run_request(connection); BoltConnection_load_pull_request(connection, -1); BoltConnection_send(connection); unsigned long long last = BoltConnection_last_request(connection); int records = BoltConnection_fetch_summary(connection, last); REQUIRE(records==1); } BoltConnection_close(connection); } } SCENARIO("Test transactions", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { BoltConnection_load_begin_request(connection); BoltRequest begin = BoltConnection_last_request(connection); const char* cypher = "RETURN 1"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 0); BoltConnection_load_run_request(connection); BoltRequest run = BoltConnection_last_request(connection); BoltConnection_load_pull_request(connection, -1); BoltRequest pull = BoltConnection_last_request(connection); BoltConnection_load_commit_request(connection); BoltRequest commit = BoltConnection_last_request(connection); BoltConnection_send(connection); BoltRequest last = BoltConnection_last_request(connection); REQUIRE(last==commit); int records = BoltConnection_fetch_summary(connection, begin); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==1); records = BoltConnection_fetch_summary(connection, run); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==1); while (BoltConnection_fetch(connection, pull)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE(BoltValue_type(value)==BOLT_INTEGER); REQUIRE(BoltInteger_get(value)==1); records += 1; } REQUIRE(BoltConnection_summary_success(connection)==1); REQUIRE(records==1); records = BoltConnection_fetch_summary(connection, commit); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==1); } BoltConnection_close(connection); } } SCENARIO("Test FAILURE", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { auto connection = bolt_open_init_default(); WHEN("an invalid cypher statement is sent") { const auto cypher = "some invalid statement"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 0); BoltConnection_load_run_request(connection); const auto run = BoltConnection_last_request(connection); BoltConnection_load_pull_request(connection, -1); const auto pull = BoltConnection_last_request(connection); BoltConnection_send(connection); THEN("connector should be in FAILED state") { const auto records = BoltConnection_fetch_summary(connection, run); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==0); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_FAILED); REQUIRE(connection->status->error==BOLT_SERVER_FAILURE); auto failure_data = BoltConnection_failure(connection); REQUIRE(failure_data!=nullptr); struct BoltValue* code = BoltDictionary_value_by_key(failure_data, "code", (int32_t) strlen("code")); struct BoltValue* message = BoltDictionary_value_by_key(failure_data, "message", (int32_t) strlen("message")); REQUIRE(code!=nullptr); REQUIRE(BoltValue_type(code)==BOLT_STRING); REQUIRE(BoltString_equals(code, "Neo.ClientError.Statement.SyntaxError", strlen("Neo.ClientError.Statement.SyntaxError"))); REQUIRE(message!=nullptr); REQUIRE(BoltValue_type(message)==BOLT_STRING); } THEN("already sent requests should be IGNORED after FAILURE") { const auto records = BoltConnection_fetch_summary(connection, pull); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==0); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_FAILED); REQUIRE(connection->status->error==BOLT_SERVER_FAILURE); struct BoltValue* failure_data = BoltConnection_failure(connection); REQUIRE(failure_data!=nullptr); struct BoltValue* code = BoltDictionary_value_by_key(failure_data, "code", (int32_t) strlen("code")); struct BoltValue* message = BoltDictionary_value_by_key(failure_data, "message", (int32_t) strlen("message")); REQUIRE(code!=nullptr); REQUIRE(BoltValue_type(code)==BOLT_STRING); REQUIRE(BoltString_equals(code, "Neo.ClientError.Statement.SyntaxError", strlen("Neo.ClientError.Statement.SyntaxError"))); REQUIRE(message!=nullptr); REQUIRE(BoltValue_type(message)==BOLT_STRING); } THEN("upcoming requests should be IGNORED after FAILURE") { const auto cypher1 = "RETURN 1"; BoltConnection_set_run_cypher(connection, cypher1, strlen(cypher1), 0); BoltConnection_load_run_request(connection); const auto run1 = BoltConnection_last_request(connection); BoltConnection_send(connection); const auto records = BoltConnection_fetch_summary(connection, run1); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==0); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_FAILED); REQUIRE(connection->status->error==BOLT_SERVER_FAILURE); auto failure_data = BoltConnection_failure(connection); REQUIRE(failure_data!=nullptr); struct BoltValue* code = BoltDictionary_value_by_key(failure_data, "code", (int32_t) strlen("code")); struct BoltValue* message = BoltDictionary_value_by_key(failure_data, "message", (int32_t) strlen("message")); REQUIRE(code!=nullptr); REQUIRE(BoltValue_type(code)==BOLT_STRING); REQUIRE(BoltString_equals(code, "Neo.ClientError.Statement.SyntaxError", strlen("Neo.ClientError.Statement.SyntaxError"))); REQUIRE(message!=nullptr); REQUIRE(BoltValue_type(message)==BOLT_STRING); } THEN("reset should clear failure state") { const auto records = BoltConnection_fetch_summary(connection, run); REQUIRE(records==0); REQUIRE(BoltConnection_summary_success(connection)==0); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_FAILED); REQUIRE(connection->status->error==BOLT_SERVER_FAILURE); auto status = BoltConnection_load_reset_request(connection); REQUIRE(status==0); REQUIRE(BoltConnection_failure(connection)==nullptr); const auto ack_failure = BoltConnection_last_request(connection); BoltConnection_send(connection); const auto records_1 = BoltConnection_fetch_summary(connection, ack_failure); REQUIRE(records_1==0); REQUIRE(BoltConnection_summary_success(connection)==1); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_READY); REQUIRE(connection->status->error==BOLT_SUCCESS); } } BoltConnection_close(connection); } } <|start_filename|>src/seabolt/src/bolt/connection.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "address-private.h" #include "config-private.h" #include "connection-private.h" #include "log-private.h" #include "mem.h" #include "protocol.h" #include "time.h" #include "v1.h" #include "v2.h" #include "v3.h" #include "atomic.h" #include "communication-plain.h" #include "communication-secure.h" #define INITIAL_TX_BUFFER_SIZE 8192 #define INITIAL_RX_BUFFER_SIZE 8192 #define ERROR_CTX_SIZE 1024 #define MAX_ID_LEN 32 #define TRY(code, error_ctx_fmt, file, line) { \ int status_try = (code); \ if (status_try != BOLT_SUCCESS) { \ if (status_try == BOLT_STATUS_SET) { \ return -1; \ } else { \ _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_DEFUNCT, status_try, error_ctx_fmt, file, line, -1); \ } \ return status_try; \ } \ } static int64_t id_seq = 0; void _status_changed(BoltConnection* connection) { char* status_text = NULL; switch (connection->status->state) { case BOLT_CONNECTION_STATE_DISCONNECTED: status_text = "<DISCONNECTED>"; break; case BOLT_CONNECTION_STATE_CONNECTED: status_text = "<CONNECTED>"; break; case BOLT_CONNECTION_STATE_READY: status_text = "<READY>"; break; case BOLT_CONNECTION_STATE_FAILED: status_text = "<FAILED>"; break; case BOLT_CONNECTION_STATE_DEFUNCT: status_text = "<DEFUNCT>"; break; } if (connection->status->error_ctx[0]!=0) { BoltLog_info(connection->log, "[%s]: %s [%s]", BoltConnection_id(connection), status_text, connection->status->error_ctx); } else { BoltLog_info(connection->log, "[%s]: %s", BoltConnection_id(connection), status_text); } if (connection->status->state==BOLT_CONNECTION_STATE_DEFUNCT || connection->status->state==BOLT_CONNECTION_STATE_FAILED) { if (connection->on_error_cb!=NULL) { (*connection->on_error_cb)(connection, connection->on_error_cb_state); } } } void _set_status(BoltConnection* connection, BoltConnectionState state, int error) { BoltConnectionState old_status = connection->status->state; connection->status->state = state; connection->status->error = error; connection->status->error_ctx[0] = '\0'; if (state!=old_status) { _status_changed(connection); } } void _set_status_with_ctx(BoltConnection* connection, BoltConnectionState status, int error, const char* error_ctx_format, ...) { BoltConnectionState old_status = connection->status->state; connection->status->state = status; connection->status->error = error; connection->status->error_ctx[0] = '\0'; if (error_ctx_format!=NULL) { va_list args; va_start(args, error_ctx_format); vsnprintf(connection->status->error_ctx, ERROR_CTX_SIZE, error_ctx_format, args); va_end(args); } if (status!=old_status) { _status_changed(connection); } } void _set_status_from_comm(BoltConnection* connection, BoltConnectionState state) { _set_status_with_ctx(connection, state, connection->comm->status->error, connection->comm->status->error_ctx); } void _close(BoltConnection* connection) { BoltLog_info(connection->log, "[%s]: Closing connection", BoltConnection_id(connection)); if (connection->protocol!=NULL) { connection->protocol->goodbye(connection); switch (connection->protocol_version) { case 1: BoltProtocolV1_destroy_protocol(connection->protocol); break; case 2: BoltProtocolV2_destroy_protocol(connection->protocol); break; case 3: BoltProtocolV3_destroy_protocol(connection->protocol); break; default: break; } connection->protocol = NULL; connection->protocol_version = 0; } if (connection->comm!=NULL) { BoltCommunication_close(connection->comm, BoltConnection_id(connection)); BoltCommunication_destroy(connection->comm); connection->comm = NULL; } BoltTime_get_time(&connection->metrics->time_closed); _set_status(connection, BOLT_CONNECTION_STATE_DISCONNECTED, BOLT_SUCCESS); } int handshake_b(BoltConnection* connection, int32_t _1, int32_t _2, int32_t _3, int32_t _4) { BoltLog_info(connection->log, "[%s]: Performing handshake", BoltConnection_id(connection)); char handshake[20]; memcpy(&handshake[0x00], "\x60\x60\xB0\x17", 4); memcpy_be(&handshake[0x04], &_1, 4); memcpy_be(&handshake[0x08], &_2, 4); memcpy_be(&handshake[0x0C], &_3, 4); memcpy_be(&handshake[0x10], &_4, 4); int status = BoltCommunication_send(connection->comm, handshake, 20, BoltConnection_id(connection)); if (status!=BOLT_SUCCESS) { _set_status_from_comm(connection, BOLT_CONNECTION_STATE_DEFUNCT); return BOLT_STATUS_SET; } int received = 0; status = BoltCommunication_receive(connection->comm, handshake, 4, 4, &received, BoltConnection_id(connection)); if (status!=BOLT_SUCCESS) { _set_status_from_comm(connection, BOLT_CONNECTION_STATE_DEFUNCT); return BOLT_STATUS_SET; } memcpy_be(&connection->protocol_version, &handshake[0], 4); BoltLog_info(connection->log, "[%s]: <SET protocol_version=%d>", BoltConnection_id(connection), connection->protocol_version); switch (connection->protocol_version) { case 1: connection->protocol = BoltProtocolV1_create_protocol(); return BOLT_SUCCESS; case 2: connection->protocol = BoltProtocolV2_create_protocol(); return BOLT_SUCCESS; case 3: connection->protocol = BoltProtocolV3_create_protocol(); return BOLT_SUCCESS; default: _close(connection); return BOLT_PROTOCOL_UNSUPPORTED; } } BoltConnection* BoltConnection_create() { const size_t size = sizeof(BoltConnection); BoltConnection* connection = BoltMem_allocate(size); memset(connection, 0, size); connection->access_mode = BOLT_ACCESS_MODE_WRITE; connection->status = BoltStatus_create_with_ctx(ERROR_CTX_SIZE); connection->metrics = BoltMem_allocate(sizeof(BoltConnectionMetrics)); memset(connection->metrics, 0, sizeof(BoltConnectionMetrics)); return connection; } void BoltConnection_destroy(BoltConnection* connection) { if (connection->status!=NULL) { BoltStatus_destroy(connection->status); } if (connection->metrics!=NULL) { BoltMem_deallocate(connection->metrics, sizeof(BoltConnectionMetrics)); } BoltMem_deallocate(connection, sizeof(BoltConnection)); } int32_t BoltConnection_open(BoltConnection* connection, BoltTransport transport, struct BoltAddress* address, struct BoltTrust* trust, struct BoltLog* log, struct BoltSocketOptions* sock_opts) { if (connection->status->state!=BOLT_CONNECTION_STATE_DISCONNECTED) { BoltConnection_close(connection); } // Id buffer composed of local&remote Endpoints connection->id = BoltMem_allocate(MAX_ID_LEN); snprintf(connection->id, MAX_ID_LEN, "conn-%" PRId64, BoltAtomic_increment(&id_seq)); connection->log = log; // Store connection info connection->address = BoltAddress_create(address->host, address->port); switch (transport) { case BOLT_TRANSPORT_PLAINTEXT: connection->comm = BoltCommunication_create_plain(sock_opts, log); break; case BOLT_TRANSPORT_ENCRYPTED: connection->comm = BoltCommunication_create_secure(connection->sec_context, trust, sock_opts, log, connection->address->host, connection->id); break; case BOLT_TRANSPORT_MOCKED: // Expect connection->comm to be explicitly set by the caller break; } int status = BoltCommunication_open(connection->comm, address, connection->id); if (status==BOLT_SUCCESS) { BoltTime_get_time(&connection->metrics->time_opened); connection->tx_buffer = BoltBuffer_create(INITIAL_TX_BUFFER_SIZE); connection->rx_buffer = BoltBuffer_create(INITIAL_RX_BUFFER_SIZE); TRY(handshake_b(connection, 3, 2, 1, 0), "BoltConnection_open(%s:%d), handshake_b error code: %d", __FILE__, __LINE__); _set_status(connection, BOLT_CONNECTION_STATE_CONNECTED, BOLT_SUCCESS); } else { _set_status_from_comm(connection, BOLT_CONNECTION_STATE_DEFUNCT); return BOLT_STATUS_SET; } return connection->status->state==BOLT_CONNECTION_STATE_READY ? BOLT_SUCCESS : connection->status->error; } void BoltConnection_close(BoltConnection* connection) { if (connection->status->state!=BOLT_CONNECTION_STATE_DISCONNECTED) { _close(connection); } if (connection->rx_buffer!=NULL) { BoltBuffer_destroy(connection->rx_buffer); connection->rx_buffer = NULL; } if (connection->tx_buffer!=NULL) { BoltBuffer_destroy(connection->tx_buffer); connection->tx_buffer = NULL; } if (connection->address!=NULL) { BoltAddress_destroy((struct BoltAddress*) connection->address); connection->address = NULL; } if (connection->id!=NULL) { BoltMem_deallocate(connection->id, MAX_ID_LEN); connection->id = NULL; } } int32_t BoltConnection_send(BoltConnection* connection) { int size = BoltBuffer_unloadable(connection->tx_buffer); int status = BoltCommunication_send(connection->comm, BoltBuffer_unload_pointer(connection->tx_buffer, size), size, BoltConnection_id(connection)); if (status!=BOLT_SUCCESS) { _set_status_from_comm(connection, BOLT_CONNECTION_STATE_DEFUNCT); status = BOLT_STATUS_SET; } BoltBuffer_compact(connection->tx_buffer); return status; } int BoltConnection_receive(BoltConnection* connection, char* buffer, int size) { if (size==0) return 0; int available = BoltBuffer_unloadable(connection->rx_buffer); if (size>available) { int delta = size-available; while (delta>0) { int max_size = BoltBuffer_loadable(connection->rx_buffer); if (max_size==0) { BoltBuffer_compact(connection->rx_buffer); max_size = BoltBuffer_loadable(connection->rx_buffer); } max_size = delta>max_size ? delta : max_size; int received = 0; int status = BoltCommunication_receive(connection->comm, BoltBuffer_load_pointer(connection->rx_buffer, max_size), delta, max_size, &received, BoltConnection_id(connection)); if (status!=BOLT_SUCCESS) { _set_status_from_comm(connection, BOLT_CONNECTION_STATE_DEFUNCT); return BOLT_STATUS_SET; } // adjust the buffer extent based on the actual amount of data received connection->rx_buffer->extent = connection->rx_buffer->extent-max_size+received; delta -= received; } } BoltBuffer_unload(connection->rx_buffer, buffer, size); return BOLT_SUCCESS; } int BoltConnection_fetch(BoltConnection* connection, BoltRequest request) { const int fetched = connection->protocol->fetch(connection, request); if (fetched==FETCH_SUMMARY) { if (connection->protocol->is_success_summary(connection)) { _set_status(connection, BOLT_CONNECTION_STATE_READY, BOLT_SUCCESS); } else if (connection->protocol->is_ignored_summary(connection)) { // we may need to update status based on an earlier reported FAILURE // which our consumer did not care its result if (connection->protocol->failure(connection)!=NULL) { _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_FAILED, BOLT_SERVER_FAILURE, "BoltConnection_fetch(%s:%d), failure upon ignored message", __FILE__, __LINE__); } } else if (connection->protocol->is_failure_summary(connection)) { _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_FAILED, BOLT_SERVER_FAILURE, "BoltConnection_fetch(%s:%d), failure message", __FILE__, __LINE__); } else { BoltLog_error(connection->log, "[%s]: Protocol violation (received summary code %d)", BoltConnection_id(connection), connection->protocol->last_data_type(connection)); _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_DEFUNCT, BOLT_PROTOCOL_VIOLATION, "BoltConnection_fetch(%s:%d), received summary code: %d", __FILE__, __LINE__, connection->protocol->last_data_type(connection)); return FETCH_ERROR; } } return fetched; } int32_t BoltConnection_fetch_summary(BoltConnection* connection, BoltRequest request) { int records = 0; int data; do { data = BoltConnection_fetch(connection, request); if (data<0) { return data; } records += data; } while (data); return records; } struct BoltValue* BoltConnection_field_values(BoltConnection* connection) { return connection->protocol->field_values(connection); } int32_t BoltConnection_summary_success(BoltConnection* connection) { return connection->protocol->is_success_summary(connection); } int32_t BoltConnection_summary_failure(BoltConnection* connection) { return connection->protocol->is_failure_summary(connection); } int32_t BoltConnection_init(BoltConnection* connection, const char* user_agent, const struct BoltValue* auth_token) { BoltLog_info(connection->log, "[%s]: Initialising connection", BoltConnection_id(connection)); switch (connection->protocol_version) { case 1: case 2: case 3: { int code = connection->protocol->init(connection, user_agent, auth_token); switch (code) { case BOLT_V1_SUCCESS: _set_status(connection, BOLT_CONNECTION_STATE_READY, BOLT_SUCCESS); return 0; case BOLT_V1_FAILURE: _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_DEFUNCT, BOLT_PERMISSION_DENIED, "BoltConnection_init(%s:%d), failure message", __FILE__, __LINE__); return -1; default: BoltLog_error(connection->log, "[%s]: Protocol violation (received summary code %d)", BoltConnection_id(connection), code); _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_DEFUNCT, BOLT_PROTOCOL_VIOLATION, "BoltConnection_init(%s:%d), received summary code: %d", __FILE__, __LINE__, code); return -1; } } default: _set_status_with_ctx(connection, BOLT_CONNECTION_STATE_DEFUNCT, BOLT_PROTOCOL_UNSUPPORTED, "BoltConnection_init(%s:%d)", __FILE__, __LINE__); return -1; } } int32_t BoltConnection_clear_begin(BoltConnection* connection) { TRY(connection->protocol->clear_begin_tx(connection), "BoltConnection_clear_begin(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_set_begin_bookmarks(BoltConnection* connection, struct BoltValue* bookmark_list) { TRY(connection->protocol->set_begin_tx_bookmark(connection, bookmark_list), "BoltConnection_set_begin_bookmarks(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_set_begin_tx_timeout(BoltConnection* connection, int64_t timeout) { TRY(connection->protocol->set_begin_tx_timeout(connection, timeout), "BoltConnection_set_begin_tx_timeout(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_set_begin_tx_metadata(BoltConnection* connection, struct BoltValue* metadata) { TRY(connection->protocol->set_begin_tx_metadata(connection, metadata), "BoltConnection_set_begin_tx_metadata(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_begin_request(BoltConnection* connection) { TRY(connection->protocol->load_begin_tx(connection), "BoltConnection_load_begin_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_commit_request(BoltConnection* connection) { TRY(connection->protocol->load_commit_tx(connection), "BoltConnection_load_commit_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_rollback_request(BoltConnection* connection) { TRY(connection->protocol->load_rollback_tx(connection), "BoltConnection_load_rollback_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_clear_run(BoltConnection* connection) { TRY(connection->protocol->clear_run(connection), "BoltConnection_clear_run(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_set_run_cypher(BoltConnection* connection, const char* cypher, const uint64_t cypher_size, const int32_t n_parameter) { TRY(connection->protocol->set_run_cypher(connection, cypher, cypher_size, n_parameter), "BoltConnection_set_run_cypher(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } struct BoltValue* BoltConnection_set_run_cypher_parameter(BoltConnection* connection, int32_t index, const char* name, const uint64_t name_size) { return connection->protocol->set_run_cypher_parameter(connection, index, name, name_size); } int32_t BoltConnection_set_run_bookmarks(BoltConnection* connection, struct BoltValue* bookmark_list) { TRY(connection->protocol->set_run_bookmark(connection, bookmark_list), "BoltConnection_set_run_bookmarks(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_set_run_tx_timeout(BoltConnection* connection, int64_t timeout) { TRY(connection->protocol->set_run_tx_timeout(connection, timeout), "BoltConnection_set_run_tx_timeout(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_set_run_tx_metadata(BoltConnection* connection, struct BoltValue* metadata) { TRY(connection->protocol->set_run_tx_metadata(connection, metadata), "BoltConnection_set_run_tx_metadata(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_run_request(BoltConnection* connection) { TRY(connection->protocol->load_run(connection), "BoltConnection_load_run_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_discard_request(BoltConnection* connection, int32_t n) { TRY(connection->protocol->load_discard(connection, n), "BoltConnection_load_discard_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_pull_request(BoltConnection* connection, int32_t n) { TRY(connection->protocol->load_pull(connection, n), "BoltConnection_load_pull_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int32_t BoltConnection_load_reset_request(BoltConnection* connection) { TRY(connection->protocol->load_reset(connection), "BoltConnection_load_reset_request(%s:%d), error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } BoltRequest BoltConnection_last_request(BoltConnection* connection) { return connection->protocol->last_request(connection); } const char* BoltConnection_server(BoltConnection* connection) { return connection->protocol->server(connection); } const char* BoltConnection_id(BoltConnection* connection) { if (connection->protocol!=NULL && connection->protocol->id!=NULL) { return connection->protocol->id(connection); } return connection->id; } const BoltAddress* BoltConnection_address(BoltConnection* connection) { return connection->address; } const BoltAddress* BoltConnection_remote_endpoint(BoltConnection* connection) { return connection->comm!=NULL ? BoltCommunication_remote_endpoint(connection->comm) : NULL; } const BoltAddress* BoltConnection_local_endpoint(BoltConnection* connection) { return connection->comm!=NULL ? BoltCommunication_local_endpoint(connection->comm) : NULL; } const char* BoltConnection_last_bookmark(BoltConnection* connection) { return connection->protocol->last_bookmark(connection); } struct BoltValue* BoltConnection_field_names(BoltConnection* connection) { return connection->protocol->field_names(connection); } struct BoltValue* BoltConnection_metadata(BoltConnection* connection) { return connection->protocol->metadata(connection); } struct BoltValue* BoltConnection_failure(BoltConnection* connection) { return connection->protocol->failure(connection); } BoltStatus* BoltConnection_status(BoltConnection* connection) { return connection->status; } <|start_filename|>src/seabolt/tests/utils/test-context.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "test-context.h" #include <tuple> #include <algorithm> void record_debug_log(void* state, const char* message) { vector<string>* messages = (vector<string>*) state; messages->push_back(string("DEBUG: ")+message); } void record_info_log(void* state, const char* message) { vector<string>* messages = (vector<string>*) state; messages->push_back(string("INFO: ")+message); } void record_warning_log(void* state, const char* message) { vector<string>* messages = (vector<string>*) state; messages->push_back(string("WARNING: ")+message); } void record_error_log(void* state, const char* message) { vector<string>* messages = (vector<string>*) state; messages->push_back(string("ERROR: ")+message); } BoltLog* create_recording_logger(vector<string>* messages) { BoltLog* logger = BoltLog_create(messages); BoltLog_set_debug_func(logger, &record_debug_log); BoltLog_set_info_func(logger, &record_info_log); BoltLog_set_warning_func(logger, &record_warning_log); BoltLog_set_error_func(logger, &record_error_log); return logger; } TestContext::TestContext() { this->recording_log = create_recording_logger(&this->recorded_log_messages); } TestContext::~TestContext() { for (auto it = this->calls_cleanup.cbegin(); it!=this->calls_cleanup.cend(); ++it) { delete[] *it; } BoltLog_destroy(this->recording_log); } void TestContext::reset() { queue<tuple<string, int, intptr_t*>> empty; swap(this->calls, empty); this->calls_vector.clear(); this->recorded_log_messages.clear(); } void TestContext::add_call(string name, intptr_t value) { intptr_t* values = new intptr_t[1]; values[0] = value; this->calls_cleanup.push_back(values); this->calls.push(tuple<string, int, intptr_t*>(name, 1, values)); } void TestContext::add_call(string name, intptr_t value1, intptr_t value2) { intptr_t* values = new intptr_t[2]; values[0] = value1; values[1] = value2; this->calls_cleanup.push_back(values); this->calls.push(tuple<string, int, intptr_t*>(name, 2, values)); } tuple<string, int, intptr_t*> TestContext::next_call() { tuple<string, int, intptr_t*> expected = this->calls.front(); this->calls.pop(); return expected; } void TestContext::record_call(string name) { this->calls_vector.push_back(name); } BoltLog* TestContext::log() { return this->recording_log; } bool TestContext::contains_log(string message) const { auto begin = this->recorded_log_messages.cbegin(); auto end = this->recorded_log_messages.cend(); return std::find(begin, end, message)!=end; } <|start_filename|>src/seabolt/src/bolt/address-set.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "address-private.h" #include "address-set-private.h" #include "mem.h" volatile BoltAddressSet* BoltAddressSet_create() { struct BoltAddressSet* set = (struct BoltAddressSet*) BoltMem_allocate(SIZE_OF_ADDRESS_SET); set->size = 0; set->elements = NULL; return set; } void BoltAddressSet_destroy(volatile BoltAddressSet* set) { for (int i = 0; i<set->size; i++) { BoltAddress_destroy((BoltAddress*) set->elements[i]); } BoltMem_deallocate((void*) set->elements, set->size*sizeof(BoltAddress*)); BoltMem_deallocate((void*) set, SIZE_OF_ADDRESS_SET); } int32_t BoltAddressSet_size(volatile BoltAddressSet* set) { return set->size; } int32_t BoltAddressSet_index_of(volatile BoltAddressSet* set, volatile const BoltAddress* address) { for (int i = 0; i<set->size; i++) { volatile BoltAddress* current = set->elements[i]; if (strcmp(address->host, current->host)==0 && strcmp(address->port, current->port)==0) { return i; } } return -1; } int32_t BoltAddressSet_add(volatile BoltAddressSet* set, volatile const BoltAddress* address) { if (BoltAddressSet_index_of(set, address)==-1) { set->elements = BoltMem_reallocate((void*) set->elements, set->size*sizeof(BoltAddress*), (set->size+1)*sizeof(BoltAddress*)); set->elements[set->size] = BoltAddress_create(address->host, address->port); set->size++; return set->size-1; } return -1; } int32_t BoltAddressSet_remove(volatile BoltAddressSet* set, volatile const BoltAddress* address) { int index = BoltAddressSet_index_of(set, address); if (index>=0) { volatile BoltAddress** old_elements = set->elements; volatile BoltAddress** new_elements = BoltMem_allocate((set->size-1)*sizeof(BoltAddress*)); int new_elements_index = 0; for (int i = 0; i<set->size; i++) { if (i==index) { continue; } new_elements[new_elements_index++] = old_elements[i]; } BoltAddress_destroy((BoltAddress*) set->elements[index]); BoltMem_deallocate((void*) old_elements, set->size*sizeof(BoltAddress*)); set->elements = new_elements; set->size--; return index; } return -1; } void BoltAddressSet_replace(volatile BoltAddressSet* dest, volatile BoltAddressSet* source) { for (int i = 0; i<dest->size; i++) { BoltAddress_destroy((BoltAddress*) dest->elements[i]); } dest->elements = BoltMem_reallocate((void*) dest->elements, dest->size*sizeof(BoltAddress*), source->size*sizeof(BoltAddress*)); for (int i = 0; i<source->size; i++) { dest->elements[i] = BoltAddress_create(source->elements[i]->host, source->elements[i]->port); } dest->size = source->size; } void BoltAddressSet_add_all(volatile BoltAddressSet* destination, volatile BoltAddressSet* source) { for (int i = 0; i<source->size; i++) { BoltAddressSet_add(destination, (BoltAddress*) source->elements[i]); } } <|start_filename|>src/seabolt/src/bolt/sync.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_SYNC_H #define SEABOLT_SYNC_H #include "bolt-public.h" typedef void* mutex_t; typedef void* rwlock_t; typedef void* cond_t; int BoltSync_mutex_create(mutex_t* mutex); int BoltSync_mutex_destroy(mutex_t* mutex); int BoltSync_mutex_lock(mutex_t* mutex); int BoltSync_mutex_unlock(mutex_t* mutex); int BoltSync_mutex_trylock(mutex_t* mutex); int BoltSync_rwlock_create(rwlock_t* rwlock); int BoltSync_rwlock_destroy(rwlock_t* rwlock); int BoltSync_rwlock_rdlock(rwlock_t* rwlock); int BoltSync_rwlock_wrlock(rwlock_t* rwlock); int BoltSync_rwlock_tryrdlock(rwlock_t* rwlock); int BoltSync_rwlock_trywrlock(rwlock_t* rwlock); int BoltSync_rwlock_timedrdlock(rwlock_t* rwlock, int timeout_ms); int BoltSync_rwlock_timedwrlock(rwlock_t* rwlock, int timeout_ms); int BoltSync_rwlock_rdunlock(rwlock_t* rwlock); int BoltSync_rwlock_wrunlock(rwlock_t* rwlock); int BoltSync_cond_create(cond_t* cond); int BoltSync_cond_destroy(cond_t* cond); int BoltSync_cond_signal(cond_t* cond); int BoltSync_cond_broadcast(cond_t* cond); int BoltSync_cond_wait(cond_t* cond, mutex_t* mutex); int BoltSync_cond_timedwait(cond_t* cond, mutex_t* mutex, int timeout_ms); unsigned long BoltThread_id(); #endif //SEABOLT_SYNC_H <|start_filename|>src/seabolt/src/bolt/communication.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_COMMUNICATION_H #define SEABOLT_COMMUNICATION_H #include "bolt-private.h" #include "address.h" #include "config.h" #include "protocol.h" typedef struct BoltCommunication BoltCommunication; typedef BoltAddress* endpoint_func(struct BoltCommunication*); typedef int int_func(int); typedef int comm_func(BoltCommunication*); typedef int comm_with_int_func(BoltCommunication*, int); typedef int comm_open_func(BoltCommunication*, const struct sockaddr_storage*); typedef int comm_send_func(BoltCommunication*, char*, int, int*); typedef int comm_receive_func(BoltCommunication*, char*, int, int*); typedef BoltAddress* comm_get_endpoint(BoltCommunication*); typedef struct BoltCommunication { comm_open_func* open; comm_func* close; comm_send_func* send; comm_receive_func* recv; comm_func* destroy; comm_func* ignore_sigpipe; comm_func* restore_sigpipe; comm_func* last_error; comm_with_int_func* transform_error; comm_get_endpoint* get_local_endpoint; comm_get_endpoint* get_remote_endpoint; BoltStatus* status; int status_owned; BoltSocketOptions* sock_opts; int sock_opts_owned; BoltLog* log; void* context; } BoltCommunication; int BoltCommunication_startup(); int BoltCommunication_shutdown(); int BoltCommunication_open(BoltCommunication* comm, BoltAddress* address, const char* id); int BoltCommunication_send(BoltCommunication* comm, char* buffer, int size, const char* id); int BoltCommunication_close(BoltCommunication* comm, const char* id); int BoltCommunication_receive(BoltCommunication* comm, char* buffer, int min_size, int max_size, int* received, const char* id); BoltAddress* BoltCommunication_local_endpoint(BoltCommunication* comm); BoltAddress* BoltCommunication_remote_endpoint(BoltCommunication* comm); void BoltCommunication_destroy(BoltCommunication* comm); #endif //SEABOLT_COMMUNICATION_H <|start_filename|>src/seabolt/src/bolt/lifecycle.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "lifecycle.h" #include "communication.h" #include "communication-secure.h" void Bolt_startup() { #if USE_WINSOCK WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); #endif BoltCommunication_startup(); BoltSecurityContext_startup(); } void Bolt_shutdown() { #if USE_WINSOCK WSACleanup(); #endif BoltSecurityContext_shutdown(); BoltCommunication_shutdown(); } <|start_filename|>src/seabolt/src/bolt/config-private.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_CONFIG_PRIVATE_H #define SEABOLT_CONFIG_PRIVATE_H #include "config.h" /** * Use BOLT_SCHEME_CONNECTION to establish connections on-demand to a single server without * any connection pooling kicking in. The returned connection will behave as * BOLT_SCHEME_DIRECT. */ #define BOLT_SCHEME_DIRECT_UNPOOLED 2 struct BoltTrust { char* certs; uint64_t certs_len; int32_t skip_verify; int32_t skip_verify_hostname; }; struct BoltSocketOptions { int32_t connect_timeout; int32_t recv_timeout; int32_t send_timeout; int32_t keep_alive; }; struct BoltConfig { BoltScheme scheme; BoltTransport transport; struct BoltTrust* trust; char* user_agent; struct BoltValue* routing_context; struct BoltAddressResolver* address_resolver; struct BoltLog* log; int32_t max_pool_size; int32_t max_connection_life_time; int32_t max_connection_acquisition_time; struct BoltSocketOptions* socket_options; }; BoltConfig* BoltConfig_clone(BoltConfig* config); BoltTrust* BoltTrust_clone(BoltTrust* source); BoltSocketOptions* BoltSocketOptions_clone(BoltSocketOptions* socket_options); #endif //SEABOLT_CONFIG_PRIVATE_H <|start_filename|>make.cmd<|end_filename|> @Echo Off If "%~1" == "" ( Goto :Usage ) Else If Not "%~1" == "MSVC" ( If Not "%~1" == "MINGW" ( Goto :Usage ) ) If "%~2" == "" ( Goto :Usage ) Else If Not "%~2" == "Debug" ( If Not "%~2" == "Release" ( Goto :Usage ) ) If "%~3" == "" ( Goto :Usage ) Else If Not "%~3" == "x86" ( If Not "%~3" == "x64" ( Goto :Usage ) ) If "%~4" == "" ( Goto :Usage ) Else If Not "%~4" == "package" ( If Not "%~4" == "install" ( Goto :Usage ) ) If "%~1" == "MSVC" ( Set "BUILDTYPE=msvc" Set "CMAKE_GENERATOR=Visual Studio 15 2017 Win64" If "%~3" == "x86" ( Set "CMAKE_GENERATOR=Visual Studio 15 2017" ) ) If "%~1" == "MINGW" ( Set "BUILDTYPE=mingw" Set "CMAKE_GENERATOR=MinGW Makefiles" ) If "%~2" == "Debug" ( Set "BUILDCONFIG=debug" Set "CMAKE_BUILD=Debug" ) If "%~2" == "Release" ( Set "BUILDCONFIG=release" Set "CMAKE_BUILD=RelWithDebInfo" ) Set TARGET=%~4 Set SEABOLTDIR=%~dp0 Set BUILDDIR=%SEABOLTDIR%\build-%BUILDTYPE%-%BUILDCONFIG% Mkdir %BUILDDIR% Pushd %BUILDDIR% cmake.exe -G "%CMAKE_GENERATOR%" -DCMAKE_CONFIGURATION_TYPES=%CMAKE_BUILD% -DCMAKE_BUILD_TYPE=%CMAKE_BUILD% -DCMAKE_INSTALL_PREFIX=dist .. || Goto :Failure cmake.exe --build . --target %TARGET% --config %CMAKE_BUILD% || Goto :Failure Popd Exit /b 0 :Usage @Echo "Usage: %~n0 (MSVC|MINGW) (Debug|Release) (x86|x64) (install|package)" Goto :Failure :Failure If "%NEO4J_CHILD_SCRIPT%" == "" ( If Not "%TEAMCITY_PROJECT_NAME%" == "" ( ECHO ##teamcity[buildStatus status='FAILURE' text='compilation failed'] ) ) popd.exe Exit /b 1 <|start_filename|>src/seabolt/src/bolt/address.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <string.h> #include "bolt-private.h" #include "address-private.h" #include "log-private.h" #include "mem.h" #include "name.h" #include "sync.h" #define DEFAULT_BOLT_PORT "7687" #define DEFAULT_BOLT_HOST "localhost" #define SOCKADDR_STORAGE_SIZE sizeof(struct sockaddr_storage) BoltAddress* BoltAddress_create(const char* host, const char* port) { BoltAddress* address = (BoltAddress*) BoltMem_allocate(sizeof(BoltAddress)); if (host==NULL || strlen(host)==0) { host = DEFAULT_BOLT_HOST; } address->host = (char*) BoltMem_duplicate(host, strlen(host)+1); if (port==NULL || strlen(port)==0) { port = DEFAULT_BOLT_PORT; } address->port = (char*) BoltMem_duplicate(port, strlen(port)+1); address->n_resolved_hosts = 0; address->resolved_hosts = NULL; address->resolved_port = 0; address->lock = NULL; return address; } BoltAddress* BoltAddress_create_with_lock(const char* host, const char* port) { BoltAddress* address = BoltAddress_create(host, port); BoltSync_rwlock_create(&address->lock); return address; } const char* BoltAddress_host(BoltAddress* address) { return address->host; } const char* BoltAddress_port(BoltAddress* address) { return address->port; } BoltAddress* BoltAddress_create_from_string(const char* endpoint_str, uint64_t endpoint_len) { // Create a copy of the string and add null character at the end to properly // work with string functions char* address_str = (char*) BoltMem_duplicate(endpoint_str, endpoint_len+1); address_str[endpoint_len] = '\0'; // Find the last index of `:` which is our port separator char* port_str = strrchr(address_str, ':'); if (port_str!=NULL) { // If we found the separator, set it to null and advance the pointer by 1 // By this we have two null terminated strings pointed by address_str (hostname) // port_str (port) *port_str++ = '\0'; } BoltAddress* result = BoltAddress_create(address_str, port_str); BoltMem_deallocate(address_str, endpoint_len+1); return result; } int32_t BoltAddress_resolve(BoltAddress* address, int32_t* n_resolved, BoltLog* log) { if (address->lock!=NULL) { BoltSync_rwlock_wrlock(&address->lock); } if (strchr(address->host, ':')==NULL) { BoltLog_info(log, "[addr]: Resolving address %s:%s", address->host, address->port); } else { BoltLog_info(log, "[addr]: Resolving address [%s]:%s", address->host, address->port); } struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG); struct addrinfo* ai; const int gai_status = getaddrinfo(address->host, address->port, &hints, &ai); if (gai_status==0) { unsigned short count = 0; for (struct addrinfo* ai_node = ai; ai_node!=NULL; ai_node = ai_node->ai_next) { switch (ai_node->ai_family) { case AF_INET: case AF_INET6: { count += 1; break; } default: // We only care about IPv4 and IPv6 continue; } } address->resolved_hosts = BoltMem_reallocate((void*) address->resolved_hosts, address->n_resolved_hosts*SOCKADDR_STORAGE_SIZE, count*SOCKADDR_STORAGE_SIZE); address->n_resolved_hosts = count; size_t p = 0; for (struct addrinfo* ai_node = ai; ai_node!=NULL; ai_node = ai_node->ai_next) { switch (ai_node->ai_family) { case AF_INET: case AF_INET6: { memcpy((void*) &address->resolved_hosts[p], ai_node->ai_addr, ai_node->ai_addrlen); break; } default: // We only care about IPv4 and IPv6 continue; } p += 1; } freeaddrinfo(ai); if (address->n_resolved_hosts==1) { BoltLog_info(log, "[addr]: Host resolved to 1 IP address"); } else { BoltLog_info(log, "[addr]: Host resolved to %d IP addresses", address->n_resolved_hosts); } } else { BoltLog_info(log, "[addr]: Host resolution failed (status %d)", gai_status); } if (address->n_resolved_hosts>0) { volatile struct sockaddr_storage* resolved = &address->resolved_hosts[0]; const uint16_t resolved_port = resolved->ss_family==AF_INET ? ((struct sockaddr_in*) (resolved))->sin_port : ((struct sockaddr_in6*) (resolved))->sin6_port; address->resolved_port = ntohs(resolved_port); } if (gai_status==0 && n_resolved!=NULL) { *n_resolved = address->n_resolved_hosts; } if (address->lock!=NULL) { BoltSync_rwlock_wrunlock(&address->lock); } return gai_status; } int32_t BoltAddress_resolved_count(BoltAddress* address) { if (address->lock!=NULL) { BoltSync_rwlock_rdlock(&address->lock); } int32_t result = address->n_resolved_hosts; if (address->lock!=NULL) { BoltSync_rwlock_rdunlock(&address->lock); } return result; } int BoltAddress_resolved_addr(BoltAddress* address, int32_t index, struct sockaddr_storage* target) { if (address->lock!=NULL) { BoltSync_rwlock_rdlock(&address->lock); } int32_t result = 0; if (address->n_resolved_hosts>index) { memcpy(target, (const void*) &address->resolved_hosts[index], sizeof(struct sockaddr_storage)); result = 1; } if (address->lock!=NULL) { BoltSync_rwlock_rdunlock(&address->lock); } return result; } int32_t BoltAddress_copy_resolved_host(BoltAddress* address, int32_t index, char* buffer, int32_t buffer_size) { if (address->lock!=NULL) { BoltSync_rwlock_rdlock(&address->lock); } int32_t result; volatile struct sockaddr_storage* resolved_host = &address->resolved_hosts[index]; int status = get_address_components(resolved_host, buffer, (int) buffer_size, NULL, 0); switch (status) { case 0: result = resolved_host->ss_family; break; default: result = -1; break; } if (address->lock!=NULL) { BoltSync_rwlock_rdunlock(&address->lock); } return result; } void BoltAddress_destroy(BoltAddress* address) { if (address->resolved_hosts!=NULL) { address->resolved_hosts = BoltMem_deallocate((void*) address->resolved_hosts, address->n_resolved_hosts*SOCKADDR_STORAGE_SIZE); address->n_resolved_hosts = 0; } if (address->lock!=NULL) { BoltSync_rwlock_destroy(&address->lock); } BoltMem_deallocate((char*) address->host, strlen(address->host)+1); BoltMem_deallocate((char*) address->port, strlen(address->port)+1); BoltMem_deallocate(address, sizeof(BoltAddress)); } <|start_filename|>src/seabolt/src/bolt/sync-pthread.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "sync.h" #include "mem.h" #include "time.h" #include <pthread.h> #include <sys/time.h> void BoltSync_sleep(int milliseconds) { usleep(milliseconds*1000); } int BoltSync_mutex_create(mutex_t* mutex) { *mutex = BoltMem_allocate(sizeof(pthread_mutex_t)); pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); return pthread_mutex_init(*mutex, &mutex_attr); } int BoltSync_mutex_destroy(mutex_t* mutex) { int status = pthread_mutex_destroy(*mutex); BoltMem_deallocate(*mutex, sizeof(pthread_mutex_t)); return status; } int BoltSync_mutex_lock(mutex_t* mutex) { return pthread_mutex_lock(*mutex); } int BoltSync_mutex_unlock(mutex_t* mutex) { return pthread_mutex_unlock(*mutex); } int BoltSync_mutex_trylock(mutex_t* mutex) { return pthread_mutex_trylock(*mutex)==0; } int BoltSync_rwlock_create(rwlock_t* rwlock) { *rwlock = BoltMem_allocate(sizeof(pthread_rwlock_t)); return pthread_rwlock_init(*rwlock, NULL)==0; } int BoltSync_rwlock_destroy(rwlock_t* rwlock) { int status = pthread_rwlock_destroy(*rwlock)==0; BoltMem_deallocate(*rwlock, sizeof(pthread_rwlock_t)); *rwlock = NULL; return status; } int BoltSync_rwlock_rdlock(rwlock_t* rwlock) { return pthread_rwlock_rdlock(*rwlock)==0; } int BoltSync_rwlock_wrlock(rwlock_t* rwlock) { return pthread_rwlock_wrlock(*rwlock)==0; } int BoltSync_rwlock_tryrdlock(rwlock_t* rwlock) { return pthread_rwlock_tryrdlock(*rwlock)==0; } int BoltSync_rwlock_trywrlock(rwlock_t* rwlock) { return pthread_rwlock_trywrlock(*rwlock)==0; } int BoltSync_rwlock_timedrdlock(rwlock_t* rwlock, int timeout_ms) { int64_t end_at = BoltTime_get_time_ms()+timeout_ms; while (1) { if (BoltSync_rwlock_tryrdlock(rwlock)) { return 1; } if (BoltTime_get_time_ms()>end_at) { return 0; } BoltSync_sleep(10); } } int BoltSync_rwlock_timedwrlock(rwlock_t* rwlock, int timeout_ms) { int64_t end_at = BoltTime_get_time_ms()+timeout_ms; while (1) { if (BoltSync_rwlock_trywrlock(rwlock)) { return 1; } if (BoltTime_get_time_ms()>end_at) { return 0; } BoltSync_sleep(10); } } int BoltSync_rwlock_rdunlock(rwlock_t* rwlock) { return pthread_rwlock_unlock(*rwlock)==0; } int BoltSync_rwlock_wrunlock(rwlock_t* rwlock) { return pthread_rwlock_unlock(*rwlock)==0; } int BoltSync_cond_create(cond_t* cond) { *cond = BoltMem_allocate(sizeof(pthread_cond_t)); return pthread_cond_init(*cond, NULL)==0; } int BoltSync_cond_destroy(cond_t* cond) { int status = pthread_cond_destroy(*cond)==0; BoltMem_deallocate(*cond, sizeof(pthread_cond_t)); return status; } int BoltSync_cond_signal(cond_t* cond) { return pthread_cond_signal(*cond)==0; } int BoltSync_cond_broadcast(cond_t* cond) { return pthread_cond_broadcast(*cond)==0; } int BoltSync_cond_wait(cond_t* cond, mutex_t* mutex) { return pthread_cond_wait(*cond, *mutex); } int BoltSync_cond_timedwait(cond_t* cond, mutex_t* mutex, int timeout_ms) { struct timeval now; struct timespec timeout; gettimeofday(&now, NULL); timeout.tv_sec = now.tv_sec+(timeout_ms/1000); timeout.tv_nsec = (now.tv_usec*1000)+((timeout_ms%1000)*1000000); if (timeout.tv_nsec>=NANOS_PER_SEC) { timeout.tv_sec++; timeout.tv_nsec -= NANOS_PER_SEC; } return pthread_cond_timedwait(*cond, *mutex, &timeout)==0; } unsigned long BoltThread_id() { return (unsigned long) pthread_self(); } <|start_filename|>src/seabolt/src/bolt/communication-secure.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_COMMUNICATION_SECURE_H #define SEABOLT_COMMUNICATION_SECURE_H #include "communication.h" typedef struct BoltSecurityContext BoltSecurityContext; int BoltSecurityContext_startup(); int BoltSecurityContext_shutdown(); BoltSecurityContext* BoltSecurityContext_create(BoltTrust* trust, const char* hostname, const BoltLog* log, const char* id); void BoltSecurityContext_destroy(BoltSecurityContext* context); BoltCommunication* BoltCommunication_create_secure(BoltSecurityContext* sec_ctx, BoltTrust* trust, BoltSocketOptions* socket_options, BoltLog* log, const char* hostname, const char* id); #endif //SEABOLT_COMMUNICATION_SECURE_H <|start_filename|>src/seabolt/src/bolt/auth.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <string.h> #include "auth.h" BoltValue* BoltAuth_basic(const char* username, const char* password, const char* realm) { struct BoltValue* auth_token = BoltValue_create(); BoltValue_format_as_Dictionary(auth_token, realm==NULL ? 3 : 4); BoltDictionary_set_key(auth_token, 0, "scheme", 6); BoltValue_format_as_String(BoltDictionary_value(auth_token, 0), "basic", 5); BoltDictionary_set_key(auth_token, 1, "principal", 9); BoltValue_format_as_String(BoltDictionary_value(auth_token, 1), username, (int32_t) strlen(username)); BoltDictionary_set_key(auth_token, 2, "credentials", 11); BoltValue_format_as_String(BoltDictionary_value(auth_token, 2), password, (int32_t) strlen(password)); if (realm!=NULL) { BoltDictionary_set_key(auth_token, 3, "realm", 5); BoltValue_format_as_String(BoltDictionary_value(auth_token, 3), realm, (int32_t) strlen(realm)); } return auth_token; } BoltValue* BoltAuth_none() { struct BoltValue* auth_token = BoltValue_create(); BoltValue_format_as_Dictionary(auth_token, 1); BoltDictionary_set_key(auth_token, 0, "scheme", 6); BoltValue_format_as_String(BoltDictionary_value(auth_token, 0), "none", 5); return auth_token; } <|start_filename|>src/seabolt/tests/test-communication.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <string> #include <vector> #include <queue> #include <algorithm> #include "integration.hpp" #include "catch.hpp" #include "utils/test-context.h" using namespace Catch::Matchers; using namespace std; #define RENDER_STD_MOCK_CALL(type, name) \ auto ctx = (TestContext*) comm->context; \ tuple<string, int, intptr_t*> call = ctx->next_call(); \ if (get<0>(call)!=name) { \ throw "expected"+get<0>(call)+", but called "+name;\ }\ ctx->record_call(name);\ return (type)(get<2>(call)[0]) int test_open(BoltCommunication* comm, const struct sockaddr_storage* address) { UNUSED(address); RENDER_STD_MOCK_CALL(int, "open"); } int test_close(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(int, "close"); } int test_send(BoltCommunication* comm, char* buf, int length, int* sent) { UNUSED(buf); UNUSED(length); UNUSED(sent); auto ctx = (TestContext*) comm->context; tuple<string, int, intptr_t*> call = ctx->next_call(); if (get<0>(call)!="send") { throw "expected send but called "+get<0>(call); } ctx->record_call("send"); intptr_t* values = get<2>(call); *sent = (int) values[1]; return (int) (values[0]); } int test_recv(BoltCommunication* comm, char* buf, int length, int* received) { UNUSED(buf); UNUSED(length); UNUSED(received); auto ctx = (TestContext*) comm->context; tuple<string, int, intptr_t*> call = ctx->next_call(); if (get<0>(call)!="recv") { throw "expected recv but called "+get<0>(call); } ctx->record_call("recv"); intptr_t* values = get<2>(call); *received = (int) values[1]; return (int) (values[0]); } int test_destroy(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(int, "destroy"); } int test_ignore_sigpipe(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(int, "ignore_sigpipe"); } int test_restore_sigpipe(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(int, "restore_sigpipe"); } int test_last_error(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(int, "last_error"); } int test_transform_error(BoltCommunication* comm, int error_code) { UNUSED(error_code); RENDER_STD_MOCK_CALL(int, "transform_error"); } BoltAddress* test_local_endpoint(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(BoltAddress*, "local_endpoint"); } BoltAddress* test_remote_endpoint(BoltCommunication* comm) { RENDER_STD_MOCK_CALL(BoltAddress*, "remote_endpoint"); } TEST_CASE("communication", "[unit]") { BoltSocketOptions* sock_opts = BoltSocketOptions_create(); BoltStatus* status = BoltStatus_create_with_ctx(1024); BoltAddress* local = BoltAddress_create("127.0.0.1", "32000"); TestContext* test_ctx = new TestContext(); auto comm_under_test = new(BoltCommunication); comm_under_test->log = test_ctx->log(); comm_under_test->sock_opts = sock_opts; comm_under_test->context = test_ctx; comm_under_test->status = status; comm_under_test->open = &test_open; comm_under_test->close = &test_close; comm_under_test->send = &test_send; comm_under_test->recv = &test_recv; comm_under_test->destroy = &test_destroy; comm_under_test->ignore_sigpipe = &test_ignore_sigpipe; comm_under_test->restore_sigpipe = &test_restore_sigpipe; comm_under_test->last_error = &test_last_error; comm_under_test->transform_error = &test_transform_error; comm_under_test->get_local_endpoint = &test_local_endpoint; comm_under_test->get_remote_endpoint = &test_remote_endpoint; SECTION("BoltCommunication_open") { WHEN("unresolved address is given") { BoltAddress* unresolved = BoltAddress_create("host", "port"); THEN("should return BOLT_ADDRESS_NOT_RESOVED") { int result = BoltCommunication_open(comm_under_test, unresolved, nullptr); REQUIRE(result==BOLT_ADDRESS_NOT_RESOLVED); } BoltAddress_destroy(unresolved); } WHEN("resolved address with unsupported address family is given") { BoltAddress* unsupported = BoltAddress_create("127.0.0.1", "7687"); REQUIRE(BoltAddress_resolve(unsupported, NULL, NULL)==0); unsupported->resolved_hosts[0].ss_family = AF_IPX; int result = BoltCommunication_open(comm_under_test, unsupported, "id-0"); THEN("should return error") { REQUIRE(result==BOLT_UNSUPPORTED); } AND_THEN("should create a log entry") { REQUIRE_THAT(*test_ctx, ContainsLog("ERROR: [id-0]: Unsupported address family "+to_string(AF_IPX))); } BoltAddress_destroy(unsupported); } WHEN("resolved address with 1 socket address is given") { BoltAddress* remote = BoltAddress_create("127.0.0.1", "7687"); REQUIRE(BoltAddress_resolve(remote, NULL, NULL)==0); test_ctx->reset(); AND_WHEN("connection attempt fails") { test_ctx->add_call("open", BOLT_CONNECTION_REFUSED); int result = BoltCommunication_open(comm_under_test, remote, "id-0"); THEN("should return error") { REQUIRE(result==BOLT_CONNECTION_REFUSED); } THEN("should log connection attempt") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7687")); } } AND_WHEN("connection attempt succeeds") { test_ctx->add_call("open", BOLT_SUCCESS); test_ctx->add_call("remote_endpoint", (intptr_t) remote); test_ctx->add_call("local_endpoint", (intptr_t) local); int result = BoltCommunication_open(comm_under_test, remote, "id-0"); THEN("should return success") { REQUIRE(result==BOLT_SUCCESS); } THEN("should log connection attempt") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7687")); } THEN("should log remote endpoint") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Remote endpoint is 127.0.0.1:7687")); } THEN("should log local endpoint") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Local endpoint is 127.0.0.1:32000")); } } BoltAddress_destroy(remote); } WHEN("resolved address with 2 socket address is given") { BoltAddress* remote1 = BoltAddress_create("127.0.0.1", "7687"); REQUIRE(BoltAddress_resolve(remote1, NULL, NULL)==0); BoltAddress* remote2 = BoltAddress_create("127.0.0.1", "7688"); REQUIRE(BoltAddress_resolve(remote2, NULL, NULL)==0); BoltAddress* remote = BoltAddress_create("127.0.0.1", "7687"); remote->n_resolved_hosts = 2; remote->resolved_hosts = (struct sockaddr_storage*) malloc(2*sizeof(struct sockaddr_storage)); memcpy((void*) &remote->resolved_hosts[0], (void*) &remote1->resolved_hosts[0], sizeof(struct sockaddr_storage)); memcpy((void*) &remote->resolved_hosts[1], (void*) &remote2->resolved_hosts[0], sizeof(struct sockaddr_storage)); test_ctx->reset(); AND_WHEN("all connection attempts fail") { test_ctx->add_call("open", BOLT_CONNECTION_REFUSED); test_ctx->add_call("open", BOLT_NETWORK_UNREACHABLE); int result = BoltCommunication_open(comm_under_test, remote, "id-0"); THEN("should return last error") { REQUIRE(result==BOLT_NETWORK_UNREACHABLE); } THEN("should log connection attempt 1") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7687")); } THEN("should log connection attempt 2") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7688")); } } AND_WHEN("first connection attempt succeeds") { test_ctx->add_call("open", BOLT_SUCCESS); test_ctx->add_call("remote_endpoint", (intptr_t) remote); test_ctx->add_call("local_endpoint", (intptr_t) local); int result = BoltCommunication_open(comm_under_test, remote, "id-0"); THEN("should return success") { REQUIRE(result==BOLT_SUCCESS); } THEN("should log connection attempt") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7687")); } THEN("should log remote endpoint") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Remote endpoint is 127.0.0.1:7687")); } THEN("should log local endpoint") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Local endpoint is 127.0.0.1:32000")); } } AND_WHEN("first connection attempt fails") { test_ctx->add_call("open", BOLT_CONNECTION_REFUSED); test_ctx->add_call("open", BOLT_SUCCESS); test_ctx->add_call("remote_endpoint", (intptr_t) remote2); test_ctx->add_call("local_endpoint", (intptr_t) local); int result = BoltCommunication_open(comm_under_test, remote, "id-0"); THEN("should return success") { REQUIRE(result==BOLT_SUCCESS); } THEN("should log connection attempt 1") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7687")); } THEN("should log connection attempt 2") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Opening IPv4 connection to 127.0.0.1 at port 7688")); } THEN("should log remote endpoint") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Remote endpoint is 127.0.0.1:7688")); } THEN("should log local endpoint") { REQUIRE_THAT(*test_ctx, ContainsLog("INFO: [id-0]: Local endpoint is 127.0.0.1:32000")); } } BoltAddress_destroy(remote1); BoltAddress_destroy(remote2); BoltAddress_destroy(remote); } } SECTION("BoltCommunication_close") { test_ctx->reset(); WHEN("close succeeds") { test_ctx->add_call("ignore_sigpipe", 0); test_ctx->add_call("close", 0); test_ctx->add_call("restore_sigpipe", 0); int result = BoltCommunication_close(comm_under_test, "id-1"); THEN("should return success") { REQUIRE(result==BOLT_SUCCESS); } THEN("should create a log entry") { REQUIRE_THAT(*test_ctx, ContainsLog("DEBUG: [id-1]: Closing socket")); } } WHEN("close fails") { test_ctx->add_call("ignore_sigpipe", 0); test_ctx->add_call("close", BOLT_END_OF_TRANSMISSION); test_ctx->add_call("restore_sigpipe", 0); int result = BoltCommunication_close(comm_under_test, "id-1"); THEN("should return success") { REQUIRE(result==BOLT_END_OF_TRANSMISSION); } THEN("should create a log entry") { REQUIRE_THAT(*test_ctx, ContainsLog("DEBUG: [id-1]: Closing socket")); } THEN("should create a warning log entry") { REQUIRE_THAT(*test_ctx, ContainsLog("WARNING: [id-1]: Unable to close socket, return code is " +to_string(BOLT_END_OF_TRANSMISSION))); } } WHEN("ignore_sigaction fails") { test_ctx->add_call("ignore_sigpipe", BOLT_UNKNOWN_ERROR); int result = BoltCommunication_close(comm_under_test, "id-1"); THEN("should fail") { REQUIRE(result==BOLT_UNKNOWN_ERROR); } THEN("should not create a log entry") { REQUIRE_THAT(*test_ctx, NotContainsLog("DEBUG: [id-1]: Closing socket")); } THEN("should set status") { REQUIRE(status->error==BOLT_UNKNOWN_ERROR); REQUIRE_THAT(status->error_ctx, Contains("unable to ignore SIGPIPE")); } } WHEN("restore_sigaction fails") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("close", BOLT_SUCCESS); test_ctx->add_call("restore_sigpipe", BOLT_UNKNOWN_ERROR); int result = BoltCommunication_close(comm_under_test, "id-1"); THEN("should fail") { REQUIRE(result==BOLT_UNKNOWN_ERROR); } THEN("should create a log entry") { REQUIRE_THAT(*test_ctx, ContainsLog("DEBUG: [id-1]: Closing socket")); } THEN("should set status") { REQUIRE(status->error==BOLT_UNKNOWN_ERROR); REQUIRE_THAT(status->error_ctx, Contains("unable to restore SIGPIPE")); } } } SECTION("BoltCommunication_send") { test_ctx->reset(); WHEN("size is 0") { int result = BoltCommunication_send(comm_under_test, NULL, 0, "id-0"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("should not make any unexpected calls") { REQUIRE(test_ctx->recorded_calls().empty()); } } WHEN("send fails") { AND_WHEN("in first round") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("send", BOLT_END_OF_TRANSMISSION, 0); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int result = BoltCommunication_send(comm_under_test, NULL, 100, "id-1"); THEN("should fail") { REQUIRE(result==BOLT_STATUS_SET); } THEN("should not create log entry") { REQUIRE(test_ctx->recorded_messages().empty()); } THEN("should set status") { REQUIRE(status->error==BOLT_END_OF_TRANSMISSION); REQUIRE_THAT(status->error_ctx, Contains("unable to send data: "+to_string(BOLT_END_OF_TRANSMISSION))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "send", "restore_sigpipe"})); } } AND_WHEN("in later rounds") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("send", BOLT_SUCCESS, 75); test_ctx->add_call("send", BOLT_END_OF_TRANSMISSION, 0); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int result = BoltCommunication_send(comm_under_test, NULL, 100, "id-1"); THEN("should fail") { REQUIRE(result==BOLT_STATUS_SET); } THEN("should not create log entry") { REQUIRE(test_ctx->recorded_messages().empty()); } THEN("should set status") { REQUIRE(status->error==BOLT_END_OF_TRANSMISSION); REQUIRE_THAT(status->error_ctx, Contains("unable to send data: "+to_string(BOLT_END_OF_TRANSMISSION))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "send", "send", "restore_sigpipe"})); } } } WHEN("size is 100") { AND_WHEN("send processes all in one go") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("send", BOLT_SUCCESS, 100); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int result = BoltCommunication_send(comm_under_test, NULL, 100, "id-1"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-1]: (Sent 100 of 100 bytes)"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "send", "restore_sigpipe"})); } } AND_WHEN("send processes smaller chunks") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("send", BOLT_SUCCESS, 25); test_ctx->add_call("send", BOLT_SUCCESS, 25); test_ctx->add_call("send", BOLT_SUCCESS, 45); test_ctx->add_call("send", BOLT_SUCCESS, 5); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int result = BoltCommunication_send(comm_under_test, NULL, 100, "id-1"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-1]: (Sent 100 of 100 bytes)"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "send", "send", "send", "send", "restore_sigpipe"})); } } } WHEN("ignore_sigaction fails") { test_ctx->add_call("ignore_sigpipe", BOLT_UNKNOWN_ERROR); int result = BoltCommunication_send(comm_under_test, NULL, 1, "id-0"); THEN("should fail") { REQUIRE(result==BOLT_UNKNOWN_ERROR); } THEN("should not create a log entry") { REQUIRE(test_ctx->recorded_messages().empty()); } THEN("should set status") { REQUIRE(status->error==BOLT_UNKNOWN_ERROR); REQUIRE_THAT(status->error_ctx, Contains("unable to ignore SIGPIPE")); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe"})); } } WHEN("restore_sigaction fails") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("send", BOLT_SUCCESS, 25); test_ctx->add_call("send", BOLT_SUCCESS, 25); test_ctx->add_call("send", BOLT_SUCCESS, 45); test_ctx->add_call("send", BOLT_SUCCESS, 5); test_ctx->add_call("restore_sigpipe", BOLT_UNKNOWN_ERROR); int result = BoltCommunication_send(comm_under_test, NULL, 100, "id-1"); THEN("should succeed") { REQUIRE(result==BOLT_UNKNOWN_ERROR); } THEN("should set status") { REQUIRE(status->error==BOLT_UNKNOWN_ERROR); REQUIRE_THAT(status->error_ctx, Contains("unable to restore SIGPIPE")); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "send", "send", "send", "send", "restore_sigpipe"})); } } } SECTION("BoltCommunication_receive") { test_ctx->reset(); WHEN("min size is 0") { int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, 0, 100, &received, "id-0"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("should not make any unexpected calls") { REQUIRE(test_ctx->recorded_calls().empty()); } } WHEN("min size is 100") { int min_size = 100; AND_WHEN("max size is 100") { int max_size = 100; AND_WHEN("recv receives all in one go") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("recv", BOLT_SUCCESS, 100); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, min_size, max_size, &received, "id-2"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("returns correct received byte count") { REQUIRE(received==100); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-2]: Received 100 of 100 bytes"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "recv", "restore_sigpipe"})); } } AND_WHEN("recv receives in smaller chunks") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("recv", BOLT_SUCCESS, 50); test_ctx->add_call("recv", BOLT_SUCCESS, 30); test_ctx->add_call("recv", BOLT_SUCCESS, 20); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, min_size, max_size, &received, "id-2"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("returns correct received byte count") { REQUIRE(received==100); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-2]: Received 100 of 100 bytes"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "recv", "recv", "recv", "restore_sigpipe"})); } } } AND_WHEN("max size is 200") { int max_size = 200; AND_WHEN("recv receives all in one go") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("recv", BOLT_SUCCESS, 100); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, min_size, max_size, &received, "id-2"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("returns correct received byte count") { REQUIRE(received==100); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-2]: Received 100 of 100..200 bytes"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "recv", "restore_sigpipe"})); } } AND_WHEN("recv receives in smaller chunks") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("recv", BOLT_SUCCESS, 50); test_ctx->add_call("recv", BOLT_SUCCESS, 30); test_ctx->add_call("recv", BOLT_SUCCESS, 20); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, min_size, max_size, &received, "id-2"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("returns correct received byte count") { REQUIRE(received==100); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-2]: Received 100 of 100..200 bytes"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "recv", "recv", "recv", "restore_sigpipe"})); } } AND_WHEN("recv receives more than min size") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("recv", BOLT_SUCCESS, 50); test_ctx->add_call("recv", BOLT_SUCCESS, 30); test_ctx->add_call("recv", BOLT_SUCCESS, 50); test_ctx->add_call("restore_sigpipe", BOLT_SUCCESS); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, min_size, max_size, &received, "id-2"); THEN("should succeed") { REQUIRE(result==BOLT_SUCCESS); } THEN("returns correct received byte count") { REQUIRE(received==130); } THEN("should create a log entry") { REQUIRE_THAT(test_ctx->recorded_messages(), VectorContains(string("INFO: [id-2]: Received 130 of 100..200 bytes"))); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "recv", "recv", "recv", "restore_sigpipe"})); } } } } WHEN("ignore_sigaction fails") { test_ctx->add_call("ignore_sigpipe", BOLT_UNKNOWN_ERROR); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, 100, 100, &received, "id-0"); THEN("should fail") { REQUIRE(result==BOLT_UNKNOWN_ERROR); } THEN("should not create a log entry") { REQUIRE(test_ctx->recorded_messages().empty()); } THEN("should set status") { REQUIRE(status->error==BOLT_UNKNOWN_ERROR); REQUIRE_THAT(status->error_ctx, Contains("unable to ignore SIGPIPE")); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe"})); } } WHEN("restore_sigaction fails") { test_ctx->add_call("ignore_sigpipe", BOLT_SUCCESS); test_ctx->add_call("recv", BOLT_SUCCESS, 25); test_ctx->add_call("recv", BOLT_SUCCESS, 25); test_ctx->add_call("recv", BOLT_SUCCESS, 45); test_ctx->add_call("recv", BOLT_SUCCESS, 5); test_ctx->add_call("restore_sigpipe", BOLT_UNKNOWN_ERROR); int received = 0; int result = BoltCommunication_receive(comm_under_test, NULL, 100, 100, &received, "id-0"); THEN("should succeed") { REQUIRE(result==BOLT_UNKNOWN_ERROR); } THEN("should set status") { REQUIRE(status->error==BOLT_UNKNOWN_ERROR); REQUIRE_THAT(status->error_ctx, Contains("unable to restore SIGPIPE")); } THEN("should not make any unexpected calls") { REQUIRE_THAT(test_ctx->recorded_calls(), Equals(vector<string>{"ignore_sigpipe", "recv", "recv", "recv", "recv", "restore_sigpipe"})); } } } delete test_ctx; delete comm_under_test; BoltStatus_destroy(status); BoltSocketOptions_destroy(sock_opts); BoltAddress_destroy(local); } <|start_filename|>src/seabolt/src/bolt/config.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "config-private.h" #include "address-resolver-private.h" #include "log-private.h" #include "mem.h" BoltSocketOptions* BoltSocketOptions_create() { BoltSocketOptions* socket_options = BoltMem_allocate(sizeof(BoltSocketOptions)); socket_options->connect_timeout = 5000; socket_options->recv_timeout = 0; socket_options->send_timeout = 0; socket_options->keep_alive = 1; return socket_options; } BoltSocketOptions* BoltSocketOptions_clone(BoltSocketOptions* socket_options) { if (socket_options==NULL) { return NULL; } BoltSocketOptions* clone = BoltSocketOptions_create(); clone->connect_timeout = socket_options->connect_timeout; clone->recv_timeout = socket_options->recv_timeout; clone->send_timeout = socket_options->send_timeout; clone->keep_alive = socket_options->keep_alive; return clone; } void BoltSocketOptions_destroy(BoltSocketOptions* socket_options) { BoltMem_deallocate(socket_options, sizeof(BoltSocketOptions)); } int32_t BoltSocketOptions_get_connect_timeout(BoltSocketOptions* socket_options) { return socket_options->connect_timeout; } int32_t BoltSocketOptions_set_connect_timeout(BoltSocketOptions* socket_options, int32_t connect_timeout) { socket_options->connect_timeout = connect_timeout; return BOLT_SUCCESS; } int32_t BoltSocketOptions_get_keep_alive(BoltSocketOptions* socket_options) { return socket_options->keep_alive; } int32_t BoltSocketOptions_set_keep_alive(BoltSocketOptions* socket_options, int32_t keep_alive) { socket_options->keep_alive = keep_alive; return BOLT_SUCCESS; } BoltTrust* BoltTrust_create() { BoltTrust* trust = BoltMem_allocate(sizeof(BoltTrust)); trust->certs = NULL; trust->certs_len = 0; trust->skip_verify = 1; trust->skip_verify_hostname = 1; return trust; } BoltTrust* BoltTrust_clone(BoltTrust* source) { if (source==NULL) { return NULL; } BoltTrust* clone = BoltTrust_create(); BoltTrust_set_certs(clone, source->certs, source->certs_len); BoltTrust_set_skip_verify(clone, source->skip_verify); BoltTrust_set_skip_verify_hostname(clone, source->skip_verify_hostname); return clone; } void BoltTrust_destroy(BoltTrust* trust) { if (trust->certs!=NULL) { BoltMem_deallocate(trust->certs, trust->certs_len); } BoltMem_deallocate(trust, sizeof(BoltTrust)); } const char* BoltTrust_get_certs(BoltTrust* trust, uint64_t* size) { *size = trust->certs_len; return trust->certs; } int32_t BoltTrust_set_certs(BoltTrust* trust, const char* certs_pem, uint64_t certs_pem_size) { trust->certs = BoltMem_duplicate(certs_pem, certs_pem_size); trust->certs_len = certs_pem_size; return BOLT_SUCCESS; } int32_t BoltTrust_get_skip_verify(BoltTrust* trust) { return trust->skip_verify; } int32_t BoltTrust_set_skip_verify(BoltTrust* trust, int32_t skip_verify) { trust->skip_verify = skip_verify; return BOLT_SUCCESS; } int32_t BoltTrust_get_skip_verify_hostname(BoltTrust* trust) { return trust->skip_verify_hostname; } int32_t BoltTrust_set_skip_verify_hostname(BoltTrust* trust, int32_t skip_verify_hostname) { trust->skip_verify_hostname = skip_verify_hostname; return BOLT_SUCCESS; } BoltConfig* BoltConfig_create() { BoltConfig* config = BoltMem_allocate(sizeof(BoltConfig)); config->scheme = BOLT_SCHEME_DIRECT; config->transport = BOLT_TRANSPORT_ENCRYPTED; config->trust = NULL; config->user_agent = NULL; config->routing_context = NULL; config->address_resolver = NULL; config->log = NULL; config->max_pool_size = 100; config->max_connection_life_time = 0; config->max_connection_acquisition_time = 0; config->socket_options = NULL; return config; } BoltConfig* BoltConfig_clone(BoltConfig* config) { BoltConfig* clone = BoltConfig_create(); if (config!=NULL) { BoltConfig_set_scheme(clone, config->scheme); BoltConfig_set_transport(clone, config->transport); BoltConfig_set_trust(clone, config->trust); BoltConfig_set_user_agent(clone, config->user_agent); BoltConfig_set_routing_context(clone, config->routing_context); BoltConfig_set_address_resolver(clone, config->address_resolver); BoltConfig_set_log(clone, config->log); BoltConfig_set_max_pool_size(clone, config->max_pool_size); BoltConfig_set_max_connection_life_time(clone, config->max_connection_life_time); BoltConfig_set_max_connection_acquisition_time(clone, config->max_connection_acquisition_time); BoltConfig_set_socket_options(clone, config->socket_options); } return clone; } void BoltConfig_destroy(BoltConfig* config) { if (config->trust!=NULL) { BoltTrust_destroy(config->trust); } if (config->user_agent!=NULL) { BoltMem_deallocate(config->user_agent, SIZE_OF_C_STRING(config->user_agent)); } if (config->routing_context!=NULL) { BoltValue_destroy(config->routing_context); } if (config->address_resolver!=NULL) { BoltAddressResolver_destroy(config->address_resolver); } if (config->log!=NULL) { BoltLog_destroy(config->log); } if (config->socket_options!=NULL) { BoltSocketOptions_destroy(config->socket_options); } BoltMem_deallocate(config, sizeof(BoltConfig)); } BoltScheme BoltConfig_get_scheme(BoltConfig* config) { return config->scheme; } int32_t BoltConfig_set_scheme(BoltConfig* config, BoltScheme scheme) { config->scheme = scheme; return BOLT_SUCCESS; } BoltTransport BoltConfig_get_transport(BoltConfig* config) { return config->transport; } int32_t BoltConfig_set_transport(BoltConfig* config, BoltTransport transport) { config->transport = transport; return BOLT_SUCCESS; } BoltTrust* BoltConfig_get_trust(BoltConfig* config) { return config->trust; } int32_t BoltConfig_set_trust(BoltConfig* config, BoltTrust* trust) { config->trust = BoltTrust_clone(trust); return BOLT_SUCCESS; } const char* BoltConfig_get_user_agent(BoltConfig* config) { return config->user_agent; } int32_t BoltConfig_set_user_agent(BoltConfig* config, const char* user_agent) { config->user_agent = BoltMem_duplicate(user_agent, SIZE_OF_C_STRING(user_agent)); return BOLT_SUCCESS; } BoltValue* BoltConfig_get_routing_context(BoltConfig* config) { return config->routing_context; } int32_t BoltConfig_set_routing_context(BoltConfig* config, BoltValue* routing_context) { config->routing_context = BoltValue_duplicate(routing_context); return BOLT_SUCCESS; } BoltAddressResolver* BoltConfig_get_address_resolver(BoltConfig* config) { return config->address_resolver; } int32_t BoltConfig_set_address_resolver(BoltConfig* config, BoltAddressResolver* address_resolver) { config->address_resolver = BoltAddressResolver_clone(address_resolver); return BOLT_SUCCESS; } BoltLog* BoltConfig_get_log(BoltConfig* config) { return config->log; } int32_t BoltConfig_set_log(BoltConfig* config, BoltLog* log) { config->log = BoltLog_clone(log); return BOLT_SUCCESS; } int32_t BoltConfig_get_max_pool_size(BoltConfig* config) { return config->max_pool_size; } int32_t BoltConfig_set_max_pool_size(BoltConfig* config, int32_t max_pool_size) { config->max_pool_size = max_pool_size; return BOLT_SUCCESS; } int32_t BoltConfig_get_max_connection_life_time(BoltConfig* config) { return config->max_connection_life_time; } int32_t BoltConfig_set_max_connection_life_time(BoltConfig* config, int32_t max_connection_life_time) { config->max_connection_life_time = max_connection_life_time; return BOLT_SUCCESS; } int32_t BoltConfig_get_max_connection_acquisition_time(BoltConfig* config) { return config->max_connection_acquisition_time; } int32_t BoltConfig_set_max_connection_acquisition_time(BoltConfig* config, int32_t max_connection_acquisition_time) { config->max_connection_acquisition_time = max_connection_acquisition_time; return BOLT_SUCCESS; } BoltSocketOptions* BoltConfig_get_socket_options(BoltConfig* config) { return config->socket_options; } int32_t BoltConfig_set_socket_options(BoltConfig* config, BoltSocketOptions* socket_options) { config->socket_options = BoltSocketOptions_clone(socket_options); return BOLT_SUCCESS; } <|start_filename|>src/seabolt/tests/test-string-builder.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "catch.hpp" #include "integration.hpp" TEST_CASE("StringBuilder") { const char* charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!"; const int charset_size = (int)strlen(charset); StringBuilder* builder = StringBuilder_create(); REQUIRE(builder!=nullptr); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); SECTION("StringBuilder_append") { SECTION("null") { StringBuilder_append(builder, nullptr); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); } SECTION("empty string") { StringBuilder_append(builder, ""); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); } SECTION("abcd") { StringBuilder_append(builder, "abcd"); REQUIRE(StringBuilder_get_length(builder)==4); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]=='a'); REQUIRE(StringBuilder_get_string(builder)[1]=='b'); REQUIRE(StringBuilder_get_string(builder)[2]=='c'); REQUIRE(StringBuilder_get_string(builder)[3]=='d'); REQUIRE(StringBuilder_get_string(builder)[4]==0); SECTION("and whitespace") { StringBuilder_append(builder, " "); REQUIRE(StringBuilder_get_length(builder)==5); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[4]==' '); REQUIRE(StringBuilder_get_string(builder)[5]==0); SECTION("and efg") { StringBuilder_append(builder, "efg"); REQUIRE(StringBuilder_get_length(builder)==8); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[5]=='e'); REQUIRE(StringBuilder_get_string(builder)[6]=='f'); REQUIRE(StringBuilder_get_string(builder)[7]=='g'); REQUIRE(StringBuilder_get_string(builder)[8]==0); } } } SECTION("long string") { const int size = 128000; char buffer[size+1]; for (int i = 0; i<size; i++) { buffer[i] = charset[rand()%(charset_size-1)]; } buffer[size] = 0; StringBuilder_append(builder, buffer); REQUIRE(StringBuilder_get_length(builder)==size); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[size]==0); REQUIRE(strcmp(StringBuilder_get_string(builder), buffer)==0); SECTION("and append a number") { StringBuilder_append(builder, "1"); REQUIRE(StringBuilder_get_length(builder)==size+1); REQUIRE(StringBuilder_get_string(builder)[size]=='1'); REQUIRE(StringBuilder_get_string(builder)[size+1]==0); } } } SECTION("StringBuilder_append_n") { SECTION("null") { StringBuilder_append_n(builder, nullptr, 0); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); } SECTION("empty string") { StringBuilder_append_n(builder, "", 0); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); } SECTION("abcd") { StringBuilder_append_n(builder, "abcd", 4); REQUIRE(StringBuilder_get_length(builder)==4); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]=='a'); REQUIRE(StringBuilder_get_string(builder)[1]=='b'); REQUIRE(StringBuilder_get_string(builder)[2]=='c'); REQUIRE(StringBuilder_get_string(builder)[3]=='d'); REQUIRE(StringBuilder_get_string(builder)[4]==0); SECTION("and whitespace") { StringBuilder_append_n(builder, " ", 1); REQUIRE(StringBuilder_get_length(builder)==5); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[4]==' '); REQUIRE(StringBuilder_get_string(builder)[5]==0); SECTION("and efg") { StringBuilder_append_n(builder, "efg", 3); REQUIRE(StringBuilder_get_length(builder)==8); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[5]=='e'); REQUIRE(StringBuilder_get_string(builder)[6]=='f'); REQUIRE(StringBuilder_get_string(builder)[7]=='g'); REQUIRE(StringBuilder_get_string(builder)[8]==0); } SECTION("and efg from efghij") { StringBuilder_append_n(builder, "efghij", 3); REQUIRE(StringBuilder_get_length(builder)==8); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[5]=='e'); REQUIRE(StringBuilder_get_string(builder)[6]=='f'); REQUIRE(StringBuilder_get_string(builder)[7]=='g'); REQUIRE(StringBuilder_get_string(builder)[8]==0); } } } SECTION("long string") { const int size = 128000; char buffer[size+1]; for (int i = 0; i<size; i++) { buffer[i] = charset[rand()%(charset_size-1)]; } buffer[size] = 0; StringBuilder_append_n(builder, buffer, size); REQUIRE(StringBuilder_get_length(builder)==size); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[size]==0); REQUIRE(strcmp(StringBuilder_get_string(builder), buffer)==0); SECTION("and append a number") { StringBuilder_append_n(builder, "1", 1); REQUIRE(StringBuilder_get_length(builder)==size+1); REQUIRE(StringBuilder_get_string(builder)[size]=='1'); REQUIRE(StringBuilder_get_string(builder)[size+1]==0); } } } SECTION("StringBuilder_append_f") { SECTION("null format") { StringBuilder_append_f(builder, nullptr); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); } SECTION("empty format") { StringBuilder_append_f(builder, ""); REQUIRE(StringBuilder_get_length(builder)==0); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]==0); } SECTION("string format - abcd") { StringBuilder_append_f(builder, "%s", "abcd"); REQUIRE(StringBuilder_get_length(builder)==4); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[0]=='a'); REQUIRE(StringBuilder_get_string(builder)[1]=='b'); REQUIRE(StringBuilder_get_string(builder)[2]=='c'); REQUIRE(StringBuilder_get_string(builder)[3]=='d'); REQUIRE(StringBuilder_get_string(builder)[4]==0); SECTION("and whitespace") { StringBuilder_append_f(builder, "%c", ' '); REQUIRE(StringBuilder_get_length(builder)==5); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[4]==' '); REQUIRE(StringBuilder_get_string(builder)[5]==0); SECTION("and efg") { StringBuilder_append_f(builder, "%s", "efg"); REQUIRE(StringBuilder_get_length(builder)==8); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[5]=='e'); REQUIRE(StringBuilder_get_string(builder)[6]=='f'); REQUIRE(StringBuilder_get_string(builder)[7]=='g'); REQUIRE(StringBuilder_get_string(builder)[8]==0); } SECTION("and number") { StringBuilder_append_f(builder, "%03d", 3); REQUIRE(StringBuilder_get_length(builder)==8); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[5]=='0'); REQUIRE(StringBuilder_get_string(builder)[6]=='0'); REQUIRE(StringBuilder_get_string(builder)[7]=='3'); REQUIRE(StringBuilder_get_string(builder)[8]==0); } } } SECTION("long string") { const int size = 128000; char buffer[size+1]; for (int i = 0; i<size; i++) { buffer[i] = charset[rand()%(charset_size-1)]; } buffer[size] = 0; StringBuilder_append_f(builder, "%s", buffer); REQUIRE(StringBuilder_get_length(builder)==size); REQUIRE(StringBuilder_get_string(builder)!=nullptr); REQUIRE(StringBuilder_get_string(builder)[size]==0); REQUIRE(strcmp(StringBuilder_get_string(builder), buffer)==0); SECTION("and append a number") { StringBuilder_append_f(builder, "%d", 1); REQUIRE(StringBuilder_get_length(builder)==size+1); REQUIRE(StringBuilder_get_string(builder)[size]=='1'); REQUIRE(StringBuilder_get_string(builder)[size+1]==0); } } } StringBuilder_destroy(builder); } <|start_filename|>src/seabolt/src/bolt/routing-table.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "address-private.h" #include "address-set-private.h" #include "mem.h" #include "routing-table.h" #include "time.h" #include "values-private.h" #define READ_ROLE "READ" #define WRITE_ROLE "WRITE" #define ROUTE_ROLE "ROUTE" #define TTL_KEY "ttl" #define TTL_KEY_LEN 3 #define SERVERS_KEY "servers" #define SERVERS_KEY_LEN 7 #define ROLE_KEY "role" #define ROLE_KEY_LEN 4 #define ADDRESSES_KEY "addresses" #define ADDRESSES_KEY_LEN 9 volatile RoutingTable* RoutingTable_create() { struct RoutingTable* table = (RoutingTable*) BoltMem_allocate(SIZE_OF_ROUTING_TABLE); table->expires = 0; table->last_updated = 0; table->readers = BoltAddressSet_create(); table->writers = BoltAddressSet_create(); table->routers = BoltAddressSet_create(); return table; } void RoutingTable_destroy(volatile RoutingTable* state) { BoltAddressSet_destroy(state->readers); BoltAddressSet_destroy(state->writers); BoltAddressSet_destroy(state->routers); BoltMem_deallocate((void*) state, SIZE_OF_ROUTING_TABLE); } int RoutingTable_update(volatile RoutingTable* table, struct BoltValue* response) { int status = BOLT_SUCCESS; if (BoltValue_type(response)!=BOLT_DICTIONARY) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; } int64_t ttl = 0; if (status==BOLT_SUCCESS) { struct BoltValue* ttl_value = BoltDictionary_value_by_key(response, TTL_KEY, TTL_KEY_LEN); if (ttl_value==NULL || BoltValue_type(ttl_value)!=BOLT_INTEGER) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; } ttl = BoltInteger_get(ttl_value)*1000; } struct BoltValue* servers_value = NULL; if (status==BOLT_SUCCESS) { servers_value = BoltDictionary_value_by_key(response, SERVERS_KEY, SERVERS_KEY_LEN); if (servers_value==NULL || BoltValue_type(servers_value)!=BOLT_LIST) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; } } volatile BoltAddressSet* readers = BoltAddressSet_create(); volatile BoltAddressSet* writers = BoltAddressSet_create(); volatile BoltAddressSet* routers = BoltAddressSet_create(); for (int32_t i = 0; i<servers_value->size && status==BOLT_SUCCESS; i++) { struct BoltValue* server_value = BoltList_value(servers_value, i); if (server_value==NULL || BoltValue_type(server_value)!=BOLT_DICTIONARY) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; break; } struct BoltValue* role_value = BoltDictionary_value_by_key(server_value, ROLE_KEY, ROLE_KEY_LEN); if (role_value==NULL || BoltValue_type(role_value)!=BOLT_STRING) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; break; } struct BoltValue* addresses_value = BoltDictionary_value_by_key(server_value, ADDRESSES_KEY, ADDRESSES_KEY_LEN); if (addresses_value==NULL || BoltValue_type(addresses_value)!=BOLT_LIST) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; break; } if (status==BOLT_SUCCESS) { char* role = BoltString_get(role_value); for (int32_t j = 0; j<addresses_value->size && status==BOLT_SUCCESS; j++) { struct BoltValue* address_value = BoltList_value(addresses_value, j); if (address_value==NULL || BoltValue_type(address_value)!=BOLT_STRING) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; continue; } struct BoltAddress* address = BoltAddress_create_from_string(BoltString_get(address_value), address_value->size); if (strcmp(role, READ_ROLE)==0) { BoltAddressSet_add(readers, address); } else if (strcmp(role, WRITE_ROLE)==0) { BoltAddressSet_add(writers, address); } else if (strcmp(role, ROUTE_ROLE)==0) { BoltAddressSet_add(routers, address); } else { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; } BoltAddress_destroy(address); } } } if (status==BOLT_SUCCESS) { BoltAddressSet_replace(table->readers, readers); BoltAddressSet_replace(table->writers, writers); BoltAddressSet_replace(table->routers, routers); table->last_updated = BoltTime_get_time_ms(); table->expires = table->last_updated+ttl; } BoltAddressSet_destroy(readers); BoltAddressSet_destroy(writers); BoltAddressSet_destroy(routers); return status; } int RoutingTable_is_expired(volatile RoutingTable* state, BoltAccessMode mode) { return state->routers->size==0 || (mode==BOLT_ACCESS_MODE_READ ? state->readers->size==0 : state->writers->size==0) || state->expires<=BoltTime_get_time_ms(); } void RoutingTable_forget_server(volatile RoutingTable* state, const struct BoltAddress* address) { BoltAddressSet_remove(state->routers, address); BoltAddressSet_remove(state->readers, address); BoltAddressSet_remove(state->writers, address); } void RoutingTable_forget_writer(volatile RoutingTable* state, const struct BoltAddress* address) { BoltAddressSet_remove(state->writers, address); } <|start_filename|>src/seabolt/src/bolt/connector.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ALL_CONNECTOR_H #define SEABOLT_ALL_CONNECTOR_H #include "bolt-public.h" #include "log.h" #include "connection.h" #include "address-resolver.h" /** * The intended access mode of the connection. * * Only applies to connectors that are configured to operate on a \ref BOLT_MODE_ROUTING mode. */ typedef int32_t BoltAccessMode; /** * Use BOLT_ACCESS_MODE_WRITE to acquire a connection against a WRITE server. */ #define BOLT_ACCESS_MODE_WRITE 0 /** * Use BOLT_ACCESS_MODE_READ to acquire a connection against a READ server. */ #define BOLT_ACCESS_MODE_READ 1 /** * The type that holds a pool(s) of connections and handles connection acquisition and release operations based * on the configuration provided. * * An instance needs to be created with \ref BoltConnector_create and destroyed with \ref BoltConnector_destroy * when there is no more interaction is expected. */ typedef struct BoltConnector BoltConnector; /** * Creates a new instance of \ref BoltConnector. * * @param address the \ref BoltAddress "address instance" that holds the target endpoint. * @param auth_token the authentication token to present to the server during connection initialisation. * @param config the \ref BoltConfig "configuration" that should apply to the created instance. * @return the pointer to the newly allocated \ref BoltConnector instance. */ SEABOLT_EXPORT BoltConnector* BoltConnector_create(BoltAddress* address, BoltValue* auth_token, BoltConfig* config); /** * Destroys the passed \ref BoltConnector instance and all related resources (connections, pools, etc.). * * @param connector the instance to be destroyed. */ SEABOLT_EXPORT void BoltConnector_destroy(BoltConnector* connector); /** * Acquires a \ref BoltConnection "connection" from the underlying connection pool(s) based on the * provided \ref BoltAccessMode "access mode". * * It is the first call of this function that actual connection attempt is made towards the address provided. * If the connector is created with a \ref BOLT_MODE_ROUTING mode, this will cause an initial discovery to be * carried out against the cluster member pointed by the address. * In case a custom name resolver is specified through \ref BoltConfig_set_address_resolver, the initial and fallback * discoveries trigger this name resolver and the returned addresses will be used for routing table updates. * * @param connector the instance to acquire connection from. * @param mode the intended \ref BoltAccessMode "access mode" for the acquired connection. * @param status the status about the acquisition, which is mostly useful if something went wrong and no connection * could be acquired * @returns the acquired connection or NULL if something went wrong. Inspect status for more detailed information about * the underlying failure. */ SEABOLT_EXPORT BoltConnection* BoltConnector_acquire(BoltConnector* connector, BoltAccessMode mode, BoltStatus* status); /** * Releases the provided \ref BoltConnection "connection" to the internal connection pool to be used by further * \ref BoltConnector_acquire calls. * * @param connector the instance to release the connection to. * @param connection the actual \ref BoltConnection "connection" to be released. */ SEABOLT_EXPORT void BoltConnector_release(BoltConnector* connector, BoltConnection* connection); #endif //SEABOLT_ALL_CONNECTOR_H <|start_filename|>src/seabolt/tests/seabolt.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <cstring> #include <cstdlib> #include <integration.hpp> #include "catch.hpp" void log_to_stderr(void* state, const char* message) { UNUSED(state); fprintf(stderr, "%s\n", message); } struct BoltLog* create_logger() { struct BoltLog* log = BoltLog_create(0); int debug = 0; int warn = 0; int info = 0; int error = 0; if (strcmp(BOLT_LOG, "error")==0) { error = 1; } if (strcmp(BOLT_LOG, "warning")==0) { error = 1; warn = 1; } if (strcmp(BOLT_LOG, "info")==0) { error = 1; warn = 1; info = 1; } if (strcmp(BOLT_LOG, "debug")==0) { error = 1; warn = 1; info = 1; debug = 1; } BoltLog_set_debug_func(log, debug ? log_to_stderr : NULL); BoltLog_set_warning_func(log, warn ? log_to_stderr : NULL); BoltLog_set_info_func(log, info ? log_to_stderr : NULL); BoltLog_set_error_func(log, error ? log_to_stderr : NULL); return log; } struct BoltAddress* bolt_get_address(const char* host, const char* port) { struct BoltAddress* address = BoltAddress_create(host, port); int status = BoltAddress_resolve(address, NULL, NULL); REQUIRE(status==0); return address; } struct BoltConnection* bolt_open_b(BoltTransport transport, const char* host, const char* port) { struct BoltTrust trust{nullptr, 0, 1, 1}; struct BoltAddress* address = bolt_get_address(host, port); struct BoltConnection* connection = BoltConnection_create(); BoltConnection_open(connection, transport, address, &trust, create_logger(), NULL); BoltAddress_destroy(address); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_CONNECTED); return connection; } struct BoltConnection* bolt_open_init_b(BoltTransport transport, const char* host, const char* port, const char* user_agent, const struct BoltValue* auth_token) { struct BoltConnection* connection = bolt_open_b(transport, host, port); BoltConnection_init(connection, user_agent, auth_token); REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_READY); return connection; } struct BoltConnection* bolt_open_init_default() { struct BoltValue* auth_token = BoltAuth_basic(BOLT_USER, BOLT_PASSWORD, NULL); struct BoltConnection* connection = bolt_open_init_b(BOLT_TRANSPORT_ENCRYPTED, BOLT_IPV6_HOST, BOLT_PORT, BOLT_USER_AGENT, auth_token); BoltValue_destroy(auth_token); return connection; } struct BoltConnection* bolt_open_init_mocked(int32_t bolt_version, BoltLog* logger) { BoltAddress* address = bolt_get_address("localhost", "7687"); BoltConnection* connection = BoltConnection_create(); connection->comm = BoltCommunication_create_mock(bolt_version, NULL, logger); BoltConnection_open(connection, BOLT_TRANSPORT_MOCKED, address, NULL, logger, NULL); strcpy(connection->id, "id-0"); connection->status->state = BOLT_CONNECTION_STATE_READY; BoltAddress_destroy(address); return connection; } void bolt_close_and_destroy_b(struct BoltConnection* connection) { BoltConnection_close(connection); if (connection->log!=NULL) { BoltLog_destroy((BoltLog*) connection->log); } BoltConnection_destroy(connection); } <|start_filename|>src/seabolt/src/bolt/communication-plain-win32.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "communication-secure.h" int socket_last_error(BoltCommunication* comm) { UNUSED(comm); return WSAGetLastError(); } int socket_transform_error(BoltCommunication* comm, int error_code) { UNUSED(comm); switch (error_code) { case WSAEACCES: return BOLT_PERMISSION_DENIED; case WSAEAFNOSUPPORT: case WSAEINVAL: case WSAEPROTONOSUPPORT: return BOLT_UNSUPPORTED; case WSAEMFILE: return BOLT_OUT_OF_FILES; case WSAENOBUFS: case WSA_NOT_ENOUGH_MEMORY: return BOLT_OUT_OF_MEMORY; case WSAECONNREFUSED: return BOLT_CONNECTION_REFUSED; case WSAEINTR: return BOLT_INTERRUPTED; case WSAECONNRESET: return BOLT_CONNECTION_RESET; case WSAENETUNREACH: case WSAENETRESET: case WSAENETDOWN: return BOLT_NETWORK_UNREACHABLE; case WSAEWOULDBLOCK: case WSAETIMEDOUT: return BOLT_TIMED_OUT; default: return BOLT_UNKNOWN_ERROR; } } int socket_ignore_sigpipe(void** replaced_action) { UNUSED(replaced_action); return BOLT_SUCCESS; } int socket_restore_sigpipe(void** action_to_restore) { UNUSED(action_to_restore); return BOLT_SUCCESS; } int socket_disable_sigpipe(int sockfd) { UNUSED(sockfd); return 0; } int socket_set_blocking_mode(int sockfd, int blocking) { u_long non_blocking = blocking ? 0 : 1; return ioctlsocket(sockfd, FIONBIO, &non_blocking); } int socket_set_recv_timeout(int sockfd, int timeout) { int recv_timeout = timeout; int recv_timeout_size = sizeof(int); return setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*) &recv_timeout, recv_timeout_size); } int socket_set_keepalive(int sockfd, int keepalive) { return setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (const char*) &keepalive, sizeof(keepalive)); } int socket_set_nodelay(int sockfd, int nodelay) { return setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*) &nodelay, sizeof(nodelay)); } int socket_open(int domain, int type, int protocol) { return (int) socket(domain, type, protocol); } int socket_shutdown(int sockfd) { return shutdown(sockfd, SD_BOTH); } int socket_close(int sockfd) { return closesocket(sockfd); } int socket_connect(int sockfd, const struct sockaddr* addr, socklen_t addrlen, int* in_progress) { int status = connect(sockfd, addr, addrlen); *in_progress = status==-1 && GetLastError()==WSAEWOULDBLOCK; return status; } int socket_send(int sockfd, const void* buf, int len, int flags) { return send(sockfd, buf, len, flags); } int socket_recv(int sockfd, void* buf, int len, int flags) { return recv(sockfd, buf, len, flags); } int socket_get_local_addr(int sockfd, struct sockaddr_storage* address, socklen_t* address_size) { return getsockname(sockfd, (struct sockaddr*) address, address_size); } int socket_select(int sockfd, int timeout) { // connection in progress fd_set write_set; FD_ZERO(&write_set); FD_SET((SOCKET) sockfd, &write_set); struct timeval select_timeout; select_timeout.tv_sec = timeout/1000; select_timeout.tv_usec = (timeout%1000)*1000; int status = select(FD_SETSIZE, NULL, &write_set, NULL, &select_timeout); if (status==1) { int so_error = 0; socklen_t so_error_len = sizeof(int); getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char*) &so_error, &so_error_len); if (so_error!=0) { WSASetLastError(so_error); return -1; } } return status; } int socket_lifecycle_startup() { WSADATA data; return WSAStartup(MAKEWORD(2, 2), &data); } int socket_lifecycle_shutdown() { return WSACleanup(); } <|start_filename|>src/seabolt/src/bolt/communication-mock.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "communication-mock.h" #include "bolt-private.h" #include "config-private.h" #include "mem.h" #include "name.h" #include "status-private.h" #include "log-private.h" #define MAX_IPADDR_LEN 64 int mock_last_error(BoltCommunication* comm) { UNUSED(comm); return BOLT_SUCCESS; } int mock_transform_error(BoltCommunication* comm, int error_code) { UNUSED(comm); UNUSED(error_code); return BOLT_SUCCESS; } int mock_socket_ignore_sigpipe(BoltCommunication* comm) { BoltLog_debug(comm->log, "socket_ignore_sigpipe"); return BOLT_SUCCESS; } int mock_socket_restore_sigpipe(BoltCommunication* comm) { BoltLog_debug(comm->log, "socket_restore_sigpipe"); return BOLT_SUCCESS; } int mock_socket_open(BoltCommunication* comm, const struct sockaddr_storage* address) { BoltLog_debug(comm->log, "socket_open"); MockCommunicationContext* context = comm->context; char resolved_host[MAX_IPADDR_LEN], resolved_port[6]; int status = get_address_components(address, resolved_host, MAX_IPADDR_LEN, resolved_port, 6); if (status!=0) { BoltStatus_set_error_with_ctx(comm->status, BOLT_ADDRESS_NAME_INFO_FAILED, "mock_socket_open(%s:%d), remote get_address_components error code: %d", __FILE__, __LINE__, status); return BOLT_STATUS_SET; } context->remote_endpoint = BoltAddress_create(resolved_host, resolved_port); context->local_endpoint = BoltAddress_create("localhost", "65000"); BoltLog_debug(comm->log, "socket_open: connected"); return BOLT_SUCCESS; } int mock_socket_close(BoltCommunication* comm) { BoltLog_debug(comm->log, "socket_close"); MockCommunicationContext* context = comm->context; if (context->local_endpoint!=NULL) { BoltAddress_destroy(context->local_endpoint); context->local_endpoint = NULL; } if (context->remote_endpoint!=NULL) { BoltAddress_destroy(context->remote_endpoint); context->remote_endpoint = NULL; } return BOLT_SUCCESS; } int mock_socket_send(BoltCommunication* comm, char* buffer, int length, int* sent) { UNUSED(buffer); BoltLog_debug(comm->log, "socket_send: %d bytes", length); *sent = length; return BOLT_SUCCESS; } int mock_socket_recv(BoltCommunication* comm, char* buffer, int length, int* received) { BoltLog_debug(comm->log, "socket_recv: %d bytes", length); MockCommunicationContext* context = comm->context; if (!context->protocol_version_sent) { memcpy_be(buffer, &context->protocol_version, sizeof(int32_t)); context->protocol_version_sent = 1; } *received = length; return BOLT_SUCCESS; } int mock_socket_destroy(BoltCommunication* comm) { BoltLog_debug(comm->log, "socket_destroy"); MockCommunicationContext* context = comm->context; if (context!=NULL) { if (context->local_endpoint!=NULL) { BoltAddress_destroy(context->local_endpoint); context->local_endpoint = NULL; } if (context->remote_endpoint!=NULL) { BoltAddress_destroy(context->remote_endpoint); context->remote_endpoint = NULL; } BoltMem_deallocate(context, sizeof(MockCommunicationContext)); comm->context = NULL; } return BOLT_SUCCESS; } BoltAddress* mock_socket_local_endpoint(BoltCommunication* comm) { MockCommunicationContext* context = comm->context; return context->local_endpoint; } BoltAddress* mock_socket_remote_endpoint(BoltCommunication* comm) { MockCommunicationContext* context = comm->context; return context->remote_endpoint; } BoltCommunication* BoltCommunication_create_mock(int32_t version, BoltSocketOptions* sock_opts, BoltLog* log) { BoltCommunication* comm = BoltMem_allocate(sizeof(BoltCommunication)); comm->open = &mock_socket_open; comm->close = &mock_socket_close; comm->send = &mock_socket_send; comm->recv = &mock_socket_recv; comm->destroy = &mock_socket_destroy; comm->get_local_endpoint = &mock_socket_local_endpoint; comm->get_remote_endpoint = &mock_socket_remote_endpoint; comm->ignore_sigpipe = &mock_socket_ignore_sigpipe; comm->restore_sigpipe = &mock_socket_restore_sigpipe; comm->last_error = &mock_last_error; comm->transform_error = &mock_transform_error; comm->status_owned = 1; comm->status = BoltStatus_create_with_ctx(1024); comm->sock_opts_owned = sock_opts==NULL; comm->sock_opts = sock_opts==NULL ? BoltSocketOptions_create() : sock_opts; comm->log = log; MockCommunicationContext* context = BoltMem_allocate(sizeof(MockCommunicationContext)); context->local_endpoint = NULL; context->remote_endpoint = NULL; context->protocol_version = version; context->protocol_version_sent = 0; comm->context = context; return comm; } <|start_filename|>src/seabolt/tests/test-values.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <cmath> #include "integration.hpp" #include "catch.hpp" using Catch::Matchers::Equals; #define REQUIRE_BOLT_NULL(value) { REQUIRE(BoltValue_type(value) == BOLT_NULL); } #define REQUIRE_BOLT_BOOLEAN(value, x) { REQUIRE(BoltValue_type(value) == BOLT_BOOLEAN); REQUIRE(BoltBoolean_get(value) == (x)); } #define REQUIRE_BOLT_INTEGER(value, x) { REQUIRE(BoltValue_type(value) == BOLT_INTEGER); REQUIRE(BoltInteger_get(value) == (x)); } #define REQUIRE_BOLT_FLOAT(value, x) { REQUIRE(BoltValue_type(value) == BOLT_FLOAT); REQUIRE( BoltFloat_get(value) == (x)); } #define REQUIRE_BOLT_STRING(value, x, size_) { REQUIRE(BoltValue_type(value) == BOLT_STRING); REQUIRE(strncmp(BoltString_get(value), x, size_) == 0); REQUIRE(BoltValue_size(value) == (size_)); } #define REQUIRE_BOLT_DICTIONARY(value, size_) { REQUIRE(BoltValue_type(value) == BOLT_DICTIONARY); REQUIRE(BoltValue_size(value) == (size_)); } #define REQUIRE_BOLT_LIST(value, size_) { REQUIRE(BoltValue_type(value) == BOLT_LIST); REQUIRE(BoltValue_size(value) == (size_)); } #define REQUIRE_BOLT_BYTES(value, size_) { REQUIRE(BoltValue_type(value) == BOLT_BYTES); REQUIRE(BoltValue_size(value) == (size_)); } #define REQUIRE_BOLT_STRUCTURE(value, code, size_) { REQUIRE(BoltValue_type(value) == BOLT_STRUCTURE); REQUIRE(BoltStructure_code(value) == (code)); REQUIRE(BoltValue_size(value) == (size_)); } #define REQUIRE_BOLT_SUCCESS(connection) { REQUIRE(BoltConnection_summary_success(connection) == 1); } #define RUN_PULL_SEND(connection, result)\ BoltConnection_load_run_request(connection);\ BoltConnection_load_pull_request(connection, -1);\ BoltConnection_send(connection);\ BoltRequest (result) = BoltConnection_last_request(connection); SCENARIO("Test null parameter", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Null(x); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_NULL(value); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test boolean in boolean out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Boolean(x, 1); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_BOOLEAN(value, 1); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test bytes in bytes out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); char array[5] = {33, 44, 55, 66, 77}; BoltValue_format_as_Bytes(x, &array[0], sizeof(array)); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_BYTES(value, 5); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test string in string out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_String(x, "hello, world", 12); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_STRING(value, "hello, world", 12); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test list in list out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; REQUIRE(BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1)==0); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_List(x, 3); BoltValue_format_as_Integer(BoltList_value(x, 0), 0); BoltValue_format_as_Integer(BoltList_value(x, 1), 1); BoltValue_format_as_Integer(BoltList_value(x, 2), 2); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { BoltValue* field_values = BoltConnection_field_values(connection); BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_LIST(value, 3); REQUIRE(BoltInteger_get(BoltList_value(value, 0))==0); REQUIRE(BoltInteger_get(BoltList_value(value, 1))==1); REQUIRE(BoltInteger_get(BoltList_value(value, 2))==2); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test empty list in empty list out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; REQUIRE(BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1)==0); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_List(x, 0); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { BoltValue* field_values = BoltConnection_field_values(connection); BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_LIST(value, 0); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test mixed list in mixed list out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; REQUIRE(BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1)==0); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); // list [42, "hello", false, 42.4242, {key1: "value1", key2: -424242}] BoltValue_format_as_List(x, 5); BoltValue_format_as_Integer(BoltList_value(x, 0), 42); BoltValue_format_as_String(BoltList_value(x, 1), "hello", 5); BoltValue_format_as_Boolean(BoltList_value(x, 2), 0); BoltValue_format_as_Float(BoltList_value(x, 3), 42.4242); BoltValue_format_as_Dictionary(BoltList_value(x, 4), 2); BoltDictionary_set_key(BoltList_value(x, 4), 0, "key1", 4); BoltValue_format_as_String(BoltDictionary_value(BoltList_value(x, 4), 0), "value1", 6); BoltDictionary_set_key(BoltList_value(x, 4), 1, "key2", 4); BoltValue_format_as_Integer(BoltDictionary_value(BoltList_value(x, 4), 1), -424242); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { BoltValue* field_values = BoltConnection_field_values(connection); BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_LIST(value, 5); REQUIRE(BoltInteger_get(BoltList_value(value, 0))==42); CHECK_THAT(BoltString_get(BoltList_value(value, 1)), Equals("hello")); REQUIRE(BoltBoolean_get(BoltList_value(value, 2))==0); REQUIRE(BoltFloat_get(BoltList_value(value, 3))==42.4242); BoltValue* dictionary = BoltList_value(value, 4); REQUIRE_BOLT_DICTIONARY(dictionary, 2); CHECK_THAT(BoltString_get(BoltDictionary_value_by_key(dictionary, "key1", 4)), Equals("value1")); REQUIRE(BoltInteger_get(BoltDictionary_value_by_key(dictionary, "key2", 4))==-424242); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test dictionary in dictionary out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Dictionary(x, 2); BoltDictionary_set_key(x, 0, "name", 4); BoltValue_format_as_String(BoltDictionary_value(x, 0), "Alice", 5); BoltDictionary_set_key(x, 1, "age", 3); BoltValue_format_as_Integer(BoltDictionary_value(x, 1), 33); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* dict = BoltList_value(field_values, 0); REQUIRE_BOLT_DICTIONARY(dict, 2); int found = 0; for (int i = 0; i<dict->size; i++) { const char* key = BoltDictionary_get_key(dict, i); if (strcmp(key, "name")==0) { REQUIRE_BOLT_STRING(BoltDictionary_value(dict, i), "Alice", 5); found += 1; } else if (strcmp(key, "age")==0) { REQUIRE_BOLT_INTEGER(BoltDictionary_value(dict, i), 33); found += 1; } else { FAIL(); } } REQUIRE(found==2); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test empty dictionary in empty dictionary out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Dictionary(x, 0); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_DICTIONARY(value, 0); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test mixed dictionary in mixed dictionary out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); // dictionary {k1: "apa", key2: [1.9283, "hello world!"], TheKey3: true} BoltValue_format_as_Dictionary(x, 3); BoltDictionary_set_key(x, 0, "k1", 2); BoltValue_format_as_String(BoltDictionary_value(x, 0), "apa", 3); BoltDictionary_set_key(x, 1, "key2", 4); BoltValue_format_as_List(BoltDictionary_value(x, 1), 2); BoltValue_format_as_Float(BoltList_value(BoltDictionary_value(x, 1), 0), 1.9283); BoltValue_format_as_String(BoltList_value(BoltDictionary_value(x, 1), 1), "hello world!", 12); BoltDictionary_set_key(x, 2, "TheKey3", 7); BoltValue_format_as_Boolean(BoltDictionary_value(x, 2), 1); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_DICTIONARY(value, 3); CHECK_THAT(BoltString_get(BoltDictionary_value_by_key(value, "k1", 2)), Equals("apa")); BoltValue* list = BoltDictionary_value_by_key(value, "key2", 4); REQUIRE_BOLT_LIST(list, 2); REQUIRE(BoltFloat_get(BoltList_value(list, 0))==1.9283); CHECK_THAT(BoltString_get(BoltList_value(list, 1)), Equals("hello world!")); REQUIRE_BOLT_BOOLEAN(BoltDictionary_value_by_key(value, "TheKey3", 7), 1); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test integer in integer out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Integer(x, 123456789); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_INTEGER(value, 123456789); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test max & min integer in max & min integer out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Integer(x, INT64_MAX); RUN_PULL_SEND(connection, result1); while (BoltConnection_fetch(connection, result1)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_INTEGER(value, INT64_MAX); } BoltValue_format_as_Integer(x, INT64_MIN); RUN_PULL_SEND(connection, result2); while (BoltConnection_fetch(connection, result2)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_INTEGER(value, INT64_MIN); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test float in float out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Float(x, 6.283185307179); RUN_PULL_SEND(connection, result); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_FLOAT(value, 6.283185307179); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test max & min float in max & min float out", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); BoltValue_format_as_Float(x, 1.7976931348623157E308); RUN_PULL_SEND(connection, result1); while (BoltConnection_fetch(connection, result1)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_FLOAT(value, 1.7976931348623157E308); } BoltValue_format_as_Float(x, 4.9E-324); RUN_PULL_SEND(connection, result2); while (BoltConnection_fetch(connection, result2)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_FLOAT(value, 4.9E-324); } REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } SCENARIO("Test structure in result", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("successfully executed Cypher") { BoltConnection_load_begin_request(connection); const char* cypher = "CREATE (a:Person {name:'Alice'}) RETURN a"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 0); BoltConnection_load_run_request(connection); BoltConnection_load_pull_request(connection, -1); BoltRequest result = BoltConnection_last_request(connection); BoltConnection_load_rollback_request(connection); BoltConnection_send(connection); BoltRequest last = BoltConnection_last_request(connection); while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* node = BoltList_value(field_values, 0); REQUIRE_BOLT_STRUCTURE(node, 'N', 3); BoltValue* id = BoltStructure_value(node, 0); BoltValue* labels = BoltStructure_value(node, 1); BoltValue* properties = BoltStructure_value(node, 2); REQUIRE(BoltValue_type(id)==BOLT_INTEGER); REQUIRE_BOLT_LIST(labels, 1); REQUIRE_BOLT_STRING(BoltList_value(labels, 0), "Person", 6); REQUIRE_BOLT_DICTIONARY(properties, 1); REQUIRE(strcmp(BoltDictionary_get_key(properties, 0), "name")==0); REQUIRE_BOLT_STRING(BoltDictionary_value(properties, 0), "Alice", 5); } BoltConnection_fetch_summary(connection, last); REQUIRE_BOLT_SUCCESS(connection); } bolt_close_and_destroy_b(connection); } } TEST_CASE("BoltValue") { SECTION("BoltValue_to_string") { // assume an un-initialized buffer const int buffer_size = 128000; char buffer[buffer_size+1]; for (int i = 0; i<buffer_size; i++) { buffer[i] = 'a'; } BoltValue* value = BoltValue_create(); SECTION("Null") { BoltValue_format_as_Null(value); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==4); REQUIRE(strlen(buffer)==4); REQUIRE(strcmp(buffer, "null")==0); } SECTION("Boolean") { SECTION("True") { BoltValue_format_as_Boolean(value, 1); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==4); REQUIRE(strlen(buffer)==4); REQUIRE(strcmp(buffer, "true")==0); } SECTION("False") { BoltValue_format_as_Boolean(value, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==5); REQUIRE(strlen(buffer)==5); REQUIRE(strcmp(buffer, "false")==0); } } SECTION("Integer") { SECTION("-9223372036854775807") { BoltValue_format_as_Integer(value, -9223372036854775807); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==20); REQUIRE(strlen(buffer)==20); REQUIRE(strcmp(buffer, "-9223372036854775807")==0); } SECTION("-100050") { BoltValue_format_as_Integer(value, -100050); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==7); REQUIRE(strlen(buffer)==7); REQUIRE(strcmp(buffer, "-100050")==0); } SECTION("0") { BoltValue_format_as_Integer(value, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==1); REQUIRE(strlen(buffer)==1); REQUIRE(strcmp(buffer, "0")==0); } SECTION("100") { BoltValue_format_as_Integer(value, 100); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==3); REQUIRE(strlen(buffer)==3); REQUIRE(strcmp(buffer, "100")==0); } SECTION("9223372036854775807") { BoltValue_format_as_Integer(value, 9223372036854775807); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==19); REQUIRE(strlen(buffer)==19); REQUIRE(strcmp(buffer, "9223372036854775807")==0); } } SECTION("Float") { SECTION("-100513.14574789") { BoltValue_format_as_Float(value, -100513.14574789); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==14); REQUIRE(strlen(buffer)==14); REQUIRE(strcmp(buffer, "-100513.145748")==0); } SECTION("0") { BoltValue_format_as_Float(value, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==8); REQUIRE(strlen(buffer)==8); REQUIRE(strcmp(buffer, "0.000000")==0); } SECTION("3.14") { BoltValue_format_as_Float(value, 3.14); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==8); REQUIRE(strlen(buffer)==8); REQUIRE(strcmp(buffer, "3.140000")==0); } SECTION("100513.145747") { BoltValue_format_as_Float(value, 100513.145747); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==13); REQUIRE(strlen(buffer)==13); REQUIRE(strcmp(buffer, "100513.145747")==0); } SECTION("100513.14574789") { BoltValue_format_as_Float(value, 100513.14574789); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==13); REQUIRE(strlen(buffer)==13); REQUIRE(strcmp(buffer, "100513.145748")==0); } } SECTION("String") { SECTION("null") { BoltValue_format_as_String(value, nullptr, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==0); REQUIRE(strlen(buffer)==0); REQUIRE(strcmp(buffer, "")==0); } SECTION("empty string") { BoltValue_format_as_String(value, "", 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==0); REQUIRE(strlen(buffer)==0); REQUIRE(strcmp(buffer, "")==0); } SECTION("abcdefg hijkl") { BoltValue_format_as_String(value, "abcdefg hijkl", 13); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==13); REQUIRE(strlen(buffer)==13); REQUIRE(strcmp(buffer, "abcdefg hijkl")==0); } } SECTION("Bytes") { SECTION("null") { BoltValue_format_as_Bytes(value, nullptr, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==1); REQUIRE(strlen(buffer)==1); REQUIRE(strcmp(buffer, "#")==0); } SECTION("empty array") { char empty[1]; BoltValue_format_as_Bytes(value, empty, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==1); REQUIRE(strlen(buffer)==1); REQUIRE(strcmp(buffer, "#")==0); } SECTION("byte sequence") { char empty[11] = "abcdefghij"; BoltValue_format_as_Bytes(value, empty, 10); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==21); REQUIRE(strlen(buffer)==21); REQUIRE(strcmp(buffer, "#6162636465666768696A")==0); } } SECTION("List") { SECTION("empty list") { BoltValue_format_as_List(value, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==2); REQUIRE(strlen(buffer)==2); REQUIRE(strcmp(buffer, "[]")==0); } SECTION("a list of basic types") { BoltValue_format_as_List(value, 5); BoltValue_format_as_Null(BoltList_value(value, 0)); BoltValue_format_as_Boolean(BoltList_value(value, 1), 1); BoltValue_format_as_Integer(BoltList_value(value, 2), 2467); BoltValue_format_as_Float(BoltList_value(value, 3), 3.14); BoltValue_format_as_String(BoltList_value(value, 4), "test string", 11); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==41); REQUIRE(strlen(buffer)==41); REQUIRE(strcmp(buffer, "[null, true, 2467, 3.140000, test string]")==0); } } SECTION("Dictionary") { SECTION("empty dictionary") { BoltValue_format_as_Dictionary(value, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==2); REQUIRE(strlen(buffer)==2); REQUIRE(strcmp(buffer, "{}")==0); } SECTION("a dictionary of basic types") { BoltValue_format_as_Dictionary(value, 5); BoltDictionary_set_key(value, 0, "a", 1); BoltValue_format_as_Null(BoltDictionary_value(value, 0)); BoltDictionary_set_key(value, 1, "b", 1); BoltValue_format_as_Boolean(BoltDictionary_value(value, 1), 1); BoltDictionary_set_key(value, 2, "c", 1); BoltValue_format_as_Integer(BoltDictionary_value(value, 2), 2467); BoltDictionary_set_key(value, 3, "d", 1); BoltValue_format_as_Float(BoltDictionary_value(value, 3), 3.14); BoltDictionary_set_key(value, 4, "e", 1); BoltValue_format_as_String(BoltDictionary_value(value, 4), "test string", 11); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==56); REQUIRE(strlen(buffer)==56); REQUIRE(strcmp(buffer, "{a: null, b: true, c: 2467, d: 3.140000, e: test string}")==0); } } SECTION("Structure") { SECTION("code only") { BoltValue_format_as_Structure(value, 65, 0); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==8); REQUIRE(strlen(buffer)==8); REQUIRE(strcmp(buffer, "$#0041()")==0); } SECTION("with simple fields") { BoltValue_format_as_Structure(value, 95, 5); BoltValue_format_as_Null(BoltStructure_value(value, 0)); BoltValue_format_as_Boolean(BoltStructure_value(value, 1), 0); BoltValue_format_as_Integer(BoltStructure_value(value, 2), 2467); BoltValue_format_as_Float(BoltStructure_value(value, 3), 3.14); BoltValue_format_as_String(BoltStructure_value(value, 4), "test string", 11); REQUIRE(BoltValue_to_string(value, buffer, buffer_size, nullptr)==48); REQUIRE(strlen(buffer)==48); REQUIRE(strcmp(buffer, "$#005F(null, false, 2467, 3.140000, test string)")==0); } } BoltValue_destroy(value); } } <|start_filename|>src/seabolt/src/bolt/name.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_NAME_H #define SEABOLT_NAME_H int get_address_components(volatile const struct sockaddr_storage* address, char* host_buffer, int host_buffer_size, char* port_buffer, int port_buffer_size); #endif //SEABOLT_NAME_H <|start_filename|>src/seabolt/src/bolt/routing-pool.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "address-private.h" #include "address-resolver-private.h" #include "address-set-private.h" #include "config-private.h" #include "connection-private.h" #include "direct-pool.h" #include "log-private.h" #include "mem.h" #include "routing-pool.h" #include "routing-table.h" #include "values-private.h" int BoltRoutingPool_ensure_server(struct BoltRoutingPool* pool, const struct BoltAddress* server, int create_direct_pool) { int index = BoltAddressSet_index_of(pool->servers, server); while (create_direct_pool && index<0) { // Release read lock BoltSync_rwlock_rdunlock(&pool->rwlock); if (BoltSync_rwlock_wrlock(&pool->rwlock)) { BoltLog_debug(pool->config->log, "[routing]: ensure_server(%s:%s): write lock acquired.", server->host, server->port); // Check once more if any other thread added this server in the mean-time index = BoltAddressSet_index_of(pool->servers, server); if (index<0) { // Add and return the index (which is always the end of the set - there's no ordering in place) index = BoltAddressSet_add(pool->servers, server); // Expand the direct pools and create a new one for this server pool->server_pools = BoltMem_reallocate((void*) pool->server_pools, (pool->servers->size-1)*SIZE_OF_DIRECT_POOL_PTR, (pool->servers->size)*SIZE_OF_DIRECT_POOL_PTR); pool->server_pools[index] = BoltDirectPool_create(server, pool->auth_token, pool->config); } BoltSync_rwlock_wrunlock(&pool->rwlock); BoltLog_debug(pool->config->log, "[routing]: ensure_server(%s:%s): write lock released.", server->host, server->port); } BoltSync_rwlock_rdlock(&pool->rwlock); } return index; } int BoltRoutingPool_update_routing_table_from(struct BoltRoutingPool* pool, struct BoltAddress* server) { const char* routing_table_call = "CALL dbms.cluster.routing.getRoutingTable($context)"; struct BoltConnection* connection = BoltConnection_create(); // Resolve the address int status = BoltAddress_resolve(server, NULL, pool->config->log); // Open a new connection if (status==BOLT_SUCCESS) { status = BoltConnection_open(connection, pool->config->transport, server, pool->config->trust, pool->config->log, pool->config->socket_options); } // Initialize if (status==BOLT_SUCCESS) { status = BoltConnection_init(connection, pool->config->user_agent, pool->auth_token); } // Load Run message filled with discovery procedure along with routing context if (status==BOLT_SUCCESS) { status = BoltConnection_set_run_cypher(connection, routing_table_call, strlen(routing_table_call), 1); if (status==BOLT_SUCCESS) { struct BoltValue* routing_table_context = BoltConnection_set_run_cypher_parameter(connection, 0, "context", 7); if (pool->config->routing_context!=NULL) { BoltValue_copy(routing_table_context, pool->config->routing_context); } status = BoltConnection_load_run_request(connection); } } // Load Pull All message if (status==BOLT_SUCCESS) { status = BoltConnection_load_pull_request(connection, -1); } // Send pending messages BoltRequest pull_all = 0; if (status==BOLT_SUCCESS) { pull_all = BoltConnection_last_request(connection); status = BoltConnection_send(connection); } // Retrieve results struct BoltValue* response = NULL; if (status==BOLT_SUCCESS) { while (BoltConnection_fetch(connection, pull_all)>0) { // We don't expect more than 1 record being returned if (response!=NULL) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; break; } struct BoltValue* field_keys = BoltConnection_field_names(connection); struct BoltValue* field_values = BoltConnection_field_values(connection); response = BoltValue_create(); BoltValue_format_as_Dictionary(response, field_keys->size); for (int i = 0; i<field_keys->size; i++) { BoltValue_copy(BoltDictionary_key(response, i), BoltList_value(field_keys, i)); BoltValue_copy(BoltDictionary_value(response, i), BoltList_value(field_values, i)); } } // We didn't receive any records if (response==NULL) { status = BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE; } } if (status==BOLT_SUCCESS) { status = RoutingTable_update(pool->routing_table, response); } BoltValue_destroy(response); BoltConnection_close(connection); BoltConnection_destroy(connection); return status; } int BoltRoutingPool_update_routing_table(struct BoltRoutingPool* pool) { int result = BOLT_ROUTING_UNABLE_TO_RETRIEVE_ROUTING_TABLE; // discover initial routers which pass through address resolver volatile BoltAddressSet* initial_routers = BoltAddressSet_create(); // first try to resolve using address resolver callback if specified BoltAddressResolver_resolve(pool->config->address_resolver, pool->address, initial_routers); // if nothing got added to the initial router addresses, add the connector hostname and port if (initial_routers->size==0) { BoltAddressSet_add(initial_routers, pool->address); } // Create a set of servers to update the routing table from volatile BoltAddressSet* routers = BoltAddressSet_create(); // First add routers present in the routing table BoltAddressSet_add_all(routers, pool->routing_table->routers); // Then add initial routers BoltAddressSet_add_all(routers, initial_routers); // Try each in turn until successful for (int i = 0; i<routers->size; i++) { BoltLog_debug(pool->config->log, "[routing]: trying routing table update from server '%s:%s'", routers->elements[i]->host, routers->elements[i]->port); int status = BoltRoutingPool_update_routing_table_from(pool, (BoltAddress*) routers->elements[i]); if (status==BOLT_SUCCESS) { result = BOLT_SUCCESS; break; } } // Destroy the set of servers BoltAddressSet_destroy(routers); BoltAddressSet_destroy(initial_routers); return result; } void BoltRoutingPool_cleanup(struct BoltRoutingPool* pool) { BoltLog_debug(pool->config->log, "[routing]: starting pool cleanup"); volatile BoltAddressSet* active_servers = BoltAddressSet_create(); BoltAddressSet_add_all(active_servers, pool->routing_table->routers); BoltAddressSet_add_all(active_servers, pool->routing_table->writers); BoltAddressSet_add_all(active_servers, pool->routing_table->readers); volatile BoltAddressSet* old_servers = pool->servers; volatile BoltDirectPool** old_server_pools = pool->server_pools; int old_size = old_servers->size; int cleanup_count = 0; int* cleanup_marker = (int*) BoltMem_allocate(old_size*sizeof(int)); for (int i = 0; i<old_size; i++) { cleanup_marker[i] = BoltAddressSet_index_of(active_servers, (BoltAddress*) old_servers->elements[i])<0 && BoltDirectPool_connections_in_use((BoltDirectPool*) old_server_pools[i])==0; cleanup_count = cleanup_count+cleanup_marker[i]; } if (cleanup_count>0) { int new_size = old_size-cleanup_count; volatile BoltAddressSet* new_servers = BoltAddressSet_create(); volatile BoltDirectPool** new_server_pools = BoltMem_allocate(new_size*SIZE_OF_DIRECT_POOL_PTR); for (int i = 0; i<old_size; i++) { if (cleanup_marker[i]) { continue; } int index = BoltAddressSet_add((BoltAddressSet*) new_servers, (BoltAddress*) old_servers->elements[i]); new_server_pools[index] = old_server_pools[i]; } pool->servers = new_servers; pool->server_pools = new_server_pools; for (int i = 0; i<old_size; i++) { if (cleanup_marker[i]) { BoltDirectPool* old_pool = (BoltDirectPool*) old_server_pools[i]; BoltLog_debug(pool->config->log, "[routing]: cleaning up pool towards %s:%s", old_pool->address->host, old_pool->address->port); BoltDirectPool_destroy(old_pool); } } BoltAddressSet_destroy((BoltAddressSet*) old_servers); BoltMem_deallocate((void*) old_server_pools, old_size*SIZE_OF_DIRECT_POOL_PTR); } BoltMem_deallocate(cleanup_marker, old_size*sizeof(int)); BoltAddressSet_destroy(active_servers); BoltLog_debug(pool->config->log, "[routing]: clean up complete (%d direct pools removed)", cleanup_count); } int BoltRoutingPool_ensure_routing_table(struct BoltRoutingPool* pool, BoltAccessMode mode) { int status = BOLT_SUCCESS; // Is routing table refresh wrt the requested access mode? while (status==BOLT_SUCCESS && RoutingTable_is_expired(pool->routing_table, mode)) { // First unlock read lock BoltSync_rwlock_rdunlock(&pool->rwlock); // Try acquire write lock if (BoltSync_rwlock_wrlock(&pool->rwlock)) { BoltLog_debug(pool->config->log, "[routing]: ensure_routing_table: write lock acquired."); // Check once more if routing table is still stale if (RoutingTable_is_expired(pool->routing_table, mode)) { BoltLog_debug(pool->config->log, "[routing]: routing table is expired, starting refresh"); status = BoltRoutingPool_update_routing_table(pool); if (status==BOLT_SUCCESS) { BoltLog_debug(pool->config->log, "[routing]: routing table is updated, calling cleanup on server pools"); BoltRoutingPool_cleanup(pool); BoltLog_debug(pool->config->log, "[routing]: server pools cleanup completed"); } else { BoltLog_debug(pool->config->log, "[routing]: routing table update failed with code %d", status); } } // Unlock write lock BoltSync_rwlock_wrunlock(&pool->rwlock); BoltLog_debug(pool->config->log, "[routing]: ensure_routing_table: write lock released."); } // Acquire read lock BoltSync_rwlock_rdlock(&pool->rwlock); } return status; } struct BoltAddress* BoltRoutingPool_select_least_connected(struct BoltRoutingPool* pool, volatile BoltAddressSet* servers, volatile int64_t offset) { if (servers->size==0) { return NULL; } // Start at an index that round-robins int start_index = offset%servers->size; int index = start_index; struct BoltAddress* least_connected_server = NULL; int least_connected = INT_MAX; while (1) { // Pick the current server BoltAddress* server = (BoltAddress*) servers->elements[index]; // Retrieve related direct pool if only it exists int pool_index = BoltRoutingPool_ensure_server(pool, server, 0); int server_active_connections = 0; if (pool_index>=0) { BoltDirectPool* server_pool = (BoltDirectPool*) pool->server_pools[pool_index]; // Compare in use connections to what we currently have and update if this is less server_active_connections = BoltDirectPool_connections_in_use(server_pool); } if (server_active_connections<least_connected) { least_connected_server = server; least_connected = server_active_connections; } // Stop if we had cycled through all servers index = (index+1)%servers->size; if (index==start_index) { break; } } return least_connected_server; } struct BoltAddress* BoltRoutingPool_select_least_connected_reader(struct BoltRoutingPool* pool) { return BoltRoutingPool_select_least_connected(pool, pool->routing_table->readers, BoltAtomic_increment(&pool->readers_offset)); } struct BoltAddress* BoltRoutingPool_select_least_connected_writer(struct BoltRoutingPool* pool) { return BoltRoutingPool_select_least_connected(pool, pool->routing_table->writers, BoltAtomic_increment(&pool->writers_offset)); } void BoltRoutingPool_forget_server(struct BoltRoutingPool* pool, const struct BoltAddress* server) { // Lock BoltSync_rwlock_wrlock(&pool->rwlock); BoltLog_debug(pool->config->log, "[routing]: forget_server(%s:%s): write lock acquired.", server->host, server->port); RoutingTable_forget_server(pool->routing_table, server); // Unlock BoltSync_rwlock_wrunlock(&pool->rwlock); BoltLog_debug(pool->config->log, "[routing]: forget_server(%s:%s): write lock released.", server->host, server->port); } void BoltRoutingPool_forget_writer(struct BoltRoutingPool* pool, const struct BoltAddress* server) { // Lock BoltSync_rwlock_wrlock(&pool->rwlock); BoltLog_debug(pool->config->log, "[routing]: forget_writer(%s:%s): write lock acquired.", server->host, server->port); RoutingTable_forget_writer(pool->routing_table, server); // Unlock BoltSync_rwlock_wrunlock(&pool->rwlock); BoltLog_debug(pool->config->log, "[routing]: forget_writer(%s:%s): write lock acquired.", server->host, server->port); } void BoltRoutingPool_handle_connection_error_by_code(struct BoltRoutingPool* pool, const struct BoltAddress* server, int code) { switch (code) { case BOLT_ROUTING_UNABLE_TO_RETRIEVE_ROUTING_TABLE: case BOLT_ROUTING_NO_SERVERS_TO_SELECT: case BOLT_ROUTING_UNABLE_TO_CONSTRUCT_POOL_FOR_SERVER: case BOLT_ROUTING_UNABLE_TO_REFRESH_ROUTING_TABLE: case BOLT_ROUTING_UNEXPECTED_DISCOVERY_RESPONSE: BoltRoutingPool_forget_server(pool, server); break; case BOLT_INTERRUPTED: case BOLT_CONNECTION_RESET: case BOLT_NO_VALID_ADDRESS: case BOLT_TIMED_OUT: case BOLT_CONNECTION_REFUSED: case BOLT_NETWORK_UNREACHABLE: case BOLT_TLS_ERROR: case BOLT_END_OF_TRANSMISSION: BoltRoutingPool_forget_server(pool, server); break; case BOLT_ADDRESS_NOT_RESOLVED: BoltRoutingPool_forget_server(pool, server); break; default: break; } } void BoltRoutingPool_handle_connection_error_by_failure(struct BoltRoutingPool* pool, const struct BoltAddress* server, const struct BoltValue* failure) { if (failure==NULL) { return; } struct BoltValue* code = BoltDictionary_value_by_key(failure, "code", 4); if (code==NULL) { return; } char* code_str = (char*) BoltMem_allocate((code->size+1)*sizeof(char)); strncpy(code_str, BoltString_get(code), code->size); code_str[code->size] = '\0'; if (strcmp(code_str, "Neo.ClientError.General.ForbiddenOnReadOnlyDatabase")==0) { BoltRoutingPool_forget_writer(pool, server); } else if (strcmp(code_str, "Neo.ClientError.Cluster.NotALeader")==0) { BoltRoutingPool_forget_writer(pool, server); } else if (strcmp(code_str, "Neo.TransientError.General.DatabaseUnavailable")==0) { BoltRoutingPool_forget_server(pool, server); } BoltMem_deallocate(code_str, (code->size+1)*sizeof(char)); } void BoltRoutingPool_handle_connection_error(struct BoltRoutingPool* pool, struct BoltConnection* connection) { switch (connection->status->error) { case BOLT_SUCCESS: break; case BOLT_SERVER_FAILURE: BoltRoutingPool_handle_connection_error_by_failure(pool, connection->address, BoltConnection_failure(connection)); break; default: BoltRoutingPool_handle_connection_error_by_code(pool, connection->address, connection->status->error); break; } } void BoltRoutingPool_connection_error_handler(struct BoltConnection* connection, void* state) { BoltRoutingPool_handle_connection_error((struct BoltRoutingPool*) state, connection); } struct BoltRoutingPool* BoltRoutingPool_create(const struct BoltAddress* address, const struct BoltValue* auth_token, const struct BoltConfig* config) { struct BoltRoutingPool* pool = (struct BoltRoutingPool*) BoltMem_allocate(SIZE_OF_ROUTING_POOL); pool->address = address; pool->config = config; pool->auth_token = <PASSWORD>_token; pool->servers = BoltAddressSet_create(); pool->server_pools = NULL; pool->routing_table = RoutingTable_create(); pool->readers_offset = 0; pool->writers_offset = 0; BoltSync_rwlock_create(&pool->rwlock); return pool; } void BoltRoutingPool_destroy(struct BoltRoutingPool* pool) { for (int i = 0; i<pool->servers->size; i++) { BoltDirectPool_destroy((BoltDirectPool*) pool->server_pools[i]); } BoltMem_deallocate((void*) pool->server_pools, pool->servers->size*SIZE_OF_DIRECT_POOL_PTR); BoltAddressSet_destroy((BoltAddressSet*) pool->servers); RoutingTable_destroy(pool->routing_table); BoltSync_rwlock_destroy(&pool->rwlock); BoltMem_deallocate(pool, SIZE_OF_ROUTING_POOL); } BoltConnection* BoltRoutingPool_acquire(struct BoltRoutingPool* pool, BoltAccessMode mode, BoltStatus* status) { struct BoltAddress* server = NULL; BoltSync_rwlock_rdlock(&pool->rwlock); int result = BoltRoutingPool_ensure_routing_table(pool, mode); if (result==BOLT_SUCCESS) { server = mode==BOLT_ACCESS_MODE_READ ? BoltRoutingPool_select_least_connected_reader(pool) : BoltRoutingPool_select_least_connected_writer(pool); if (server==NULL) { result = BOLT_ROUTING_NO_SERVERS_TO_SELECT; } else { // protect against modification of the returned address instance by other threads that may free it server = BoltAddress_create(server->host, server->port); } } int server_pool_index = -1; if (result==BOLT_SUCCESS) { server_pool_index = BoltRoutingPool_ensure_server(pool, server, 1); if (server_pool_index<0) { result = BOLT_ROUTING_UNABLE_TO_CONSTRUCT_POOL_FOR_SERVER; } } BoltConnection* connection = NULL; if (result==BOLT_SUCCESS) { connection = BoltDirectPool_acquire((BoltDirectPool*) pool->server_pools[server_pool_index], status); if (connection!=NULL) { result = BOLT_SUCCESS; connection->on_error_cb_state = pool; connection->on_error_cb = BoltRoutingPool_connection_error_handler; } } if (server!=NULL) { BoltAddress_destroy(server); } BoltSync_rwlock_rdunlock(&pool->rwlock); if (result==BOLT_SUCCESS) { return connection; } // check if we were able to complete server selection. this is not the case when routing // table refresh fails. if (server!=NULL) { BoltRoutingPool_handle_connection_error_by_code(pool, server, result); } status->error = result; status->error_ctx = NULL; return NULL; } int BoltRoutingPool_release(struct BoltRoutingPool* pool, struct BoltConnection* connection) { int result = -1; BoltSync_rwlock_rdlock(&pool->rwlock); connection->on_error_cb = NULL; connection->on_error_cb_state = NULL; int server_pool_index = BoltRoutingPool_ensure_server(pool, connection->address, 0); if (server_pool_index<0) { BoltConnection_close(connection); } else { result = BoltDirectPool_release((BoltDirectPool*) pool->server_pools[server_pool_index], connection); } BoltSync_rwlock_rdunlock(&pool->rwlock); return result; } <|start_filename|>src/seabolt/src/bolt/sync-win32.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "sync.h" #include "mem.h" #include "time.h" void BoltSync_sleep(int milliseconds) { SleepEx(milliseconds, TRUE); } int BoltSync_mutex_create(mutex_t* mutex) { *mutex = BoltMem_allocate(sizeof(CRITICAL_SECTION)); InitializeCriticalSectionAndSpinCount(*mutex, 0x400); return 0; } int BoltSync_mutex_destroy(mutex_t* mutex) { DeleteCriticalSection(*mutex); BoltMem_deallocate(*mutex, sizeof(CRITICAL_SECTION)); return 0; } int BoltSync_mutex_lock(mutex_t* mutex) { EnterCriticalSection(*mutex); return 0; } int BoltSync_mutex_unlock(mutex_t* mutex) { LeaveCriticalSection(*mutex); return 0; } int BoltSync_mutex_trylock(mutex_t* mutex) { const BOOL result = TryEnterCriticalSection(*mutex); if (result) { return 1; } return 0; } int BoltSync_rwlock_create(rwlock_t* rwlock) { InitializeSRWLock((PSRWLOCK) rwlock); return 1; } int BoltSync_rwlock_destroy(rwlock_t* rwlock) { UNUSED(rwlock); return 1; } int BoltSync_rwlock_rdlock(rwlock_t* rwlock) { AcquireSRWLockShared((PSRWLOCK) rwlock); return 1; } int BoltSync_rwlock_wrlock(rwlock_t* rwlock) { AcquireSRWLockExclusive((PSRWLOCK) rwlock); return 1; } int BoltSync_rwlock_tryrdlock(rwlock_t* rwlock) { return TryAcquireSRWLockShared((PSRWLOCK) rwlock)==TRUE; } int BoltSync_rwlock_trywrlock(rwlock_t* rwlock) { return TryAcquireSRWLockExclusive((PSRWLOCK) rwlock)==TRUE; } int BoltSync_rwlock_timedrdlock(rwlock_t* rwlock, int timeout_ms) { int64_t end_at = BoltTime_get_time_ms()+timeout_ms; while (1) { if (BoltSync_rwlock_tryrdlock(rwlock)) { return 1; } if (BoltTime_get_time_ms()>end_at) { return 0; } BoltSync_sleep(10); } } int BoltSync_rwlock_timedwrlock(rwlock_t* rwlock, int timeout_ms) { int64_t end_at = BoltTime_get_time_ms()+timeout_ms; while (1) { if (BoltSync_rwlock_trywrlock(rwlock)) { return 1; } if (BoltTime_get_time_ms()>end_at) { return 0; } BoltSync_sleep(10); } } int BoltSync_rwlock_rdunlock(rwlock_t* rwlock) { ReleaseSRWLockShared((PSRWLOCK) rwlock); return 1; } int BoltSync_rwlock_wrunlock(rwlock_t* rwlock) { ReleaseSRWLockExclusive((PSRWLOCK) rwlock); return 1; } int BoltSync_cond_create(cond_t* cond) { *cond = BoltMem_allocate(sizeof(CONDITION_VARIABLE)); InitializeConditionVariable((PCONDITION_VARIABLE)*cond); return 1; } int BoltSync_cond_destroy(cond_t* cond) { BoltMem_deallocate(*cond, sizeof(CONDITION_VARIABLE)); return 1; } int BoltSync_cond_signal(cond_t* cond) { WakeConditionVariable(*cond); return 1; } int BoltSync_cond_broadcast(cond_t* cond) { WakeAllConditionVariable(*cond); return 1; } int BoltSync_cond_wait(cond_t* cond, mutex_t* mutex) { return SleepConditionVariableCS(*cond, *mutex, INFINITE); } int BoltSync_cond_timedwait(cond_t* cond, mutex_t* mutex, int timeout_ms) { return SleepConditionVariableCS(*cond, *mutex, timeout_ms); } unsigned long BoltThread_id() { return (unsigned long) GetCurrentThreadId(); } <|start_filename|>src/seabolt/src/bolt/address-resolver.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ALL_SERVER_ADDRESS_RESOLVER_H #define SEABOLT_ALL_SERVER_ADDRESS_RESOLVER_H #include "bolt-public.h" #include "address.h" #include "address-set.h" /** * The address resolver function signature that implementors should provide for a working custom resolver. * * @param state the state object as provided to \ref BoltAddressResolver_create. * @param address the address to be resolved by the resolver function. * @param set the target set the resolved addresses should be added. */ typedef void (* address_resolver_func)(void* state, BoltAddress* address, BoltAddressSet* set); /** * The type that defines an address resolver to be used during the initial (and fall back) routing discovery. * * An instance needs to be created with \ref BoltAddressResolver_create and destroyed with * \ref BoltAddressResolver_destroy after \ref BoltConfig_set_address_resolver is called. */ typedef struct BoltAddressResolver BoltAddressResolver; /** * Creates a new instance of \ref BoltAddressResolver. * * @param state an optional object that will be passed to provided address resolver function. * @param resolver_func the address resolver function to be called. * @returns the pointer to the newly allocated \ref BoltAddressResolver instance. */ SEABOLT_EXPORT BoltAddressResolver* BoltAddressResolver_create(void* state, address_resolver_func resolver_func); /** * Destroys the passed \ref BoltAddressResolver instance. * * @param resolver the instance to be destroyed. */SEABOLT_EXPORT void BoltAddressResolver_destroy(BoltAddressResolver* resolver); #endif //SEABOLT_ALL_SERVER_ADDRESS_RESOLVER_H <|start_filename|>src/seabolt/src/bolt/communication-secure-openssl.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "communication-secure.h" #include "config-private.h" #include "log-private.h" #include "status-private.h" #include "mem.h" #include "communication-plain.h" #include "sync.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/x509v3.h> typedef struct BoltSecurityContext { SSL_CTX* ssl_ctx; } BoltSecurityContext; typedef struct OpenSSLContext { int owns_sec_ctx; BoltSecurityContext* sec_ctx; char* id; char* hostname; SSL* ssl; BoltTrust* trust; BoltCommunication* plain_comm; } OpenSSLContext; int SSL_CTX_TRUST_INDEX = -1; int SSL_CTX_LOG_INDEX = -1; int SSL_ID_INDEX = -1; int verify_callback(int preverify_ok, X509_STORE_CTX* ctx) { // get related BoltTrust and BoltLog instances SSL* ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); SSL_CTX* context = SSL_get_SSL_CTX(ssl); struct BoltTrust* trust = (struct BoltTrust*) SSL_CTX_get_ex_data(context, SSL_CTX_TRUST_INDEX); struct BoltLog* log = (struct BoltLog*) SSL_CTX_get_ex_data(context, SSL_CTX_LOG_INDEX); char* id = (char*) SSL_get_ex_data(ssl, SSL_ID_INDEX); //char* id = (char*) SSL_CTX_get_ex_data(context, SSL_CTX_ID_INDEX); // check if preverify is successful or not if (!preverify_ok) { // get the error code, bear in mind that we'll have this callback called twice if both X509 // and hostname verification failed int error = X509_STORE_CTX_get_error(ctx); switch (error) { case X509_V_ERR_HOSTNAME_MISMATCH: if (trust!=NULL && trust->skip_verify_hostname) { BoltLog_warning(log, "[%s]: Openssl reported failure of hostname verification due to a mismatch, but resuming handshake since hostname verification is set to be skipped", id); return 1; } else { BoltLog_debug(log, "[%s]: Openssl reported failure of hostname verification due to a mismatch, aborting handshake", id); return 0; } default: if (trust!=NULL && trust->skip_verify) { BoltLog_warning(log, "[%s]: Openssl reported error '%s' with code '%d' when establishing trust, but resuming handshake since trust verification is set to be skipped", id, X509_verify_cert_error_string(error), error); return 1; } else { BoltLog_debug(log, "[%s]: Openssl reported error '%s' with code '%d' when establishing trust, aborting handshake", id, X509_verify_cert_error_string(error), error); return 0; } } } else { BoltLog_debug(log, "[%s]: Openssl established trust", id); } return 1; } BoltSecurityContext* BoltSecurityContext_create(struct BoltTrust* trust, const char* hostname, const struct BoltLog* log, const char* id) { UNUSED(id); SSL_CTX* context = NULL; X509_STORE* store = NULL; const SSL_METHOD* ctx_init_method = NULL; #if OPENSSL_VERSION_NUMBER<0x10100000L ctx_init_method = TLSv1_2_client_method(); #else ctx_init_method = TLS_client_method(); #endif // create a new SSL_CTX with TLS1.2 enabled context = SSL_CTX_new(ctx_init_method); if (context==NULL) { return NULL; } // set auto retry unsigned long new_mode = (unsigned long) SSL_CTX_set_mode(context, SSL_MODE_AUTO_RETRY); if ((new_mode & (unsigned long) SSL_MODE_AUTO_RETRY)!=SSL_MODE_AUTO_RETRY) { BoltLog_warning(log, "[%s]: Unable to set SSL_MODE_AUTO_RETRY"); } // load trusted certificates int status = 1; if (trust!=NULL && trust->certs!=NULL && trust->certs_len!=0) { // create a new x509 certificate store store = X509_STORE_new(); if (store!=NULL) { // add default trust certs to the store, which are pointed by // SSL_CERT_DIR and SSL_CERT_FILE, see more on OPENSSL docs status = X509_STORE_set_default_paths(store); } if (status) { // if an explicit PEM encoded certs are provided as part of config if (trust->certs!=NULL && trust->certs_len!=0) { // load the buffer into a BIO memory reader BIO* trusted_certs_bio = BIO_new(BIO_s_mem()); BIO_write(trusted_certs_bio, trust->certs, (int32_t) trust->certs_len); // read all X509_AUX objects encoded (_AUX suffix tells that these // certificates are to be treated as trusted X509* trusted_cert = PEM_read_bio_X509_AUX(trusted_certs_bio, NULL, NULL, NULL); while (trusted_cert!=NULL) { X509_STORE_add_cert(store, trusted_cert); trusted_cert = PEM_read_bio_X509_AUX(trusted_certs_bio, NULL, NULL, NULL); } // free the BIO reader BIO_free(trusted_certs_bio); } } // set trusted certificate store on the context status = SSL_CTX_set1_verify_cert_store(context, store); } else { // set trusted certificates from the defaults, which are pointed by // SSL_CERT_DIR and SSL_CERT_FILE, see more on OPENSSL docs status = SSL_CTX_set_default_verify_paths(context); } // Store BoltTrust and BoltLog objects into the context to be used in verification callback SSL_CTX_set_ex_data(context, SSL_CTX_TRUST_INDEX, trust); SSL_CTX_set_ex_data(context, SSL_CTX_LOG_INDEX, (void*) log); // Enable hostname verification X509_VERIFY_PARAM* param = SSL_CTX_get0_param(context); X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname)); // Enable verification and set verify callback SSL_CTX_set_verify(context, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, verify_callback); // cleanup context if anything went wrong if (!status && context!=NULL) { SSL_CTX_free(context); context = NULL; } // cleanup store if anything went wrong if (!status && store!=NULL) { X509_STORE_free(store); store = NULL; } if (context!=NULL) { BoltSecurityContext* secContext = BoltMem_allocate(sizeof(BoltSecurityContext)); secContext->ssl_ctx = context; return secContext; } return NULL; } void BoltSecurityContext_destroy(BoltSecurityContext* context) { SSL_CTX_free(context->ssl_ctx); BoltMem_deallocate(context, sizeof(BoltSecurityContext)); } #if OPENSSL_VERSION_NUMBER<0x10100000L static mutex_t* locks; struct CRYPTO_dynlock_value { mutex_t mutex; }; static unsigned long secure_openssl_id_callback(void); static void secure_openssl_locking_callback(int mode, int type, const char* file, int line); static struct CRYPTO_dynlock_value* secure_openssl_create_mutex(const char* file, int line); static void secure_openssl_lock_mutext(int mode, struct CRYPTO_dynlock_value* l, const char* file, int line); static void secure_openssl_destroy_mutex(struct CRYPTO_dynlock_value* l, const char* file, int line); void CRYPTO_thread_setup(void) { int i; locks = OPENSSL_malloc(CRYPTO_num_locks()*sizeof(mutex_t)); if (!locks) { return; } for (i = 0; i<CRYPTO_num_locks(); i++) { BoltSync_mutex_create(&locks[i]); } CRYPTO_set_id_callback(secure_openssl_id_callback); CRYPTO_set_locking_callback(secure_openssl_locking_callback); CRYPTO_set_dynlock_create_callback(secure_openssl_create_mutex); CRYPTO_set_dynlock_lock_callback(secure_openssl_lock_mutext); CRYPTO_set_dynlock_destroy_callback(secure_openssl_destroy_mutex); } void CRYPTO_thread_cleanup(void) { CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); CRYPTO_set_dynlock_create_callback(NULL); CRYPTO_set_dynlock_lock_callback(NULL); CRYPTO_set_dynlock_destroy_callback(NULL); CRYPTO_set_locking_callback(NULL); for (int i = 0; i<CRYPTO_num_locks(); i++) { BoltSync_mutex_destroy(&locks[i]); } OPENSSL_free(locks); } static void secure_openssl_locking_callback(int mode, int type, const char* file, int line) { UNUSED(file); UNUSED(line); if (mode & CRYPTO_LOCK) { BoltSync_mutex_lock(&locks[type]); } else { BoltSync_mutex_unlock(&locks[type]); } } static unsigned long secure_openssl_id_callback(void) { return BoltThread_id(); } static struct CRYPTO_dynlock_value* secure_openssl_create_mutex(const char* file, int line) { UNUSED(file); UNUSED(line); struct CRYPTO_dynlock_value* value; value = (struct CRYPTO_dynlock_value*) malloc(sizeof(struct CRYPTO_dynlock_value)); if (!value) return NULL; BoltSync_mutex_create(&value->mutex); return value; } static void secure_openssl_lock_mutext(int mode, struct CRYPTO_dynlock_value* l, const char* file, int line) { UNUSED(file); UNUSED(line); if (mode & CRYPTO_LOCK) { BoltSync_mutex_lock(&l->mutex); } else { BoltSync_mutex_unlock(&l->mutex); } } static void secure_openssl_destroy_mutex(struct CRYPTO_dynlock_value* l, const char* file, int line) { UNUSED(file); UNUSED(line); BoltSync_mutex_destroy(&l->mutex); free(l); } #endif int BoltSecurityContext_startup() { #if OPENSSL_VERSION_NUMBER<0x10100000L CRYPTO_thread_setup(); SSL_library_init(); #else OPENSSL_init_ssl(0, NULL); #endif // load error strings and have cryto initialized SSL_load_error_strings(); OpenSSL_add_all_algorithms(); // register two ex_data indexes that we'll use to store // BoltTrust and BoltLog instances SSL_CTX_TRUST_INDEX = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL); SSL_CTX_LOG_INDEX = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL); SSL_ID_INDEX = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); return BOLT_SUCCESS; } int BoltSecurityContext_shutdown() { #if OPENSSL_VERSION_NUMBER<0x10100000L CRYPTO_thread_cleanup(); #endif return BOLT_SUCCESS; } int secure_openssl_last_error(BoltCommunication* comm, int ssl_ret, int* ssl_error_code, int* last_error) { OpenSSLContext* ctx = comm->context; // On windows, SSL_get_error resets WSAGetLastError so we're left without an error code after // asking error code - so we're saving it here in case. int last_error_saved = ctx->plain_comm->last_error(ctx->plain_comm); *ssl_error_code = SSL_get_error(ctx->ssl, ssl_ret); switch (*ssl_error_code) { case SSL_ERROR_NONE: return BOLT_SUCCESS; case SSL_ERROR_SYSCALL: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: { *last_error = ctx->plain_comm->last_error(ctx->plain_comm); if (*last_error==0) { *last_error = last_error_saved; } if (*last_error==0) { return BOLT_END_OF_TRANSMISSION; } return ctx->plain_comm->transform_error(ctx->plain_comm, *last_error); } case SSL_ERROR_ZERO_RETURN: { return BOLT_END_OF_TRANSMISSION; } default: return BOLT_TLS_ERROR; } } int secure_openssl_open(BoltCommunication* comm, const struct sockaddr_storage* address) { OpenSSLContext* ctx = comm->context; PlainCommunicationContext* ctx_plain = ctx->plain_comm->context; int status = ctx->plain_comm->open(ctx->plain_comm, address); if (status!=BOLT_SUCCESS) { return status; } if (ctx->sec_ctx==NULL) { ctx->sec_ctx = BoltSecurityContext_create(ctx->trust, ctx->hostname, comm->log, ctx->id); ctx->owns_sec_ctx = 1; } ctx->ssl = SSL_new(ctx->sec_ctx->ssl_ctx); SSL_set_ex_data(ctx->ssl, SSL_ID_INDEX, (void*) ctx->id); status = 1; // Link to underlying socket if (status) { status = SSL_set_fd(ctx->ssl, ctx_plain->fd_socket); if (!status) { BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_openssl_open(%s:%d), SSL_set_fd returned: %d", __FILE__, __LINE__, status); } } // Enable SNI if (status) { status = SSL_set_tlsext_host_name(ctx->ssl, ctx->hostname); if (!status) { BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_openssl_open(%s:%d), SSL_set_tlsext_host_name returned: %d", __FILE__, __LINE__, status); } } if (status) { status = SSL_connect(ctx->ssl); if (status==1) { return BOLT_SUCCESS; } BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_openssl_open(%s:%d), SSL_connect returned: %d", __FILE__, __LINE__, status); } SSL_free(ctx->ssl); if (ctx->owns_sec_ctx) { BoltSecurityContext_destroy(ctx->sec_ctx); } ctx->owns_sec_ctx = 0; ctx->sec_ctx = NULL; ctx->ssl = NULL; return comm->status->error; } int secure_openssl_close(BoltCommunication* comm) { OpenSSLContext* ctx = comm->context; if (ctx->ssl!=NULL) { SSL_shutdown(ctx->ssl); SSL_free(ctx->ssl); ctx->ssl = NULL; } if (ctx->sec_ctx!=NULL && ctx->owns_sec_ctx) { BoltSecurityContext_destroy(ctx->sec_ctx); ctx->sec_ctx = NULL; ctx->owns_sec_ctx = 0; } return ctx->plain_comm->close(ctx->plain_comm); } int secure_openssl_send(BoltCommunication* comm, char* buffer, int length, int* sent) { OpenSSLContext* ctx = comm->context; int bytes = SSL_write(ctx->ssl, buffer, length); if (bytes<0) { int last_error = 0, ssl_error = 0; int last_error_transformed = secure_openssl_last_error(comm, bytes, &ssl_error, &last_error); BoltStatus_set_error_with_ctx(comm->status, last_error_transformed, "secure_openssl_send(%s:%d), SSL_write error code: %d, underlying error code: %d", __FILE__, __LINE__, ssl_error, last_error); return BOLT_STATUS_SET; } *sent = bytes; return BOLT_SUCCESS; } int secure_openssl_recv(BoltCommunication* comm, char* buffer, int length, int* received) { OpenSSLContext* ctx = comm->context; int bytes = SSL_read(ctx->ssl, buffer, length); if (bytes<=0) { int last_error = 0, ssl_error = 0; int last_error_transformed = secure_openssl_last_error(comm, bytes, &ssl_error, &last_error); BoltStatus_set_error_with_ctx(comm->status, last_error_transformed, "secure_openssl_recv(%s:%d), SSL_read error code: %d, underlying error code: %d", __FILE__, __LINE__, ssl_error, last_error); return BOLT_STATUS_SET; } *received = bytes; return BOLT_SUCCESS; } int secure_openssl_destroy(BoltCommunication* comm) { OpenSSLContext* ctx = comm->context; if (ctx==NULL) { return BOLT_SUCCESS; } if (ctx->sec_ctx!=NULL && ctx->owns_sec_ctx) { BoltSecurityContext_destroy(ctx->sec_ctx); ctx->sec_ctx = NULL; ctx->owns_sec_ctx = 0; } BoltCommunication_destroy(ctx->plain_comm); BoltMem_deallocate(ctx->hostname, strlen(ctx->hostname)+1); BoltMem_deallocate(ctx->id, strlen(ctx->id)+1); BoltMem_deallocate(ctx, sizeof(OpenSSLContext)); comm->context = NULL; return BOLT_SUCCESS; } BoltAddress* secure_openssl_local_endpoint(BoltCommunication* comm) { OpenSSLContext* ctx = comm->context; return ctx->plain_comm->get_local_endpoint(ctx->plain_comm); } BoltAddress* secure_openssl_remote_endpoint(BoltCommunication* comm) { OpenSSLContext* ctx = comm->context; return ctx->plain_comm->get_remote_endpoint(ctx->plain_comm); } int secure_openssl_ignore_sigpipe(BoltCommunication* comm) { OpenSSLContext* ctx = comm->context; return ctx->plain_comm->ignore_sigpipe(ctx->plain_comm); } int secure_openssl_restore_sigpipe(BoltCommunication* comm) { OpenSSLContext* ctx = comm->context; return ctx->plain_comm->restore_sigpipe(ctx->plain_comm); } BoltCommunication* BoltCommunication_create_secure(BoltSecurityContext* sec_ctx, BoltTrust* trust, BoltSocketOptions* socket_options, BoltLog* log, const char* hostname, const char* id) { BoltCommunication* plain_comm = BoltCommunication_create_plain(socket_options, log); BoltCommunication* comm = BoltMem_allocate(sizeof(BoltCommunication)); comm->open = &secure_openssl_open; comm->close = &secure_openssl_close; comm->send = &secure_openssl_send; comm->recv = &secure_openssl_recv; comm->destroy = &secure_openssl_destroy; comm->get_local_endpoint = &secure_openssl_local_endpoint; comm->get_remote_endpoint = &secure_openssl_remote_endpoint; comm->ignore_sigpipe = &secure_openssl_ignore_sigpipe; comm->restore_sigpipe = &secure_openssl_restore_sigpipe; comm->status_owned = 0; comm->status = plain_comm->status; comm->sock_opts_owned = 0; comm->sock_opts = plain_comm->sock_opts; comm->log = log; OpenSSLContext* context = BoltMem_allocate(sizeof(OpenSSLContext)); context->sec_ctx = sec_ctx; context->owns_sec_ctx = sec_ctx==NULL; context->ssl = NULL; context->trust = trust; context->plain_comm = plain_comm; context->id = BoltMem_duplicate(id, strlen(id)+1); context->hostname = BoltMem_duplicate(hostname, strlen(hostname)+1); comm->context = context; return comm; } #if defined(SEABOLT_STATIC_DEFINE) && defined(_MSC_VER) FILE * __cdecl __iob_func(void) { FILE* _iob = (FILE*)malloc(3 * sizeof(FILE)); _iob[0] = *stdin; _iob[1] = *stdout; _iob[2] = *stderr; return _iob; } #endif <|start_filename|>src/seabolt/src/bolt/no-pool.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "address-private.h" #include "atomic.h" #include "config-private.h" #include "connection-private.h" #include "no-pool.h" #include "log-private.h" #include "mem.h" #include "protocol.h" #include "sync.h" #include "time.h" #define MAX_ID_LEN 16 static int64_t pool_seq = 0; int find_open_connection(struct BoltNoPool* pool, struct BoltConnection* connection) { for (int i = 0; i<pool->size; i++) { BoltConnection*candidate = (BoltConnection*) pool->connections[i]; if (candidate==connection) { return i; } } return -1; } struct BoltNoPool* BoltNoPool_create(const struct BoltAddress* address, const struct BoltValue* auth_token, const struct BoltConfig* config) { char* id = BoltMem_allocate(MAX_ID_LEN); snprintf(id, MAX_ID_LEN, "pool-%" PRId64, BoltAtomic_increment(&pool_seq)); BoltLog_info(config->log, "[%s]: Creating pool towards %s:%s", id, address->host, address->port); struct BoltNoPool* pool = (struct BoltNoPool*) BoltMem_allocate(SIZE_OF_NO_POOL); BoltSync_mutex_create(&pool->mutex); pool->id = id; pool->config = config; pool->address = BoltAddress_create_with_lock(address->host, address->port); pool->auth_token = <PASSWORD>_token; pool->size = 0; pool->connections = NULL; return pool; } void BoltNoPool_destroy(struct BoltNoPool* pool) { BoltLog_info(pool->config->log, "[%s]: Destroying non-released connections towards %s:%s", pool->id, pool->address->host, pool->address->port); for (int index = 0; index<pool->size; index++) { BoltConnection*connection = (BoltConnection*) pool->connections[index]; BoltConnection_close(connection); BoltConnection_destroy(connection); } BoltMem_deallocate((void*) pool->connections, pool->size*sizeof(BoltConnection*)); BoltAddress_destroy(pool->address); BoltMem_deallocate(pool->id, MAX_ID_LEN); BoltSync_mutex_destroy(&pool->mutex); BoltMem_deallocate(pool, SIZE_OF_NO_POOL); } BoltConnection* BoltNoPool_acquire(struct BoltNoPool* pool, BoltStatus* status) { int pool_error = BOLT_SUCCESS; BoltConnection*connection = NULL; BoltLog_info(pool->config->log, "[%s]: Acquiring connection towards %s:%s", pool->id, pool->address->host, pool->address->port); connection = BoltConnection_create(); switch (BoltAddress_resolve(pool->address, NULL, pool->config->log)) { case 0: break; default: pool_error = BOLT_ADDRESS_NOT_RESOLVED; // Could not resolve address } if (pool_error==BOLT_SUCCESS) { switch (BoltConnection_open(connection, pool->config->transport, pool->address, pool->config->trust, pool->config->log, pool->config->socket_options)) { case 0: break; default: pool_error = BOLT_CONNECTION_HAS_MORE_INFO; // Could not open socket } } if (pool_error==BOLT_SUCCESS) { switch (BoltConnection_init(connection, pool->config->user_agent, pool->auth_token)) { case 0: break; default: pool_error = BOLT_CONNECTION_HAS_MORE_INFO; } } switch (pool_error) { case BOLT_SUCCESS: { status->state = connection->status->state; status->error = BOLT_SUCCESS; status->error_ctx = NULL; status->error_ctx_size = 0; BoltSync_mutex_lock(&pool->mutex); int index = pool->size; pool->connections = BoltMem_reallocate((void*) pool->connections, pool->size*sizeof(BoltConnection*), (pool->size+1)*sizeof(BoltConnection*)); pool->size = pool->size+1; pool->connections[index] = connection; BoltSync_mutex_unlock(&pool->mutex); break; } case BOLT_CONNECTION_HAS_MORE_INFO: status->state = connection->status->state; status->error = connection->status->error; status->error_ctx_size = connection->status->error_ctx_size; status->error_ctx = BoltMem_duplicate(connection->status->error_ctx, connection->status->error_ctx_size); break; default: status->state = BOLT_CONNECTION_STATE_DISCONNECTED; status->error = pool_error; status->error_ctx = NULL; status->error_ctx_size = 0; break; } return connection; } int BoltNoPool_release(struct BoltNoPool* pool, struct BoltConnection* connection) { BoltLog_info(pool->config->log, "[%s]: Closing connection towards %s:%s", pool->id, pool->address->host, pool->address->port); BoltSync_mutex_lock(&pool->mutex); int index = find_open_connection(pool, connection); if (index>=0) { for (int i = index; i<pool->size-1; i++) { pool->connections[i] = pool->connections[i+1]; } pool->connections = BoltMem_reallocate((void*) pool->connections, pool->size*sizeof(BoltConnection*), (pool->size-1)*sizeof(BoltConnection*)); pool->size = pool->size-1; } BoltSync_mutex_unlock(&pool->mutex); BoltConnection_close(connection); BoltConnection_destroy(connection); return index; } <|start_filename|>src/seabolt/src/bolt/buffering.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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. */ /** * @file */ #ifndef SEABOLT_BUFFERING #define SEABOLT_BUFFERING #include "bolt-public.h" /** * General purpose data buffer. */ typedef struct BoltBuffer { int size; int extent; int cursor; char* data; } BoltBuffer; /** * Create a buffer. * * @param size * @return */ BoltBuffer* BoltBuffer_create(int size); /** * Destroy a buffer. * * @param buffer */ void BoltBuffer_destroy(BoltBuffer* buffer); /** * Compact a buffer by removing unused space. * * @param buffer */ void BoltBuffer_compact(BoltBuffer* buffer); /** * Return the amount of loadable space in a buffer, in bytes. * * @param buffer * @return */ int BoltBuffer_loadable(BoltBuffer* buffer); /** * Allocate space in a buffer for loading data and return a pointer to that space. * * @param buffer * @param size * @return */ char* BoltBuffer_load_pointer(BoltBuffer* buffer, int size); /** * Load data into a buffer. * * @param buffer * @param data * @param size */ void BoltBuffer_load(BoltBuffer* buffer, const char* data, int size); /** * Load an unsigned 8-bit integer into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_u8(BoltBuffer* buffer, uint8_t x); /** * Load an unsigned 16-bit integer (big-endian) into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_u16be(BoltBuffer* buffer, uint16_t x); /** * Load a signed 8-bit integer into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_i8(BoltBuffer* buffer, int8_t x); /** * Load a signed 16-bit integer (big-endian) into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_i16be(BoltBuffer* buffer, int16_t x); /** * Load a signed 32-bit integer (big-endian) into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_i32be(BoltBuffer* buffer, int32_t x); /** * Load a signed 64-bit integer (big-endian) into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_i64be(BoltBuffer* buffer, int64_t x); /** * Load a double precision floating point number (big-endian) into a buffer. * * @param buffer * @param x */ void BoltBuffer_load_f64be(BoltBuffer* buffer, double x); /** * Return the amount of unloadable data in a buffer, in bytes. * * @param buffer * @return */ int BoltBuffer_unloadable(BoltBuffer* buffer); /** * Mark data in a buffer for unloading and return a pointer to that data. * * @param buffer * @param size * @return */ char* BoltBuffer_unload_pointer(BoltBuffer* buffer, int size); /** * Unload data from a buffer. * * @param buffer * @param data * @param size * @return */ int BoltBuffer_unload(BoltBuffer* buffer, char* data, int size); /** * Return the next unloadable byte in a buffer as an unsigned 8-bit integer. * * @param buffer * @param x * @return */ int BoltBuffer_peek_u8(BoltBuffer* buffer, uint8_t* x); /** * Unload an unsigned 8-bit integer from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_u8(BoltBuffer* buffer, uint8_t* x); /** * Unload an unsigned 16-bit integer (big endian) from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_u16be(BoltBuffer* buffer, uint16_t* x); /** * Unload a signed 8-bit integer from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_i8(BoltBuffer* buffer, int8_t* x); /** * Unload a signed 16-bit integer (big endian) from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_i16be(BoltBuffer* buffer, int16_t* x); /** * Unload a signed 32-bit integer (big endian) from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_i32be(BoltBuffer* buffer, int32_t* x); /** * Unload a signed 64-bit integer (big endian) from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_i64be(BoltBuffer* buffer, int64_t* x); /** * Unload a double precision floating point number (big endian) from a buffer. * * @param buffer * @param x * @return */ int BoltBuffer_unload_f64be(BoltBuffer* buffer, double* x); #endif // SEABOLT_BUFFERING <|start_filename|>src/seabolt/src/bolt/string-builder.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "string-builder.h" struct StringBuilder* StringBuilder_create() { struct StringBuilder* builder = (struct StringBuilder*) malloc(sizeof(struct StringBuilder)); builder->buffer = (char*) malloc(256*sizeof(char)); builder->buffer[0] = 0; builder->buffer_pos = 0; builder->buffer_size = 256; return builder; } void StringBuilder_destroy(struct StringBuilder* builder) { free(builder->buffer); free(builder); } void StringBuilder_ensure_buffer(struct StringBuilder* builder, int size_to_add) { if (builder->buffer_size-builder->buffer_pos>size_to_add) { return; } int new_size = builder->buffer_pos+size_to_add; builder->buffer = (char*) realloc(builder->buffer, new_size); builder->buffer_size = new_size; } void StringBuilder_append(struct StringBuilder* builder, const char* string) { if (string!=NULL) { StringBuilder_append_n(builder, string, (int) strlen(string)); } } void StringBuilder_append_n(struct StringBuilder* builder, const char* string, const int len) { if (len>0) { StringBuilder_ensure_buffer(builder, len+1); memcpy(builder->buffer+builder->buffer_pos, string, len); builder->buffer_pos += len; builder->buffer[builder->buffer_pos] = 0; } } void StringBuilder_append_f(struct StringBuilder* builder, const char* format, ...) { if (format==NULL) { return; } int written; int size = 10240*sizeof(char); char* message_fmt = (char*) malloc(size); message_fmt[0] = 0; while (1) { va_list args; va_start(args, format); written = vsnprintf(message_fmt, size, format, args); va_end(args); if (written!=-1 && written<size) { break; } // For some old implementations, vsnprintf returns -1 if the target buffer size is less than // the generated string. if (written==-1) { written = size*10; } message_fmt = (char*) realloc(message_fmt, written+1); size = written+1; } StringBuilder_append_n(builder, message_fmt, written); free(message_fmt); } char* StringBuilder_get_string(struct StringBuilder* builder) { return builder->buffer; } int StringBuilder_get_length(struct StringBuilder* builder) { return builder->buffer_pos; } <|start_filename|>src/seabolt/src/bolt/bolt-private.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_BOLT_PRIVATE_H #define SEABOLT_BOLT_PRIVATE_H #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #if USE_POSIXSOCK #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <fcntl.h> #include <netdb.h> #include <signal.h> #endif // USE_POSIXSOCK #if USE_WINSOCK #include <winsock2.h> #include <windows.h> #include <Ws2tcpip.h> #endif // USE_WINSOCK #include "error.h" #define SIZE_OF_C_STRING(str) (sizeof(char)*(strlen(str)+1)) #define UNUSED(x) (void)(x) #endif //SEABOLT_BOLT_PRIVATE_H <|start_filename|>src/seabolt/src/bolt/status.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_STATUS_H #define SEABOLT_STATUS_H #include "bolt-public.h" /** * The type that identifies the state of the connection */ typedef int32_t BoltConnectionState; /** * Not connected */ #define BOLT_CONNECTION_STATE_DISCONNECTED 0 /** * Connected but not authenticated */ #define BOLT_CONNECTION_STATE_CONNECTED 1 /** * Connected and authenticated */ #define BOLT_CONNECTION_STATE_READY 2 /** * Recoverable failure */ #define BOLT_CONNECTION_STATE_FAILED 3 /** * Unrecoverable failure */ #define BOLT_CONNECTION_STATE_DEFUNCT 4 /** * The type that holds status information about connection, including details about errors. */ typedef struct BoltStatus BoltStatus; /** * Creates a new instance of \ref BoltStatus. * * @return the pointer to the newly allocated \ref BoltStatus instance. */ SEABOLT_EXPORT BoltStatus* BoltStatus_create(); /** * Destroys the passed \ref BoltStatus instance. * * @param status the instance to be destroyed. */ SEABOLT_EXPORT void BoltStatus_destroy(BoltStatus* status); /** * Returns the current \ref BoltConnectionState "state". * * @param status the instance to be destroyed. * @returns the current \ref BoltConnectionState "state". */ SEABOLT_EXPORT BoltConnectionState BoltStatus_get_state(BoltStatus* status); /** * Returns the current error code. * * A string representation of the returned error code can be retrieved by calling * \ref BoltError_get_string. * * @param status the instance to be destroyed. * @returns the current error code. */ SEABOLT_EXPORT int32_t BoltStatus_get_error(BoltStatus* status); /** * Returns more information (if set by the internal code) about the error stored, like * which internal call generated the error and the location of it. * * @param status the instance to be destroyed. * @returns the current error context (may be NULL or empty string). */ SEABOLT_EXPORT const char* BoltStatus_get_error_context(BoltStatus* status); #endif //SEABOLT_STATUS_H <|start_filename|>src/seabolt/tests/test-chunking-v1.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <cmath> #include "integration.hpp" #include "catch.hpp" using Catch::Matchers::Equals; #define REQUIRE_BOLT_NULL(value) { REQUIRE(BoltValue_type(value) == BOLT_NULL); } #define REQUIRE_BOLT_BOOLEAN(value, x) { REQUIRE(BoltValue_type(value) == BOLT_BOOLEAN); REQUIRE(BoltBoolean_get(value) == (x)); } #define REQUIRE_BOLT_INTEGER(value, x) { REQUIRE(BoltValue_type(value) == BOLT_INTEGER); REQUIRE(BoltInteger_get(value) == (x)); } #define REQUIRE_BOLT_FLOAT(value, x) { REQUIRE(BoltValue_type(value) == BOLT_FLOAT); REQUIRE( BoltFloat_get(value) == (x)); } #define REQUIRE_BOLT_STRING(value, x, size_) { REQUIRE(BoltValue_type(value) == BOLT_STRING); REQUIRE(strncmp(BoltString_get(value), x, size_) == 0); REQUIRE(BoltValue_size(value) == (int32_t)(size_)); } #define REQUIRE_BOLT_DICTIONARY(value, size_) { REQUIRE(BoltValue_type(value) == BOLT_DICTIONARY); REQUIRE((value)->size == (int32_t)(size_)); } #define REQUIRE_BOLT_LIST(value, size_) { REQUIRE(BoltValue_type(value) == BOLT_LIST); REQUIRE((value)->size == (int32_t)(size_)); } #define REQUIRE_BOLT_BYTES(value, size_) { REQUIRE(BoltValue_type(value) == BOLT_BYTES); REQUIRE((value)->size == (int32_t)(size_)); } #define REQUIRE_BOLT_STRUCTURE(value, code, size_) { REQUIRE(BoltValue_type(value) == BOLT_STRUCTURE); REQUIRE(BoltStructure_code(value) == (code)); REQUIRE(BoltValue_size(value) == (int32_t)(size_)); } #define REQUIRE_BOLT_SUCCESS(connection) { REQUIRE(BoltConnection_summary_success(connection) == 1); } #define RUN_PULL_SEND(connection, result)\ BoltConnection_load_run_request(connection);\ BoltConnection_load_pull_request(connection, -1);\ BoltConnection_send(connection);\ BoltRequest (result) = BoltConnection_last_request(connection); SCENARIO("Test chunking", "[integration][ipv6][secure]") { GIVEN("an open and initialised connection") { struct BoltConnection* connection = bolt_open_init_default(); WHEN("Cypher with parameter of small size") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); int param_size = 2; char* param = (char*) calloc(param_size, sizeof(char)); for (int i = 1; i<param_size; i++) { param[i-1] = 'A'+(rand()%25); } BoltValue_format_as_String(x, param, (int32_t) strlen(param)); RUN_PULL_SEND(connection, result); THEN("It should return passed parameter") { while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_STRING(value, param, strlen(param)); } REQUIRE_BOLT_SUCCESS(connection); } } WHEN("Cypher with parameter of medium size") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); int param_size = 32769; char* param = (char*) calloc(param_size, sizeof(char)); for (int i = 1; i<param_size; i++) { param[i-1] = 'A'+(rand()%25); } BoltValue_format_as_String(x, param, (int32_t) strlen(param)); RUN_PULL_SEND(connection, result); THEN("It should return passed parameter") { while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_STRING(value, param, strlen(param)); } REQUIRE_BOLT_SUCCESS(connection); } } WHEN("Cypher with parameter of boundary size") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); int param_size = 65536; char* param = (char*) calloc(param_size, sizeof(char)); for (int i = 1; i<param_size; i++) { param[i-1] = 'A'+(rand()%25); } BoltValue_format_as_String(x, param, (int32_t) strlen(param)); RUN_PULL_SEND(connection, result); THEN("It should return passed parameter") { while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_STRING(value, param, strlen(param)); } REQUIRE_BOLT_SUCCESS(connection); } } WHEN("Cypher with parameter of large size") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); int param_size = 65535*2+1; char* param = (char*) calloc(param_size, sizeof(char)); for (int i = 1; i<param_size; i++) { param[i-1] = 'A'+(rand()%25); } BoltValue_format_as_String(x, param, (int32_t) strlen(param)); RUN_PULL_SEND(connection, result); THEN("It should return passed parameter") { while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_STRING(value, param, strlen(param)); } REQUIRE_BOLT_SUCCESS(connection); } } WHEN("Cypher with parameter of very large size") { const char* cypher = "RETURN $x"; BoltConnection_set_run_cypher(connection, cypher, strlen(cypher), 1); BoltValue* x = BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1); int param_size = 65535*10+1; char* param = (char*) calloc(param_size, sizeof(char)); for (int i = 1; i<param_size; i++) { param[i-1] = 'A'+(rand()%25); } BoltValue_format_as_String(x, param, (int32_t) strlen(param)); RUN_PULL_SEND(connection, result); THEN("It should return passed parameter") { while (BoltConnection_fetch(connection, result)) { const struct BoltValue* field_values = BoltConnection_field_values(connection); struct BoltValue* value = BoltList_value(field_values, 0); REQUIRE_BOLT_STRING(value, param, strlen(param)); } REQUIRE_BOLT_SUCCESS(connection); } } bolt_close_and_destroy_b(connection); } } <|start_filename|>src/seabolt/src/bolt/log.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "log-private.h" #include "mem.h" #include "string-builder.h" #include "values-private.h" struct BoltLog* BoltLog_create(void* state) { struct BoltLog* log = (struct BoltLog*) BoltMem_allocate(sizeof(struct BoltLog)); log->state = state; log->debug_logger = NULL; log->info_logger = NULL; log->warning_logger = NULL; log->error_logger = NULL; log->debug_enabled = 0; log->info_enabled = 0; log->warning_enabled = 0; log->error_enabled = 0; return log; } BoltLog* BoltLog_clone(BoltLog* log) { if (log==NULL) { return NULL; } BoltLog* clone = BoltLog_create(log->state); clone->debug_logger = log->debug_logger; clone->debug_enabled = log->debug_enabled; clone->info_logger = log->info_logger; clone->info_enabled = log->info_enabled; clone->warning_logger = log->warning_logger; clone->warning_enabled = log->warning_enabled; clone->error_logger = log->error_logger; clone->error_enabled = log->error_enabled; return clone; } void BoltLog_destroy(struct BoltLog* log) { BoltMem_deallocate(log, sizeof(struct BoltLog)); } void BoltLog_set_error_func(BoltLog* log, log_func func) { log->error_enabled = func!=NULL; log->error_logger = func; } void BoltLog_set_warning_func(BoltLog* log, log_func func) { log->warning_enabled = func!=NULL; log->warning_logger = func; } void BoltLog_set_info_func(BoltLog* log, log_func func) { log->info_enabled = func!=NULL; log->info_logger = func; } void BoltLog_set_debug_func(BoltLog* log, log_func func) { log->debug_enabled = func!=NULL; log->debug_logger = func; } void _perform_log_call(log_func func, void* state, const char* format, va_list args) { uint64_t size = 512*sizeof(char); char* message_fmt = (char*) BoltMem_allocate(size); while (1) { va_list args_copy; va_copy(args_copy, args); uint64_t written = (uint64_t) vsnprintf(message_fmt, size, format, args_copy); va_end(args_copy); if (written<size) { break; } message_fmt = (char*) BoltMem_reallocate(message_fmt, size, written+1); size = written+1; } func(state, message_fmt); BoltMem_deallocate(message_fmt, size); } void BoltLog_error(const struct BoltLog* log, const char* format, ...) { if (log!=NULL && log->error_enabled) { va_list args; va_start(args, format); _perform_log_call(log->error_logger, log->state, format, args); va_end(args); } } void BoltLog_warning(const struct BoltLog* log, const char* format, ...) { if (log!=NULL && log->warning_enabled) { va_list args; va_start(args, format); _perform_log_call(log->warning_logger, log->state, format, args); va_end(args); } } void BoltLog_info(const struct BoltLog* log, const char* format, ...) { if (log!=NULL && log->info_enabled) { va_list args; va_start(args, format); _perform_log_call(log->info_logger, log->state, format, args); va_end(args); } } void BoltLog_debug(const struct BoltLog* log, const char* format, ...) { if (log!=NULL && log->debug_enabled) { va_list args; va_start(args, format); _perform_log_call(log->debug_logger, log->state, format, args); va_end(args); } } void BoltLog_value(const struct BoltLog* log, const char* format, const char* id, struct BoltValue* value, name_resolver_func struct_name_resolver) { if (log!=NULL && log->debug_enabled) { struct StringBuilder* builder = StringBuilder_create(); BoltValue_write(builder, value, struct_name_resolver); BoltLog_debug(log, format, id, StringBuilder_get_string(builder)); StringBuilder_destroy(builder); } } void BoltLog_message(const struct BoltLog* log, const char* id, const char* peer, BoltRequest request_id, int16_t code, struct BoltValue* fields, name_resolver_func struct_name_resolver, name_resolver_func message_name_resolver) { if (log!=NULL && log->debug_enabled) { const char* message_name = "?"; if (message_name_resolver!=NULL) { message_name = message_name_resolver(code); } struct StringBuilder* builder = StringBuilder_create(); BoltValue_write(builder, fields, struct_name_resolver); BoltLog_debug(log, "[%s]: %s[%" PRIu64 "] %s %s", id, peer, request_id, message_name, StringBuilder_get_string(builder)); StringBuilder_destroy(builder); } } <|start_filename|>src/seabolt/src/bolt/address.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_ADDRESSING_H #define SEABOLT_ADDRESSING_H #include "bolt-public.h" /** * The type that represents a network endpoint as a host name and a port number. * * This can carry both the original host name and port details, as supplied by the application, * as well as one or more resolved IP addresses and port number. */ typedef struct BoltAddress BoltAddress; /** * Creates a new instance of \ref BoltAddress for a given host and port. * * No name resolution is carried out on creation so this simply initialises * the original host and port details and zeroes out the remainder * of the structure. * * @param host host name, e.g. "www.example.com" * @param port port name or numeric string, e.g. "7687" or "http" * @returns the pointer to the newly allocated \ref BoltAddress instance. */ SEABOLT_EXPORT BoltAddress* BoltAddress_create(const char* host, const char* port); /** * Returns the host name. * * @param address the instance to be queried. * @returns the host name as specified with \ref BoltAddress_create. */ SEABOLT_EXPORT const char* BoltAddress_host(BoltAddress* address); /** * Returns the port. * * @param address the instance to be queried. * @returns the port as specified with \ref BoltAddress_create. */ SEABOLT_EXPORT const char* BoltAddress_port(BoltAddress* address); /** * Destroys the passed \ref BoltAddress instance. * * @param address the instance to be destroyed. */ SEABOLT_EXPORT void BoltAddress_destroy(BoltAddress* address); #endif // SEABOLT_ADDRESSING_H <|start_filename|>src/seabolt/src/bolt/time-win32.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "time.h" #define MS_PER_SEC 1000ULL // MS = milliseconds #define US_PER_MS 1000ULL // US = microseconds #define HNS_PER_US 10ULL // HNS = hundred-nanoseconds (e.g., 1 hns = 100 ns) #define NS_PER_US 1000ULL #define HNS_PER_SEC (MS_PER_SEC * US_PER_MS * HNS_PER_US) #define NS_PER_HNS (100ULL) // NS = nanoseconds #define NS_PER_SEC (MS_PER_SEC * US_PER_MS * NS_PER_US) int BoltTime_get_time(struct timespec* tp) { static LARGE_INTEGER ticksPerSec; LARGE_INTEGER ticks; double seconds; if (!ticksPerSec.QuadPart) { QueryPerformanceFrequency(&ticksPerSec); if (!ticksPerSec.QuadPart) { // not supported return -1; } } QueryPerformanceCounter(&ticks); seconds = (double) ticks.QuadPart/(double) ticksPerSec.QuadPart; tp->tv_sec = (time_t) seconds; tp->tv_nsec = (long) ((ULONGLONG) (seconds*NS_PER_SEC)%NS_PER_SEC); return 0; } <|start_filename|>src/seabolt/src/bolt/v1.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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. */ /** * @file */ #ifndef SEABOLT_PROTOCOL_V1 #define SEABOLT_PROTOCOL_V1 #include <stdint.h> #include "connection.h" #include "protocol.h" #define BOLT_V1_INIT 0x01 #define BOLT_V1_ACK_FAILURE 0x0E #define BOLT_V1_RESET 0x0F #define BOLT_V1_RUN 0x10 #define BOLT_V1_DISCARD_ALL 0x2F #define BOLT_V1_PULL_ALL 0x3F #define BOLT_V1_NODE 'N' #define BOLT_V1_RELATIONSHIP 'R' #define BOLT_V1_UNBOUND_RELATIONSHIP 'r' #define BOLT_V1_PATH 'P' #define BOLT_V1_SUCCESS 0x70 #define BOLT_V1_RECORD 0x71 #define BOLT_V1_IGNORED 0x7E #define BOLT_V1_FAILURE 0x7F struct BoltProtocolV1State { // These buffers exclude chunk headers. struct BoltBuffer* tx_buffer; struct BoltBuffer* rx_buffer; /// The product name and version of the remote server char* server; /// A BoltValue containing field names for the active result struct BoltValue* result_field_names; /// A BoltValue containing metadata fields struct BoltValue* result_metadata; /// A BoltValue containing error code and message struct BoltValue* failure_data; /// The last bookmark received from the server char* last_bookmark; BoltRequest next_request_id; BoltRequest response_counter; unsigned long long record_counter; struct BoltMessage* run_request; struct BoltMessage* begin_request; struct BoltMessage* commit_request; struct BoltMessage* rollback_request; struct BoltMessage* discard_request; struct BoltMessage* pull_request; struct BoltMessage* reset_request; /// Holder for fetched data and metadata int16_t data_type; struct BoltValue* data; }; int BoltProtocolV1_check_readable_struct_signature(int16_t signature); int BoltProtocolV1_check_writable_struct_signature(int16_t signature); const char* BoltProtocolV1_structure_name(int16_t code); struct BoltProtocolV1State* BoltProtocolV1_state(struct BoltConnection* connection); struct BoltProtocol* BoltProtocolV1_create_protocol(); void BoltProtocolV1_destroy_protocol(struct BoltProtocol* protocol); #endif // SEABOLT_PROTOCOL_V1 <|start_filename|>src/seabolt/tests/test-v3.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 <string> #include <utils/test-context.h> #include "integration.hpp" #include "catch.hpp" using Catch::Matchers::Equals; #define CONNECTION_ID_KEY "connection_id" #define CONNECTION_ID_KEY_SIZE 13 TEST_CASE("Extract metadata", "[unit]") { GIVEN("an open and initialised connection") { TestContext* test_ctx = new TestContext(); struct BoltConnection* connection = bolt_open_init_mocked(3, test_ctx->log()); WHEN("new connection_id would not overrun buffer") { BoltValue* metadata = BoltValue_create(); BoltValue_format_as_Dictionary(metadata, 1); BoltDictionary_set_key(metadata, 0, CONNECTION_ID_KEY, CONNECTION_ID_KEY_SIZE); std::string old_connection_id = BoltConnection_id(connection); std::string value = "foo"; BoltValue_format_as_String( BoltDictionary_value(metadata, 0), value.c_str(), (int32_t) value.length()); BoltProtocolV3_extract_metadata(connection, metadata); std::string connection_id = BoltConnection_id(connection); REQUIRE(old_connection_id.length()>0); THEN("it should not be concatenated to a blank with comma") { REQUIRE_THAT(connection_id, Equals( old_connection_id+", "+value )); } BoltValue_destroy(metadata); } WHEN("new connection_id would overrun buffer") { BoltValue* metadata = BoltValue_create(); BoltValue_format_as_Dictionary(metadata, 1); BoltDictionary_set_key(metadata, 0, CONNECTION_ID_KEY, CONNECTION_ID_KEY_SIZE); THEN("new connection_id should be ignored and the original connection_id should persist") { std::string old_connection_id = BoltConnection_id(connection); std::string value = "0123456789""0123456789""0123456789""0123456789""0123456789" "0123456789""0123456789""0123456789""0123456789""0123456789" "0123456789""0123456789""0123456789""0123456789""0123456789" "0123456789""0123456789""0123456789""0123456789""0123456789"; BoltValue_format_as_String(BoltDictionary_value(metadata, 0), value.c_str(), (int32_t) value.length()); BoltProtocolV3_extract_metadata(connection, metadata); std::string connection_id = BoltConnection_id(connection); REQUIRE(connection_id.find(value)==std::string::npos); REQUIRE(connection_id==old_connection_id); } BoltValue_destroy(metadata); } BoltConnection_close(connection); BoltConnection_destroy(connection); } } TEST_CASE("Pass access mode", "[unit]") { GIVEN("an open and initialised connection") { TestContext* test_ctx = new TestContext(); struct BoltConnection* connection = bolt_open_init_mocked(3, test_ctx->log()); BoltValue* tx_metadata = BoltValue_create(); BoltValue_format_as_Dictionary(tx_metadata, 2); BoltDictionary_set_key(tx_metadata, 0, "m1", 2); BoltValue_format_as_Integer(BoltDictionary_value(tx_metadata, 0), 10); BoltDictionary_set_key(tx_metadata, 1, "m2", 2); BoltValue_format_as_Boolean(BoltDictionary_value(tx_metadata, 1), 1); BoltValue* bookmarks = BoltValue_create(); BoltValue_format_as_List(bookmarks, 3); BoltValue_format_as_String(BoltList_value(bookmarks, 0), "bookmark-1", 10); BoltValue_format_as_String(BoltList_value(bookmarks, 1), "bookmark-2", 10); BoltValue_format_as_String(BoltList_value(bookmarks, 2), "bookmark-3", 10); WHEN("connection access mode is READ") { connection->access_mode = BOLT_ACCESS_MODE_READ; AND_WHEN("a BEGIN message is loaded") { BoltConnection_clear_begin(connection); BoltConnection_set_begin_tx_timeout(connection, 1000); BoltConnection_set_begin_tx_metadata(connection, tx_metadata); BoltConnection_set_begin_bookmarks(connection, bookmarks); BoltConnection_load_begin_request(connection); THEN("mode=r should be present in the statement metadata") { REQUIRE_THAT(*test_ctx, ContainsLog( "DEBUG: [id-0]: C[0] BEGIN [{tx_timeout: 1000, tx_metadata: {m1: 10, m2: true}, " "bookmarks: [bookmark-1, bookmark-2, bookmark-3], mode: r}]")); } } AND_WHEN("a RUN message is loaded") { BoltConnection_clear_run(connection); BoltConnection_set_run_cypher(connection, "RETURN $x", 9, 1); BoltValue_format_as_Integer(BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1), 5); BoltConnection_set_run_tx_timeout(connection, 5000); BoltConnection_set_run_tx_metadata(connection, tx_metadata); BoltConnection_set_run_bookmarks(connection, bookmarks); BoltConnection_load_run_request(connection); THEN("mode=r should be present in the statement metadata") { REQUIRE_THAT(*test_ctx, ContainsLog( "DEBUG: [id-0]: C[0] RUN [RETURN $x, {x: 5}, {tx_timeout: 5000, tx_metadata: {m1: 10, m2: true}, " "bookmarks: [bookmark-1, bookmark-2, bookmark-3], mode: r}]")); } } } WHEN("connection access mode is WRITE") { connection->access_mode = BOLT_ACCESS_MODE_WRITE; AND_WHEN("a BEGIN message is loaded") { BoltConnection_clear_begin(connection); BoltConnection_set_begin_tx_timeout(connection, 1000); BoltConnection_set_begin_tx_metadata(connection, tx_metadata); BoltConnection_set_begin_bookmarks(connection, bookmarks); BoltConnection_load_begin_request(connection); THEN("no access mode should be present in the statement metadata") { REQUIRE_THAT(*test_ctx, ContainsLog( "DEBUG: [id-0]: C[0] BEGIN [{tx_timeout: 1000, tx_metadata: {m1: 10, m2: true}, " "bookmarks: [bookmark-1, bookmark-2, bookmark-3]}]")); } } AND_WHEN("a RUN message is loaded") { BoltConnection_clear_run(connection); BoltConnection_set_run_cypher(connection, "RETURN $x", 9, 1); BoltValue_format_as_Integer(BoltConnection_set_run_cypher_parameter(connection, 0, "x", 1), 5); BoltConnection_set_run_tx_timeout(connection, 5000); BoltConnection_set_run_tx_metadata(connection, tx_metadata); BoltConnection_set_run_bookmarks(connection, bookmarks); BoltConnection_load_run_request(connection); THEN("no access mode should be present in the statement metadata") { REQUIRE_THAT(*test_ctx, ContainsLog( "DEBUG: [id-0]: C[0] RUN [RETURN $x, {x: 5}, {tx_timeout: 5000, tx_metadata: {m1: 10, m2: true}, " "bookmarks: [bookmark-1, bookmark-2, bookmark-3]}]")); } } } BoltValue_destroy(tx_metadata); BoltValue_destroy(bookmarks); BoltConnection_close(connection); BoltConnection_destroy(connection); } } <|start_filename|>src/seabolt/src/bolt/v1.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "connection-private.h" #include "log-private.h" #include "mem.h" #include "protocol.h" #include "v1.h" #include "values-private.h" #define BOOKMARKS_KEY "bookmarks" #define BOOKMARKS_KEY_SIZE 9 #define BOOKMARK_KEY "bookmark" #define BOOKMARK_KEY_SIZE 8 #define FIELDS_KEY "fields" #define FIELDS_KEY_SIZE 6 #define SERVER_KEY "server" #define SERVER_KEY_SIZE 6 #define FAILURE_CODE_KEY "code" #define FAILURE_CODE_KEY_SIZE 4 #define FAILURE_MESSAGE_KEY "message" #define FAILURE_MESSAGE_KEY_SIZE 7 #define INITIAL_TX_BUFFER_SIZE 8192 #define INITIAL_RX_BUFFER_SIZE 8192 #define MAX_BOOKMARK_SIZE 40 #define MAX_SERVER_SIZE 200 #define MAX_LOGGED_RECORDS 3 #define char_to_uint16be(array) ((uint8_t)(header[0]) << 8) | (uint8_t)(header[1]); #define TRY(code) { int status_try = (code); if (status_try != BOLT_SUCCESS) { return status_try; } } int BoltProtocolV1_compile_INIT(struct BoltMessage* message, const char* user_agent, const struct BoltValue* auth_token, int mask_secure_fields) { struct BoltValue* user_agent_field = BoltList_value(message->fields, 0); struct BoltValue* auth_token_field = BoltList_value(message->fields, 1); BoltValue_format_as_String(user_agent_field, user_agent, (int32_t) (strlen(user_agent))); BoltValue_copy(auth_token_field, auth_token); if (mask_secure_fields) { struct BoltValue* secure_value = BoltDictionary_value_by_key(auth_token_field, "credentials", 11); if (secure_value!=NULL) { BoltValue_format_as_String(secure_value, "********", 8); } } return BOLT_SUCCESS; } struct BoltMessage* create_run_message(const char* statement, size_t statement_size, int32_t n_parameters) { struct BoltMessage* message = BoltMessage_create(BOLT_V1_RUN, 2); BoltValue_format_as_String(BoltMessage_param(message, 0), statement, (int32_t) statement_size); BoltValue_format_as_Dictionary(BoltMessage_param(message, 1), n_parameters); return message; } int BoltProtocolV1_check_readable_struct_signature(int16_t signature) { switch (signature) { case BOLT_V1_SUCCESS: case BOLT_V1_FAILURE: case BOLT_V1_IGNORED: case BOLT_V1_RECORD: case BOLT_V1_NODE: case BOLT_V1_RELATIONSHIP: case BOLT_V1_UNBOUND_RELATIONSHIP: case BOLT_V1_PATH: return 1; } return 0; } int BoltProtocolV1_check_writable_struct_signature(int16_t signature) { switch (signature) { case BOLT_V1_INIT: case BOLT_V1_ACK_FAILURE: case BOLT_V1_RESET: case BOLT_V1_RUN: case BOLT_V1_DISCARD_ALL: case BOLT_V1_PULL_ALL: return 1; } return 0; } const char* BoltProtocolV1_structure_name(int16_t code) { switch (code) { case BOLT_V1_NODE: return "Node"; case BOLT_V1_RELATIONSHIP: return "Relationship"; case BOLT_V1_UNBOUND_RELATIONSHIP: return "UnboundRelationship"; case BOLT_V1_PATH: return "Path"; default: return "?"; } } const char* BoltProtocolV1_message_name(int16_t code) { switch (code) { case BOLT_V1_INIT: return "INIT"; case BOLT_V1_ACK_FAILURE: return "ACK_FAILURE"; case BOLT_V1_RESET: return "RESET"; case BOLT_V1_RUN: return "RUN"; case BOLT_V1_DISCARD_ALL: return "DISCARD_ALL"; case BOLT_V1_PULL_ALL: return "PULL_ALL"; case BOLT_V1_SUCCESS: return "SUCCESS"; case BOLT_V1_RECORD: return "RECORD"; case BOLT_V1_IGNORED: return "IGNORED"; case BOLT_V1_FAILURE: return "FAILURE"; default: return "?"; } } struct BoltProtocolV1State* BoltProtocolV1_state(struct BoltConnection* connection) { return (struct BoltProtocolV1State*) (connection->protocol->proto_state); } void ensure_failure_data(struct BoltProtocolV1State* state) { if (state->failure_data==NULL) { state->failure_data = BoltValue_create(); BoltValue_format_as_Dictionary(state->failure_data, 2); BoltDictionary_set_key(state->failure_data, 0, "code", (int32_t) strlen("code")); BoltDictionary_set_key(state->failure_data, 1, "message", (int32_t) strlen("message")); } } void clear_failure_data(struct BoltProtocolV1State* state) { if (state->failure_data!=NULL) { BoltValue_destroy(state->failure_data); state->failure_data = NULL; } } int BoltProtocolV1_load_message(struct BoltConnection* connection, struct BoltMessage* message, int quiet) { if (!quiet) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); BoltLog_message(connection->log, BoltConnection_id(connection), "C", state->next_request_id, message->code, message->fields, connection->protocol->structure_name, connection->protocol->message_name); } struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); int prev_cursor = state->tx_buffer->cursor; int prev_extent = state->tx_buffer->extent; int status = write_message(message, connection->protocol->check_writable_struct, state->tx_buffer, connection->log); if (status==BOLT_SUCCESS) { push_to_transmission(state->tx_buffer, connection->tx_buffer); state->next_request_id += 1; } else { // Reset buffer to its previous state state->tx_buffer->cursor = prev_cursor; state->tx_buffer->extent = prev_extent; } return status; } int BoltProtocolV1_init(struct BoltConnection* connection, const char* user_agent, const struct BoltValue* auth_token) { struct BoltMessage* init = BoltMessage_create(BOLT_V1_INIT, 2); struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_compile_INIT(init, user_agent, auth_token, 1)); BoltLog_message(connection->log, BoltConnection_id(connection), "C", state->next_request_id, init->code, init->fields, connection->protocol->structure_name, connection->protocol->message_name); TRY(BoltProtocolV1_compile_INIT(init, user_agent, auth_token, 0)); TRY(BoltProtocolV1_load_message(connection, init, 1)); BoltRequest init_request = BoltConnection_last_request(connection); BoltMessage_destroy(init); TRY(BoltConnection_send(connection)); TRY(BoltConnection_fetch_summary(connection, init_request)); return state->data_type; } int BoltProtocolV1_load_discard_request(struct BoltConnection* connection, int32_t n) { if (n>=0) { return BOLT_PROTOCOL_VIOLATION; } else { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->discard_request, 0)); return BOLT_SUCCESS; } } int BoltProtocolV1_load_pull_request(struct BoltConnection* connection, int32_t n) { if (n>=0) { return BOLT_PROTOCOL_VIOLATION; } else { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->pull_request, 0)); return BOLT_SUCCESS; } } int BoltProtocolV1_load_reset_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->reset_request, 0)); clear_failure_data(state); return BOLT_SUCCESS; } int BoltProtocolV1_clear_load_run_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); BoltValue_format_as_String(BoltMessage_param(state->run_request, 0), "", 0); BoltValue_format_as_Dictionary(BoltMessage_param(state->run_request, 1), 0); return BOLT_SUCCESS; } int BoltProtocolV1_set_run_cypher(struct BoltConnection* connection, const char* cypher, const size_t cypher_size, int32_t n_parameter) { if (cypher_size<=INT32_MAX) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); struct BoltValue* statement = BoltMessage_param(state->run_request, 0); struct BoltValue* params = BoltMessage_param(state->run_request, 1); BoltValue_format_as_String(statement, cypher, (int32_t) (cypher_size)); BoltValue_format_as_Dictionary(params, n_parameter); return BOLT_SUCCESS; } return BOLT_PROTOCOL_VIOLATION; } struct BoltValue* BoltProtocolV1_set_run_cypher_parameter(struct BoltConnection* connection, int32_t index, const char* name, size_t name_size) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); struct BoltValue* params = BoltMessage_param(state->run_request, 1); BoltDictionary_set_key(params, index, name, (int32_t) name_size); return BoltDictionary_value(params, index); } int BoltProtocolV1_load_run_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->run_request, 0)); return BOLT_SUCCESS; } int BoltProtocolV1_clear_load_begin_tx_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); struct BoltValue* params = BoltMessage_param(state->begin_request, 1); BoltValue_format_as_Dictionary(params, 0); return BOLT_SUCCESS; } int BoltProtocolV1_set_begin_tx_bookmark(struct BoltConnection* connection, struct BoltValue* bookmark_list) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); struct BoltValue* params = BoltMessage_param(state->begin_request, 1); if (bookmark_list==NULL) { BoltValue_format_as_Dictionary(params, 0); return BOLT_SUCCESS; } if (BoltValue_type(bookmark_list)!=BOLT_LIST) { return BOLT_PROTOCOL_VIOLATION; } for (int32_t i = 0; i<bookmark_list->size; i++) { struct BoltValue* element = BoltList_value(bookmark_list, i); if (BoltValue_type(element)!=BOLT_STRING) { return BOLT_PROTOCOL_VIOLATION; } if (element->size>INT32_MAX) { return BOLT_PROTOCOL_VIOLATION; } } struct BoltValue* bookmarks; if (params->size==0) { BoltValue_format_as_Dictionary(params, 1); if (BoltDictionary_set_key(params, 0, BOOKMARKS_KEY, BOOKMARKS_KEY_SIZE)) { return BOLT_PROTOCOL_VIOLATION; } bookmarks = BoltDictionary_value(params, 0); } else { bookmarks = BoltDictionary_value(params, 0); } BoltValue_copy(bookmarks, bookmark_list); return BOLT_SUCCESS; } int BoltProtocolV1_load_begin_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->begin_request, 0)); TRY(BoltProtocolV1_load_message(connection, state->discard_request, 0)); return BOLT_SUCCESS; } int BoltProtocolV1_load_commit_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->commit_request, 0)); TRY(BoltProtocolV1_load_message(connection, state->discard_request, 0)); return BOLT_SUCCESS; } int BoltProtocolV1_load_rollback_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); TRY(BoltProtocolV1_load_message(connection, state->rollback_request, 0)); TRY(BoltProtocolV1_load_message(connection, state->discard_request, 0)); return BOLT_SUCCESS; } struct BoltValue* BoltProtocolV1_result_field_names(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); switch (BoltValue_type(state->result_field_names)) { case BOLT_LIST: return state->result_field_names; default: return NULL; } } struct BoltValue* BoltProtocolV1_result_field_values(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); switch (state->data_type) { case BOLT_V1_RECORD: switch (BoltValue_type(state->data)) { case BOLT_LIST: { struct BoltValue* values = BoltList_value(state->data, 0); return values; } default: return NULL; } default: return NULL; } } struct BoltValue* BoltProtocolV1_result_metadata(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); switch (BoltValue_type(state->result_metadata)) { case BOLT_DICTIONARY: return state->result_metadata; default: return NULL; } } struct BoltValue* BoltProtocolV1_failure(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->failure_data; } char* BoltProtocolV1_last_bookmark(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->last_bookmark; } char* BoltProtocolV1_server(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->server; } BoltRequest BoltProtocolV1_last_request(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->next_request_id-1; } int BoltProtocolV1_is_success_summary(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->data_type==BOLT_V1_SUCCESS; } int BoltProtocolV1_is_failure_summary(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->data_type==BOLT_V1_FAILURE; } int BoltProtocolV1_is_ignored_summary(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->data_type==BOLT_V1_IGNORED; } int16_t BoltProtocolV1_last_data_type(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); return state->data_type; } struct BoltProtocolV1State* BoltProtocolV1_create_state() { struct BoltProtocolV1State* state = BoltMem_allocate(sizeof(struct BoltProtocolV1State)); state->tx_buffer = BoltBuffer_create(INITIAL_TX_BUFFER_SIZE); state->rx_buffer = BoltBuffer_create(INITIAL_RX_BUFFER_SIZE); state->server = BoltMem_allocate(MAX_SERVER_SIZE); memset(state->server, 0, MAX_SERVER_SIZE); state->result_field_names = BoltValue_create(); state->result_metadata = BoltValue_create(); BoltValue_format_as_Dictionary(state->result_metadata, 0); state->failure_data = NULL; state->last_bookmark = BoltMem_allocate(MAX_BOOKMARK_SIZE); memset(state->last_bookmark, 0, MAX_BOOKMARK_SIZE); state->next_request_id = 0; state->response_counter = 0; state->record_counter = 0; state->run_request = create_run_message("", 0, 0); state->begin_request = create_run_message("BEGIN", 5, 0); state->commit_request = create_run_message("COMMIT", 6, 0); state->rollback_request = create_run_message("ROLLBACK", 8, 0); state->discard_request = BoltMessage_create(BOLT_V1_DISCARD_ALL, 0); state->pull_request = BoltMessage_create(BOLT_V1_PULL_ALL, 0); state->reset_request = BoltMessage_create(BOLT_V1_RESET, 0); state->data_type = BOLT_V1_RECORD; state->data = BoltValue_create(); return state; } void BoltProtocolV1_destroy_state(struct BoltProtocolV1State* state) { if (state==NULL) return; BoltBuffer_destroy(state->tx_buffer); BoltBuffer_destroy(state->rx_buffer); BoltMessage_destroy(state->run_request); BoltMessage_destroy(state->begin_request); BoltMessage_destroy(state->commit_request); BoltMessage_destroy(state->rollback_request); BoltMessage_destroy(state->discard_request); BoltMessage_destroy(state->pull_request); BoltMessage_destroy(state->reset_request); BoltMem_deallocate(state->server, MAX_SERVER_SIZE); if (state->failure_data!=NULL) { BoltValue_destroy(state->failure_data); } BoltValue_destroy(state->result_field_names); BoltValue_destroy(state->result_metadata); BoltMem_deallocate(state->last_bookmark, MAX_BOOKMARK_SIZE); BoltValue_destroy(state->data); BoltMem_deallocate(state, sizeof(struct BoltProtocolV1State)); } int BoltProtocolV1_unload(struct BoltConnection* connection) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); if (BoltBuffer_unloadable(state->rx_buffer)==0) { return 0; } uint8_t marker; TRY(BoltBuffer_unload_u8(state->rx_buffer, &marker)); if (marker_type(marker)!=PACKSTREAM_STRUCTURE) { return BOLT_PROTOCOL_VIOLATION; } uint8_t code; TRY(BoltBuffer_unload_u8(state->rx_buffer, &code)); state->data_type = code; int32_t size = marker & 0x0F; BoltValue_format_as_List(state->data, size); for (int i = 0; i<size; i++) { TRY(unload(connection->protocol->check_readable_struct, state->rx_buffer, BoltList_value(state->data, i), connection->log)); } if (code==BOLT_V1_RECORD) { if (state->record_counter<MAX_LOGGED_RECORDS) { BoltLog_message(connection->log, BoltConnection_id(connection), "S", state->response_counter, code, state->data, connection->protocol->structure_name, connection->protocol->message_name); } state->record_counter += 1; } else { if (state->record_counter>MAX_LOGGED_RECORDS) { BoltLog_info(connection->log, "[%s]: S[%d]: Received %llu more records", BoltConnection_id(connection), state->response_counter, state->record_counter-MAX_LOGGED_RECORDS); } state->record_counter = 0; BoltLog_message(connection->log, BoltConnection_id(connection), "S", state->response_counter, code, state->data, connection->protocol->structure_name, connection->protocol->message_name); } return BOLT_SUCCESS; } void BoltProtocolV1_extract_metadata(struct BoltConnection* connection, struct BoltValue* metadata) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); switch (BoltValue_type(metadata)) { case BOLT_DICTIONARY: { for (int32_t i = 0; i<metadata->size; i++) { struct BoltValue* key = BoltDictionary_key(metadata, i); if (BoltString_equals(key, BOOKMARK_KEY, BOOKMARK_KEY_SIZE)) { struct BoltValue* value = BoltDictionary_value(metadata, i); switch (BoltValue_type(value)) { case BOLT_STRING: { memset(state->last_bookmark, 0, MAX_BOOKMARK_SIZE); memcpy(state->last_bookmark, BoltString_get(value), (size_t) (value->size)); BoltLog_info(connection->log, "[%s]: <SET last_bookmark=\"%s\">", BoltConnection_id(connection), state->last_bookmark); break; } default: break; } } else if (BoltString_equals(key, FIELDS_KEY, FIELDS_KEY_SIZE)) { struct BoltValue* value = BoltDictionary_value(metadata, i); switch (BoltValue_type(value)) { case BOLT_LIST: { struct BoltValue* target_value = state->result_field_names; BoltValue_format_as_List(target_value, value->size); for (int j = 0; j<value->size; j++) { struct BoltValue* source_value = BoltList_value(value, j); switch (BoltValue_type(source_value)) { case BOLT_STRING: BoltValue_format_as_String(BoltList_value(target_value, j), BoltString_get(source_value), source_value->size); break; default: BoltValue_format_as_Null(BoltList_value(target_value, j)); } } BoltLog_value(connection->log, "[%s]: <SET result_field_names=%s>", BoltConnection_id(connection), target_value, connection->protocol->structure_name); break; } default: break; } } else if (BoltString_equals(key, SERVER_KEY, SERVER_KEY_SIZE)) { struct BoltValue* value = BoltDictionary_value(metadata, i); switch (BoltValue_type(value)) { case BOLT_STRING: { memset(state->server, 0, MAX_SERVER_SIZE); memcpy(state->server, BoltString_get(value), (size_t) (value->size)); BoltLog_info(connection->log, "[%s]: <SET server=\"%s\">", BoltConnection_id(connection), state->server); break; } default: break; } } else if (BoltString_equals(key, FAILURE_CODE_KEY, FAILURE_CODE_KEY_SIZE) && state->data_type==BOLT_V1_FAILURE) { struct BoltValue* value = BoltDictionary_value(metadata, i); switch (BoltValue_type(value)) { case BOLT_STRING: { ensure_failure_data(state); struct BoltValue* target_value = BoltDictionary_value(state->failure_data, 0); BoltValue_format_as_String(target_value, BoltString_get(value), value->size); BoltLog_value(connection->log, "[%s]: <FAILURE code=\"%s\">", BoltConnection_id(connection), target_value, connection->protocol->structure_name); break; } default: break; } } else if (BoltString_equals(key, FAILURE_MESSAGE_KEY, FAILURE_MESSAGE_KEY_SIZE) && state->data_type==BOLT_V1_FAILURE) { struct BoltValue* value = BoltDictionary_value(metadata, i); switch (BoltValue_type(value)) { case BOLT_STRING: { ensure_failure_data(state); struct BoltValue* target_value = BoltDictionary_value(state->failure_data, 1); BoltValue_format_as_String(target_value, BoltString_get(value), value->size); BoltLog_value(connection->log, "[%s]: <FAILURE message=\"%s\">", BoltConnection_id(connection), target_value, connection->protocol->structure_name); break; } default: break; } } else { struct BoltValue* source_key = BoltDictionary_key(metadata, i); struct BoltValue* source_value = BoltDictionary_value(metadata, i); // increase length int32_t index = state->result_metadata->size; BoltValue_format_as_Dictionary(state->result_metadata, index+1); struct BoltValue* dest_key = BoltDictionary_key(state->result_metadata, index); struct BoltValue* dest_value = BoltDictionary_value(state->result_metadata, index); BoltValue_copy(dest_key, source_key); BoltValue_copy(dest_value, source_value); } } break; } default: break; } } int BoltProtocolV1_fetch(struct BoltConnection* connection, BoltRequest request_id) { struct BoltProtocolV1State* state = BoltProtocolV1_state(connection); BoltRequest response_id; do { char header[2]; int status = BoltConnection_receive(connection, &header[0], 2); if (status!=BOLT_SUCCESS) { return -1; } uint16_t chunk_size = char_to_uint16be(header); BoltBuffer_compact(state->rx_buffer); while (chunk_size!=0) { status = BoltConnection_receive(connection, BoltBuffer_load_pointer(state->rx_buffer, chunk_size), chunk_size); if (status!=BOLT_SUCCESS) { return -1; } status = BoltConnection_receive(connection, &header[0], 2); if (status!=BOLT_SUCCESS) { return -1; } chunk_size = char_to_uint16be(header); } response_id = state->response_counter; TRY(BoltProtocolV1_unload(connection)); if (state->data_type!=BOLT_V1_RECORD) { state->response_counter += 1; // Clean existing metadata BoltValue_format_as_Dictionary(state->result_metadata, 0); if (state->data->size>=1) { BoltProtocolV1_extract_metadata(connection, BoltList_value(state->data, 0)); } } } while (response_id!=request_id); if (state->data_type!=BOLT_V1_RECORD) { return 0; } return 1; } int BoltProtocolV1_set_tx_timeout_unsupported(struct BoltConnection* connection, int64_t n) { UNUSED(connection); UNUSED(n); return BOLT_PROTOCOL_UNSUPPORTED; } int BoltProtocolV1_set_tx_bookmark_ignore(struct BoltConnection* connection, struct BoltValue* value) { UNUSED(connection); UNUSED(value); // we will ignore bookmarks with this version of the protocol return BOLT_SUCCESS; } int BoltProtocolV1_set_tx_metadata_unsupported(struct BoltConnection* connection, struct BoltValue* value) { UNUSED(connection); UNUSED(value); return BOLT_PROTOCOL_UNSUPPORTED; } int BoltProtocolV1_goodbye_noop(struct BoltConnection* connection) { UNUSED(connection); return BOLT_SUCCESS; } struct BoltProtocol* BoltProtocolV1_create_protocol() { struct BoltProtocol* protocol = BoltMem_allocate(sizeof(struct BoltProtocol)); protocol->proto_state = BoltProtocolV1_create_state(); protocol->message_name = &BoltProtocolV1_message_name; protocol->structure_name = &BoltProtocolV1_structure_name; protocol->check_readable_struct = &BoltProtocolV1_check_readable_struct_signature; protocol->check_writable_struct = &BoltProtocolV1_check_writable_struct_signature; protocol->init = &BoltProtocolV1_init; protocol->goodbye = &BoltProtocolV1_goodbye_noop; protocol->clear_run = &BoltProtocolV1_clear_load_run_request; protocol->set_run_cypher = &BoltProtocolV1_set_run_cypher; protocol->set_run_cypher_parameter = &BoltProtocolV1_set_run_cypher_parameter; protocol->set_run_bookmark = &BoltProtocolV1_set_tx_bookmark_ignore; protocol->set_run_tx_timeout = &BoltProtocolV1_set_tx_timeout_unsupported; protocol->set_run_tx_metadata = &BoltProtocolV1_set_tx_metadata_unsupported; protocol->load_run = &BoltProtocolV1_load_run_request; protocol->clear_begin_tx = &BoltProtocolV1_clear_load_begin_tx_request; protocol->set_begin_tx_bookmark = &BoltProtocolV1_set_begin_tx_bookmark; protocol->set_begin_tx_timeout = &BoltProtocolV1_set_tx_timeout_unsupported; protocol->set_begin_tx_metadata = &BoltProtocolV1_set_tx_metadata_unsupported; protocol->load_begin_tx = &BoltProtocolV1_load_begin_request; protocol->load_commit_tx = &BoltProtocolV1_load_commit_request; protocol->load_rollback_tx = &BoltProtocolV1_load_rollback_request; protocol->load_discard = &BoltProtocolV1_load_discard_request; protocol->load_pull = &BoltProtocolV1_load_pull_request; protocol->load_reset = &BoltProtocolV1_load_reset_request; protocol->last_request = &BoltProtocolV1_last_request; protocol->field_names = &BoltProtocolV1_result_field_names; protocol->field_values = &BoltProtocolV1_result_field_values; protocol->metadata = &BoltProtocolV1_result_metadata; protocol->failure = &BoltProtocolV1_failure; protocol->last_data_type = &BoltProtocolV1_last_data_type; protocol->last_bookmark = &BoltProtocolV1_last_bookmark; protocol->server = &BoltProtocolV1_server; protocol->id = NULL; protocol->is_failure_summary = &BoltProtocolV1_is_failure_summary; protocol->is_success_summary = &BoltProtocolV1_is_success_summary; protocol->is_ignored_summary = &BoltProtocolV1_is_ignored_summary; protocol->fetch = &BoltProtocolV1_fetch; return protocol; } void BoltProtocolV1_destroy_protocol(struct BoltProtocol* protocol) { if (protocol!=NULL) { BoltProtocolV1_destroy_state(protocol->proto_state); } BoltMem_deallocate(protocol, sizeof(struct BoltProtocol)); } <|start_filename|>src/seabolt/src/bolt/time-macos.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "time.h" #include <mach/clock.h> #include <mach/mach.h> int BoltTime_get_time(struct timespec* tp) { clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); tp->tv_sec = mts.tv_sec; tp->tv_nsec = mts.tv_nsec; return 0; } <|start_filename|>src/seabolt/src/bolt/config.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_CONFIG_H #define SEABOLT_CONFIG_H #include "bolt-public.h" #include "address-resolver.h" #include "values.h" /** * The operating mode of the connector. */ typedef int32_t BoltScheme; /** * Use BOLT_SCHEME_DIRECT to establish direct connections towards a single server */ #define BOLT_SCHEME_DIRECT 0 #ifndef SEABOLT_NO_DEPRECATED /** * Use BOLT_SCHEME_ROUTING to establish routing connections towards a casual cluster. * This is deprecated, please use BOLT_SCHEME_NEO4J instead. */ #define BOLT_SCHEME_ROUTING 1 #endif /** * Use BOLT_SCHEME_NEO4J to establish routing first connections towards a neo4j server. */ #define BOLT_SCHEME_NEO4J 1 /** * The transport to use for established connections. */ typedef int32_t BoltTransport; /** * Use BOLT_TRANSPORT_PLAINTEXT to establish clear text connections */ #define BOLT_TRANSPORT_PLAINTEXT 0 /** * Use BOLT_TRANSPORT_ENCRYPTED to establish encrypted connections that're protected with TLS 1.2. */ #define BOLT_TRANSPORT_ENCRYPTED 1 /** * The type that holds available configuration options applicable to underlying sockets. * * An instance needs to be created with \ref BoltSocketOptions_create and destroyed with \ref BoltSocketOptions_destroy * either after \ref BoltConfig_set_socket_options is called if using \ref BoltConnector, or after all * \ref BoltConnection instances explicitly opened with \ref BoltConnection_open are closed. */ typedef struct BoltSocketOptions BoltSocketOptions; /** * Creates a new instance of \ref BoltSocketOptions. * * @returns the pointer to the newly allocated \ref BoltSocketOptions instance. */ SEABOLT_EXPORT BoltSocketOptions* BoltSocketOptions_create(); /** * Destroys the passed \ref BoltSocketOptions instance. * * @param socket_options the instance to be destroyed. */ SEABOLT_EXPORT void BoltSocketOptions_destroy(BoltSocketOptions* socket_options); /** * Gets the configured connect timeout. * * @param socket_options the socket options instance to query. * @return the configured connect timeout. */ SEABOLT_EXPORT int32_t BoltSocketOptions_get_connect_timeout(BoltSocketOptions* socket_options); /** * Sets the configured connect timeout. * * @param socket_options the socket options instance to modify. * @param connect_timeout the connect timeout to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltSocketOptions_set_connect_timeout(BoltSocketOptions* socket_options, int32_t connect_timeout); /** * Gets whether keep alive is enabled or not. * * @param socket_options the socket options instance to query. * @return the configured keep alive, 1 if enabled or 0 if disabled. */ SEABOLT_EXPORT int32_t BoltSocketOptions_get_keep_alive(BoltSocketOptions* socket_options); /** * Sets whether keep alive is enabled or not * * @param socket_options the socket options instance to modify. * @param keep_alive the keep alive mode to set, 1 to enable and 0 to disable. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltSocketOptions_set_keep_alive(BoltSocketOptions* socket_options, int32_t keep_alive); /** * The type that holds available configuration options applicable to encrypted connections. * * An instance needs to be created with \ref BoltTrust_create and destroyed with \ref BoltTrust_destroy either * after \ref BoltConfig_set_trust is called if using \ref BoltConnector, or after all \ref BoltConnection instances * explicitly opened with \ref BoltConnection_open are closed. */ typedef struct BoltTrust BoltTrust; /** * Creates a new instance of \ref BoltTrust. * * @returns the pointer to the newly allocated \ref BoltTrust instance. */ SEABOLT_EXPORT BoltTrust* BoltTrust_create(); /** * Destroys the passed \ref BoltTrust instance. * * @param trust the instance to be destroyed. */ SEABOLT_EXPORT void BoltTrust_destroy(BoltTrust* trust); /** * Gets the configured trusted certificate byte stream (sequence of PEM encoded X509 certificates). * * @param trust the trust instance to query. * @param size the size of the returned byte stream, set to 0 if certs stream is NULL * @return the configured trusted certificate byte stream. */ SEABOLT_EXPORT const char* BoltTrust_get_certs(BoltTrust* trust, uint64_t* size); /** * Sets the configured trusted certificate byte stream (sequence of PEM encoded X509 certificates). * * @param trust the trust instance to query. * @param certs_pem the trusted certificate byte stream to set. * @param certs_pem_size the size of the trusted certificate byte stream. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltTrust_set_certs(BoltTrust* trust, const char* certs_pem, uint64_t certs_pem_size); /** * Gets the configured verification mode. * * @param trust the trust instance to query. * @return the configured verification mode, 1 if verification is in place or 0 if it will be skipped. */ SEABOLT_EXPORT int32_t BoltTrust_get_skip_verify(BoltTrust* trust); /** * Sets the configured verification mode. * * @param trust the trust instance to modify. * @param skip_verify the verification mode to set, 1 to enable verification or 0 to disable. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltTrust_set_skip_verify(BoltTrust* trust, int32_t skip_verify); /** * Gets the configured hostname verification mode. * * @param trust the trust instance to query. * @return the configured hostname verification mode, 1 if hostname verification is in place or 0 if it will be skipped. */ SEABOLT_EXPORT int32_t BoltTrust_get_skip_verify_hostname(BoltTrust* trust); /** * Sets the configured hostname verification mode. * * @param trust the trust instance to modify. * @param skip_verify_hostname the hostname verification mode to set, 1 to enable verification or 0 to disable. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltTrust_set_skip_verify_hostname(BoltTrust* trust, int32_t skip_verify_hostname); /** * The type that holds available configuration options to be provided to \ref BoltConnector. * * An instance needs to be created with \ref BoltConfig_create and destroyed with \ref BoltConfig_destroy after * \ref BoltConnector_create is called. */ typedef struct BoltConfig BoltConfig; /** * Creates a new instance of \ref BoltConfig. * * @returns the pointer to the newly allocated \ref BoltConfig instance. */ SEABOLT_EXPORT BoltConfig* BoltConfig_create(); /** * Destroys the passed \ref BoltConfig instance. * * @param config the instance to be destroyed. */ SEABOLT_EXPORT void BoltConfig_destroy(BoltConfig* config); /** * Gets the configured \ref BoltScheme "scheme". * * @param config the config instance to query. * @return the configured \ref BoltScheme "scheme". */ SEABOLT_EXPORT BoltScheme BoltConfig_get_scheme(BoltConfig* config); /** * Sets the configured \ref BoltScheme "scheme". * * @param config the config instance to modify. * @param mode the \ref BoltScheme "scheme" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_scheme(BoltConfig* config, BoltScheme scheme); /** * Gets the configured \ref BoltTransport "transport". * * @param config the config instance to query. * @return the configured \ref BoltTransport "transport". */ SEABOLT_EXPORT BoltTransport BoltConfig_get_transport(BoltConfig* config); /** * Sets the configured \ref BoltTransport "transport". * * @param config the config instance to modify. * @param transport the \ref BoltTransport "transport" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_transport(BoltConfig* config, BoltTransport transport); /** * Gets the configured \ref BoltTrust "trust settings". * * @param config the config instance to query. * @return the configured \ref BoltTrust "trust settings". */ SEABOLT_EXPORT BoltTrust* BoltConfig_get_trust(BoltConfig* config); /** * Sets the configured \ref BoltTrust "trust settings". * * @param config the config instance to modify. * @param trust the \ref BoltTrust "trust settings" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_trust(BoltConfig* config, BoltTrust* trust); /** * Gets the configured user agent that will be presented to the server. * * @param config the config instance to query. * @return the configured user agent. */ SEABOLT_EXPORT const char* BoltConfig_get_user_agent(BoltConfig* config); /** * Sets the configured user agent that will be presented to the server. * * @param config the config instance to modify. * @param user_agent the user agent to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_user_agent(BoltConfig* config, const char* user_agent); /** * Gets the configured \ref BoltValue "routing context". * * @param config the config instance to query. * @return the configured \ref BoltValue "routing context". */ SEABOLT_EXPORT BoltValue* BoltConfig_get_routing_context(BoltConfig* config); /** * Sets the configured \ref BoltValue "routing context". The routing context is a \ref BoltValue of type Dictionary * which consists of string key=value pairs that will be passed on to the routing procedure as explained in * <a href="https://neo4j.com/docs/developer-manual/current/drivers/client-applications/#_routing_drivers_with_routing_context">Routing drivers with routing context</a> * * @param config the config instance to modify. * @param routing_context the \ref BoltValue "routing context" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_routing_context(BoltConfig* config, BoltValue* routing_context); /** * Gets the configured \ref BoltAddressResolver "address resolver". * * @param config the config instance to query. * @return the configured \ref BoltAddressResolver "address resolver". */ SEABOLT_EXPORT BoltAddressResolver* BoltConfig_get_address_resolver(BoltConfig* config); /** * Sets the configured \ref BoltAddressResolver "address resolver". * * @param config the config instance to modify. * @param address_resolver the \ref BoltAddressResolver "address resolver" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_address_resolver(BoltConfig* config, BoltAddressResolver* address_resolver); /** * Gets the configured \ref BoltLog "logger". * * @param config the config instance to query. * @return the configured \ref BoltLog "logger". */ SEABOLT_EXPORT BoltLog* BoltConfig_get_log(BoltConfig* config); /** * Sets the configured \ref BoltLog "logger". * * @param config the config instance to modify. * @param log the \ref BoltLog "logger" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_log(BoltConfig* config, BoltLog* log); /** * Gets the configured maximum connection pool size. * * @param config the config instance to query. * @return the configured maximum connection pool size. */ SEABOLT_EXPORT int32_t BoltConfig_get_max_pool_size(BoltConfig* config); /** * Sets the configured maximum connection pool size. * * @param config the config instance to modify. * @param max_pool_size the maximum connection pool size to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_max_pool_size(BoltConfig* config, int32_t max_pool_size); /** * Gets the configured maximum connection life time. * * @param config the config instance to query. * @return the configured maximum connection life time. */ SEABOLT_EXPORT int32_t BoltConfig_get_max_connection_life_time(BoltConfig* config); /** * Sets the configured maximum connection life time. * * @param config the config instance to modify. * @param max_connection_life_time the maximum connection life time to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_max_connection_life_time(BoltConfig* config, int32_t max_connection_life_time); /** * Gets the configured maximum connection acquisition time. * * @param config the config instance to query. * @return the configured maximum connection acquisition time. */ SEABOLT_EXPORT int32_t BoltConfig_get_max_connection_acquisition_time(BoltConfig* config); /** * Sets the configured maximum connection acquisition time. * * @param config the config instance to modify. * @param max_connection_acquisition_time the maximum connection acquisition time to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_max_connection_acquisition_time(BoltConfig* config, int32_t max_connection_acquisition_time); /** * Gets the configured \ref BoltSocketOptions "socket options". * * @param config the config instance to query. * @return the configured \ref BoltSocketOptions "socket options". */ SEABOLT_EXPORT BoltSocketOptions* BoltConfig_get_socket_options(BoltConfig* config); /** * Sets the configured \ref BoltSocketOptions "socket options". * * @param config the config instance to modify. * @param socket_options the \ref BoltSocketOptions "socket options" to set. * @returns \ref BOLT_SUCCESS when the operation is successful, or another positive error code identifying the reason. */ SEABOLT_EXPORT int32_t BoltConfig_set_socket_options(BoltConfig* config, BoltSocketOptions* socket_options); #endif //SEABOLT_CONFIG_H <|start_filename|>src/seabolt/src/bolt/name.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "name.h" int get_address_components(volatile const struct sockaddr_storage* address, char* host_buffer, int host_buffer_size, char* port_buffer, int port_buffer_size) { int flags = 0; int address_size = address->ss_family==AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6); if (host_buffer!=NULL) { flags = flags | NI_NUMERICHOST; } else { host_buffer_size = 0; } if (port_buffer!=NULL) { flags = flags | NI_NUMERICSERV; } else { port_buffer_size = 0; } return getnameinfo((const struct sockaddr*) address, address_size, host_buffer, host_buffer_size, port_buffer, port_buffer_size, flags); } <|start_filename|>src/seabolt/src/bolt/time.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_TIME_H #define SEABOLT_TIME_H #include "bolt-public.h" #include <time.h> #ifndef NANOS_PER_SEC #define NANOS_PER_SEC 1000000000 #endif SEABOLT_EXPORT int BoltTime_get_time(struct timespec* tp); int64_t BoltTime_get_time_ms(); int64_t BoltTime_get_time_ms_from(struct timespec* tp); void BoltTime_diff_time(struct timespec* t, struct timespec* t0, struct timespec* t1); #endif //SEABOLT_TIME_H <|start_filename|>make_release.cmd<|end_filename|> @Echo Off Call %~dp0\make.cmd %~1 Release x64 install || Goto :Failure Exit /b 0 :Failure Exit /b 1 <|start_filename|>CMakeCPack.cmake<|end_filename|> set(CPACK_PACKAGE_NAME "${PROJECT_NAME}") set(CPACK_PACKAGE_VENDOR "neo4j") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "seabolt: The C Connector Library for Neo4j") set(CPACK_PACKAGE_HOMEPAGE_URL "https://github.com/neo4j-drivers/seabolt") set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE") set(CPACK_MONOLITHIC_INSTALL ON) if (WIN32 OR MINGW) unset(CPACK_PACKAGING_INSTALL_PREFIX) else () set(CPACK_PACKAGING_INSTALL_PREFIX "/usr/local") endif () set(CPACK_PACKAGE_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") set(CPACK_PACKAGE_VERSION_MINOR "${PROJECT_VERSION_MINOR}") set(CPACK_PACKAGE_VERSION_PATCH "${PROJECT_VERSION_PATCH}") set(CPACK_PACKAGE_VERSION_TWEAK "${PROJECT_VERSION_TWEAK}") set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") set(CPACK_PACKAGE_CHECKSUM "SHA256") set(CPACK_SOURCE_IGNORE_FILES "${PROJECT_BINARY_DIR};/.git/;.gitignore;menu.yml") set(CPACK_PACKAGE_DIRECTORY "${PROJECT_BINARY_DIR}/dist-package") if (UNIX) set(CPACK_GENERATOR "TGZ") else () set(CPACK_GENERATOR "ZIP") endif () if (CMAKE_SYSTEM_NAME STREQUAL "Linux") set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${PROJECT_VERSION}-${CMAKE_SYSTEM_NAME}-${OS_ID}-${OS_VERSION_ID}") endif () if (CMAKE_SYSTEM_NAME STREQUAL "Windows") if ("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8") set(CMAKE_BITNESS "64") elseif (CMAKE_SIZEOF_VOID_P STREQUAL "4") set(CMAKE_BITNESS "32") endif () if (MSVC) set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${PROJECT_VERSION}-win${CMAKE_BITNESS}-msvc") else () set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${PROJECT_VERSION}-win${CMAKE_BITNESS}-mingw") endif () endif () if (UNIX) if (OS_ID_LIKE MATCHES "debian") list(APPEND CPACK_GENERATOR "DEB") set(CPACK_DEBIAN_PACKAGE_NAME "${SEABOLT_NAME}") set(CPACK_DEBIAN_PACKAGE_VERSION "${PROJECT_VERSION}") set(CPACK_DEBIAN_PACKAGE_MAINTAINER "neo4j") set(CPACK_DEBIAN_PACKAGE_SECTION "devel") set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_SOURCE_DIR}/cmake/package/deb/postinst;${CMAKE_CURRENT_SOURCE_DIR}/cmake/package/deb/postrm;") endif () if (OS_ID_LIKE MATCHES "rhel|fedora|suse") list(APPEND CPACK_GENERATOR "RPM") set(CPACK_RPM_PACKAGE_NAME "${SEABOLT_NAME}") set(CPACK_RPM_PACKAGE_RELEASE "1") set(CPACK_RPM_PACKAGE_LICENSE "Apache") set(CPACK_RPM_POST_INSTALL_SCRIPT_FILE "${CMAKE_CURRENT_SOURCE_DIR}/cmake/package/rpm/post") set(CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE "${CMAKE_CURRENT_SOURCE_DIR}/cmake/package/rpm/postun") endif () endif () message(STATUS "CPack generators: ${CPACK_GENERATOR}") include(CPack) <|start_filename|>src/seabolt/src/bolt/log-private.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_LOG_PRIVATE_H #define SEABOLT_LOG_PRIVATE_H #include "log.h" #include "values-private.h" struct BoltLog { void* state; int error_enabled; int warning_enabled; int info_enabled; int debug_enabled; log_func error_logger; log_func warning_logger; log_func info_logger; log_func debug_logger; }; BoltLog* BoltLog_clone(BoltLog *log); void BoltLog_error(const struct BoltLog* log, const char* format, ...); void BoltLog_warning(const struct BoltLog* log, const char* format, ...); void BoltLog_info(const struct BoltLog* log, const char* format, ...); void BoltLog_debug(const struct BoltLog* log, const char* format, ...); void BoltLog_value(const struct BoltLog* log, const char* format, const char* id, struct BoltValue* value, name_resolver_func struct_name_resolver); void BoltLog_message(const struct BoltLog* log, const char* id, const char* peer, BoltRequest request_id, int16_t code, struct BoltValue* fields, name_resolver_func struct_name_resolver, name_resolver_func message_name_resolver); #endif //SEABOLT_LOG_PRIVATE_H <|start_filename|>src/seabolt/src/bolt/communication-plain.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "communication-plain.h" #include "bolt-private.h" #include "config-private.h" #include "mem.h" #include "name.h" #include "status-private.h" #include "log-private.h" #define MAX_IPADDR_LEN 64 #define ADDR_SIZE(address) address->ss_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) #define TRY_SOCKET(code, status, error_ctx_fmt, file, line) { \ int status_try = (code); \ if (status_try == -1) { \ int last_error = socket_last_error(comm); \ int last_error_transformed = socket_transform_error(comm, last_error); \ BoltStatus_set_error_with_ctx(status, last_error_transformed, error_ctx_fmt, file, line, last_error); \ return BOLT_STATUS_SET; \ } \ } int socket_last_error(BoltCommunication* comm); int socket_transform_error(BoltCommunication* comm, int error_code); int socket_ignore_sigpipe(void* replaced_action); int socket_restore_sigpipe(void* action_to_restore); int socket_lifecycle_startup(); int socket_lifecycle_shutdown(); int socket_open(int domain, int type, int protocol); int socket_shutdown(int sockfd); int socket_close(int sockfd); int socket_connect(int sockfd, const struct sockaddr* addr, socklen_t addrlen, int* in_progress); int socket_select(int sockfd, int timeout); int socket_send(int sockfd, const void* buf, int len, int flags); int socket_recv(int sockfd, void* buf, int len, int flags); int socket_get_local_addr(int sockfd, struct sockaddr_storage* address, socklen_t* address_size); int socket_disable_sigpipe(int sockfd); int socket_set_blocking_mode(int sockfd, int blocking); int socket_set_recv_timeout(int sockfd, int timeout); int socket_set_keepalive(int sockfd, int keepalive); int socket_set_nodelay(int sockfd, int nodelay); int plain_socket_ignore_sigpipe(BoltCommunication* comm) { PlainCommunicationContext* ctx = comm->context; int status = socket_ignore_sigpipe(&ctx->action_to_restore); if (status<0) { int last_error = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, last_error), "plain_socket_ignore_sigpipe(%s:%d): unable to install ignore handler for SIGPIPE: %d", __FILE__, __LINE__, last_error); return BOLT_STATUS_SET; } return BOLT_SUCCESS; } int plain_socket_restore_sigpipe(BoltCommunication* comm) { PlainCommunicationContext* ctx = comm->context; int status = socket_restore_sigpipe(&ctx->action_to_restore); if (status<0) { int last_error = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, last_error), "plain_socket_ignore_sigpipe(%s:%d): unable to restore original handler for SIGPIPE: %d", __FILE__, __LINE__, last_error); return BOLT_STATUS_SET; } return BOLT_SUCCESS; } int plain_socket_open(BoltCommunication* comm, const struct sockaddr_storage* address) { PlainCommunicationContext* context = comm->context; context->fd_socket = socket_open(address->ss_family, SOCK_STREAM, IPPROTO_TCP); if (context->fd_socket==-1) { int last_error_code = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, last_error_code), "plain_socket_open(%s,%d): socket error code: %d", __FILE__, __LINE__, last_error_code); return comm->status->error; } TRY_SOCKET(socket_disable_sigpipe(context->fd_socket), comm->status, "plain_socket_open(%s:%d), unable to set SO_NOSIGPIPE: %d", __FILE__, __LINE__); if (comm->sock_opts!=NULL && comm->sock_opts->connect_timeout>0) { // enable non-blocking mode TRY_SOCKET(socket_set_blocking_mode(context->fd_socket, 0), comm->status, "plain_socket_open(%s:%d), plain_socket_set_blocking error code: %d", __FILE__, __LINE__); // initiate connection int in_progress = 0; int conn_status = socket_connect(context->fd_socket, (struct sockaddr*) (address), ADDR_SIZE(address), &in_progress); if (conn_status==-1 && !in_progress) { int error_code = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, error_code), "plain_socket_open(%s:%d), connect error code: %d", __FILE__, __LINE__, error_code); return BOLT_STATUS_SET; } if (conn_status) { conn_status = socket_select(context->fd_socket, comm->sock_opts->connect_timeout); switch (conn_status) { case 0: { //timeout expired BoltStatus_set_error_with_ctx(comm->status, BOLT_TIMED_OUT, "plain_socket_open(%s:%d)", __FILE__, __LINE__); return BOLT_STATUS_SET; } case 1: { //connection successful break; } default: { int last_error = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, last_error), "plain_socket_open(%s:%d), select error code: %d", __FILE__, __LINE__, last_error); return BOLT_STATUS_SET; } } } // revert to blocking mode TRY_SOCKET(socket_set_blocking_mode(context->fd_socket, 1), comm->status, "plain_socket_open(%s:%d), plain_socket_set_blocking error code: %d", __FILE__, __LINE__); } else { int in_progress = 0; TRY_SOCKET(socket_connect(context->fd_socket, (struct sockaddr*) (address), ADDR_SIZE(address), &in_progress), comm->status, "plain_socket_open(%s:%d), connect error code: %d", __FILE__, __LINE__); } char resolved_host[MAX_IPADDR_LEN], resolved_port[6]; int status = get_address_components(address, resolved_host, MAX_IPADDR_LEN, resolved_port, 6); if (status!=0) { BoltStatus_set_error_with_ctx(comm->status, BOLT_ADDRESS_NAME_INFO_FAILED, "plain_socket_open(%s:%d), remote get_address_components error code: %d", __FILE__, __LINE__, status); return BOLT_STATUS_SET; } context->remote_endpoint = BoltAddress_create(resolved_host, resolved_port); char local_host[MAX_IPADDR_LEN], local_port[6]; struct sockaddr_storage local_addr; socklen_t local_addr_size = address->ss_family==AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6); TRY_SOCKET(socket_get_local_addr(context->fd_socket, &local_addr, &local_addr_size), comm->status, "plain_socket_open(%s:%d): getsockname error code: %d", __FILE__, __LINE__); status = get_address_components(&local_addr, local_host, MAX_IPADDR_LEN, local_port, 6); if (status!=0) { BoltStatus_set_error_with_ctx(comm->status, BOLT_ADDRESS_NAME_INFO_FAILED, "plain_socket_open(%s:%d), local get_address_components error code: %d", __FILE__, __LINE__, status); return BOLT_STATUS_SET; } context->local_endpoint = BoltAddress_create(local_host, local_port); TRY_SOCKET(socket_set_nodelay(context->fd_socket, 1), comm->status, "plain_socket_open(%s:%d), socket_set_nodelay error code: %d", __FILE__, __LINE__); TRY_SOCKET(socket_set_recv_timeout(context->fd_socket, comm->sock_opts->recv_timeout), comm->status, "plain_socket_open(%s:%d), socket_set_recv_timeout error code: %d", __FILE__, __LINE__); TRY_SOCKET(socket_set_keepalive(context->fd_socket, comm->sock_opts->keep_alive), comm->status, "plain_socket_open(%s:%d), socket_set_keepalive error code: %d", __FILE__, __LINE__); return BOLT_SUCCESS; } int plain_socket_close(BoltCommunication* comm) { PlainCommunicationContext* context = comm->context; if (context->fd_socket) { socket_shutdown(context->fd_socket); socket_close(context->fd_socket); context->fd_socket = 0; } if (context->local_endpoint!=NULL) { BoltAddress_destroy(context->local_endpoint); context->local_endpoint = NULL; } if (context->remote_endpoint!=NULL) { BoltAddress_destroy(context->remote_endpoint); context->remote_endpoint = NULL; } return BOLT_SUCCESS; } int plain_socket_send(BoltCommunication* comm, char* buffer, int length, int* sent) { PlainCommunicationContext* context = comm->context; int bytes = socket_send(context->fd_socket, buffer, (size_t) length, 0); if (bytes==-1) { int last_error = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, last_error), "plain_socket_send(%s:%d), send error code: %d", __FILE__, __LINE__, last_error); return BOLT_STATUS_SET; } *sent = bytes; return BOLT_SUCCESS; } int plain_socket_recv(BoltCommunication* comm, char* buffer, int length, int* received) { PlainCommunicationContext* context = comm->context; int bytes = socket_recv(context->fd_socket, buffer, (size_t) length, 0); if (bytes==-1) { int last_error = socket_last_error(comm); BoltStatus_set_error_with_ctx(comm->status, socket_transform_error(comm, last_error), "plain_socket_recv(%s:%d), recv error code: %d", __FILE__, __LINE__, last_error); return BOLT_STATUS_SET; } if (bytes==0 && length!=0) { BoltStatus_set_error_with_ctx(comm->status, BOLT_END_OF_TRANSMISSION, "plain_socket_recv(%s:%d), recv returned 0", __FILE__, __LINE__); return BOLT_STATUS_SET; } *received = bytes; return BOLT_SUCCESS; } int plain_socket_destroy(BoltCommunication* comm) { PlainCommunicationContext* context = comm->context; if (context!=NULL) { if (context->local_endpoint!=NULL) { BoltAddress_destroy(context->local_endpoint); context->local_endpoint = NULL; } if (context->remote_endpoint!=NULL) { BoltAddress_destroy(context->remote_endpoint); context->remote_endpoint = NULL; } BoltMem_deallocate(context, sizeof(PlainCommunicationContext)); comm->context = NULL; } return BOLT_SUCCESS; } BoltAddress* plain_socket_local_endpoint(BoltCommunication* comm) { PlainCommunicationContext* context = comm->context; return context->local_endpoint; } BoltAddress* plain_socket_remote_endpoint(BoltCommunication* comm) { PlainCommunicationContext* context = comm->context; return context->remote_endpoint; } int BoltCommunication_startup() { return socket_lifecycle_startup(); } int BoltCommunication_shutdown() { return socket_lifecycle_shutdown(); } BoltCommunication* BoltCommunication_create_plain(BoltSocketOptions* sock_opts, BoltLog* log) { BoltCommunication* comm = BoltMem_allocate(sizeof(BoltCommunication)); comm->open = &plain_socket_open; comm->close = &plain_socket_close; comm->send = &plain_socket_send; comm->recv = &plain_socket_recv; comm->destroy = &plain_socket_destroy; comm->get_local_endpoint = &plain_socket_local_endpoint; comm->get_remote_endpoint = &plain_socket_remote_endpoint; comm->ignore_sigpipe = &plain_socket_ignore_sigpipe; comm->restore_sigpipe = &plain_socket_restore_sigpipe; comm->last_error = &socket_last_error; comm->transform_error = &socket_transform_error; comm->status_owned = 1; comm->status = BoltStatus_create_with_ctx(1024); comm->sock_opts_owned = sock_opts==NULL; comm->sock_opts = sock_opts==NULL ? BoltSocketOptions_create() : sock_opts; comm->log = log; PlainCommunicationContext* context = BoltMem_allocate(sizeof(PlainCommunicationContext)); context->local_endpoint = NULL; context->remote_endpoint = NULL; context->fd_socket = 0; context->action_to_restore = NULL; comm->context = context; return comm; } <|start_filename|>cmake/GitHash.cmake<|end_filename|> # in case Git is not available, we default to "unknown" set(VERSION_HASH "unknown") if (DEFINED ENV{SEABOLT_VERSION_HASH}) set(VERSION_HASH $ENV{SEABOLT_VERSION_HASH}) message(STATUS "Using Git hash from environment: ${VERSION_HASH}") else () # find Git and if available set GIT_HASH variable find_package(Git QUIET) if (GIT_FOUND) execute_process( COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%h OUTPUT_VARIABLE VERSION_HASH OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) endif () message(STATUS "Using Git hash from git command: ${VERSION_HASH}") endif () get_filename_component(OUTPUT_FILE_NAME ${OUTPUT_FILE} NAME) set(OUTPUT_TMP_FILE "${OUTPUT_FILE_NAME}.tmp") # generate a temporary outputfile based on input file configure_file( ${INPUT_FILE} ${OUTPUT_TMP_FILE} @ONLY ) if (EXISTS ${OUTPUT_FILE}) file(SHA256 ${OUTPUT_FILE} OLD_CONTENT_HASH) else () set(OLD_CONTENT_HASH "") endif () file(SHA256 ${OUTPUT_TMP_FILE} NEW_CONTENT_HASH) if (OLD_CONTENT_HASH STREQUAL NEW_CONTENT_HASH) # let's not copy contents because they're equal else () configure_file( ${INPUT_FILE} ${OUTPUT_FILE} @ONLY ) endif () file(REMOVE ${OUTPUT_TMP_FILE}) <|start_filename|>cmake/PkgConfigFiles.cmake<|end_filename|> message(STATUS "Passed ${LIBRARIES}") set(LIBS_PROCESSED "") foreach (lib ${LIBRARIES}) if (lib MATCHES "^\\$") continue() endif () if (lib MATCHES ">$") continue() endif () if (lib MATCHES "^-l") string(SUBSTRING ${lib} 2 -1 lib) endif () if (lib MATCHES ".*\\.a$") string(APPEND LIBS_PROCESSED "${lib} ") elseif (lib MATCHES ".*\\.so") string(APPEND LIBS_PROCESSED "${lib} ") elseif (lib MATCHES ".*\\.dylib") string(APPEND LIBS_PROCESSED "${lib} ") elseif (lib MATCHES ".*\\.lib$") string(APPEND LIBS_PROCESSED "-l${lib} ") else () string(APPEND LIBS_PROCESSED "-l${lib} ") endif () endforeach () message(STATUS "Processed ${LIBS_PROCESSED}") configure_file( ${INPUT_FILE} ${OUTPUT_FILE} @ONLY ) <|start_filename|>src/seabolt/tests/test-address-set.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "catch.hpp" #include "integration.hpp" SCENARIO("BoltAddressSet") { struct BoltAddress* localhost7687 = BoltAddress_create("localhost", "7687"); struct BoltAddress* localhost7688 = BoltAddress_create("localhost", "7688"); struct BoltAddress* localhost7689 = BoltAddress_create("localhost", "7689"); struct BoltAddress* localhost7690 = BoltAddress_create("localhost", "7690"); WHEN("constructed") { volatile BoltAddressSet* set = BoltAddressSet_create(); THEN("it should have size = 0") { REQUIRE(set->size==0); } THEN("it should have elements = NULL") { REQUIRE(set->elements==nullptr); } THEN("it should report size = 0") { REQUIRE(BoltAddressSet_size(set)==0); } } GIVEN("a newly constructed BoltAddressSet") { volatile BoltAddressSet* set = BoltAddressSet_create(); WHEN("BoltAddress[localhost,7687] is added") { BoltAddressSet_add(set, localhost7687); THEN("it should have size = 1") { REQUIRE(BoltAddressSet_size(set)==1); } THEN("it should report index of = 0") { REQUIRE(BoltAddressSet_index_of(set, localhost7687)==0); } } WHEN("BoltAddress[localhost,7687] is added again") { BoltAddressSet_add(set, localhost7687); THEN("it should have size = 1") { REQUIRE(BoltAddressSet_size(set)==1); } THEN("it should report index of = 0") { REQUIRE(BoltAddressSet_index_of(set, localhost7687)==0); } } WHEN("BoltAddress[localhost,7687] and BoltAddress[localhost,7688] is added") { BoltAddressSet_add(set, localhost7687); BoltAddressSet_add(set, localhost7688); THEN("it should have size = 2") { REQUIRE(BoltAddressSet_size(set)==2); } THEN("it should report index of BoltAddress[localhost,7687] = 0") { REQUIRE(BoltAddressSet_index_of(set, localhost7687)==0); } THEN("it should report index of BoltAddress[localhost,7688] = 1") { REQUIRE(BoltAddressSet_index_of(set, localhost7688)==1); } THEN("it should report index of BoltAddress[localhost,7689] = -1") { REQUIRE(BoltAddressSet_index_of(set, localhost7689)==-1); } } BoltAddressSet_destroy(set); } GIVEN("A BoltAddressSet with 3 addresses") { volatile BoltAddressSet* set = BoltAddressSet_create(); BoltAddressSet_add(set, localhost7687); BoltAddressSet_add(set, localhost7688); BoltAddressSet_add(set, localhost7689); WHEN("index of BoltAddress[localhost,7689] is queried") { THEN("it should report = 2") { REQUIRE(BoltAddressSet_index_of(set, localhost7689)==2); } } WHEN("index of BoltAddress[localhost,7690] is queried") { THEN("it should report = -1") { REQUIRE(BoltAddressSet_index_of(set, localhost7690)==-1); } } WHEN("BoltAddress[localhost,7689] is added again") { THEN("it should return -1") { REQUIRE(BoltAddressSet_add(set, localhost7689)==-1); } } WHEN("BoltAddress[localhost,7689] is removed") { REQUIRE(BoltAddressSet_remove(set, localhost7689)==2); THEN("it should have size = 2") { REQUIRE(BoltAddressSet_size(set)==2); } AND_WHEN("BoltAddress[localhost,7689] is removed again") { THEN("it should return -1") { REQUIRE(BoltAddressSet_remove(set, localhost7689)==-1); } THEN("it should have size = 2") { REQUIRE(BoltAddressSet_size(set)==2); } } } BoltAddressSet_destroy(set); } GIVEN("Two different BoltAddressSets") { volatile BoltAddressSet* set1 = BoltAddressSet_create(); REQUIRE(BoltAddressSet_add(set1, localhost7687)==0); REQUIRE(BoltAddressSet_add(set1, localhost7688)==1); volatile BoltAddressSet* set2 = BoltAddressSet_create(); REQUIRE(BoltAddressSet_add(set2, localhost7689)==0); WHEN("set1 is updated from set2") { BoltAddressSet_replace(set1, set2); THEN("set1 should have size = 1") { REQUIRE(BoltAddressSet_size(set1)==1); } THEN("set1 should contain BoltAddress[localhost,7689]") { REQUIRE(BoltAddressSet_index_of(set1, localhost7689)==0); } THEN("set1 should not contain BoltAddress[localhost,7687]") { REQUIRE(BoltAddressSet_index_of(set1, localhost7687)==-1); } THEN("set1 should not contain BoltAddress[localhost,7688]") { REQUIRE(BoltAddressSet_index_of(set1, localhost7688)==-1); } } } GIVEN("Two different BoltAddressSets") { volatile BoltAddressSet* set1 = BoltAddressSet_create(); REQUIRE(BoltAddressSet_add(set1, localhost7689)==0); volatile BoltAddressSet* set2 = BoltAddressSet_create(); REQUIRE(BoltAddressSet_add(set2, localhost7687)==0); REQUIRE(BoltAddressSet_add(set2, localhost7688)==1); REQUIRE(BoltAddressSet_add(set2, localhost7689)==2); WHEN("set2 is added to set1") { BoltAddressSet_add_all(set1, set2); THEN("set1 should have size = 1") { REQUIRE(BoltAddressSet_size(set1)==3); } THEN("set1 should contain BoltAddress[localhost,7689]") { REQUIRE(BoltAddressSet_index_of(set1, localhost7689)==0); } THEN("set1 should not contain BoltAddress[localhost,7687]") { REQUIRE(BoltAddressSet_index_of(set1, localhost7687)>=0); } THEN("set1 should not contain BoltAddress[localhost,7688]") { REQUIRE(BoltAddressSet_index_of(set1, localhost7688)>=0); } } } BoltAddress_destroy(localhost7687); BoltAddress_destroy(localhost7688); BoltAddress_destroy(localhost7689); BoltAddress_destroy(localhost7690); } <|start_filename|>src/seabolt/tests/test-direct-pool.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "integration.hpp" #include "catch.hpp" TEST_CASE("Direct Pool", "[unit]") { BoltAddress* address = BoltAddress_create("localhost", "8888"); BoltValue* auth_token = BoltAuth_basic("user", "password", NULL); BoltConfig* config = BoltConfig_create(); SECTION("Pool is Full") { SECTION("max_connection_acquisition_time>0") { BoltDirectPool* pool = nullptr; SECTION("should fail with BOLT_POOL_ACQUISITION_TIMED_OUT") { BoltConfig_set_max_pool_size(config, 10); BoltConfig_set_max_connection_acquisition_time(config, 1000); pool = BoltDirectPool_create(address, auth_token, config); // fake the pool to believe all of its connections are in use for (int i = 0; i<pool->max_size; i++) { pool->connections[i]->agent = "USED"; } BoltStatus* status = BoltStatus_create(); BoltConnection* connection = BoltDirectPool_acquire(pool, status); REQUIRE(connection==nullptr); REQUIRE(status->error==BOLT_POOL_ACQUISITION_TIMED_OUT); } BoltDirectPool_destroy(pool); } SECTION("max_connection_acquisition_time=0") { BoltDirectPool* pool = nullptr; SECTION("should fail with BOLT_POOL_FULL") { BoltConfig_set_max_pool_size(config, 10); BoltConfig_set_max_connection_acquisition_time(config, 0); pool = BoltDirectPool_create(address, auth_token, config); // fake the pool to believe all of its connections are in use for (int i = 0; i<pool->max_size; i++) { pool->connections[i]->agent = "USED"; } BoltStatus* status = BoltStatus_create(); BoltConnection* connection = BoltDirectPool_acquire(pool, status); REQUIRE(connection==nullptr); REQUIRE(status->error==BOLT_POOL_FULL); } BoltDirectPool_destroy(pool); } } BoltConfig_destroy(config); BoltValue_destroy(auth_token); BoltAddress_destroy(address); } <|start_filename|>src/seabolt/src/bolt/connection-private.h<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_CONNECTION_PRIVATE_H #define SEABOLT_CONNECTION_PRIVATE_H #include "communication.h" #include "connection.h" #include "status-private.h" #include "bolt.h" /** * Use BOLT_TRANSPORT_MOCK to establish a mock connection */ #define BOLT_TRANSPORT_MOCKED -1 typedef void (* error_action_func)(struct BoltConnection*, void*); typedef struct BoltConnectionMetrics BoltConnectionMetrics; typedef struct BoltSecurityContext BoltSecurityContext; /** * Record of connection usage statistics. */ struct BoltConnectionMetrics { struct timespec time_opened; struct timespec time_closed; unsigned long long bytes_sent; unsigned long long bytes_received; }; struct BoltConnection { /// The agent currently responsible for using this connection const void* agent; BoltAccessMode access_mode; /// Transport type for this connection BoltTransport transport; const BoltAddress* address; char* id; const BoltLog* log; /// The security context (secure connections only) BoltSecurityContext* sec_context; /// The communication object BoltCommunication* comm; /// The protocol version used for this connection int32_t protocol_version; /// State required by the protocol struct BoltProtocol* protocol; // These buffers contain data exactly as it is transmitted or // received. Therefore for Bolt v1, chunk headers are included // in these buffers /// Transmit buffer struct BoltBuffer* tx_buffer; /// Receive buffer struct BoltBuffer* rx_buffer; /// Connection metrics BoltConnectionMetrics* metrics; /// Current status of the connection BoltStatus* status; error_action_func on_error_cb; void* on_error_cb_state; }; /** * Creates a new instance of \ref BoltConnection. * * @return the pointer to the newly allocated \ref BoltConnection instance. */ BoltConnection* BoltConnection_create(); /** * Destroys the passed \ref BoltConnection instance. * * @param connection the instance to be destroyed. */ void BoltConnection_destroy(BoltConnection* connection); /** * Opens a connection to a Bolt server. * * This function attempts to connect a BoltConnection to _address_ over * _transport_. The `address` should be a pointer to a `BoltAddress` struct * that has been successfully resolved. * * This function blocks until the connection attempt succeeds or fails. * On returning, the connection status will be set to either \ref BOLT_CONNECTION_STATE_CONNECTED * (if successful) or \ref BOLT_CONNECTION_STATE_DEFUNCT (if not). If defunct, the actual error code will * be returned. * * In case an error code is returned, more information can be gathered through \ref BoltStatus for which you can * get a reference by calling \ref BoltConnection_status. * * @param connection the instance to attempt the connection. * @param transport the type of transport over which to connect. * @param address the Bolt server address. * @param trust the trust settings to be used for \ref BOLT_TRANSPORT_ENCRYPTED connections. * @param log the logger to be used for logging purposes. * @param sock_opts the socket options to be applied to the underlying socket. * @return \ref BOLT_SUCCESS if the connection was opened successfully, * an error code otherwise. */ int32_t BoltConnection_open(BoltConnection* connection, BoltTransport transport, BoltAddress* address, BoltTrust* trust, BoltLog* log, BoltSocketOptions* sock_opts); /** * Closes the connection. * * @param connection the instance to be closed. */ void BoltConnection_close(BoltConnection* connection); /** * Initialise the connection and authenticate using the provided authentication token. * * Returns 0 on success and -1 in case of an error. More information about the underlying error can be gathered * through \ref BoltStatus for which you can get a reference by calling \ref BoltConnection_status. * * @param connection the instance to be initialised and authenticated. * @param user_agent the user agent string to present to the server. * @param auth_token dictionary that contains an authentication token. * @return 0 on success, * -1 on error. */ int32_t BoltConnection_init(BoltConnection* connection, const char* user_agent, const BoltValue* auth_token); /** * Take an exact amount of data from the receive buffer, deferring to * the socket if not enough data is available. * * @param connection * @param buffer * @param buffer_size * @return */ int32_t BoltConnection_receive(BoltConnection* connection, char* buffer, int buffer_size); #endif //SEABOLT_CONNECTION_PRIVATE_H <|start_filename|>src/seabolt/tests/test-connection.cpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "catch.hpp" #include "integration.hpp" SCENARIO("BoltConnection") { GIVEN("a new constructed BoltConnection") { BoltConnection* connection = BoltConnection_create(); THEN("access mode should be set to WRITE") { REQUIRE(connection->access_mode==BOLT_ACCESS_MODE_WRITE); } THEN("status is not null") { REQUIRE(connection->status!=nullptr); } THEN("status->state should be DISCONNECTED") { REQUIRE(connection->status->state==BOLT_CONNECTION_STATE_DISCONNECTED); } THEN("status->error should be SUCCESS") { REQUIRE(connection->status->error==BOLT_SUCCESS); } THEN("status->error_ctx should not be NULL") { REQUIRE(connection->status->error_ctx!=nullptr); } THEN("metrics is not null") { REQUIRE(connection->metrics!=nullptr); } BoltConnection_destroy(connection); } } <|start_filename|>src/seabolt/tests/integration.hpp<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SEABOLT_TEST_INTEGRATION #define SEABOLT_TEST_INTEGRATION #include <cstring> #include <cstdlib> #include "bolt/bolt.h" extern "C" { #include "bolt/address-private.h" #include "bolt/address-set-private.h" #include "bolt/config-private.h" #include "bolt/connection-private.h" #include "bolt/values-private.h" #include "bolt/string-builder.h" #include "bolt/direct-pool.h" #include "bolt/v3.h" #include "bolt/communication.h" #include "bolt/communication-mock.h" } #define SETTING(name, default_value) ((char*)((getenv(name) == nullptr) ? (default_value) : getenv(name))) #define BOLT_IPV4_HOST SETTING("BOLT_IPV4_HOST", "127.0.0.1") #define BOLT_IPV6_HOST SETTING("BOLT_IPV6_HOST", "::1") #define BOLT_PORT SETTING("BOLT_PORT", "7687") #define BOLT_USER SETTING("BOLT_USER", "neo4j") #define BOLT_PASSWORD SETTING("BOLT_PASSWORD", "password") #define BOLT_USER_AGENT SETTING("BOLT_USER_AGENT", "seabolt/1.0.0a") #define BOLT_LOG SETTING("BOLT_LOG", "error") static struct BoltAddress BOLT_IPV6_ADDRESS{(char*) BOLT_IPV6_HOST, (char*) BOLT_PORT, 0, NULL, 0, NULL}; static struct BoltAddress BOLT_IPV4_ADDRESS{(char*) BOLT_IPV4_HOST, (char*) BOLT_PORT, 0, NULL, 0, NULL}; struct BoltAddress* bolt_get_address(const char* host, const char* port); struct BoltConnection* bolt_open_b(BoltTransport transport, const char* host, const char* port); struct BoltConnection* bolt_open_init_b(BoltTransport transport, const char* host, const char* port, const char* user_agent, const struct BoltValue* auth_token); struct BoltConnection* bolt_open_init_default(); struct BoltConnection* bolt_open_init_mocked(int32_t bolt_version, BoltLog* logger); struct BoltValue* bolt_basic_auth(const char* username, const char* password); void bolt_close_and_destroy_b(struct BoltConnection* connection); #endif // SEABOLT_TEST_INTEGRATION <|start_filename|>src/seabolt/src/bolt/communication-secure-schannel.c<|end_filename|> /* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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 "bolt-private.h" #include "communication-secure.h" #include "config-private.h" #include "log-private.h" #include "status-private.h" #include "mem.h" #include "communication-plain.h" #include <security.h> #include <sspi.h> #include <schnlsp.h> #ifndef SP_PROT_TLS1_2_CLIENT #define SP_PROT_TLS1_2_CLIENT 0x00000800 #endif #ifndef SP_PROT_TLS1_3_CLIENT #define SP_PROT_TLS1_3_CLIENT 0x00002000 #endif #ifndef SCH_SEND_AUX_RECORD #define SCH_SEND_AUX_RECORD 0x00200000 #endif #ifndef SCH_USE_STRONG_CRYPTO #define SCH_USE_STRONG_CRYPTO 0x00400000 #endif #ifndef SECURITY_FLAG_IGNORE_CERT_CN_INVALID #define SECURITY_FLAG_IGNORE_CERT_CN_INVALID 0x00001000 #endif #define PEM_MARKER "-----BEGIN" typedef struct BoltSecurityContext { const BoltLog* log; CredHandle* cred_handle; HCERTCHAINENGINE* cert_engine; HCERTSTORE* root_store; HCERTSTORE* trust_store; } BoltSecurityContext; typedef struct SChannelContext { int owns_sec_ctx; BoltSecurityContext* sec_ctx; char* id; char* hostname; CtxtHandle* context_handle; SecPkgContext_StreamSizes* stream_sizes; char* send_buffer; int send_buffer_length; char* recv_buffer; DWORD recv_buffer_length; DWORD recv_buffer_pos; char* hs_buffer; DWORD hs_buffer_length; DWORD hs_buffer_pos; char* pt_pending_buffer; DWORD pt_pending_buffer_length; DWORD pt_pending_buffer_pos; char* ct_pending_buffer; DWORD ct_pending_buffer_length; BoltTrust* trust; BoltCommunication* plain_comm; } SChannelContext; typedef void (* logger_func)(const struct BoltLog* log, const char* format, ...); const char* secure_schannel_trust_error(DWORD status) { switch (status) { case TRUST_E_CERT_SIGNATURE: return "The signature of the certificate cannot be verified."; case CRYPT_E_REVOKED: return "The certificate or signature has been revoked."; case CERT_E_UNTRUSTEDROOT: return "A certification chain processed correctly but terminated in a root certificate that is not trusted by the trust provider."; case CERT_E_UNTRUSTEDTESTROOT: return "The root certificate is a testing certificate, and policy settings disallow test certificates."; case CERT_E_CHAINING: return "A chain of certificates was not correctly created."; case CERT_E_WRONG_USAGE: return "The certificate is not valid for the requested usage."; case CERT_E_EXPIRED: return "A required certificate is not within its validity period."; case CERT_E_INVALID_NAME: return "The certificate has an invalid name. Either the name is not included in the permitted list, or it is explicitly excluded."; case CERT_E_INVALID_POLICY: return "The certificate has an invalid policy."; case TRUST_E_BASIC_CONSTRAINTS: return "The basic constraints of the certificate are not valid, or they are missing."; case CERT_E_CRITICAL: return "The certificate is being used for a purpose other than the purpose specified by its CA."; case CERT_E_VALIDITYPERIODNESTING: return "The validity periods of the certification chain do not nest correctly."; case CRYPT_E_NO_REVOCATION_CHECK: return "The revocation function was unable to check revocation for the certificate."; case CRYPT_E_REVOCATION_OFFLINE: return "The revocation function was unable to check revocation because the revocation server was offline. "; case CERT_E_PURPOSE: return "The certificate is being used for a purpose other than one specified by the issuing CA."; case CERT_E_REVOKED: return "The certificate has been explicitly revoked by the issuer."; case CERT_E_REVOCATION_FAILURE: return "The revocation process could not continue, and the certificate could not be checked. "; case CERT_E_CN_NO_MATCH: return "The certificate's CN name does not match the passed value."; case CERT_E_ROLE: return "A certificate that can only be used as an end-entity is being used as a CA or vice versa. "; default: return "An unknown error."; } } const char* secure_schannel_status_error(DWORD status) { switch (status) { case SEC_E_INSUFFICIENT_MEMORY: return "There is not enough memory available to complete the requested action."; case SEC_E_INTERNAL_ERROR: return "An error occurred that did not map to an SSPI error code."; case SEC_E_INVALID_HANDLE: return "The handle passed to the function is not valid."; case SEC_E_INVALID_TOKEN: return "The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; case SEC_E_LOGON_DENIED: return "The logon failed."; case SEC_E_NO_AUTHENTICATING_AUTHORITY: return "No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; case SEC_E_NO_CREDENTIALS: return "No credentials are available in the security package."; case SEC_E_TARGET_UNKNOWN: return "The target was not recognized."; case SEC_E_WRONG_PRINCIPAL: return "The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication. "; case SEC_E_NOT_OWNER: return "The caller of the function does not have the necessary credentials."; case SEC_E_SECPKG_NOT_FOUND: return "The requested security package does not exist."; case SEC_E_UNKNOWN_CREDENTIALS: return "The credentials supplied to the package were not recognized. "; case SEC_E_UNSUPPORTED_FUNCTION: return "The function requested is not supported."; case SEC_E_BUFFER_TOO_SMALL: return "The message buffer is too small."; case SEC_E_CRYPTO_SYSTEM_INVALID: return "The cipher chosen for the security context is not supported."; case SEC_E_INCOMPLETE_MESSAGE: return "The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (Digest) again."; case SEC_E_MESSAGE_ALTERED: return "The message has been altered. Used with the Digest SSP."; case SEC_E_OUT_OF_SEQUENCE: return "The message was not received in the correct sequence."; case SEC_E_QOP_NOT_SUPPORTED: return "Neither confidentiality nor integrity are supported by the security context."; case SEC_E_CONTEXT_EXPIRED: return "The application is referencing a context that has already been closed. A properly written application should not receive this error."; default: return "An unclassified security status is returned."; } } void log_with_last_error(const struct BoltLog* log, logger_func func, const DWORD error_code, const char* format_msg, const char* id) { LPSTR error_msg = NULL; DWORD error_msg_length = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &error_msg, 0, NULL); if (error_msg_length==0) { error_msg = "Unable retrieve OS-specific error message"; } func(log, format_msg, id, error_code, error_msg); if (error_msg!=NULL) { LocalFree(error_msg); } } void log_with_sec_stat(const struct BoltLog* log, logger_func func, const SECURITY_STATUS status, const char* format_msg, const char* id) { func(log, format_msg, id, status, secure_schannel_status_error(status)); } void log_with_trust_error(const struct BoltLog* log, logger_func func, const DWORD trust_status, const char* format_msg, const char* id) { func(log, format_msg, id, trust_status, secure_schannel_trust_error(trust_status)); } /** * Loads certificates from a sequence of PEM-encoded certificates. Returns BOLT_SUCCESS on success and BOLT_TLS_ERROR * on failure. * * Self-signed certificates are placed into an in-memory store named root_store and other certificates are placed into * trust_store. Returned store handles should be closed by the user. * * @param trust * @param log * @param id * @param root_store * @param trust_store * @return */ int secure_schannel_load_certs(struct BoltTrust* trust, const struct BoltLog* log, const char* id, HCERTSTORE* root_store, HCERTSTORE* trust_store) { int result = BOLT_SUCCESS; BYTE* binary = NULL; DWORD binary_size = 0; PCCERT_CONTEXT cert = NULL; *root_store = NULL; *trust_store = NULL; // Create a certificate store to hold trusted root certificates *root_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, NULL); if (*root_store==NULL) { log_with_last_error(log, &BoltLog_error, GetLastError(), "[%s]: Unable to create an in-memory certificate store: CertOpenStore returned 0x%x: '%s'", id); result = BOLT_TLS_ERROR; goto cleanup; } // Create a certificate store to hold other trusted peer or intermediate CA certificates. *trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, NULL); if (*trust_store==NULL) { log_with_last_error(log, &BoltLog_error, GetLastError(), "[%s]: Unable to create an in-memory certificate store: CertOpenStore returned 0x%x: '%s'", id); result = BOLT_TLS_ERROR; goto cleanup; } // Find the first instance of PEM encoded block char* pem = strstr(trust->certs, PEM_MARKER); while (pem!=NULL) { DWORD pem_length = (DWORD) (trust->certs_len-(pem-trust->certs)); // Decode PEM-encoded string into its binary form if (!CryptStringToBinary(pem, pem_length, CRYPT_STRING_ANY, NULL, &binary_size, NULL, NULL)) { log_with_last_error(log, &BoltLog_error, GetLastError(), "[%s]: Unable to decode PEM encoded string: CryptStringToBinary returned 0x%x: '%s", id); result = BOLT_TLS_ERROR; goto cleanup; } binary = BoltMem_allocate(binary_size); if (!CryptStringToBinary(pem, pem_length, CRYPT_STRING_ANY, binary, &binary_size, NULL, NULL)) { log_with_last_error(log, &BoltLog_error, GetLastError(), "[%s]: Unable to decode PEM encoded string: CryptStringToBinary returned 0x%x: '%s'", id); result = BOLT_TLS_ERROR; goto cleanup; } // Parse the PEM-encoded certificate cert = CertCreateCertificateContext(X509_ASN_ENCODING, binary, binary_size); if (cert==NULL) { log_with_last_error(log, &BoltLog_error, GetLastError(), "[%s]: Unable to create certificate context: CertCreateCertificateContext returned 0x%x: '%s'", id); result = BOLT_TLS_ERROR; goto cleanup; } // Decide which store should the certificate to be placed HCERTSTORE* target_store = NULL; if (CertCompareCertificateName(X509_ASN_ENCODING, &cert->pCertInfo->Subject, &cert->pCertInfo->Issuer)) { target_store = root_store; } else { target_store = trust_store; } // Add it to the target store if (!CertAddCertificateContextToStore(*target_store, cert, CERT_STORE_ADD_ALWAYS, NULL)) { log_with_last_error(log, &BoltLog_error, GetLastError(), "[%s]: Unable to add certificate to store: CertAddCertificateContextToStore returned 0x%x: '%s", id); result = BOLT_TLS_ERROR; goto cleanup; } // Free allocated certificate CertFreeCertificateContext(cert); cert = NULL; // Free buffer BoltMem_deallocate(binary, binary_size); binary = NULL; binary_size = 0; // Find the next instance of PEM encoded block pem = strstr(pem+1, PEM_MARKER); } cleanup: if (cert!=NULL) { CertFreeCertificateContext(cert); } if (binary!=NULL) { BoltMem_deallocate(binary, binary_size); } if (result!=BOLT_SUCCESS) { if (*root_store!=NULL) { CertCloseStore(*root_store, CERT_CLOSE_STORE_FORCE_FLAG); } if (*trust_store!=NULL) { CertCloseStore(*trust_store, CERT_CLOSE_STORE_FORCE_FLAG); } } return result; } BoltSecurityContext* BoltSecurityContext_create(struct BoltTrust* trust, const char* hostname, const struct BoltLog* log, const char* id) { UNUSED(trust); UNUSED(hostname); CredHandle* handle = BoltMem_allocate(sizeof(CredHandle)); TimeStamp lifetime; SCHANNEL_CRED credData; ZeroMemory(&credData, sizeof(credData)); credData.dwVersion = SCHANNEL_CRED_VERSION; credData.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_3_CLIENT; credData.dwFlags = SCH_SEND_AUX_RECORD | SCH_USE_STRONG_CRYPTO; // we explicitly disable automatic certificate validation credData.dwFlags |= SCH_CRED_MANUAL_CRED_VALIDATION; SECURITY_STATUS status = AcquireCredentialsHandle(NULL, UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL, &credData, NULL, NULL, handle, &lifetime); if (status!=SEC_E_OK) { log_with_sec_stat(log, &BoltLog_error, status, "[%s]: Unable to initialise security context: AcquireCredentialsHandle returned 0x%x: '%s'", id); return NULL; } HCERTSTORE root_store = NULL, trust_store = NULL; HCERTCHAINENGINE cert_engine = 0; if (trust!=NULL && trust->certs!=NULL && trust->certs_len>0) { int result = secure_schannel_load_certs(trust, log, id, &root_store, &trust_store); if (result!=BOLT_SUCCESS) { return NULL; } CERT_CHAIN_ENGINE_CONFIG cert_engine_config; memset(&cert_engine_config, 0, sizeof(cert_engine_config)); cert_engine_config.cbSize = sizeof(CERT_CHAIN_ENGINE_CONFIG); cert_engine_config.hRestrictedRoot = NULL; cert_engine_config.hRestrictedTrust = NULL; cert_engine_config.hRestrictedOther = NULL; cert_engine_config.cAdditionalStore = 0; cert_engine_config.rghAdditionalStore = NULL; cert_engine_config.dwFlags = 0; cert_engine_config.dwUrlRetrievalTimeout = 0; cert_engine_config.MaximumCachedCertificates = 0; cert_engine_config.CycleDetectionModulus = 0; cert_engine_config.hExclusiveRoot = root_store; cert_engine_config.hExclusiveTrustedPeople = trust_store; if (!CertCreateCertificateChainEngine(&cert_engine_config, &cert_engine)) { log_with_last_error(log, &BoltLog_error, GetLastError(), "Unable to create chain engine: CertCreateCertificateEngine returned 0x%x: '%s'", id); return NULL; } } BoltSecurityContext* context = BoltMem_allocate(sizeof(BoltSecurityContext)); context->log = log; context->cred_handle = handle; context->cert_engine = cert_engine; context->root_store = root_store; context->trust_store = trust_store; return context; } void BoltSecurityContext_destroy(BoltSecurityContext* context) { if (context!=NULL) { if (context->cred_handle!=NULL) { SECURITY_STATUS status = FreeCredentialsHandle(context->cred_handle); if (status!=SEC_E_OK) { BoltLog_warning(context->log, "Unable to destroy security context: FreeCredentialsHandle returned %d", status); } BoltMem_deallocate(context->cred_handle, sizeof(CredHandle)); context->cred_handle = NULL; } if (context->cert_engine!=NULL) { CertFreeCertificateChainEngine(context->cert_engine); context->cert_engine = NULL; } if (context->root_store!=NULL) { if (!CertCloseStore(context->root_store, CERT_CLOSE_STORE_CHECK_FLAG)) { BoltLog_warning(context->log, "Unable to close custom root store: CertCloseStore returned: 0x%x", GetLastError()); } context->root_store = NULL; } if (context->trust_store!=NULL) { if (!CertCloseStore(context->trust_store, CERT_CLOSE_STORE_CHECK_FLAG)) { BoltLog_warning(context->log, "Unable to close custom trust store: CertCloseStore returned: 0x%x", GetLastError()); } context->trust_store = NULL; } BoltMem_deallocate(context, sizeof(BoltSecurityContext)); } } int BoltSecurityContext_startup() { return BOLT_SUCCESS; } int BoltSecurityContext_shutdown() { return BOLT_SUCCESS; } int secure_schannel_disconnect(BoltCommunication* comm); int secure_schannel_handshake(BoltCommunication* comm); int secure_schannel_handshake_loop(BoltCommunication* comm, int do_initial_read); void secure_schannel_log_cert(BoltCommunication* comm, PCCERT_CONTEXT cert, int remote) { SChannelContext* ctx = comm->context; char name[1000]; // display leaf name if (!CertNameToStr(cert->dwCertEncodingType, &cert->pCertInfo->Subject, CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG, name, sizeof(name))) { log_with_last_error(comm->log, &BoltLog_warning, GetLastError(), "[%s]: Unable to extract subject name: CertNameToStr returned 0x%x: '%s'", ctx->id); } BoltLog_debug(comm->log, "[%s]: %s subject name: %s", ctx->id, remote ? "Server" : "Client", name); if (!CertNameToStr(cert->dwCertEncodingType, &cert->pCertInfo->Issuer, CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG, name, sizeof(name))) { log_with_last_error(comm->log, &BoltLog_warning, GetLastError(), "[%s]: Unable to extract issuer name: CertNameToStr returned 0x%x: '%s'", ctx->id); } BoltLog_debug(comm->log, "[%s]: %s issuer name: %s", ctx->id, remote ? "Server" : "Client", name); // display certificate chain PCCERT_CONTEXT current_cert = cert; PCCERT_CONTEXT issuer_cert = NULL; int level = 0; while (1) { DWORD verification_flags = 0; issuer_cert = CertGetIssuerCertificateFromStore(cert->hCertStore, current_cert, NULL, &verification_flags); if (issuer_cert==NULL) { if (current_cert!=cert) { CertFreeCertificateContext(current_cert); } break; } if (!CertNameToStr(issuer_cert->dwCertEncodingType, &issuer_cert->pCertInfo->Subject, CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG, name, sizeof(name))) { log_with_last_error(comm->log, &BoltLog_warning, GetLastError(), "[%s]: Unable to extract CA subject name: CertNameToStr returned 0x%x: '%s'", ctx->id); } BoltLog_debug(comm->log, "[%s]: CA[%d] subject name: %s", ctx->id, level, name); if (!CertNameToStr(issuer_cert->dwCertEncodingType, &issuer_cert->pCertInfo->Issuer, CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG, name, sizeof(name))) { log_with_last_error(comm->log, &BoltLog_warning, GetLastError(), "[%s]: Unable to extract CA issuer name: CertNameToStr returned 0x%x: '%s'", ctx->id); } BoltLog_debug(comm->log, "[%s]: CA[%d] issuer name: %s", ctx->id, level, name); if (current_cert!=cert) { CertFreeCertificateContext(current_cert); } current_cert = issuer_cert; level += 1; } if (level==0 && remote) { BoltLog_warning(comm->log, "[%s]: Server did not provide its certificate chain.", ctx->id); } } int secure_schannel_verify_chain(BoltCommunication* comm) { SChannelContext* ctx = comm->context; if (ctx->context_handle==NULL) { return BOLT_TLS_ERROR; } int result; int server_name_length = 0; wchar_t* server_name = NULL; PCCERT_CHAIN_CONTEXT chain_context = NULL; // Retrive certificate presented by the remote server PCCERT_CONTEXT server_cert = NULL; SECURITY_STATUS status = QueryContextAttributes(ctx->context_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*) &server_cert); if (status!=SEC_E_OK) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: Unable to retrieve server certificate: QueryContextAttributes returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_verify_chain(%s:%d), QueryContextAttributes error code: 0x%x", __FILE__, __LINE__, status); result = BOLT_TLS_ERROR; goto cleanup; } // Log server certificate secure_schannel_log_cert(comm, server_cert, 1); // Windows API requires the hostname given for hostname verification to be in UTF-8 server_name_length = MultiByteToWideChar(CP_ACP, 0, ctx->hostname, -1, NULL, 0); server_name = malloc(sizeof(wchar_t)*server_name_length); if (server_name==NULL) { result = BOLT_OUT_OF_MEMORY; goto cleanup; } server_name_length = MultiByteToWideChar(CP_ACP, 0, ctx->hostname, -1, server_name, server_name_length); if (server_name_length==0) { result = BOLT_TLS_ERROR; goto cleanup; } // Set chain building parameters char* requested_usages[] = {szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE}; DWORD requested_usages_length = sizeof(requested_usages)/sizeof(char*); CERT_CHAIN_PARA chain_param; memset(&chain_param, 0, sizeof(chain_param)); chain_param.cbSize = sizeof(chain_param); chain_param.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR; chain_param.RequestedUsage.Usage.cUsageIdentifier = requested_usages_length; chain_param.RequestedUsage.Usage.rgpszUsageIdentifier = requested_usages; // Build a chain for verification, include server presented chain for building if (!CertGetCertificateChain(ctx->sec_ctx->cert_engine, server_cert, NULL, server_cert->hCertStore, &chain_param, 0, NULL, &chain_context)) { DWORD error_code = GetLastError(); log_with_last_error(comm->log, &BoltLog_error, error_code, "[%s]: Unable to build certificate chain: CertGetCertificateChain returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_verify_chain(%s:%d), CertGetCertificateChain error code: 0x%x", __FILE__, __LINE__, error_code); result = BOLT_TLS_ERROR; goto cleanup; } // Set chain verification parameters HTTPSPolicyCallbackData https_policy; CERT_CHAIN_POLICY_PARA policy_param; CERT_CHAIN_POLICY_STATUS policy_stat; memset(&https_policy, 0, sizeof(https_policy)); https_policy.cbStruct = sizeof(HTTPSPolicyCallbackData); https_policy.dwAuthType = AUTHTYPE_SERVER; https_policy.fdwChecks = 0; https_policy.pwszServerName = server_name; memset(&policy_param, 0, sizeof(policy_param)); policy_param.cbSize = sizeof(policy_param); policy_param.pvExtraPolicyPara = &https_policy; memset(&policy_stat, 0, sizeof(policy_stat)); policy_stat.cbSize = sizeof(policy_stat); if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context, &policy_param, &policy_stat)) { DWORD error_code = GetLastError(); log_with_last_error(comm->log, &BoltLog_error, error_code, "[%s]: Unable to verify certificate chain: CertVerifyCertificateChainPolicy returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_verify_chain(%s:%d), CertVerifyCertificateChainPolicy error code: 0x%x", __FILE__, __LINE__, error_code); result = BOLT_TLS_ERROR; goto cleanup; } // CertVerifyCertificateChainPolicy only returns 1 error, check if it returned CERT_E_CN_NO_MATCH // If the reported error is not a hostname mismatch, let's re-issue another CertVerifyCertificateChainPolicy call to // surface possible hostname mismatch condition. DWORD stored_error = 0; if (policy_stat.dwError!=0 && policy_stat.dwError!=(DWORD) CERT_E_CN_NO_MATCH) { stored_error = policy_stat.dwError; // once more excluding X509 related checks https_policy.fdwChecks = 0x00000080 | // SECURITY_FLAG_IGNORE_REVOCATION 0x00000100 | // SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00002000 | // SECURITY_FLAG_IGNORE_CERT_DATE_INVALID 0x00000200; // SECURITY_FLAG_IGNORE_WRONG_USAGE policy_param.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS | CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG | CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG | CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG | CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG | CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG | CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS | CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG | CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG | CERT_CHAIN_POLICY_IGNORE_NOT_SUPPORTED_CRITICAL_EXT_FLAG | CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG; if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context, &policy_param, &policy_stat)) { DWORD error_code = GetLastError(); log_with_last_error(comm->log, &BoltLog_error, error_code, "[%s]: Unable to verify certificate chain: CertVerifyCertificateChainPolicy returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_verify_chain(%s:%d), CertVerifyCertificateChainPolicy error code: 0x%x", __FILE__, __LINE__, error_code); result = BOLT_STATUS_SET; goto cleanup; } } int fail = 0; if (policy_stat.dwError && policy_stat.dwError==(DWORD) CERT_E_CN_NO_MATCH) { if (ctx->trust!=NULL && ctx->trust->skip_verify_hostname) { BoltLog_warning(comm->log, "[%s]: Hostname verification failed due to a mismatch, but resuming handshake since hostname verification is set to be skipped", ctx->id); fail = fail!=0; } else { BoltLog_error(comm->log, "[%s]: Hostname verification failed due to a mismatch, aborting handshake", ctx->id); fail = 1; } } if (stored_error!=0) { if (ctx->trust!=NULL && ctx->trust->skip_verify) { BoltLog_warning(comm->log, "[%s]: Unable to establish trust due to '%s' (code '0x%x'), but resuming handshake since trust verification is set to be skipped", ctx->id, secure_schannel_trust_error(stored_error), stored_error); fail = fail!=0; } else { log_with_trust_error(comm->log, &BoltLog_error, stored_error, "[%s]: Unable to establish trust due to 0x%x: '%s', aborting handshake", ctx->id); fail = 1; } } result = fail ? BOLT_TLS_ERROR : BOLT_SUCCESS; cleanup: if (chain_context!=NULL) { CertFreeCertificateChain(chain_context); } if (server_name!=NULL) { free(server_name); } return result; } int secure_schannel_open(BoltCommunication* comm, const struct sockaddr_storage* address) { SChannelContext* ctx = comm->context; int status = ctx->plain_comm->open(ctx->plain_comm, address); if (status!=BOLT_SUCCESS) { return status; } if (ctx->sec_ctx==NULL) { ctx->sec_ctx = BoltSecurityContext_create(ctx->trust, ctx->hostname, comm->log, ctx->id); ctx->owns_sec_ctx = 1; } ctx->context_handle = BoltMem_allocate(sizeof(CtxtHandle)); status = secure_schannel_handshake(comm); if (status!=BOLT_SUCCESS) { return status; } status = secure_schannel_verify_chain(comm); if (status!=BOLT_SUCCESS) { return status; } ctx->stream_sizes = BoltMem_allocate(sizeof(SecPkgContext_StreamSizes)); SECURITY_STATUS size_status = QueryContextAttributes(ctx->context_handle, SECPKG_ATTR_STREAM_SIZES, ctx->stream_sizes); if (size_status!=SEC_E_OK) { log_with_sec_stat(comm->log, &BoltLog_error, size_status, "[%s]: Unable to query TLS stream sizes: QueryContextAttributes returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_open(%s:%d), QueryContextAttributes error code: 0x%x", __FILE__, __LINE__, size_status); return BOLT_STATUS_SET; } ctx->send_buffer_length = (int) (ctx->stream_sizes->cbHeader+ctx->stream_sizes->cbMaximumMessage +ctx->stream_sizes->cbTrailer); ctx->send_buffer = BoltMem_allocate(ctx->send_buffer_length); ctx->recv_buffer_length = (int) (ctx->stream_sizes->cbHeader+ctx->stream_sizes->cbMaximumMessage +ctx->stream_sizes->cbTrailer); ctx->recv_buffer_pos = 0; ctx->recv_buffer = BoltMem_allocate(ctx->recv_buffer_length); return BOLT_SUCCESS; } int secure_schannel_close(BoltCommunication* comm) { SChannelContext* ctx = comm->context; if (ctx->context_handle!=NULL) { int status = secure_schannel_disconnect(comm); if (status!=BOLT_SUCCESS) { // TODO: warn } DeleteSecurityContext(ctx->context_handle); BoltMem_deallocate(ctx->context_handle, sizeof(CtxtHandle)); ctx->context_handle = NULL; } if (ctx->stream_sizes!=NULL) { BoltMem_deallocate(ctx->stream_sizes, sizeof(SecPkgContext_StreamSizes)); ctx->stream_sizes = NULL; } if (ctx->send_buffer!=NULL) { BoltMem_deallocate(ctx->send_buffer, ctx->send_buffer_length); ctx->send_buffer_length = 0; ctx->send_buffer = NULL; } if (ctx->recv_buffer!=NULL) { BoltMem_deallocate(ctx->recv_buffer, ctx->recv_buffer_length); ctx->recv_buffer_length = 0; ctx->recv_buffer_pos = 0; ctx->recv_buffer = NULL; } ctx->pt_pending_buffer = NULL; ctx->pt_pending_buffer_pos = 0; ctx->pt_pending_buffer_length = 0; ctx->ct_pending_buffer = NULL; ctx->ct_pending_buffer_length = 0; if (ctx->sec_ctx!=NULL && ctx->owns_sec_ctx) { BoltSecurityContext_destroy(ctx->sec_ctx); ctx->sec_ctx = NULL; ctx->owns_sec_ctx = 0; } return ctx->plain_comm->close(ctx->plain_comm); } int secure_schannel_send(BoltCommunication* comm, char* buffer, int length, int* sent) { SChannelContext* ctx = comm->context; SecBufferDesc msg; SecBuffer msg_bufs[4]; char* msg_buffer = ctx->send_buffer+ctx->stream_sizes->cbHeader; int msg_buffer_length = 0; int msg_buffer_sent = 0; int remaining = length; int total_sent = 0; int result = BOLT_SUCCESS; while (total_sent<length) { int current_length = remaining<(int) ctx->stream_sizes->cbMaximumMessage ? remaining : (int) ctx->stream_sizes->cbMaximumMessage; char* current = buffer+total_sent; MoveMemory(msg_buffer, current, (size_t) current_length); msg_bufs[0].pvBuffer = ctx->send_buffer; msg_bufs[0].cbBuffer = ctx->stream_sizes->cbHeader; msg_bufs[0].BufferType = SECBUFFER_STREAM_HEADER; msg_bufs[1].pvBuffer = msg_buffer; msg_bufs[1].cbBuffer = (unsigned long) current_length; msg_bufs[1].BufferType = SECBUFFER_DATA; msg_bufs[2].pvBuffer = msg_buffer+current_length; msg_bufs[2].cbBuffer = ctx->stream_sizes->cbTrailer; msg_bufs[2].BufferType = SECBUFFER_STREAM_TRAILER; msg_bufs[3].BufferType = SECBUFFER_EMPTY; msg.ulVersion = SECBUFFER_VERSION; msg.cBuffers = 4; msg.pBuffers = msg_bufs; SECURITY_STATUS status = EncryptMessage(ctx->context_handle, 0, &msg, 0); if (FAILED(status)) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: Unable to encrypt outgoing message: EncryptMessage returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_send(%s:%d), EncryptMessage error code: 0x%x", __FILE__, __LINE__, status); result = BOLT_STATUS_SET; break; } msg_buffer_length = (int) (msg_bufs[0].cbBuffer+msg_bufs[1].cbBuffer+msg_bufs[2].cbBuffer); msg_buffer_sent = 0; while (msg_buffer_sent<msg_buffer_length) { int sent_current = 0; result = ctx->plain_comm->send(ctx->plain_comm, ctx->send_buffer+msg_buffer_sent, msg_buffer_length-msg_buffer_sent, &sent_current); if (result!=BOLT_SUCCESS) { goto cleanup; } msg_buffer_sent += sent_current; } remaining -= current_length; total_sent += current_length; } cleanup: if (result==BOLT_SUCCESS) { *sent = total_sent; } return result; } int secure_schannel_recv(BoltCommunication* comm, char* buffer, int length, int* received) { SChannelContext* ctx = comm->context; // First check if we have any pending plain text that was previously decrypted but not returned due to size // restrictions if (ctx->pt_pending_buffer!=NULL) { DWORD data_size = ctx->pt_pending_buffer_length-ctx->pt_pending_buffer_pos; DWORD copy_length = length<(int) data_size ? (DWORD) length : data_size; MoveMemory(buffer, ctx->pt_pending_buffer+ctx->pt_pending_buffer_pos, copy_length); *received = (int) copy_length; ctx->pt_pending_buffer_pos += copy_length; if (ctx->pt_pending_buffer_pos==ctx->pt_pending_buffer_length) { ctx->pt_pending_buffer = NULL; ctx->pt_pending_buffer_length = 0; ctx->pt_pending_buffer_pos = 0; } return BOLT_SUCCESS; } // Then check if we have any pending cipher text that was previously received from the socket but not yet // processed if (ctx->ct_pending_buffer!=NULL && ctx->ct_pending_buffer_length>0) { MoveMemory(ctx->recv_buffer, ctx->ct_pending_buffer, ctx->ct_pending_buffer_length); ctx->recv_buffer_pos = ctx->ct_pending_buffer_length; ctx->ct_pending_buffer = NULL; ctx->ct_pending_buffer_length = 0; } SecBufferDesc msg; SecBuffer msg_bufs[4]; SecBuffer* data_buffer; SecBuffer* extra_buffer; SECURITY_STATUS status = SEC_E_OK; int result = BOLT_SUCCESS; memset(msg_bufs, 0, sizeof(msg_bufs)); while (1) { if (ctx->recv_buffer_pos==0 || status==SEC_E_INCOMPLETE_MESSAGE) { int now_received = 0; result = ctx->plain_comm->recv(ctx->plain_comm, ctx->recv_buffer+ctx->recv_buffer_pos, (int) (ctx->recv_buffer_length-ctx->recv_buffer_pos), &now_received); if (result!=BOLT_SUCCESS) { break; } ctx->recv_buffer_pos += now_received; } msg_bufs[0].pvBuffer = ctx->recv_buffer; msg_bufs[0].cbBuffer = (unsigned long) ctx->recv_buffer_pos; msg_bufs[0].BufferType = SECBUFFER_DATA; msg_bufs[1].BufferType = SECBUFFER_EMPTY; msg_bufs[2].BufferType = SECBUFFER_EMPTY; msg_bufs[3].BufferType = SECBUFFER_EMPTY; msg.ulVersion = SECBUFFER_VERSION; msg.cBuffers = 4; msg.pBuffers = msg_bufs; status = DecryptMessage(ctx->context_handle, &msg, 0, NULL); if (status==SEC_E_INCOMPLETE_MESSAGE) { continue; } if (status==SEC_I_CONTEXT_EXPIRED) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: Unable to decrypt incoming message: DecryptMessage returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_END_OF_TRANSMISSION, "secure_schannel_recv(%s:%d), DecryptMessage error code: 0x%x", __FILE__, __LINE__, status); result = BOLT_STATUS_SET; break; } if (status!=SEC_E_OK && status!=SEC_I_RENEGOTIATE) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: Unable to decrypt incoming message: DecryptMessage returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_recv(%s:%d), DecryptMessage error code: 0x%x", __FILE__, __LINE__, status); result = BOLT_STATUS_SET; break; } data_buffer = NULL; extra_buffer = NULL; for (int i = 1; i<(int) msg.cBuffers; i++) { if (data_buffer==NULL && msg_bufs[i].BufferType==SECBUFFER_DATA) { data_buffer = &msg_bufs[i]; } if (extra_buffer==NULL && msg_bufs[i].BufferType==SECBUFFER_EXTRA) { extra_buffer = &msg_bufs[i]; } } if (data_buffer) { DWORD data_size = data_buffer->cbBuffer; DWORD copy_length = length<(int) data_size ? (DWORD) length : data_size; MoveMemory(buffer, data_buffer->pvBuffer, copy_length); *received = (int) copy_length; if (copy_length<data_size) { ctx->pt_pending_buffer = data_buffer->pvBuffer; ctx->pt_pending_buffer_length = data_size; ctx->pt_pending_buffer_pos = copy_length; } else { ctx->pt_pending_buffer = NULL; ctx->pt_pending_buffer_length = 0; ctx->pt_pending_buffer_pos = 0; } } if (extra_buffer) { ctx->ct_pending_buffer = extra_buffer->pvBuffer; ctx->ct_pending_buffer_length = (int) extra_buffer->cbBuffer; } if (status==SEC_I_RENEGOTIATE) { BoltLog_debug(comm->log, "[%s]: The server asked for a new handshake, entering handshake loop", ctx->id); result = secure_schannel_handshake_loop(comm, 0); if (result!=BOLT_SUCCESS) { break; } } if (status==SEC_E_OK) { result = BOLT_SUCCESS; ctx->recv_buffer_pos = 0; break; } } return result; } int secure_schannel_destroy(BoltCommunication* comm) { SChannelContext* ctx = comm->context; if (ctx==NULL) { return BOLT_SUCCESS; } if (ctx->context_handle!=NULL) { DeleteSecurityContext(ctx->context_handle); BoltMem_deallocate(ctx->context_handle, sizeof(CtxtHandle)); ctx->context_handle = NULL; } if (ctx->stream_sizes!=NULL) { BoltMem_deallocate(ctx->stream_sizes, sizeof(SecPkgContext_StreamSizes)); ctx->stream_sizes = NULL; } if (ctx->send_buffer!=NULL) { BoltMem_deallocate(ctx->send_buffer, ctx->send_buffer_length); ctx->send_buffer_length = 0; ctx->send_buffer = NULL; } if (ctx->recv_buffer!=NULL) { BoltMem_deallocate(ctx->recv_buffer, ctx->recv_buffer_length); ctx->recv_buffer_length = 0; ctx->recv_buffer_pos = 0; ctx->recv_buffer = NULL; } if (ctx->hs_buffer!=NULL) { BoltMem_deallocate(ctx->hs_buffer, ctx->hs_buffer_length); ctx->hs_buffer = NULL; ctx->hs_buffer_length = 0; ctx->hs_buffer_pos = 0; } if (ctx->sec_ctx!=NULL && ctx->owns_sec_ctx) { BoltSecurityContext_destroy(ctx->sec_ctx); ctx->sec_ctx = NULL; ctx->owns_sec_ctx = 0; } BoltCommunication_destroy(ctx->plain_comm); BoltMem_deallocate(ctx->hostname, strlen(ctx->hostname)+1); BoltMem_deallocate(ctx->id, strlen(ctx->id)+1); BoltMem_deallocate(ctx, sizeof(SChannelContext)); comm->context = NULL; return BOLT_SUCCESS; } BoltAddress* secure_schannel_local_endpoint(BoltCommunication* comm) { SChannelContext* ctx = comm->context; return ctx->plain_comm->get_local_endpoint(ctx->plain_comm); } BoltAddress* secure_schannel_remote_endpoint(BoltCommunication* comm) { SChannelContext* ctx = comm->context; return ctx->plain_comm->get_remote_endpoint(ctx->plain_comm); } int secure_schannel_ignore_sigpipe(BoltCommunication* comm) { SChannelContext* ctx = comm->context; return ctx->plain_comm->ignore_sigpipe(ctx->plain_comm); } int secure_schannel_restore_sigpipe(BoltCommunication* comm) { SChannelContext* ctx = comm->context; return ctx->plain_comm->restore_sigpipe(ctx->plain_comm); } BoltCommunication* BoltCommunication_create_secure(BoltSecurityContext* sec_ctx, BoltTrust* trust, BoltSocketOptions* socket_options, BoltLog* log, const char* hostname, const char* id) { BoltCommunication* plain_comm = BoltCommunication_create_plain(socket_options, log); BoltCommunication* comm = BoltMem_allocate(sizeof(BoltCommunication)); comm->open = &secure_schannel_open; comm->close = &secure_schannel_close; comm->send = &secure_schannel_send; comm->recv = &secure_schannel_recv; comm->destroy = &secure_schannel_destroy; comm->get_local_endpoint = &secure_schannel_local_endpoint; comm->get_remote_endpoint = &secure_schannel_remote_endpoint; comm->ignore_sigpipe = &secure_schannel_ignore_sigpipe; comm->restore_sigpipe = &secure_schannel_restore_sigpipe; comm->status_owned = 0; comm->status = plain_comm->status; comm->sock_opts_owned = 0; comm->sock_opts = plain_comm->sock_opts; comm->log = log; SChannelContext* context = BoltMem_allocate(sizeof(SChannelContext)); context->sec_ctx = sec_ctx; context->owns_sec_ctx = sec_ctx==NULL; context->context_handle = NULL; context->stream_sizes = NULL; context->recv_buffer = NULL; context->recv_buffer_pos = 0; context->recv_buffer_length = 0; context->pt_pending_buffer = NULL; context->pt_pending_buffer_pos = 0; context->pt_pending_buffer_length = 0; context->ct_pending_buffer = NULL; context->ct_pending_buffer_length = 0; context->send_buffer = NULL; context->send_buffer_length = 0; context->hs_buffer_length = 16*1024; context->hs_buffer_pos = 0; context->hs_buffer = BoltMem_allocate(context->hs_buffer_length); context->trust = trust; context->plain_comm = plain_comm; context->id = BoltMem_duplicate(id, strlen(id)+1); context->hostname = BoltMem_duplicate(hostname, strlen(hostname)+1); comm->context = context; return comm; } int secure_schannel_disconnect(BoltCommunication* comm) { SecBufferDesc out_buf; SecBuffer out_bufs[1]; SECURITY_STATUS status; int result = BOLT_SUCCESS; SChannelContext* ctx = comm->context; // Generate a shutdown token int control_token = SCHANNEL_SHUTDOWN; out_bufs[0].pvBuffer = &control_token; out_bufs[0].BufferType = SECBUFFER_TOKEN; out_bufs[0].cbBuffer = sizeof(control_token); out_buf.cBuffers = 1; out_buf.pBuffers = out_bufs; out_buf.ulVersion = SECBUFFER_VERSION; status = ApplyControlToken(ctx->context_handle, &out_buf); if (status!=SEC_E_OK) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: Unable to generate shutdown token: ApplyControlToken returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_disconnect(%s:%d), ApplyControlToken error code: 0x%x", __FILE__, __LINE__, status); return BOLT_STATUS_SET; } // Generate the actual message sequence DWORD sspi_flags_requested = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; DWORD sspi_flags_got; out_bufs[0].pvBuffer = NULL; out_bufs[0].BufferType = SECBUFFER_TOKEN; out_bufs[0].cbBuffer = 0; out_buf.cBuffers = 1; out_buf.pBuffers = out_bufs; out_buf.ulVersion = SECBUFFER_VERSION; status = InitializeSecurityContext(ctx->sec_ctx->cred_handle, ctx->context_handle, NULL, sspi_flags_requested, 0, SECURITY_NATIVE_DREP, NULL, 0, ctx->context_handle, &out_buf, &sspi_flags_got, NULL); if (status!=SEC_E_OK) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: Unable to generate shutdown token: InitializeSecurityToken returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_disconnect(%s:%d), InitializeSecurityToken error code: 0x%x", __FILE__, __LINE__, status); return BOLT_STATUS_SET; } // Send out the shutdown token to the server char* msg = out_bufs[0].pvBuffer; DWORD msg_length = (int) out_bufs[0].cbBuffer; DWORD msg_sent = 0; while (msg_sent<msg_length) { int sent = 0; result = ctx->plain_comm->send(ctx->plain_comm, msg+msg_sent, msg_length-msg_sent, &sent); if (result!=BOLT_SUCCESS) { break; } msg_sent += sent; } if (out_bufs[0].pvBuffer!=NULL) { FreeContextBuffer(out_bufs[0].pvBuffer); } return result; } int secure_schannel_handshake(BoltCommunication* comm) { SecBufferDesc out_buf; SecBuffer out_bufs[1]; SECURITY_STATUS status; SChannelContext* ctx = comm->context; DWORD sspi_flags_requested = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; DWORD sspi_flags_got; out_bufs[0].pvBuffer = NULL; out_bufs[0].BufferType = SECBUFFER_TOKEN; out_bufs[0].cbBuffer = 0; out_buf.cBuffers = 1; out_buf.pBuffers = out_bufs; out_buf.ulVersion = SECBUFFER_VERSION; status = InitializeSecurityContext(ctx->sec_ctx->cred_handle, NULL, ctx->hostname, sspi_flags_requested, 0, SECURITY_NATIVE_DREP, NULL, 0, ctx->context_handle, &out_buf, &sspi_flags_got, NULL); if (status!=SEC_I_CONTINUE_NEEDED) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: TLS handshake initialization failed: InitializeSecurityToken returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_handshake(%s:%d), InitializeSecurityToken error code: 0x%x", __FILE__, __LINE__, status); return BOLT_STATUS_SET; } char* msg = out_bufs[0].pvBuffer; DWORD msg_length = out_bufs[0].cbBuffer; if (msg!=NULL && msg_length!=0) { DWORD msg_sent = 0; int result = BOLT_SUCCESS; while (msg_sent<msg_length) { int sent = 0; result = ctx->plain_comm->send(ctx->plain_comm, msg+msg_sent, (int) (msg_length-msg_sent), &sent); if (result!=BOLT_SUCCESS) { break; } msg_sent += sent; } FreeContextBuffer(out_bufs[0].pvBuffer); if (result!=BOLT_SUCCESS) { return result; } } return secure_schannel_handshake_loop(comm, 1); } int secure_schannel_handshake_loop(BoltCommunication* comm, int do_initial_read) { int result = BOLT_SUCCESS; SChannelContext* ctx = comm->context; SecBufferDesc in_buf; SecBuffer in_bufs[2]; SecBufferDesc out_buf; SecBuffer out_bufs[1]; memset(in_bufs, 0, sizeof(in_bufs)); memset(out_bufs, 0, sizeof(out_bufs)); DWORD sspi_flags_requested = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; DWORD sspi_flags_got; int do_read = do_initial_read; SECURITY_STATUS status = SEC_I_CONTINUE_NEEDED; while (status==SEC_I_CONTINUE_NEEDED || status==SEC_E_INCOMPLETE_MESSAGE || status==SEC_I_INCOMPLETE_CREDENTIALS) { if (ctx->hs_buffer_pos==0 || status==SEC_E_INCOMPLETE_MESSAGE) { if (do_read) { int received = 0; result = ctx->plain_comm->recv(ctx->plain_comm, ctx->hs_buffer+ctx->hs_buffer_pos, (int) (ctx->hs_buffer_length-ctx->hs_buffer_pos), &received); if (result!=BOLT_SUCCESS) { break; } ctx->hs_buffer_pos += received; } else { do_read = 1; } } // Set up input buffers. Buffer 0 is used to pass in data received from the server. Schannel will consume // some or all of this. Leftover data (if any) will be placed in buffer 1 and given a buffer type of // SECBUFFER_EXTRA. in_bufs[0].pvBuffer = ctx->hs_buffer; in_bufs[0].cbBuffer = (unsigned long) ctx->hs_buffer_pos; in_bufs[0].BufferType = SECBUFFER_TOKEN; // Free previously allocated buffers if present if (in_bufs[1].pvBuffer!=NULL) { FreeContextBuffer(in_bufs[1].pvBuffer); } in_bufs[1].pvBuffer = NULL; in_bufs[1].cbBuffer = 0; in_bufs[1].BufferType = SECBUFFER_EMPTY; in_buf.cBuffers = 2; in_buf.pBuffers = in_bufs; in_buf.ulVersion = SECBUFFER_VERSION; // Set up output buffers. These are initialized to NULL so as to make it less likely we'll attempt to // free random garbage later. if (out_bufs[0].pvBuffer!=NULL) { FreeContextBuffer(out_bufs[0].pvBuffer); } out_bufs[0].pvBuffer = NULL; out_bufs[0].BufferType = SECBUFFER_TOKEN; out_bufs[0].cbBuffer = 0; out_buf.cBuffers = 1; out_buf.pBuffers = out_bufs; out_buf.ulVersion = SECBUFFER_VERSION; status = InitializeSecurityContext(ctx->sec_ctx->cred_handle, ctx->context_handle, NULL, sspi_flags_requested, 0, SECURITY_NATIVE_DREP, &in_buf, 0, NULL, &out_buf, &sspi_flags_got, NULL); // If InitializeSecurityContext was successful (or if the error was // one of the special extended ones), send the contends of the output // buffer to the server. if (status==SEC_E_OK || status==SEC_I_CONTINUE_NEEDED || (FAILED(status) && (sspi_flags_got & ISC_RET_EXTENDED_ERROR))) { char* msg = out_bufs[0].pvBuffer; DWORD msg_length = out_bufs[0].cbBuffer; if (msg!=NULL && msg_length!=0) { DWORD msg_sent = 0; while (msg_sent<msg_length) { int sent = 0; result = ctx->plain_comm->send(ctx->plain_comm, msg+msg_sent, (int) (msg_length-msg_sent), &sent); if (result!=BOLT_SUCCESS) { goto cleanup; } msg_sent += sent; } } } // If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, then we need to read more data // from the server and try again. if (status==SEC_E_INCOMPLETE_MESSAGE) { continue; } // If InitializeSecurityContext returned SEC_E_OK, then the handshake completed successfully. if (status==SEC_E_OK) { // If the "extra" buffer contains data, this is encrypted application protocol layer stuff. It // needs to be saved. The application layer will later decrypt it with DecryptMessage. if (in_bufs[1].BufferType==SECBUFFER_EXTRA) { MoveMemory(ctx->recv_buffer+ctx->recv_buffer_pos, in_bufs[1].pvBuffer, in_bufs[1].cbBuffer); ctx->ct_pending_buffer = ctx->recv_buffer+ctx->recv_buffer_pos; ctx->ct_pending_buffer_length = in_bufs[1].cbBuffer; } result = BOLT_SUCCESS; break; } if (FAILED(status)) { log_with_sec_stat(comm->log, &BoltLog_error, status, "[%s]: TLS handshake loop failed: InitializeSecurityToken returned 0x%x: '%s'", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_handshake_loop(%s:%d), InitializeSecurityToken error code: 0x%x", __FILE__, __LINE__, status); result = BOLT_STATUS_SET; break; } // If InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS, // then the server just requested client authentication. if (status==SEC_I_INCOMPLETE_CREDENTIALS) { BoltLog_error(comm->log, "[%s]: TLS mutual authentication is not supported.", ctx->id); BoltStatus_set_error_with_ctx(comm->status, BOLT_TLS_ERROR, "secure_schannel_handshake_loop(%s:%d), TLS mutual authentication is not supported", __FILE__, __LINE__); result = BOLT_STATUS_SET; break; } if (in_bufs[1].BufferType==SECBUFFER_EXTRA) { MoveMemory(ctx->hs_buffer, in_bufs[1].pvBuffer, in_bufs[1].cbBuffer); ctx->hs_buffer_pos = in_bufs[1].cbBuffer; } else { ctx->hs_buffer_pos = 0; } } cleanup: if (in_bufs[1].pvBuffer!=NULL) { FreeContextBuffer(in_bufs[1].pvBuffer); } if (out_bufs[0].pvBuffer!=NULL) { FreeContextBuffer(out_bufs[0].pvBuffer); } return result; }
ak15/seabolt
<|start_filename|>node_modules/vue-play/app.js<|end_filename|> require('./dist/app.css') module.exports = require('./dist/app') <|start_filename|>node_modules/vue-play/preview.js<|end_filename|> module.exports = require('./dist/preview') <|start_filename|>node_modules/vue-play/index.js<|end_filename|> module.exports = require('./dist/play')
XuanPH/steyr-frontend
<|start_filename|>test/Serilog.Enrichers.Process.Tests/Enrichers/ProcessNameEnricherTests.cs<|end_filename|> using Serilog.Events; using Serilog.Tests.Support; using Xunit; namespace Serilog.Enrichers.Process.Tests { public class ProcessNameEnricherTests { [Fact] public void ProcessNameEnricherIsApplied() { LogEvent evt = null; var log = new LoggerConfiguration() .Enrich.WithProcessName() .WriteTo.Sink(new DelegatingSink(e => evt = e)) .CreateLogger(); log.Information(@"Has a ProcessName property"); Assert.NotNull(evt); var processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; Assert.Equal(processName, (string)evt.Properties["ProcessName"].LiteralValue()); } } } <|start_filename|>test/Serilog.Enrichers.Process.Tests/Enrichers/ProcessIdEnricherTests.cs<|end_filename|> using Serilog.Events; using Serilog.Tests.Support; using Xunit; namespace Serilog.Enrichers.Process.Tests { public class ProcessIdEnricherTests { [Fact] public void ProcessIdEnricherIsApplied() { LogEvent evt = null; var log = new LoggerConfiguration() .Enrich.WithProcessId() .WriteTo.Sink(new DelegatingSink(e => evt = e)) .CreateLogger(); log.Information(@"Has a ProcessId property"); Assert.NotNull(evt); var processId = System.Diagnostics.Process.GetCurrentProcess().Id; Assert.Equal(processId, (int)evt.Properties["ProcessId"].LiteralValue()); } } }
Numpsy/serilog-enrichers-process
<|start_filename|>src/niftypkg/help.json<|end_filename|> { "help": { "_syntax": "help [<command>]", "_description": "Display help on the specified command (or all commands)." }, "info": { "_syntax": "info <package>", "_description": "Displays information on <package>" }, "init": { "_syntax": "init [<storage-dir>]", "_description": "Initializes a project in the current directory (using <storage-dir> as storage directory)." }, "list": { "_syntax": "list", "_description": "Lists all dependencies (recursively) of the current project." }, "map": { "_syntax": "map <package>", "_description": "Configures a new or existing package <package>." }, "purge": { "_syntax": "purge", "_description": "Deletes the storage directory and all its contents." }, "remove": { "_syntax": "remove [<package>]", "_description": "Physically deletes the specified package (or all packages) from the storage directory." }, "unmap": { "_syntax": "unmap <package>", "_description": "Unmaps the previously-mapped package <package>." }, "update": { "_syntax": "update", "_description": "Updates the command definitions for the current project and migrate nifty.json file (if necessary)." } }
AvdN/nifty
<|start_filename|>apis/more.js<|end_filename|> var niceAgo = require('nice-ago') var pull = require('pull-stream') var u = require('yap-util') module.exports = function (sbot) { return function (opts, apply) { var _opts = u.createQuery(opts, {limit: 1}) return function (cb) { pull( sbot.query.read(_opts), pull.collect(function (err, ary) { //check if there are more messages in this direction cb(err, ['a'+(ary.length ? '.more' : '.no-more'), Object.assign( { href: opts.href, title: opts.title }, apply.cacheAttrs(apply.toUrl('more', opts), 'more', apply.since) ), opts.label ]) }) ) } } } <|start_filename|>apis/message.js<|end_filename|> var ref = require('ssb-ref') var niceAgo = require('nice-ago') var htmlEscape = require('html-escape') var u = require('yap-util') var h = u.h toUrl = u.toUrl module.exports = u.createRenderer(function render (data, apply) { return apply(['messages', data.value.content.type], data) }) <|start_filename|>apis/search.js<|end_filename|> var pull = require('pull-stream') var ref = require('ssb-ref') function isChannel (c) { return /^#\w+/.test(c) } function isName (c) { return /^@\w+/.test(c) } module.exports = function (sbot) { return function (opts, apply, req) { console.log("SEARCH", opts) var tr = require('../translations')(req.cookies.lang) var query = (opts.query || '').trim() delete opts.query opts.limit = opts.limit ? +opts.limit : 10 if(ref.isMsgLink(query)) return apply('message', {id: query}) if(ref.isFeed(query)) return apply('patch/public', Object.assign(opts, {id: query})) if(isChannel(query)) return apply('patch/public', Object.assign(opts, {channel: query.substring(1)})) if(isName(query)) //is name return function (cb) { sbot.names.getSignifies(query.substring(1), function (err, ids) { if(err) return cb(err) if(ids.length == 0) cb(null, ['h1', tr('NoFeedNamed'), query]) else if(ids.length == 1) cb(null, apply('patch/public', {author: ids[0].id})) else cb(null, ['div', ['div', query, ' ', tr('MayAlsoBe')].concat(ids.slice(1).map(function (e) { return apply('avatar', {id: e.id, name: false}) })), apply('patch/public', {author: ids[0].id}) ]) }) } return pull( sbot.search.query(Object.assign({query: query}, opts)), pull.map(function (data) { console.log('result', data) return apply('message', data) }) ) } } <|start_filename|>message-layout.js<|end_filename|> var u = require('yap-util') var ref = require('ssb-ref') var niceAgo = require('nice-ago') var toUrl = u.toUrl module.exports = function (opts, apply) { return ['div.Message', apply.cacheAttrs(toUrl('message', {id: opts.key}), opts.key, apply.since), ['div.MessageSide', apply('avatar', {id: opts.author, name: false, image: true}), ['a', { href: toUrl('message', {id: opts.id || opts.key}), title: new Date(opts.ts)+'\n'+opts.key }, ''+niceAgo(Date.now(), opts.ts) ] ], ['div.MessageMain', ['div.MessageMeta', apply('avatar', {id: opts.author, name: true, image: false}), ['label.msgId', opts.id], opts.meta ? opts.meta : '' ], ['div.MessageContent', opts.content], opts.extra && ['div.MessageExtra', apply('extra', {id: opts.key || opts.id, root: opts.root, branch: opts.branch})] ] ] } <|start_filename|>apis/backlinks.js<|end_filename|> function backlinks (sbot, id, cb) { var likes = [], backlinks = [] pull( sbot.links({dest: id, values: true}), pull.drain(function (e) { var content = e.value.content var vote = content.vote if(isObject(vote) && vote.value == 1 && vote.link == id) likes.push(e) else if(content.type == 'post' && isArray(content.mentions)) { for(var i in content.mentions) { var m = content.mentions[i] if(m && m.link == id) { backlinks.push(e) return //if something links twice, don't back link it twice } } } }, function () { cb(null, likes, backlinks) }) ) } //XXX should backlinks be built into the layout? //i.e. assumed to always be a part of the thing? module.exports = function (sbot) { return function (opts) { return function (cb) { backlinks(sbot, opts.id, function (err, votes, backlinks) { }) } } }
dominictarr/yap
<|start_filename|>packages/bslib/lib/bs-a11y-p/src/js/carousel.js<|end_filename|> // Carousel Extension // =============================== $('.carousel').each(function (index) { // This function positions a highlight box around the tabs in the tablist to use in focus styling function setTablistHighlightBox() { var $tab , offset , height , width , highlightBox = {} highlightBox.top = 0 highlightBox.left = 32000 highlightBox.height = 0 highlightBox.width = 0 for (var i = 0; i < $tabs.length; i++) { $tab = $tabs[i] offset = $($tab).offset() height = $($tab).height() width = $($tab).width() // console.log(" Top: " + offset.top + " Left: " + offset.left + " Height: " + height + " Width: " + width) if (highlightBox.top < offset.top) { highlightBox.top = Math.round(offset.top) } if (highlightBox.height < height) { highlightBox.height = Math.round(height) } if (highlightBox.left > offset.left) { highlightBox.left = Math.round(offset.left) } var w = (offset.left - highlightBox.left) + Math.round(width) if (highlightBox.width < w) { highlightBox.width = w } } // end for // console.log("[HIGHLIGHT] Top: " + highlightBox.top + " Left: " + highlightBox.left + " Height: " + highlightBox.height + " Width: " + highlightBox.width) $tablistHighlight.style.top = (highlightBox.top - 2) + 'px' $tablistHighlight.style.left = (highlightBox.left - 2) + 'px' $tablistHighlight.style.height = (highlightBox.height + 7) + 'px' $tablistHighlight.style.width = (highlightBox.width + 8) + 'px' } // end function var $this = $(this) , $prev = $this.find('[data-slide="prev"]') , $next = $this.find('[data-slide="next"]') , $tablist = $this.find('.carousel-indicators') , $tabs = $this.find('.carousel-indicators li') , $tabpanels = $this.find('.item') , $tabpanel , $tablistHighlight , $pauseCarousel , $complementaryLandmark , $tab , $is_paused = false , offset , height , width , i , id_title = 'id_title' , id_desc = 'id_desc' $tablist.attr('role', 'tablist') $tabs.focus(function() { $this.carousel('pause') $is_paused = true $pauseCarousel.innerHTML = "Play Carousel" $(this).parent().addClass('active'); // $(this).addClass('focus') setTablistHighlightBox() $($tablistHighlight).addClass('focus') $(this).parents('.carousel').addClass('contrast') }) $tabs.blur(function(event) { $(this).parent().removeClass('active'); // $(this).removeClass('focus') $($tablistHighlight).removeClass('focus') $(this).parents('.carousel').removeClass('contrast') }) for (i = 0; i < $tabpanels.length; i++) { $tabpanel = $tabpanels[i] $tabpanel.setAttribute('role', 'tabpanel') $tabpanel.setAttribute('id', 'tabpanel-' + index + '-' + i) $tabpanel.setAttribute('aria-labelledby', 'tab-' + index + '-' + i) } if (typeof $this.attr('role') !== 'string') { $this.attr('role', 'complementary'); $this.attr('aria-labelledby', id_title); $this.attr('aria-describedby', id_desc); $this.prepend('<p id="' + id_desc + '" class="sr-only">A carousel is a rotating set of images, rotation stops on keyboard focus on carousel tab controls or hovering the mouse pointer over images. Use the tabs or the previous and next buttons to change the displayed slide.</p>') $this.prepend('<h2 id="' + id_title + '" class="sr-only">Carousel content with ' + $tabpanels.length + ' slides.</h2>') } for (i = 0; i < $tabs.length; i++) { $tab = $tabs[i] $tab.setAttribute('role', 'tab') $tab.setAttribute('id', 'tab-' + index + '-' + i) $tab.setAttribute('aria-controls', 'tabpanel-' + index + '-' + i) var tpId = '#tabpanel-' + index + '-' + i var caption = $this.find(tpId).find('h1').text() if ((typeof caption !== 'string') || (caption.length === 0)) caption = $this.find(tpId).text() if ((typeof caption !== 'string') || (caption.length === 0)) caption = $this.find(tpId).find('h3').text() if ((typeof caption !== 'string') || (caption.length === 0)) caption = $this.find(tpId).find('h4').text() if ((typeof caption !== 'string') || (caption.length === 0)) caption = $this.find(tpId).find('h5').text() if ((typeof caption !== 'string') || (caption.length === 0)) caption = $this.find(tpId).find('h6').text() if ((typeof caption !== 'string') || (caption.length === 0)) caption = "no title"; // console.log("CAPTION: " + caption ) var tabName = document.createElement('span') tabName.setAttribute('class', 'sr-only') tabName.innerHTML='Slide ' + (i+1) if (caption) tabName.innerHTML += ": " + caption $tab.appendChild(tabName) } // create div for focus styling of tablist $tablistHighlight = document.createElement('div') $tablistHighlight.className = 'carousel-tablist-highlight' document.body.appendChild($tablistHighlight) // create button for screen reader users to stop rotation of carousel // create button for screen reader users to pause carousel for virtual mode review $complementaryLandmark = document.createElement('aside') $complementaryLandmark.setAttribute('class', 'carousel-aside-pause') $complementaryLandmark.setAttribute('aria-label', 'carousel pause/play control') $this.prepend($complementaryLandmark) $pauseCarousel = document.createElement('button') $pauseCarousel.className = "carousel-pause-button" $pauseCarousel.innerHTML = "Pause Carousel" $pauseCarousel.setAttribute('title', "Pause/Play carousel button can be used by screen reader users to stop carousel animations") $($complementaryLandmark).append($pauseCarousel) $($pauseCarousel).click(function() { if ($is_paused) { $pauseCarousel.innerHTML = "Pause Carousel" $this.carousel('cycle') $is_paused = false } else { $pauseCarousel.innerHTML = "Play Carousel" $this.carousel('pause') $is_paused = true } }) $($pauseCarousel).focus(function() { $(this).addClass('focus') }) $($pauseCarousel).blur(function() { $(this).removeClass('focus') }) setTablistHighlightBox() $( window ).resize(function() { setTablistHighlightBox() }) // Add space bar behavior to prev and next buttons for SR compatibility $prev.attr('aria-label', 'Previous Slide') $prev.keydown(function(e) { var k = e.which || e.keyCode if (/(13|32)/.test(k)) { e.preventDefault() e.stopPropagation() $prev.trigger('click'); } }); $prev.focus(function() { $(this).parents('.carousel').addClass('contrast') }) $prev.blur(function() { $(this).parents('.carousel').removeClass('contrast') }) $next.attr('aria-label', 'Next Slide') $next.keydown(function(e) { var k = e.which || e.keyCode if (/(13|32)/.test(k)) { e.preventDefault() e.stopPropagation() $next.trigger('click'); } }); $next.focus(function() { $(this).parents('.carousel').addClass('contrast') }) $next.blur(function() { $(this).parents('.carousel').removeClass('contrast') }) $('.carousel-inner a').focus(function() { $(this).parents('.carousel').addClass('contrast') }) $('.carousel-inner a').blur(function() { $(this).parents('.carousel').removeClass('contrast') }) $tabs.each(function () { var item = $(this) if(item.hasClass('active')) { item.attr({ 'aria-selected': 'true', 'tabindex' : '0' }) }else{ item.attr({ 'aria-selected': 'false', 'tabindex' : '-1' }) } }) }) var slideCarousel = $.fn.carousel.Constructor.prototype.slide $.fn.carousel.Constructor.prototype.slide = function (type, next) { var $element = this.$element , $active = $element.find('[role=tabpanel].active') , $next = next || $active[type]() , $tab , $tab_count = $element.find('[role=tabpanel]').length , $prev_side = $element.find('[data-slide="prev"]') , $next_side = $element.find('[data-slide="next"]') , $index = 0 , $prev_index = $tab_count -1 , $next_index = 1 , $id if ($next && $next.attr('id')) { $id = $next.attr('id') $index = $id.lastIndexOf("-") if ($index >= 0) $index = parseInt($id.substring($index+1), 10) $prev_index = $index - 1 if ($prev_index < 1) $prev_index = $tab_count - 1 $next_index = $index + 1 if ($next_index >= $tab_count) $next_index = 0 } $prev_side.attr('aria-label', 'Show slide ' + ($prev_index+1) + ' of ' + $tab_count) $next_side.attr('aria-label', 'Show slide ' + ($next_index+1) + ' of ' + $tab_count) slideCarousel.apply(this, arguments) $active .one('bsTransitionEnd', function () { var $tab $tab = $element.find('li[aria-controls="' + $active.attr('id') + '"]') if ($tab) $tab.attr({'aria-selected':false, 'tabIndex': '-1'}) $tab = $element.find('li[aria-controls="' + $next.attr('id') + '"]') if ($tab) $tab.attr({'aria-selected': true, 'tabIndex': '0'}) }) } var $this; $.fn.carousel.Constructor.prototype.keydown = function (e) { $this = $this || $(this) if(this instanceof Node) $this = $(this) function selectTab(index) { if (index >= $tabs.length) return if (index < 0) return $carousel.carousel(index) setTimeout(function () { $tabs[index].focus() // $this.prev().focus() }, 150) } var $carousel = $(e.target).closest('.carousel') , $tabs = $carousel.find('[role=tab]') , k = e.which || e.keyCode , index if (!/(37|38|39|40)/.test(k)) return index = $tabs.index($tabs.filter('.active')) if (k == 37 || k == 38) { // Up index-- selectTab(index); } if (k == 39 || k == 40) { // Down index++ selectTab(index); } e.preventDefault() e.stopPropagation() } $(document).on('keydown.carousel.data-api', 'li[role=tab]', $.fn.carousel.Constructor.prototype.keydown);
gregorbj/FSDM-Simple-Install
<|start_filename|>lib/liquid/tags/include.js<|end_filename|> const Liquid = require('../../liquid') const Syntax = /((?:{{2}\s?)?[a-z0-9/\\_.-]+(?:\s?}{2})?)/i const SyntaxHelp = "Syntax Error in 'include' - Valid syntax: include [templateName]" module.exports = class Include extends Liquid.Tag { constructor (template, tagName, markup) { super(template, tagName, markup) const match = Syntax.exec(markup) if (!match) { throw new Liquid.SyntaxError(SyntaxHelp) } this.filepath = match[1] } async subTemplate (context) { if (this.filepath.startsWith('{{') && this.filepath.endsWith('}}')) { this.filepath = await context.get(this.filepath) } const src = await this.template .engine .fileSystem .readTemplateFile(this.filepath) return this.template.engine.parse(src) } async render (context) { const subTemplate = await this.subTemplate(context) return subTemplate.render(context) } } <|start_filename|>lib/liquid/context.js<|end_filename|> const Liquid = require('../liquid') const squareBracketed = /^\[(.*)\]$/ class Context { constructor ( engine, environments = {}, outerScope = {}, registers = {}, rethrowErrors = false ) { this.environments = Liquid.Helpers.flatten([environments]) this.scopes = [outerScope] this.registers = registers this.errors = [] this.rethrowErrors = rethrowErrors this.strainer = engine ? new engine.Strainer(this) : {} this.squashInstanceAssignsWithEnvironments() } registerFilters (...filters) { for (const filter of filters) { for (const key in filter) { if (!Object.prototype.hasOwnProperty.call(filter, key)) continue const value = filter[key] if (value instanceof Function) { this.strainer[key] = value } } } } handleError (e) { this.errors.push(e) if (this.rethrowErrors) { throw e } if (e instanceof Liquid.SyntaxError) { return 'Liquid syntax error: ' + e.message } else { return 'Liquid error: ' + e.message } } invoke (methodName, ...args) { const method = this.strainer[methodName] if (method instanceof Function) { return method.apply(this.strainer, args) } else { const available = Object.keys(this.strainer) throw new Liquid.FilterNotFound('Unknown filter `' + methodName + '`, available: [' + (available.join(', ')) + ']') } } push (newScope = {}) { this.scopes.unshift(newScope) if (this.scopes.length > 100) { throw new Error('Nesting too deep') } } merge (newScope = {}) { const results = [] for (const key in newScope) { if (!Object.prototype.hasOwnProperty.call(newScope, key)) continue const v = newScope[key] results.push(this.scopes[0][key] = v) } return results } pop () { if (this.scopes.length <= 1) { throw new Error('ContextError') } return this.scopes.shift() } lastScope () { return this.scopes[this.scopes.length - 1] } stack (newScope = {}, f) { let popLater = false try { if (arguments.length < 2) { f = newScope newScope = {} } this.push(newScope) const result = f() if (result && result.nodeify) { popLater = true result.nodeify(() => this.pop()) } return result } finally { if (!popLater) { this.pop() } } } clearInstanceAssigns () { this.scopes[0] = {} } set (key, value) { this.scopes[0][key] = value } async get (key) { return this.resolve(key) } async hasKey (key) { const value = await this.resolve(key) return value != null } async resolve (key) { let match if (Liquid.Context.Literals.hasOwnProperty(key)) { return Liquid.Context.Literals[key] } else if (match = /^'(.*)'$/.exec(key)) { // eslint-disable-line return match[1] } else if (match = /^"(.*)"$/.exec(key)) { // eslint-disable-line return match[1] } else if (match = /^(\d+)$/.exec(key)) { // eslint-disable-line return Number(match[1]) } else if (match = /^\((\S+)\.\.(\S+)\)$/.exec(key)) { // eslint-disable-line const loHi = [match[1], match[2]] const [loArg, hiArg] = await Promise.all(loHi.map(async arg => { const value = await this.resolve(arg) return Number(value) })) if (isNaN(loArg) || isNaN(hiArg)) { return [] } return new Liquid.Range(loArg, hiArg + 1) } else if (match = /^(\d[\d.]+)$/.exec(key)) { // eslint-disable-line return Number(match[1]) } else { return this.variable(key) } } async findVariable (key) { let variableScope = this.scopes.find((scope) => { return Object.prototype.hasOwnProperty.call(scope, key) }) let variable if (variableScope == null) { this.environments.some(env => { variable = this.lookupAndEvaluate(env, key) if (variable != null) { variableScope = env return variableScope } }) } if (variableScope == null) { if (this.environments.length > 0) { variableScope = this.environments[this.environments.length - 1] } else if (this.scopes.length > 0) { variableScope = this.scopes[this.scopes.length - 1] } else { throw new Error('No scopes to find variable in.') } } if (variable == null) { variable = this.lookupAndEvaluate(variableScope, key) } return this.liquify(variable) } async mapper (part, object) { if (object == null) { return object } object = await this.liquify(object) if (object == null) { return object } const bracketMatch = squareBracketed.exec(part) if (bracketMatch) { part = await this.resolve(bracketMatch[1]) } const isArrayAccess = Array.isArray(object) && isFinite(part) const isObjectAccess = object instanceof Object && ((typeof object.hasKey === 'function' ? object.hasKey(part) : void 0) || part in object) const isSpecialAccess = !bracketMatch && object && (Array.isArray(object) || Object.prototype.toString.call(object) === '[object String]') && ['size', 'first', 'last'].indexOf(part) >= 0 if (isArrayAccess || isObjectAccess) { const evaluated = await this.lookupAndEvaluate(object, part) return this.liquify(evaluated) } else if (isSpecialAccess) { switch (part) { case 'size': return this.liquify(object.length) case 'first': return this.liquify(object[0]) case 'last': return this.liquify(object[object.length - 1]) default: /* @covignore */ throw new Error('Unknown special accessor: ' + part) } } } async variable (markup) { const parts = Liquid.Helpers.scan(markup, Liquid.VariableParser) let firstPart = parts.shift() const match = squareBracketed.exec(firstPart) if (match) { firstPart = match[1] } const object = await this.findVariable(firstPart) if (parts.length === 0) { return object } const iterator = async (object, index) => { if (index < parts.length) { const o = await this.mapper(parts[index], object) return iterator(o, index + 1) } else { return object } } try { return iterator(object, 0) } catch (err) { throw new Error("Couldn't walk variable: " + markup + ': ' + err) } } lookupAndEvaluate (obj, key) { if (obj instanceof Liquid.Drop) { return obj.get(key) } else { return obj != null ? obj[key] : void 0 } } squashInstanceAssignsWithEnvironments () { const lastScope = this.lastScope() return Object.keys(lastScope).forEach(key => { return this.environments.some(env => { if (env.hasOwnProperty(key)) { lastScope[key] = this.lookupAndEvaluate(env, key) return true } }) }) } async liquify (object) { if (object == null) { return object } else if (typeof object.toLiquid === 'function') { object = object.toLiquid() } else if (typeof object === 'object') { true // eslint-disable-line } else if (typeof object === 'function') { object = '' } else { Object.prototype.toString.call(object) } if (object instanceof Liquid.Drop) { object.context = this } return object } } Context.Literals = { 'null': null, 'nil': null, '': null, 'true': true, 'false': false } module.exports = Context <|start_filename|>test/engine.js<|end_filename|> const Liquid = require('..') describe('Engine', function () { beforeEach(function () { this.filters = Liquid.StandardFilters }) it('should create strainers', function () { const engine = new Liquid.Engine() const strainer = new engine.Strainer() return expect(strainer.size).to.exist }) return it('should create separate strainers', function () { const engine1 = new Liquid.Engine() engine1.registerFilters({ foo1 () { return 'foo1' } }) const strainer1 = new engine1.Strainer() expect(typeof strainer1.size).to.equal('function') expect(typeof strainer1.foo1).to.equal('function') const engine2 = new Liquid.Engine() engine2.registerFilters({ foo2 () { return 'foo2' } }) const strainer2 = new engine2.Strainer() expect(typeof strainer2.size).to.equal('function') expect(typeof strainer2.foo2).to.equal('function') expect(strainer1.foo2).to.equal(undefined) return expect(strainer2.foo1).to.equal(undefined) }) }) <|start_filename|>lib/liquid/helpers.js<|end_filename|> module.exports = { flatten: array => { const output = [] const _flatten = childArray => { return childArray.forEach(item => { if (Array.isArray(item)) { return _flatten(item) } else { return output.push(item) } }) } _flatten(array) return output }, toFlatString: function (array) { return this.flatten(array).join('') }, scan: (string, regexp, globalMatch = false) => { const result = [] const _scan = s => { const match = regexp.exec(s) if (!match) return if (match.length === 1) { result.push(match[0]) } else { result.push(match.slice(1)) } const l = globalMatch ? 1 : match[0].length if (match.index + l < s.length) { return _scan(s.substring(match.index + l)) } } _scan(string) return result } } <|start_filename|>test/variables.js<|end_filename|> const Liquid = require('..') const util = require('util') describe('Liquid.Variable', function () { it('is parsed', function () { const variable = new Liquid.Variable('hello') return expect(variable.name).to.equal('hello') }) it('parses filters', function () { const v = new Liquid.Variable('hello | textileze') expect('hello').to.equal(v.name) return expect([['textileze', []]]).to.deep.equal(v.filters) }) it('parses multiple filters', function () { const v = new Liquid.Variable('hello | textileze | paragraph') expect('hello').to.equal(v.name) return expect([['textileze', []], ['paragraph', []]]).to.deep.equal(v.filters) }) it('parses filters with arguments', function () { const v = new Liquid.Variable("hello | strftime: '%Y'") expect('hello').to.equal(v.name) return expect([['strftime', ["'%Y'"]]]).to.deep.equal(v.filters) }) it('parses filters with a string-argument that contains an argument-separator', function () { const v = new Liquid.Variable("hello | strftime: '%Y, okay?'") expect('hello').to.equal(v.name) return expect([['strftime', ["'%Y, okay?'"]]]).to.deep.equal(v.filters) }) it('parses filters with date formatting parameter', function () { const v = new Liquid.Variable(" '2006-06-06' | date: \"%m/%d/%Y\" ") expect("'2006-06-06'").to.equal(v.name) return expect([['date', ['"%m/%d/%Y"']]]).to.deep.equal(v.filters) }) describe('with multiple arguments', function () { it('parses ', function () { const v = new Liquid.Variable("'typo' | link_to: 'Typo', true") expect("'typo'").to.equal(v.name) return expect([['link_to', ["'Typo'", 'true']]]).to.deep.equal(v.filters) }) it('parses', function () { const v = new Liquid.Variable("'typo' | link_to: 'Typo', false") expect("'typo'").to.equal(v.name) return expect([['link_to', ["'Typo'", 'false']]]).to.deep.equal(v.filters) }) it('parses', function () { const v = new Liquid.Variable("'foo' | repeat: 3") expect("'foo'").to.equal(v.name) return expect([['repeat', ['3']]]).to.deep.equal(v.filters) }) it('parses', function () { const v = new Liquid.Variable("'foo' | repeat: 3, 3") expect("'foo'").to.equal(v.name) return expect([['repeat', ['3', '3']]]).to.deep.equal(v.filters) }) it('parses', function () { const v = new Liquid.Variable("'foo' | repeat: 3, 3, 3") expect("'foo'").to.equal(v.name) return expect([['repeat', ['3', '3', '3']]]).to.deep.equal(v.filters) }) return it('parses when a string-argument contains an argument-separator', function () { const v = new Liquid.Variable(" hello | things: \"%Y, okay?\", 'the other one'") expect('hello').to.equal(v.name) return expect([['things', ['"%Y, okay?"', "'the other one'"]]]).to.deep.equal(v.filters) }) }) it('renders', () => renderTest('worked', '{{ test }}', { test: 'worked' })) it('renders when empty', () => renderTest('', '{{ }}')) it('allows ranges', () => renderTest('1-2-3', '{{ (1..3) | join:"-" }}')) context('with filter', function () { it('renders', function () { const MoneyFilter = { money (input) { return util.format(' $%d ', input) }, money_with_underscore (input) { return util.format(' $%d ', input) } } const context = new Liquid.Context() context.set('var', 1000) context.registerFilters(MoneyFilter) const variable = new Liquid.Variable('var | money') return variable.render(context).then(result => expect(result).to.equal(' $1000 ')) }) it('renders empty string', () => renderTest('', '{{ test | append: "" }}', {})) return it('renders on unknown filter', () => renderTest(/filter 'doesNotExist' in ' 1 \| doesNotExist ' could not be found/, '{{ 1 | doesNotExist }}', {}, false)) }) // TODO: This doesn't work yet. return it.skip("prevents 'RangeError: Maximum call stack size exceeded'", function () { let doc = '{{ a' while (doc.length < (1024 * 1024)) { doc += '.a' } doc += '.b' doc += ' }}' const a = {} a.a = () => a a.b = () => 'STOP' return renderTest('STOP', doc, { a }) }) }) <|start_filename|>lib/liquid/tags/if.js<|end_filename|> const Liquid = require('../../liquid') const PromiseReduce = require('../../promise_reduce') const SyntaxHelp = "Syntax Error in tag 'if' - Valid syntax: if [expression]" const Syntax = RegExp('(' + Liquid.QuotedFragment.source + ')\\s*([=!<>a-z_]+)?\\s*(' + Liquid.QuotedFragment.source + ')?') const ExpressionsAndOperators = RegExp('(?:\\b(?:\\s?and\\s?|\\s?or\\s?)\\b|(?:\\s*(?!\\b(?:\\s?and\\s?|\\s?or\\s?)\\b)(?:' + Liquid.QuotedFragment.source + '|\\S+)\\s*)+)') module.exports = class If extends Liquid.Block { constructor (template, tagName, markup) { super(template, tagName, markup) this.blocks = [] this.pushBlock('if', markup) } unknownTag (tag, markup) { if (tag === 'elsif' || tag === 'else') { return this.pushBlock(tag, markup) } else { return super.unknownTag(tag, markup) } } defineBlock (tag, markup) { if (tag === 'else') { return new Liquid.ElseCondition() } const expressions = Liquid.Helpers .scan(markup, ExpressionsAndOperators) .reverse() const match = Syntax.exec(expressions.shift()) if (!match) { throw new Liquid.SyntaxError(SyntaxHelp) } let condition = new Liquid.Condition(...match.slice(1, 4)) while (expressions.length > 0) { const operator = String(expressions.shift()).trim() const newMatch = Syntax.exec(expressions.shift()) if (!newMatch) { throw new SyntaxError(SyntaxHelp) } const newCondition = new Liquid.Condition(...newMatch.slice(1, 4)) newCondition[operator].call(newCondition, condition) // eslint-disable-line condition = newCondition } return condition } pushBlock (tag, markup) { const block = this.defineBlock(tag, markup) this.blocks.push(block) this.nodelist = block.attach([]) } async render (context) { const block = await PromiseReduce(this.blocks, async (chosenBlock, block) => { if (chosenBlock != null) return chosenBlock let ok = await block.evaluate(context) if (block.negate) ok = !ok if (ok) return block }, null) return context.stack(async () => { if (block != null) { return this.renderAll(block.attachment, context) } else { return '' } }) } } <|start_filename|>lib/promise_reduce.js<|end_filename|> module.exports = async function reduce (collection, reducer, value) { const items = await Promise.all(collection) return items.reduce(async (promise, item, index, length) => { const value = await promise return reducer(value, item, index, length) }, Promise.resolve(value)) } <|start_filename|>lib/liquid/tag.js<|end_filename|> module.exports = class Tag { constructor (template, tagName, markup) { this.template = template this.tagName = tagName this.markup = markup } async parseWithCallbacks (...args) { if (this.beforeParse) { await this.beforeParse.apply(this, args) } await this.parse.apply(this, args) if (this.afterParse) { await this.afterParse.apply(this, args) } } parse () {} name () { return this.constructor.name.toLowerCase() } render () { return '' } } <|start_filename|>lib/liquid/block.js<|end_filename|> const Liquid = require('../liquid') class Block extends Liquid.Tag { beforeParse () { if (!this.nodelist) { this.nodelist = [] } this.nodelist.length = 0 return this.nodelist.length } afterParse () { return this.assertMissingDelimitation() } async parse (tokens) { if (tokens.length === 0 || this.ended) { return } const token = tokens.shift() try { await this.parseToken(token, tokens) } catch (err) { err.message = err.message + '\n at ' + token.value + ' (' + token.filename + ':' + token.line + ':' + token.col + ')' if (!err.location) { err.location = { col: token.col, line: token.line, filename: token.filename } } throw err } return this.parse(tokens) } async parseToken (token, tokens) { if (Block.IsTag.test(token.value)) { const match = Block.FullToken.exec(token.value) if (!match) { throw new Liquid.SyntaxError("Tag '" + token.value + "' was not properly terminated with regexp: " + Liquid.TagEnd.inspect) } if (this.blockDelimiter() === match[1]) { return this.endTag() } const Tag = this.template.tags[match[1]] if (!Tag) { return this.unknownTag(match[1], match[2], tokens) } const tag = new Tag(this.template, match[1], match[2]) this.nodelist.push(tag) return tag.parseWithCallbacks(tokens) } else if (Block.IsVariable.test(token.value)) { return this.nodelist.push(this.createVariable(token)) } else if (token.value.length !== 0) { return this.nodelist.push(token.value) } } endTag () { this.ended = true return this.ended } unknownTag (tag, params, tokens) { if (tag === 'else') { throw new Liquid.SyntaxError((this.blockName()) + ' tag does not expect else tag') } else if (tag === 'end') { throw new Liquid.SyntaxError("'end' is not a valid delimiter for " + (this.blockName()) + ' tags. use ' + (this.blockDelimiter())) } else { throw new Liquid.SyntaxError("Unknown tag '" + tag + "'") } } blockDelimiter () { return 'end' + (this.blockName()) } blockName () { return this.tagName } createVariable (token) { const ref = Liquid.Block.ContentOfVariable.exec(token.value) const match = ref != null ? ref[1] : void 0 if (match) { return new Liquid.Variable(match) } throw new Liquid.SyntaxError("Variable '" + token.value + "' was not properly terminated with regexp: " + Liquid.VariableEnd.inspect) } async render (context) { return this.renderAll(this.nodelist, context) } assertMissingDelimitation () { if (!this.ended) { throw new Liquid.SyntaxError((this.blockName()) + ' tag was never closed') } } async renderAll (list, context) { const accumulator = [] for (const token of list) { if (token && typeof token.render !== 'function') { accumulator.push(token) continue } try { const renderedToken = await token.render(context) accumulator.push(renderedToken) } catch (err) { accumulator.push(context.handleError(err)) } } return accumulator } } Block.IsTag = RegExp('^' + Liquid.TagStart.source) Block.IsVariable = RegExp('^' + Liquid.VariableStart.source) Block.FullToken = RegExp('^' + Liquid.TagStart.source + '\\s*(\\w+)\\s*(.*)?' + Liquid.TagEnd.source + '$') Block.ContentOfVariable = RegExp('^' + Liquid.VariableStart.source + '(.*)' + Liquid.VariableEnd.source + '$') module.exports = Block <|start_filename|>lib/liquid/variable.js<|end_filename|> const Liquid = require('../liquid') const PromiseReduce = require('../promise_reduce') const VariableNameFragment = RegExp('\\s*(' + Liquid.QuotedFragment.source + ')(.*)') const FilterListFragment = RegExp(Liquid.FilterSeparator.source + '\\s*(.*)') const FilterArgParser = RegExp('(?:' + Liquid.FilterArgumentSeparator.source + '|' + Liquid.ArgumentSeparator.source + ')\\s*(' + Liquid.QuotedFragment.source + ')') const FilterParser = RegExp('(?:' + Liquid.FilterSeparator.source + '|(?:\\s*(?!(?:' + Liquid.FilterSeparator.source + '))(?:' + Liquid.QuotedFragment.source + '|\\S+)\\s*)+)') class Variable { constructor (markup) { this.markup = markup this.name = null this.filters = [] const match = VariableNameFragment.exec(this.markup) if (!match) return this.name = match[1] const secondMatch = FilterListFragment.exec(match[2]) if (!secondMatch) return const filters = Liquid.Helpers.scan(secondMatch[1], Liquid.Variable.FilterParser) filters.forEach(filter => { const filterMatch = /\s*(\w+)/.exec(filter) if (!filterMatch) return const filterName = filterMatch[1] const filterArgs = Liquid.Helpers.scan(filter, FilterArgParser) const flattenedArgs = Liquid.Helpers.flatten(filterArgs) return this.filters.push([filterName, flattenedArgs]) }) } async render (context) { if (this.name == null) { return '' } const reducer = async (input, filter) => { const filterArgs = filter[1].map(a => context.get(a)) const results = await Promise.all([input].concat(...filterArgs)) input = results.shift() try { return context .invoke .apply(context, [filter[0], input].concat(...results)) } catch (error) { if (!(error instanceof Liquid.FilterNotFound)) { throw error } throw new Liquid.FilterNotFound(`Error - filter '${filter[0]}' in '${this.markup}' could not be found.`) } } const value = await context.get(this.name) let filtered switch (this.filters.length) { case 0: filtered = value break case 1: filtered = reducer(value, this.filters[0]) break default: filtered = PromiseReduce(this.filters, reducer, value) } try { const f = await filtered if (!(f instanceof Liquid.Drop)) return f f.context = context return f.toString() } catch (err) { return context.handleError(err) } } } Variable.FilterParser = FilterParser module.exports = Variable <|start_filename|>test/conditions.js<|end_filename|> const Liquid = require('..') describe('Liquid.Condition', function () { it('evaluates without a context', function () { const c = new Liquid.Condition('1', '==', '1') return expect(c.evaluate()).to.be.fulfilled.then(v => expect(v).to.equal(true)) }) it('fails on illegal operators', () => renderTest('Liquid error: Unknown operator baz', '{% if foo baz bar %}X{% endif %}', {}, false)) context('if', function () { it('renders on `true` variables', () => renderTest('X', '{% if var %}X{% endif %}', { var: true })) it("doesn't render on `false` variables", () => renderTest('', '{% if var %}X{% endif %}', { var: false })) it('renders on truthy variables', () => renderTest('X', '{% if var %}X{% endif %}', { var: 'abc' })) it("doesn't render on falsy variables", () => renderTest('', '{% if var %}X{% endif %}', { var: null })) it('renders on truthy object properties', () => renderTest('X', '{% if foo.bar %}X{% endif %}', { foo: { bar: 'abc' } })) it("doesn't render on falsy object properties", () => renderTest('', '{% if foo.bar %}X{% endif %}', { foo: { bar: null } })) it("doesn't render on non existing properties", () => renderTest('', '{% if foo.bar %}X{% endif %}', { foo: {} })) it('renders on truthy constants', () => renderTest('X', '{% if "foo" %}X{% endif %}')) it("doesn't render on falsy constants", () => renderTest('', '{% if null %}X{% endif %}', { null: 42 })) context('with condition', function () { it('(true or true) renders', () => renderTest('X', '{% if a or b %}X{% endif %}', { a: true, b: true })) it('(true or false) renders', () => renderTest('X', '{% if a or b %}X{% endif %}', { a: true, b: false })) it('(false or true) renders', () => renderTest('X', '{% if a or b %}X{% endif %}', { a: false, b: true })) return it("(true or true) doesn't render", () => renderTest('', '{% if a or b %}X{% endif %}', { a: false, b: false })) }) context('with operators', function () { it('that evaluate to true renders', () => Promise.all([ renderTest('X', '{% if a == 42 %}X{% endif %}', { a: 42 }), renderTest('X', '{% if a is 42 %}X{% endif %}', { a: 42 }), renderTest('X', '{% if a != 42 %}X{% endif %}', { a: 41 }), renderTest('X', '{% if a isnt 42 %}X{% endif %}', { a: 41 }), renderTest('X', '{% if a <> 42 %}X{% endif %}', { a: 41 }), renderTest('X', '{% if a > 42 %}X{% endif %}', { a: 43 }), renderTest('X', '{% if a >= 42 %}X{% endif %}', { a: 43 }), renderTest('X', '{% if a >= 42 %}X{% endif %}', { a: 42 }), renderTest('X', '{% if a < 42 %}X{% endif %}', { a: 41 }), renderTest('X', '{% if a <= 42 %}X{% endif %}', { a: 41 }), renderTest('X', '{% if a <= 42 %}X{% endif %}', { a: 42 }), renderTest('X', '{% if a contains 2 %}X{% endif %}', { a: [1, 2, 3] }), renderTest('X', '{% if a contains "b" %}X{% endif %}', { a: 'abc' }), renderTest('X', '{% if a == empty %}X{% endif %}'), renderTest('X', '{% if empty == a %}X{% endif %}'), renderTest('X', '{% if a == empty %}X{% endif %}', { a: [] }), renderTest('X', '{% if a == blank %}X{% endif %}'), renderTest('X', '{% if blank == a %}X{% endif %}'), renderTest('X', '{% if a != blank %}X{% endif %}', { a: 'a' }) ]) ) return it("that evaluate to false doesn't render", () => Promise.all([ renderTest('', '{% if a != 42 %}X{% endif %}', { a: 42 }), renderTest('', '{% if a contains 2 %}X{% endif %}'), renderTest('', '{% if a contains 2 %}X{% endif %}', { a: { indexOf: null } }) ]) ) }) context('with awful markup', () => it('renders correctly', function () { const awfulMarkup = "a == 'and' and b == 'or' and c == 'foo and bar' and d == 'bar or baz' and e == 'foo' and foo and bar" const assigns = { 'a': 'and', 'b': 'or', 'c': 'foo and bar', 'd': 'bar or baz', 'e': 'foo', 'foo': true, 'bar': true } return renderTest(' YES ', `{% if ${awfulMarkup} %} YES {% endif %}`, assigns) }) ) return context('with else-branch', function () { it('renders else-branch on falsy variables', () => renderTest('ELSE', '{% if var %}IF{% else %}ELSE{% endif %}', { var: false })) return it('renders if-branch on truthy variables', () => renderTest('IF', '{% if var %}IF{% else %}ELSE{% endif %}', { var: true })) }) }) describe('unless', function () { it("negates 'false'", () => renderTest(' TRUE ', '{% unless false %} TRUE {% endunless %}')) it("negates 'true'", () => renderTest('', '{% unless true %} FALSE {% endunless %}')) return it('supports else', () => renderTest(' TRUE ', '{% unless true %} FALSE {% else %} TRUE {% endunless %}')) }) return describe('case', function () { it('outputs truthy when branches', () => renderTest(' 1 ', '{% case var %}{% when 1 %} 1 {% endcase %}', { var: 1 })) it("doesn't output falsy when branches", () => renderTest('', '{% case var %}{% when 1 %} 1 {% endcase %}', { var: 2 })) it('only prints one branch (duplicate when)', () => renderTest(' 1 ', '{% case var %}{% when 1 %} 1 {% when 1 %} 1 {% endcase %}', { var: 1 })) it('does support `or`', () => renderTest(' 1/2 ', '{% case var %}{% when 1 or 2 %} 1/2 {% endcase %}', { var: 2 })) return it('does support `else`', () => renderTest(' ELSE ', '{% case var %}{% when 1 %} 1 {% else %} ELSE {% endcase %}', { var: 2 })) }) }) <|start_filename|>lib/liquid/iterable.js<|end_filename|> const Range = require('./range') const isString = input => { return Object.prototype.toString.call(input) === '[object String]' } class Iterable { static cast (v) { if (v instanceof Iterable) { return v } else if (v instanceof Range) { return new IterableForArray(v.toArray()) } else if (Array.isArray(v) || isString(v)) { return new IterableForArray(v) } else if (v != null) { return new IterableForArray([v]) } else { return new IterableForArray([]) } } first () { const array = this.toArray() return array[0] } async map (mapper) { const array = this.toArray() return Promise.all(array.map(mapper)) } sort (sorter) { const array = this.toArray() return array.sort(sorter) } toArray () { return this.slice(0) } slice () { throw new Error(this.constructor.name + '.slice() not implemented') } last () { throw new Error(this.constructor.name + '.last() not implemented') } } class IterableForArray extends Iterable { constructor (array) { super() this.array = array } slice () { return this.array.slice.apply(this.array, arguments) } last () { return this.array[this.array.length - 1] } } module.exports = Iterable <|start_filename|>lib/liquid/tags/comment.js<|end_filename|> const Raw = require('./raw') module.exports = class Comment extends Raw { render () { return '' } } <|start_filename|>test/_helper.js<|end_filename|> let chai, expect const Liquid = require('..') global.chai = (chai = require('chai')) chai.use(require('chai-as-promised')) chai.use(require('sinon-chai')) global.expect = (expect = chai.expect) global.renderTest = function (expected, templateString, assigns, rethrowErrors) { if (rethrowErrors == null) { rethrowErrors = true } const engine = new Liquid.Engine() const parser = engine.parse(templateString) const renderer = parser.then(function (template) { template.rethrowErrors = rethrowErrors return template.render(assigns) }) const test = renderer.then(function (output) { expect(output).to.be.a('string') if (expected instanceof RegExp) { return expect(output).to.match(expected) } else { return expect(output).to.eq(expected) } }) return Promise.all([ expect(parser).to.be.fulfilled, expect(renderer).to.be.fulfilled, test ]) } <|start_filename|>lib/liquid/range.js<|end_filename|> module.exports = class Range { constructor (start, end, step) { this.start = start this.end = end this.step = step != null ? step : 0 if (this.step === 0) { if (this.end < this.start) { this.step = -1 } else { this.step = 1 } } Object.seal(this) } get length () { return Math.floor((this.end - this.start) / this.step) } some (f) { let current = this.start const end = this.end const step = this.step if (step > 0) { while (current < end) { if (f(current)) { return true } current += step } } else { while (current > end) { if (f(current)) { return true } current += step } } return false } forEach (f) { return this.some(function (e) { f(e) return false }) } toArray () { const array = [] this.forEach((e) => { return array.push(e) }) return array } } <|start_filename|>lib/liquid/tags/unless.js<|end_filename|> const Liquid = require('../../liquid') module.exports = class Unless extends Liquid.If { async parse (tokens) { await super.parse(tokens) this.blocks[0].negate = true } } <|start_filename|>lib/liquid/else_condition.js<|end_filename|> const Liquid = require('../liquid') module.exports = class ElseCondition extends Liquid.Condition { evaluate () { return true } } <|start_filename|>lib/liquid.js<|end_filename|> class Liquid {} Liquid.FilterSeparator = /\|/ Liquid.ArgumentSeparator = /,/ Liquid.FilterArgumentSeparator = /:/ Liquid.VariableAttributeSeparator = /\./ Liquid.TagStart = /\{%/ Liquid.TagEnd = /%\}/ Liquid.VariableSignature = /\(?[\w\-.[\]]\)?/ Liquid.VariableSegment = /[\w-]/ Liquid.VariableStart = /\{\{/ Liquid.VariableEnd = /\}\}/ Liquid.VariableIncompleteEnd = /\}\}?/ Liquid.QuotedString = /"[^"]*"|'[^']*'/ Liquid.QuotedFragment = RegExp(Liquid.QuotedString.source + "|(?:[^\\s,\\|'\"]|" + Liquid.QuotedString.source + ')+') Liquid.StrictQuotedFragment = /"[^"]+"|'[^']+'|[^\s|:,]+/ Liquid.FirstFilterArgument = RegExp(Liquid.FilterArgumentSeparator.source + '(?:' + Liquid.StrictQuotedFragment.source + ')') Liquid.OtherFilterArgument = RegExp(Liquid.ArgumentSeparator.source + '(?:' + Liquid.StrictQuotedFragment.source + ')') Liquid.SpacelessFilter = RegExp("^(?:'[^']+'|\"[^\"]+\"|[^'\"])*" + Liquid.FilterSeparator.source + '(?:' + Liquid.StrictQuotedFragment.source + ')(?:' + Liquid.FirstFilterArgument.source + '(?:' + Liquid.OtherFilterArgument.source + ')*)?') Liquid.Expression = RegExp('(?:' + Liquid.QuotedFragment.source + '(?:' + Liquid.SpacelessFilter.source + ')*)') Liquid.TagAttributes = RegExp('(\\w+)\\s*\\:\\s*(' + Liquid.QuotedFragment.source + ')') Liquid.AnyStartingTag = /\{\{|\{%/ Liquid.PartialTemplateParser = RegExp(Liquid.TagStart.source + '.*?' + Liquid.TagEnd.source + '|' + Liquid.VariableStart.source + '.*?' + Liquid.VariableIncompleteEnd.source) Liquid.TemplateParser = RegExp('(' + Liquid.PartialTemplateParser.source + '|' + Liquid.AnyStartingTag.source + ')') Liquid.VariableParser = RegExp('\\[[^\\]]+\\]|' + Liquid.VariableSegment.source + '+\\??') module.exports = Liquid <|start_filename|>lib/liquid/tags/increment.js<|end_filename|> const Liquid = require('../../liquid') module.exports = class Increment extends Liquid.Tag { constructor (template, tagName, markup) { super(template, tagName, markup) this.variable = markup.trim() } render (context) { const base = context.environments[0] if (!base[this.variable]) base[this.variable] = 0 const value = base[this.variable] context.environments[0][this.variable] = value + 1 return value.toString() } } <|start_filename|>test/file_system.js<|end_filename|> const Liquid = require('..') const Path = require('path') describe('Liquid.FileSystem', function () { describe('Liquid.BlankFileSystem', () => it('should error', function () { const c = new Liquid.BlankFileSystem() return expect(c.readTemplateFile('index')).to.be.rejectedWith(Liquid.FileSystemError, "This file system doesn't allow includes") }) ) return describe('Liquid.LocalFileSystem', function () { it('evaluates the correct path', function () { const c = new Liquid.LocalFileSystem('./') return expect(c.fullPath('index')).to.be.fulfilled.then(v => expect(v).to.equal(Path.resolve('index.html'))) }) it('evaluates the correct path and extension', function () { const c = new Liquid.LocalFileSystem('./root/files', 'html2') return expect(c.fullPath('index')).to.be.fulfilled.then(v => expect(v).to.equal(Path.resolve('root/files/index.html2'))) }) it('loads the file', function () { const c = new Liquid.LocalFileSystem('./test/fixtures', 'test.html') return expect(c.readTemplateFile('filesystem')).to.be.fulfilled.then(v => expect(v).to.equal('<html></html>')) }) it("throws an error when the file isn't found", function () { const c = new Liquid.LocalFileSystem('./', 'html') return expect(c.readTemplateFile('notfound')).to.be.rejectedWith(Liquid.FileSystemError, 'Error loading template') }) return it("errors if the filename isn't valid", function () { const c = new Liquid.LocalFileSystem('./', 'html') return expect(c.fullPath('invalid file')).to.be.rejectedWith(Liquid.ArgumentError, "Illegal template name 'invalid file'") }) }) }) <|start_filename|>test/drops.js<|end_filename|> const Liquid = require('..') describe('Drop', function () { beforeEach(function () { const Cls = (this.Droplet = class Droplet extends Liquid.Drop { static initClass () { this.prototype.a = 1 } b () { return 2 } }) Cls.initClass() this.drop = new this.Droplet() }) it('is an instanceof Drop', function () { expect(this.drop).to.be.instanceof(this.Droplet) return expect(this.drop).to.be.instanceof(Liquid.Drop) }) it('protects regular objects', function () { const notDrop = { a: 1, b () { return 'foo' } } return renderTest('1', '{{ drop.a }}{{ drop.b }}', { drop: notDrop }) }) // xit('can be rendered', function () { // return renderTest('12', '{{ drop.a }}{{ drop.b }}', { drop: this.drop }) // }) // xit('checks if methods are invokable', function () { // expect(this.Droplet.isInvokable('a')).to.be.ok // expect(this.Droplet.isInvokable('b')).to.be.ok // expect(this.Droplet.isInvokable('toLiquid')).to.be.ok // expect(this.Droplet.isInvokable('c')).to.be.not.ok // expect(this.Droplet.isInvokable('invokeDrop')).to.be.not.ok // expect(this.Droplet.isInvokable('beforeMethod')).to.be.not.ok // return expect(this.Droplet.isInvokable('hasKey')).to.be.not.ok // }) it('renders', function () { return renderTest('[Liquid.Drop Droplet]', '{{ drop }}', { drop: this.drop }) }) return it('allows method-hooks', function () { this.drop.beforeMethod = function (m) { if (m === 'c') { return 1 } else { return 2 } } return renderTest('12', '{{ drop.c }}{{ drop.d }}', { drop: this.drop }) }) }) <|start_filename|>lib/liquid/tags/case.js<|end_filename|> const Liquid = require('../../liquid') const PromiseReduce = require('../../promise_reduce') const SyntaxHelp = "Syntax Error in tag 'case' - Valid syntax: case [expression]" const Syntax = RegExp('(' + Liquid.QuotedFragment.source + ')') const WhenSyntax = RegExp('(' + Liquid.QuotedFragment.source + ')(?:(?:\\s+or\\s+|\\s*\\,\\s*)(' + Liquid.QuotedFragment.source + '))?') module.exports = class Case extends Liquid.Block { constructor (template, tagName, markup) { super(template, tagName, markup) const match = Syntax.exec(markup) if (!match) { throw new Liquid.SyntaxError(SyntaxHelp) } this.blocks = [] } unknownTag (tag, markup) { if (tag === 'when' || tag === 'else') { return this.pushBlock(tag, markup) } else { return super.unknownTag(tag, markup) } } pushBlock (tag, markup) { if (tag === 'else') { const block = new Liquid.ElseCondition() this.blocks.push(block) this.nodelist = block.attach([]) return this.nodelist } const expressions = Liquid.Helpers.scan(markup, WhenSyntax) const nodelist = [] const ref = expressions[0] const results = [] for (const value of ref) { if (value) { const block = new Liquid.Condition(this.markup, '==', value) this.blocks.push(block) results.push(this.nodelist = block.attach(nodelist)) } else { results.push(void 0) } } return results } async render (context) { const block = await PromiseReduce(this.blocks, async (chosenBlock, block) => { if (chosenBlock != null) return chosenBlock const ok = await block.evaluate(context) if (ok) return block }, null) return context.stack(() => { return block != null ? this.renderAll(block.attachment, context) : '' }) } } <|start_filename|>lib/liquid/tags/for.js<|end_filename|> const Liquid = require('../../liquid') const PromiseReduce = require('../../promise_reduce') const Iterable = require('../iterable') const SyntaxHelp = "Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]" const Syntax = RegExp('(\\w+)\\s+in\\s+((?:' + Liquid.QuotedFragment.source + ')+)\\s*(reversed)?') module.exports = class For extends Liquid.Block { constructor (template, tagName, markup) { super(template, tagName, markup) const match = Syntax.exec(markup) if (!match) { throw new Liquid.SyntaxError(SyntaxHelp) } this.variableName = match[1] this.collectionName = match[2] this.registerName = match[1] + '=' + match[2] this.reversed = match[3] this.attributes = {} this.nodelist = this.forBlock = [] Liquid.Helpers.scan(markup, Liquid.TagAttributes).forEach(attr => { this.attributes[attr[0]] = attr[1] }) } unknownTag (tag, markup) { if (tag !== 'else') { return super.unknownTag(tag, markup) } this.nodelist = this.elseBlock = [] return this.nodelist } renderElse (context) { if (this.elseBlock) { return this.renderAll(this.elseBlock, context) } else { return '' } } sliceCollection (collection, from, to) { const args = [from] if (to != null) { args.push(to) } const ref = Iterable.cast(collection) return ref.slice.apply(ref, args) } async render (context) { if (!context.registers.for) context.registers.for = {} let collection = await context.get(this.collectionName) if (collection != null ? collection.forEach : void 0) { } else if (collection instanceof Object) { const results = [] for (const key in collection) { if (!Object.prototype.hasOwnProperty.call(collection, key)) { continue } const v = collection[key] results.push([key, v]) } collection = results } else { return this.renderElse(context) } const from = this.attributes.offset === 'continue' ? Number(context.registers.for[this.registerName]) || 0 : Number(this.attributes.offset) || 0 const limit = this.attributes.limit const to = limit ? Number(limit) + from : null const segment = await this.sliceCollection(collection, from, to) if (segment.length === 0) { return this.renderElse(context) } if (this.reversed) { segment.reverse() } const length = segment.length context.registers.for[this.registerName] = from + segment.length return context.stack(() => { return PromiseReduce(segment, async (output, item, index) => { context.set(this.variableName, item) context.set('forloop', { name: this.registerName, length: length, index: index + 1, index0: index, rindex: length - index, rindex0: length - index - 1, first: index === 0, last: index === length - 1 }) try { const rendered = await this.renderAll(this.forBlock, context) output.push(rendered) } catch (err) { output.push(context.handleError(err)) } return output }, []) }) } } <|start_filename|>lib/liquid/tags/raw.js<|end_filename|> const Liquid = require('../../liquid') module.exports = class Raw extends Liquid.Block { async parse (tokens) { if (tokens.length === 0 || this.ended) { return } const token = tokens.shift() const match = Liquid.Block.FullToken.exec(token.value) if ((match != null ? match[1] : void 0) === this.blockDelimiter()) { return this.endTag() } this.nodelist.push(token.value) return this.parse(tokens) } } <|start_filename|>lib/liquid/tags/capture.js<|end_filename|> const Liquid = require('../../liquid') const Syntax = /(\w+)/ const SyntaxHelp = "Syntax Error in 'capture' - Valid syntax: capture [var]" module.exports = class Capture extends Liquid.Block { constructor (template, tagName, markup) { super(template, tagName, markup) const match = Syntax.exec(markup) if (match) { this.to = match[1] } else { throw new Liquid.SyntaxError(SyntaxHelp) } } async render (context) { const chunks = await super.render(context) const output = Liquid.Helpers.toFlatString(chunks) context.lastScope()[this.to] = output return '' } } <|start_filename|>lib/liquid/drop.js<|end_filename|> module.exports = class Drop { constructor () { this.context = null } static isInvokable (method) { if (!this.invokableMethods) { const denylist = Object.keys(Drop.prototype) const allowlist = ['toLiquid'] Object.keys(this.prototype).forEach((k) => { if (!(denylist.indexOf(k) >= 0)) { return allowlist.push(k) } }) this.invokableMethods = allowlist } return this.invokableMethods.indexOf(method) >= 0 } hasKey () { return true } invokeDrop (methodOrKey) { if (this.constructor.isInvokable(methodOrKey)) { const value = this[methodOrKey] if (typeof value === 'function') { return value.call(this) } else { return value } } else { return this.beforeMethod(methodOrKey) } } beforeMethod () {} get (methodOrKey) { return this.invokeDrop(methodOrKey) } toLiquid () { return this } toString () { return '[Liquid.Drop ' + this.constructor.name + ']' } } <|start_filename|>test/futures.js<|end_filename|> const asyncResult = function (result, delay) { if (delay == null) { delay = 1 } return new Promise(function (resolve) { const onTimeout = () => resolve(result) return setTimeout(onTimeout, delay) }) } describe('Futures', function () { it('are supported as simple variables', () => renderTest('worked', '{{ test }}', { test: asyncResult('worked') })) it('are supported as complex variables', () => renderTest('worked', '{{ test.text }}', { test: asyncResult({ text: 'worked' }) })) it('are supported as filter input', () => renderTest('WORKED', '{{ test | upcase }}', { test: asyncResult('worked') })) it('are supported as filter arguments', () => renderTest('1-2-3', '{{ array | join:minus }}', { minus: asyncResult('-'), array: [1, 2, 3] }) ) it('are supported as filter arguments', () => renderTest('1+2+3', '{{ array | join:minus | split:minus | join:plus }}', { minus: asyncResult('-'), plus: asyncResult('+'), array: [1, 2, 3] }) ) it('are supported in conditions', () => renderTest('YES', '{% if test %}YES{% else %}NO{% endif %}', { test: asyncResult(true) }) ) it('are supported in captures', () => renderTest('Monkeys&Monkeys', '{% capture heading %}{{animal}}{% endcapture %}{{heading}}&{{heading}}', { animal: asyncResult('Monkeys') }) ) it('are supported in assigns', () => renderTest('YES', '{% assign test = var %}{% if test == 42 %}YES{% else %}NO{% endif %}', { var: asyncResult(42) }) ) return context('in for-loops', function () { it('are supported as lists', function () { const products = ([1, 2, 2].map((i) => ({ id: `item${i}` }))) const doc = '{% for product in products %}- {{ product.id }}\n{% endfor %}' return renderTest('- item1\n- item2\n- item2\n', doc, { products: asyncResult(products) }) }) it('are supported as lists (with ifchanged)', function () { const products = ([1, 2, 2].map((i) => ({ id: `item${i}` }))) const doc = '{% for product in products %}{% ifchanged %}- {{ product.id }}\n{% endifchanged %}{% endfor %}' return renderTest('- item1\n- item2\n', doc, { products: asyncResult(products) }) }) return it('are supported as elements', function () { const doc = '{% for product in products %}- {{ product.id }}\n{% endfor %}' const products = ([1, 2, 3].map((i) => ({ id: asyncResult(`item${i}`) }))) return renderTest('- item1\n- item2\n- item3\n', doc, { products }) }) }) }) <|start_filename|>examples/custom_file_system.coffee<|end_filename|> Liquid = require('../src') class CustomFileSystem extends Liquid.BlankFileSystem readTemplateFile: (path) -> new Promise (resolve, reject) -> if path is 'foo' resolve 'FOO' else if path is 'bar' resolve 'BAR' else reject 'not foo or bar' engine = new Liquid.Engine engine.fileSystem = new CustomFileSystem engine.parse('{% include foo %} {% include bar %}') .then (parsed) -> parsed.render() .then (result) -> console.log "Rendered: #{result}" .catch (err) -> console.log "Failed: #{err}" <|start_filename|>lib/liquid/blank_file_system.js<|end_filename|> const Liquid = require('../liquid') module.exports = class BlankFileSystem { async readTemplateFile () { throw new Liquid.FileSystemError("This file system doesn't allow includes") } } <|start_filename|>lib/liquid/tags/assign.js<|end_filename|> const Liquid = require('../../liquid') const SyntaxHelp = "Syntax Error in 'assign' - Valid syntax: assign [var] = [source]" const Syntax = RegExp('((?:' + Liquid.VariableSignature.source + ')+)\\s*=\\s*(.*)\\s*') module.exports = class Assign extends Liquid.Tag { constructor (template, tagName, markup) { super(template, tagName, markup) const match = Syntax.exec(markup) if (match) { this.to = match[1] this.from = new Liquid.Variable(match[2]) } else { throw new Liquid.SyntaxError(SyntaxHelp) } } async render (context) { context.lastScope()[this.to] = this.from.render(context) return super.render.call(this, context) } } <|start_filename|>lib/liquid/condition.js<|end_filename|> const Liquid = require('../liquid') const LITERALS = { empty: v => !((v != null ? v.length : void 0) > 0), blank: v => !v || v.toString().length === 0 } const operators = { '==': (cond, left, right) => cond.equalVariables(left, right), 'is': (cond, left, right) => cond.equalVariables(left, right), '!=': (cond, left, right) => !cond.equalVariables(left, right), '<>': (cond, left, right) => !cond.equalVariables(left, right), 'isnt': (cond, left, right) => !cond.equalVariables(left, right), '<': (cond, left, right) => left < right, '>': (cond, left, right) => left > right, '<=': (cond, left, right) => left <= right, '>=': (cond, left, right) => left >= right, 'contains': (cond, left, right) => { if (left == null) return if (typeof left.indexOf === 'function') return left.indexOf(right) >= 0 } } class Condition { constructor (left, operator, right) { this.left = left this.operator = operator this.right = right this.childRelation = null this.childCondition = null } async evaluate (context = new Liquid.Context()) { const result = await this.interpretCondition(this.left, this.right, this.operator, context) switch (this.childRelation) { case 'or': return result || this.childCondition.evaluate(context) case 'and': return result && this.childCondition.evaluate(context) default: return result } } or (childCondition) { this.childCondition = childCondition this.childRelation = 'or' return this.childRelation } and (childCondition) { this.childCondition = childCondition this.childRelation = 'and' return this.childRelation } attach (attachment) { this.attachment = attachment return this.attachment } equalVariables (left, right) { if (typeof left === 'function') { return left(right) } else if (typeof right === 'function') { return right(left) } else { return left === right } } async resolveVariable (key, context) { if (key in LITERALS) { return LITERALS[key] } else { return context.get(key) } } async interpretCondition (left, right, op, context) { if (!op) { return this.resolveVariable(left, context) } const operation = Condition.operators[op] if (!operation) { throw new Error('Unknown operator ' + op) } const [resolvedLeft, resolvedRight] = await Promise.all([ this.resolveVariable(left, context), this.resolveVariable(right, context) ]) return operation(this, resolvedLeft, resolvedRight) } } Condition.operators = operators module.exports = Condition <|start_filename|>test/ranges.js<|end_filename|> const Liquid = require('..') describe('Range', function () { it('can be converted to array', function () { expect(new Liquid.Range(0, 1).toArray()).to.deep.equal([0]) expect(new Liquid.Range(0, 2).toArray()).to.deep.equal([0, 1]) return expect(new Liquid.Range(1, 2).toArray()).to.deep.equal([1]) }) it('has a length', function () { expect(new Liquid.Range(0, 1).length).to.equal(1) expect(new Liquid.Range(0, 2).length).to.equal(2) return expect(new Liquid.Range(1, 2).length).to.equal(1) }) it('has a step', function () { expect(new Liquid.Range(0, 4, 2).toArray()).to.deep.equal([0, 2]) return expect(new Liquid.Range(0, 5, 2).toArray()).to.deep.equal([0, 2, 4]) }) it('can have a negative step', function () { expect(new Liquid.Range(2, 0).toArray()).to.deep.equal([2, 1]) return expect(new Liquid.Range(5, 0, -2).toArray()).to.deep.equal([5, 3, 1]) }) return describe('.some', () => it('behaves as Array.some()', function () { expect(new Liquid.Range(0, 4).some(v => v === 2)).to.equal(true) expect(new Liquid.Range(4, 0).some(v => v === 2)).to.equal(true) expect(new Liquid.Range(0, 4).some(v => v === 10)).to.equal(false) return expect(new Liquid.Range(4, 0).some(v => v === 10)).to.not.be.ok }) ) }) <|start_filename|>lib/liquid/document.js<|end_filename|> const Liquid = require('../liquid') module.exports = class Document extends Liquid.Block { constructor (template) { super() this.template = template } blockDelimiter () { return [] } assertMissingDelimitation () {} } <|start_filename|>test/contexts.js<|end_filename|> const Liquid = require('..') const sinon = require('sinon') describe('Context', function () { beforeEach(function () { this.ctx = new Liquid.Context() }) context('.handleError', function () { it('throws errors if enabled', function () { this.ctx.rethrowErrors = true return expect(() => { return this.ctx.handleError(new Error('hello')) }).to.throw(/hello/) }) it('prints errors', function () { return expect(this.ctx.handleError(new Error('hello'))).to.match(/Liquid error/) }) return it('prints syntax errors', function () { return expect(this.ctx.handleError(new Liquid.SyntaxError('hello'))).to.match(/Liquid syntax error/) }) }) context('.push', function () { it('pushes scopes', function () { const scope = {} this.ctx.push(scope) return expect(this.ctx.pop()).to.equal(scope) }) it('pushes an empty scope by default', function () { this.ctx.push() return expect(this.ctx.pop()).to.deep.equal({}) }) return it('limits levels', function () { return expect(() => { return __range__(0, 150, true).map((i) => this.ctx.push()) }) .to.throw(/Nesting too deep/) }) }) context('.pop', () => it('throws an exception if no scopes are left to pop', function () { return expect(() => { return this.ctx.pop() }).to.throw(/ContextError/) }) ) context('.stack', () => it('automatically pops scopes', function () { const mySpy = sinon.spy() this.ctx.stack(null, mySpy) expect(mySpy.calledOnce).to.equal(true) expect(this.ctx.scopes.length).to.equal(1) }) ) context('.merge', function () { it('merges scopes', function () { this.ctx.push({ x: 1, y: 2 }) this.ctx.merge({ y: 3, z: 4 }) return expect(this.ctx.pop()).to.deep.equal({ x: 1, y: 3, z: 4 }) }) return it('merges null-scopes', function () { this.ctx.push({ x: 1 }) this.ctx.merge() return expect(this.ctx.pop()).to.deep.equal({ x: 1 }) }) }) context('.resolve', function () { it('resolves strings', async function () { expect(await this.ctx.resolve('"42"')).to.equal('42') }) it('resolves numbers', async function () { expect(await this.ctx.resolve('42')).to.equal(42) expect(await this.ctx.resolve('3.14')).to.equal(3.14) }) return it('resolves illegal ranges', function () { return expect(this.ctx.resolve('(0..a)')).to.become([]) }) }) context('.clearInstanceAssigns', () => it('clears current scope', function () { const scope = { x: 1 } this.ctx.push(scope) this.ctx.clearInstanceAssigns() return expect(this.ctx.pop()).to.deep.equal({}) }) ) context('.hasKey', () => it('checks for variable', async function () { this.ctx.push({ a: 0 }) this.ctx.push({ b: 1 }) this.ctx.push({ c: true }) expect(await this.ctx.hasKey('a')).to.equal(true) expect(await this.ctx.hasKey('b')).to.equal(true) expect(await this.ctx.hasKey('c')).to.equal(true) expect(await this.ctx.hasKey('z')).to.equal(false) }) ) return context('.variable', () => it('supports special access', function () { this.ctx.push({ a: [1, 99] }) expect(this.ctx.variable('a.first')).to.become(1) expect(this.ctx.variable('a.size')).to.become(2) return expect(this.ctx.variable('a.last')).to.become(99) }) ) }) function __range__ (left, right, inclusive) { let range = [] let ascending = left < right let end = !inclusive ? right : ascending ? right + 1 : right - 1 for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) { range.push(i) } return range } <|start_filename|>lib/liquid/engine.js<|end_filename|> const Liquid = require('../liquid') module.exports = class Engine { constructor () { this.tags = {} this.Strainer = function (context) { this.context = context } this.registerFilters(Liquid.StandardFilters) this.fileSystem = new Liquid.BlankFileSystem() for (const tagName in Liquid) { if (!Object.prototype.hasOwnProperty.call(Liquid, tagName)) continue const tag = Liquid[tagName] if (!(tag.prototype instanceof Liquid.Tag)) { continue } const isBlockOrTagBaseClass = [Liquid.Tag, Liquid.Block].indexOf(tag.constructor) >= 0 if (!isBlockOrTagBaseClass) { this.registerTag(tagName.toLowerCase(), tag) } } } registerTag (name, tag) { this.tags[name] = tag } registerFilters (...filters) { return filters.forEach((filter) => { const results = [] for (const key in filter) { if (!Object.prototype.hasOwnProperty.call(filter, key)) continue const value = filter[key] if (value instanceof Function) { results.push(this.Strainer.prototype[key] = value) } else { results.push(void 0) } } return results }) } async parse (source) { const template = new Liquid.Template() return template.parse(this, source) } async parseAndRender (source, context) { const template = await this.parse(source) return template.render(context) } registerFileSystem (fileSystem) { if (!(fileSystem instanceof Liquid.BlankFileSystem)) { throw Liquid.ArgumentError('Must be subclass of Liquid.BlankFileSystem') } this.fileSystem = fileSystem return this.fileSystem } } <|start_filename|>lib/liquid/tags/ifchanged.js<|end_filename|> const Liquid = require('../../liquid') module.exports = class IfChanged extends Liquid.Block { async render (context) { return context.stack(async () => { const rendered = await this.renderAll(this.nodelist, context) const output = Liquid.Helpers.toFlatString(rendered) if (output !== context.registers.ifchanged) { context.registers.ifchanged = output return context.registers.ifchanged } else { return '' } }) } }
Faraday-Labs-Inc/liquid
<|start_filename|>Makefile<|end_filename|> # Common commands to habdle the project. # ------------------------------------------------------------------------------ lint: poetry run isort . --profile black poetry run black . poetry run mypy .
systemallica/django-belt
<|start_filename|>util.go<|end_filename|> package rediswatcher import ( "fmt" "log" ) type CallbackFunc func(msg string, update, updateForAddPolicy, updateForRemovePolicy, updateForRemoveFilteredPolicy, updateForSavePolicy func(string, interface{})) func CustomDefaultFunc(defaultFunc func(string, interface{})) CallbackFunc { return func(msg string, update, updateForAddPolicy, updateForRemovePolicy, updateForRemoveFilteredPolicy, updateForSavePolicy func(string, interface{})) { msgStruct := &MSG{} err := msgStruct.UnmarshalBinary([]byte(msg)) if err != nil { log.Println(err) } invoke := func(f func(string, interface{})) { if f == nil { f = defaultFunc } f(msgStruct.ID, msgStruct.Params) } switch msgStruct.Method { case "Update": invoke(update) case "UpdateForAddPolicy": invoke(updateForAddPolicy) case "UpdateForRemovePolicy": invoke(updateForRemovePolicy) case "UpdateForRemoveFilteredPolicy": invoke(updateForRemoveFilteredPolicy) case "UpdateForSavePolicy": invoke(updateForSavePolicy) } } } func DefaultCallback(string) { } func defaultUpdateCallback(ID string, params string) { fmt.Printf("ID = %s, Params = %s\n", ID, params) } func ArrayEqual(s1, s2 []string) bool { if len(s1) != len(s2) { return false } for i := range s1 { if s1[i] != s2[i] { return false } } return true }
go-codes/redis-watcher
<|start_filename|>EventQueue.cpp<|end_filename|> #include "EventQueue.h" #include "mbed_events.h" #include "mbed.h" EventQueue::EventQueue(unsigned event_size, unsigned char *event_pointer) { if (!event_pointer) { equeue_create(&_equeue, event_size); } else { equeue_create_inplace(&_equeue, event_size, event_pointer); } } EventQueue::~EventQueue() { equeue_destroy(&_equeue); } void EventQueue::dispatch(int ms) { return equeue_dispatch(&_equeue, ms); } void EventQueue::break_dispatch() { return equeue_break(&_equeue); } unsigned EventQueue::tick() { return equeue_tick(); } void EventQueue::cancel(int id) { return equeue_cancel(&_equeue, id); } void EventQueue::background(Callback<void(int)> update) { _update = update; if (_update) { equeue_background(&_equeue, &Callback<void(int)>::thunk, &_update); } else { equeue_background(&_equeue, 0, 0); } } void EventQueue::chain(EventQueue *target) { if (target) { equeue_chain(&_equeue, &target->_equeue); } else { equeue_chain(&_equeue, 0); } }
risc604/mbed-events
<|start_filename|>src/Middleware/Exception.fs<|end_filename|> // Copyright 2020 Cognite AS // SPDX-License-Identifier: Apache-2.0 namespace Oryx open System /// Skip exception will not be recorded and forwarded by `choose`. exception SkipException of string with static member Create() = SkipException String.Empty /// Wrapping an exception as a PanicException will short-circuit the /// handlers. A PanicException cannot be catched by `catch` and will /// not be skipped by `choose` exception PanicException of exn with /// Ensures that the exception is a `PanicException`, but will not /// wrap a `PanicException` in another `PanicException`. static member Ensure(error) = match error with | PanicException (_) -> error | _ -> PanicException error <|start_filename|>src/Middleware/Error.fs<|end_filename|> // Copyright 2020 Cognite AS // SPDX-License-Identifier: Apache-2.0 namespace Oryx.Middleware open System open FSharp.Control.Tasks open Oryx [<AutoOpen>] module Error = /// Handler for protecting the pipeline from exceptions and protocol violations. let protect<'TContext, 'TSource> = { new IAsyncMiddleware<'TContext, 'TSource> with member _.Subscribe(next) = let mutable stopped = false { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = task { match stopped with | false -> try return! next.OnNextAsync(ctx, content) with err -> stopped <- true return! next.OnErrorAsync(ctx, err) | _ -> () } member _.OnErrorAsync(ctx, err) = task { match stopped with | false -> stopped <- true return! next.OnErrorAsync(ctx, err) | _ -> () } member _.OnCompletedAsync(ctx) = task { match stopped with | false -> stopped <- true return! next.OnCompletedAsync(ctx) | _ -> () } } } /// Handler for catching errors and then delegating to the error handler on what to do. let catch<'TContext, 'TSource> (errorHandler: exn -> IAsyncMiddleware<'TContext, unit, 'TSource>) : IAsyncMiddleware<'TContext, 'TSource> = { new IAsyncMiddleware<'TContext, 'TSource> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = task { try return! next.OnNextAsync(ctx, content) with err -> return! next.OnErrorAsync(ctx, err) } member _.OnErrorAsync(ctx, err) = task { match err with | PanicException (error) -> return! next.OnErrorAsync(ctx, error) | _ -> let obv = (errorHandler err).Subscribe(next) return! obv.OnNextAsync(ctx, ()) } member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } [<RequireQualifiedAccess>] type ChooseState = | NoError | Error | Panic /// Choose from a list of middlewares to use. The first middleware that succeeds will be used. Handlers will be /// tried until one does not produce any error, or a `PanicException`. let choose<'TContext, 'TSource, 'TResult> (handlers: IAsyncMiddleware<'TContext, 'TSource, 'TResult> seq) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = let exns : ResizeArray<exn> = ResizeArray() { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = let mutable state = ChooseState.Error task { let obv = { new IAsyncNext<'TContext, 'TResult> with member _.OnNextAsync(ctx, content) = task { exns.Clear() // Clear to avoid buildup of exceptions in streaming scenarios. if state = ChooseState.NoError then return! next.OnNextAsync(ctx, content) } member _.OnErrorAsync(_, error) = task { match error, state with | PanicException (_), st when st <> ChooseState.Panic -> state <- ChooseState.Panic return! next.OnErrorAsync(ctx, error) | SkipException (_), st when st = ChooseState.NoError -> // Flag error, but do not record skips. state <- ChooseState.Error | _, ChooseState.Panic -> // Already panic. Ignoring additional error. () | _, _ -> state <- ChooseState.Error exns.Add(error) } member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } /// Proces handlers until `NoError` or `Panic`. for handler in handlers do if state = ChooseState.Error then state <- ChooseState.NoError do! handler.Subscribe(obv).OnNextAsync(ctx, content) match state, exns with | ChooseState.Panic, _ -> // Panic is sent immediately above () | ChooseState.Error, exns when exns.Count > 1 -> return! next.OnErrorAsync(ctx, AggregateException(exns)) | ChooseState.Error, exns when exns.Count = 1 -> return! next.OnErrorAsync(ctx, exns.[0]) | ChooseState.Error, _ -> return! next.OnErrorAsync(ctx, SkipException "Choose: No hander matched") | ChooseState.NoError, _ -> () } member _.OnErrorAsync(ctx, error) = exns.Clear() next.OnErrorAsync(ctx, error) member _.OnCompletedAsync(ctx) = exns.Clear() next.OnCompletedAsync(ctx) } } /// Error handler for forcing error. Use with e.g `req` computational expression if you need to "return" an error. let fail<'TContext, 'TSource, 'TResult> (error: Exception) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = next.OnErrorAsync(ctx, error) member _.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Error handler for forcing a panic error. Use with e.g `req` computational expression if you need break out of /// the any error handling e.g `choose` or `catch`•. let panic<'TContext, 'TSource, 'TResult> (error: Exception) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = next.OnErrorAsync(ctx, PanicException error) member _.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } <|start_filename|>examples/github/Program.fs<|end_filename|> open System.Net.Http open FSharp.Control.Tasks open Oryx open Oryx.ThothJsonNet.ResponseReader open Thoth.Json.Net [<EntryPoint>] let main argv = use client = new HttpClient() let context = HttpContext.defaultContext |> HttpContext.withHttpClient client let request = GET >=> withUrl "https://api.github.com/repos/cognitedata/oryx/releases/latest" >=> fetch >=> json (Decode.field "tag_name" Decode.string) task { let! tag = request |> runAsync context printfn "%A" tag return 0 } |> (fun t -> t.GetAwaiter().GetResult()) |> ignore 0 // return an integer exit code <|start_filename|>src/Middleware/Core.fs<|end_filename|> // Copyright 2020 Cognite AS // SPDX-License-Identifier: Apache-2.0 namespace Oryx.Middleware open System open System.Threading.Tasks open FSharp.Control.Tasks open FsToolkit.ErrorHandling open Oryx type IAsyncNext<'TContext, 'TSource> = abstract member OnNextAsync : ctx: 'TContext * content: 'TSource -> Task<unit> abstract member OnErrorAsync : ctx: 'TContext * error: exn -> Task<unit> abstract member OnCompletedAsync : ctx: 'TContext -> Task<unit> type IAsyncMiddleware<'TContext, 'TSource, 'TResult> = abstract member Subscribe : next: IAsyncNext<'TContext, 'TResult> -> IAsyncNext<'TContext, 'TSource> type IAsyncMiddleware<'TContext, 'TSource> = IAsyncMiddleware<'TContext, 'TSource, 'TSource> module Core = /// Returns a middleware whose elements are the result of invoking the async transform function on each /// element of the source. let transform<'TContext, 'TSource, 'TResult> (transform: ('TContext * 'TResult -> Task<unit>) -> 'TContext -> 'TSource -> Task<unit>) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = let subscribeAsync (next: IAsyncNext<'TContext, 'TResult>) = { new IAsyncNext<'TContext, 'TSource> with member __.OnNextAsync(ctx, x) = transform next.OnNextAsync ctx x member __.OnErrorAsync(ctx, err) = next.OnErrorAsync(ctx, err) member __.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member __.Subscribe o = subscribeAsync o } /// A next continuation for observing the final result. let finish (tcs: TaskCompletionSource<'TResult>) = { new IAsyncNext<'TContext, 'TResult> with member _.OnNextAsync(_, response) = task { tcs.SetResult response } member _.OnErrorAsync(_, error) = task { tcs.SetException error } member _.OnCompletedAsync _ = task { tcs.SetCanceled() } } /// Run the HTTP handler in the given context. Returns content as result type. let runAsync<'TContext, 'TResult> (ctx: 'TContext) (handler: IAsyncMiddleware<'TContext, unit, 'TResult>) : Task<Result<'TResult, exn>> = let tcs = TaskCompletionSource<'TResult>() task { do! handler.Subscribe(finish tcs).OnNextAsync(ctx, ()) try let! value = tcs.Task return Ok value with err -> return Error err } /// Run the HTTP handler in the given context. Returns content and throws exception if any error occured. let runUnsafeAsync<'TContext, 'TResult> (ctx: 'TContext) (handler: IAsyncMiddleware<'TContext, unit, 'TResult>) : Task<'TResult> = task { let! result = runAsync ctx handler match result with | Ok value -> return value | Error err -> return raise err } /// Produce the given content. let singleton<'TContext, 'TSource, 'TResult> (content: 'TResult) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = next.OnNextAsync(ctx, content = content) member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Map the content of the middleware. let map<'TContext, 'TSource, 'TResult> (mapper: 'TSource -> 'TResult) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = try next.OnNextAsync(ctx, mapper content) with error -> next.OnErrorAsync(ctx, error) member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Bind the content of the middleware. let bind<'TContext, 'TSource, 'TValue, 'TResult> (fn: 'TValue -> IAsyncMiddleware<'TContext, 'TSource, 'TResult>) (source: IAsyncMiddleware<'TContext, 'TSource, 'TValue>) : IAsyncMiddleware<'TContext, 'TSource, 'TResult> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = let valueObs = { new IAsyncNext<'TContext, 'TValue> with member _.OnNextAsync(ctx, value) = task { let result = try fn value |> Ok with error -> Error error match result with | Ok handler -> return! handler.Subscribe(next).OnNextAsync(ctx, content) | Error error -> return! next.OnErrorAsync(ctx, error) } member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } task { let sourceObv = source.Subscribe(valueObs) return! sourceObv.OnNextAsync(ctx, content) } member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Compose two middlewares into one. let inline compose (first: IAsyncMiddleware<'TContext, 'T1, 'T2>) (second: IAsyncMiddleware<'TContext, 'T2, 'T3>) : IAsyncMiddleware<'TContext, 'T1, 'T3> = { new IAsyncMiddleware<'TContext, 'T1, 'T3> with member _.Subscribe(next) = second.Subscribe(next) |> first.Subscribe } /// Composes two middleware into one. let (>=>) = compose /// Run list of middlewares concurrently. let concurrent<'TContext, 'TSource, 'TResult> (merge: 'TContext list -> 'TContext) (handlers: seq<IAsyncMiddleware<'TContext, 'TSource, 'TResult>>) : IAsyncMiddleware<'TContext, 'TSource, 'TResult list> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult list> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = task { let res : Result<'TContext * 'TResult, exn> array = Array.zeroCreate (Seq.length handlers) let obv n = { new IAsyncNext<'TContext, 'TResult> with member _.OnNextAsync(ctx, content) = task { res.[n] <- Ok(ctx, content) } member _.OnErrorAsync(_, err) = task { res.[n] <- Error err } member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } let! _ = handlers |> Seq.mapi (fun n handler -> handler.Subscribe(obv n).OnNextAsync(ctx, content)) |> Task.WhenAll let result = res |> List.ofSeq |> List.sequenceResultM match result with | Ok results -> let results, contents = results |> List.unzip let bs = merge results return! next.OnNextAsync(bs, contents) | Error err -> return! next.OnErrorAsync(ctx, err) } member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Run list middlewares sequentially. let sequential<'TContext, 'TSource, 'TResult> (merge: 'TContext list -> 'TContext) (handlers: seq<IAsyncMiddleware<'TContext, 'TSource, 'TResult>>) : IAsyncMiddleware<'TContext, 'TSource, 'TResult list> = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult list> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = task { let res = ResizeArray<Result<'TContext * 'TResult, exn>>() let obv = { new IAsyncNext<'TContext, 'TResult> with member _.OnNextAsync(ctx, content) = task { Ok(ctx, content) |> res.Add } member _.OnErrorAsync(_, err) = task { Error err |> res.Add } member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } for handler in handlers do do! handler.Subscribe(obv) |> (fun obv -> obv.OnNextAsync(ctx, content)) let result = res |> List.ofSeq |> List.sequenceResultM match result with | Ok results -> let results, contents = results |> List.unzip let bs = merge results return! next.OnNextAsync(bs, contents) | Error err -> return! next.OnErrorAsync(ctx, err) } member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Chunks a sequence of Middlewares into a combination of sequential and concurrent batches. let chunk<'TContext, 'TSource, 'TNext, 'TResult> (merge: 'TContext list -> 'TContext) (chunkSize: int) (maxConcurrency: int) (handler: seq<'TNext> -> IAsyncMiddleware<'TContext, 'TSource, seq<'TResult>>) (items: seq<'TNext>) : IAsyncMiddleware<'TContext, 'TSource, seq<'TResult>> = items |> Seq.chunkBySize chunkSize |> Seq.chunkBySize maxConcurrency |> Seq.map (Seq.map handler >> concurrent merge) |> sequential merge // Collect results >=> map (Seq.ofList >> Seq.collect (Seq.collect id)) /// Handler that skips (ignores) the content and outputs unit. let skip<'TContext, 'TSource> = { new IAsyncMiddleware<'TContext, 'TSource, unit> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = next.OnNextAsync(ctx, content = ()) member _.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Never produces a result. let never = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = Task.FromResult() member __.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member __.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Completes the current request. let complete = { new IAsyncMiddleware<'TContext, 'TSource, 'TResult> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = next.OnCompletedAsync(ctx) member __.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member __.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Filter content using a predicate function. let filter<'TContext, 'TSource> (predicate: 'TSource -> bool) : IAsyncMiddleware<'TContext, 'TSource> = { new IAsyncMiddleware<'TContext, 'TSource, 'TSource> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, value) = task { if predicate value then return! next.OnNextAsync(ctx, content = value) } member _.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Validate content using a predicate function. Same as filter ut produces an error if validation fails. let validate<'TContext, 'TSource> (predicate: 'TSource -> bool) : IAsyncMiddleware<'TContext, 'TSource> = { new IAsyncMiddleware<'TContext, 'TSource, 'TSource> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, value) = if predicate value then next.OnNextAsync(ctx, content = value) else next.OnErrorAsync(ctx, SkipException("Validation failed")) member _.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member _.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Retrieves the content. let await<'TContext, 'TSource> () = map<'TContext, 'TSource, 'TSource> id /// Returns the current environment. let ask = { new IAsyncMiddleware<'TContext, 'TSource, 'TContext> with member _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, _) = next.OnNextAsync(ctx, ctx) member __.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member __.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } /// Update (asks) the context. let update (update: 'TContext -> 'TContext) = { new IAsyncMiddleware<'TContext, 'TSource, 'TSource> with override _.Subscribe(next) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = next.OnNextAsync(update ctx, content) member __.OnErrorAsync(ctx, error) = next.OnErrorAsync(ctx, error) member __.OnCompletedAsync(ctx) = next.OnCompletedAsync(ctx) } } [<AutoOpen>] module Extensions = type IAsyncMiddleware<'TResource, 'TSource, 'TResult> with /// Subscribe using plain task returning functions. member _.Subscribe ( ?onNextAsync: 'TSource -> Task<unit>, ?onErrorAsync: exn -> Task<unit>, ?onCompletedAsync: unit -> Task<unit> ) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = match onNextAsync with | Some fn -> fn (content) | None -> Task.FromResult() member _.OnErrorAsync(ctx, exn) = match onErrorAsync with | Some fn -> fn exn | None -> Task.FromResult() member _.OnCompletedAsync(ctx) = match onCompletedAsync with | Some fn -> fn () | None -> Task.FromResult() } /// Subscribe using a task returning function taking a result. Invokations of `OnNextAsync` will result in `Ok` /// while `OnErrorAsync` and `OnCompletedAsync` will produce `Error`. `OnCompletedAsync` will produce /// `OperationCanceledException`. member _.Subscribe(next: Result<'TSource, exn> -> Task<unit>) = { new IAsyncNext<'TContext, 'TSource> with member _.OnNextAsync(ctx, content) = next (Ok content) member _.OnErrorAsync(ctx, exn) = next (Error exn) member _.OnCompletedAsync(ctx) = next (OperationCanceledException() :> exn |> Error) } <|start_filename|>src/HttpHandler/HttpContext.fs<|end_filename|> // Copyright 2020 Cognite AS // SPDX-License-Identifier: Apache-2.0 namespace Oryx open System open System.Collections open System.Diagnostics open System.Net open System.Net.Http open System.Reflection open System.Threading open Microsoft.Extensions.Logging type RequestMethod = | POST | PUT | GET | DELETE type ResponseType = | JsonValue | Protobuf type Value = | String of string | Number of int64 | Url of Uri // Give proper output for logging override x.ToString() = match x with | String str -> str | Number num -> num.ToString() | Url uri -> uri.ToString() module PlaceHolder = [<Literal>] let HttpMethod = "HttpMethod" [<Literal>] let RequestContent = "RequestContent" [<Literal>] let ResponseContent = "ResponseContent" [<Literal>] let Message = "Message" [<Literal>] let Url = "Url" [<Literal>] let Elapsed = "Elapsed" type UrlBuilder = HttpRequest -> string and HttpRequest = { /// HTTP client to use for sending the request. HttpClient: unit -> HttpClient /// HTTP method to be used. Method: HttpMethod /// Getter for content to be sent as body of the request. We use a getter so content may be re-created for /// retries. ContentBuilder: (unit -> HttpContent) option /// Query parameters Query: seq<struct (string * string)> /// Responsetype. JSON or Protobuf ResponseType: ResponseType /// Map of headers to be sent Headers: Map<string, string> /// A function that builds the request URL based on the collected extra info. UrlBuilder: UrlBuilder /// Optional CancellationToken for cancelling the request. CancellationToken: CancellationToken /// Optional Logger for logging requests. Logger: ILogger option /// The LogLevel to log at LogLevel: LogLevel /// Logging format string LogFormat: string /// Optional Metrics for recording metrics. Metrics: IMetrics /// Optional Labels to label the request Labels: Generic.IDictionary<string, string> /// Extra state used to e.g build the URL. Clients are free to utilize this property for adding extra /// information to the context. Items: Map<string, Value> /// The given `HttpCompletionOption` to use for the request. CompletionMode: HttpCompletionOption } type HttpResponse = { /// Map of received headers Headers: Map<string, seq<string>> /// Http status code StatusCode: HttpStatusCode /// True if response is successful IsSuccessStatusCode: bool /// Reason phrase which typically is sent by servers together with the status code ReasonPhrase: string } type HttpContext = { Request: HttpRequest Response: HttpResponse } [<RequireQualifiedAccess>] module HttpContext = let private fileVersion = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion let defaultLogFormat = "Oryx: {Message} {HttpMethod} {Url}\n→ {RequestContent}\n← {ResponseContent}" /// Default request to use. let defaultRequest = let ua = sprintf "Oryx / v%s (Cognite)" fileVersion { HttpClient = (fun () -> failwith "Must set HttpClient") Method = HttpMethod.Get ContentBuilder = None Query = List.empty ResponseType = JsonValue Headers = [ "User-Agent", ua ] |> Map UrlBuilder = fun _ -> String.Empty CancellationToken = CancellationToken.None Logger = None LogLevel = LogLevel.None LogFormat = defaultLogFormat Metrics = EmptyMetrics() Labels = dict [] Items = Map.empty CompletionMode = HttpCompletionOption.ResponseContentRead } /// Default response to use. let defaultResponse = { StatusCode = HttpStatusCode.NotFound IsSuccessStatusCode = false Headers = Map.empty ReasonPhrase = String.Empty } /// The default context. let defaultContext : HttpContext = { Request = defaultRequest Response = defaultResponse } /// Add HTTP header to context. let withHeader (header: string * string) (ctx: HttpContext) = { ctx with Request = { ctx.Request with Headers = ctx.Request.Headers.Add header } } /// Replace all headers in the context. let withHeaders (headers: Map<string, string>) (context: HttpContext) = { context with Request = { context.Request with Headers = headers } } /// Helper for setting Bearer token as Authorization header. let withBearerToken (token: string) (ctx: HttpContext) = let header = ("Authorization", sprintf "Bearer %s" token) { ctx with Request = { ctx.Request with Headers = ctx.Request.Headers.Add header } } /// Set the HTTP client to use for the requests. let withHttpClient (client: HttpClient) (ctx: HttpContext) = { ctx with Request = { ctx.Request with HttpClient = (fun () -> client) } } /// Set the HTTP client factory to use for the requests. let withHttpClientFactory (factory: unit -> HttpClient) (ctx: HttpContext) = { ctx with Request = { ctx.Request with HttpClient = factory } } /// Set the URL builder to use. let withUrlBuilder (builder: HttpRequest -> string) (ctx: HttpContext) = { ctx with Request = { ctx.Request with UrlBuilder = builder } } /// Set a cancellation token to use for the requests. let withCancellationToken (token: CancellationToken) (ctx: HttpContext) = { ctx with Request = { ctx.Request with CancellationToken = token } } /// Set the logger (ILogger) to use. let withLogger (logger: ILogger) (ctx: HttpContext) = { ctx with Request = { ctx.Request with Logger = Some logger } } /// Set the log level to use (default is LogLevel.None). let withLogLevel (logLevel: LogLevel) (context: HttpContext) = { context with Request = { context.Request with LogLevel = logLevel } } /// Set the log format to use. let withLogFormat (format: string) (ctx: HttpContext) = { ctx with Request = { ctx.Request with LogFormat = format } } /// Set the log message to use (normally you would like to use the withLogMessage handler instead) let withLogMessage (msg: string) (ctx: HttpContext) = { ctx with Request = { ctx.Request with Items = ctx.Request.Items.Add(PlaceHolder.Message, String msg) } } /// Set the metrics (IMetrics) to use. let withMetrics (metrics: IMetrics) (ctx: HttpContext) = { ctx with Request = { ctx.Request with Metrics = metrics } } /// Merge the list of context objects. Used by the sequential and concurrent HTTP handlers. let merge (ctxs: List<HttpContext>) : HttpContext = let ctxs = match ctxs with | [] -> [ defaultContext ] | _ -> ctxs // Use the max status code. let statusCode = ctxs |> List.map (fun ctx -> ctx.Response.StatusCode) |> List.max // Concat the reason phrases (if they are different) let reasonPhrase = ctxs |> List.map (fun ctx -> ctx.Response.ReasonPhrase) |> List.distinct |> String.concat ", " let merge (a: Map<'a, 'b>) (b: Map<'a, 'b>) (f: 'a -> 'b * 'b -> 'b) = Map.fold (fun s k v -> match Map.tryFind k s with | Some v' -> Map.add k (f k (v, v')) s | None -> Map.add k v s) a b // Merge headers let headers = ctxs |> List.map (fun ctx -> ctx.Response.Headers) |> List.fold (fun state hdr -> merge state hdr (fun k (a, b) -> if a = b then a else Seq.append a b)) Map.empty { Request = ctxs |> Seq.map (fun ctx -> ctx.Request) |> Seq.head Response = { Headers = headers StatusCode = statusCode IsSuccessStatusCode = true ReasonPhrase = reasonPhrase } } <|start_filename|>test/Builder.fs<|end_filename|> module Tests.Builder open FSharp.Control.Tasks open Swensen.Unquote open Xunit open Oryx open Tests.Common [<Fact>] let ``Zero builder is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext // Act let! result = req { () } |> runAsync ctx // Assert test <@ Result.isOk result @> } [<Fact>] let ``Simple unit handler in builder is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext // Act let! result = let a = req { let! value = singleton 42 return value } a |> runUnsafeAsync ctx // Assert test <@ result = 42 @> } [<Fact>] let ``Simple return from unit handler in builder is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext let a = singleton 42 >=> skip |> runAsync ctx // Act let! result = req { return! singleton 42 } |> runUnsafeAsync ctx // Assert test <@ result = 42 @> } [<Fact>] let ``Multiple handlers in builder is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext // Act let request = req { let! a = singleton 10 let! b = singleton 20 return! add a b >=> validate (fun value -> value = 10 + 20) } let! result = request |> runUnsafeAsync ctx // Assert test <@ result = 30 @> } [<Fact>] let ``Get value is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext // Act let request = req { let! a = HttpHandler.get () >=> validate (fun value -> value = 42) return a } let! result = singleton 42 >=> request |> runUnsafeAsync ctx // Assert test <@ result = 42 @> } [<Fact>] let ``Get value 2 is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext // Act let request = req { yield 42 let! a = HttpHandler.get () return a + 1 } let! result = request |> runUnsafeAsync ctx // Assert test <@ result = 43 @> } [<Fact>] let ``Iterate handlers is Ok`` () = task { // Arrange let ctx = HttpContext.defaultContext // Act let request = req { let! h = req { for a in 1 .. 10 do yield 42 } return List.sum h } let! result = request |> runUnsafeAsync ctx // Assert test <@ result = 420 @> }
cognitedata/oryx
<|start_filename|>src/utils.js<|end_filename|> (function() { 'use strict'; module.exports.mergeOptions = mergeOptions; module.exports.toArray = toArray; module.exports.toFunction = toFunction; module.exports.prettyNumbers = function(numbers) { return numbers.map(prettyNumber); } function mergeOptions(options, defaults) { if (options) options = JSON.parse(JSON.stringify(options)); else options = {}; defaults = defaults || {}; for (var opt in defaults) { if (defaults.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) { options[opt] = defaults[opt]; } } return options; } function toArray(x) { if (x.constructor !== Array) x = [x]; return x; } function toFunction(x) { if (typeof x === "function") return (x); x = toArray(x); return function(d, i) {return x[i % x.length]}; } function prettyNumber(number) { if (isNaN(number) || !isFinite(number)) return ""; var absVal = Math.abs(number); var sign= number < 0? "-": ""; var scale; if( absVal < 1000 ) { scale = ''; } else if( absVal < 1000000 ) { scale = 'K'; absVal = absVal/1000; } else if( absVal < 1000000000 ) { scale = 'M'; absVal = absVal/1000000; } else if( absVal < 1000000000000 ) { scale = 'B'; absVal = absVal/1000000000; } else if( absVal < 1000000000000000 ) { scale = 'T'; absVal = absVal/1000000000000; } if (absVal > 10) absVal = roundTo(absVal); else if (absVal > 1) absVal = roundTo(absVal, 10, true); else absVal = roundTo(absVal, 100, true); return sign + absVal + scale; } function roundTo(number, to, inverse) { to = to || 1; if (inverse) return Math.round(number * to) / to; else return Math.round(number / to) * to; } }()); <|start_filename|>src/minichart.js<|end_filename|> // Copyright © 2016 RTE Réseau de transport d’électricité (function() { var d3 = require("d3"); var minicharts = require("minicharts"); var utils = require("./utils.js"); L.Minichart = L.CircleMarker.extend({ /** Options used to initialize/update a Minichart object. * @typedef {object} MinichartOptions * @memberOf 'L.Minichart' * @prop {string} [type = "bar"] * Type of chart to create. Possible values are "bar" for barcharts, "pie" * for pie charts, "polar-radius" and "polar-area" for polar area charts * where values are represented either by the radius or the area of the * slices. * @prop {number[]} [data = [1]] * Data values the chart has to represent. * @prop {number[]|"auto"} [maxValues = "auto"] * maximal absolute value the data could take. It can be a single numeric * value or an array of values with same length as data. In the first case, * all values will be represented with the same scale while in the second * case, each value will have its own scale. This is useful when one wants * to represent multiple variables that are not comparable. If it equals to * "auto" (the default) then the maximum absolute value in data is used. * @prop {string[]} [colors=d3.schemeCategory10] Array of colors. If its * length is less than the length of data, colors are recycled. * @prop {number} [width=60] * Width of the chart when `type` equals 'bar' or maximal diameter of the * chart for all other types. * @prop {number} [height=60] * Maximal height of barcharts. * @prop {string[]|"none"|"auto"}[labels="none"] * Labels to display on the chart. If it equals to "auto" then data values * are displayed in a compact way. * @prop {number} [labelMinSize=8] * Labels are automatically hidden if the label height is less than this number. * @prop {number} [labelMaxSize=24] * Maximal height of labels in pixels. * @prop {number} [labelPadding=2] * Padding to apply to labels. * @prop {string} [labelStyle="font-family:sans-serif"] * CSS style to apply to labels * @prop {string} [labelColor="auto"] * Color to apply to labels. If "auto", text will be black or white * depending on the background color. * @prop {number} [transitionTime=750] * Duration in millisecondq of transitions. * */ options: { type: "bar", data: [1], maxValues: "auto", colors: d3.schemeCategory10, width: 60, height: 60, opacity: 1, labels:"none", labelMinSize: 8, labelMaxSize: 24, labelPadding: 2, labelColor: "auto", labelStyle: "font-family:sans-serif", transitionTime: 750 }, /** * @class 'L.Minichart' * @summary add add bar, pie and polar charts to a leaflet map * @desc L.Minichart is used to add dynamic charts on a leaflet map. It is specially * useful to represent multiple data values associated to some geographical * coordinates. * * @example * * L.minichart([0, 0], {data: [1, 2, 3], maxValues: 3}) * * @param {L.Point} center * @param {MinichartOptions} options - Object containing * options to construct a chart. */ initialize: function(center, options) { this._center = center; this._zoom = 0; this.options = utils.mergeOptions(options, this.options); this._setMaxValue(); L.CircleMarker.prototype.initialize.call( this, center, {radius: this.options.width/2, stroke: false, fill: false} ); }, onAdd: function(map) { L.CircleMarker.prototype.onAdd.call(this, map); // Change class of container so that the element hides when zooming var container = this._container || this._renderer._rootGroup; container.setAttribute("class", "leaflet-zoom-hide"); // create the svg element that holds the chart this._chart = d3.select(container).append("g"); if (L.version >= "1.0") this.addInteractiveTarget(this._chart.node()); map.on('moveend', this._onMoveend, this); this._redraw(true); }, onRemove: function(map) { // remove layer's DOM elements and listeners L.CircleMarker.prototype.onRemove.call(this, map); this._chart.selectAll("*").remove(); map.off('moveend', this._onMoveend, this); }, _onMoveend: function() { // Redraw chart only if zoom has changed var oldZoom = this._zoom; this._zoom = this._map.getZoom(); if (oldZoom != this._zoom) this._redraw() ; }, /** Update the options of a minichart object. * @method setOptions * @instance * @memberOf 'L.Minichart' * * @param {MinichartOptions} options - Object containing options to update the chart. */ setOptions: function(options) { var newChart = options.type && options.type != this.options.type; this.options = utils.mergeOptions(options, this.options); this._setMaxValue(); this._redraw(newChart); }, _setMaxValue: function() { // Max absolute value for each variable var max = this.options.maxValues; var data = utils.toArray(this.options.data); if (max === "auto") { max = Math.max( d3.max(data), Math.abs(d3.min(data)) ) if (max == 0) max = 1; } max = utils.toArray(max); if(max.length !== 1 && max.length != data.length) { throw new Error("'maxValues' should be a single number or have same length as 'data'"); } for (var i = 0; i < data.length; i++) { if (Math.abs(data[i]) > max[i % max.length]) { console.warn("Some data values are greater than 'maxValues'." + " Chart will be truncated. You should set option 'maxValues'" + " to avoid this problem."); break; } } this.options.maxValues = max; }, _redraw: function(newChart) { // Move container on the map var c = this._map.latLngToLayerPoint(this._center); var h; if (this.options.type == "bar") { h = this.options.height * 2; } else { h = this.options.width; } this._chart .attr("transform", "translate(" + (c.x - this.options.width / 2) + "," + (c.y - h / 2) + ")") .transition() .duration(this.options.transitionTime) .attr("opacity", this.options.opacity); // prepare data var data = this.options.data; data = utils.toArray(data); for (var i = 0; i < data.length; i++) { if (isNaN(data[i]) || !isFinite(data[i])) data[i] = 0; } var max = this.options.maxValues; // Scale data. This step is essential to have different scales for each // variable. Only relevant if chart is not a pie/ var dataScaled = []; if (this.options.type == "pie") { dataScaled = data; } else { for (var i = 0; i < data.length; i++) { dataScaled.push(data[i] / max[i % max.length]); } } // Prepare labels var labels = this.options.labels; if (labels === "auto") { labels = utils.prettyNumbers(data); } // Generator function var generator, type; switch(this.options.type) { case "bar": generator = minicharts.Barchart; break; case "pie": generator = minicharts.Piechart; break; case "polar-radius": generator = minicharts.Polarchart; type = "radius"; break; case "polar-area": generator = minicharts.Polarchart; type = "area"; break; } // Graphical options for the generator function var chartOpts = { width: this.options.width, height: this.options.height * 2, // Used only if type = "bar" colors: this.options.colors, type: type, transitionTime: this.options.transitionTime, minValue: -1, maxValue:1, labels: labels, labelColors: this.options.labelColor, labelMinSize: this.options.labelMinSize, labelMaxSize: this.options.labelMaxSize, labelPadding: this.options.labelPadding, labelClass: "leaflet-clickable leaflet-interactive", shapeClass: "leaflet-clickable leaflet-interactive" }; // Create of update chart if (newChart === true) { this._chart.selectAll("*").remove(); this._chartObject = new generator(this._chart.node(), dataScaled, chartOpts); } else { this._chartObject.update(dataScaled, chartOpts); } } }); L.minichart = function(center, options) { return new L.Minichart(center, options); }; })(); <|start_filename|>docs/tutorial-PISA scores.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>leaflet.minichart Tutorial: International comparison of PISA scores</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.sandstone.css"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">leaflet.minichart</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="topNavigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Reference<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="-_L.Minichart_.html">'L.Minichart'</a></li> </ul> </li> <li class="dropdown"> <a href="tutorials.list.html" class="dropdown-toggle" data-toggle="dropdown">Exemples<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="tutorial-PISA scores.html">International comparison of PISA scores</a></li> </ul> </li> </ul> <div class="col-sm-3 col-md-3"> <form class="navbar-form" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="search-input"> <div class="input-group-btn"> <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </div> </div> </div> </div> <div class="container" id="toc-content"> <div class="row"> <div class="col-md-12"> <div id="main"> <section class="tutorial-section"> <header> <h2>International comparison of PISA scores</h2> </header> <article> <p>The <a href="https://en.wikipedia.org/wiki/Programme_for_International_Student_Assessment">Program for International Student Assesment (PISA)</a> is an international study conducted by the OECD. It measures the evolution of the performance of 15 years old pupils on mathematics, science and reading in different countries.</p> <p>This document demonstrates how to use the <code>leaflet.minichart</code> plugin to represent over a leaflet map the scores of the pupils of the different countries.</p> <h2>Data</h2><p>The data to represent has the following format:</p> <pre class="prettyprint source lang-javascript"><code>var data = [ {&quot;year&quot;:2015,&quot;country&quot;:&quot;Australia&quot;,&quot;math&quot;:494,&quot;reading&quot;:503,&quot;science&quot;:510,&quot;lon&quot;:133.7751,&quot;lat&quot;:-25.2744}, {&quot;year&quot;:2015,&quot;country&quot;:&quot;Austria&quot;,&quot;math&quot;:497,&quot;reading&quot;:485,&quot;science&quot;:495,&quot;lon&quot;:14.5501,&quot;lat&quot;:47.5162}, {&quot;year&quot;:2015,&quot;country&quot;:&quot;Belgium&quot;,&quot;math&quot;:507,&quot;reading&quot;:499,&quot;science&quot;:502,&quot;lon&quot;:4.4699,&quot;lat&quot;:50.5039}, ... ];</code></pre><p>We also have the average score for each category:</p> <pre class="prettyprint source lang-javascript"><code>var avgScores = {math: 493.4, reading: 492.7, science: 498.2};</code></pre><h2>Initialisation of the map</h2><p>In the header of our html file we include <code>leaflet</code> and the <code>leaflet.minichart</code> plugin:</p> <pre class="prettyprint source lang-xml"><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/leaflet@0.7.3/dist/leaflet.css&quot; media=&quot;screen&quot; title=&quot;leaflet&quot;> &lt;script src=&quot;https://unpkg.com/leaflet@0.7.3/dist/leaflet.js&quot; charset=&quot;utf-8&quot;>&lt;/script> &lt;script src=&quot;../dist/leaflet.minichart.min.js&quot; charset=&quot;utf-8&quot;>&lt;/script> &lt;script src=&quot;https://unpkg.com/leaflet.minichart@0.1.3/dist/leaflet.minichart.min.js&quot; charset=&quot;utf-8&quot;>&lt;/script></code></pre><p>We also add a div that will contain the leaflet map:</p> <pre class="prettyprint source lang-xml"><code>&lt;div id=&quot;map&quot; style=&quot;width:100%;height:400px;&quot;>&lt;/div></code></pre><p>The following javascript code initializes the map:</p> <pre class="prettyprint source lang-javascript"><code>var center = [48.861415, 4.349326]; var mymap = L.map('map').setView(center, 4); var tiles = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}'); tiles.addTo(mymap);</code></pre><p>We now want to add to the map barcharts that represent the deviance to the mean of the three scores for year 2015. To do so, we loop over our data and create a <code>minicharts</code> object for each country. We store store them in an array so we will be able to update them later.</p> <pre class="prettyprint source lang-javascript"><code>var charts = {}; for (var i = 0; i &lt; data.length; i++) { var d = data[i]; if (d.year == 2015) { var scoresDiff = [ d.math - avgScores.math, d.reading - avgScores.reading, d.science - avgScores.science ]; charts[d.country] = L.minichart([d.lat, d.lon], {data: scoresDiff, maxValues: 90}); mymap.addLayer(charts[d.country] ) ; } }</code></pre><div id="map0" style="width:100%;height:400px;margin-bottom:20px;"></div> <p>We can improve our map by passing some additional options to <code>L.minichart</code> to reduce the size of the charts and use prettier colors:</p> <pre class="prettyprint source lang-javascript"><code>charts[d.country] = L.minichart( [d.lat, d.lon], { data: scoresDiff, maxValues: 90, width:40, height:40, colors: [&quot;#7A8B99&quot;, &quot;#91ADC2&quot;, &quot;#A9DDD6&quot;] } );</code></pre><div id="map1" style="width:100%;height:400px;margin-bottom:20px;"></div> <h2>Update charts</h2><p>We have represented the PISA results for 2015 but we would like to also look at the results of the other years. To do so let us add a select input to our document. Each time the user changes the value of the input a javascript function called &quot;updateMap&quot; is</p> <pre class="prettyprint source lang-xml"><code>&lt;select id = &quot;year&quot; onchange=&quot;updateMap()&quot;> &lt;option value=&quot;2015&quot;>2015&lt;/option> &lt;option value=&quot;2012&quot;>2012&lt;/option> &lt;option value=&quot;2009&quot;>2009&lt;/option> &lt;option value=&quot;2006&quot;>2006&lt;/option> &lt;/select></code></pre><p>To update charts we use the <code>setOption</code> method.</p> <pre class="prettyprint source lang-javascript"><code>function updateMap() { var year = document.getElementById(&quot;year&quot;).value; for (var i = 0; i &lt; data.length; i++) { var d = data[i]; if (d.year == year) { var scoresDiff = [ d.math - avgScores.math, d.reading - avgScores.reading, d.science - avgScores.science ]; charts[d.country].setOptions({data:scoresDiff}); } } }</code></pre><p>Here is the final result:</p> <p><select id = "year" onchange="updateMap()"> <option value="2015">2015</option> <option value="2012">2012</option> <option value="2009">2009</option> <option value="2006">2006</option> </select></p> <div id="map" style="width:100%;height:600px;margin-bottom:10px;"></div> <p><link rel="stylesheet" href="https://unpkg.com/leaflet@0.7.3/dist/leaflet.css" media="screen" title="leaflet"></p> <script src="https://unpkg.com/leaflet@0.7.3/dist/leaflet.js" charset="utf-8"></script> <script src="leaflet.minichart.min.js" charset="utf-8"></script> <script type="text/javascript" src = "js/pisa.js"></script> </article> </section> </div> </div> <div class="clearfix"></div> </div> </div> <div class="modal fade" id="searchResults"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Search results</h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <footer> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on 2017-05-03T11:04:16+02:00 using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>. </span> </footer> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/toc.js"></script> <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/); lang = langClassMatch ? langClassMatch[1] : "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : false, showMenu : false, enableDoclinks : true } ); $.catchAnchorLinks( { navbarOffset: 10 } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { return $( heading ).attr( "id" ) || ( prefix + i ); }, selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4", showAndHide : false, smoothScrolling: true } ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); $( "table" ).each( function () { var $this = $( this ); $this.addClass('table'); } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> <script type="text/javascript"> $(document).ready(function() { SearcherDisplay.init(); }); </script> </body> </html> <|start_filename|>docs/js/pisa.js<|end_filename|> var data = [ {"year":2015,"country":"Australia","math":494,"reading":503,"science":510,"lon":133.7751,"lat":-25.2744}, {"year":2015,"country":"Austria","math":497,"reading":485,"science":495,"lon":14.5501,"lat":47.5162}, {"year":2015,"country":"Belgium","math":507,"reading":499,"science":502,"lon":4.4699,"lat":50.5039}, {"year":2015,"country":"Canada","math":516,"reading":527,"science":528,"lon":-106.3468,"lat":56.1304}, {"year":2015,"country":"Chile","math":423,"reading":459,"science":447,"lon":-71.543,"lat":-35.6751}, {"year":2015,"country":"Czech Republic","math":492,"reading":487,"science":493,"lon":15.473,"lat":49.8175}, {"year":2015,"country":"Denmark","math":511,"reading":500,"science":502,"lon":9.5018,"lat":56.2639}, {"year":2015,"country":"Estonia","math":520,"reading":519,"science":534,"lon":25.0136,"lat":58.5953}, {"year":2015,"country":"Finland","math":511,"reading":526,"science":531,"lon":25.7482,"lat":61.9241}, {"year":2015,"country":"France","math":493,"reading":499,"science":495,"lon":2.2137,"lat":46.2276}, {"year":2015,"country":"Germany","math":506,"reading":509,"science":509,"lon":10.4515,"lat":51.1657}, {"year":2015,"country":"Greece","math":454,"reading":467,"science":455,"lon":21.8243,"lat":39.0742}, {"year":2015,"country":"Hungary","math":477,"reading":470,"science":477,"lon":19.5033,"lat":47.1625}, {"year":2015,"country":"Iceland","math":488,"reading":482,"science":473,"lon":-19.0208,"lat":64.9631}, {"year":2015,"country":"Ireland","math":504,"reading":521,"science":503,"lon":-7.6921,"lat":53.1424}, {"year":2015,"country":"Israel","math":470,"reading":479,"science":467,"lon":34.8516,"lat":31.0461}, {"year":2015,"country":"Italy","math":490,"reading":485,"science":481,"lon":12.5674,"lat":41.8719}, {"year":2015,"country":"Japan","math":532,"reading":516,"science":538,"lon":138.2529,"lat":36.2048}, {"year":2015,"country":"Korea","math":524,"reading":517,"science":516,"lon":127.9785,"lat":37.664}, {"year":2015,"country":"Latvia","math":482,"reading":488,"science":490,"lon":24.6032,"lat":56.8796}, {"year":2015,"country":"Luxembourg","math":486,"reading":481,"science":483,"lon":6.1296,"lat":49.8153}, {"year":2015,"country":"Mexico","math":408,"reading":423,"science":416,"lon":-102.5528,"lat":23.6345}, {"year":2015,"country":"Netherlands","math":512,"reading":503,"science":509,"lon":5.2913,"lat":52.1326}, {"year":2015,"country":"New Zealand","math":495,"reading":509,"science":513,"lon":174.886,"lat":-40.9006}, {"year":2015,"country":"Norway","math":502,"reading":513,"science":498,"lon":8.4689,"lat":60.472}, {"year":2015,"country":"Poland","math":504,"reading":506,"science":501,"lon":19.1451,"lat":51.9194}, {"year":2015,"country":"Portugal","math":492,"reading":498,"science":501,"lon":-8.2245,"lat":39.3999}, {"year":2015,"country":"Slovak Republic","math":475,"reading":453,"science":461,"lon":19.699,"lat":48.669}, {"year":2015,"country":"Slovenia","math":510,"reading":505,"science":513,"lon":14.9955,"lat":46.1512}, {"year":2015,"country":"Spain","math":486,"reading":496,"science":493,"lon":-3.7492,"lat":40.4637}, {"year":2015,"country":"Sweden","math":494,"reading":500,"science":493,"lon":18.6435,"lat":60.1282}, {"year":2015,"country":"Switzerland","math":521,"reading":492,"science":506,"lon":8.2275,"lat":46.8182}, {"year":2015,"country":"Turkey","math":420,"reading":428,"science":425,"lon":35.2433,"lat":38.9637}, {"year":2015,"country":"United Kingdom","math":492,"reading":498,"science":509,"lon":-3.436,"lat":55.3781}, {"year":2015,"country":"United States","math":470,"reading":497,"science":496,"lon":-95.7129,"lat":37.0902}, {"year":2012,"country":"Australia","math":504,"reading":512,"science":521,"lon":133.7751,"lat":-25.2744}, {"year":2012,"country":"Austria","math":506,"reading":490,"science":506,"lon":14.5501,"lat":47.5162}, {"year":2012,"country":"Belgium","math":515,"reading":509,"science":505,"lon":4.4699,"lat":50.5039}, {"year":2012,"country":"Canada","math":518,"reading":523,"science":525,"lon":-106.3468,"lat":56.1304}, {"year":2012,"country":"Chile","math":423,"reading":441,"science":445,"lon":-71.543,"lat":-35.6751}, {"year":2012,"country":"Czech Republic","math":499,"reading":493,"science":508,"lon":15.473,"lat":49.8175}, {"year":2012,"country":"Denmark","math":500,"reading":496,"science":498,"lon":9.5018,"lat":56.2639}, {"year":2012,"country":"Estonia","math":521,"reading":516,"science":541,"lon":25.0136,"lat":58.5953}, {"year":2012,"country":"Finland","math":519,"reading":524,"science":545,"lon":25.7482,"lat":61.9241}, {"year":2012,"country":"France","math":495,"reading":505,"science":499,"lon":2.2137,"lat":46.2276}, {"year":2012,"country":"Germany","math":514,"reading":508,"science":524,"lon":10.4515,"lat":51.1657}, {"year":2012,"country":"Greece","math":453,"reading":477,"science":467,"lon":21.8243,"lat":39.0742}, {"year":2012,"country":"Hungary","math":477,"reading":488,"science":494,"lon":19.5033,"lat":47.1625}, {"year":2012,"country":"Iceland","math":493,"reading":483,"science":478,"lon":-19.0208,"lat":64.9631}, {"year":2012,"country":"Ireland","math":501,"reading":523,"science":522,"lon":-7.6921,"lat":53.1424}, {"year":2012,"country":"Israel","math":466,"reading":486,"science":470,"lon":34.8516,"lat":31.0461}, {"year":2012,"country":"Italy","math":485,"reading":490,"science":494,"lon":12.5674,"lat":41.8719}, {"year":2012,"country":"Japan","math":536,"reading":538,"science":547,"lon":138.2529,"lat":36.2048}, {"year":2012,"country":"Korea","math":554,"reading":536,"science":538,"lon":127.9785,"lat":37.664}, {"year":2012,"country":"Latvia","math":491,"reading":489,"science":502,"lon":24.6032,"lat":56.8796}, {"year":2012,"country":"Luxembourg","math":490,"reading":488,"science":491,"lon":6.1296,"lat":49.8153}, {"year":2012,"country":"Mexico","math":413,"reading":424,"science":415,"lon":-102.5528,"lat":23.6345}, {"year":2012,"country":"Netherlands","math":523,"reading":511,"science":522,"lon":5.2913,"lat":52.1326}, {"year":2012,"country":"New Zealand","math":500,"reading":512,"science":516,"lon":174.886,"lat":-40.9006}, {"year":2012,"country":"Norway","math":489,"reading":504,"science":495,"lon":8.4689,"lat":60.472}, {"year":2012,"country":"Poland","math":518,"reading":518,"science":526,"lon":19.1451,"lat":51.9194}, {"year":2012,"country":"Portugal","math":487,"reading":488,"science":489,"lon":-8.2245,"lat":39.3999}, {"year":2012,"country":"Slovak Republic","math":482,"reading":463,"science":471,"lon":19.699,"lat":48.669}, {"year":2012,"country":"Slovenia","math":501,"reading":481,"science":514,"lon":14.9955,"lat":46.1512}, {"year":2012,"country":"Spain","math":484,"reading":488,"science":496,"lon":-3.7492,"lat":40.4637}, {"year":2012,"country":"Sweden","math":478,"reading":483,"science":485,"lon":18.6435,"lat":60.1282}, {"year":2012,"country":"Switzerland","math":531,"reading":509,"science":515,"lon":8.2275,"lat":46.8182}, {"year":2012,"country":"Turkey","math":448,"reading":475,"science":463,"lon":35.2433,"lat":38.9637}, {"year":2012,"country":"United Kingdom","math":494,"reading":499,"science":514,"lon":-3.436,"lat":55.3781}, {"year":2012,"country":"United States","math":481,"reading":498,"science":497,"lon":-95.7129,"lat":37.0902}, {"year":2009,"country":"Australia","math":514,"reading":515,"science":527,"lon":133.7751,"lat":-25.2744}, {"year":2009,"country":"Austria","math":496,"reading":470,"science":494,"lon":14.5501,"lat":47.5162}, {"year":2009,"country":"Belgium","math":515,"reading":506,"science":507,"lon":4.4699,"lat":50.5039}, {"year":2009,"country":"Canada","math":527,"reading":524,"science":529,"lon":-106.3468,"lat":56.1304}, {"year":2009,"country":"Chile","math":421,"reading":449,"science":447,"lon":-71.543,"lat":-35.6751}, {"year":2009,"country":"Czech Republic","math":493,"reading":478,"science":500,"lon":15.473,"lat":49.8175}, {"year":2009,"country":"Denmark","math":503,"reading":495,"science":499,"lon":9.5018,"lat":56.2639}, {"year":2009,"country":"Estonia","math":512,"reading":501,"science":528,"lon":25.0136,"lat":58.5953}, {"year":2009,"country":"Finland","math":541,"reading":536,"science":554,"lon":25.7482,"lat":61.9241}, {"year":2009,"country":"France","math":497,"reading":496,"science":498,"lon":2.2137,"lat":46.2276}, {"year":2009,"country":"Germany","math":513,"reading":497,"science":520,"lon":10.4515,"lat":51.1657}, {"year":2009,"country":"Greece","math":466,"reading":483,"science":470,"lon":21.8243,"lat":39.0742}, {"year":2009,"country":"Hungary","math":490,"reading":494,"science":503,"lon":19.5033,"lat":47.1625}, {"year":2009,"country":"Iceland","math":507,"reading":500,"science":496,"lon":-19.0208,"lat":64.9631}, {"year":2009,"country":"Ireland","math":487,"reading":496,"science":508,"lon":-7.6921,"lat":53.1424}, {"year":2009,"country":"Israel","math":447,"reading":474,"science":455,"lon":34.8516,"lat":31.0461}, {"year":2009,"country":"Italy","math":483,"reading":486,"science":489,"lon":12.5674,"lat":41.8719}, {"year":2009,"country":"Japan","math":529,"reading":520,"science":539,"lon":138.2529,"lat":36.2048}, {"year":2009,"country":"Korea","math":546,"reading":539,"science":538,"lon":127.9785,"lat":37.664}, {"year":2009,"country":"Latvia","math":482,"reading":484,"science":494,"lon":24.6032,"lat":56.8796}, {"year":2009,"country":"Luxembourg","math":489,"reading":472,"science":484,"lon":6.1296,"lat":49.8153}, {"year":2009,"country":"Mexico","math":419,"reading":425,"science":416,"lon":-102.5528,"lat":23.6345}, {"year":2009,"country":"Netherlands","math":526,"reading":508,"science":522,"lon":5.2913,"lat":52.1326}, {"year":2009,"country":"New Zealand","math":519,"reading":521,"science":532,"lon":174.886,"lat":-40.9006}, {"year":2009,"country":"Norway","math":498,"reading":503,"science":500,"lon":8.4689,"lat":60.472}, {"year":2009,"country":"Poland","math":495,"reading":500,"science":508,"lon":19.1451,"lat":51.9194}, {"year":2009,"country":"Portugal","math":487,"reading":489,"science":493,"lon":-8.2245,"lat":39.3999}, {"year":2009,"country":"Slovak Republic","math":497,"reading":477,"science":490,"lon":19.699,"lat":48.669}, {"year":2009,"country":"Slovenia","math":501,"reading":483,"science":512,"lon":14.9955,"lat":46.1512}, {"year":2009,"country":"Spain","math":483,"reading":481,"science":488,"lon":-3.7492,"lat":40.4637}, {"year":2009,"country":"Sweden","math":494,"reading":497,"science":495,"lon":18.6435,"lat":60.1282}, {"year":2009,"country":"Switzerland","math":534,"reading":501,"science":517,"lon":8.2275,"lat":46.8182}, {"year":2009,"country":"Turkey","math":445,"reading":464,"science":454,"lon":35.2433,"lat":38.9637}, {"year":2009,"country":"United Kingdom","math":492,"reading":494,"science":514,"lon":-3.436,"lat":55.3781}, {"year":2009,"country":"United States","math":487,"reading":500,"science":502,"lon":-95.7129,"lat":37.0902}, {"year":2006,"country":"Australia","math":520,"reading":513,"science":527,"lon":133.7751,"lat":-25.2744}, {"year":2006,"country":"Austria","math":505,"reading":490,"science":511,"lon":14.5501,"lat":47.5162}, {"year":2006,"country":"Belgium","math":520,"reading":501,"science":510,"lon":4.4699,"lat":50.5039}, {"year":2006,"country":"Canada","math":527,"reading":527,"science":534,"lon":-106.3468,"lat":56.1304}, {"year":2006,"country":"Chile","math":411,"reading":442,"science":438,"lon":-71.543,"lat":-35.6751}, {"year":2006,"country":"Czech Republic","math":510,"reading":483,"science":513,"lon":15.473,"lat":49.8175}, {"year":2006,"country":"Denmark","math":513,"reading":494,"science":496,"lon":9.5018,"lat":56.2639}, {"year":2006,"country":"Estonia","math":515,"reading":501,"science":531,"lon":25.0136,"lat":58.5953}, {"year":2006,"country":"Finland","math":548,"reading":547,"science":563,"lon":25.7482,"lat":61.9241}, {"year":2006,"country":"France","math":496,"reading":488,"science":495,"lon":2.2137,"lat":46.2276}, {"year":2006,"country":"Germany","math":504,"reading":495,"science":516,"lon":10.4515,"lat":51.1657}, {"year":2006,"country":"Greece","math":459,"reading":460,"science":473,"lon":21.8243,"lat":39.0742}, {"year":2006,"country":"Hungary","math":491,"reading":482,"science":504,"lon":19.5033,"lat":47.1625}, {"year":2006,"country":"Iceland","math":506,"reading":484,"science":491,"lon":-19.0208,"lat":64.9631}, {"year":2006,"country":"Ireland","math":501,"reading":517,"science":508,"lon":-7.6921,"lat":53.1424}, {"year":2006,"country":"Israel","math":442,"reading":439,"science":454,"lon":34.8516,"lat":31.0461}, {"year":2006,"country":"Italy","math":462,"reading":469,"science":475,"lon":12.5674,"lat":41.8719}, {"year":2006,"country":"Japan","math":523,"reading":498,"science":531,"lon":138.2529,"lat":36.2048}, {"year":2006,"country":"Korea","math":547,"reading":556,"science":522,"lon":127.9785,"lat":37.664}, {"year":2006,"country":"Latvia","math":486,"reading":479,"science":490,"lon":24.6032,"lat":56.8796}, {"year":2006,"country":"Luxembourg","math":490,"reading":479,"science":486,"lon":6.1296,"lat":49.8153}, {"year":2006,"country":"Mexico","math":406,"reading":410,"science":410,"lon":-102.5528,"lat":23.6345}, {"year":2006,"country":"Netherlands","math":531,"reading":507,"science":525,"lon":5.2913,"lat":52.1326}, {"year":2006,"country":"New Zealand","math":522,"reading":521,"science":530,"lon":174.886,"lat":-40.9006}, {"year":2006,"country":"Norway","math":490,"reading":484,"science":487,"lon":8.4689,"lat":60.472}, {"year":2006,"country":"Poland","math":495,"reading":508,"science":498,"lon":19.1451,"lat":51.9194}, {"year":2006,"country":"Portugal","math":466,"reading":472,"science":474,"lon":-8.2245,"lat":39.3999}, {"year":2006,"country":"Slovak Republic","math":492,"reading":466,"science":488,"lon":19.699,"lat":48.669}, {"year":2006,"country":"Slovenia","math":504,"reading":494,"science":519,"lon":14.9955,"lat":46.1512}, {"year":2006,"country":"Spain","math":480,"reading":461,"science":488,"lon":-3.7492,"lat":40.4637}, {"year":2006,"country":"Sweden","math":502,"reading":507,"science":503,"lon":18.6435,"lat":60.1282}, {"year":2006,"country":"Switzerland","math":530,"reading":499,"science":512,"lon":8.2275,"lat":46.8182}, {"year":2006,"country":"Turkey","math":424,"reading":447,"science":424,"lon":35.2433,"lat":38.9637}, {"year":2006,"country":"United Kingdom","math":495,"reading":495,"science":515,"lon":-3.436,"lat":55.3781}, {"year":2006,"country":"United States","math":474,"science":489,"lon":-95.7129,"lat":37.0902} ]; var avgScores = {math: 493.4, reading: 492.7, science: 498.2}; var niceOptions = { width:40, height:40, colors: ["#7A8B99", "#91ADC2", "#A9DDD6"] } // Initialize maps. initMap("map0"); initMap("map1", niceOptions); var charts = initMap("map", niceOptions); function initMap(id, options) { var coord = [48.861415, 6.349326]; var mymap = L.map(id).setView(coord, 4); var tiles = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}'); tiles.addTo(mymap); var charts = {}; var d, scoresDiff; for (var i = 0; i < data.length; i++) { d = data[i]; if (d.year == 2015) { scoresDiff = [ d.math - avgScores.math, d.reading - avgScores.reading, d.science - avgScores.science ]; charts[d.country] = L.minichart([d.lat, d.lon], {data: scoresDiff, maxValues: 90}); mymap.addLayer(charts[d.country]); if (options) { charts[d.country].setOptions(options); } } } return charts; } function updateMap() { var year = document.getElementById("year").value; for (var i = 0; i < data.length; i++) { var d = data[i]; if (d.year == year) { var scoresDiff = [ d.math - avgScores.math, d.reading - avgScores.reading, d.science - avgScores.science ]; charts[d.country].setOptions({data:scoresDiff}); } } } <|start_filename|>docs/index.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>leaflet.minichart Index</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.sandstone.css"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">leaflet.minichart</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="topNavigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Reference<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="-_L.Minichart_.html">'L.Minichart'</a></li> </ul> </li> <li class="dropdown"> <a href="tutorials.list.html" class="dropdown-toggle" data-toggle="dropdown">Exemples<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="tutorial-PISA scores.html">International comparison of PISA scores</a></li> </ul> </li> </ul> <div class="col-sm-3 col-md-3"> <form class="navbar-form" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="search-input"> <div class="input-group-btn"> <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </div> </div> </div> </div> <div class="container" id="toc-content"> <div class="row"> <div class="col-md-8"> <div id="main"> <section class="readme-section"> <article><h1>Leaflet.minichart</h1><p>Leaflet.minichart is a leaflet plugin for adding to a leaflet map small animated bar charts, pie charts or polar area charts.</p> <p>It can be used to visualize multiple variables associated to geographical coordinates and to look at the evolution of these variables.</p> <p>Here are screenshots of some maps that use this plugin.</p> <p><img src="img/piecharts.png" alt=""> <img src="img/barcharts.png" alt=""> <img src="img/bubblecharts.png" alt=""></p> <p>This plugin is also available as an <a href="https://github.com/rte-antares-rpackage/leaflet.minicharts">R package</a>.</p> <h2>Usage</h2><p>You need to include the <code>leaflet</code> CSS and javascript files and then the <code>leaflet.minichart</code> javascript file in the head section of your document:</p> <pre class="prettyprint source lang-xml"><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/leaflet@1.0.2/dist/leaflet.css&quot; media=&quot;screen&quot; title=&quot;leaflet&quot;> &lt;script src=&quot;https://unpkg.com/leaflet@1.0.2/dist/leaflet.js&quot; charset=&quot;utf-8&quot;>&lt;/script> &lt;script src=&quot;https://unpkg.com/leaflet.minichart/dist/leaflet.minichart.min.js&quot; charset=&quot;utf-8&quot;>&lt;/script></code></pre><p>Once these files included, you can create charts with function <code>L.minichart()</code>. All parameters are described <a href="https://rte-antares-rpackage.github.io/leaflet.minichart/-_L.Minichart_.html">here</a>.</p> <h2>Example</h2><p>Here is a sample code that initializes a map and adds to it a barchart that represents three random values. Then the code updates the value every two seconds and redraws the chart.</p> <pre class="prettyprint source lang-javascript"><code>var center = [48.861415, 2.349326]; var mymap = L.map('map').setView(coord, 13); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(mymap); // Let us generate fake data function fakeData() { return [Math.random(), Math.random(), Math.random()]; } // Create a barchart var myBarChart = L.minichart(center, {data: fakeData()}); mymap.addLayer(myBarChart); // Update data every 2 seconds setInterval(function() { myBarChart.setOptions({data: fakeData()}) }, 2000);</code></pre><p><img src="img/example_barchart.gif" alt="Example of a barchart on a map"></p> <p>You can find more complete examples here:</p> <ul> <li><a href="https://rte-antares-rpackage.github.io/leaflet.minichart/tutorial-PISA%20scores.html">International comparison of PISA scores</a></li> </ul></article> </section> </div> </div> <div class="clearfix"></div> <div class="col-md-3"> <div id="toc" class="col-md-3 hidden-xs hidden-sm hidden-md"></div> </div> </div> </div> <div class="modal fade" id="searchResults"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Search results</h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <footer> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on 2017-05-03T11:04:16+02:00 using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>. </span> </footer> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/toc.js"></script> <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/); lang = langClassMatch ? langClassMatch[1] : "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : false, showMenu : false, enableDoclinks : true } ); $.catchAnchorLinks( { navbarOffset: 10 } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { return $( heading ).attr( "id" ) || ( prefix + i ); }, selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4", showAndHide : false, smoothScrolling: true } ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); $( "table" ).each( function () { var $this = $( this ); $this.addClass('table'); } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> <script type="text/javascript"> $(document).ready(function() { SearcherDisplay.init(); }); </script> </body> </html> <|start_filename|>docs/-_L.Minichart_.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>leaflet.minichart L.Minichart</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.sandstone.css"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">leaflet.minichart</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="topNavigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Reference<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="-_L.Minichart_.html">'L.Minichart'</a></li> </ul> </li> <li class="dropdown"> <a href="tutorials.list.html" class="dropdown-toggle" data-toggle="dropdown">Exemples<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="tutorial-PISA scores.html">International comparison of PISA scores</a></li> </ul> </li> </ul> <div class="col-sm-3 col-md-3"> <form class="navbar-form" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="search-input"> <div class="input-group-btn"> <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </div> </div> </div> </div> <div class="container" id="toc-content"> <div class="row"> <div class="col-md-8"> <div id="main"> <h1 class="page-title">L.Minichart</h1> <section> <header> </header> <article> <div class="container-overview"> <p class="summary"><em style="font-size:1.5em;">add add bar, pie and polar charts to a leaflet map</em></p> <hr> <dd> <div class="description"> L.Minichart is used to add dynamic charts on a leaflet map. It is specially useful to represent multiple data values associated to some geographical coordinates. </div> <h3>Constructor</h3> <h4 class="name" id="'L.Minichart'"><span class="type-signature"></span>new L.Minichart(center, options)</h4> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>center</code></td> <td class="type"> <span class="param-type">L.Point</span> </td> <td class="description last"></td> </tr> <tr> <td class="name"><code>options</code></td> <td class="type"> <span class="param-type">MinichartOptions</span> </td> <td class="description last">Object containing options to construct a chart.</td> </tr> </tbody> </table> <dl class="details"> </dl> <h5>Example</h5> <pre class="sunlight-highlight-javascript">L.minichart([0, 0], {data: [1, 2, 3], maxValues: 3})</pre> </dd> </div> <h3 class="subsection-title">Options</h3> <dl> <dd> <dl class="details"> <dl> <table class="props table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>type</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="default"> "bar" </td> <td class="description last">Type of chart to create. Possible values are "bar" for barcharts, "pie" for pie charts, "polar-radius" and "polar-area" for polar area charts where values are represented either by the radius or the area of the slices.</td> </tr> <tr> <td class="name"><code>data</code></td> <td class="type"> <span class="param-type">Array.&lt;number></span> </td> <td class="default"> [1] </td> <td class="description last">Data values the chart has to represent.</td> </tr> <tr> <td class="name"><code>maxValues</code></td> <td class="type"> <span class="param-type">Array.&lt;number></span> | <span class="param-type">"auto"</span> </td> <td class="default"> "auto" </td> <td class="description last">maximal absolute value the data could take. It can be a single numeric value or an array of values with same length as data. In the first case, all values will be represented with the same scale while in the second case, each value will have its own scale. This is useful when one wants to represent multiple variables that are not comparable. If it equals to "auto" (the default) then the maximum absolute value in data is used.</td> </tr> <tr> <td class="name"><code>colors</code></td> <td class="type"> <span class="param-type">Array.&lt;string></span> </td> <td class="default"> d3.schemeCategory10 </td> <td class="description last">Array of colors. If its length is less than the length of data, colors are recycled.</td> </tr> <tr> <td class="name"><code>width</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="default"> 60 </td> <td class="description last">Width of the chart when `type` equals 'bar' or maximal diameter of the chart for all other types.</td> </tr> <tr> <td class="name"><code>height</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="default"> 60 </td> <td class="description last">Maximal height of barcharts.</td> </tr> <tr> <td class="name"><code>labels</code></td> <td class="type"> <span class="param-type">Array.&lt;string></span> | <span class="param-type">"none"</span> | <span class="param-type">"auto"</span> </td> <td class="default"> "none" </td> <td class="description last">Labels to display on the chart. If it equals to "auto" then data values are displayed in a compact way.</td> </tr> <tr> <td class="name"><code>labelMinSize</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="default"> 8 </td> <td class="description last">Labels are automatically hidden if the label height is less than this number.</td> </tr> <tr> <td class="name"><code>labelMaxSize</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="default"> 24 </td> <td class="description last">Maximal height of labels in pixels.</td> </tr> <tr> <td class="name"><code>labelPadding</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="default"> 2 </td> <td class="description last">Padding to apply to labels.</td> </tr> <tr> <td class="name"><code>labelStyle</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="default"> "font-family:sans-serif" </td> <td class="description last">CSS style to apply to labels</td> </tr> <tr> <td class="name"><code>labelColor</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="default"> "auto" </td> <td class="description last">Color to apply to labels. If "auto", text will be black or white depending on the background color.</td> </tr> <tr> <td class="name"><code>transitionTime</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="default"> 750 </td> <td class="description last">Duration in millisecondq of transitions.</td> </tr> </tbody> </table> </dl> </dl> </dd> </dl> <h3 class="subsection-title">Methods</h3> <dl> <hr> <dd> <h4 class="name" id="setOptions"><span class="type-signature"></span>setOptions(options)</h4> <div class="description"> Update the options of a minichart object. </div> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>options</code></td> <td class="type"> <span class="param-type">MinichartOptions</span> </td> <td class="description last">Object containing options to update the chart.</td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> </dl> </article> </section> </div> </div> <div class="clearfix"></div> <div class="col-md-3"> <div id="toc" class="col-md-3 hidden-xs hidden-sm hidden-md"></div> </div> </div> </div> <div class="modal fade" id="searchResults"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Search results</h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <footer> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on 2017-05-03T11:04:16+02:00 using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>. </span> </footer> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/toc.js"></script> <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/); lang = langClassMatch ? langClassMatch[1] : "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : false, showMenu : false, enableDoclinks : true } ); $.catchAnchorLinks( { navbarOffset: 10 } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { return $( heading ).attr( "id" ) || ( prefix + i ); }, selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4", showAndHide : false, smoothScrolling: true } ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); $( "table" ).each( function () { var $this = $( this ); $this.addClass('table'); } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> <script type="text/javascript"> $(document).ready(function() { SearcherDisplay.init(); }); </script> </body> </html>
rte-antares-rpackage/leaflet.minichart
<|start_filename|>lib/src/view/app_statefulwidget.dart<|end_filename|> /// /// Copyright (C) 2018 <NAME> /// /// 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. /// /// Created 24 Dec 2018 /// import 'dart:async' show Future; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart' show FlutterExceptionHandler, Key, mustCallSuper, protected; import 'package:flutter/material.dart'; import 'package:mvc_application/controller.dart' show AppConMVC, ControllerMVC; import 'package:mvc_application/controller.dart' show Assets; import 'package:mvc_application/view.dart' as v show App, AppMVC, AppMenu, AppState, AppStateWidget, I10n, ReportErrorHandler, SetState; import 'package:prefs/prefs.dart' show Prefs; // Replace 'dart:io' for Web applications import 'package:universal_platform/universal_platform.dart'; // Export the classes needed to use this file. export 'package:connectivity_plus/connectivity_plus.dart' show Connectivity, ConnectivityResult; /// Error Screen Builder if an error occurs. typedef ErrorWidgetBuilder = Widget Function( FlutterErrorDetails flutterErrorDetails); /// The app-level StatefulWidget /// The widget passed to runApp(). abstract class AppStatefulWidget extends v.AppMVC { // You must supply a 'View.' AppStatefulWidget({ AppConMVC? con, Key? key, this.loadingScreen, FlutterExceptionHandler? errorHandler, ErrorWidgetBuilder? errorScreen, v.ReportErrorHandler? errorReport, bool allowNewHandlers = true, }) : _app = v.App( errorHandler: errorHandler, errorScreen: errorScreen, errorReport: errorReport, allowNewHandlers: allowNewHandlers, ), super(con: con, key: key) { // Listen to the device's connectivity. _app.addConnectivityListener(con); _app.setAppStatefulWidget(this); } final v.App _app; @protected v.AppState createView(); /// Gives access to the App's View. The 'MyView' you first work with. static v.AppState? get vw => _vw; static v.AppState? _vw; /// Supply on onboarding screen. final Widget? loadingScreen; @override Widget build(BuildContext context) { Assets.init(context); return FutureBuilder<bool>( future: initAsync(), initialData: false, builder: (_, snapshot) => _asyncBuilder(snapshot, loadingScreen)); } /// Runs all the asynchronous operations necessary before the app can proceed. @override Future<bool> initAsync() async { var init = true; try { if (v.App.hotReload) { _vw = createView(); _vw?.con?.initApp(); } else { // Initialize System Preferences await Prefs.init(); // Collect installation & connectivity information await _app.initInternal(); // // If not running on the Web. // if (!kIsWeb) { await v.App.getDeviceInfo(); // } // Initiate multi-language translations. await v.I10n.initAsync(); // Set theme using App's menu system if any theme was saved. v.AppMenu.setThemeData(); init = await super.initAsync(); if (init) { _vw = createView(); // Supply the state object to the App object. init = _app.setAppState(_vw); if (init) { init = await _vw!.initAsync(); } if (init) { _vw?.con?.initApp(); } } } } catch (e) { init = false; v.App.isInit = false; rethrow; } return v.App.isInit = init; } /// Clean up resources before the app is finally terminated. @mustCallSuper @override void dispose() { Prefs.dispose(); // Assets.init(context); called in App.build() -gp Assets.dispose(); // _app.dispose(); super.dispose(); } /// Run the CircularProgressIndicator() until asynchronous operations are /// completed before the app proceeds. Widget _asyncBuilder(AsyncSnapshot<bool> snapshot, Widget? loading) { if (snapshot.hasData && snapshot.data! && (v.App.isInit != null && v.App.isInit!)) { // return const v.AppStateWidget(); // } else if (snapshot.hasError) { // final dynamic exception = snapshot.error; final details = FlutterErrorDetails( exception: exception, stack: exception is Error ? exception.stackTrace : null, library: 'app_statefulwidget.dart', context: ErrorDescription('While getting ready in FutureBuilder Async'), ); var handled = false; if (_vw != null) { // handled = _vw!.onAsyncError(details); } if (!handled) { // _app.onAsyncError(snapshot); } return v.App.errorHandler!.displayError(details); // } else if (snapshot.connectionState == ConnectionState.done && snapshot.hasData && !snapshot.data!) { // final FlutterErrorDetails details = FlutterErrorDetails( exception: Exception('App failed to initialize'), library: 'app_statefulwidget.dart', context: ErrorDescription('Please, notify admin.'), ); FlutterError.reportError(details); return ErrorWidget.builder(details); // } else if (snapshot.connectionState == ConnectionState.done || // (v.App.isInit != null && v.App.isInit!)) { // return const v.AppStateWidget(); } else { // Widget widget; if (loading != null) { // widget = loading; } else { // if (UniversalPlatform.isAndroid || UniversalPlatform.isWeb) { // widget = const Center(child: CircularProgressIndicator()); } else { // widget = const Center(child: CupertinoActivityIndicator()); } } return widget; } } } /// Obtains [Controllers<T>] from its ancestors and passes its value to [builder]. /// class ConConsumer<T extends ControllerMVC> extends StatelessWidget { const ConConsumer({ Key? key, required this.builder, this.child, }) : super(key: key); /// The builder final Widget Function(BuildContext context, T? controller, Widget? child) builder; /// The child widget to pass to [builder]. final Widget? child; @override Widget build(BuildContext context) => v.SetState( builder: (context, object) => builder( context, AppStatefulWidget._vw?.controllerByType<T>(), child, )); } <|start_filename|>lib/src/view/utils/error_handler.dart<|end_filename|> /// /// Copyright (C) 2020 <NAME> /// /// 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. /// /// Created 10 Feb 2020 /// /// import 'dart:ui' as ui show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, TextStyle; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder, DiagnosticsTreeStyle, FlutterError, FlutterErrorDetails, FlutterExceptionHandler, InformationCollector, StringProperty; import 'package:flutter/rendering.dart' show Color, DiagnosticPropertiesBuilder, EdgeInsets, FlutterError, Offset, Paint, PaintingContext, RenderBox, Size, StringProperty, TextAlign, TextDirection; typedef ReportErrorHandler = Future<void> Function( dynamic exception, StackTrace stack); /// Your App's error handler. class AppErrorHandler { factory AppErrorHandler({ FlutterExceptionHandler? handler, ErrorWidgetBuilder? builder, ReportErrorHandler? report, bool allowNewHandlers = true, }) { _this ??= AppErrorHandler._(builder); /// Allows you to set an error handler more than once. set(handler: handler, builder: builder, report: report); // Once set to false, you can't assign different handlers anymore. if (!allowNewHandlers) { _allowNewHandlers = false; } return _this!; } AppErrorHandler._(ErrorWidgetBuilder? builder) { // Record the current error handler. _oldOnError = FlutterError.onError; // Record the current Widget builder when a widget fails to build. _oldBuilder = ErrorWidget.builder; // At the start, define our own 'error building widget' widget if one is not provided. builder ??= errorDisplayWidget; ErrorWidget.builder = builder; FlutterError.onError = (FlutterErrorDetails details) { // Prevent an infinite loop and fall back to the original handler. if (_inHandler) { // An error in the Error Handler if (_onError != null && _oldOnError != null) { _onError = null; try { _oldOnError!(details); } catch (ex) { // intentionally left empty. } } return; } // If there's an error in the error handler, we want to know about it. _inHandler = true; final _handler = _onError ?? _oldOnError; if (_handler != null) { _handler(details); _inHandler = false; } }; // Record the 'current' error handler. _flutterExceptionHandler = FlutterError.onError; } static AppErrorHandler? _this; static bool _allowNewHandlers = true; // FlutterExceptionHandler get oldOnError => _oldOnError; static FlutterExceptionHandler? _oldOnError; // // ErrorWidgetBuilder get oldBuilder => _oldBuilder; ErrorWidgetBuilder? _oldBuilder; static ReportErrorHandler? _errorReport; static bool _inHandler = false; static bool ranApp = false; FlutterExceptionHandler? get flutterExceptionHandler => _flutterExceptionHandler; static FlutterExceptionHandler? _flutterExceptionHandler; FlutterExceptionHandler? get onError => _onError ?? _oldOnError; static FlutterExceptionHandler? _onError; /// Set a handler and the report static bool set({ required FlutterExceptionHandler? handler, ErrorWidgetBuilder? builder, ReportErrorHandler? report, }) { // Once you're not allowed to reset the handlers, it can't be reversed. if (!_allowNewHandlers) { return false; } // Are you allowed to reset a handler? // Only if an item was passed to reset. var reset = false; if (handler != null) { // The default is to dump the error to the console. You can do more. _onError = handler; reset = true; } if (report != null) { _errorReport = report; reset = true; } if (builder != null) { // Change the widget presented when another widget fails to build. ErrorWidget.builder = builder; reset = true; } // Something was set; return reset; } /// Display the Error details in a widget. /// try..catch to ensure a widget is returned. Widget displayError(FlutterErrorDetails details) { Widget widget; try { widget = ErrorWidget.builder(details); } catch (ex) { widget = errorDisplayWidget(details); } return widget; } /// Return the original handlers. void dispose() { // Restore the error widget routine. if (_oldBuilder != null) { ErrorWidget.builder = _oldBuilder!; } // Return the original error routine. if (_oldOnError != null) { FlutterError.onError = _oldOnError; } } /// Determines if running in an IDE or in production. static bool get inDebugger { var inDebugMode = false; // assert is removed in production. assert(inDebugMode = true); return inDebugMode; } /// Report the error. Future<void> reportError( dynamic ex, StackTrace stack, { String? message, String? library, InformationCollector? informationCollector, }) async { if (_errorReport == null) { message ??= 'while attempting to execute your app'; library ??= 'Your app'; _debugReportException( ErrorSummary(message), ex, stack, library: library, informationCollector: informationCollector, ); } else { await _errorReport!(ex, stack); } } /// Report the error in an isolate. void isolateError(dynamic ex, StackTrace stack) { reportError( ex, stack, message: 'while attempting to execute main()', library: 'likely main.dart', ); } /// Report the error in a zone. void runZonedError(dynamic ex, StackTrace stack) { reportError( ex, stack, message: 'while attempting to execute runApp()', library: 'controller/app.dart', ); } /// Display the error details. // This is a copy used in the Flutter Framework. FlutterErrorDetails _debugReportException( DiagnosticsNode context, dynamic exception, StackTrace stack, { String library = 'Flutter framework', InformationCollector? informationCollector, }) { final details = FlutterErrorDetails( exception: exception, stack: stack, library: library, context: context, informationCollector: informationCollector, ); FlutterError.reportError(details); return details; } /// This class is intentionally doing things using the low-level /// primitives to avoid depending on any subsystems that may have ended /// up in an unstable state -- after all, this class is mainly used when /// things have gone wrong. static Widget errorDisplayWidget(FlutterErrorDetails details) { String message; try { message = 'ERROR\n\n${details.exception}\n\n'; final stackTrace = details.stack.toString().split('\n'); final length = stackTrace.length > 5 ? 5 : stackTrace.length; final buffer = StringBuffer()..write(message); for (var i = 0; i < length; i++) { buffer.write('${stackTrace[i]}\n'); } message = buffer.toString(); } catch (e) { message = 'Error'; } final exception = details.exception; return DisplayErrorWidget( message: message, error: exception is Error ? exception : null); } } /// A low-level widget to present instead of the failed widget. class DisplayErrorWidget extends LeafRenderObjectWidget { DisplayErrorWidget({this.message = '', Error? error}) : _error = error, super(key: UniqueKey()); /// The message to display. final String message; final Error? _error; @override RenderBox createRenderObject(BuildContext context) => _ErrorBox(_errorMessage()); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (_error == null || _error is! FlutterError) { properties.add(StringProperty('message', _errorMessage(), quoted: false)); } else { final FlutterError _flutterError = _error as FlutterError; properties.add(_flutterError.toDiagnosticsNode( style: DiagnosticsTreeStyle.whitespace)); } } // Compose an error message to be displayed. // An empty string if no message was provided. String _errorMessage() { String _message; if (message.isEmpty) { if (_error == null) { _message = ''; } else { _message = _error.toString(); } } else { _message = message; } return _message; } } class _ErrorBox extends RenderBox { /// /// A message can optionally be provided. If a message is provided, an attempt /// will be made to render the message when the box paints. _ErrorBox([this.message = '']) { try { if (message != '') { /// /// Generally, the much better way to draw text in a RenderObject is to /// use the TextPainter class. If you're looking for code to crib from, /// see the paragraph.dart file and the RenderParagraph class. final builder = ui.ParagraphBuilder(paragraphStyle) ..pushStyle(textStyle) ..addText(message); _paragraph = builder.build(); } } catch (error) { // Intentionally left empty. } } /// The message to attempt to display at paint time. final String message; ui.Paragraph? _paragraph; @override double computeMaxIntrinsicWidth(double height) { return 100000; } @override double computeMaxIntrinsicHeight(double width) { return 100000; } @override bool get sizedByParent => true; @override bool hitTestSelf(Offset position) => true; @override void performResize() { size = constraints.constrain(const Size(100000, 100000)); } /// The distance to place around the text. /// /// This is intended to ensure that if the [RenderBox] is placed at the top left /// of the screen, under the system's status bar, the error text is still visible in /// the area below the status bar. /// /// The padding is ignored if the error box is smaller than the padding. /// /// See also: /// /// * [minimumWidth], which controls how wide the box must be before the // horizontal padding is applied. static EdgeInsets padding = const EdgeInsets.fromLTRB(34, 96, 34, 12); /// The width below which the horizontal padding is not applied. /// /// If the left and right padding would reduce the available width to less than /// this value, then the text is rendered flush with the left edge. static double minimumWidth = 200; /// The color to use when painting the background of [RenderBox] objects. /// a red from a light gray. static Color backgroundColor = _initBackgroundColor(); /// Ligt gray in production; Red in development. static Color _initBackgroundColor() { var result = const Color(0xF0C0C0C0); assert(() { result = const Color(0xF0900000); return true; }()); return result; } /// The text style to use when painting [RenderBox] objects. /// a dark gray sans-serif font. static ui.TextStyle textStyle = _initTextStyle(); /// Black text in production; Yellow in development. static ui.TextStyle _initTextStyle() { var result = ui.TextStyle( color: const Color(0xFF303030), fontFamily: 'sans-serif', fontSize: 18, ); assert(() { result = ui.TextStyle( color: const Color(0xFFFFFF66), fontFamily: 'monospace', fontSize: 14, fontWeight: FontWeight.bold, ); return true; }()); return result; } /// The paragraph style to use when painting [RenderBox] objects. static ui.ParagraphStyle paragraphStyle = ui.ParagraphStyle( textDirection: TextDirection.ltr, textAlign: TextAlign.left, ); @override void paint(PaintingContext context, Offset offset) { try { context.canvas.drawRect(offset & size, Paint()..color = backgroundColor); if (_paragraph != null) { var width = size.width; var left = 0.0; var top = 0.0; if (width > padding.left + minimumWidth + padding.right) { width -= padding.left + padding.right; left += padding.left; } _paragraph!.layout(ui.ParagraphConstraints(width: width)); if (size.height > padding.top + _paragraph!.height + padding.bottom) { top += padding.top; } context.canvas.drawParagraph(_paragraph!, offset + Offset(left, top)); } } catch (ex) { // Intentionally left empty. } } } @Deprecated('Use the AppErrorHandler class now.') class ErrorHandler { ErrorHandler({ FlutterExceptionHandler? handler, ErrorWidgetBuilder? builder, ReportErrorHandler? report, }) { errorHandler = AppErrorHandler( handler: handler, builder: builder, report: report, ); } late AppErrorHandler errorHandler; void dispose() => errorHandler.dispose(); static bool get inDebugger => AppErrorHandler.inDebugger; Future<void> reportError( dynamic ex, StackTrace stack, { String? message, String? library, InformationCollector? informationCollector, }) => errorHandler.reportError( ex, stack, message: message, library: library, informationCollector: informationCollector, ); void isolateError(dynamic ex, StackTrace stack) => errorHandler.isolateError(ex, stack); void runZonedError(dynamic ex, StackTrace stack) => errorHandler.runZonedError(ex, stack); } <|start_filename|>lib/run_app.dart<|end_filename|> /// /// Copyright (C) 2021 <NAME> /// /// 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. /// /// Created 28 Sep 2021 /// /// At times, you may need to explicitly supply the custom runApp function: /// /// import 'package:mvc_application/run_app.dart'; /// /// Otherwise, it's supplied by the view.dart export file. /// export 'package:mvc_application/src/conditional_export.dart' if (dart.library.html) 'package:mvc_application/src/view/platforms/run_webapp.dart' if (dart.library.io) 'package:mvc_application/src/view/platforms/run_app.dart' show runApp; <|start_filename|>lib/src/view/uxutils/src/view/dialog_box.dart<|end_filename|> /// /// Copyright (C) 2019 <NAME> /// /// 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. /// /// Created 05 Feb 2019 /// import 'package:mvc_application/view.dart'; /// A high-level function /// Displays a String passing specific one to two button options /// and their corresponding fucntion calls. /// Displays a particular dialogue box depending on platform. Future<bool> showBox({ required BuildContext context, String? text, Option? button01, Option? button02, VoidCallback? press01, VoidCallback? press02, Widget? title, EdgeInsetsGeometry? titlePadding, TextStyle? titleTextStyle, Widget? content, EdgeInsetsGeometry? contentPadding, TextStyle? contentTextStyle, List<Widget>? actions, EdgeInsetsGeometry? actionsPadding, VerticalDirection? actionsOverflowDirection, double? actionsOverflowButtonSpacing, EdgeInsetsGeometry? buttonPadding, Color? backgroundColor, double? elevation, String? semanticLabel, EdgeInsets? insetPadding, Clip? clipBehavior, ShapeBorder? shape, bool? scrollable, bool? barrierDismissible, Color? barrierColor, String? barrierLabel, bool? useSafeArea, bool? useRootNavigator, RouteSettings? routeSettings, }) async { button01 ??= OKOption(); button02 ??= CancelOption(); bool? result; if (App.useMaterial) { result = await showDialog<bool>( context: context, barrierDismissible: barrierDismissible ?? true, barrierColor: barrierColor ?? Colors.black54, barrierLabel: barrierLabel, useSafeArea: useSafeArea ?? true, useRootNavigator: useRootNavigator ?? true, routeSettings: routeSettings, builder: (BuildContext context) => AlertDialog( title: title, titlePadding: titlePadding, titleTextStyle: titleTextStyle, content: content ?? Text(text ?? ' '), contentPadding: contentPadding ?? const EdgeInsets.fromLTRB(24, 20, 24, 24), contentTextStyle: contentTextStyle, actionsPadding: actionsPadding ?? EdgeInsets.zero, actionsOverflowDirection: actionsOverflowDirection, actionsOverflowButtonSpacing: actionsOverflowButtonSpacing, buttonPadding: buttonPadding, backgroundColor: backgroundColor, elevation: elevation, semanticLabel: semanticLabel, insetPadding: insetPadding ?? const EdgeInsets.symmetric(horizontal: 40, vertical: 24), clipBehavior: clipBehavior ?? Clip.none, shape: shape, scrollable: scrollable ?? false, actions: <Widget>[ TextButton( onPressed: () { if (press02 != null) { press02(); } if (button02!.onPressed != null) { button02.onPressed!(); } Navigator.pop(context, button02.result ?? false); }, child: Text(button02!.text ?? 'Cancel'), ), TextButton( onPressed: () { if (press01 != null) { press01(); } if (button01!.onPressed != null) { button01.onPressed!(); } Navigator.pop(context, button01.result ?? true); }, child: Text(button01!.text ?? 'OK'), ), ]), ); } else { result = await showCupertinoDialog<bool>( context: context, builder: (BuildContext context) => CupertinoAlertDialog(content: Text(text ?? ' '), actions: <Widget>[ CupertinoDialogAction( onPressed: () { if (press02 != null) { press02(); } if (button02!.onPressed != null) { button02.onPressed!(); } Navigator.pop(context, button02.result ?? false); }, child: Text(button02!.text ?? 'Cancel'), ), CupertinoDialogAction( onPressed: () { if (press01 != null) { press01(); } if (button01!.onPressed != null) { button01.onPressed!(); } Navigator.pop(context, button01.result ?? true); }, child: Text(button01!.text ?? 'OK'), ), ]), ); } return result ?? false; } /// A high-level function /// Displays a String passing specific one to two button options /// and their corresponding function calls. void dialogBox({ required BuildContext context, String? title, Option? button01, Option? button02, VoidCallback? press01, VoidCallback? press02, bool barrierDismissible = false, bool switchButtons = false, }) { showDialog<bool>( context: context, barrierDismissible: barrierDismissible, builder: (BuildContext context) { return _DialogWindow( context: context, title: title, button01: button01, button02: button02, press01: press01, press02: press02, switchButtons: switchButtons, ).show(); }); } class _DialogWindow with DialogOptions { _DialogWindow({ required BuildContext context, this.title, Option? button01, Option? button02, VoidCallback? press01, VoidCallback? press02, bool? switchButtons, }) { this.context = context; this.button01 = button01; this.button02 = button02; this.press01 = press01; this.press02 = press02; this.switchButtons = switchButtons; } final String? title; SimpleDialog show() { return SimpleDialog( title: Text(title ?? ' '), children: _listOptions(), ); } } mixin DialogOptions { BuildContext? context; Option? button01; Option? button02; VoidCallback? press01; VoidCallback? press02; bool? switchButtons; List<Widget> _listOptions() { final opList = <Widget>[]; Option option01, option02; if (button01 != null || press01 != null) { option01 = Option( text: button01?.text ?? 'Cancel', onPressed: press01 ?? button01!.onPressed, result: true); } else { option01 = CancelOption(); } if (button02 != null || press02 != null) { option02 = Option( text: button02?.text ?? 'OK', onPressed: press02 ?? button02!.onPressed, result: false); } else { if (option01 is! OKOption) { option02 = OKOption(); opList.add(_simpleOption(option02)); } else { option02 = CancelOption(); } } if (switchButtons != null && switchButtons!) { opList.add(_simpleOption(option02)); opList.add(_simpleOption(option01)); } else { opList.add(_simpleOption(option01)); opList.add(_simpleOption(option02)); } return opList; } Widget _simpleOption(Option option) => SimpleDialogOption( onPressed: () { if (option.onPressed != null) { option.onPressed!(); } Navigator.pop(context!, option.result); }, child: Text(option.text!), ); } class Option { Option({this.text, this.onPressed, this.result}) : assert(result != null, 'Must provide a option result!'); final String? text; final VoidCallback? onPressed; final dynamic result; } class OKOption extends Option { OKOption({VoidCallback? onPressed}) : super( text: 'OK', onPressed: () { if (onPressed != null) { onPressed(); } }, result: true, ); } class CancelOption extends Option { CancelOption({VoidCallback? onPressed}) : super( text: 'Cancel', onPressed: () { if (onPressed != null) { onPressed(); } }, result: false, ); } class MsgBox { const MsgBox({ required this.context, this.title, this.msg, this.body, this.actions, }); final BuildContext context; final String? title; final String? msg; final List<Widget>? body; final List<Widget>? actions; Future<void> show({ BuildContext? context, String? title, String? msg, List<Widget>? body, List<Widget>? actions, }) { context = context ?? this.context; title = title ?? this.title; msg = msg ?? this.msg; body = body ?? this.body; if (body == null) { if (msg == null || msg.isEmpty) { body = [const Text('Shall we continue?')]; } else { body = [Text(msg)]; } } actions = actions ?? this.actions; actions ??= <Widget>[ TextButton( onPressed: () { Navigator.pop(context!); }, child: const Text('OK'), ), ]; return showDialog<void>( context: context, barrierDismissible: false, builder: (BuildContext context) => AlertDialog( title: Text(title ?? ''), content: SingleChildScrollView( child: ListBody( children: body!, ), ), actions: actions, )); } } /// Display an extensive widget to a dialogue window. /// class DialogBox with DialogOptions { DialogBox({ required BuildContext context, this.title, Option? button01, Option? button02, VoidCallback? press01, VoidCallback? press02, bool? switchButtons, this.body, this.actions, this.barrierDismissible = false, }) { this.context = context; this.button01 = button01; this.button02 = button02; this.press01 = press01; this.press02 = press02; this.switchButtons = switchButtons; } final String? title; final List<Widget>? body; final List<Widget>? actions; final bool? barrierDismissible; Future<void> show({ BuildContext? context, String? title, Option? button01, Option? button02, VoidCallback? press01, VoidCallback? press02, bool? switchButtons, String? msg, List<Widget>? body, List<Widget>? actions, bool? barrierDismissible, }) { context = context ?? this.context; title = title ?? this.title; title ??= ''; this.button01 ??= button01; this.button02 ??= button02; this.press01 ??= press01; this.press02 ??= press02; this.switchButtons ??= switchButtons; body = body ?? this.body; body ??= [Container()]; actions ??= this.actions; actions ??= _listOptions(); barrierDismissible ??= this.barrierDismissible ?? false; return showDialog<void>( context: context!, barrierDismissible: barrierDismissible, builder: (BuildContext context) => AlertDialog( title: Text(title!), content: SingleChildScrollView( child: ListBody( children: body!, ), ), actions: actions, )); } } <|start_filename|>lib/src/controller/app.dart<|end_filename|> /// /// Copyright (C) 2018 <NAME> /// /// 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. /// /// Created 24 Dec 2018 /// import 'package:flutter/foundation.dart' show FlutterErrorDetails; import 'package:mvc_application/controller.dart' show HandleError; import 'package:mvc_application/view.dart' as v show App, ConnectivityListener, ConnectivityResult, StateMVC; import 'package:mvc_pattern/mvc_pattern.dart' as mvc; /// A Controller for the 'app level'. class AppController extends ControllerMVC implements mvc.AppConMVC { // AppController([v.StateMVC? state]) : super(state); /// Initialize any immediate 'none time-consuming' operations /// at the very beginning. @override void initApp() {} /// Override if you like to customize your error handling. @override void onError(FlutterErrorDetails details) { // Call the App's 'current' error handler. v.App?.onError(details); } } /// A Controller for the 'app level' to influence the whole app. class AppConMVC extends mvc.AppConMVC with v.ConnectivityListener, HandleError { // AppConMVC([v.StateMVC? state]) : super(state); /// If the device's connectivity changes. @override void onConnectivityChanged(v.ConnectivityResult result) {} } /// Your 'working' class most concerned with the app's functionality. /// Incorporates an Error Handler. class ControllerMVC extends mvc.ControllerMVC with HandleError { // ControllerMVC([v.StateMVC? state]) : super(state); } <|start_filename|>lib/src/conditional_export.dart<|end_filename|> /// /// Copyright (C) 2020 <NAME> /// /// 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. /// /// Created 02 Oct 2020 /// /// /// Merely a 'stub' used by conditional import and export statements. import 'package:flutter/material.dart' show ErrorWidgetBuilder, Widget; import 'package:flutter/foundation.dart' show FlutterExceptionHandler; import 'package:mvc_application/view.dart' show ReportErrorHandler; /// Used in the conditional export statement: /// Found in 'package:mvc_application/view.dart' /// For example: /// export 'package:mvc_application/src/conditional_export.dart' /// if (dart.library.html) 'package:flutter/material.dart' /// if (dart.library.io) 'package:mvc_application/src/controller/app.dart' show runApp; /// This of course is fake. Merely to satisfy the Dart Analysis tool. void runApp( Widget app, { FlutterExceptionHandler? errorHandler, ErrorWidgetBuilder? errorScreen, ReportErrorHandler? errorReport, bool allowNewHandlers = false, }) {} <|start_filename|>lib/src/view/platforms/run_app.dart<|end_filename|> /// /// Copyright (C) 2021 <NAME> /// /// 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. /// /// Created 28 Sep 2021 /// import 'dart:async' show runZonedGuarded; import 'dart:isolate' show Isolate, RawReceivePort; import 'package:flutter/foundation.dart' show FlutterExceptionHandler; import 'package:flutter/material.dart' as m show ErrorWidgetBuilder, Widget, runApp; import 'package:mvc_application/view.dart' as v show AppErrorHandler, ReportErrorHandler; /// Add an Error Handler right at the start. void runApp( m.Widget app, { FlutterExceptionHandler? errorHandler, m.ErrorWidgetBuilder? errorScreen, v.ReportErrorHandler? errorReport, bool allowNewHandlers = false, }) { // Instantiate the app's error handler. final handler = v.AppErrorHandler( handler: errorHandler, builder: errorScreen, report: errorReport, allowNewHandlers: allowNewHandlers); Isolate.current.addErrorListener(RawReceivePort((dynamic pair) { // if (pair is List<dynamic>) { final isolateError = pair; handler.isolateError( isolateError.first.toString(), StackTrace.fromString(isolateError.last.toString()), ); } }).sendPort); // Catch any errors attempting to execute runApp(); runZonedGuarded(() { m.runApp(app); }, handler.runZonedError); }
AndriousSolutions/mvc_application
<|start_filename|>Assets/NewtonVR/Example/Shaders/3DText.shader<|end_filename|> // Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)' Shader "GUI/3DText" { Properties { _MainTex("Font Texture", 2D) = "white" {} } SubShader { Tags{ "RenderType" = "Transparent" "Queue" = "Transparent" } Pass { Blend SrcAlpha OneMinusSrcAlpha ZWrite Off CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; struct v2f { float4 pos : SV_POSITION; fixed4 color : COLOR; float2 uv : TEXCOORD0; }; struct appdata { float4 vertex : POSITION; fixed4 color : COLOR; float2 texcoord : TEXCOORD0; }; float4 _MainTex_ST; v2f vert(appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.color = v.color; o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); return o; } fixed4 frag(v2f o) : COLOR { // this gives us text or not based on alpha, apparently o.color.a *= tex2D(_MainTex, o.uv).a; return o.color; } ENDCG } } } <|start_filename|>Assets/NewtonVR/Oculus/NVROculusInputDevice.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; #if NVR_Oculus namespace NewtonVR { public class NVROculusInputDevice : NVRInputDevice { private GameObject RenderModel; private OVRInput.Controller Controller; private Dictionary<NVRButtons, OVRInput.Button> ButtonMapping = new Dictionary<NVRButtons, OVRInput.Button>(new NVRButtonsComparer()); private Dictionary<NVRButtons, OVRInput.Touch> TouchMapping = new Dictionary<NVRButtons, OVRInput.Touch>(new NVRButtonsComparer()); private Dictionary<NVRButtons, OVRInput.NearTouch> NearTouchMapping = new Dictionary<NVRButtons, OVRInput.NearTouch>(new NVRButtonsComparer()); private Dictionary<NVRButtons, OVRInput.Axis1D> TriggerMapping = new Dictionary<NVRButtons, OVRInput.Axis1D>(new NVRButtonsComparer()); private Dictionary<NVRButtons, OVRInput.Axis2D> StickMapping = new Dictionary<NVRButtons, OVRInput.Axis2D>(new NVRButtonsComparer()); public override void Initialize(NVRHand hand) { base.Initialize(hand); SetupButtonMapping(); if (hand == Hand.Player.LeftHand) { Controller = OVRInput.Controller.LTouch; } else { Controller = OVRInput.Controller.RTouch; } } protected virtual void SetupButtonMapping() { ButtonMapping.Add(NVRButtons.A, OVRInput.Button.One); ButtonMapping.Add(NVRButtons.B, OVRInput.Button.Two); ButtonMapping.Add(NVRButtons.X, OVRInput.Button.One); ButtonMapping.Add(NVRButtons.Y, OVRInput.Button.Two); ButtonMapping.Add(NVRButtons.Touchpad, OVRInput.Button.PrimaryThumbstick); ButtonMapping.Add(NVRButtons.DPad_Up, OVRInput.Button.DpadUp); ButtonMapping.Add(NVRButtons.DPad_Down, OVRInput.Button.DpadDown); ButtonMapping.Add(NVRButtons.DPad_Left, OVRInput.Button.DpadLeft); ButtonMapping.Add(NVRButtons.DPad_Right, OVRInput.Button.DpadRight); ButtonMapping.Add(NVRButtons.Trigger, OVRInput.Button.PrimaryIndexTrigger); ButtonMapping.Add(NVRButtons.Grip, OVRInput.Button.PrimaryHandTrigger); ButtonMapping.Add(NVRButtons.System, OVRInput.Button.Back); ButtonMapping.Add(NVRButtons.ApplicationMenu, OVRInput.Button.Start); TouchMapping.Add(NVRButtons.A, OVRInput.Touch.One); TouchMapping.Add(NVRButtons.B, OVRInput.Touch.Two); TouchMapping.Add(NVRButtons.X, OVRInput.Touch.One); TouchMapping.Add(NVRButtons.Y, OVRInput.Touch.Two); TouchMapping.Add(NVRButtons.Touchpad, OVRInput.Touch.PrimaryThumbstick); TouchMapping.Add(NVRButtons.Trigger, OVRInput.Touch.PrimaryIndexTrigger); NearTouchMapping.Add(NVRButtons.Touchpad, OVRInput.NearTouch.PrimaryThumbButtons); NearTouchMapping.Add(NVRButtons.Trigger, OVRInput.NearTouch.PrimaryIndexTrigger); TriggerMapping.Add(NVRButtons.Grip, OVRInput.Axis1D.PrimaryHandTrigger); TriggerMapping.Add(NVRButtons.Trigger, OVRInput.Axis1D.PrimaryIndexTrigger); StickMapping.Add(NVRButtons.Touchpad, OVRInput.Axis2D.PrimaryThumbstick); } private OVRInput.Button GetButtonMap(NVRButtons button) { if (ButtonMapping.ContainsKey(button) == false) { //Debug.LogError("No Oculus button configured for: " + button.ToString()); return OVRInput.Button.None; } return ButtonMapping[button]; } private OVRInput.Touch GetTouchMap(NVRButtons button) { if (TouchMapping.ContainsKey(button) == false) { //Debug.LogError("No Oculus touch map configured for: " + button.ToString()); return OVRInput.Touch.None; } return TouchMapping[button]; } private OVRInput.NearTouch GetNearTouchMap(NVRButtons button) { if (NearTouchMapping.ContainsKey(button) == false) { //Debug.LogError("No Oculus near touch map configured for: " + button.ToString()); return OVRInput.NearTouch.None; } return NearTouchMapping[button]; } private OVRInput.Axis1D GetTriggerMap(NVRButtons button) { if (TriggerMapping.ContainsKey(button) == false) { //Debug.LogError("No Oculus trigger map configured for: " + button.ToString()); return OVRInput.Axis1D.None; } return TriggerMapping[button]; } private OVRInput.Axis2D GetStickMap(NVRButtons button) { if (StickMapping.ContainsKey(button) == false) { //Debug.LogError("No Oculus stick map configured for: " + button.ToString()); return OVRInput.Axis2D.None; } return StickMapping[button]; } public override float GetAxis1D(NVRButtons button) { return OVRInput.Get(GetTriggerMap(button), Controller); } public override Vector2 GetAxis2D(NVRButtons button) { return OVRInput.Get(GetStickMap(button), Controller); } public override bool GetPressDown(NVRButtons button) { return OVRInput.GetDown(GetButtonMap(button), Controller); } public override bool GetPressUp(NVRButtons button) { return OVRInput.GetUp(GetButtonMap(button), Controller); } public override bool GetPress(NVRButtons button) { return OVRInput.Get(GetButtonMap(button), Controller); } public override bool GetTouchDown(NVRButtons button) { return OVRInput.GetDown(GetTouchMap(button), Controller); } public override bool GetTouchUp(NVRButtons button) { return OVRInput.GetUp(GetTouchMap(button), Controller); } public override bool GetTouch(NVRButtons button) { return OVRInput.Get(GetTouchMap(button), Controller); } public override bool GetNearTouchDown(NVRButtons button) { return OVRInput.GetDown(GetNearTouchMap(button), Controller); } public override bool GetNearTouchUp(NVRButtons button) { return OVRInput.GetUp(GetNearTouchMap(button), Controller); } public override bool GetNearTouch(NVRButtons button) { return OVRInput.Get(GetNearTouchMap(button), Controller); } public override void TriggerHapticPulse(ushort durationMicroSec = 500, NVRButtons button = NVRButtons.Touchpad) { StartCoroutine(DoHapticPulse(durationMicroSec)); } private IEnumerator DoHapticPulse(ushort durationMicroSec) { OVRInput.SetControllerVibration(0.2f, 0.2f, Controller); //Should we allow setting strength float endTime = Time.time + ((float)durationMicroSec / 1000000); do { yield return null; } while (Time.time < endTime); OVRInput.SetControllerVibration(0, 0, Controller); } public override bool IsCurrentlyTracked { get { return OVRInput.GetControllerPositionTracked(Controller); } } public override GameObject SetupDefaultRenderModel() { if (Hand.IsLeft == true) { RenderModel = GameObject.Instantiate(Resources.Load<GameObject>("TouchControllers/oculusTouchLeft")); } else { RenderModel = GameObject.Instantiate(Resources.Load<GameObject>("TouchControllers/oculusTouchRight")); } RenderModel.name = "Render Model for " + Hand.gameObject.name; RenderModel.transform.parent = Hand.transform; RenderModel.transform.localPosition = Vector3.zero; RenderModel.transform.localRotation = Quaternion.identity; RenderModel.transform.localScale = Vector3.one; return RenderModel; } public override bool ReadyToInitialize() { return true; } public override string GetDeviceName() { if (Hand.HasCustomModel == true) { return "Custom"; } else { return OVRInput.GetActiveController().ToString(); } } public override Collider[] SetupDefaultPhysicalColliders(Transform ModelParent) { Collider[] Colliders = null; string name = "oculusTouch"; if (Hand.IsLeft == true) { name += "Left"; } else { name += "Right"; } name += "Colliders"; Transform touchColliders = ModelParent.transform.FindChild(name); if (touchColliders == null) { touchColliders = GameObject.Instantiate(Resources.Load<GameObject>("TouchControllers/" + name)).transform; touchColliders.parent = ModelParent.transform; touchColliders.localPosition = Vector3.zero; touchColliders.localRotation = Quaternion.identity; touchColliders.localScale = Vector3.one; } Colliders = touchColliders.GetComponentsInChildren<Collider>(); return Colliders; } public override Collider[] SetupDefaultColliders() { Collider[] Colliders = null; SphereCollider OculusCollider = RenderModel.AddComponent<SphereCollider>(); OculusCollider.isTrigger = true; OculusCollider.radius = 0.15f; Colliders = new Collider[] { OculusCollider }; return Colliders; } } } #else namespace NewtonVR { public class NVROculusInputDevice : NVRInputDevice { public override bool IsCurrentlyTracked { get { throw new NotImplementedException(); } } public override float GetAxis1D(NVRButtons button) { throw new NotImplementedException(); } public override Vector2 GetAxis2D(NVRButtons button) { throw new NotImplementedException(); } public override string GetDeviceName() { throw new NotImplementedException(); } public override bool GetNearTouch(NVRButtons button) { throw new NotImplementedException(); } public override bool GetNearTouchDown(NVRButtons button) { throw new NotImplementedException(); } public override bool GetNearTouchUp(NVRButtons button) { throw new NotImplementedException(); } public override bool GetPress(NVRButtons button) { throw new NotImplementedException(); } public override bool GetPressDown(NVRButtons button) { throw new NotImplementedException(); } public override bool GetPressUp(NVRButtons button) { throw new NotImplementedException(); } public override bool GetTouch(NVRButtons button) { throw new NotImplementedException(); } public override bool GetTouchDown(NVRButtons button) { throw new NotImplementedException(); } public override bool GetTouchUp(NVRButtons button) { throw new NotImplementedException(); } public override bool ReadyToInitialize() { throw new NotImplementedException(); } public override Collider[] SetupDefaultColliders() { throw new NotImplementedException(); } public override Collider[] SetupDefaultPhysicalColliders(Transform ModelParent) { throw new NotImplementedException(); } public override GameObject SetupDefaultRenderModel() { throw new NotImplementedException(); } public override void TriggerHapticPulse(ushort durationMicroSec = 500, NVRButtons button = NVRButtons.Touchpad) { throw new NotImplementedException(); } } } #endif <|start_filename|>Assets/NewtonVR/NVRTeleporter.cs<|end_filename|> using System.Collections.Generic; using System.Collections; using UnityEngine; namespace NewtonVR { public class NVRTeleporter : MonoBehaviour { public bool TunnelTeleport = true; public float TunnelOverTime = 0.2f; public float VignettePower = 17; public float VignetteEaseInTime = 0.125f; public float VignetteEaseOutTime = 0.1f; public LineRenderer ArcRendererDisplay; public GameObject PlaySpaceDisplay; public GameObject InvalidPointDisplay; public GameObject TargetDisplay; public bool LimitToHorizontal = false; public float LimitSensitivity = 45f; public NVRButtons TeleportButton = NVRButtons.Touchpad; public LayerMask TeleportSurfaceMask; public LayerMask TeleportBlockMask; private LayerMask fullMask; public float ArcStrength = 5; public float ArcMaxLength = 30; public float SampleFrequency = 0.2f; private int samplePoints { get { return Mathf.CeilToInt(ArcMaxLength / SampleFrequency); } } private float curveMod = 0.25f; private float acceleration = -5; private float arcLineDisplayOffset = 0.1f; private float playspaceVerticalOffset = 0.025f; private Dictionary<int, TeleportPreview> teleportPreviews; private NVRPlayer player; private void Awake() { fullMask = TeleportSurfaceMask | TeleportBlockMask; teleportPreviews = new Dictionary<int, TeleportPreview>(); } private void Start() { player = GetComponentInParent<NVRPlayer>(); if (player != null) { Vector3 scale = player.PlayspaceSize / 2; scale.y = 1; //Render Playspace PlaySpaceDisplay.gameObject.transform.localScale = scale; } else { Debug.Log("NVR Player is Null"); } } private void OnValidate() { ArcStrength = Mathf.Max(0.01f, ArcStrength); SampleFrequency = Mathf.Max(0.01f, SampleFrequency); ArcMaxLength = Mathf.Max(SampleFrequency * 2, ArcMaxLength); } /// <summary> /// Paint and check parabolic curve for valid teleport position. Returns null if none found. /// </summary> /// <param name="origin"></param> /// <returns></returns> public Vector3? UpdateArcTeleport(Transform origin, int controllerIndex) { //Controller is not currently paired with a line. Assign if (!teleportPreviews.ContainsKey(controllerIndex)) { TeleportPreview preview = new TeleportPreview(); //Default line is not being used. Assign it. if (teleportPreviews.Count == 0) { preview.ArcLine = ArcRendererDisplay; preview.PlaySpaceDisplay = PlaySpaceDisplay; preview.InvalidPointDisplay = InvalidPointDisplay; preview.TeleportTargetDisplay = TargetDisplay; } //Default line is already in use. Create another one. else { GameObject newLine = Instantiate(ArcRendererDisplay.gameObject, transform) as GameObject; preview.ArcLine = newLine.GetComponent<LineRenderer>(); preview.PlaySpaceDisplay = Instantiate(PlaySpaceDisplay, transform); preview.InvalidPointDisplay = Instantiate(InvalidPointDisplay, transform); preview.TeleportTargetDisplay = Instantiate(TargetDisplay, transform); } teleportPreviews.Add(controllerIndex, preview); } teleportPreviews[controllerIndex].ArcLine.enabled = true; //Update start position to be a little away from the controller Vector3 startPosition = origin.position + (origin.transform.forward * arcLineDisplayOffset); //Check for Valid Teleport. Returns Points along curve until (possible) hit List<Vector3> points; bool hit; RaycastHit hitInfo; bool validTeleport = CheckTeleportCurve(startPosition, origin.TransformDirection(Vector3.forward * ArcStrength), Vector3.up * acceleration, out points, out hit, out hitInfo); //Render Line to second to last point (small gap for display) teleportPreviews[controllerIndex].ArcLine.positionCount = points.Count - 1; for (int i = 0; i < points.Count - 1; i++) { teleportPreviews[controllerIndex].ArcLine.SetPosition(i, points[i]); } if (hit) { //Line hit a surface if (validTeleport) { //Render Plasypace and target Vector3 offset = player.Head.transform.localPosition; offset.y = 0; teleportPreviews[controllerIndex].PlaySpaceDisplay.SetActive(true); Vector3 playSpacePos = hitInfo.point - offset; playSpacePos.y += playspaceVerticalOffset; teleportPreviews[controllerIndex].PlaySpaceDisplay.transform.position = playSpacePos; teleportPreviews[controllerIndex].TeleportTargetDisplay.SetActive(true); teleportPreviews[controllerIndex].TeleportTargetDisplay.transform.position = hitInfo.point; //Hide Invalid teleportPreviews[controllerIndex].InvalidPointDisplay.SetActive(false); //Hit point is final point in curve return hitInfo.point; } else { //Show Invalid teleportPreviews[controllerIndex].InvalidPointDisplay.SetActive(true); teleportPreviews[controllerIndex].InvalidPointDisplay.gameObject.transform.position = hitInfo.point + (hitInfo.normal * 0.05f); teleportPreviews[controllerIndex].InvalidPointDisplay.gameObject.transform.rotation = Quaternion.LookRotation(hitInfo.normal); //Hide Playspace and target teleportPreviews[controllerIndex].PlaySpaceDisplay.SetActive(false); teleportPreviews[controllerIndex].TeleportTargetDisplay.SetActive(false); } } else { //Hide Playspace, Target, and Invalid Marker teleportPreviews[controllerIndex].PlaySpaceDisplay.SetActive(false); teleportPreviews[controllerIndex].InvalidPointDisplay.SetActive(false); teleportPreviews[controllerIndex].TeleportTargetDisplay.SetActive(false); } //No valid teleport data. Return null return null; } /// <summary> /// Hide the arc teleporter (button release) /// </summary> /// <param name="controllerIndex"></param> public void HideArcTeleport(int controllerIndex) { if (teleportPreviews.ContainsKey(controllerIndex) == false) return; teleportPreviews[controllerIndex].ArcLine.positionCount = 0; teleportPreviews[controllerIndex].ArcLine.enabled = false; teleportPreviews[controllerIndex].PlaySpaceDisplay.SetActive(false); teleportPreviews[controllerIndex].InvalidPointDisplay.SetActive(false); teleportPreviews[controllerIndex].TeleportTargetDisplay.SetActive(false); } /// <summary> /// Sample points along a curve until you hit a collider, or you run out of sample points /// </summary> /// <param name="startingPoint">Starting point of your parabolic curve</param> /// <param name="initialVelocity">Initial velocity of your parabolic curve</param> /// <param name="initialAcceleration">Initial acceleration of your parabolic curve</param> /// <returns></returns> private bool CheckTeleportCurve(Vector3 startingPoint, Vector3 initialVelocity, Vector3 initialAcceleration, out List<Vector3> points, out bool hit, out RaycastHit hitInfo) { points = new List<Vector3>() { startingPoint }; hitInfo = new RaycastHit(); bool validTeleport = false; hit = false; Vector3 lastPoint = startingPoint; float t = 0; for (int pointIndex = 0; pointIndex < samplePoints; pointIndex++) { t += SampleFrequency / CurveDerivitive(initialVelocity, initialAcceleration, t).magnitude; Vector3 nextPoint = Curve(startingPoint, initialVelocity, initialAcceleration, t); //Check for a valid teleport collision if (Physics.Linecast(lastPoint, nextPoint, out hitInfo, fullMask)) { //Register the Hit hit = true; //End of curve. Add final position. points.Add(hitInfo.point); //If the hit was a valid teleport position if (TeleportSurfaceMask == (TeleportSurfaceMask | 1 << hitInfo.collider.gameObject.layer)) { if (LimitToHorizontal == false || Vector3.Angle(hitInfo.normal, Vector3.up) <= LimitSensitivity) { validTeleport = true; } } break; } else { points.Add(nextPoint); } lastPoint = nextPoint; } return validTeleport; } /// <summary> /// Teleport Player and anything in their hands to the new location /// </summary> /// <param name="teleportPosition"></param> public void TeleportPlayer(Vector3 teleportPosition) { if (TunnelTeleport) { StartCoroutine(DoTunnelTeleport(teleportPosition)); } else { MovePosition(teleportPosition); } } private void MovePosition(Vector3 newPosition) { if (player != null) { Vector3 offset = player.Head.transform.position - player.transform.position; offset.y = 0; //Move Player Vector3 oldPosition = player.transform.position; player.transform.position = newPosition - offset; offset = player.transform.position - oldPosition; //Teleport any objects in left hand to new hand position if (player.LeftHand.CurrentlyInteracting != null) { player.LeftHand.CurrentlyInteracting.transform.position += offset; } //Teleport any objects in left hand to new hand position if (player.RightHand.CurrentlyInteracting != null) { player.RightHand.CurrentlyInteracting.transform.position += offset; } } } private Vector3 GetPlayerPositionFromCameraPosition(Vector3 newCameraFloor) { if (player != null) { Vector3 offset = player.Head.transform.position - player.transform.position; offset.y = 0; return newCameraFloor - offset; } return Vector3.zero; } private void MovePlayer(Vector3 newPlayerPosition) { if (player != null) { Vector3 offset = newPlayerPosition - player.transform.position; //Move Player player.transform.position = newPlayerPosition; //Teleport any objects in left hand to new hand position if (player.LeftHand.CurrentlyInteracting != null) { player.LeftHand.CurrentlyInteracting.transform.position += offset; } //Teleport any objects in left hand to new hand position if (player.RightHand.CurrentlyInteracting != null) { player.RightHand.CurrentlyInteracting.transform.position += offset; } } } private IEnumerator DoTunnelTeleport(Vector3 teleportPosition) { float easeInStartTime = Time.time; float easeInEndTime = easeInStartTime + VignetteEaseInTime; while (Time.time < easeInEndTime) { yield return null; NVRVignette.instance.SetAmount(Mathf.Lerp(0, VignettePower, (Time.time - easeInStartTime) / VignetteEaseInTime)); } NVRVignette.instance.SetAmount(VignettePower); float moveTimeStart = Time.time; float moveTimeEnd = moveTimeStart + TunnelOverTime; Vector3 initialPosition = player.transform.position; Vector3 endPosition = GetPlayerPositionFromCameraPosition(teleportPosition); while (Time.time < moveTimeEnd) { Vector3 lerpPosition = Vector3.Lerp(initialPosition, endPosition, (Time.time - moveTimeStart) / TunnelOverTime); MovePlayer(lerpPosition); yield return null; } MovePlayer(endPosition); float easeOutStartTime = Time.time; float easeOutEndTime = easeOutStartTime + VignetteEaseOutTime; while (Time.time < easeOutEndTime) { yield return null; NVRVignette.instance.SetAmount(Mathf.Lerp(VignettePower, 0, (Time.time - easeOutStartTime) / VignetteEaseOutTime)); } yield return null; NVRVignette.instance.SetAmount(0); } private Vector3 CurveDerivitive(Vector3 velocity, Vector3 acceleration, float time) { Vector3 result = new Vector3(); result.x = CurveDerivitive(velocity.x, acceleration.x, time); result.y = CurveDerivitive(velocity.y, acceleration.y, time); result.z = CurveDerivitive(velocity.z, acceleration.z, time); return result; } private float CurveDerivitive(float velocity, float acceleration, float time) { return velocity + acceleration * time; } private Vector3 Curve(Vector3 point, Vector3 velocity, Vector3 acceleration, float time) { Vector3 result = new Vector3(); result.x = Curve(point.x, velocity.x, acceleration.x, time); result.y = Curve(point.y, velocity.y, acceleration.y, time); result.z = Curve(point.z, velocity.z, acceleration.z, time); return result; } private float Curve(float point, float velocity, float acceleration, float time) { return point + velocity * time + curveMod * acceleration * time * time; } public class TeleportPreview { public LineRenderer ArcLine; public GameObject PlaySpaceDisplay; public GameObject InvalidPointDisplay; public GameObject TeleportTargetDisplay; } } } <|start_filename|>Assets/NewtonVR/NVRHelpers.cs<|end_filename|> using UnityEngine; using System.Collections; using System.Reflection; namespace NewtonVR { public class NVRHelpers { private static Shader standardShader; private static Shader StandardShader { get { if (standardShader == null) { standardShader = Shader.Find("Standard"); } return standardShader; } } public static void SetTransparent(Material material, Color? newcolor = null) { if (material.shader != StandardShader) Debug.LogWarning("Trying to set transparent mode on non-standard shader. Please use the Standard Shader instead or modify this method."); material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.SetFloat("_Metallic", 0f); material.SetFloat("_Glossiness", 0f); material.renderQueue = 3000; material.mainTexture = null; if (newcolor != null) { material.color = newcolor.Value; } } public static void SetOpaque(Material material) { if (material.shader != StandardShader) Debug.LogWarning("Trying to set opaque mode on non-standard shader. Please use the Standard Shader instead or modify this method."); material.SetOverrideTag("RenderType", ""); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } public static void SetProperty(object obj, string propertyName, object value, bool isPublic) { BindingFlags flags = BindingFlags.Instance; if (isPublic) flags = flags | BindingFlags.Public; else flags = flags | BindingFlags.NonPublic; PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName, flags); propertyInfo.SetValue(obj, value, null); } public static void SetField(object obj, string fieldName, object value, bool isPublic) { BindingFlags flags = BindingFlags.Instance; if (isPublic) flags = flags | BindingFlags.Public; else flags = flags | BindingFlags.NonPublic; FieldInfo fieldInfo = obj.GetType().GetField(fieldName, flags); fieldInfo.SetValue(obj, value); } public static void LineRendererSetColor(LineRenderer lineRenderer, Color startColor, Color endColor) { #if UNITY_5_5_OR_NEWER lineRenderer.startColor = startColor; lineRenderer.endColor = endColor; #else lineRenderer.SetColors(startColor, endColor); #endif } public static void LineRendererSetWidth(LineRenderer lineRenderer, float startWidth, float endWidth) { #if UNITY_5_5_OR_NEWER lineRenderer.startWidth = startWidth; lineRenderer.endWidth = endWidth; #else lineRenderer.SetWidth(startWidth, endWidth); #endif } //Get an average (mean) from more than two quaternions (with two, slerp would be used). //Note: this only works if all the quaternions are relatively close together. //Usage: //-Cumulative is an external Vector4 which holds all the added x y z and w components. //-newRotation is the next rotation to be added to the average pool //-firstRotation is the first quaternion of the array to be averaged //-addAmount holds the total amount of quaternions which are currently added //This function returns the current average quaternion public static Quaternion AverageQuaternion(ref Vector4 cumulative, Quaternion newRotation, Quaternion firstRotation, int addAmount) { float w = 0.0f; float x = 0.0f; float y = 0.0f; float z = 0.0f; //Before we add the new rotation to the average (mean), we have to check whether the quaternion has to be inverted. Because //q and -q are the same rotation, but cannot be averaged, we have to make sure they are all the same. if (!AreQuaternionsClose(newRotation, firstRotation)) { newRotation = InverseSignQuaternion(newRotation); } //Average the values float addDet = 1f / (float)addAmount; cumulative.w += newRotation.w; w = cumulative.w * addDet; cumulative.x += newRotation.x; x = cumulative.x * addDet; cumulative.y += newRotation.y; y = cumulative.y * addDet; cumulative.z += newRotation.z; z = cumulative.z * addDet; //note: if speed is an issue, you can skip the normalization step return NormalizeQuaternion(x, y, z, w); } public static Quaternion NormalizeQuaternion(float x, float y, float z, float w) { float lengthD = 1.0f / (w * w + x * x + y * y + z * z); w *= lengthD; x *= lengthD; y *= lengthD; z *= lengthD; return new Quaternion(x, y, z, w); } //Changes the sign of the quaternion components. This is not the same as the inverse. public static Quaternion InverseSignQuaternion(Quaternion q) { return new Quaternion(-q.x, -q.y, -q.z, -q.w); } //Returns true if the two input quaternions are close to each other. This can //be used to check whether or not one of two quaternions which are supposed to //be very similar but has its component signs reversed (q has the same rotation as //-q) public static bool AreQuaternionsClose(Quaternion q1, Quaternion q2) { float dot = Quaternion.Dot(q1, q2); if (dot < 0.0f) { return false; } else { return true; } } } } <|start_filename|>Assets/NewtonVR/NVRTeleportController.cs<|end_filename|> using UnityEngine; namespace NewtonVR { public class NVRTeleportController : MonoBehaviour { public Transform BeamStart; private NVRTeleporter teleporter; //NVRHand sometimes gets destroyed. Pull it each time. private NVRHand nvrHand { get { NVRHand hand = GetComponent<NVRHand>(); if (hand == null) { Debug.LogError("NVRHand is missing!"); } return hand; } } private int controllerIndex = 0; private bool held = false; private Vector3? validTeleportPosition; private void Start() { teleporter = NVRPlayer.Instance.GetComponentInChildren<NVRTeleporter>(); if (teleporter == null) { Debug.LogError("NVRTeleporter is Missing"); } if (BeamStart == null) BeamStart = this.transform; controllerIndex = System.Convert.ToInt32(nvrHand.IsLeft); } private void FixedUpdate() { if (teleporter != null) { if (nvrHand.Inputs[teleporter.TeleportButton].IsPressed) { //Show Arc Teleport Preview validTeleportPosition = teleporter.UpdateArcTeleport(BeamStart, controllerIndex); held = true; } else if (held == true) { //Was held on the last frame. Kill teleport preview teleporter.HideArcTeleport(controllerIndex); held = false; if (validTeleportPosition != null) { teleporter.TeleportPlayer((Vector3)validTeleportPosition); } } } } private void OnDestroy() { if (teleporter != null) { teleporter.HideArcTeleport(controllerIndex); } } } } <|start_filename|>Assets/NewtonVR/Editor/NVRTeleporterEditor.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace NewtonVR { [CustomEditor(typeof(NVRTeleporter))] public class NVRTeleporterEditor : Editor { //Options private SerializedProperty limitToHorizontalProp; private SerializedProperty limitSensitivityProp; private SerializedProperty useTunnellingProp; private bool limitToHorizontal; private bool useTunnelling; //Masks private SerializedProperty teleportSurfaceMask; private SerializedProperty teleportBlockMask; //Tunnelling private SerializedProperty tunnelOverTimeProp; private SerializedProperty vignettePowerProp; private SerializedProperty vignetteEaseInTimeProp; private SerializedProperty vignetteEaseOutTimeProp; //Arc Properties private SerializedProperty arcStrengthProp; private SerializedProperty arcLengthProp; private SerializedProperty sampleFrequencyProp; //Line Renderers private bool _showRenderers = false; private SerializedProperty arcRendererTemplateProp; private SerializedProperty playSpaceRendererTemplateProp; private SerializedProperty invalidRendererTemplateProp; private SerializedProperty teleportTargetTemplateProp; //Hands private enum Hand { Left, Right }; private GameObject[] _hands; //Styles private GUIStyle _boldFoldout; private float arcLength; public void OnEnable() { NVRTeleporter teleporter = (NVRTeleporter)target; limitToHorizontalProp = serializedObject.FindProperty("LimitToHorizontal"); limitSensitivityProp = serializedObject.FindProperty("LimitSensitivity"); limitToHorizontal = limitToHorizontalProp.boolValue; useTunnellingProp = serializedObject.FindProperty("TunnelTeleport"); useTunnelling = useTunnellingProp.boolValue; tunnelOverTimeProp = serializedObject.FindProperty("TunnelOverTime"); vignettePowerProp = serializedObject.FindProperty("VignettePower"); vignetteEaseInTimeProp = serializedObject.FindProperty("VignetteEaseInTime"); vignetteEaseOutTimeProp = serializedObject.FindProperty("VignetteEaseOutTime"); teleportSurfaceMask = serializedObject.FindProperty("TeleportSurfaceMask"); teleportBlockMask = serializedObject.FindProperty("TeleportBlockMask"); arcRendererTemplateProp = serializedObject.FindProperty("ArcRendererDisplay"); playSpaceRendererTemplateProp = serializedObject.FindProperty("PlaySpaceDisplay"); invalidRendererTemplateProp = serializedObject.FindProperty("InvalidPointDisplay"); teleportTargetTemplateProp = serializedObject.FindProperty("TargetDisplay"); arcStrengthProp = serializedObject.FindProperty("ArcStrength"); arcLengthProp = serializedObject.FindProperty("ArcMaxLength"); sampleFrequencyProp = serializedObject.FindProperty("SampleFrequency"); NVRPlayer player = teleporter.gameObject.GetComponentInParent<NVRPlayer>(); if (player != null) { _hands = new GameObject[2]; _hands[0] = player.LeftHand.gameObject; _hands[1] = player.RightHand.gameObject; } } public override void OnInspectorGUI() { serializedObject.Update(); NVRTeleporter teleporter = (NVRTeleporter)target; GUILayout.Label("Options", EditorStyles.boldLabel); HandCheck(Hand.Left); HandCheck(Hand.Right); GUILayout.Space(6); GUIContent useTunnelTooltip = new GUIContent(" Use tunnel teleporting", "Vignette the user's view and move over a short time while teleporting"); useTunnelling = GUILayout.Toggle(useTunnelling, useTunnelTooltip); if (useTunnelling != useTunnellingProp.boolValue) { useTunnellingProp.boolValue = useTunnelling; } if (useTunnelling) { EditorGUI.indentLevel = 2; GUIContent tunnelOverTimeTooltip = new GUIContent("Tunnelling time", "How long should it take to teleport from one place to another"); EditorGUILayout.PropertyField(tunnelOverTimeProp, tunnelOverTimeTooltip); GUIContent vignettePowerTooltip = new GUIContent("Vignette power", "How much of a vignette should we display while tunnelling"); EditorGUILayout.PropertyField(vignettePowerProp, vignettePowerTooltip); GUIContent vignetteEaseInTimeTooltip = new GUIContent("Vignette ease-in time", "How long should it take to fade into the vignette before tunnelling"); EditorGUILayout.PropertyField(vignetteEaseInTimeProp, vignetteEaseInTimeTooltip); GUIContent vignetteEaseOutTimeTooltip = new GUIContent("Vignette ease-out time", "How long should it take to fade out of the vignette after tunnelling"); EditorGUILayout.PropertyField(vignetteEaseOutTimeProp, vignetteEaseOutTimeTooltip); EditorGUI.indentLevel = 0; } GUILayout.Space(6); GUIContent limitToHorizTooltip = new GUIContent(" Limit surfaces to horizontal", "This property will limit your teleports to only flat surfaces"); limitToHorizontal = GUILayout.Toggle(limitToHorizontal, limitToHorizTooltip); if (limitToHorizontal != limitToHorizontalProp.boolValue) { limitToHorizontalProp.boolValue = limitToHorizontal; } if (limitToHorizontal) { EditorGUI.indentLevel = 2; GUIContent limitSensitivityTooltip = new GUIContent("Tolerance", "How much of an angle we're allowed to teleport onto in degree difference from up.\nEx. A floor would be 0. A perpendicular wall would be 90."); EditorGUILayout.PropertyField(limitSensitivityProp, limitSensitivityTooltip); EditorGUI.indentLevel = 0; } GUILayout.Space(10); //Arc Stuff GUILayout.Label("Arc Editor", EditorStyles.boldLabel); GUIContent arcStrengthTooltip = new GUIContent("Arc strength", "How much the line extends forward before arching down"); EditorGUILayout.PropertyField(arcStrengthProp, arcStrengthTooltip); GUIContent arcLengthTooltip = new GUIContent("Maximum arc length", "The maximum length the theleporter arc will go before cutting out"); EditorGUILayout.PropertyField(arcLengthProp, arcLengthTooltip); GUIContent sampleFrequencyTooltip = new GUIContent("Sample frequency", "How many points the teleport arc has (smaller is more smooth)"); EditorGUILayout.PropertyField(sampleFrequencyProp, sampleFrequencyTooltip); GUILayout.Space(10); //Layer Masks GUILayout.Label("Layer Masks", EditorStyles.boldLabel); GUIContent surfacaeMaskTooltip = new GUIContent("Teleport surface mask", "Layers that we can teleport onto"); EditorGUILayout.PropertyField(teleportSurfaceMask, surfacaeMaskTooltip); GUIContent blockMaskTooltip = new GUIContent("Teleport block mask", "Layers that should block teleportation"); EditorGUILayout.PropertyField(teleportBlockMask, blockMaskTooltip); GUILayout.Space(10); //Line Renderers GUILayout.Label("Overrides", EditorStyles.boldLabel); GUILayout.Label("The default displays are all children of the NVRTeleporter GameObject and can be edited. They can also be replaced and overidden below." + "The arc must be a line renderer, but the other displays can be any GameObject." , EditorStyles.wordWrappedMiniLabel); GUILayout.Space(4); _showRenderers = EditorGUILayout.Foldout(_showRenderers, "Displays"); if (_showRenderers) { GUIContent arcRendererTooltip = new GUIContent("Arc renderer display", "Line Renderer that represents the Teleport Arc"); EditorGUILayout.PropertyField(arcRendererTemplateProp, arcRendererTooltip); GUIContent playSpaceRendererTooltip = new GUIContent("Play space display", "GameObject that represents the Play Space for a valid teleport. Scales with play space area, default should have a scale of 1,1,1."); EditorGUILayout.PropertyField(playSpaceRendererTemplateProp, playSpaceRendererTooltip); GUIContent invalidRendererTooltip = new GUIContent("Invalid point display", "GameObject that represents an invalid teleport. Rotates with invalid surface, default should face forward along z"); EditorGUILayout.PropertyField(invalidRendererTemplateProp, invalidRendererTooltip); GUIContent teleportTargetTooltip = new GUIContent("Teleport target display", "GameObject that represents player's position within the playspace of a valid teleport. Appears at the end of the teleport arc."); EditorGUILayout.PropertyField(teleportTargetTemplateProp, teleportTargetTooltip); } serializedObject.ApplyModifiedProperties(); } private void HandCheck(Hand hand) { //If right hand was found if (_hands != null && _hands[(int)hand] != null) { //If the right hand doesn't already have the teleport controller NVRTeleportController comp = _hands[(int)hand].GetComponent<NVRTeleportController>(); if (comp == null) { if (GUILayout.Button("Attach Teleporter to " + hand.ToString() + " Hand")) { _hands[(int)hand].AddComponent<NVRTeleportController>(); } } else { if (GUILayout.Button("Remove Teleporter from " + hand.ToString() + " Hand")) { DestroyImmediate(comp); } } } } } } <|start_filename|>Assets/NewtonVR/Resources/Shaders/Vignette.shader<|end_filename|> Shader "Vignette" { Properties { _MainTex("Base (RGB)", 2D) = "white" {} _VignettePower("VignettePower", Range(0.0,6.0)) = 0 } SubShader { Pass { CGPROGRAM #pragma vertex vert_img #pragma fragment frag #pragma fragmentoption ARB_precision_hint_fastest #include "UnityCG.cginc" uniform sampler2D _MainTex; half4 _MainTex_ST; uniform float _VignettePower; struct v2f { float2 texcoord : TEXCOORD0; }; float4 frag(v2f_img i) : COLOR { float2 uv = UnityStereoScreenSpaceUVAdjust(i.uv, _MainTex_ST); float4 renderTex = tex2D(_MainTex, uv); float2 dist = (i.uv - 0.5f) * 1.25f; dist.x = 1 - dot(dist, dist) * _VignettePower; renderTex *= dist.x; return renderTex; } ENDCG } } } <|start_filename|>Assets/NewtonVR/WindowsMR/NVRWindowsMRIntegration.cs<|end_filename|> using UnityEngine; using UnityEngine.VR; #if UNITY_WSA && NVR_WindowsMR using HoloToolkit.Unity; #if UNITY_2017_2_OR_NEWER using UnityEngine.XR.WSA; #else using UnityEngine.VR.WSA; #endif #endif namespace NewtonVR { public class NVRWindowsMRIntegration : NVRIntegration { [Tooltip("The near clipping plane distance for an opaque display.")] public float NearClipPlane_OpaqueDisplay = 0.1f; [Tooltip("Values for Camera.clearFlags, determining what to clear when rendering a Camera for an opaque display.")] public CameraClearFlags CameraClearFlags_OpaqueDisplay = CameraClearFlags.Skybox; [Tooltip("Background color for a transparent display.")] public Color BackgroundColor_OpaqueDisplay = Color.black; [Tooltip("Set the desired quality for your application for opaque display.")] public int OpaqueQualityLevel; [Tooltip("The near clipping plane distance for a transparent display.")] public float NearClipPlane_TransparentDisplay = 0.85f; [Tooltip("Values for Camera.clearFlags, determining what to clear when rendering a Camera for an opaque display.")] public CameraClearFlags CameraClearFlags_TransparentDisplay = CameraClearFlags.SolidColor; [Tooltip("Background color for a transparent display.")] public Color BackgroundColor_TransparentDisplay = Color.clear; [Tooltip("Set the desired quality for your application for HoloLens.")] public int HoloLensQualityLevel; public enum DisplayType { Opaque = 0, Transparent }; public override void Initialize(NVRPlayer player) { Player = player; Player.gameObject.SetActive(false); if (!Application.isEditor) { #if UNITY_WSA #if UNITY_2017_2_OR_NEWER if (!UnityEngine.XR.WSA.HolographicSettings.IsDisplayOpaque) #endif { CurrentDisplayType = DisplayType.Transparent; ApplySettingsForTransparentDisplay(Player.Head.GetComponent<Camera>()); if (OnDisplayDetected != null) { OnDisplayDetected(DisplayType.Transparent); } return; } #endif } CurrentDisplayType = DisplayType.Opaque; ApplySettingsForOpaqueDisplay(Player.Head.GetComponent<Camera>()); if (OnDisplayDetected != null) { OnDisplayDetected(DisplayType.Opaque); } Player.gameObject.SetActive(true); } private Vector3 PlayspaceBounds = Vector3.zero; public override Vector3 GetPlayspaceBounds() { #if UNITY_2017_2_OR_NEWER if (UnityEngine.Experimental.XR.Boundary.configured) { UnityEngine.Experimental.XR.Boundary.TryGetDimensions(out PlayspaceBounds); } #else if (UnityEngine.Experimental.VR.Boundary.configured) { UnityEngine.Experimental.VR.Boundary.TryGetDimensions(out PlayspaceBounds); } #endif return PlayspaceBounds; } public override bool IsHmdPresent() { #if UNITY_2017_2_OR_NEWER if (Application.isPlaying == false) //try and enable vr if we're in the editor so we can get hmd present { if (UnityEngine.XR.XRSettings.enabled == false) { UnityEngine.XR.XRSettings.enabled = true; } } return UnityEngine.XR.XRDevice.isPresent; #else if (Application.isPlaying == false) //try and enable vr if we're in the editor so we can get hmd present { if (UnityEngine.VR.VRSettings.enabled == false) { UnityEngine.VR.VRSettings.enabled = true; } } return UnityEngine.VR.VRDevice.isPresent; #endif } public DisplayType CurrentDisplayType { get; private set; } public delegate void DisplayEventHandler(DisplayType displayType); /// <summary> /// Event is fired when a display is detected. /// DisplayType enum value tells you if display is Opaque Vs Transparent. /// </summary> public event DisplayEventHandler OnDisplayDetected; public void ApplySettingsForOpaqueDisplay(Camera cam) { Debug.Log("Display is Opaque"); cam.clearFlags = CameraClearFlags_OpaqueDisplay; cam.nearClipPlane = NearClipPlane_OpaqueDisplay; cam.backgroundColor = BackgroundColor_OpaqueDisplay; SetQuality(OpaqueQualityLevel); } public void ApplySettingsForTransparentDisplay(Camera cam) { Debug.Log("Display is Transparent"); cam.clearFlags = CameraClearFlags_TransparentDisplay; cam.backgroundColor = BackgroundColor_TransparentDisplay; cam.nearClipPlane = NearClipPlane_TransparentDisplay; SetQuality(HoloLensQualityLevel); } private static void SetQuality(int level) { QualitySettings.SetQualityLevel(level, false); } } } <|start_filename|>Assets/NewtonVR/NVRSDKIntegrations.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NewtonVR { public enum NVRSDKIntegrations { None, FallbackNonVR, SteamVR, Oculus, WindowsMR, } } <|start_filename|>Assets/NewtonVR/CollisionSoundFramework/NVRCollisionSoundProviderFMOD.cs<|end_filename|> using UnityEngine; using System.Collections; using System.Collections.Generic; #if NVR_FMOD using FMOD.Studio; using FMODUnity; namespace NewtonVR { public class NVRCollisionSoundProviderFMOD : NVRCollisionSoundProvider { private static Dictionary<NVRCollisionSoundMaterials, string> eventStrings; public static Dictionary<NVRCollisionSoundMaterials, string> EventStrings { get { if (eventStrings == null) { eventStrings = new Dictionary<NVRCollisionSoundMaterials, string>(new EnumEqualityComparer<NVRCollisionSoundMaterials>()); foreach (NVRCollisionSoundMaterials mat in NVRCollisionSoundMaterialsList.List) { if (mat == NVRCollisionSoundMaterials.EndNewtonVRMaterials) { continue; } eventStrings.Add(mat, string.Format("event:/Collisions/{0}", mat.ToString())); } } return eventStrings; } } private static Dictionary<NVRCollisionSoundMaterials, System.Guid> eventGuids; public static Dictionary<NVRCollisionSoundMaterials, System.Guid> EventGuids { get { if (eventGuids == null) { eventGuids = new Dictionary<NVRCollisionSoundMaterials, System.Guid>(new EnumEqualityComparer<NVRCollisionSoundMaterials>()); foreach (var mat in EventStrings) { if (mat.Key == NVRCollisionSoundMaterials.EndNewtonVRMaterials) { continue; } eventGuids.Add(mat.Key, FMODUnity.RuntimeManager.PathToGUID(mat.Value)); } } return eventGuids; } } public override void Awake() { } public override void Play(NVRCollisionSoundMaterials material, Vector3 position, float impactVolume) { if (material == NVRCollisionSoundMaterials.none) return; System.Guid playGuid = EventGuids[material]; EventInstance collidingInstance = RuntimeManager.CreateInstance(playGuid); collidingInstance.set3DAttributes(RuntimeUtils.To3DAttributes(position)); collidingInstance.setVolume(impactVolume); collidingInstance.start(); collidingInstance.release(); } } } #else namespace NewtonVR { public class NVRCollisionSoundProviderFMOD : NVRCollisionSoundProvider { public override void Awake() { } public override void Play(NVRCollisionSoundMaterials material, Vector3 position, float impactVolume) { return; } } } #endif <|start_filename|>Assets/NewtonVR/CollisionSoundFramework/NVRCollisionSoundController.cs<|end_filename|> using UnityEngine; using System.Collections; namespace NewtonVR { public class NVRCollisionSoundController : MonoBehaviour { public static NVRCollisionSoundController Instance; [Tooltip("The max number of sounds that can possibly be playing at once.")] public int SoundPoolSize = 100; [Tooltip("Turns on or off randomizing the pitch of the collision sounds")] public bool PitchModulationEnabled = true; [Range(0f, 3f)] public float PitchModulationRange = 0.5f; [Tooltip("Don't play collision sounds that will produce an impact with a volume lower than this number")] public float MinCollisionVolume = 0.1f; public float MaxCollisionVelocity = 5; [HideInInspector] public NVRCollisionSoundProviders SoundEngine = NVRCollisionSoundProviders.Unity; private static NVRCollisionSoundProvider Provider; private void Awake() { Instance = this; #if NVR_FMOD Provider = this.gameObject.AddComponent<NVRCollisionSoundProviderFMOD>(); #else Provider = this.gameObject.AddComponent<NVRCollisionSoundProviderUnity>(); #endif } public static void Play(NVRCollisionSoundMaterials material, Vector3 position, float impactVolume) { if (Provider != null) Provider.Play(material, position, impactVolume); } } public enum NVRCollisionSoundProviders { None, Unity, FMOD, } } <|start_filename|>Assets/NewtonVR/SteamVR/NVRSteamVRInputDevice.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; #if NVR_SteamVR using Valve.VR; namespace NewtonVR { public class NVRSteamVRInputDevice : NVRInputDevice { private SteamVR_Controller.Device Controller; private int DeviceIndex = -1; private bool RenderModelInitialized = false; private Dictionary<NVRButtons, EVRButtonId> ButtonMapping = new Dictionary<NVRButtons, EVRButtonId>(new NVRButtonsComparer()); protected bool isKnuckles = false; protected float indexCurl; protected float middleCurl; protected float ringCurl; protected float pinkyCurl; protected bool thumbTouch; public override void Initialize(NVRHand hand) { SetupButtonMapping(); base.Initialize(hand); SteamVR_Events.RenderModelLoaded.Listen(RenderModelLoaded); } private void OnDestroy() { SteamVR_Events.RenderModelLoaded.Remove(RenderModelLoaded); } protected virtual void SetupButtonMapping() { ButtonMapping.Add(NVRButtons.A, EVRButtonId.k_EButton_A); ButtonMapping.Add(NVRButtons.ApplicationMenu, EVRButtonId.k_EButton_ApplicationMenu); ButtonMapping.Add(NVRButtons.Axis0, EVRButtonId.k_EButton_Axis0); ButtonMapping.Add(NVRButtons.Axis1, EVRButtonId.k_EButton_Axis1); ButtonMapping.Add(NVRButtons.Axis2, EVRButtonId.k_EButton_Axis2); ButtonMapping.Add(NVRButtons.Axis3, EVRButtonId.k_EButton_Axis3); ButtonMapping.Add(NVRButtons.Axis4, EVRButtonId.k_EButton_Axis4); ButtonMapping.Add(NVRButtons.Back, EVRButtonId.k_EButton_Dashboard_Back); ButtonMapping.Add(NVRButtons.DPad_Down, EVRButtonId.k_EButton_DPad_Down); ButtonMapping.Add(NVRButtons.DPad_Left, EVRButtonId.k_EButton_DPad_Left); ButtonMapping.Add(NVRButtons.DPad_Right, EVRButtonId.k_EButton_DPad_Right); ButtonMapping.Add(NVRButtons.DPad_Up, EVRButtonId.k_EButton_DPad_Up); ButtonMapping.Add(NVRButtons.Grip, EVRButtonId.k_EButton_Grip); ButtonMapping.Add(NVRButtons.System, EVRButtonId.k_EButton_System); ButtonMapping.Add(NVRButtons.Touchpad, EVRButtonId.k_EButton_SteamVR_Touchpad); ButtonMapping.Add(NVRButtons.Trigger, EVRButtonId.k_EButton_SteamVR_Trigger); ButtonMapping.Add(NVRButtons.B, EVRButtonId.k_EButton_A); ButtonMapping.Add(NVRButtons.X, EVRButtonId.k_EButton_A); ButtonMapping.Add(NVRButtons.Y, EVRButtonId.k_EButton_A); } private EVRButtonId GetButton(NVRButtons button) { if (ButtonMapping.ContainsKey(button) == false) { return EVRButtonId.k_EButton_System; //Debug.LogError("No SteamVR button configured for: " + button.ToString()); } return ButtonMapping[button]; } public override float GetAxis1D(NVRButtons button) { if (Controller != null) return Controller.GetAxis(GetButton(button)).x; return 0; } public override Vector2 GetAxis2D(NVRButtons button) { if (Controller != null) return Controller.GetAxis(GetButton(button)); return Vector2.zero; } public override bool GetPressDown(NVRButtons button) { if (Controller != null) { if (isKnuckles == true) { if (button == NVRButtons.Grip) { UpdateKnucklesFingerCurl(); return (wasGripped == false) && (isGripped == true); } } return Controller.GetPressDown(GetButton(button)); } return false; } public override bool GetPressUp(NVRButtons button) { if (Controller != null) { if (isKnuckles == true) { if (button == NVRButtons.Grip) { UpdateKnucklesFingerCurl(); return (wasGripped == true) && (isGripped == false); } } return Controller.GetPressUp(GetButton(button)); } return false; } public override bool GetPress(NVRButtons button) { if (Controller != null) { if (isKnuckles == true) { if (button == NVRButtons.Grip) { UpdateKnucklesFingerCurl(); return isGripped; } } return Controller.GetPress(GetButton(button)); } return false; } public override bool GetTouchDown(NVRButtons button) { if (Controller != null) return Controller.GetTouchDown(GetButton(button)); return false; } public override bool GetTouchUp(NVRButtons button) { if (Controller != null) return Controller.GetTouchUp(GetButton(button)); return false; } public override bool GetTouch(NVRButtons button) { if (Controller != null) return Controller.GetTouch(GetButton(button)); return false; } public override bool GetNearTouchDown(NVRButtons button) { return false; } public override bool GetNearTouchUp(NVRButtons button) { return false; } public override bool GetNearTouch(NVRButtons button) { return false; } public override void TriggerHapticPulse(ushort durationMicroSec = 500, NVRButtons button = NVRButtons.Touchpad) { if (Controller != null) { if (durationMicroSec < 3000) { Controller.TriggerHapticPulse(durationMicroSec, ButtonMapping[button]); } } } public override bool IsCurrentlyTracked { get { return DeviceIndex != -1; } } protected bool wasGripped; protected bool isGripped; protected float lastChecked; protected void UpdateKnucklesFingerCurl() { if (Time.unscaledTime != lastChecked) { wasGripped = isGripped; indexCurl = Controller.GetAxis(EVRButtonId.k_EButton_Axis3).x; middleCurl = Controller.GetAxis(EVRButtonId.k_EButton_Axis3).y; ringCurl = Controller.GetAxis(EVRButtonId.k_EButton_Axis4).x; pinkyCurl = Controller.GetAxis(EVRButtonId.k_EButton_Axis4).y; thumbTouch = Controller.GetTouch(EVRButtonId.k_EButton_SteamVR_Touchpad); isGripped = IsKnucklesGripped(); } lastChecked = Time.unscaledTime; } protected float curlAmountNeeded = 0.7f; protected bool IsKnucklesGripped() { return (indexCurl > curlAmountNeeded) || (middleCurl > curlAmountNeeded) || (ringCurl > curlAmountNeeded) || (pinkyCurl > curlAmountNeeded); } public override GameObject SetupDefaultRenderModel() { GameObject renderModel = new GameObject("Render Model for " + Hand.gameObject.name); renderModel.transform.parent = Hand.transform; renderModel.transform.localPosition = Vector3.zero; renderModel.transform.localRotation = Quaternion.identity; renderModel.transform.localScale = Vector3.one; renderModel.AddComponent<SteamVR_RenderModel>(); renderModel.GetComponent<SteamVR_RenderModel>().shader = Shader.Find("Standard"); return renderModel; } public override bool ReadyToInitialize() { return (RenderModelInitialized || Hand.HasCustomModel) && DeviceIndex != -1; } private void RenderModelLoaded(SteamVR_RenderModel renderModel, bool success) { if ((int)renderModel.index == DeviceIndex) RenderModelInitialized = success; if (Hand != null && Hand.CurrentHandState != HandState.Uninitialized) { Hand.Initialize(); } } private void SetDeviceIndex(int index) { DeviceIndex = index; Controller = SteamVR_Controller.Input(index); } public override string GetDeviceName() { if (Hand.HasCustomModel == true) { return "Custom"; } else { return this.GetComponentInChildren<SteamVR_RenderModel>(true).renderModelName; } } public override Collider[] SetupDefaultPhysicalColliders(Transform ModelParent) { Collider[] colliders = null; string controllerModel = GetDeviceName(); if (controllerModel.Contains("Windows")) { colliders = AddAcerPhysicalColliders(ModelParent, controllerModel); } else { switch (controllerModel) { case "vr_controller_05_wireless_b": Transform dk1Trackhat = ModelParent.transform.Find("trackhat"); Collider dk1TrackhatCollider = dk1Trackhat.gameObject.GetComponent<BoxCollider>(); if (dk1TrackhatCollider == null) dk1TrackhatCollider = dk1Trackhat.gameObject.AddComponent<BoxCollider>(); Transform dk1Body = ModelParent.transform.Find("body"); Collider dk1BodyCollider = dk1Body.gameObject.GetComponent<BoxCollider>(); if (dk1BodyCollider == null) dk1BodyCollider = dk1Body.gameObject.AddComponent<BoxCollider>(); colliders = new Collider[] { dk1TrackhatCollider, dk1BodyCollider }; break; case "vr_controller_vive_1_5": Transform dk2TrackhatColliders = ModelParent.transform.Find("ViveColliders"); if (dk2TrackhatColliders == null) { dk2TrackhatColliders = GameObject.Instantiate(Resources.Load<GameObject>("ViveControllers/ViveColliders")).transform; dk2TrackhatColliders.parent = ModelParent.transform; dk2TrackhatColliders.localPosition = Vector3.zero; dk2TrackhatColliders.localRotation = Quaternion.identity; dk2TrackhatColliders.localScale = Vector3.one; } colliders = dk2TrackhatColliders.GetComponentsInChildren<Collider>(); break; case "{knuckles}valve_controller_knu_ev1_3_left": case "{knuckles}valve_controller_knu_ev1_3_right": string name = "KnucklesPhysicalHand"; if (Hand.IsLeft == true) { name += "Left"; } else { name += "Right"; } Transform knucklesColliders = ModelParent.transform.Find(name); if (knucklesColliders == null) { knucklesColliders = GameObject.Instantiate(Resources.Load<GameObject>("ViveControllers/" + name)).transform; knucklesColliders.parent = ModelParent.transform; knucklesColliders.localPosition = Vector3.zero; knucklesColliders.localRotation = Quaternion.identity; knucklesColliders.localScale = Vector3.one; } colliders = knucklesColliders.GetComponentsInChildren<Collider>(); break; case "external_controllers": case "oculus_cv1_controller_left": case "oculus_cv1_controller_right": colliders = AddOculusTouchPhysicalColliders(ModelParent, controllerModel); break; default: //kindy hacky but may future proof a bit for released builds Debug.LogError("[NewtonVR] NVRSteamVRInputDevice Error. Unsupported device type while trying to setup physical colliders: " + controllerModel); SphereCollider defaultCollider = ModelParent.gameObject.AddComponent<SphereCollider>(); defaultCollider.isTrigger = false; defaultCollider.radius = 0.15f; colliders = new Collider[] { defaultCollider }; break; } } return colliders; } public override Collider[] SetupDefaultColliders() { Collider[] colliders = null; string controllerModel = GetDeviceName(); SteamVR_RenderModel renderModel = this.GetComponentInChildren<SteamVR_RenderModel>(); if (controllerModel.Contains("Windows")) { colliders = AddOculusTouchTriggerCollider(renderModel.gameObject, controllerModel); } else { switch (controllerModel) { case "vr_controller_05_wireless_b": Transform dk1Trackhat = renderModel.transform.Find("trackhat"); if (dk1Trackhat == null) { // Dk1 controller model has trackhat } else { dk1Trackhat.gameObject.SetActive(true); } SphereCollider dk1TrackhatCollider = dk1Trackhat.gameObject.GetComponent<SphereCollider>(); if (dk1TrackhatCollider == null) { dk1TrackhatCollider = dk1Trackhat.gameObject.AddComponent<SphereCollider>(); dk1TrackhatCollider.isTrigger = true; } colliders = new Collider[] { dk1TrackhatCollider }; break; case "vr_controller_vive_1_5": Transform dk2Trackhat = renderModel.transform.Find("trackhat"); if (dk2Trackhat == null) { dk2Trackhat = new GameObject("trackhat").transform; dk2Trackhat.gameObject.layer = this.gameObject.layer; dk2Trackhat.parent = renderModel.transform; dk2Trackhat.localPosition = new Vector3(0, -0.033f, 0.014f); dk2Trackhat.localScale = Vector3.one * 0.1f; dk2Trackhat.localEulerAngles = new Vector3(325, 0, 0); dk2Trackhat.gameObject.SetActive(true); } else { dk2Trackhat.gameObject.SetActive(true); } Collider dk2TrackhatCollider = dk2Trackhat.gameObject.GetComponent<SphereCollider>(); if (dk2TrackhatCollider == null) { dk2TrackhatCollider = dk2Trackhat.gameObject.AddComponent<SphereCollider>(); dk2TrackhatCollider.isTrigger = true; } colliders = new Collider[] { dk2TrackhatCollider }; break; case "{knuckles}valve_controller_knu_ev1_3_left": case "{knuckles}valve_controller_knu_ev1_3_right": isKnuckles = true; Transform knucklesTrackpad = renderModel.transform.Find("trackpad").GetChild(0); SphereCollider knucklesTrackpadCollider = knucklesTrackpad.gameObject.GetComponent<SphereCollider>(); if (knucklesTrackpadCollider == null) { knucklesTrackpadCollider = knucklesTrackpad.gameObject.AddComponent<SphereCollider>(); knucklesTrackpadCollider.isTrigger = true; knucklesTrackpadCollider.radius = 0.04f; } colliders = new Collider[] { knucklesTrackpadCollider }; break; case "external_controllers": colliders = AddOculusTouchTriggerCollider(renderModel.gameObject, controllerModel); break; case "oculus_cv1_controller_left": colliders = AddOculusTouchTriggerCollider(renderModel.gameObject, controllerModel); break; case "oculus_cv1_controller_right": colliders = AddOculusTouchTriggerCollider(renderModel.gameObject, controllerModel); break; default: SphereCollider defaultCollider = renderModel.gameObject.AddComponent<SphereCollider>(); defaultCollider.isTrigger = true; defaultCollider.radius = 0.15f; colliders = new Collider[] { defaultCollider }; // kindy hacky but may future proof a bit Debug.LogError("Error. Unsupported device type: " + controllerModel); break; } } return colliders; } protected Collider[] AddAcerPhysicalColliders(Transform ModelParent, string controllerModel) { string name = "AcerController"; if (Hand.IsLeft == true) { name += "Left"; } else { name += "Right"; } name += "_Colliders"; Transform acerColliders = ModelParent.Find(name); if (acerColliders == null) { acerColliders = GameObject.Instantiate(Resources.Load<GameObject>("AcerControllers/" + name)).transform; acerColliders.parent = ModelParent; acerColliders.localPosition = Vector3.zero; acerColliders.localRotation = Quaternion.identity; acerColliders.localScale = Vector3.one; } return acerColliders.GetComponentsInChildren<Collider>(); } protected static Vector3 SteamVROculusControllerPositionAddition = new Vector3(0.001f, -0.0086f, -0.0197f); protected Collider[] AddOculusTouchPhysicalColliders(Transform ModelParent, string controllerModel) { Transform tip = ModelParent.GetChild(0); if (tip != null) { tip = tip.Find("tip"); if (tip != null) { tip = tip.GetChild(0); } } if (tip == null) { tip = ModelParent; } string name = "oculusTouch"; if (Hand.IsLeft == true) { name += "Left"; } else { name += "Right"; } name += "Colliders"; Transform touchColliders = ModelParent.Find(name); if (touchColliders == null) { touchColliders = GameObject.Instantiate(Resources.Load<GameObject>("TouchControllers/" + name)).transform; touchColliders.parent = tip; touchColliders.localPosition = SteamVROculusControllerPositionAddition; touchColliders.localRotation = Quaternion.identity; touchColliders.localScale = Vector3.one; } return touchColliders.GetComponentsInChildren<Collider>(); } protected Collider[] AddOculusTouchTriggerCollider(GameObject renderModel, string name) { Transform grip = renderModel.transform.Find("grip"); SphereCollider oculusCollider; if (grip != null) { Transform child = grip.GetChild(0); if (child != null) { oculusCollider = child.gameObject.AddComponent<SphereCollider>(); } else { oculusCollider = grip.gameObject.AddComponent<SphereCollider>(); } oculusCollider.isTrigger = true; oculusCollider.radius = 0.10f; } else { oculusCollider = renderModel.AddComponent<SphereCollider>(); oculusCollider.isTrigger = true; oculusCollider.radius = 0.10f; } return new Collider[] { oculusCollider }; } } } #else namespace NewtonVR { public class NVRSteamVRInputDevice : NVRInputDevice { public override bool IsCurrentlyTracked { get { PrintNotEnabledError(); return false; } } public override float GetAxis1D(NVRButtons button) { PrintNotEnabledError(); return 0; } public override Vector2 GetAxis2D(NVRButtons button) { PrintNotEnabledError(); return Vector2.zero; } public override string GetDeviceName() { PrintNotEnabledError(); return ""; } public override bool GetNearTouch(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetNearTouchDown(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetNearTouchUp(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetPress(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetPressDown(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetPressUp(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetTouch(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetTouchDown(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool GetTouchUp(NVRButtons button) { PrintNotEnabledError(); return false; } public override bool ReadyToInitialize() { PrintNotEnabledError(); return false; } public override Collider[] SetupDefaultColliders() { PrintNotEnabledError(); return null; } public override Collider[] SetupDefaultPhysicalColliders(Transform ModelParent) { PrintNotEnabledError(); return null; } public override GameObject SetupDefaultRenderModel() { PrintNotEnabledError(); return null; } public override void TriggerHapticPulse(ushort durationMicroSec = 500, NVRButtons button = NVRButtons.Touchpad) { PrintNotEnabledError(); } private void PrintNotEnabledError() { Debug.LogError("Enable SteamVR in NVRPlayer to allow steamvr calls."); } } } #endif
maoa3/NewtonVR
<|start_filename|>prometheus.go<|end_filename|> package main import ( "strconv" "sync" "github.com/biter777/countries" cloudflare "github.com/cloudflare/cloudflare-go" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) var ( // Requests zoneRequestTotal = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_total", Help: "Number of requests for zone", }, []string{"zone"}, ) zoneRequestCached = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_cached", Help: "Number of cached requests for zone", }, []string{"zone"}, ) zoneRequestSSLEncrypted = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_ssl_encrypted", Help: "Number of encrypted requests for zone", }, []string{"zone"}, ) zoneRequestContentType = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_content_type", Help: "Number of request for zone per content type", }, []string{"zone", "content_type"}, ) zoneRequestCountry = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_country", Help: "Number of request for zone per country", }, []string{"zone", "country", "region"}, ) zoneRequestHTTPStatus = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_status", Help: "Number of request for zone per HTTP status", }, []string{"zone", "status"}, ) zoneRequestOriginStatusCountryHost = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_origin_status_country_host", Help: "Count of not cached requests for zone per origin HTTP status per country per host", }, []string{"zone", "status", "country", "host"}, ) zoneRequestStatusCountryHost = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_requests_status_country_host", Help: "Count of requests for zone per edge HTTP status per country per host", }, []string{"zone", "status", "country", "host"}, ) zoneBandwidthTotal = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_bandwidth_total", Help: "Total bandwidth per zone in bytes", }, []string{"zone"}, ) zoneBandwidthCached = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_bandwidth_cached", Help: "Cached bandwidth per zone in bytes", }, []string{"zone"}, ) zoneBandwidthSSLEncrypted = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_bandwidth_ssl_encrypted", Help: "Encrypted bandwidth per zone in bytes", }, []string{"zone"}, ) zoneBandwidthContentType = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_bandwidth_content_type", Help: "Bandwidth per zone per content type", }, []string{"zone", "content_type"}, ) zoneBandwidthCountry = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_bandwidth_country", Help: "Bandwidth per country per zone", }, []string{"zone", "country", "region"}, ) zoneThreatsTotal = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_threats_total", Help: "Threats per zone", }, []string{"zone"}, ) zoneThreatsCountry = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_threats_country", Help: "Threats per zone per country", }, []string{"zone", "country", "region"}, ) zoneThreatsType = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_threats_type", Help: "Threats per zone per type", }, []string{"zone", "type"}, ) zonePageviewsTotal = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_pageviews_total", Help: "Pageviews per zone", }, []string{"zone"}, ) zoneUniquesTotal = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_uniques_total", Help: "Uniques per zone", }, []string{"zone"}, ) zoneColocationVisits = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_colocation_visits", Help: "Total visits per colocation", }, []string{"zone", "colocation"}, ) zoneColocationEdgeResponseBytes = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_colocation_edge_response_bytes", Help: "Edge response bytes per colocation", }, []string{"zone", "colocation"}, ) zoneFirewallEventsCount = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_firewall_events_count", Help: "Count of Firewall events", }, []string{"zone", "action", "source", "host", "country"}, ) zoneHealthCheckEventsOriginCount = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_zone_health_check_events_origin_count", Help: "Number of Heath check events per region per origin", }, []string{"zone", "health_status", "origin_ip", "region", "fqdn"}, ) workerRequests = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_worker_requests_count", Help: "Number of requests sent to worker by script name", }, []string{"script_name"}, ) workerErrors = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cloudflare_worker_errors_count", Help: "Number of errors by script name", }, []string{"script_name"}, ) workerCPUTime = promauto.NewGaugeVec(prometheus.GaugeOpts{ Name: "cloudflare_worker_cpu_time", Help: "CPU time quantiles by script name", }, []string{"script_name", "quantile"}, ) workerDuration = promauto.NewGaugeVec(prometheus.GaugeOpts{ Name: "cloudflare_worker_duration", Help: "Duration quantiles by script name (GB*s)", }, []string{"script_name", "quantile"}, ) ) func fetchWorkerAnalytics(account cloudflare.Account, wg *sync.WaitGroup) { wg.Add(1) defer wg.Done() r, err := fetchWorkerTotals(account.ID) if err != nil { return } for _, a := range r.Viewer.Accounts { for _, w := range a.WorkersInvocationsAdaptive { workerRequests.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName}).Add(float64(w.Sum.Requests)) workerErrors.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName}).Add(float64(w.Sum.Errors)) workerCPUTime.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P50"}).Set(float64(w.Quantiles.CPUTimeP50)) workerCPUTime.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P75"}).Set(float64(w.Quantiles.CPUTimeP75)) workerCPUTime.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P99"}).Set(float64(w.Quantiles.CPUTimeP99)) workerCPUTime.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P999"}).Set(float64(w.Quantiles.CPUTimeP999)) workerDuration.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P50"}).Set(float64(w.Quantiles.DurationP50)) workerDuration.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P75"}).Set(float64(w.Quantiles.DurationP75)) workerDuration.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P99"}).Set(float64(w.Quantiles.DurationP99)) workerDuration.With(prometheus.Labels{"script_name": w.Dimensions.ScriptName, "quantile": "P999"}).Set(float64(w.Quantiles.DurationP999)) } } } func fetchZoneColocationAnalytics(zones []cloudflare.Zone, wg *sync.WaitGroup) { wg.Add(1) defer wg.Done() // Colocation metrics are not available in non-enterprise zones if cfgFreeTier { return } zoneIDs := extractZoneIDs(zones) r, err := fetchColoTotals(zoneIDs) if err != nil { return } for _, z := range r.Viewer.Zones { cg := z.ColoGroups name := findZoneName(zones, z.ZoneTag) for _, c := range cg { zoneColocationVisits.With(prometheus.Labels{"zone": name, "colocation": c.Dimensions.ColoCode}).Add(float64(c.Sum.Visits)) zoneColocationEdgeResponseBytes.With(prometheus.Labels{"zone": name, "colocation": c.Dimensions.ColoCode}).Add(float64(c.Sum.EdgeResponseBytes)) } } } func fetchZoneAnalytics(zones []cloudflare.Zone, wg *sync.WaitGroup) { wg.Add(1) defer wg.Done() // None of the below referenced metrics are available in the free tier if cfgFreeTier { return } zoneIDs := extractZoneIDs(zones) r, err := fetchZoneTotals(zoneIDs) if err != nil { return } for _, z := range r.Viewer.Zones { name := findZoneName(zones, z.ZoneTag) addHTTPGroups(&z, name) addFirewallGroups(&z, name) addHealthCheckGroups(&z, name) addHTTPAdaptiveGroups(&z, name) } } func addHTTPGroups(z *zoneResp, name string) { // Nothing to do. if len(z.HTTP1mGroups) == 0 { return } zt := z.HTTP1mGroups[0] zoneRequestTotal.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.Requests)) zoneRequestCached.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.CachedRequests)) zoneRequestSSLEncrypted.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.EncryptedRequests)) for _, ct := range zt.Sum.ContentType { zoneRequestContentType.With(prometheus.Labels{"zone": name, "content_type": ct.EdgeResponseContentType}).Add(float64(ct.Requests)) zoneBandwidthContentType.With(prometheus.Labels{"zone": name, "content_type": ct.EdgeResponseContentType}).Add(float64(ct.Bytes)) } for _, country := range zt.Sum.Country { c := countries.ByName(country.ClientCountryName) region := c.Info().Region.Info().Name zoneRequestCountry.With(prometheus.Labels{"zone": name, "country": country.ClientCountryName, "region": region}).Add(float64(country.Requests)) zoneBandwidthCountry.With(prometheus.Labels{"zone": name, "country": country.ClientCountryName, "region": region}).Add(float64(country.Bytes)) zoneThreatsCountry.With(prometheus.Labels{"zone": name, "country": country.ClientCountryName, "region": region}).Add(float64(country.Threats)) } for _, status := range zt.Sum.ResponseStatus { zoneRequestHTTPStatus.With(prometheus.Labels{"zone": name, "status": strconv.Itoa(status.EdgeResponseStatus)}).Add(float64(status.Requests)) } zoneBandwidthTotal.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.Bytes)) zoneBandwidthCached.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.CachedBytes)) zoneBandwidthSSLEncrypted.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.EncryptedBytes)) zoneThreatsTotal.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.Threats)) for _, t := range zt.Sum.ThreatPathing { zoneThreatsType.With(prometheus.Labels{"zone": name, "type": t.Name}).Add(float64(t.Requests)) } zonePageviewsTotal.With(prometheus.Labels{"zone": name}).Add(float64(zt.Sum.PageViews)) // Uniques zoneUniquesTotal.With(prometheus.Labels{"zone": name}).Add(float64(zt.Unique.Uniques)) } func addFirewallGroups(z *zoneResp, name string) { // Nothing to do. if len(z.FirewallEventsAdaptiveGroups) == 0 { return } for _, g := range z.FirewallEventsAdaptiveGroups { zoneFirewallEventsCount.With( prometheus.Labels{ "zone": name, "action": g.Dimensions.Action, "source": g.Dimensions.Source, "host": g.Dimensions.ClientRequestHTTPHost, "country": g.Dimensions.ClientCountryName, }).Add(float64(g.Count)) } } func addHealthCheckGroups(z *zoneResp, name string) { if len(z.HealthCheckEventsAdaptiveGroups) == 0 { return } for _, g := range z.HealthCheckEventsAdaptiveGroups { zoneHealthCheckEventsOriginCount.With( prometheus.Labels{ "zone": name, "health_status": g.Dimensions.HealthStatus, "origin_ip": g.Dimensions.OriginIP, "region": g.Dimensions.Region, "fqdn": g.Dimensions.Fqdn, }).Add(float64(g.Count)) } } func addHTTPAdaptiveGroups(z *zoneResp, name string) { for _, g := range z.HTTPRequestsAdaptiveGroups { zoneRequestOriginStatusCountryHost.With( prometheus.Labels{ "zone": name, "status": strconv.Itoa(int(g.Dimensions.OriginResponseStatus)), "country": g.Dimensions.ClientCountryName, "host": g.Dimensions.ClientRequestHTTPHost, }).Add(float64(g.Count)) } for _, g := range z.HTTPRequestsEdgeCountryHost { zoneRequestStatusCountryHost.With( prometheus.Labels{ "zone": name, "status": strconv.Itoa(int(g.Dimensions.EdgeResponseStatus)), "country": g.Dimensions.ClientCountryName, "host": g.Dimensions.ClientRequestHTTPHost, }).Add(float64(g.Count)) } } <|start_filename|>cloudflare.go<|end_filename|> package main import ( "context" "time" "github.com/cloudflare/cloudflare-go" "github.com/machinebox/graphql" log "github.com/sirupsen/logrus" ) var ( cfGraphQLEndpoint = "https://api.cloudflare.com/client/v4/graphql/" ) type cloudflareResponse struct { Viewer struct { Zones []zoneResp `json:"zones"` } `json:"viewer"` } type cloudflareResponseAccts struct { Viewer struct { Accounts []accountResp `json:"accounts"` } `json:"viewer"` } type cloudflareResponseColo struct { Viewer struct { Zones []zoneRespColo `json:"zones"` } `json:"viewer"` } type accountResp struct { WorkersInvocationsAdaptive []struct { Dimensions struct { ScriptName string `json:"scriptName"` Status string `json:"status"` } Sum struct { Requests uint64 `json:"requests"` Errors uint64 `json:"errors"` Duration float64 `json:"duration"` } `json:"sum"` Quantiles struct { CPUTimeP50 float32 `json:"cpuTimeP50"` CPUTimeP75 float32 `json:"cpuTimeP75"` CPUTimeP99 float32 `json:"cpuTimeP99"` CPUTimeP999 float32 `json:"cpuTimeP999"` DurationP50 float32 `json:"durationP50"` DurationP75 float32 `json:"durationP75"` DurationP99 float32 `json:"durationP99"` DurationP999 float32 `json:"durationP999"` } `json:"quantiles"` } `json:"workersInvocationsAdaptive"` } type zoneRespColo struct { ColoGroups []struct { Dimensions struct { Datetime string `json:"datetime"` ColoCode string `json:"coloCode"` } `json:"dimensions"` Count uint64 `json:"count"` Sum struct { EdgeResponseBytes uint64 `json:"edgeResponseBytes"` Visits uint64 `json:"visits"` } `json:"sum"` Avg struct { SampleInterval float64 `json:"sampleInterval"` } `json:"avg"` } `json:"httpRequestsAdaptiveGroups"` ZoneTag string `json:"zoneTag"` } type zoneResp struct { HTTP1mGroups []struct { Dimensions struct { Datetime string `json:"datetime"` } `json:"dimensions"` Unique struct { Uniques uint64 `json:"uniques"` } `json:"uniq"` Sum struct { Bytes uint64 `json:"bytes"` CachedBytes uint64 `json:"cachedBytes"` CachedRequests uint64 `json:"cachedRequests"` Requests uint64 `json:"requests"` BrowserMap []struct { PageViews uint64 `json:"pageViews"` UaBrowserFamily string `json:"uaBrowserFamily"` } `json:"browserMap"` ClientHTTPVersion []struct { Protocol string `json:"clientHTTPProtocol"` Requests uint64 `json:"requests"` } `json:"clientHTTPVersionMap"` ClientSSL []struct { Protocol string `json:"clientSSLProtocol"` } `json:"clientSSLMap"` ContentType []struct { Bytes uint64 `json:"bytes"` Requests uint64 `json:"requests"` EdgeResponseContentType string `json:"edgeResponseContentTypeName"` } `json:"contentTypeMap"` Country []struct { Bytes uint64 `json:"bytes"` ClientCountryName string `json:"clientCountryName"` Requests uint64 `json:"requests"` Threats uint64 `json:"threats"` } `json:"countryMap"` EncryptedBytes uint64 `json:"encryptedBytes"` EncryptedRequests uint64 `json:"encryptedRequests"` IPClass []struct { Type string `json:"ipType"` Requests uint64 `json:"requests"` } `json:"ipClassMap"` PageViews uint64 `json:"pageViews"` ResponseStatus []struct { EdgeResponseStatus int `json:"edgeResponseStatus"` Requests uint64 `json:"requests"` } `json:"responseStatusMap"` ThreatPathing []struct { Name string `json:"threatPathingName"` Requests uint64 `json:"requests"` } `json:"threatPathingMap"` Threats uint64 `json:"threats"` } `json:"sum"` } `json:"httpRequests1mGroups"` FirewallEventsAdaptiveGroups []struct { Count uint64 `json:"count"` Dimensions struct { Action string `json:"action"` Source string `json:"source"` ClientCountryName string `json:"clientCountryName"` ClientRequestHTTPHost string `json:"clientRequestHTTPHost"` } `json:"dimensions"` } `json:"firewallEventsAdaptiveGroups"` HTTPRequestsAdaptiveGroups []struct { Count uint64 `json:"count"` Dimensions struct { OriginResponseStatus uint16 `json:"originResponseStatus"` ClientCountryName string `json:"clientCountryName"` ClientRequestHTTPHost string `json:"clientRequestHTTPHost"` } `json:"dimensions"` } `json:"httpRequestsAdaptiveGroups"` HTTPRequestsEdgeCountryHost []struct { Count uint64 `json:"count"` Dimensions struct { EdgeResponseStatus uint16 `json:"edgeResponseStatus"` ClientCountryName string `json:"clientCountryName"` ClientRequestHTTPHost string `json:"clientRequestHTTPHost"` } `json:"dimensions"` } `json:"httpRequestsEdgeCountryHost"` HealthCheckEventsAdaptiveGroups []struct { Count uint64 `json:"count"` Dimensions struct { HealthStatus string `json:"healthStatus"` OriginIP string `json:"originIP"` FailureReason string `json:"failureReason"` Region string `json:"region"` Fqdn string `json:"fqdn"` } `json:"dimensions"` } `json:"healthCheckEventsAdaptiveGroups"` ZoneTag string `json:"zoneTag"` } func fetchZones() []cloudflare.Zone { var api *cloudflare.API var err error if len(cfgCfAPIToken) > 0 { api, err = cloudflare.NewWithAPIToken(cfgCfAPIToken) } else { api, err = cloudflare.New(cfgCfAPIKey, cfgCfAPIEmail) } if err != nil { log.Fatal(err) } ctx := context.Background() z, err := api.ListZones(ctx) if err != nil { log.Fatal(err) } return z } func fetchAccounts() []cloudflare.Account { var api *cloudflare.API var err error if len(cfgCfAPIToken) > 0 { api, err = cloudflare.NewWithAPIToken(cfgCfAPIToken) } else { api, err = cloudflare.New(cfgCfAPIKey, cfgCfAPIEmail) } if err != nil { log.Fatal(err) } ctx := context.Background() a, _, err := api.Accounts(ctx, cloudflare.PaginationOptions{PerPage: 100}) if err != nil { log.Fatal(err) } return a } func fetchZoneTotals(zoneIDs []string) (*cloudflareResponse, error) { now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC() s := 60 * time.Second now = now.Truncate(s) now1mAgo := now.Add(-60 * time.Second) request := graphql.NewRequest(` query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) { viewer { zones(filter: { zoneTag_in: $zoneIDs }) { zoneTag httpRequests1mGroups(limit: $limit filter: { datetime: $maxtime }) { uniq { uniques } sum { browserMap { pageViews uaBrowserFamily } bytes cachedBytes cachedRequests clientHTTPVersionMap { clientHTTPProtocol requests } clientSSLMap { clientSSLProtocol requests } contentTypeMap { bytes requests edgeResponseContentTypeName } countryMap { bytes clientCountryName requests threats } encryptedBytes encryptedRequests ipClassMap { ipType requests } pageViews requests responseStatusMap { edgeResponseStatus requests } threatPathingMap { requests threatPathingName } threats } dimensions { datetime } } firewallEventsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) { count dimensions { action source clientRequestHTTPHost clientCountryName } } httpRequestsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime, cacheStatus_notin: ["hit"] }) { count dimensions { originResponseStatus clientCountryName clientRequestHTTPHost } } httpRequestsEdgeCountryHost: httpRequestsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) { count dimensions { edgeResponseStatus clientCountryName clientRequestHTTPHost } } healthCheckEventsAdaptiveGroups(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime }) { count dimensions { healthStatus originIP region fqdn } } } } } `) if len(cfgCfAPIToken) > 0 { request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken) } else { request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail) request.Header.Set("X-AUTH-KEY", cfgCfAPIKey) } request.Var("limit", 9999) request.Var("maxtime", now) request.Var("mintime", now1mAgo) request.Var("zoneIDs", zoneIDs) ctx := context.Background() graphqlClient := graphql.NewClient(cfGraphQLEndpoint) var resp cloudflareResponse if err := graphqlClient.Run(ctx, request, &resp); err != nil { log.Error(err) return nil, err } return &resp, nil } func fetchColoTotals(zoneIDs []string) (*cloudflareResponseColo, error) { now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC() s := 60 * time.Second now = now.Truncate(s) now1mAgo := now.Add(-60 * time.Second) request := graphql.NewRequest(` query ($zoneIDs: [String!], $mintime: Time!, $maxtime: Time!, $limit: Int!) { viewer { zones(filter: { zoneTag_in: $zoneIDs }) { zoneTag httpRequestsAdaptiveGroups( limit: $limit filter: { datetime_geq: $mintime, datetime_lt: $maxtime } ) { count avg { sampleInterval } dimensions { coloCode datetime } sum { edgeResponseBytes visits } } } } } `) if len(cfgCfAPIToken) > 0 { request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken) } else { request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail) request.Header.Set("X-AUTH-KEY", cfgCfAPIKey) } request.Var("limit", 9999) request.Var("maxtime", now) request.Var("mintime", now1mAgo) request.Var("zoneIDs", zoneIDs) ctx := context.Background() graphqlClient := graphql.NewClient(cfGraphQLEndpoint) var resp cloudflareResponseColo if err := graphqlClient.Run(ctx, request, &resp); err != nil { log.Error(err) return nil, err } return &resp, nil } func fetchWorkerTotals(accountID string) (*cloudflareResponseAccts, error) { now := time.Now().Add(-time.Duration(cfgScrapeDelay) * time.Second).UTC() s := 60 * time.Second now = now.Truncate(s) now1mAgo := now.Add(-60 * time.Second) request := graphql.NewRequest(` query ($accountID: String!, $mintime: Time!, $maxtime: Time!, $limit: Int!) { viewer { accounts(filter: {accountTag: $accountID} ) { workersInvocationsAdaptive(limit: $limit, filter: { datetime_geq: $mintime, datetime_lt: $maxtime}) { dimensions { scriptName status datetime } sum { requests errors duration } quantiles { cpuTimeP50 cpuTimeP75 cpuTimeP99 cpuTimeP999 durationP50 durationP75 durationP99 durationP999 } } } } } `) if len(cfgCfAPIToken) > 0 { request.Header.Set("Authorization", "Bearer "+cfgCfAPIToken) } else { request.Header.Set("X-AUTH-EMAIL", cfgCfAPIEmail) request.Header.Set("X-AUTH-KEY", cfgCfAPIKey) } request.Var("limit", 9999) request.Var("maxtime", now) request.Var("mintime", now1mAgo) request.Var("accountID", accountID) ctx := context.Background() graphqlClient := graphql.NewClient(cfGraphQLEndpoint) var resp cloudflareResponseAccts if err := graphqlClient.Run(ctx, request, &resp); err != nil { log.Error(err) return nil, err } return &resp, nil } func findZoneName(zones []cloudflare.Zone, ID string) string { for _, z := range zones { if z.ID == ID { return z.Name } } return "" } func extractZoneIDs(zones []cloudflare.Zone) []string { var IDs []string for _, z := range zones { IDs = append(IDs, z.ID) } return IDs }
tomas-balaz/cloudflare-exporter
<|start_filename|>dependencies/freeglut-3.2.0/src/fg_window.c<|end_filename|> /* * fg_window.c * * Window management methods. * * Copyright (c) 1999-2000 <NAME>. All Rights Reserved. * Written by <NAME>, <<EMAIL>> * Creation date: Fri Dec 3 1999 * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * <NAME> BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define FREEGLUT_BUILDING_LIB #include <GL/freeglut.h> #include "fg_internal.h" #include "fg_gl2.h" /* * TODO BEFORE THE STABLE RELEASE: * * fgSetupPixelFormat -- ignores the display mode settings * fgOpenWindow() -- check the Win32 version, -iconic handling! * fgCloseWindow() -- check the Win32 version * glutCreateWindow() -- Check when default position and size is {-1,-1} * glutCreateSubWindow() -- Check when default position and size is {-1,-1} * glutDestroyWindow() -- check the Win32 version * glutSetWindow() -- check the Win32 version * glutSetWindowTitle() -- check the Win32 version * glutSetIconTitle() -- check the Win32 version * glutShowWindow() -- check the Win32 version * glutHideWindow() -- check the Win32 version * glutIconifyWindow() -- check the Win32 version * glutPushWindow() -- check the Win32 version * glutPopWindow() -- check the Win32 version */ extern void fgPlatformSetWindow ( SFG_Window *window ); extern void fgPlatformOpenWindow( SFG_Window* window, const char* title, GLboolean positionUse, int x, int y, GLboolean sizeUse, int w, int h, GLboolean gameMode, GLboolean isSubWindow ); extern void fgPlatformCloseWindow( SFG_Window* window ); extern void fgPlatformGlutSetWindowTitle( const char* title ); extern void fgPlatformGlutSetIconTitle( const char* title ); /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */ int fghIsLegacyContextRequested( void ) { return fgState.MajorVersion < 2 || (fgState.MajorVersion == 2 && fgState.MinorVersion <= 1); } int fghNumberOfAuxBuffersRequested( void ) { if ( fgState.DisplayMode & GLUT_AUX4 ) { return 4; } if ( fgState.DisplayMode & GLUT_AUX3 ) { return 3; } if ( fgState.DisplayMode & GLUT_AUX2 ) { return 2; } if ( fgState.DisplayMode & GLUT_AUX1 ) { /* NOTE: Same as GLUT_AUX! */ return fgState.AuxiliaryBufferNumber; } return 0; } int fghMapBit( int mask, int from, int to ) { return ( mask & from ) ? to : 0; } void fghContextCreationError( void ) { fgError( "Unable to create OpenGL %d.%d context (flags %x, profile %x)", fgState.MajorVersion, fgState.MinorVersion, fgState.ContextFlags, fgState.ContextProfile ); } /* -- SYSTEM-DEPENDENT PRIVATE FUNCTIONS ------------------------------------ */ /* * Sets the OpenGL context and the fgStructure "Current Window" pointer to * the window structure passed in. */ void fgSetWindow ( SFG_Window *window ) { fgPlatformSetWindow ( window ); fgStructure.CurrentWindow = window; } /* * Opens a window. Requires a SFG_Window object created and attached * to the freeglut structure. OpenGL context is created here. */ void fgOpenWindow( SFG_Window* window, const char* title, GLboolean positionUse, int x, int y, GLboolean sizeUse, int w, int h, GLboolean gameMode, GLboolean isSubWindow ) { fgPlatformOpenWindow( window, title, positionUse, x, y, sizeUse, w, h, gameMode, isSubWindow ); fgSetWindow( window ); #ifndef EGL_VERSION_1_0 window->Window.DoubleBuffered = ( fgState.DisplayMode & GLUT_DOUBLE ) ? 1 : 0; if ( ! window->Window.DoubleBuffered ) { glDrawBuffer ( GL_FRONT ); glReadBuffer ( GL_FRONT ); } #else /* - EGL is always double-buffered */ /* - No glDrawBuffer/glReadBuffer in GLES */ window->Window.DoubleBuffered = 1; #endif window->Window.attribute_v_coord = -1; window->Window.attribute_v_normal = -1; window->Window.attribute_v_texture = -1; fgInitGL2(); window->State.WorkMask |= GLUT_INIT_WORK; } /* * Closes a window, destroying the frame and OpenGL context */ void fgCloseWindow( SFG_Window* window ) { /* if we're in gamemode and we're closing the gamemode window, * call glutLeaveGameMode first to make sure the gamemode is * properly closed before closing the window */ if (fgStructure.GameModeWindow != NULL && fgStructure.GameModeWindow->ID==window->ID) glutLeaveGameMode(); fgPlatformCloseWindow ( window ); } /* -- INTERFACE FUNCTIONS -------------------------------------------------- */ /* * Creates a new top-level freeglut window */ int FGAPIENTRY glutCreateWindow( const char* title ) { /* XXX GLUT does not exit; it simply calls "glutInit" quietly if the * XXX application has not already done so. The "freeglut" community * XXX decided not to go this route (freeglut-developer e-mail from * XXX <NAME>, 12/16/04, 4:22 PM CST, "Re: [Freeglut-developer] * XXX Desired 'freeglut' behaviour when there is no current window") */ FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateWindow" ); return fgCreateWindow( NULL, title, fgState.Position.Use, fgState.Position.X, fgState.Position.Y, fgState.Size.Use, fgState.Size.X, fgState.Size.Y, GL_FALSE, GL_FALSE )->ID; } /* * This function creates a sub window. */ int FGAPIENTRY glutCreateSubWindow( int parentID, int x, int y, int w, int h ) { int ret = 0; SFG_Window* window = NULL; SFG_Window* parent = NULL; FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateSubWindow" ); parent = fgWindowByID( parentID ); freeglut_return_val_if_fail( parent != NULL, 0 ); if ( fgState.AllowNegativeWindowPosition ) { /* XXX This results in different widths/heights than if AllowNegativeWindowPosition * XXX was false. The "freeglut" community defined this logic. * XXX (freeglut-developer e-mail from <NAME>, 11/15/2015, 4:06 PM EST. * XXX "Re: [Freeglut-developer] glutInitWindowPosition with negative coordinate(s)") */ if ( w < 0 ) w = parent->State.Width + w ; if ( h < 0 ) h = parent->State.Height + h ; } else { if ( ( x < 0 ) ) { x = parent->State.Width + x ; if ( w > 0 ) x -= w ; } if ( w < 0 ) w = parent->State.Width - x + w ; if ( w < 0 ) { x += w ; w = -w ; } if ( ( y < 0 ) ) { y = parent->State.Height + y ; if ( h > 0 ) y -= h ; } if ( h < 0 ) h = parent->State.Height - y + h ; if ( h < 0 ) { y += h ; h = -h ; } } window = fgCreateWindow( parent, "", GL_TRUE, x, y, GL_TRUE, w, h, GL_FALSE, GL_FALSE ); ret = window->ID; return ret; } /* * Destroys a window and all of its subwindows */ void FGAPIENTRY glutDestroyWindow( int windowID ) { SFG_Window* window; FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutDestroyWindow" ); window = fgWindowByID( windowID ); freeglut_return_if_fail( window != NULL ); { fgExecutionState ExecState = fgState.ExecState; fgAddToWindowDestroyList( window ); fgState.ExecState = ExecState; } } /* * This function selects the specified window as the current window */ void FGAPIENTRY glutSetWindow( int ID ) { SFG_Window* window = NULL; FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindow" ); if( fgStructure.CurrentWindow != NULL ) if( fgStructure.CurrentWindow->ID == ID ) return; window = fgWindowByID( ID ); if( window == NULL ) { fgWarning( "glutSetWindow(): window ID %d not found!", ID ); return; } fgSetWindow( window ); } /* * This function returns the ID number of the current window, 0 if none exists */ int FGAPIENTRY glutGetWindow( void ) { SFG_Window *win = fgStructure.CurrentWindow; /* * Since GLUT did not throw an error if this function was called without a prior call to * "glutInit", this function shouldn't do so here. Instead let us return a zero. * See Feature Request "[ 1307049 ] glutInit check". */ if ( ! fgState.Initialised ) return 0; while ( win && win->IsMenu ) win = win->Parent; return win ? win->ID : 0; } /* * This function makes the current window visible */ void FGAPIENTRY glutShowWindow( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutShowWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutShowWindow" ); fgStructure.CurrentWindow->State.WorkMask |= GLUT_VISIBILITY_WORK; fgStructure.CurrentWindow->State.DesiredVisibility = DesireNormalState; fgStructure.CurrentWindow->State.WorkMask |= GLUT_DISPLAY_WORK; } /* * This function hides the current window */ void FGAPIENTRY glutHideWindow( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutHideWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutHideWindow" ); fgStructure.CurrentWindow->State.WorkMask |= GLUT_VISIBILITY_WORK; fgStructure.CurrentWindow->State.DesiredVisibility = DesireHiddenState; fgStructure.CurrentWindow->State.WorkMask &= ~GLUT_DISPLAY_WORK; } /* * Iconify the current window (top-level windows only) */ void FGAPIENTRY glutIconifyWindow( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutIconifyWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutIconifyWindow" ); fgStructure.CurrentWindow->State.WorkMask |= GLUT_VISIBILITY_WORK; fgStructure.CurrentWindow->State.DesiredVisibility = DesireIconicState; fgStructure.CurrentWindow->State.WorkMask &= ~GLUT_DISPLAY_WORK; } /* * Set the current window's title */ void FGAPIENTRY glutSetWindowTitle( const char* title ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowTitle" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowTitle" ); if( ! fgStructure.CurrentWindow->Parent ) { fgPlatformGlutSetWindowTitle ( title ); } } /* * Set the current window's iconified title */ void FGAPIENTRY glutSetIconTitle( const char* title ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetIconTitle" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetIconTitle" ); if( ! fgStructure.CurrentWindow->Parent ) { fgPlatformGlutSetIconTitle ( title ); } } /* * Change the current window's size */ void FGAPIENTRY glutReshapeWindow( int width, int height ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutReshapeWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutReshapeWindow" ); if (glutGet(GLUT_FULL_SCREEN)) { /* Leave full screen state before resizing. */ glutLeaveFullScreen(); } fgStructure.CurrentWindow->State.WorkMask |= GLUT_SIZE_WORK; fgStructure.CurrentWindow->State.DesiredWidth = width ; fgStructure.CurrentWindow->State.DesiredHeight = height; } /* * Change the current window's position */ void FGAPIENTRY glutPositionWindow( int x, int y ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPositionWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPositionWindow" ); if (glutGet(GLUT_FULL_SCREEN)) { /* Leave full screen state before moving. */ glutLeaveFullScreen(); } fgStructure.CurrentWindow->State.WorkMask |= GLUT_POSITION_WORK; fgStructure.CurrentWindow->State.DesiredXpos = x; fgStructure.CurrentWindow->State.DesiredYpos = y; } /* * Lowers the current window (by Z order change) */ void FGAPIENTRY glutPushWindow( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPushWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPushWindow" ); fgStructure.CurrentWindow->State.WorkMask |= GLUT_ZORDER_WORK; fgStructure.CurrentWindow->State.DesiredZOrder = -1; } /* * Raises the current window (by Z order change) */ void FGAPIENTRY glutPopWindow( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPopWindow" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPopWindow" ); fgStructure.CurrentWindow->State.WorkMask |= GLUT_ZORDER_WORK; fgStructure.CurrentWindow->State.DesiredZOrder = 1; } /* * Resize the current window so that it fits the whole screen */ void FGAPIENTRY glutFullScreen( void ) { SFG_Window *win; FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreen" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreen" ); win = fgStructure.CurrentWindow; if (win->Parent) { /* Child windows cannot be made fullscreen, consistent with GLUT's behavior * Also, what would it mean for a child window to be fullscreen, given that it * is confined to its parent? */ fgWarning("glutFullScreen called on a child window, ignoring..."); return; } else if (fgStructure.GameModeWindow != NULL && fgStructure.GameModeWindow->ID==win->ID && win->State.IsFullscreen) { /* Ignore fullscreen call on GameMode window, those are always fullscreen already * only exception is when first entering GameMode */ return; } if (!win->State.IsFullscreen) win->State.WorkMask |= GLUT_FULL_SCREEN_WORK; } /* * If we are fullscreen, resize the current window back to its original size */ void FGAPIENTRY glutLeaveFullScreen( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreen" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreen" ); if (fgStructure.CurrentWindow->State.IsFullscreen) fgStructure.CurrentWindow->State.WorkMask |= GLUT_FULL_SCREEN_WORK; } /* * Toggle the window's full screen state. */ void FGAPIENTRY glutFullScreenToggle( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreenToggle" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreenToggle" ); fgStructure.CurrentWindow->State.WorkMask |= GLUT_FULL_SCREEN_WORK; } /* * A.Donev: Set and retrieve the window's user data */ void* FGAPIENTRY glutGetWindowData( void ) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGetWindowData" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutGetWindowData" ); return fgStructure.CurrentWindow->UserData; } void FGAPIENTRY glutSetWindowData(void* data) { FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowData" ); FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowData" ); fgStructure.CurrentWindow->UserData = data; } /*** END OF FILE ***/
sgavil/chip8-interpreter
<|start_filename|>pwa.js<|end_filename|> if ("serviceWorker" in navigator) { window.addEventListener("load", () => { navigator.serviceWorker .register("./sw.js") .then((reg) => console.log("Registered! ", reg)) .catch((err) => console.log("Registeration Failed", err)); }); } // Use this in case you want to add install button popup // let deferredPrompt; // window.addEventListener("beforeinstallprompt", (e) => { // // Prevent old bowsers to trigger prompt before waiting for this event // // here we are triggering installing prompt using button and preventing it from opening itself on some browsers // // checkout here - https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent // e.preventDefault(); // deferredPrompt = e; // // make the UI changes here ---> // const btnAdd = document.getElementById("installButton"); // btnAdd.style.display = "block"; // // Add event listener on UI element // btnAdd.addEventListener("click", (e) => { // // prompt the user with install prompt // deferredPrompt.prompt(); // // wait for user choice // deferredPrompt.userChoice.then((choiceResult) => { // if (choiceResult.outcome === "accepted") { // console.log("User Accepted the A2HS prompt"); // } // // here set custom prompt to null as it is not accepted and this before install prompt will trigger next time page is reloaded // deferredPrompt = null; // }); // }); // }); // Analytics window.addEventListener("appinstalled", (e) => app.logEvent("a2hs", "installed") ); <|start_filename|>js/projects.js<|end_filename|> let domain = [ "Web Development", "Machine Learning", "API", "DSA", "NODEJS", "App Development", ]; let htmlc = `<select class="custom-select mr-sm-2 " id="type">`; htmlc += `<option value="Choose your Domain" disabled selected>Choose your Domain</option>`; for (let index = 0; index < domain.length; index++) { htmlc += `<option value="${index}">${domain[index]}</option>`; } htmlc += "</select>"; $("#selectoption").append(htmlc); fetch("../data/projects.json") .then((data) => data.json()) .then((data) => { let valu; $(function () { $("#type").change(function () { valu = $(this).val(); console.log(valu); let index = valu; $("#project").empty(); $("#error").empty(); console.log(data[index].Data.length); if (valu < data.length && data[index].Data.length > 0) { for (let i = 0; i < data[index].Data.length; i++) { try { console.log(data); var html = ""; for (i = 0; i < data[index].Data.length; i++) { html += ` <li class="cards_item"> <div class="card"> <div class="card_content"> <p class="card_title">${data[index].Data[i].langName}</p> <span class="cardtitle">Project Admin-${data[index].Data[i].langAdmin}</span> <h6 class="card_title">Tech Stack- ${data[index].Data[i].langTitle}</h6> <p class="card_text">${data[index].Data[i].langDesc}</p> <button class="btn card_btn" onclick="window.location.href='${data[index].Data[i].langurl}'"target="blank">Repo Url</button> </div> </div> </li> `; } $("#project").append(html); } catch (error) { console.log(error); } } } else { var htmlz = `<div class= "container unique-style3 mb-5 pb-5">`; htmlz += `<p class="text-light text-center text-no-data">No data found.Please select another month.</p>`; htmlz += `</div>`; $("#error").append(htmlz); } }); }); }); <|start_filename|>js/tutorial.js<|end_filename|> const getData = async () => { fetch("../data/tutorial.json") .then((data) => data.json()) .then((data) => { try { console.log(data); var html = '<div class="row">'; for (i = 0; i < data.length; i++) { if (i % 3 == 0 && i != 0) { html += "</div>"; html += '<div class="row">'; } html += `<div class="col-lg-4 col-sm-4">`; html += `<div class="mt-5 card text-center"> <a href=https://www.youtube.com/embed/${data[i].tutorialId}?autoplay=1> <img id="ytimg" height="100%" width="100%" src=https://img.youtube.com/vi/${data[i].tutorialId}/hqdefault.jpg alt='ytvideo'> <div class" text-center" > <span id="butt"><img src="https://img.icons8.com/color/48/000000/youtube-play.png"/></span> </div> </a> </div> `; html += `<div class="about-txt"> <span class="style-span">${data[i].title}</span> <h5 style="color: white; padding:8px 0px 8px 0px;">${data[i].subtitle}</h5> <div> <p style="text-align: justify;">${data[i].para}</p> </div> </div></div>`; } $("#rowdy").append(html); } catch (error) { console.log(error); } }) }; getData(); <|start_filename|>sw.js<|end_filename|> // documented by <NAME> - https://neerajgupta.codes self.addEventListener("install", (event) => { console.log("Service worker install event!"); // event.waitUntil will wait until innermost event is resolved // waitUntil will prevent the browser to terminate the service worker process before promise is resolved // read about waitUntil here - https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil event.waitUntil( // Open cache(cacheName) from CacheStorage and if opened add all resourcesToPrecache in CacheStorage caches .open(cacheName) .then((cache) => cache.addAll(resourcesToPrecache)) .catch((err) => console.log("Faled to precache", err)) ); }); self.addEventListener("activate", (event) => console.log("Activate event")); // fetching files from either cache or network self.addEventListener("fetch", (event) => { // respondWith will prevent browser to directly go and do fetch request instead provide user with power to do task manually depending on promise // read about respondWith here - https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith event.respondWith( caches .match(event.request) .then((cachedResponse) => cachedResponse || fetch(event.request)) //returning cache or if not available fetching from event ); }); self.addEventListener("push", (event) => { const title = "Yes, a message"; const body = "We have received a push message"; const tag = "simple-push-example-tag"; const options = { body: body, tag: tag, }; event.waitUntil(self.registration.showNotification(title, options)); }); // Pre Caching resources const cacheName = "cache-v1"; const resourcesToPrecache = [ "/", "/index.html", "/pages/about.html", "/pages/Error.html", "/pages/program.html", "/pages/projects.html", "/pages/tutorial.html", "/css/style.css", "/css/about.css", "/css/bootstrap.min.css", "/css/projects.css", "/css/responsive.css.css", "/css/slick.css", "/images/Opentek.png", "/js/auth0.js", "/js/bootstrap.min.js", "/js/circular.js", "/js/custom.js", "/js/event.js", "/js/jquery-3.3.1.min.js", "/js/program.js", "/js/projects.js", "/js/slick.min.js", "/js/tutorial.js", "/images/team.svg", "/images/error.svg", "/images/about3.svg", "/images/about2.svg", "/images/about1.svg", ]; <|start_filename|>css/about.css<|end_filename|> .banner-about { font-family: pb; color: #aa80ff; padding-bottom: 23px; /* padding-top: 16px; */ } #p-tag-left { padding-top: 20px; color: #f0e0d0; } #p-tag-right { color: white; position: relative; right: 60px; padding-top: 40px; /* padding-bottom: 23px; */ } #image-team { /* position: relative; */ /* right: 30px; */ padding-top: 1rem; max-width: 100%; height: auto; } .ul-tag ::before { content: "\2022"; color: #aa80ff; font-weight: bolder; font-size: medium; display: inline-block; width: 1em; margin-left: -1em; } .ul-tag { color: #f0e0d0; } li { font-size: medium; line-height: 1.5rem; } /*=========================== *** TEAM AREA START *** =============================*/ #team { padding: 80px 0; position: relative; } .team-header h3:after { width: 164px; } #team::after { position: absolute; content: ""; top: 380px; left: -25px; width: 170px; height: 140px; background: #aa80ff; z-index: -1; -webkit-clip-path: polygon( 34% 32%, 64% 46%, 100% 31%, 100% 55%, 65% 70%, 33% 56%, 0 61%, 0 39% ); clip-path: polygon( 34% 32%, 64% 46%, 100% 31%, 100% 55%, 65% 70%, 33% 56%, 0 61%, 0 39% ); -webkit-box-shadow: 0 31px 35px rgba(0, 0, 0, 0.1); box-shadow: 0 31px 35px rgba(0, 0, 0, 0.1); } #team::before { position: absolute; content: ""; top: 430px; left: -25px; width: 170px; height: 140px; background: #aa80ff; z-index: -1; -webkit-clip-path: polygon( 34% 32%, 64% 46%, 100% 31%, 100% 55%, 65% 70%, 33% 56%, 0 61%, 0 39% ); clip-path: polygon( 34% 32%, 64% 46%, 100% 31%, 100% 55%, 65% 70%, 33% 56%, 0 61%, 0 39% ); -webkit-box-shadow: 0 31px 35px rgba(0, 0, 0, 0.1); box-shadow: 0 31px 35px rgba(0, 0, 0, 0.1); } .team-pa { padding-top: 85px; } .team-item img { border-radius: 30% 84% 28% 76% / 87% 23% 69% 29%; border: 6px solid #aa80ff; width: 40vh; } .team-item h3 { font-family: pb; font-size: 26px; color: white; padding: 30px 0 14px; } .team-item p { font-family: pr; font-size: 18px; /* font-size: clamp(1rem, 2.5vw, 2rem); */ color: #a19999; padding-bottom: 14px; } @media screen and (max-width: 800px) { #p-tag-right { right: 0%; padding: 5px; } .ul-tag { padding: 0 1em; } } .team-item a { font-family: pb; font-size: 16px; color: #aa80ff; } .team-btn a { padding: 14px 20px; background: #aa80ff; color: #fff; font-size: 18px; font-family: pb; position: relative; } .contributors { display: flex; justify-content: center; margin-bottom: 3rem; width: 100%; object-fit: cover; } #imgid { border-radius: 50%; width: 60px; height: 60px; } <|start_filename|>css/responsive.css<|end_filename|> .navbar-toggler:not(:disabled):not(.disabled) { cursor: pointer; background: none; } #index2 .navbar-light .navbar-toggler { color: #fff; outline: 0; } #index3 .navbar-light .navbar-toggler, #index4 .navbar-light .navbar-toggler { color: #fff; outline: 0; } .navbar-light .navbar-toggler { color: #fff; outline: 0; } .navbar-toggler i { font-size: 28px; } .nav-bg i { color: #fff; } .navbar-toggler { border: none; } @media (max-width: 1380px) { .row { padding-top: 35px; } } @media (max-width: 991px) { .navbar-light .navbar-nav .nav-link { margin: 18px; color: #fff; line-height: 0; } .nav-bg { padding-left: 12px; } .menu-item { background: #101822; text-align: center; padding: 15px 0; } .navbar::after { display: none; } .navbar-light .navbar-brand { color: #fff; } .navbar-light .navbar-brand:hover { color: #fff; } .nav-bg .navbar-brand:hover { color: #fff; } .nav-bg .navbar-brand { color: #fff; } .navbar-light .navbar-nav .nav-link.active::after { opacity: 0; } .navbar-light .navbar-nav .nav-link:hover:after { opacity: 0; } .nav-bg .bor { background: none; } .menu-item .bor { color: #aa80ff; } .bor::after { display: none; } } @media (max-width: 1000px) and (min-width: 575px) { #text { font-size: 2.5rem; } } @media (max-width: 575px) { .dropboxx, .dropboxx2 { font-size: 15px; } #banner { padding: 154px 0 93px; } #text-down { font-size: small !important; } .banner-txt h3 { font-size: 30px !important; } .banner-txt h1 { font-size: 20px !important; } .banner-txt { padding-top: 60px; } .navbar-toggler i { font-size: 23px; } .navbar-light .navbar-brand { font-size: 20px; } #banner::before, .mob-hide, .mob-img-hide, #team::before, #team::after, #review::after, .design-layer { display: none; } .design-layer::after { top: 690px; right: -35px; } .design-layer::before { top: 730px; right: -35px; } .unique-style:before, .unique-style2:before, .unique-style:after, .unique-style2:after { display: none; } .unique-style3::after { top: -5px; } .unique-style3::before { top: -12px; } .over-item { text-align: center !important; padding: 35px 14px; } .txt-right p { padding-left: 0; } .txt-left p { padding-right: 0; } #about { padding: 80px 0; } .about-pa { padding-top: 0; } .about-txt h3 { font-size: 24px; } .list { margin-left: 1em; } .mob-mar-top, .g-mar { margin-top: 30px; } .mob-mar-bottom { margin-bottom: 30px; } #team { padding: 60px 0; } .team-pa { padding-top: 65px; } .team-item { padding-top: 45px; } } @media (min-width: 576px) and (max-width: 767px) { #banner { padding: 145px 0 100px; } .banner-txt { padding-top: 85px; } #banner::before { display: none; } .over-item p { font-size: 16px; } .design-layer::before { top: 765px; } .design-layer::after { top: 717px; } .over-item { padding: 30px 25px; } .over-item h3 { font-size: 23px; } .unique-style:before, .unique-style2:before, .unique-style:after, .unique-style2:after { display: none; } #about { padding: 60px 0; } .about-item, .about-txt { padding-top: 75px; } .team-item h3 { font-size: 22px; } #team::after { top: 475px; left: -49px; height: 125px; } #team::before { top: 510px; left: -49px; height: 125px; } .team-item img { border: 4px solid #aa80ff; } .footer-social { padding-bottom: 35px; } #footer { padding: 120px 0 80px; } } @media (min-width: 768px) and (max-width: 991px) { #banner::before { display: none; } .design-layer::before { top: 685px; } .design-layer::after { top: 727px; } .unique-style:before, .unique-style2:before, .unique-style:after, .unique-style2:after { display: none; } .over-item { padding: 35px 24px; } .about-txt h3 { font-size: 21px; } .counter-1 span { font-size: 13px; } .about-txt p { padding-bottom: 45px; } #team::before { top: 530px; } #team::after { top: 488px; } .footer-social { padding-top: 11px; padding-bottom: 40px; } .links h3 { font-size: 19px; } #footer { padding: 115px 0 75px; } } @media (min-width: 992px) and (max-width: 1199px) { #banner::before { display: none; } .sp-img { height: 277px; } .sp-img2 { height: 286px; } .unique-style:before, .unique-style2:before, .unique-style:after, .unique-style2:after { display: none; } #team::before { top: 600px; } #team::after { top: 562px; } .links h3 { font-size: 18px; } .footer-social { padding-top: 5px; } } <|start_filename|>data/tutorial.json<|end_filename|> [ { "tutorialId": "msyGybzCKRs", "title": "<NAME>", "subtitle": "About the Video", "para": "In this video you will understand what Open Source is and how contributing can help you." }, { "tutorialId": "uj4fy4kpaOA", "title": "<NAME>", "subtitle": "About the Video", "para": "This video includes overview of Git and Github, complete practical use of all the git commands IN JUST 33 MINUTES" }, { "tutorialId": "2j7fD92g-gE", "title": "Simplilearn", "subtitle": "About the Video", "para": "This Git installation video will take you through the step by step process involved in Git installation on Windows." }, { "tutorialId": "apGV9Kg7ics", "title": "<NAME>", "subtitle": "About the Video", "para": "This tutorial will help you with using Git & GitHub for your personal projects and contributing to Open Source, with no prerequisites, in an easy to understand language." }, { "tutorialId": "yzeVMecydCE", "title": "FreeCodeCamp", "subtitle": "About the Video", "para": "Learn why and how to contribute to open source software. You will learn about how to find projects to contribute to, how to make issues and PRs, how to make money from open source, and more." }, { "tutorialId": "VdF6RvLiCao", "title": "Code For Cause", "subtitle": "About the Video", "para": "Are you a Java Developer looking for some Open Source organisations to contribute to? Here's a list of some Open Source organisations for you, & also some that take part in Google Summer of Code (GSoC) ☀️" }, { "tutorialId": "SYtPC9tHYyQ", "title": "<NAME>", "subtitle": "About the Video", "para": "Learn the jargons of GitHub like tag/release, commit, branch, fork, project board, label, milestone, actions and much more!" }, { "tutorialId": "GbqSvJs-6W4", "title": "Web Dev Simplified", "subtitle": "About the Video", "para": "In this video you will be guided through the process of finding your first issue and creating your first pull request." }, { "tutorialId": "loCLu8Iq1dQ", "title": "<NAME>", "subtitle": "About the Video", "para": "In this video, Kunal talks about his journey of getting into open source development and how he got the opportunity to become a Major League hacking Fellow. He talks about the benefits of contributing to open source as a developer, what are best open source orgs that you can check out to start contributing." } ] <|start_filename|>js/event.js<|end_filename|> let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; var d = new Date(); var n = months[d.getMonth()]; let htmlc = `<select class="custom-select mr-sm-2 " id="type">`; htmlc += `<option value="This month is ${n}. Check if any event is happening!!" disabled selected>This month is ${n}. Check if any event is happening!!</option>`; for (let index = 0; index < months.length; index++) { htmlc += `<option value="${index}">${months[index]}</option>`; } htmlc += "</select>"; $("#selectoption").append(htmlc); fetch("../data/event.json") .then((data) => data.json()) .then((data) => { let valu; $(function () { $("#type").change(function () { valu = $(this).val(); // console.log(valu); let index = valu; $("#rowdy").empty(); $("#error").empty(); if (valu < data.length && data[index].Data.length > 0) { for (let i = 0; i < data[index].Data.length; i++) { try { // console.log(data); var html = '<div class="row">'; for (i = 0; i < data[index].Data.length; i++) { if (i % 3 == 0 && i != 0) { html += "</div>"; html += '<div class="row">'; } html += `<div class="col-lg-9 col-12 m-auto"> <div class="over-item txt-right unique-style3 rounded-3"> <div class="row"> <div class="col-md-8 col-12 "> <div class="break"></div> <h3 class="text-left" >${data[index].Data[i].details.eventName}</h3> <h6 class="text-left text-light" >${data[index].Data[i].details.eventDate}</h6></br> <p class="text-left">${data[index].Data[i].details.eventDesc}</p> <div class="over-btn text-left"> <a href ="${data[index].Data[i].details.eventurl}" target="blank">Website</a> </div> </div> <div class="col-md-4 col-12"> <img src="${data[index].Data[i].details.eventImg}" height="auto" width="80%" alt="" srcset=""></div> </div> </div></div>`; } $("#rowdy").append(html); } catch (error) { console.log(error); } } } else { var htmlz = `<div class= "container unique-style3 mb-5 pb-5">`; htmlz += `<p class="text-light text-center text-no-data">No data found.Please select another month.</p>`; htmlz += `</div>`; $("#error").append(htmlz); } }); }); });
nileshkr17/opentek
<|start_filename|>public/docs/collection.json<|end_filename|> {"variables":[],"info":{"name":"","_postman_id":"eaeceac7-ad30-4f39-a660-2db83dc23dd6","description":"","schema":"https:\/\/schema.getpostman.com\/json\/collection\/v2.0.0\/collection.json"},"item":[{"name":"Authentication","description":"","item":[{"name":"Login","request":{"url":"http:\/\/localhost\/api\/v1\/auth\/login","method":"POST","body":{"mode":"formdata","formdata":[]},"description":"Handle a login request to the application.","response":[]}},{"name":"Registration","request":{"url":"http:\/\/localhost\/api\/v1\/auth\/register","method":"POST","body":{"mode":"formdata","formdata":[]},"description":"Handle a registration request for the application.","response":[]}}]},{"name":"Dashboards","description":"","item":[{"name":"Dashboard","request":{"url":"http:\/\/localhost\/api\/v1\/dashboard\/data","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Get user dashboard data","response":[]}},{"name":"Admin dashboard","request":{"url":"http:\/\/localhost\/api\/v1\/dashboard\/adminData","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Get admin dashboard data","response":[]}}]},{"name":"Entry","description":"","item":[{"name":"All ennties list","request":{"url":"http:\/\/localhost\/api\/v1\/entry\/all","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Display a listing of all users time entries (admin access only).","response":[]}},{"name":"Entries list","request":{"url":"http:\/\/localhost\/api\/v1\/entry","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Display a listing of time entries.","response":[]}},{"name":"Store Entry","request":{"url":"http:\/\/localhost\/api\/v1\/entry","method":"POST","body":{"mode":"formdata","formdata":[]},"description":"Store a newly created time entry in storage.","response":[]}},{"name":"Show entry","request":{"url":"http:\/\/localhost\/api\/v1\/entry\/{entry}","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Display the specified time entry.","response":[]}},{"name":"Update entry","request":{"url":"http:\/\/localhost\/api\/v1\/entry\/{entry}","method":"PUT","body":{"mode":"formdata","formdata":[]},"description":"Update time entry in storage.","response":[]}},{"name":"Delete entry","request":{"url":"http:\/\/localhost\/api\/v1\/entry\/{entry}","method":"DELETE","body":{"mode":"formdata","formdata":[]},"description":"Remove time entry from storage.","response":[]}}]},{"name":"Reports","description":"","item":[{"name":"Get weekly report","request":{"url":"http:\/\/localhost\/api\/v1\/report\/weekly","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"","response":[]}}]},{"name":"User","description":"","item":[{"name":"\u0421urrent authenticated user","request":{"url":"http:\/\/localhost\/api\/v1\/user\/me","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Return current authenticated user data","response":[]}},{"name":"Users list","request":{"url":"http:\/\/localhost\/api\/v1\/user","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Display a listing of users","response":[]}},{"name":"Show user","request":{"url":"http:\/\/localhost\/api\/v1\/user\/{user}","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"Display the specified user.","response":[]}},{"name":"Update user","request":{"url":"http:\/\/localhost\/api\/v1\/user\/{user}","method":"PUT","body":{"mode":"formdata","formdata":[]},"description":"Update the specified user in storage.","response":[]}},{"name":"Delete user","request":{"url":"http:\/\/localhost\/api\/v1\/user\/{user}","method":"DELETE","body":{"mode":"formdata","formdata":[]},"description":"Remove the specified user from storage.","response":[]}}]}]}
edgarFerlando/portal-admin-laravel
<|start_filename|>utils.test.js<|end_filename|> const utils = require("./utils"); test("#ffffff converts to rgb object", () => { expect(utils.hexToRGB("#ffffff")).toStrictEqual({ r: 255, g: 255, b: 255 }); }); <|start_filename|>index.test.js<|end_filename|> const hexAlpha = require("./index"); test("#FFFFFF converts to rgb(255,255,255)", () => { expect(hexAlpha("#ffffff")).toBe("rgb(255,255,255)"); }); test("#000000 converts to rgba(0,0,0,1)", () => { expect(hexAlpha("#000000", 1)).toBe("rgba(0,0,0,1)"); }); test("#fa6d01 converts to rgb(250,109,1)", () => { expect(hexAlpha("#fa6d01")).toBe("rgb(250,109,1)"); }); test("#f00 converts to rgba(0,0,0,1)", () => { expect(hexAlpha("#f00", 0.1)).toBe("rgba(255,0,0,0.1)"); }); test("HEX color and alpha converts to RGBA", () => { expect(hexAlpha("#fa6d01", 0.1)).toBe("rgba(250,109,1,0.1)"); }); test("HEX color with 0 or 1 alpha converts to RGBA", () => { expect(hexAlpha("#fa6d01", 0)).toBe("rgba(250,109,1,0)"); expect(hexAlpha("#fa6d01", 1)).toBe("rgba(250,109,1,1)"); }); test("HEX color with invalid `alpha` converts to RGB", () => { expect(hexAlpha("#fa6d01", "")).toBe("rgb(250,109,1)"); expect(hexAlpha("#fa6d01", false)).toBe("rgb(250,109,1)"); expect(hexAlpha("#fa6d01", -1)).toBe("rgb(250,109,1)"); expect(hexAlpha("#fa6d01", 2.4)).toBe("rgb(250,109,1)"); });
stowball/hex-alpha
<|start_filename|>RealtekCardReader/IOSDCard-CSD.hpp<|end_filename|> // // IOSDCard-CSD.hpp // RealtekCardReader // // Created by FireWolf on 12/24/21. // #ifndef IOSDCard_CSD_hpp #define IOSDCard_CSD_hpp #include "Utilities.hpp" /// Card specific data (Version 1.0) (16 bytes) struct PACKED CSDV1 { // =============== // | Common | // =============== /// The structure version UInt8 version: 2; /// Reserved 6 bits UInt8 reserved0: 6; /// Data read access time - 1 (Reserved 1 bit) UInt8 reserved1: 1; /// Data read access time - 1 (Time value) UInt8 taacTimeValue: 4; /// Data read access time - 1 (Time unit) UInt8 taacTimeUnit: 3; /// Data read access time - 2 in clock cycles UInt8 nasc; /// Maximum data transfer rate (Reserved 1 bit) UInt8 reservedDTR: 1; /// Maximum data transfer rate (Transfer rate value) UInt8 maxTransferRateValue: 4; /// Maximum data transfer rate (Transfer rate unit) UInt8 maxTransferRateUnit: 3; /// Card command classes UInt16 cardCommandClasses: 12; /// Maximum read data block length UInt16 maxReadDataBlockLength: 4; /// `True` if reading partial blocks is allowed bool isPartialBlockReadAllowed: 1; /// Write block misalignment UInt8 writeBlockMisalignment: 1; /// Read block misalignment UInt8 readBlockMisalignment: 1; /// `True` if DSR is implemented bool isDSRImplemented: 1; // =============== // | V1 Specific | // =============== /// Reserved 2 bits UInt8 reserved2: 2; /// Device size UInt16 deviceSize: 12; /// Maximum read current @ the minimum VDD UInt8 maxReadCurrentAtVDDMin: 3; /// Maximum read current @ the maximum VDD UInt8 maxReadCurrentAtVDDMax: 3; /// Maximum write current @ the minimum VDD UInt8 maxWriteCurrentAtVDDMin: 3; /// Maximum write current @ the maximum VDD UInt8 maxWriteCurrentAtVDDMax: 3; /// Device size multiplier UInt8 deviceSizeMultiplier: 3; // =============== // | Common | // =============== /// `True` if erasing a single block is enabled bool isEraseSingleBlockEnabled: 1; /// Erase sector size UInt8 eraseSectorSize: 7; /// Write protect group size UInt8 writeProtectGroupSize: 7; /// `True` if write protect group is enabled bool isWriteProtectGroupEnabled: 1; /// Reserved 2 bits UInt8 reserved3: 2; /// Write speed factor UInt8 writeSpeedFactor: 3; /// Maximum write data block length UInt8 maxWriteDataBlockLength: 4; /// `True` if writing partial blocks is allowed bool isPartialBlockWriteAllowed: 1; /// Reserved 5 bits UInt8 reserved4: 5; /// File format group UInt8 fileFormatGroup: 1; /// Copy flag UInt8 copyFlag: 1; /// Permanent write protection bool permanentWriteProtection: 1; /// Temporary write protection bool temporaryWriteProtection: 1; /// File format UInt8 fileFormat: 2; /// Reserved 2 bits UInt8 reserved5: 2; /// CRC7 checksum and the end bit UInt8 end; }; /// Card specific data (Version 2.0) (16 bytes) struct PACKED CSDV2 { // =============== // | Common | // =============== /// The structure version UInt8 version: 2; /// Reserved 6 bits UInt8 reserved0: 6; /// Data read access time - 1 (Reserved 1 bit) UInt8 reserved1: 1; /// Data read access time - 1 (Time value) UInt8 taacTimeValue: 4; /// Data read access time - 1 (Time unit) UInt8 taacTimeUnit: 3; /// Data read access time - 2 in clock cycles UInt8 nasc; /// Maximum data transfer rate (Reserved 1 bit) UInt8 reservedDTR: 1; /// Maximum data transfer rate (Transfer rate value) UInt8 maxTransferRateValue: 4; /// Maximum data transfer rate (Transfer rate unit) UInt8 maxTransferRateUnit: 3; /// Card command classes UInt16 cardCommandClasses: 12; /// Maximum read data block length UInt16 maxReadDataBlockLength: 4; /// `True` if reading partial blocks is allowed bool isPartialBlockReadAllowed: 1; /// Write block misalignment UInt8 writeBlockMisalignment: 1; /// Read block misalignment UInt8 readBlockMisalignment: 1; /// `True` if DSR is implemented bool isDSRImplemented: 1; // =============== // | V2 Specific | // =============== /// Reserved 6 bits UInt8 reserved2: 6; /// Device size UInt32 deviceSize: 22; /// Reserved 1 bit UInt8 reserved21: 1; // =============== // | Common | // =============== /// `True` if erasing a single block is enabled bool isEraseSingleBlockEnabled: 1; /// Erase sector size UInt8 eraseSectorSize: 7; /// Write protect group size UInt8 writeProtectGroupSize: 7; /// `True` if write protect group is enabled bool isWriteProtectGroupEnabled: 1; /// Reserved 2 bits UInt8 reserved3: 2; /// Write speed factor UInt8 writeSpeedFactor: 3; /// Maximum write data block length UInt8 maxWriteDataBlockLength: 4; /// `True` if writing partial blocks is allowed bool isPartialBlockWriteAllowed: 1; /// Reserved 5 bits UInt8 reserved4: 5; /// File format group UInt8 fileFormatGroup: 1; /// Copy flag UInt8 copyFlag: 1; /// Permanent write protection bool permanentWriteProtection: 1; /// Temporary write protection bool temporaryWriteProtection: 1; /// File format UInt8 fileFormat: 2; /// Reserved 2 bits UInt8 reserved5: 2; /// CRC7 checksum and the end bit UInt8 end; }; /// Card specific data (Version 3.0) (16 bytes) struct PACKED CSDV3 { // =============== // | Common | // =============== /// The structure version UInt8 version: 2; /// Reserved 6 bits UInt8 reserved0: 6; /// Data read access time - 1 (Reserved 1 bit) UInt8 reserved1: 1; /// Data read access time - 1 (Time value) UInt8 taacTimeValue: 4; /// Data read access time - 1 (Time unit) UInt8 taacTimeUnit: 3; /// Data read access time - 2 in clock cycles UInt8 nasc; /// Maximum data transfer rate (Reserved 1 bit) UInt8 reservedDTR: 1; /// Maximum data transfer rate (Transfer rate value) UInt8 maxTransferRateValue: 4; /// Maximum data transfer rate (Transfer rate unit) UInt8 maxTransferRateUnit: 3; /// Card command classes UInt16 cardCommandClasses: 12; /// Maximum read data block length UInt16 maxReadDataBlockLength: 4; /// `True` if reading partial blocks is allowed bool isPartialBlockReadAllowed: 1; /// Write block misalignment UInt8 writeBlockMisalignment: 1; /// Read block misalignment UInt8 readBlockMisalignment: 1; /// `True` if DSR is implemented bool isDSRImplemented: 1; // =============== // | V3 Specific | // =============== /// Device size UInt32 deviceSize: 28; /// Reserved 1 bit UInt8 reserved2: 1; // =============== // | Common | // =============== /// `True` if erasing a single block is enabled bool isEraseSingleBlockEnabled: 1; /// Erase sector size UInt8 eraseSectorSize: 7; /// Write protect group size UInt8 writeProtectGroupSize: 7; /// `True` if write protect group is enabled bool isWriteProtectGroupEnabled: 1; /// Reserved 2 bits UInt8 reserved3: 2; /// Write speed factor UInt8 writeSpeedFactor: 3; /// Maximum write data block length UInt8 maxWriteDataBlockLength: 4; /// `True` if writing partial blocks is allowed bool isPartialBlockWriteAllowed: 1; /// Reserved 5 bits UInt8 reserved4: 5; /// File format group UInt8 fileFormatGroup: 1; /// Copy flag UInt8 copyFlag: 1; /// Permanent write protection bool permanentWriteProtection: 1; /// Temporary write protection bool temporaryWriteProtection: 1; /// File format UInt8 fileFormat: 2; /// Reserved 2 bits UInt8 reserved5: 2; /// CRC7 checksum and the end bit UInt8 end; }; /// Card specific data (Raw Data) union CSDVX { UInt8 data[16]; CSDV1 v1; CSDV2 v2; CSDV3 v3; }; /// Card specific data (Parsed Data) struct CSD { /// CSD struct version enum Version { k1 = 0, k2 = 1, k3 = 2, }; /// Data read access time in nanoseconds UInt32 taacTimeNanosecs; /// Data read access time in number of clocks UInt32 taacTimeClocks; /// Card command classes UInt32 cardCommandClasses; /// Enumerate all SD command classes enum CommandClass { /// Class 0: Basic protocol functions /// CMD0, 1, 2, 3, 4, 7, 9, 10, 12, 13, 15 kBasic = 1 << 0, /// Class 1: Stream read commands /// CMD11 kStreamRead = 1 << 1, /// Class 2: Block read commands /// CMD16, 17, 18 kBlockRead = 1 << 2, /// Class 3: Stream write commands /// CMD20 kStreamWrite = 1 << 3, /// Class 4: Block write commands /// CMD16, 24, 25, 26, 27 kBlockWrite = 1 << 4, /// Class 5: Ability to erase blocks /// CMD32, 33, 34, 35, 36, 37, 38, 39 kErase = 1 << 5, /// Class 6: Ability to write protect blocks /// CMD28, 29, 30 kWriteProtect = 1 << 6, /// Class 7: Ability to lock down the card /// CMD16, 42 kLockCard = 1 << 7, /// Class 8: Application specific commands /// CMD55, 56, 57, ACMD* kAppSpecific = 1 << 8, /// Class 9: SD I/O mode /// CMD5, 39, 40, 52, 53 kIOMode = 1 << 9, /// Class 10: High Speed Switch /// CMD6, 11, 34, 35, 36, 37, 50 kSwitch = 1 << 10, }; /// Maximum data transfer rate (in bps or Hz) UInt32 maxDataTransferRate; /// Card capacity (in number of read blocks) UInt32 capacity; /// Read block length is 2^ReadBlockLength UInt32 readBlockLength; /// Write block length UInt32 writeBlockLength; /// Write speed factor UInt32 writeSpeedFactor; /// Erase size in number of sectors UInt32 eraseSize; /// Device size UInt32 deviceSize; /// True if reading a partial block is allowed bool canReadPartialBlock; /// True if reading a block that spreads over more than one physical block is allowed bool canReadMisalignedBlock; /// True if writing a partial is allowed bool canWritePartialBlock; /// True if writing a block that spreads over more than one physical block is allowed bool canWriteMisalignedBlock; /// True if the driver stage register is implemented bool isDSRImplemented; /// `True` if the card is block-addressed (SDHC/SDXC) /// @note This field is derived from the CSD struct version. bool isBlockAddressed; /// `True` if the card has extended capacity (SDXC) /// @note This field is derived from the device size. bool hasExtendedCapacity; /// Data access time (TAAC): Time unit in nanoseconds static constexpr UInt32 kTAACTimeUnits[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, }; /// Data access time (TAAC): Time value multipliers (scaled to 10x) static constexpr UInt32 kTAACTimeValues[] = { 00, 10, 12, 13, 15, 20, 25, 30, // 1.0 - 3.0x 35, 40, 45, 50, 55, 60, 70, 80, // 3.5 - 8.0x }; /// Maximum data transfer rate (DTR): Rate unit (scaled to 1/10x) static constexpr UInt32 kDTRUnits[] = { 10000, // 100 Kbps 100000, // 1 Mbps 1000000, // 10 Mbps 10000000, // 100 Mbps 0, 0, 0, 0, }; /// Maximum data transfer rate (DTR): Rate multiplier (scaled to 10x) static constexpr UInt32 kDTRValues[] = { 00, 10, 12, 13, 15, 20, 25, 30, // 1.0 - 3.0x 35, 40, 45, 50, 55, 60, 70, 80, // 3.5 - 8.0x }; /// /// Decode from the given raw data /// /// @param data An array of 4 integers encoded in big endian /// @param pcsd The parsed card specific data on return /// @return `true` on success, `false` otherwise. /// static bool decode(const UInt32* data, CSD& pcsd) { UInt32 version = UNSTUFF_BITS(data, 126, 2); UInt32 unit, value; switch (version) { // SDSC cards case CSD::Version::k1: { pcsd.isBlockAddressed = false; pcsd.hasExtendedCapacity = false; value = UNSTUFF_BITS(data, 115, 4); unit = UNSTUFF_BITS(data, 112, 3); pcsd.taacTimeNanosecs = (kTAACTimeUnits[unit] * kTAACTimeValues[value] + 9) / 10; pcsd.taacTimeClocks = UNSTUFF_BITS(data, 104, 8) * 100; value = UNSTUFF_BITS(data, 99, 4); unit = UNSTUFF_BITS(data, 96, 3); pcsd.maxDataTransferRate = kDTRUnits[unit] * kDTRValues[value]; pcsd.cardCommandClasses = UNSTUFF_BITS(data, 84, 12); pcsd.capacity = (1 + UNSTUFF_BITS(data, 62, 12)) << (UNSTUFF_BITS(data, 47, 3) + 2); pcsd.readBlockLength = UNSTUFF_BITS(data, 80, 4); pcsd.canReadPartialBlock = UNSTUFF_BITS(data, 79, 1); pcsd.canWriteMisalignedBlock = UNSTUFF_BITS(data, 78, 1); pcsd.canReadMisalignedBlock = UNSTUFF_BITS(data, 77, 1); pcsd.isDSRImplemented = UNSTUFF_BITS(data, 76, 1); pcsd.writeSpeedFactor = UNSTUFF_BITS(data, 26, 3); pcsd.writeBlockLength = UNSTUFF_BITS(data, 22, 4); pcsd.canWritePartialBlock = UNSTUFF_BITS(data, 21, 1); if (UNSTUFF_BITS(data, 46, 1)) { pcsd.eraseSize = 1; } else if (pcsd.writeBlockLength >= 9) { pcsd.eraseSize = UNSTUFF_BITS(data, 39, 7) + 1; pcsd.eraseSize <<= (pcsd.writeBlockLength - 9); } break; } // SDHC / SDXC cards case CSD::Version::k2: { pcsd.isBlockAddressed = true; pcsd.taacTimeNanosecs = 0; pcsd.taacTimeClocks = 0; value = UNSTUFF_BITS(data, 99, 4); unit = UNSTUFF_BITS(data, 96, 3); pcsd.maxDataTransferRate = kDTRUnits[unit] * kDTRValues[value]; pcsd.cardCommandClasses = UNSTUFF_BITS(data, 84, 12); pcsd.deviceSize = UNSTUFF_BITS(data, 48, 22); pcsd.hasExtendedCapacity = pcsd.deviceSize >= 0xFFFF; pcsd.capacity = (1 + pcsd.deviceSize) << 10; pcsd.readBlockLength = 9; pcsd.canReadPartialBlock = false; pcsd.canWriteMisalignedBlock = false; pcsd.canReadMisalignedBlock = false; pcsd.writeSpeedFactor = 4; // Unused pcsd.writeBlockLength = 9; pcsd.canWritePartialBlock = false; pcsd.eraseSize = 1; break; } case CSD::Version::k3: { perr("SDUC card is not supported at this moment."); return false; } default: { perr("Unrecognized CSD structure version %d.", version); return false; } } return true; } }; static_assert(sizeof(CSDVX) == 16, "CSD X.0 should be 16 bytes long."); static_assert(sizeof(CSDV1) == 16, "CSD 1.0 should be 16 bytes long."); static_assert(sizeof(CSDV2) == 16, "CSD 2.0 should be 16 bytes long."); static_assert(sizeof(CSDV3) == 16, "CSD 3.0 should be 16 bytes long."); #endif /* IOSDCard_CSD_hpp */ <|start_filename|>RealtekCardReader/RealtekRTS5287Controller.cpp<|end_filename|> // // RealtekRTS5287Controller.cpp // RealtekCardReader // // Created by FireWolf on 6/20/21. // #include "RealtekRTS5287Controller.hpp" // // MARK: - Meta Class Definitions // OSDefineMetaClassAndStructors(RealtekRTS5287Controller, RealtekRTS8411SeriesController); // // MARK: - SD Pull Control Tables // /// A sequence of registers to transfer to enable SD pull control (QFN48) const RealtekRTS5287Controller::ChipRegValuePair RealtekRTS5287Controller::kSDEnablePullControlTablePairsQFN48[] = { { RTSX::PCR::Chip::CARD::PULL::rCTL2, 0xAA }, { RTSX::PCR::Chip::CARD::PULL::rCTL3, 0x69 | 0x90 }, { RTSX::PCR::Chip::CARD::PULL::rCTL6, 0x08 | 0x11 }, }; const RealtekRTS5287Controller::SimpleRegValuePairs RealtekRTS5287Controller::kSDEnablePullControlTableQFN48 = { RealtekRTS5287Controller::kSDEnablePullControlTablePairsQFN48 }; /// A sequence of registers to transfer to disable SD pull control (QFN48) const RealtekRTS5287Controller::ChipRegValuePair RealtekRTS5287Controller::kSDDisablePullControlTablePairsQFN48[] = { { RTSX::PCR::Chip::CARD::PULL::rCTL2, 0x55 }, { RTSX::PCR::Chip::CARD::PULL::rCTL3, 0x65 | 0x90 }, { RTSX::PCR::Chip::CARD::PULL::rCTL6, 0x04 | 0x11 }, }; const RealtekRTS5287Controller::SimpleRegValuePairs RealtekRTS5287Controller::kSDDisablePullControlTableQFN48 = { RealtekRTS5287Controller::kSDDisablePullControlTablePairsQFN48 }; /// A sequence of registers to transfer to enable SD pull control (QFN64) const RealtekRTS5287Controller::ChipRegValuePair RealtekRTS5287Controller::kSDEnablePullControlTablePairsQFN64[] = { { RTSX::PCR::Chip::CARD::PULL::rCTL1, 0xAA }, { RTSX::PCR::Chip::CARD::PULL::rCTL2, 0xAA }, { RTSX::PCR::Chip::CARD::PULL::rCTL3, 0x09 | 0xD0 }, { RTSX::PCR::Chip::CARD::PULL::rCTL4, 0x09 | 0x50 }, { RTSX::PCR::Chip::CARD::PULL::rCTL5, 0x05 | 0x50 }, { RTSX::PCR::Chip::CARD::PULL::rCTL6, 0x04 | 0x11 }, }; const RealtekRTS5287Controller::SimpleRegValuePairs RealtekRTS5287Controller::kSDEnablePullControlTableQFN64 = { RealtekRTS5287Controller::kSDEnablePullControlTablePairsQFN64 }; /// A sequence of registers to transfer to disable SD pull control (QFN64) const RealtekRTS5287Controller::ChipRegValuePair RealtekRTS5287Controller::kSDDisablePullControlTablePairsQFN64[] = { { RTSX::PCR::Chip::CARD::PULL::rCTL1, 0x65 }, { RTSX::PCR::Chip::CARD::PULL::rCTL2, 0x55 }, { RTSX::PCR::Chip::CARD::PULL::rCTL3, 0x05 | 0xD0 }, { RTSX::PCR::Chip::CARD::PULL::rCTL4, 0x09 | 0x50 }, { RTSX::PCR::Chip::CARD::PULL::rCTL5, 0x05 | 0x50 }, { RTSX::PCR::Chip::CARD::PULL::rCTL6, 0x04 | 0x11 }, }; const RealtekRTS5287Controller::SimpleRegValuePairs RealtekRTS5287Controller::kSDDisablePullControlTableQFN64 = { RealtekRTS5287Controller::kSDDisablePullControlTablePairsQFN64 }; // // MARK: - Hardware Initialization and Configuration // /// /// Check whether the package mode is QFN48 /// /// @param result Set to `true` if the package mode is QFN48 on return /// @return `kIOReturnSuccess` on success, other values if failed to read the register. /// IOReturn RealtekRTS5287Controller::isQFN48(bool& result) { UInt8 mode; IOReturn retVal = this->readChipRegister(RTSX::PCR::Chip::rPKGMODE, mode); if (retVal != kIOReturnSuccess) { perr("Failed to read the package mode. Error = 0x%x.", retVal); return retVal; } result = (mode & 0x02) == 0x02; return kIOReturnSuccess; } /// /// Initialize hardware-specific parameters /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `*_init_params()` defined in each controller file. /// @note Port: This function replaces `rtl8411_init_common_params()` defined in `rts8411.c`. /// Concrete controllers must override and extend this function to set the pull control tables. /// IOReturn RealtekRTS5287Controller::initParameters() { IOReturn retVal = super::initParameters(); if (retVal != kIOReturnSuccess) { perr("Failed to fetch the common device-specific parameters. Error = 0x%x.", retVal); return retVal; } bool result = false; retVal = this->isQFN48(result); if (retVal != kIOReturnSuccess) { perr("Failed to check whether the package mode is QFN48. Error = 0x%x.", retVal); return retVal; } if (result) { this->parameters.sdEnablePullControlTable = &RealtekRTS5287Controller::kSDEnablePullControlTableQFN48; this->parameters.sdDisablePullControlTable = &RealtekRTS5287Controller::kSDDisablePullControlTableQFN48; } else { this->parameters.sdEnablePullControlTable = &RealtekRTS5287Controller::kSDEnablePullControlTableQFN64; this->parameters.sdDisablePullControlTable = &RealtekRTS5287Controller::kSDDisablePullControlTableQFN64; } return kIOReturnSuccess; } /// /// Initialize vendor-specific parameters /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `fetch_vendor_settings()` defined in the `pcr->ops`. /// @note Port: This function replaces `rtl8411_fetch_vendor_settings()` defined in `rts8411.c`. /// RTS5287 controller must override this function. /// IOReturn RealtekRTS5287Controller::initVendorSpecificParameters() { pinfo("Initializing the vendor-specific parameters..."); // PCR Config 1 UInt32 regVal = this->device->configRead32(RTSX::PCR::kSREG1); pinfo("PCR Config 1 = 0x%08x.", regVal); if (!this->vsIsRegisterValueValid(regVal)) { perr("Vendor settings are invalid."); return kIOReturnError; } this->parameters.pm.isASPML1Enabled = this->vsIsASPML1Enabled(regVal); this->parameters.sd30DriveSelector1d8V = this->vsMapDriveSelector(this->vsGetSD30DriveSelector1d8V(regVal)); this->parameters.sd30DriveSelector3d3V = this->vsMapDriveSelector(this->vsGetSD30DriveSelector3d3V(regVal)); pinfo("PCR CFG1: RegVal = 0x%08x.", regVal); pinfo("PCR CFG1: ASPM L1 Enabled: %s.", YESNO(this->parameters.pm.isASPML1Enabled)); pinfo("PCR CFG1: SD30 Drive Selector (1.8V) = %d.", this->parameters.sd30DriveSelector1d8V); pinfo("PCR CFG1: SD30 Drive Selector (3.3V) = %d.", this->parameters.sd30DriveSelector3d3V); pinfo("Vendor-specific parameters have been initialized."); return kIOReturnSuccess; } /// /// Initialize the hardware (Extra Part) /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `extra_init_hw()` defined in defined in the `pcr->ops`. /// @note Port: This function replaces `rtl8411_extra_init_hw()` defined in `rts8411.c`. /// RTS5287 controller must override this function. /// IOReturn RealtekRTS5287Controller::initHardwareExtra() { using namespace RTSX::PCR::Chip; const ChipRegValuePair pairs[] = { // QFN48 only { CARD::PULL::rCTL3, 0xFF, 0xF5 }, // Set the initial driving selector { CARD::SD30::DRVSEL::rCFG, 0xFF, this->parameters.sd30DriveSelector3d3V }, // Enable the card { CARD::rPADCTL, CARD::PADCTL::kDisableMask | CARD::PADCTL::kAutoDisable, CARD::PADCTL::kEnableAll }, // ??? { rFCTL, 0x06, 0x00 } }; bool result = false; IOReturn retVal = this->isQFN48(result); if (retVal != kIOReturnSuccess) { perr("Failed to check whether the package mode is QFN48. Error = 0x%x.", retVal); return retVal; } if (result) { return this->transferWriteRegisterCommands(SimpleRegValuePairs(pairs)); } else { return this->transferWriteRegisterCommands(SimpleRegValuePairs(pairs + 1, arrsize(pairs) - 1)); } } <|start_filename|>RealtekCardReader/Utilities.hpp<|end_filename|> // // Utilities.hpp // RealtekCardReader // // Created by FireWolf on 2/27/21. // #ifndef Utilities_hpp #define Utilities_hpp #include <IOKit/pci/IOPCIDevice.h> #include "Debug.hpp" // // MARK: - Attributes // /** * Export function or symbol for linking */ #define EXPORT __attribute__((visibility("default"))) /** * Ensure the symbol is not exported */ #define PRIVATE __attribute__((visibility("hidden"))) /** * For private fallback symbol definition */ #define WEAKFUNC __attribute__((weak)) /** * Remove padding between fields */ #define PACKED __attribute__((packed)) /** * Deprecate the interface */ #define DEPRECATE(x) __attribute__((deprecated(x))) /** * Non-null argument */ #define NONNULL __attribute__((nonnull)) /** * Compiler hints regarding branching * (Until Apple's Clang supports C++20's [[unlikely]] and [[likely]] attributes) */ #define LIKELY(x) __builtin_expect(!!(x), 1) #define UNLIKELY(x) __builtin_expect(!!(x), 0) // // MARK: - Convenient Helpers // static constexpr IOPMPowerFlags kIOPMPowerOff = 0; /// Kernel major version extern const int version_major; /// Kernel minor version extern const int version_minor; /// Kernel revision extern const int version_revision; /// Get the number of elements in an array template <typename T, size_t N> constexpr size_t arrsize(const T (&array)[N]) { return N; } template <typename InputIterator, typename Action> void forEach(InputIterator begin, InputIterator end, Action action) { for (InputIterator current = begin; current != end; current++) { action(*current); } } template <typename InputIterator, typename Action, typename Result> Result forEachUntil(InputIterator begin, InputIterator end, Action action, Result expected) { for (InputIterator current = begin; current != end; current++) { Result result = action(*current); if (result != expected) { return result; } } return expected; } template <typename T1, typename T2> struct Pair { T1 first; T2 second; Pair(T1 first, T2 second) : first(first), second(second) {} }; template <typename T1, typename T2, typename T3> struct Triplet { T1 first; T2 second; T3 third; Triplet(T1 first, T2 second, T3 third) : first(first), second(second), third(third) {} }; #define KPTR(ptr) \ static_cast<UInt32>(reinterpret_cast<UInt64>(ptr) >> 32), \ static_cast<UInt32>(reinterpret_cast<UInt64>(ptr)) template <typename T> constexpr T MHz2Hz(T mhz) { return mhz * 1000000; } template <typename T> constexpr T KHz2Hz(T khz) { return khz * 1000; } template <typename T> constexpr T Hz2MHz(T hz) { return hz / 1000000; } namespace Value { template <typename T> struct Value { T value; explicit Value(T value) : value(value) {} template<typename... Ts> bool isOneOf(Ts... args) { return ((this->value == args) || ...); } template <typename... Ts> bool isNotOneOf(Ts... args) { return ((this->value != args) && ...); } }; template <typename T> static Value<T> of(T value) { return Value<T>(value); } } /// A simplified version of c++17 std::optional<T> /// T must be default constructable template <typename T> struct Optional { T value; bool exists; Optional(const T& value) : value(value), exists(true) {} Optional() : value(), exists(false) {} inline bool hasValue() { return this->exists; } T* operator->() { return &this->value; } T& operator*() { return this->value; } static Optional<T> nullopt() { return Optional<T>(); } }; namespace BootArgs { static inline bool contains(const char* name) { int dummy = 0; return PE_parse_boot_argn(name, &dummy, sizeof(dummy)); } template <typename T> Optional<T> get(const char* name) { T value; if (PE_parse_boot_argn(name, &value, sizeof(T))) { return Optional<T>(value); } else { return Optional<T>::nullopt(); } } template <typename T> T get(const char* name, T fallback) { T value = {}; return PE_parse_boot_argn(name, &value, sizeof(T)) ? value : fallback; } } /// Align the given numeric value to the next `boundary` bytes boundary template <typename T> T align(T value, T boundary) { T mask = boundary - 1; return (value + mask) & (~mask); } static inline const char* YESNO(bool value) { return value ? "Yes" : "No"; } /* * Find Last Set bit */ static inline int myfls(int mask) { #if __has_builtin(__builtin_fls) return __builtin_fls(mask); #elif __has_builtin(__builtin_clz) if(mask == 0) return (0); return (sizeof(mask) << 3) - __builtin_clz(mask); #else int bit; if(mask == 0) return (0); for(bit = 1; mask != 1; bit++) mask = (unsigned)mask >> 1; return (bit); #endif } // Linux #define UNSTUFF_BITS(resp,start,size) \ ({ \ const int __size = size; \ const UInt32 __mask = (__size < 32 ? 1 << __size : 0) - 1; \ const int __off = 3 - ((start) / 32); \ const int __shft = (start) & 31; \ UInt32 __res; \ \ __res = resp[__off] >> __shft; \ if (__size + __shft > 32) \ __res |= resp[__off-1] << ((32 - __shft) % 32); \ __res & __mask; \ }) #endif /* Utilities_hpp */ <|start_filename|>RealtekCardReader/IOSDHostDriver.cpp<|end_filename|> // // IOSDHostDriver.cpp // RealtekCardReader // // Created by FireWolf on 6/1/21. // #include "IOSDHostDriver.hpp" #include "BitOptions.hpp" #include "Debug.hpp" #include "IOSDBlockStorageDevice.hpp" #include "IOMemoryDescriptor.hpp" #include "IOSDHostDriverUserConfigs.hpp" #include "IOCommandGate.hpp" #include <IOKit/storage/IOBlockStorageDriver.h> // // MARK: - Meta Class Definitions // OSDefineMetaClassAndStructors(IOSDHostDriver, IOService); // // MARK: - Submit Block I/O Requests // /// /// Submit the given request to the queue /// /// @param processor The processor that services the request /// @param buffer The data transfer buffer /// @param block The starting block number /// @param nblocks The number of blocks to transfer /// @param attributes Attributes of the data transfer /// @param completion The completion routine to call once the data transfer completes /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDHostDriver::submitBlockRequest(IOSDBlockRequest::Processor processor, IOMemoryDescriptor* buffer, UInt64 block, UInt64 nblocks, IOStorageAttributes* attributes, IOStorageCompletion* completion) { pinfo("BREQ: Start Block Index = %llu; Number of Blocks = %llu; Number of Bytes = %llu.", block, nblocks, nblocks * 512); psoftassert(buffer->getLength() == nblocks * 512, "Buffer lengths mismatched."); // Guard: Ensure that the queue event source is still enabled // It is enabled if and only if the card is not ejected or removed. if (!this->queueEventSource->isEnabled()) { perr("The queue event source is disabled."); return kIOReturnNoMedia; } // Guard: The maximum number of blocks in one request is 1024 (for example) // Split the incoming request into multiple smaller one if necessary IOSDBlockRequest* request = nullptr; if (nblocks <= this->host->getDMALimits().maxRequestNumBlocks()) { request = this->simpleBlockRequestPool->getCommand(); } else { request = this->complexBlockRequestPool->getCommand(); } passert(request != nullptr, "The block request should not be null at this moment."); request->init(this, processor, buffer, block, nblocks, attributes, completion); // It is possible that the user removes the card just before the host driver enqueues the request and signals the processor workloop. // In this case, the card removal handler has already disabled the queue event source. // Here the host driver notifies the processor workloop that a block request is pending, // and the workloop will invoke `IOSDBlockRequestEventSource::checkForWork()`. // Since the event source is disabled, it will not process this request. // The request remains in the queue, but the host driver will recycle it when a new card is inserted. // See `IOSDHostDriver::attachCard(frequency:)` for details. this->pendingRequests->enqueueRequest(request); this->queueEventSource->notify(); return kIOReturnSuccess; } // // MARK: - Process Block I/O Requests // /// /// [Helper] Transform the given starting block number to the argument of CMD17/18/24/25 if necessary /// /// @param block The starting block number /// @return The argument to be passed to CMD17/18/24/25. /// i.e. The given block number if the card is block addressed (SDHC/XC), /// or the corresponding byte offset if the card is byte addressed (SDSC). /// UInt32 IOSDHostDriver::transformBlockOffsetIfNecessary(UInt64 block) { // SDXC supports up to 2TB passert(block <= UINT32_MAX, "The maximum capacity supported is 2TB."); // This function is invoked by the processor workloop (i.e. the queue event source), // so the instance variable `card` is guaranteed to be non-null. // 1) It is possible that the user removes the SD card while the workloop is processing this request, // but the card will be released and set to NULL only after the workloop finishes this request. // 2) If the user removes the SD card before the workloop starts to process this request, // the queue event source is disabled, so we should never reach at here. passert(this->card != nullptr, "The card should be non-null at this moment."); if (!this->card->getCSD().isBlockAddressed) { block <<= 9; pinfo("The card is byte addressed. Adjusted argument = %llu.", block); } return static_cast<UInt32>(block); } /// /// Process the given request to read a single block /// /// @param request A non-null block request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The return value will be passed to the storage completion routine. /// @note When this function is invoked, the memory descriptor is guaranteed to be non-null and prepared. /// IOReturn IOSDHostDriver::processReadBlockRequest(IOSDBlockRequest* request) { pinfo("Processing the request that reads a single block..."); auto creq = this->host->getRequestFactory().CMD17(this->transformBlockOffsetIfNecessary(request->getBlockOffset()), request->getMemoryDescriptor()); return this->waitForRequest(creq); } /// /// Process the given request to read multiple blocks /// /// @param request A non-null block request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The return value will be passed to the storage completion routine. /// @note When this function is invoked, the memory descriptor is guaranteed to be non-null and prepared. /// IOReturn IOSDHostDriver::processReadBlocksRequest(IOSDBlockRequest* request) { // Guard: Check if the driver should separate the incoming request if (UNLIKELY(UserConfigs::Card::SeparateAccessBlocksRequest)) { pinfo("User requests to separate the CMD18 request into multiple CMD17 ones."); return this->processReadBlocksRequestSeparately(request); } pinfo("Processing the request that reads multiple blocks..."); auto creq = this->host->getRequestFactory().CMD18(this->transformBlockOffsetIfNecessary(request->getBlockOffset()), request->getMemoryDescriptor(), request->getNumBlocks()); return this->waitForRequest(creq); } /// /// Process the given request to read multiple blocks separately /// /// @param request A non-null block request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The return value will be passed to the storage completion routine. /// @note When this function is invoked, the memory descriptor is guaranteed to be non-null and prepared. /// @note This function separates a CMD18 request into multiple CMD17 ones. /// IOReturn IOSDHostDriver::processReadBlocksRequestSeparately(IOSDBlockRequest* request) { pinfo("Processing the request that reads multiple blocks separately..."); auto builder = [&](UInt32 offset, IOMemoryDescriptor* data) -> IOSDSingleBlockRequest { return this->host->getRequestFactory().CMD17(offset, data); }; return this->processAccessBlocksRequestSeparately(request, builder); } /// /// Process the given request to write a single block /// /// @param request A non-null block request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The return value will be passed to the storage completion routine. /// @note When this function is invoked, the memory descriptor is guaranteed to be non-null and prepared. /// IOReturn IOSDHostDriver::processWriteBlockRequest(IOSDBlockRequest* request) { pinfo("Processing the request that writes a single block..."); auto creq = this->host->getRequestFactory().CMD24(this->transformBlockOffsetIfNecessary(request->getBlockOffset()), request->getMemoryDescriptor()); return this->waitForRequest(creq); } /// /// Process the given request to write multiple blocks /// /// @param request A non-null block request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The return value will be passed to the storage completion routine. /// @note When this function is invoked, the memory descriptor is guaranteed to be non-null and prepared. /// IOReturn IOSDHostDriver::processWriteBlocksRequest(IOSDBlockRequest* request) { // Guard: Check if the driver should separate the incoming request if (UNLIKELY(UserConfigs::Card::SeparateAccessBlocksRequest)) { pinfo("User requests to separate the CMD25 request into multiple CMD24 ones."); return this->processWriteBlocksRequestSeparately(request); } // Guard: Check if the driver should issue the ACMD23 for the incoming request if (LIKELY(!UserConfigs::Card::NoACMD23)) { // Issue the ACMD23 to set the number of pre-erased blocks pinfo("Issuing an ACMD23 to set the number of pre-erased blocks..."); passert(request->getNumBlocks() <= ((1 << 23) - 1), "The number of blocks should be less than 2^23 - 1."); auto preq = this->host->getRequestFactory().ACMD23(static_cast<UInt32>(request->getNumBlocks())); IOReturn retVal = this->waitForAppRequest(preq, this->card->getRCA()); if (retVal != kIOReturnSuccess) { perr("Failed to issue the ACMD23 to set the number of pre-erased blocks. Error = 0x%x.", retVal); return retVal; } pinfo("The ACMD23 has been issued."); } else { pinfo("User requests not to issue the ACMD23 before the CMD25."); } // Process the block request pinfo("Processing the request that writes multiple blocks..."); auto creq = this->host->getRequestFactory().CMD25(this->transformBlockOffsetIfNecessary(request->getBlockOffset()), request->getMemoryDescriptor(), request->getNumBlocks()); return this->waitForRequest(creq); } /// /// Process the given request to write multiple blocks separately /// /// @param request A non-null block request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The return value will be passed to the storage completion routine. /// @note When this function is invoked, the memory descriptor is guaranteed to be non-null and prepared. /// @note This function separates a CMD25 request into multiple CMD24 ones. /// IOReturn IOSDHostDriver::processWriteBlocksRequestSeparately(IOSDBlockRequest* request) { pinfo("Processing the request that writes multiple blocks separately..."); auto builder = [&](UInt32 offset, IOMemoryDescriptor* data) -> IOSDSingleBlockRequest { return this->host->getRequestFactory().CMD24(offset, data); }; return this->processAccessBlocksRequestSeparately(request, builder); } /// /// Finalize a request that has been processed /// /// @param request A non-null block request /// @note This function is the completion routine registered with the block request event source. /// It deinitializes the given request and puts it back to the block request pool. /// void IOSDHostDriver::finalizeBlockRequest(IOSDBlockRequest* request) { pinfo("The given request has been processed."); request->deinit(); this->releaseBlockRequestToPool(request); } // // MARK: - Query Host Properties // /// /// Check whether the host supports the High Speed mode /// /// @return `true` if the High Speed mode is supported by the host. /// bool IOSDHostDriver::hostSupportsHighSpeedMode() { return this->host->getCapabilities().contains(IOSDHostDevice::Capability::kSDHighSpeed); } /// /// Check whether the host supports the Ultra High Speed mode /// /// @return `true` if the Ultra High Speed mode is supported by the host. /// bool IOSDHostDriver::hostSupportsUltraHighSpeedMode() { auto caps = this->host->getCapabilities(); bool s4b = caps.contains(IOSDHostDevice::Capability::k4BitData); bool uhs = caps.containsOneOf(IOSDHostDevice::Capability::kUHSSDR12, IOSDHostDevice::Capability::kUHSSDR25, IOSDHostDevice::Capability::kUHSSDR50, IOSDHostDevice::Capability::kUHSSDR104, IOSDHostDevice::Capability::kUHSDDR50); return s4b && uhs; } /// /// Check whether the host supports the 4-bit bus width /// /// @return `true` if the 4-bit bus width is supported by the host. /// bool IOSDHostDriver::hostSupports4BitBusWidth() { return this->host->getCapabilities().contains(IOSDHostDevice::Capability::k4BitData); } /// /// Get the maximum current setting at its current voltage /// /// @return The maximum current in mA. /// @note Port: This function replaces `sd_get_host_max_current()` defined in `sd.c`. /// UInt32 IOSDHostDriver::getHostMaxCurrent() { IOSDHostDevice::MaxCurrents maxCurrents = this->host->getHostMaxCurrents(); const IOSDBusConfig& config = this->host->getHostBusConfig(); UInt32 maxCurrent = 0; switch (1 << config.vdd) { case IOSDBusConfig::VDD::k165_195: { maxCurrent = maxCurrents.v18; break; } case IOSDBusConfig::VDD::k29_30: case IOSDBusConfig::VDD::k30_31: { maxCurrent = maxCurrents.v30; break; } case IOSDBusConfig::VDD::k32_33: case IOSDBusConfig::VDD::k33_34: { maxCurrent = maxCurrents.v33; break; } default: { perr("Unsupported host signal voltage level."); break; } } return maxCurrent; } /// /// Select voltage levels mutually supported by the host and the card /// /// @param ocr The card OCR value /// @return The OCR value that contains voltage levels supported by both parties. /// @note Port: This function replaces `mmc_select_voltage()` defined in `core.c`. /// UInt32 IOSDHostDriver::selectMutualVoltageLevels(UInt32 ocr) { pinfo("Selecting voltage levels that are supported by both sides..."); // Sanitize the card OCR value // The low 7 bits should be zero if ((ocr & 0x7F) != 0) { pwarning("The card OCR value 0x%08x reports to support undefined voltage levels.", ocr); ocr &= ~0x7F; } pinfo("[OCR] Card = 0x%08x.", ocr); // Filter out voltage levels unsupported by both sides ocr &= this->host->getHostSupportedVoltageRanges(); pinfo("[OCR] Both = 0x%08x.", ocr); if (ocr == 0) { pwarning("No voltage levels supported by the host and the card."); return 0; } if (this->host->getCapabilities().contains(IOSDHostDevice::Capability::kFullPowerCycle)) { pinfo("The host device supports a full power cycle."); ocr &= 3 << (ffs(ocr) - 1); pinfo("Restarting the host device with the new OCR value 0x%08x.", ocr); psoftassert(this->powerCycle(ocr) == kIOReturnSuccess, "Failed to restart the power of the card with the new OCR value 0x%08x.", ocr); } else { ocr &= 3 << (myfls(ocr) - 1); psoftassert(myfls(ocr) - 1 == this->host->getHostBusConfig().vdd, "The host voltage supply exceeds the card's supported value."); } pinfo("Selected mutual voltage levels = 0x%x.", ocr); return ocr; } // // MARK: - Adjust Host Bus Settings // /// /// [Shared] Set the bus config /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_ios()` defined in `core.c`. /// IOReturn IOSDHostDriver::setBusConfig() { const IOSDBusConfig& config = this->host->getHostBusConfig(); pinfo("Setting the bus configuration..."); config.print(); return this->host->setBusConfig(config); } /// /// Set the initial bus config /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_initial_state()` defined in `core.c`. /// IOReturn IOSDHostDriver::setInitialBusConfig() { pinfo("Setting the initial bus config..."); IOSDBusConfig& config = this->host->getHostBusConfig(); config.chipSelect = IOSDBusConfig::ChipSelect::kDoNotCare; config.busMode = IOSDBusConfig::BusMode::kPushPull; config.busWidth = IOSDBusConfig::BusWidth::k1Bit; config.busTiming = IOSDBusConfig::BusTiming::kLegacy; config.driverType = IOSDBusConfig::DriverType::kTypeB; return this->setBusConfig(); } /// /// Set the SPI chip select mode /// /// @param chipSelect The target mode /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_chip_select()` defined in `core.c`. /// IOReturn IOSDHostDriver::setChipSelect(IOSDBusConfig::ChipSelect chipSelect) { if (this->host->getCapabilities().contains(IOSDHostDevice::Capability::kOptimizeChipSelect)) { pinfo("Optimization: The host device ignores the chip select mode."); return kIOReturnSuccess; } IOSDBusConfig& config = this->host->getHostBusConfig(); config.chipSelect = chipSelect; return this->setBusConfig(); } /// /// Set the bus speed mode /// /// @param timing The target bus speed mode /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_timing()` defined in `core.c`. /// IOReturn IOSDHostDriver::setBusTiming(IOSDBusConfig::BusTiming timing) { IOSDBusConfig& config = this->host->getHostBusConfig(); config.busTiming = timing; return this->setBusConfig(); } /// /// Set the bus clock /// /// @param clock The target clock frequency in Hz /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_clock()` defined in `core.c`. /// @warning If the given clock frequency is beyond the range of supported clock frequencies, /// this function will adjust the final clock appropriately. /// IOReturn IOSDHostDriver::setBusClock(UInt32 clock) { ClosedRange<UInt32> range = this->host->getHostClockRange(); IOSDBusConfig& config = this->host->getHostBusConfig(); psoftassert(range.contains(clock), "The given clock %u Hz is beyond the range.", clock); config.clock = min(range.upperBound, clock); return this->setBusConfig(); } /// /// Set the bus width /// /// @param width The target bus width /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_bus_width()` defined in `core.c`. /// IOReturn IOSDHostDriver::setBusWidth(IOSDBusConfig::BusWidth width) { IOSDBusConfig& config = this->host->getHostBusConfig(); config.busWidth = width; return this->setBusConfig(); } /// /// Set the signal voltage /// /// @param voltage The target signal voltage /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_signal_voltage()` defined in `core.c`. /// IOReturn IOSDHostDriver::setSignalVoltage(IOSDBusConfig::SignalVoltage voltage) { IOSDBusConfig& config = this->host->getHostBusConfig(); auto oldVoltage = config.signalVoltage; config.signalVoltage = voltage; IOReturn retVal = this->host->switchSignalVoltage(config); if (retVal != kIOReturnSuccess) { perr("Failed to switch to the signal voltage %hhu. Error = 0x%x.", voltage, retVal); config.signalVoltage = oldVoltage; } return retVal; } /// /// Set the initial signal voltage /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_set_initial_signal_voltage()` defined in `core.c`. /// IOReturn IOSDHostDriver::setInitialSignalVoltage() { // Try to set the signal voltage to 3.3V pinfo("Attempt to set the signal voltage to 3.3V."); if (this->setSignalVoltage(IOSDBusConfig::SignalVoltage::k3d3V) == kIOReturnSuccess) { pinfo("The initial signal voltage has been set to 3.3V."); return kIOReturnSuccess; } perr("Failed to set the signal voltage to 3.3V. Will try to set the signal voltage to 1.8V."); if (this->setSignalVoltage(IOSDBusConfig::SignalVoltage::k1d8V) == kIOReturnSuccess) { pinfo("The initial signal voltage has been set to 1.8V."); return kIOReturnSuccess; } perr("Failed to set the signal voltage to 1.8V. Will try to set the signal voltage to 1.2V."); if (this->setSignalVoltage(IOSDBusConfig::SignalVoltage::k1d2V) == kIOReturnSuccess) { pinfo("The initial signal voltage has been set to 1.2V."); return kIOReturnSuccess; } perr("Cannot set the initial signal voltage to one of supported values."); return kIOReturnError; } /// /// Set the signal voltage for the Ultra High Speed mode /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_host_set_uhs_voltage()` defined in `core.c`. /// IOReturn IOSDHostDriver::setUltraHighSpeedSignalVoltage() { // The clock must be gated for 5ms during a signal voltage level switch IOSDBusConfig& config = this->host->getHostBusConfig(); UInt32 clock = config.clock; config.clock = 0; IOReturn retVal = this->setBusConfig(); if (retVal != kIOReturnSuccess) { perr("Failed to gate the clock. Error = 0x%x.", retVal); return retVal; } // Set the signal voltage to 1.8V retVal = this->setSignalVoltage(IOSDBusConfig::SignalVoltage::k1d8V); if (retVal != kIOReturnSuccess) { perr("Failed to switch the signal voltage to 1.8V. Error = 0x%x.", retVal); return retVal; } // Keep the clock gated for at least 10ms IOSleep(10); // Restore the clock config.clock = clock; retVal = this->setBusConfig(); if (retVal != kIOReturnSuccess) { perr("Failed to restore the clock. Error = 0x%x.", retVal); return retVal; } return kIOReturnSuccess; } /// /// Execute the tuning algorithm /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_execute_tuning()` defined in `core.c`. /// IOReturn IOSDHostDriver::executeTuning() { // TODO: RETUNE ENABLE??? return this->host->executeTuning(this->host->getHostBusConfig()); } /// /// Power up the SD stack /// /// @param ocr The OCR value from which to select the VDD value /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_power_up()` defined in `core.c`. /// IOReturn IOSDHostDriver::powerUp(UInt32 ocr) { // Check whether the bus power is already on IOSDBusConfig& config = this->host->getHostBusConfig(); if (config.powerMode == IOSDBusConfig::PowerMode::kPowerOn) { pinfo("The bus power is already on."); return kIOReturnSuccess; } // Power up the bus // Set the initial bus config without the clock running pinfo("Powering up the bus..."); config.vdd = myfls(ocr) - 1; config.powerMode = IOSDBusConfig::PowerMode::kPowerUp; IOReturn retVal = this->setInitialBusConfig(); if (retVal != kIOReturnSuccess) { perr("Failed to set the initial bus state. Error = 0x%x.", retVal); return retVal; } pinfo("The bus power is now up."); // Set the initial signal voltage level pinfo("Setting the initial signal voltage..."); retVal = this->setInitialSignalVoltage(); if (retVal != kIOReturnSuccess) { perr("Failed to set the initial signal voltage level. Error = 0x%x.", retVal); return retVal; } // Wait for a while until the power supply becomes stable IOSleep(config.powerDelay); pinfo("The initial signal voltage has been set."); // Power on the bus with the clock running pinfo("Powering on the bus..."); config.clock = this->host->getHostInitialClock(); config.powerMode = IOSDBusConfig::PowerMode::kPowerOn; retVal = this->setBusConfig(); if (retVal != kIOReturnSuccess) { perr("Failed to power up the bus with the clock running. Error = 0x%x.", retVal); } // Wait for a while until the voltage level becomes stable IOSleep(config.powerDelay); pinfo("The bus power is now on."); return retVal; } /// /// Power off the SD stack /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_power_up()` defined in `core.c`. /// IOReturn IOSDHostDriver::powerOff() { // Check whether the bus power is already off IOSDBusConfig& config = this->host->getHostBusConfig(); if (config.powerMode == IOSDBusConfig::PowerMode::kPowerOff) { pinfo("The bus power is already off."); return kIOReturnSuccess; } pinfo("Powering off the bus..."); config.clock = 0; config.vdd = 0; config.powerMode = IOSDBusConfig::PowerMode::kPowerOff; IOReturn retVal = this->setInitialBusConfig(); if (retVal != kIOReturnSuccess) { perr("Failed to power off the bus. Error = 0x%x.", retVal); } // Some cards require a short delay after powered off before turned on again IOSleep(1); return retVal; } /// /// Reboot the SD stack /// /// @param ocr The OCR value from which to select the VDD value /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_power_cycle()` defined in `core.c`. /// IOReturn IOSDHostDriver::powerCycle(UInt32 ocr) { // Power off the stack IOReturn retVal = this->powerOff(); if (retVal != kIOReturnSuccess) { perr("Failed to power off the stack. Error = 0x%x.", retVal); return retVal; } // Wait at least 1 ms according to the SD specification IOSleep(1); // Power on the stack retVal = this->powerUp(ocr); if (retVal != kIOReturnSuccess) { perr("Failed to power on the stack. Error = 0x%x.", retVal); return retVal; } return kIOReturnSuccess; } // // MARK: - SD Request Center // /// /// [Helper] Send the given SD command request and wait for the response /// /// @param request A SD command request /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDHostDriver::waitForRequest(IOSDHostRequest& request) { pinfo("Preprocessing the request..."); IOReturn retVal = this->host->preprocessRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to preprocess the request. Error = 0x%x.", retVal); return retVal; } pinfo("Processing the request..."); retVal = this->host->processRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to process the request. Error = 0x%x.", retVal); psoftassert(this->host->postprocessRequest(request) == kIOReturnSuccess, "Failed to postprocess the request."); return retVal; } return this->host->postprocessRequest(request); } /// /// [Helper] Send the given SD application command request and wait for the response /// /// @param request A SD application command request /// @param rca The card relative address /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_wait_for_app_cmd()` defined in `sd_ops.c`. /// @note This function issues a CMD55 before sending the given request. /// IOReturn IOSDHostDriver::waitForAppRequest(IOSDHostRequest& request, UInt32 rca) { IOReturn retVal = kIOReturnSuccess; for (int attempt = 0; attempt < UserConfigs::Card::ACMDMaxNumAttempts; attempt += 1) { pinfo("[%02d] Sending the application command...", attempt); // Guard: Send the CMD55 retVal = this->CMD55(rca); if (retVal != kIOReturnSuccess) { perr("Failed to issue a CMD55. Error = 0x%x.", retVal); continue; } // Send the application command retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to issue the application command. Error = 0x%x.", retVal); continue; } pinfo("[%02d] The application command has been sent successfully.", attempt); return kIOReturnSuccess; } perr("Failed to send the application command. Error = 0x%x.", retVal); return retVal; } /// /// CMD0: Reset all cards to the idle state /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_go_idle()` defined in `mmc_ops.c`. /// IOReturn IOSDHostDriver::CMD0() { pinfo("Sending CMD0..."); // Guard: Ensure that chip select is high to prevent the chip entering into the SPI mode pinfo("Setting the chip select to high to prevent the SPI mode..."); IOReturn retVal = this->setChipSelect(IOSDBusConfig::ChipSelect::kHigh); if (retVal != kIOReturnSuccess) { perr("Failed to set the chip select to high. Error = 0x%x.", retVal); return retVal; } IOSleep(1); pinfo("The chip select is now set to high."); // Issue the CMD0 pinfo("Sending CMD0 to the card..."); auto request = this->host->getRequestFactory().CMD0(); retVal = this->waitForRequest(request); IOSleep(1); if (retVal != kIOReturnSuccess) { perr("Failed to issue the CMD0. Error = 0x%x.", retVal); psoftassert(this->setChipSelect(IOSDBusConfig::ChipSelect::kDoNotCare) == kIOReturnSuccess, "Failed to reset the chip select."); return retVal; } pinfo("The card is now in the idle state."); // Reset the chip select value pinfo("Setting the chip select to do-not-care..."); retVal = this->setChipSelect(IOSDBusConfig::ChipSelect::kDoNotCare); if (retVal != kIOReturnSuccess) { perr("Failed to reset the chip select. Error = 0x%x.", retVal); return retVal; } pinfo("CMD0 has been sent."); return kIOReturnSuccess; } /// /// CMD2: Ask any card to send the card identification data /// /// @param buffer A non-null that stores the raw card identification data on return /// @param length Specify the number of bytes read from the card identification data (must not exceed 16 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_cid()` defined in `mmc_ops.c`. /// @note Upon a successful return, the given buffer contains the response data as is. /// The caller is responsible for dealing with the endianness and parsing the data. /// @note It is recommended to use `IOSDHostDriver::CMD2(cid:)` to fetch and parse the data in one function call. /// IOReturn IOSDHostDriver::CMD2(UInt8* buffer, IOByteCount length) { auto request = this->host->getRequestFactory().CMD2(); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to issue the CMD2. Error = 0x%x.", retVal); return retVal; } length = min(sizeof(CID), length); memcpy(buffer, request.command.reinterpretResponseAs<IOSDHostResponse2>()->value, length); return kIOReturnSuccess; } /// /// CMD2: Ask any card to send the card identification data and parse the returned data /// /// @param cid The **parsed** card identification data on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_cid()` defined in `mmc_ops.c`. /// IOReturn IOSDHostDriver::CMD2(CID& cid) { UInt8 buffer[sizeof(CID)] = {}; IOReturn retVal = this->CMD2(buffer); if (retVal != kIOReturnSuccess) { perr("Failed to fetch the raw card identification data. Error = 0x%x.", retVal); return retVal; } // FIXME: Compatibility layer: REMOVE THIS ONCE THE DECODE FUNC IS REWRITTEN // FIXME: The decode function uses Linux's UNSTUFF_BITS macro to extract bits from the response // FIXME: This macro assumes that the data is an array of four UInt32 intergers encoded in big endian UInt32* data = reinterpret_cast<UInt32*>(buffer); for (auto index = 0; index < sizeof(CID) / sizeof(UInt32); index += 1) { data[index] = OSSwapInt32(data[index]); } if (!CID::decode(data, cid)) { perr("Failed to decode the raw card identification data."); return kIOReturnInvalid; } pinfo("Fetched and decoded the card identification data successfully."); return kIOReturnSuccess; } /// /// CMD3: Ask the card to publish its relative address /// /// @param rca The card relative address on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_relative_addr()` defined in `sd_ops.c`. /// IOReturn IOSDHostDriver::CMD3(UInt32& rca) { auto request = this->host->getRequestFactory().CMD3(); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to issue the CMD3. Error = 0x%x.", retVal); return retVal; } rca = request.command.reinterpretResponseAs<IOSDHostResponse6>()->getRCA(); return kIOReturnSuccess; } /// /// CMD6: Check switchable function or switch the card function /// /// @param mode Pass 0 to check switchable function or 1 to switch the card function /// @param group The function group /// @param value The function value /// @param response A non-null buffer that stores the response on return /// @param length Specify the number of bytes read from the response (must not exceed 64 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_sd_switch()` defined in `sd_ops.c`. /// @note This function allocates an internal 64-byte DMA capable buffer to store the response from the card. /// The response is then copied to the given `response` buffer. /// @seealso `IOSDHostDriver::CMD6(mode:group:value:response)` if the caller desires to reuse an existing buffer. /// IOReturn IOSDHostDriver::CMD6(UInt32 mode, UInt32 group, UInt8 value, UInt8* response, IOByteCount length) { // Send the command auto action = [&](IOMemoryDescriptor* descriptor) -> IOReturn { IOReturn retVal = this->CMD6(mode, group, value, descriptor); if (retVal == kIOReturnSuccess) { // Copy the response from the memory descriptor length = min(length, 64); retVal = descriptor->readBytes(0, response, length) == length ? kIOReturnSuccess : kIOReturnError; } return retVal; }; return IOMemoryDescriptorRunActionWithWiredBuffer(64, kIODirectionInOut, action); } /// /// CMD6: Check switchable function or switch the card function /// /// @param mode Pass 0 to check switchable function or 1 to switch the card function /// @param group The function group /// @param value The function value /// @param response A non-null and prepared memory descriptor that stores the response on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_sd_switch()` defined in `sd_ops.c`. /// @note This function uses the given response buffer to initiate a DMA read operation. /// The caller is responsbile for managing the life cycle of the given buffer. /// IOReturn IOSDHostDriver::CMD6(UInt32 mode, UInt32 group, UInt8 value, IOMemoryDescriptor* response) { // Sanitize the given `mode` and `value` pinfo("CMD6: [ORG] Mode = %d; Group = %d; Value = %d.", mode, group, value); mode = !!mode; value &= 0x0F; pinfo("CMD6: [SAN] Mode = %d; Group = %d; Value = %d.", mode, group, value); // Generate the SD command request auto request = this->host->getRequestFactory().CMD6(mode, group, value, response); // TODO: Set the data timeout as Linux??? // TODO: Realtek's driver seems to ignore the data timeout in the mmc_data struct return this->waitForRequest(request); } /// /// CMD7: Select a card /// /// @param rca The relative address of the card to be selected; /// Pass 0 to deselect all cards /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `_mmc_select_card()` defined in `sd_ops.c`. /// IOReturn IOSDHostDriver::CMD7(UInt32 rca) { auto request = this->host->getRequestFactory().CMD7(rca); return this->waitForRequest(request); } /// /// CMD8: Send the interface condition and the voltage supply information /// /// @param vhs The voltage supply information /// @param response The response value on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `__mmc_send_if_cond()` defined in `sd_ops.c`, /// the caller is responsbile for set the VHS value from the OCR register value. /// @seealso `IOSDHostDriver::CMD8(vhs:)` if the response can be ignored. /// IOReturn IOSDHostDriver::CMD8(UInt8 vhs, IOSDHostResponse7& response) { static constexpr UInt8 kCheckPattern = 0xAA; // Guard: Send the command auto request = this->host->getRequestFactory().CMD8(vhs, kCheckPattern); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to issue the CMD8. Error = 0x%x.", retVal); return retVal; } // Guard: Verify the check pattern in the response auto res = request.command.reinterpretResponseAs<IOSDHostResponse7>(); if (res->checkPattern != kCheckPattern) { perr("The check pattern in the response is invalid."); return kIOReturnInvalid; } response = *res; return kIOReturnSuccess; } /// /// CMD9: Ask the card specified by the given relative address to send the card specific data /// /// @param rca The card relative address /// @param buffer A non-null that stores the **raw** card specific data on return /// @param length Specify the number of bytes read from the card specific data (must not exceed 16 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_csd()` defined in `mmc_ops.c`. /// @note Upon a successful return, the given buffer contains the response data as is. /// The caller is responsible for dealing with the endianness and parsing the data. /// @note It is recommended to use `IOSDHostDriver::CMD9(rca:csd:)` to fetch and parse the data in one function call. /// IOReturn IOSDHostDriver::CMD9(UInt32 rca, UInt8* buffer, IOByteCount length) { auto request = this->host->getRequestFactory().CMD9(rca); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to issue the CMD9. Error = 0x%x.", retVal); return retVal; } length = min(sizeof(CSDVX), length); memcpy(buffer, request.command.reinterpretResponseAs<IOSDHostResponse2>()->value, length); return kIOReturnSuccess; } /// /// CMD9: Ask the card specified by the given relative address to send the card specific data and parse the returned data /// /// @param rca The card relative address /// @param csd The card specific data on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_csd()` defined in `mmc_ops.c`. /// @note Upon a successful return, the given buffer contains the response data as is. /// The caller is responsible for dealing with the endianness and parsing the data. /// @note It is recommended to use `IOSDHostDriver::CMD9(cid:)` to fetch and parse the data in one function call. /// IOReturn IOSDHostDriver::CMD9(UInt32 rca, CSD& csd) { UInt8 buffer[sizeof(CSDVX)] = {}; IOReturn retVal = this->CMD9(rca, buffer); if (retVal != kIOReturnSuccess) { perr("Failed to fetch the card specific data. Error = 0x%x.", retVal); return retVal; } // FIXME: Compatibility layer: REMOVE THIS ONCE THE DECODE FUNC IS REWRITTEN // FIXME: The decode function uses Linux's UNSTUFF_BITS macro to extract bits from the response // FIXME: This macro assumes that the data is an array of four UInt32 intergers encoded in big endian UInt32* data = reinterpret_cast<UInt32*>(buffer); for (auto index = 0; index < sizeof(CSDVX) / sizeof(UInt32); index += 1) { data[index] = OSSwapInt32(data[index]); } if (!CSD::decode(data, csd)) { perr("Failed to decode the SD configuration register value."); return kIOReturnInvalid; } pinfo("Fetched and decoded SD configuration register value successfully."); return kIOReturnSuccess; } /// /// CMD11: Switch to 1.8V bus signaling level /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces a portion of `mmc_set_uhs_voltage()` defined in `mmc_ops.c`. /// IOReturn IOSDHostDriver::CMD11() { auto request = this->host->getRequestFactory().CMD11(); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to initiate the CMD11. Error = 0x%x.", retVal); return retVal; } if (BitOptions(request.command.reinterpretResponseAs<IOSDHostResponse1>()->getStatus()).contains(R1_ERROR)) { perr("The response to the CMD11 has the error bit set."); return kIOReturnInvalid; } return kIOReturnSuccess; } /// /// CMD13: Send the card status /// /// @param rca The card relative address /// @param status The card status on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `__mmc_send_status()` defined in `mmc_ops.c`. /// IOReturn IOSDHostDriver::CMD13(UInt32 rca, UInt32& status) { auto request = this->host->getRequestFactory().CMD13(rca); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to initiate the CMD13. Error = 0x%x.", retVal); return retVal; } status = request.command.reinterpretResponseAs<IOSDHostResponse1>()->getStatus(); return kIOReturnSuccess; } /// /// CMD55: Tell the card that the next command is an application command /// /// @param rca The card relative address /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_app_cmd()` defined in `sd_ops.c`. /// IOReturn IOSDHostDriver::CMD55(UInt32 rca) { // Send the command auto request = this->host->getRequestFactory().CMD55(rca); IOReturn retVal = this->waitForRequest(request); if (retVal != kIOReturnSuccess) { perr("Failed to initiate the CMD55. Error = 0x%x.", retVal); return retVal; } // Check whether the card supports application commands if (!BitOptions(request.command.reinterpretResponseAs<IOSDHostResponse1>()->getStatus()).contains(R1_APP_CMD)) { perr("The card does not support application commands."); return kIOReturnUnsupported; } return kIOReturnSuccess; } /// /// ACMD6: Set the data bus width /// /// @param rca The card relative address /// @param busWidth The data bus width (1 bit or 4 bit) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_app_set_bus_width()` defined in `sd_ops.c`. /// IOReturn IOSDHostDriver::ACMD6(UInt32 rca, IOSDBusConfig::BusWidth busWidth) { // Bus width value static constexpr UInt32 kSDBusWidth1Bit = 0b00; static constexpr UInt32 kSDBusWidth4Bit = 0b10; // Verify the given bus width UInt32 busWidthValue; switch (busWidth) { case IOSDBusConfig::BusWidth::k1Bit: { busWidthValue = kSDBusWidth1Bit; break; } case IOSDBusConfig::BusWidth::k4Bit: { busWidthValue = kSDBusWidth4Bit; break; } default: { perr("SD does not support the 8-bit bus."); return kIOReturnBadArgument; } } auto request = this->host->getRequestFactory().ACMD6(busWidthValue); return this->waitForAppRequest(request, rca); } /// /// ACMD13: Send the SD status /// /// @param rca The card relative address /// @param status A non-null buffer that stores the SD status on return /// @param length Specify the number of bytes read from the response (must not exceed 64 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_app_sd_status()` defined in `sd_ops.c`. /// @note This function allocates an internal 64-byte DMA capable buffer to store the status sent by the card. /// The status is then copied to the given `status` buffer. /// IOReturn IOSDHostDriver::ACMD13(UInt32 rca, UInt8* status, IOByteCount length) { // Send the command auto action = [&](IOMemoryDescriptor* descriptor) -> IOReturn { auto request = this->host->getRequestFactory().ACMD13(descriptor); IOReturn retVal = this->waitForAppRequest(request, rca); if (retVal == kIOReturnSuccess) { // Copy the SD status from the memory descriptor length = min(length, 64); retVal = descriptor->readBytes(0, status, length) == length ? kIOReturnSuccess : kIOReturnError; } return retVal; }; return IOMemoryDescriptorRunActionWithWiredBuffer(64, kIODirectionInOut, action); } /// /// ACMD13: Send the SD status /// /// @param rca The card relative address /// @param status The SD status on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_app_sd_status()` defined in `sd_ops.c`. /// @note This function allocates an internal 64-byte DMA capable buffer to store the status sent by the card. /// The status is then copied to the given `status` buffer. /// IOReturn IOSDHostDriver::ACMD13(UInt32 rca, SSR& status) { UInt8 buffer[sizeof(SSR)] = {}; IOReturn retVal = this->ACMD13(rca, buffer); if (retVal != kIOReturnSuccess) { perr("Failed to fetch the SD status register value. Error = 0x%x.", retVal); return retVal; } if (!SSR::decode(buffer, status)) { perr("Failed to decode the SD status register value."); return kIOReturnInvalid; } pinfo("Fetched and decoded SD status register value successfully."); return kIOReturnSuccess; } /// /// ACMD41: Send the operating condition register (OCR) value at the probe stage /// /// @param rocr The OCR value returned by the card /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_app_op_cond()` defined in `sd_ops.c`. /// IOReturn IOSDHostDriver::ACMD41(UInt32& rocr) { auto request = this->host->getRequestFactory().ACMD41(0); IOReturn retVal = this->waitForAppRequest(request, 0); if (retVal != kIOReturnSuccess) { perr("Failed to issue the ACMD41. Error = 0x%x.", retVal); return retVal; } rocr = request.command.reinterpretResponseAs<IOSDHostResponse3>()->getValue(); return kIOReturnSuccess; } /// /// ACMD41: Send the operating condition register (OCR) value /// /// @param ocr The OCR value that contains requested settings /// @param rocr The OCR value returned by the card /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_send_app_op_cond()` defined in `sd_ops.c`. /// IOReturn IOSDHostDriver::ACMD41(UInt32 ocr, UInt32& rocr) { auto request = this->host->getRequestFactory().ACMD41(ocr); for (int attempt = 0; attempt < 100; attempt += 1) { // Send the command IOReturn retVal = this->waitForAppRequest(request, 0); if (retVal != kIOReturnSuccess) { perr("Failed to issue the ACMD41. Error = 0x%x.", retVal); return retVal; } // Retrieve the returned OCR value rocr = request.command.reinterpretResponseAs<IOSDHostResponse3>()->getValue(); // Check the busy bit if (BitOptions(rocr).containsBit(31)) { return kIOReturnSuccess; } IOSleep(20); } return kIOReturnTimeout; } /// /// ACMD51: Ask the card to send the SD configuration register (SCR) value /// /// @param rca The card relative address /// @param configuration A non-null buffer that stores the **raw** SD configuration register value on return /// @param length Specify the number of bytes read from the response (must not exceed 8 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_app_send_scr()` defined in `sd_ops.c`. /// @note This function allocates an internal 8-byte DMA capable buffer to store the register value sent by the card. /// The value is then copied to the given `scr` buffer. /// @note Upon a successful return, the given buffer contains the response data as is. /// The caller is responsible for dealing with the endianness and parsing the data. /// @note It is recommended to use `IOSDHostDriver::ACMD51(cid:)` to fetch and parse the data in one function call. /// IOReturn IOSDHostDriver::ACMD51(UInt32 rca, UInt8* configuration, IOByteCount length) { // Send the command auto action = [&](IOMemoryDescriptor* descriptor) -> IOReturn { auto request = this->host->getRequestFactory().ACMD51(descriptor); IOReturn retVal = this->waitForAppRequest(request, rca); if (retVal == kIOReturnSuccess) { // Copy the SD configuration value from the memory descriptor length = min(length, 8); retVal = descriptor->readBytes(0, configuration, length) == length ? kIOReturnSuccess : kIOReturnError; } return retVal; }; return IOMemoryDescriptorRunActionWithWiredBuffer(8, kIODirectionInOut, action); } /// /// ACMD51: Ask the card to send the SD configuration register (SCR) value and parse the value /// /// @param rca The card relative address /// @param scr The **parsed** SD configuration register value on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `mmc_app_send_scr()` defined in `sd_ops.c`. /// @note This function allocates an internal 8-byte DMA capable buffer to store the register value sent by the card. /// The value is then copied to the given `scr` buffer. /// IOReturn IOSDHostDriver::ACMD51(UInt32 rca, SCR& scr) { UInt8 buffer[sizeof(SCR)] = {}; IOReturn retVal = this->ACMD51(rca, buffer); if (retVal != kIOReturnSuccess) { perr("Failed to fetch the SD configuration register value. Error = 0x%x.", retVal); return retVal; } if (!SCR::decode(buffer, scr)) { perr("Failed to decode the SD configuration register value."); return kIOReturnInvalid; } pinfo("Fetched and decoded SD configuration register value successfully."); return kIOReturnSuccess; } // // MARK: - Card Management // /// /// [Helper] Notify the block storage device that the media state has changed /// /// @param state The new state of the media /// @return The status returned by the block storage device. /// IOReturn IOSDHostDriver::notifyBlockStorageDevice(IOMediaState state) { return this->blockStorageDevice->message(kIOMessageMediaStateHasChanged, this, reinterpret_cast<void*>(state)); } /// /// [Helper] Use the given frequency to probe the card prior to the initialization process /// /// @param frequency The initial frequency in Hz /// @param rocr The OCR value returned by the card at the probe stage /// @return `true` on success, `false` otherwise. /// @note Upon a successful return, the host bus power is on and the card is ready to be initialized, otherwise the power is off. /// @note Port: This function replaces the code block in `mmc_rescan_try_freq()` defined in `core.c` and `mmc_attach_sd()` in `sd.c`. /// bool IOSDHostDriver::probeCardAtFrequency(UInt32 frequency, UInt32& rocr) { // Get the initial clock and voltages this->host->setHostInitialClock(frequency); UInt32 ocr = this->host->getHostSupportedVoltageRanges(); pinfo("Voltage ranges supported by the host: 0x%08x.", ocr); // Power up the SD bus pinfo("Powering up the host bus..."); if (this->powerUp(ocr) != kIOReturnSuccess) { perr("Failed to power up the host bus."); return false; } pinfo("The host bus is now powered up."); // Inquire the SD card do { // Tell the card to go to the idle state pinfo("Asking the card to go to the idle state..."); if (this->CMD0() != kIOReturnSuccess) { perr("Failed to tell the card to go to the idle state."); break; } pinfo("The card is now in the idle state."); // Check whether a SD card is inserted // Note that MMC cards are not supported if (this->CMD8(ocr) != kIOReturnSuccess) { perr("The card does not respond to the CMD8."); } if (this->ACMD41(rocr) != kIOReturnSuccess) { perr("The card does not respond to the ACMD41."); break; } // Successfully probed the card return true; } while (false); // Failed to probe the card psoftassert(this->powerOff() == kIOReturnSuccess, "Failed to power off the bus."); return false; } /// /// [Helper] Use the given frequency to communicate with the card and try to attach it /// /// @param frequency The initial frequency in Hz /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_rescan_try_freq()` defined in `core.c` and `mmc_attach_sd()` in `sd.c`. /// @note This function is invoked by `IOSDHostDriver::attachCard()`, /// so it runs synchronously with respect to the processor workloop. /// bool IOSDHostDriver::attachCardAtFrequency(UInt32 frequency) { // Step 1: Setup the card instance passert(this->card == nullptr, "this->card should be null at this moment."); if (!this->setupCard()) { perr("Failed to setup the card instance."); return false; } // Step 2: Probe and initialize the card IOSDCard::SpeedMode speedMode = IOSDCard::SpeedMode::kMaxSpeed; UInt32 attempts = 0; while (true) { // Step 2.1: Probe the card at the given frequency pinfo("Trying to probe the card at %u Hz.", frequency); attempts += 1; UInt32 rocr = 0; if (!this->probeCardAtFrequency(frequency, rocr)) { perr("Failed to probe the card at %u Hz.", frequency); break; } pinfo("Probed the card at %u Hz successfully. OCR returned by the card = 0x%08x.", frequency, rocr); // Step 2.2: Filter out unsupported voltage levels rocr &= ~0x7FFF; rocr = this->selectMutualVoltageLevels(rocr); if (rocr == 0) { perr("Failed to find a voltage level supported by both the host and the card."); break; } pinfo("Voltage levels supported by both sides = 0x%08x (OCR).", rocr); // Step 2.3: Start the card initialization process IOReturn retVal = card->initializeCard(rocr, speedMode); // Guard Case 1: Success if (retVal == kIOReturnSuccess) { pinfo("The card has been initialized successfully."); this->card->setProperty(kIOSDCardInitFailures, attempts - 1, 32); this->card->setProperty(kIOSDCardSpeedMode, speedMode, 32); return true; } // Guard Case 2: Abort if (retVal == kIOReturnAborted) { perr("Failed to initialize the card. Will abort the card initialization process."); break; } // Guard Case 3: Unsupported return value if (retVal != kIOReturnNotResponding) { pfatal("Unrecognized return value 0x%08x from IOSDCard::initializeCard().", retVal); break; } // Guard Case 4: Need to try the next lower speed mode perr("Failed to initialize the card. Will try the next available lower speed mode."); // Check whether we have tried every possible speed mode if (speedMode == IOSDCard::SpeedMode::kMinSpeed) { perr("The host driver has tried all possible speed modes. Will abort the initialization process."); break; } // Power off the host bus to prepare for the next initialization process psoftassert(this->powerOff() == kIOReturnSuccess, "Failed to power off the bus."); // Adjust the speed mode speedMode = IOSDCard::nextLowerSpeedMode(speedMode); } // Step 3: Tear down the card instance on error psoftassert(this->powerOff() == kIOReturnSuccess, "Failed to power off the bus."); this->tearDownCard(); return false; } /// /// Attach the SD card /// /// @param completion The completion routine to call once the card insertion event has been processed /// @param options An optional value passed to the card event handler /// @note This function is invoked on the processor workloop thread when a SD card is inserted. /// void IOSDHostDriver::attachCard(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { /// Initial card frequencies in Hz static constexpr UInt32 frequencies[] = { KHz2Hz(400), KHz2Hz(300), KHz2Hz(200), KHz2Hz(100) }; pinfo("Attaching the SD card with completion at 0x%08x%08x and event options %u...", KPTR(completion), options.flatten()); ClosedRange<UInt32> range = this->host->getHostClockRange(); OSDictionary* characteristics = nullptr; IOReturn status = kIOReturnError; // Try each default frequency for (auto frequency : frequencies) { pinfo("---------------------------------------------------------------------------"); // Guard: Ensure that the default frequency is supported if (!range.contains(frequency)) { perr("Default frequency %d Hz is not supported by the host device.", frequency); continue; } // Guard: Attempt to initialize the card if (!this->attachCardAtFrequency(frequency)) { perr("Failed to initialize the card at %u Hz.", frequency); continue; } // The card has been initialized pinfo("The card has been initialized at %u Hz.", frequency); // Fetch the card characteristics characteristics = this->card->getCardCharacteristics(); // Sanitize the pending request queue // It is possible that one or two requests are left in the queue // even after the card has been removed from the system. // See `IOSDHostDriver::submitBlockRequest()` for details. this->recyclePendingBlockRequest(); // Check whether the host driver is initializing the card to service the interrupt if (!options.contains(IOSDCard::EventOption::kPowerManagementContext)) { // Notify the block storage device that the media is online pinfo("The attach event handler is invoked by the interrupt service routine."); status = this->notifyBlockStorageDevice(kIOMediaStateOnline); break; } // The host driver is re-attaches the card when the computer wakes up pinfo("The attach event handler is invoked by the power management routine."); // Guard: Check whether users change the card when the computer is sleeping // ----------------------------------------------------------------------- // | Scenario # | Before Sleep | During Sleep | After Sleep | // ----------------------------------------------------------------------- // | Scenario 1 | No Card Inserted | No Action | No Card Inserted | // | Scenario 2 | No Card Inserted | Inserts Card | Attach Card | // | Scenario 3 | Card #1 Inserted | No Action | Attach Card #1 | // | Scenario 4 | Card #1 Inserted | Swaps Card | Attach Card #2 | // ----------------------------------------------------------------------- // Scenario 2 if (this->pcid.isEmpty()) { pinfo("User inserted a card when the computer was sleeping."); status = this->notifyBlockStorageDevice(kIOMediaStateOnline); break; } // Scenario 3 if (this->pcid == this->card->getCID()) { pinfo("Attached the card inserted before the computer slept."); status = kIOReturnSuccess; break; } // Scenario 4 pinfo("User swapped the card when the computer was sleeping."); status = this->blockStorageDevice->message(kIOMessageMediaParametersHaveChanged, this); break; } pinfo("The card insertion event has been processed. Status = 0x%08x.", status); // All done: Notify the client IOSDCard::complete(completion, status, characteristics); OSSafeReleaseNULL(characteristics); } /// /// Detach the SD card /// /// @param completion The completion routine to call once the card removal event has been processed /// @param options An optional value passed to the card event handler /// @note This function is invoked on the processor workloop thread when a SD card is removed. /// void IOSDHostDriver::detachCard(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { pinfo("Detaching the SD card with completion at 0x%08x%08x and event options %u...", KPTR(completion), options.flatten()); // Notify the block storage device that the media is offline IOReturn status = kIOReturnSuccess; if (!options.contains(IOSDCard::EventOption::kPowerManagementContext)) { pinfo("The detach event handler is invoked by the interrupt service routine."); status = this->notifyBlockStorageDevice(kIOMediaStateOffline); } // Stop the card device if (this->card != nullptr) { // Cache the card identification data when the computer sleeps this->pcid = this->card->getCID(); pinfo("Stopping the card device..."); this->card->stop(this); this->card->detach(this); this->card->release(); this->card = nullptr; pinfo("The card device has been stopped."); } else { // The card is not present when the computer sleeps/wakes up pinfo("The card device is not present or has already been stopped."); this->pcid.reset(); } // Recycle all pending requests this->recyclePendingBlockRequest(); // Power off the bus psoftassert(this->powerOff() == kIOReturnSuccess, "Failed to power off the bus."); pinfo("The card removal event has been processed. Status = 0x%08x.", status); // All done: Notify the client IOSDCard::complete(completion, status); } // // MARK: - Card Events Callbacks // /// /// [UPCALL] Notify the host driver when a SD card is inserted /// /// @param completion A nullable completion routine to be invoked when the card is attached /// @param options An optional value passed to the host driver /// @note This callback function runs in a gated context provided by the underlying card reader controller. /// The host device should implement this function without any blocking operations. /// void IOSDHostDriver::onSDCardInsertedGated(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { // Make sure that the detach event source is disabled this->detachCardEventSource->disable(); // Notify the processor work loop to attach the card this->attachCardEventSource->enable(completion, options); // Enable the queue event source to accept incoming block requests this->queueEventSource->enable(); } /// /// [UPCALL] Notify the host driver when a SD card is removed /// /// @param completion A nullable completion routine to be invoked when the card is detached /// @param options An optional value passed to the host driver /// @note This callback function runs in a gated context provided by the underlying card reader controller. /// The host device should implement this function without any blocking operations. /// void IOSDHostDriver::onSDCardRemovedGated(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { // Disable the queue event source so that the processor work loop will stop processing requests this->queueEventSource->disable(); // Make sure that the attach event source is disabled this->attachCardEventSource->disable(); // Notify the processor work loop to detach the card this->detachCardEventSource->enable(completion, options); } // // MARK: - Query Card Information // /// /// Check whether the card has write protection enabled /// /// @param result Set `true` if the card is write protected, `false` otherwise. /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDHostDriver::isCardWriteProtected(bool& result) { return this->host->isCardWriteProtected(result); } /// /// Check whether the card exists /// /// @param result Set `true` if the card exists, `false` otherwise. /// @return `kIOReturnSuccess` always. /// IOReturn IOSDHostDriver::isCardPresent(bool& result) { return this->host->isCardPresent(result); } /// /// Get the card capacity in number of blocks /// /// @param nblocks The number of blocks on return /// @return `kIOReturnSuccess` on success, `kIOReturnNoMedia` if the card is not present. /// IOReturn IOSDHostDriver::getCardNumBlocks(UInt64& nblocks) { auto action = [&]() -> IOReturn { if (this->card == nullptr) { perr("The card is not present."); return kIOReturnNoMedia; } nblocks = this->card->getCSD().capacity; // Treat the SDSC card as a block device whose block size is 512 bytes // SDHC/XC cards always have a read block length of 9 // SDSC cards may have a read block length of 9, 10, or 11 // Adjust the total number of blocks accordingly nblocks <<= (this->card->getCSD().readBlockLength - 9); return kIOReturnSuccess; }; return IOCommandGateRunAction(this->processorCommandGate, action); } /// /// Get the index of the maximum block of the card /// /// @param index The index of the last accessible block on the card on return /// @return `kIOReturnSuccess` on success, `kIOReturnNoMedia` if the card is not present. /// IOReturn IOSDHostDriver::getCardMaxBlockIndex(UInt64& index) { IOReturn retVal = this->getCardNumBlocks(index); index -= 1; return retVal; } /// /// Get the size of a block /// /// @param length The block length in bytes on return /// @return `kIOReturnSuccess` on success, `kIOReturnNoMedia` if the card is not present. /// IOReturn IOSDHostDriver::getCardBlockLength(UInt64& length) { auto action = [&]() -> IOReturn { if (this->card == nullptr) { perr("The card is not present."); return kIOReturnNoMedia; } length = 512; return kIOReturnSuccess; }; return IOCommandGateRunAction(this->processorCommandGate, action); } /// /// Get the card vendor name /// /// @return A non-null static vendor string. /// @note This function returns "<null>" if the card is not present. /// const char* IOSDHostDriver::getCardVendor() { const char* vendor = nullptr; auto action = [&]() -> IOReturn { vendor = this->card == nullptr ? "Realtek" : this->card->getCID().getVendorString(); return kIOReturnSuccess; }; IOCommandGateRunAction(this->processorCommandGate, action); return vendor; } /// /// Get the card product name /// /// @param name A non-null buffer that can hold at least 8 bytes. /// @param length The buffer length /// @return `kIOReturnSuccess` on success, /// `kIOReturnNoMedia` if the card is not present, /// `kIOReturnBadArgument` if the buffer is NULL or too small. /// IOReturn IOSDHostDriver::getCardName(char* name, IOByteCount length) { auto action = [&]() -> IOReturn { if (this->card == nullptr) { perr("The card is not present."); return kIOReturnNoMedia; } if (!this->card->getCardName(name, length)) { perr("The given buffer/length is invalid."); return kIOReturnBadArgument; } return kIOReturnSuccess; }; return IOCommandGateRunAction(this->processorCommandGate, action); } /// /// Get the card revision value /// /// @param revision A non-null buffer that can hold at least 8 bytes. /// @param length The buffer length /// @return `kIOReturnSuccess` on success, /// `kIOReturnNoMedia` if the card is not present, /// `kIOReturnBadArgument` if the buffer is NULL or too small. /// IOReturn IOSDHostDriver::getCardRevision(char* revision, IOByteCount length) { auto action = [&]() -> IOReturn { if (this->card == nullptr) { perr("The card is not present."); return kIOReturnNoMedia; } if (!this->card->getCardRevision(revision, length)) { perr("The given buffer/length is invalid."); return kIOReturnBadArgument; } return kIOReturnSuccess; }; return IOCommandGateRunAction(this->processorCommandGate, action); } /// /// Get the card manufacture date /// /// @param date A non-null buffer that can hold at least 8 bytes. /// @param length The buffer length /// @return `kIOReturnSuccess` on success, /// `kIOReturnNoMedia` if the card is not present, /// `kIOReturnBadArgument` if the buffer is NULL or too small. /// IOReturn IOSDHostDriver::getCardProductionDate(char* date, IOByteCount length) { auto action = [&]() -> IOReturn { if (this->card == nullptr) { perr("The card is not present."); return kIOReturnNoMedia; } if (!this->card->getCardProductionDate(date, length)) { perr("The given buffer/length is invalid."); return kIOReturnBadArgument; } return kIOReturnSuccess; }; return IOCommandGateRunAction(this->processorCommandGate, action); } /// /// Get the card serial number /// /// @param serial The card serial number on return /// @return `kIOReturnSuccess` on success, `kIOReturnNoMedia` if the card is not present. /// IOReturn IOSDHostDriver::getCardSerialNumber(UInt32& serial) { auto action = [&]() -> IOReturn { if (this->card == nullptr) { perr("The card is not present."); return kIOReturnNoMedia; } serial = this->card->getCID().serial; return kIOReturnSuccess; }; return IOCommandGateRunAction(this->processorCommandGate, action); } // // MARK: - Startup Routines // /// /// Setup the shared work loop to protect the pool and the queue /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupSharedWorkLoop() { pinfo("Creating the shared work loop..."); this->sharedWorkLoop = IOWorkLoop::workLoop(); if (this->sharedWorkLoop == nullptr) { perr("Failed to create the shared work loop."); return false; } pinfo("The shared work loop has been created."); return true; } /// /// Setup the SD block request pool /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupBlockRequestPool() { pinfo("Creating the block request pool..."); this->simpleBlockRequestPool = IOSDSimpleBlockRequestPool::createWithCapacity(this->sharedWorkLoop, IOSDHostDriver::kDefaultPoolSize); if (this->simpleBlockRequestPool == nullptr) { perr("Failed to create the simple block request pool.") return false; } this->complexBlockRequestPool = IOSDComplexBlockRequestPool::createWithCapacity(this->sharedWorkLoop, IOSDHostDriver::kDefaultPoolSize); if (this->complexBlockRequestPool == nullptr) { perr("Failed to create the complex block request pool."); IOSDSimpleBlockRequestPool::destory(this->simpleBlockRequestPool); this->simpleBlockRequestPool = nullptr; return false; } pinfo("The block request pool has been created."); return true; } /// /// Setup the SD block request queue /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupBlockRequestQueue() { pinfo("Creating the block request queue..."); this->pendingRequests = IOSDBlockRequestQueue::create(this->sharedWorkLoop); if (this->pendingRequests == nullptr) { perr("Failed to create the request queue."); return false; } pinfo("The block request queue has been created."); return true; } /// /// Setup the shared work loop to process card events and block requests /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupProcessorWorkLoop() { pinfo("Creating the dedicated processor work loop..."); this->processorWorkLoop = IOWorkLoop::workLoop(); if (this->processorWorkLoop == nullptr) { perr("Failed to create the dedicated processor work loop."); return false; } pinfo("The dedicated processor work loop has been created."); pinfo("Creating the processor command gate..."); this->processorCommandGate = IOCommandGate::commandGate(this); if (this->processorCommandGate == nullptr) { perr("Failed to create the command gate."); OSSafeReleaseNULL(this->processorWorkLoop); return false; } this->processorWorkLoop->addEventSource(this->processorCommandGate); pinfo("The processor command gate has been created."); return true; } /// /// Setup the event source that signals the processor work loop to process the block request /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupBlockRequestEventSource() { pinfo("Creating the block request event source..."); auto finalizer = OSMemberFunctionCast(IOSDBlockRequestEventSource::Action, this, &IOSDHostDriver::finalizeBlockRequest); this->queueEventSource = IOSDBlockRequestEventSource::createWithQueue(this, finalizer, this->pendingRequests); if (this->queueEventSource == nullptr) { perr("Failed to create the block request event source."); return false; } this->queueEventSource->disable(); this->processorWorkLoop->addEventSource(this->queueEventSource); pinfo("The block request event source has been created and registered with the processor work loop."); return true; } /// /// Setup the event sources that signal the processor work loop to handle card insertion and removal events /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupCardEventSources() { // Card Insertion Event pinfo("Creating the card insertion event source..."); auto attacher = OSMemberFunctionCast(IOSDCardEventSource::Action, this, &IOSDHostDriver::attachCard); this->attachCardEventSource = IOSDCardEventSource::createWithAction(this, attacher); if (this->attachCardEventSource == nullptr) { perr("Failed to create the card insertion event source."); return false; } // The card insertion event source will be enabled by the notification handler // @see `IOSDHostDriver::onSDCardInsertedGated()` for details this->attachCardEventSource->disable(); pinfo("The card insertion event source has been created."); // Card Removal Event pinfo("Creating the card removal event source..."); auto detacher = OSMemberFunctionCast(IOSDCardEventSource::Action, this, &IOSDHostDriver::detachCard); this->detachCardEventSource = IOSDCardEventSource::createWithAction(this, detacher); if (this->detachCardEventSource == nullptr) { perr("Failed to create the card insertion event source."); this->attachCardEventSource->release(); this->attachCardEventSource = nullptr; return false; } // The card removal event source will be enabled by the notification handler // @see `IOSDHostDriver::onSDCardRemovedGated()` for details this->detachCardEventSource->disable(); pinfo("The card insertion event source has been created."); // Register with the processor work loop this->processorWorkLoop->addEventSource(this->attachCardEventSource); this->processorWorkLoop->addEventSource(this->detachCardEventSource); pinfo("Card event sources have been registered with the processor work loop."); return true; } /// /// Wait until the block storage device is published /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// bool IOSDHostDriver::setupBlockStorageDevice() { pinfo("Waiting for the block storage device to be published..."); OSDictionary* dictionary = IOService::serviceMatching("IOSDBlockStorageDevice"); if (dictionary == nullptr) { perr("Failed to create the matching dictionary."); return false; } IOService* service = this->waitForMatchingService(dictionary); if (service == nullptr) { perr("Failed to find the matched service."); return false; } this->blockStorageDevice = OSDynamicCast(IOSDBlockStorageDevice, service); if (this->blockStorageDevice == nullptr) { perr("The matched service is not a valid block storage device."); service->release(); return false; } else { pinfo("The block storage device at 0x%08x%08x has been published.", KPTR(this->blockStorageDevice)); return true; } } /// /// Setup the SD card instance /// /// @return `true` on success, `false` otherwise. /// @note Upon an unsuccessful return, all resources allocated by this function are released. /// @note This startup routine is used by `IOSDHostDriver::attachCardAtFrequency()`. /// bool IOSDHostDriver::setupCard() { pinfo("Creating the SD card instance..."); this->card = OSTypeAlloc(IOSDCard); if (this->card == nullptr) { perr("Failed to allocate the card instance."); return false; } if (!this->card->init()) { perr("Failed to initiaize the card instance."); OSSafeReleaseNULL(this->card); return false; } if (!this->card->attach(this)) { perr("Failed to attach the card instance."); OSSafeReleaseNULL(this->card); return false; } if (!this->card->start(this)) { perr("Failed to start the card instance."); this->card->detach(this); OSSafeReleaseNULL(this->card); return false; } pinfo("The SD card instance has been created successfully."); return true; } // // MARK: - Teardown Routines // /// /// Tear down the shared workloop /// void IOSDHostDriver::tearDownSharedWorkLoop() { OSSafeReleaseNULL(this->sharedWorkLoop); } /// /// Tear down the SD block request pool /// void IOSDHostDriver::tearDownBlockRequestPool() { IOSDSimpleBlockRequestPool::safeDestory(this->simpleBlockRequestPool); IOSDComplexBlockRequestPool::safeDestory(this->complexBlockRequestPool); } /// /// Tear down the SD block request pool /// void IOSDHostDriver::tearDownBlockRequestQueue() { OSSafeReleaseNULL(this->pendingRequests); } /// /// Tear down the processor workloop /// void IOSDHostDriver::tearDownProcessorWorkLoop() { if (this->processorCommandGate != nullptr) { this->processorCommandGate->disable(); this->processorWorkLoop->removeEventSource(this->processorCommandGate); this->processorCommandGate->release(); this->processorCommandGate = nullptr; } OSSafeReleaseNULL(this->processorWorkLoop); } /// /// Tear down the SD block request event source /// void IOSDHostDriver::tearDownBlockRequestEventSource() { if (this->queueEventSource != nullptr) { this->queueEventSource->disable(); this->processorWorkLoop->removeEventSource(this->queueEventSource); this->queueEventSource->release(); this->queueEventSource = nullptr; } } /// /// Tear down the card event sources /// void IOSDHostDriver::tearDownCardEventSources() { if (this->detachCardEventSource != nullptr) { this->detachCardEventSource->disable(); this->processorWorkLoop->removeEventSource(this->detachCardEventSource); this->detachCardEventSource->release(); this->detachCardEventSource = nullptr; } if (this->attachCardEventSource != nullptr) { this->attachCardEventSource->disable(); this->processorWorkLoop->removeEventSource(this->attachCardEventSource); this->attachCardEventSource->release(); this->attachCardEventSource = nullptr; } } /// /// Tear down the block storage device /// void IOSDHostDriver::tearDownBlockStorageDevice() { OSSafeReleaseNULL(this->blockStorageDevice); } /// /// Tear down the SD card instance /// /// @note This startup routine is used by `IOSDHostDriver::attachCardAtFrequency()`. /// void IOSDHostDriver::tearDownCard() { pinfo("Stopping the SD card instance..."); if (this->card != nullptr) { this->card->stop(this); this->card->detach(this); OSSafeReleaseNULL(this->card); } pinfo("The SD card instance has been destroyed."); } // // MARK: - IOService Implementations // /// /// Start the host driver /// /// @param provider An instance of the host device /// @return `true` on success, `false` otherwise. /// bool IOSDHostDriver::start(IOService* provider) { pinfo("===================================================================="); pinfo("Starting the SD host driver with the device at 0x%08x%08x...", KPTR(provider)); pinfo("===================================================================="); // Start the super class if (!super::start(provider)) { perr("Failed to start the super class."); return false; } // Get the host device this->host = OSDynamicCast(IOSDHostDevice, provider); if (this->host == nullptr) { perr("The provider is not a valid host device."); return false; } this->host->retain(); // Setup the shared work loop if (!this->setupSharedWorkLoop()) { goto error1; } // Create the block request pool if (!this->setupBlockRequestPool()) { goto error2; } // Create the request queue if (!this->setupBlockRequestQueue()) { goto error3; } // Create the processor work loop if (!this->setupProcessorWorkLoop()) { goto error4; } // Create the block request event source if (!this->setupBlockRequestEventSource()) { goto error5; } // Create the card insertion and removal event sources if (!this->setupCardEventSources()) { goto error6; } // Publish the service to start the block storage device this->registerService(); // Wait until the block storage device is published this->setupBlockStorageDevice(); pinfo("========================================"); pinfo("The SD host driver started successfully."); pinfo("========================================"); return true; error6: this->tearDownBlockRequestEventSource(); error5: this->tearDownProcessorWorkLoop(); error4: this->tearDownBlockRequestQueue(); error3: this->tearDownBlockRequestPool(); error2: this->tearDownSharedWorkLoop(); error1: OSSafeReleaseNULL(this->host); pinfo("==================================="); perr("Failed to start the SD host driver."); pinfo("==================================="); return false; } /// /// Stop the host driver /// /// @param provider An instance of the host device /// void IOSDHostDriver::stop(IOService* provider) { pinfo("Stopping the SD host driver..."); this->tearDownCardEventSources(); this->tearDownBlockRequestEventSource(); this->tearDownProcessorWorkLoop(); this->tearDownBlockRequestQueue(); this->tearDownBlockRequestPool(); this->tearDownSharedWorkLoop(); OSSafeReleaseNULL(this->host); pinfo("The SD host driver has stopped."); super::stop(provider); } <|start_filename|>RealtekCardReader/IOSDCard-SSR.hpp<|end_filename|> // // IOSDCard-SSR.hpp // RealtekCardReader // // Created by FireWolf on 12/24/21. // #ifndef IOSDCard_SSR_hpp #define IOSDCard_SSR_hpp #include "Utilities.hpp" /// SD status register value (64 bytes) struct PACKED SSR { /// Bus width (0: 1 bit, 2: 4 bits) UInt8 busWidth: 2; /// `True` if the card is in secured mode bool securedMode: 1; /// Reserved 7 bits for security functions UInt8 reserved0: 7; /// Reserved 6 bits UInt8 reserved1: 6; /// SD card type UInt16 cardType; /// Size of protected area UInt32 protectedAreaSize; /// Speed class of the card UInt8 speedClass; /// Performance of move indicatedf by 1MB/s step UInt8 movePerformance; /// Size of an allocation unit UInt8 auSize: 4; /// Reserved 4 bits UInt8 reserved2: 4; /// Number of AUs to be erased at a time UInt16 eraseSize; /// Timeout value for erasing areaa UInt8 eraseTimeout: 6; /// Fixed offset value added to erase time UInt8 eraseOffset: 2; /// Speed grade for UHS mode UInt8 uhsSpeedGrade: 4; /// Size of AU for UHS mode UInt8 uhsAuSize: 4; /// Video speed class UInt8 videoSpeedClass; /// Reserved 6 bits UInt16 reserved3: 6; /// Size of AU for video speed class UInt16 vscAuSize: 10; /// Suspension address UInt32 suspensionAddress: 22; /// Reserved 6 bits UInt32 reserved4: 6; /// Application performance class value UInt32 appPerformanceClass: 4; /// Support for Performance Enhancement functionalities UInt8 performanceEnhance; /// Reserved 14 bits UInt16 reserved5: 14; /// Discard support bool supportsDiscard: 1; /// Full user area logical erase support bool supportsFULE: 1; /// Reserved 39 bytes for manufacturer UInt8 reserved6[39]; /// /// Decode from the given raw data /// /// @param data The raw SD status register value /// @param pssr The parsed SD status register value /// @return `true` on success, `false` otherwise. /// static bool decode(const UInt8* data, SSR& pssr) { // Note that the driver needs the speed classes only at this moment pssr.speedClass = data[8]; pssr.uhsSpeedGrade = (data[14] & 0xF0) >> 4; pssr.videoSpeedClass = data[15]; pinfo("Speed Class = %d; UHS Speed Grade = %d; Video Speed Class = %d.", pssr.speedClass, pssr.uhsSpeedGrade, pssr.videoSpeedClass); return true; } }; static_assert(sizeof(SSR) == 64, "SSR should be 64 bytes long."); #endif /* IOSDCard_SSR_hpp */ <|start_filename|>RealtekCardReader/IOSDCard-SwitchCaps.hpp<|end_filename|> // // IOSDCard-SwitchCaps.hpp // RealtekCardReader // // Created by FireWolf on 12/24/21. // #ifndef IOSDCard_SwitchCaps_hpp #define IOSDCard_SwitchCaps_hpp #include <libkern/OSTypes.h> /// High speed switch capabilities struct SwitchCaps { /// The maximum clock frequency for the current bus speed mode struct MaxClockFrequencies { /// The maximum clock frequency for the high speed mode UInt32 highSpeedMode; /// The maximum clock frequency for the ultra high speed mode UInt32 ultraHighSpeedMode; } maxClockFrequencies; /// Maximum clock frequency for each bus speed mode enum MaxClockFrequency: UInt32 { kClockDefaultSpeed = MHz2Hz(25), kClockHighSpeed = MHz2Hz(50), kClockUHSSDR12 = MHz2Hz(25), kClockUHSSDR25 = MHz2Hz(50), kClockUHSDDR50 = MHz2Hz(50), kClockUHSSDR50 = MHz2Hz(100), kClockUHSSDR104 = MHz2Hz(208), }; /// Supported bus modes (SD 3.0+) UInt32 sd3BusMode; /// Enumerates all possible bus speeds /// The value is passed to the CMD6 enum BusSpeed: UInt32 { kSpeedUHSSDR12 = 0, kSpeedUHSSDR25 = 1, kSpeedUHSSDR50 = 2, kSpeedUHSSDR104 = 3, kSpeedUHSDDR50 = 4, kSpeedHighSpeed = 1, }; /// Enumerates all possible bus modes /// Use `BitOptions(busMode).contains()` to check whether a mode is supported enum BusMode: UInt32 { kModeUHSSDR12 = 1 << BusSpeed::kSpeedUHSSDR12, kModeUHSSDR25 = 1 << BusSpeed::kSpeedUHSSDR25, kModeUHSSDR50 = 1 << BusSpeed::kSpeedUHSSDR50, kModeUHSSDR104 = 1 << BusSpeed::kSpeedUHSSDR104, kModeUHSDDR50 = 1 << BusSpeed::kSpeedUHSDDR50, kModeHighSpeed = 1 << BusSpeed::kSpeedHighSpeed, }; /// Driver strength (SD 3.0+) UInt32 sd3DriverType; /// Enumerates all possible driver types enum DriverType: UInt32 { kTypeB = 0x01, kTypeA = 0x02, kTypeC = 0x04, kTypeD = 0x08, }; /// The current limit at the host signal voltage level UInt32 sd3MaxCurrent; /// Enumerates all possible current limits /// The value is passed to the CMD6 enum SetCurrentLimit: UInt32 { kCurrentLimit200mA = 0, kCurrentLimit400mA = 1, kCurrentLimit600mA = 2, kCurrentLimit800mA = 3, }; /// Enumerates all possible maximum currents /// Use `BitOptions(maxCurrent).contains()` to check whether a current is supported enum MaxCurrent { kMaxCurrent200mA = 1 << SetCurrentLimit::kCurrentLimit200mA, kMaxCurrent400mA = 1 << SetCurrentLimit::kCurrentLimit400mA, kMaxCurrent600mA = 1 << SetCurrentLimit::kCurrentLimit600mA, kMaxCurrent800mA = 1 << SetCurrentLimit::kCurrentLimit800mA, }; }; #endif /* IOSDCard_SwitchCaps_hpp */ <|start_filename|>RealtekCardReader/IOSDCard.cpp<|end_filename|> // // IOSDCard.cpp // RealtekCardReader // // Created by FireWolf on 6/3/21. // #include "IOSDCard.hpp" #include "IOSDHostDriver.hpp" #include "IOSDHostDriverUserConfigs.hpp" #include "OSDictionary.hpp" // // MARK: - Meta Class Definitions // OSDefineMetaClassAndStructors(IOSDCard, IOService); // // MARK: - Constants and Definitions // /// The specification table const Pair<SPEC, const char*> IOSDCard::kSpecTable[] = { { { 0, 0, 0, 0 }, "1.00" }, // Version 1.0 and 1.01 { { 1, 0, 0, 0 }, "1.10" }, // Version 1.10 { { 2, 0, 0, 0 }, "2.00" }, // Version 2.00 { { 2, 1, 0, 0 }, "3.00" }, // Version 3.0X { { 2, 1, 1, 0 }, "4.00" }, // Version 4.XX { { 2, 1, 0, 1 }, "5.00" }, // Version 5.XX { { 2, 1, 1, 1 }, "5.00" }, // Version 5.XX { { 2, 1, 0, 2 }, "6.00" }, // Version 6.XX { { 2, 1, 1, 2 }, "6.00" }, // Version 6.XX { { 2, 1, 0, 3 }, "7.00" }, // Version 7.XX { { 2, 1, 1, 3 }, "7.00" }, // Version 7.XX { { 2, 1, 0, 4 }, "8.00" }, // Version 8.XX { { 2, 1, 1, 4 }, "8.00" }, // Version 8.XX }; // // MARK: - Query Card Properties // /// /// Get the card characteristics /// /// @return A dictionary that contains card characteristics which can be recognized by the System Profiler. /// @note The caller is responsible for releasing the returned dictionary. /// OSDictionaryPtr IOSDCard::getCardCharacteristics() const { OSDictionary* dictionary = OSDictionary::withCapacity(11); char name[8] = {}; char revision[8] = {}; char date[8] = {}; passert(this->getCardName(name, sizeof(name)), "Should be able to get the card name."); passert(this->getCardRevision(revision, sizeof(revision)), "Should be able to get the card revision."); passert(this->getCardProductionDate(date, sizeof(date)), "Should be able to get the card production date."); if (dictionary != nullptr && OSDictionaryAddStringToDictionary(dictionary, "Card Type", this->getCardType()) && OSDictionaryAddStringToDictionary(dictionary, "Specification Version", this->getSpecificationVersion()) && OSDictionaryAddStringToDictionary(dictionary, "Product Name", name) && OSDictionaryAddStringToDictionary(dictionary, "Product Revision Level", revision) && OSDictionaryAddStringToDictionary(dictionary, "Manufacturing Date", date) && OSDictionaryAddDataToDictionary(dictionary, "Serial Number", &this->cid.serial, sizeof(this->cid.serial)) && OSDictionaryAddDataToDictionary(dictionary, "Manufacturer ID", &this->cid.manufacturer, sizeof(this->cid.manufacturer)) && OSDictionaryAddDataToDictionary(dictionary, "Application ID", &this->cid.oem, sizeof(this->cid.oem)) && OSDictionaryAddDataToDictionary(dictionary, "Speed Class", &this->ssr.speedClass, sizeof(this->ssr.speedClass)) && OSDictionaryAddIntegerToDictionary(dictionary, "UHS Speed Grade", this->ssr.uhsSpeedGrade) && OSDictionaryAddIntegerToDictionary(dictionary, "Video Speed Class", this->ssr.videoSpeedClass)) { return dictionary; } OSSafeReleaseNULL(dictionary); return nullptr; } // // MARK: - Card Initialization Process // /// /// [Helper] Initialize the card with Default Speed Mode enabled /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces the default speed portion of `mmc_sd_init_card()` defined in `sd.c`. /// bool IOSDCard::initDefaultSpeedMode() { // Finish the card initialization sequence with the default speed enabled pinfo("Initializing the card at the default speed mode..."); // Guard: Set the bus speed UInt32 clock = min(UINT32_MAX, this->csd.maxDataTransferRate); pinfo("Setting the bus clock to %u Hz.", clock); if (this->driver->setBusClock(clock) != kIOReturnSuccess) { perr("Failed to set the bus clock to %u Hz.", clock); return false; } // Switch to wider bus if possible // Guard: Check whether the card supports the 4-bit bus if (!BitOptions(this->scr.busWidths).contains(SCR::BusWidth::k4Bit)) { pinfo("The card does not support the 4-bit bus."); return true; } // Guard: Check whether the host supports the 4-bit bus if (!this->driver->hostSupports4BitBusWidth()) { pinfo("The host does not support the 4-bit bus."); return true; } // Enable the 4-bit wide bus if (!this->enable4BitWideBus()) { perr("Failed to enable the 4-bit wide bus."); return false; } else { pinfo("The 4-bit bus has been enabled.") } pinfo("The card has been initialized with the default speed mode enabled."); return true; } /// /// [Helper] Initialize the card with High Speed Mode enabled /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces the high speed portion of `mmc_sd_init_card()` defined in `sd.c`. /// bool IOSDCard::initHighSpeedMode() { // Finish the card initialization sequence with the high speed enabled pinfo("Initializing the card at the high speed mode..."); // Guard: Set the bus timing pinfo("Setting the bus timing to the high speed mode..."); if (this->driver->setBusTiming(IOSDBusConfig::BusTiming::kSDHighSpeed) != kIOReturnSuccess) { perr("Failed to set the bus timing to High Speed."); return false; } pinfo("The bus timing has been set to the high speed mode."); // Guard: Set the bus speed UInt32 clock = this->switchCaps.maxClockFrequencies.highSpeedMode; pinfo("Setting the bus clock to %u Hz.", clock); if (this->driver->setBusClock(clock) != kIOReturnSuccess) { perr("Failed to set the bus clock to %u Hz.", clock); return false; } pinfo("The bus clock has been set to %u Hz.", clock); // Switch to wider bus if possible // Guard: Check whether the card supports the 4-bit bus if (!BitOptions(this->scr.busWidths).contains(SCR::BusWidth::k4Bit)) { pinfo("The card does not support the 4-bit bus."); return true; } // Guard: Check whether the host supports the 4-bit bus if (!this->driver->hostSupports4BitBusWidth()) { pinfo("The host does not support the 4-bit bus."); return true; } // Enable the 4-bit wide bus pinfo("Enabling the 4-bit bus..."); if (!this->enable4BitWideBus()) { perr("Failed to enable the 4-bit wide bus."); return false; } else { pinfo("The 4-bit bus has been enabled."); } // The card initialization sequence finishes pinfo("The card has been initialized with the high speed mode enabled."); return true; } /// /// [Helper] Initialize the card with UHS-I Mode enabled /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_sd_init_uhs_card()` defined in `sd.c`. /// bool IOSDCard::initUltraHighSpeedMode() { // Finish the card initialization sequence with the ultra high speed enabled pinfo("Initializing the card at the ultra high speed mode..."); // Enable the 4-bit wide bus pinfo("Enabling the 4-bit bus..."); if (!this->enable4BitWideBus()) { perr("Failed to enable the 4-bit wide bus required by the UHS-I mode."); return false; } pinfo("The 4-bit bus has been enabled.") // Select the bus speed mode based on the host and card capability SwitchCaps::BusSpeed speedMode = this->selectUltraHighSpeedBusSpeed(); pinfo("Selected bus speed mode is %d.", speedMode); // Set the driver strength for the card pinfo("Setting the driver strength for the card..."); if (!this->setUHSDriverType(speedMode)) { perr("Failed to set the driver type for the card."); return false; } pinfo("The driver strength has been set for the card."); // Set the current limit for the card pinfo("Setting the current limit for the card..."); if (!this->setUHSCurrentLimit(speedMode)) { perr("Failed to set the current limit for the card."); return false; } pinfo("The current limit has been set for the card."); // Set the bus speed mode of the card pinfo("Setting the bus speed mode for the card..."); if (!this->setUHSBusSpeedMode(speedMode)) { perr("Failed to set the bus speed mode of the card."); return false; } pinfo("The bus speed mode has been set for the card."); // Check whether the host needs tuning if (speedMode < SwitchCaps::BusSpeed::kSpeedUHSSDR50) { pinfo("The current bus speed mode does not require tuning."); return true; } // Execute the tuning pinfo("The current bus speed mode requires tuning."); if (this->driver->executeTuning() != kIOReturnSuccess) { perr("Failed to execute tuning for the current bus speed mode %d.", speedMode); return speedMode == SwitchCaps::BusSpeed::kSpeedUHSDDR50; } pinfo("Tuning has finished."); // The card initialization sequence finishes pinfo("The card has been initialized with the ultra high speed mode enabled."); return true; } /// /// [Helper] Read the card switch capabilities /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_read_switch()` defined in `sd.c`. /// bool IOSDCard::readSwitchCapabilities() { // Check the SD specification supported by the card if (this->scr.spec < SCR::Spec::kVersion1d1x) { pinfo("The card does not support SD 1.10+. Will skip the switch capabilities."); return true; } // Check whether the card supports switch functions if (!BitOptions(this->csd.cardCommandClasses).contains(CSD::CommandClass::kSwitch)) { pinfo("The card conforms to SD 1.10+ but does not support mandatory switch functions."); return false; } // Fetch the switch function status UInt8 status[64] = {}; if (this->driver->CMD6(0, 0, 0, status) != kIOReturnSuccess) { perr("Failed to issue the CMD6."); return false; } if (BitOptions(status[13]).contains(SwitchCaps::BusMode::kModeHighSpeed)) { this->switchCaps.maxClockFrequencies.highSpeedMode = SwitchCaps::MaxClockFrequency::kClockHighSpeed; } if (this->scr.spec3 != 0) { this->switchCaps.sd3BusMode = status[13]; this->switchCaps.sd3DriverType = status[9]; this->switchCaps.sd3MaxCurrent = status[7] | status[6] << 8; } return true; } /// /// [Helper] Enable the 4-bit wide bus for data transfer /// /// @return `true` on success, `false` otherwise. /// bool IOSDCard::enable4BitWideBus() { // Switch to the 4-bit bus (card) pinfo("Asking the card to use the 4-bit bus for data transfer."); if (this->driver->ACMD6(this->rca, IOSDBusConfig::BusWidth::k4Bit) != kIOReturnSuccess) { perr("Failed to issue the ACMD6 to switch to the 4-bit bus."); return false; } pinfo("The card will use the 4-bit bus for data transfer."); // Switch to the 4-bit bus (host) pinfo("Asking the host device to use the 4-bit bus for data transfer."); if (this->driver->setBusWidth(IOSDBusConfig::BusWidth::k4Bit) != kIOReturnSuccess) { perr("Failed to ask the host to switch to the 4-bit bus."); return false; } pinfo("The host device will use the 4-bit bus for data transfer."); return true; } /// /// [Helper] Enable the signal voltage for the UHS-I mode /// /// @param ocr The current operating condition register value /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_set_uhs_voltage()` defined in `core.c`. /// bool IOSDCard::enableUltraHighSpeedSignalVoltage(UInt32 ocr) { pinfo("Enabling the signal voltage for the UHS-I mode..."); // Tell the card to switch to 1.8V if (this->driver->CMD11() != kIOReturnSuccess) { perr("Failed to tell the card to switch to 1.8V."); return false; } // The card should put the CMD and DATA lines low // immediately after sending the response of CMD11 // Wait for 1ms and then check the line status IOSleep(1); // Since the driver has issued the CMD11, // if the driver fails to switch to 1.8V, // it must restart the power of the card. bool retVal = false; // Verify the line status // TODO: DATA LOW == DATA IDLE??? // bool status = false; // // if (this->driver->getHostDevice()->isCardDataLineBusy(status) != kIOReturnSuccess) // { // perr("Failed to retrieve the data line status."); // // goto cycle; // } // // if (status) // { // perr("The card should put the CMD and DATA lines low at this moment."); // // goto cycle; // } // Tell the host the switch to 1.8V if (this->driver->setUltraHighSpeedSignalVoltage() != kIOReturnSuccess) { perr("Failed to tell the host to switch to 1.8V."); goto cycle; } // Wait at least 1ms IOSleep(1); retVal = true; // If failed to switch to 1.8V, the card data lines are low // TODO: DATA LOW == DATA IDLE??? // if (this->driver->getHostDevice()->isCardDataLineBusy(status) != kIOReturnSuccess) // { // perr("Failed to retrieve the data line status."); // // goto cycle; // } // // if (status) // { // pinfo("The signal voltage has been enabled for the UHS-I mode."); // // retVal = true; // } // else // { // perr("Failed to enable the signal voltage for the UHS-I mode."); // } cycle: if (!retVal) { psoftassert(this->driver->powerCycle(ocr) == kIOReturnSuccess, "Failed to restart the power of the card."); } return retVal; } /// /// [Helper] Select the bus speed for the UHS-I mode /// /// @return The bus speed supported by both the card and the host. /// @note Port: This function replaces `sd_update_bus_speed_mode()` defined in `sd.c`. /// SwitchCaps::BusSpeed IOSDCard::selectUltraHighSpeedBusSpeed() { BitOptions hostCaps = this->driver->getHostDevice()->getCapabilities(); BitOptions cardCaps = this->switchCaps.sd3BusMode; if (hostCaps.contains(IOSDHostDevice::Capability::kUHSSDR104) && cardCaps.contains(SwitchCaps::BusMode::kModeUHSSDR104)) { pinfo("Will use the speed mode UHS-I SDR104."); return SwitchCaps::BusSpeed::kSpeedUHSSDR104; } if (hostCaps.contains(IOSDHostDevice::Capability::kUHSDDR50) && cardCaps.contains(SwitchCaps::BusMode::kModeUHSDDR50)) { pinfo("Will use the speed mode UHS-I DDR50."); return SwitchCaps::BusSpeed::kSpeedUHSDDR50; } if (hostCaps.contains(IOSDHostDevice::Capability::kUHSSDR50) && cardCaps.contains(SwitchCaps::BusMode::kModeUHSSDR50)) { pinfo("Will use the speed mode UHS-I SDR50."); return SwitchCaps::BusSpeed::kSpeedUHSSDR50; } if (hostCaps.contains(IOSDHostDevice::Capability::kUHSSDR25) && cardCaps.contains(SwitchCaps::BusMode::kModeUHSSDR25)) { pinfo("Will use the speed mode UHS-I SDR25."); return SwitchCaps::BusSpeed::kSpeedUHSSDR25; } if (hostCaps.contains(IOSDHostDevice::Capability::kUHSSDR12) && cardCaps.contains(SwitchCaps::BusMode::kModeUHSSDR12)) { pinfo("Will use the speed mode UHS-I SDR12."); return SwitchCaps::BusSpeed::kSpeedUHSSDR12; } pfatal("Should never reach at here. The host and/or card capabilities are invalid."); } /// /// [Helper] Set the driver strength for the UHS-I card /// /// @param busSpeed The bus speed /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `sd_select_driver_type()` defined in `sd.c`. /// @note This function is a part of the UHS-I card initialization routine `initUltraHighSpeedMode()`. /// bool IOSDCard::setUHSDriverType(SwitchCaps::BusSpeed busSpeed) { // TODO: NOT IMPLEMENTED YET // Note that Realtek's driver does not use this function. return true; } /// /// [Helper] Set the current limit for the UHS-I card /// /// @param busSpeed The bus speed /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `sd_set_current_limit()` defined in `sd.c`. /// @note This function is a part of the UHS-I card initialization routine `initUltraHighSpeedMode()`. /// bool IOSDCard::setUHSCurrentLimit(SwitchCaps::BusSpeed busSpeed) { // Current limit switch is only defined for SDR50, SDR104 and DDR50 modes // For other bus speed modes, we do not change the current limit if (Value::of(busSpeed).isNotOneOf(SwitchCaps::BusSpeed::kSpeedUHSSDR50, SwitchCaps::BusSpeed::kSpeedUHSSDR104, SwitchCaps::BusSpeed::kSpeedUHSDDR50)) { pinfo("No need to change the current limit."); return true; } // The host has different current capabilities when operating at different voltages // Get the maximum current supported by the host device UInt32 hostMaxCurrent = this->driver->getHostMaxCurrent(); UInt32 cardMaxCurrent = this->switchCaps.sd3MaxCurrent; // The new current limit UInt8 limit; if (hostMaxCurrent >= 800 && BitOptions(cardMaxCurrent).contains(SwitchCaps::MaxCurrent::kMaxCurrent800mA)) { limit = SwitchCaps::SetCurrentLimit::kCurrentLimit800mA; } else if (hostMaxCurrent >= 600 && BitOptions(cardMaxCurrent).contains(SwitchCaps::MaxCurrent::kMaxCurrent600mA)) { limit = SwitchCaps::SetCurrentLimit::kCurrentLimit600mA; } else if (hostMaxCurrent >= 400 && BitOptions(cardMaxCurrent).contains(SwitchCaps::MaxCurrent::kMaxCurrent400mA)) { limit = SwitchCaps::SetCurrentLimit::kCurrentLimit400mA; } else if (hostMaxCurrent >= 200 && BitOptions(cardMaxCurrent).contains(SwitchCaps::MaxCurrent::kMaxCurrent200mA)) { limit = SwitchCaps::SetCurrentLimit::kCurrentLimit200mA; } else { return true; } // Switch the current limit UInt8 status[64] = {}; if (this->driver->CMD6(1, 3, limit, status) != kIOReturnSuccess) { perr("Failed to switch the current limit."); return false; } // Verify the current limit if (((status[15] >> 4) & 0x0F) != limit) { perr("The new current limit is not the requested one."); return false; } return true; } /// /// [Helper] Set the bus speed for the UHS-I card /// /// @param busSpeed The bus speed /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `sd_set_bus_speed_mode()` defined in `sd.c`. /// @note This function is a part of the UHS-I card initialization routine `initUltraHighSpeedMode()`. /// bool IOSDCard::setUHSBusSpeedMode(SwitchCaps::BusSpeed busSpeed) { IOSDBusConfig::BusTiming timing; switch (busSpeed) { case SwitchCaps::BusSpeed::kSpeedUHSSDR104: { timing = IOSDBusConfig::BusTiming::kUHSSDR104; this->switchCaps.maxClockFrequencies.ultraHighSpeedMode = SwitchCaps::MaxClockFrequency::kClockUHSSDR104; break; } case SwitchCaps::BusSpeed::kSpeedUHSDDR50: { timing = IOSDBusConfig::BusTiming::kUHSDDR50; this->switchCaps.maxClockFrequencies.ultraHighSpeedMode = SwitchCaps::MaxClockFrequency::kClockUHSDDR50; break; } case SwitchCaps::BusSpeed::kSpeedUHSSDR50: { timing = IOSDBusConfig::BusTiming::kUHSSDR50; this->switchCaps.maxClockFrequencies.ultraHighSpeedMode = SwitchCaps::MaxClockFrequency::kClockUHSSDR50; break; } case SwitchCaps::BusSpeed::kSpeedUHSSDR25: { timing = IOSDBusConfig::BusTiming::kUHSSDR25; this->switchCaps.maxClockFrequencies.ultraHighSpeedMode = SwitchCaps::MaxClockFrequency::kClockUHSSDR25; break; } case SwitchCaps::BusSpeed::kSpeedUHSSDR12: { timing = IOSDBusConfig::BusTiming::kUHSSDR12; this->switchCaps.maxClockFrequencies.ultraHighSpeedMode = SwitchCaps::MaxClockFrequency::kClockUHSSDR12; break; } default: { perr("Detected an invalid bus speed for UHS-I card."); return false; } } // Tell the card to switch the bus speed UInt8 status[64] = {}; if (this->driver->CMD6(1, 0, busSpeed, status) != kIOReturnSuccess) { perr("Failed to issue the CMD6 to switch 1the bus speed."); return false; } // Verify the new bus speed if ((status[16] & 0x0F) != busSpeed) { perr("The new bus speed is not the one requested."); return false; } // Set the host-side timing if (this->driver->setBusTiming(timing) != kIOReturnSuccess) { perr("Failed to set the host-side timing."); return false; } // Set the host-side clock if (this->driver->setBusClock(this->switchCaps.maxClockFrequencies.ultraHighSpeedMode) != kIOReturnSuccess) { perr("Failed to set the host-side clock."); return false; } return true; } /// /// [Helper] Initialize the card at the default speed mode /// /// @param speedMode Set to `IOSDCard::SpeedMode::kDefaultSpeed` on return /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note This function is a wrapper of `IOSDCard::initDefaultSpeedMode()` to support the new fallback mechanism as of v0.9.7. /// @note The return value of this function is inherited from the caller `IOSDCard::initializeCard(ocr:speedMode:)`. /// @seealso `IOSDCard::initializeCard(ocr:speedMode:)` and `IOSDCard::initDefaultSpeedMode()`. /// IOReturn IOSDCard::initializeCardAtDefaultSpeedMode(SpeedMode& speedMode) { speedMode = SpeedMode::kDefaultSpeed; return this->initDefaultSpeedMode() ? kIOReturnSuccess : kIOReturnNotResponding; } /// /// [Helper] Initialize the card at the high speed mode /// /// @param speedMode Set to `IOSDCard::SpeedMode::kHighSpeed` on return /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note This function is a wrapper of `IOSDCard::initHighSpeedMode()` to support the new fallback mechanism as of v0.9.7. /// @note The return value of this function is inherited from the caller `IOSDCard::initializeCard(ocr:speedMode:)`. /// @seealso `IOSDCard::initializeCard(ocr:speedMode:)` and `IOSDCard::initHighSpeedMode()`. /// IOReturn IOSDCard::initializeCardAtHighSpeedMode(SpeedMode& speedMode) { speedMode = SpeedMode::kHighSpeed; return this->initHighSpeedMode() ? kIOReturnSuccess : kIOReturnNotResponding; } /// /// [Helper] Initialize the card at the ultra high speed mode /// /// @param speedMode Set to `IOSDCard::SpeedMode::kUltraHighSpeed` on return /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note This function is a wrapper of `IOSDCard::initUltraHighSpeedMode()` to support the new fallback mechanism as of v0.9.7. /// @note The return value of this function is inherited from the caller `IOSDCard::initializeCard(ocr:speedMode:)`. /// @seealso `IOSDCard::initializeCard(ocr:speedMode:)` and `IOSDCard::initUltraHighSpeedMode()`. /// IOReturn IOSDCard::initializeCardAtUltraHighSpeedMode(SpeedMode& speedMode) { speedMode = SpeedMode::kUltraHighSpeed; return this->initUltraHighSpeedMode() ? kIOReturnSuccess : kIOReturnNotResponding; } /// /// Initialize the card with the given OCR register value /// /// @param ocr The current operating condition register value /// @param speedMode The suggested speed mode (see below) /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note The given speed mode is treated as a hint and may be overridden by user configurations or the capability of the card. /// The caller should always invoke this function with the maximum speed mode (i.e. `IOSDCard::SpeedMode::kMaxSpeed`) at the beginning. /// If this function returns `kIOReturnNotResponding`, `speedMode` is set to the speed mode at which the card has failed to initialize. /// The caller may repeatedly invoke this function with a lower speed mode until one of the following scenarios occurs. /// (1) The function returns `kIOReturnSuccess`, indicating that the card has been initialized successfully. /// (2) The function returns `kIOReturnAborted`, indicating that the card failed to initialize thus the caller should abort the initialization process. /// (3) The function returns `kIOReturnNotResponding` with `speedMode` set to the minimum speed mode (i.e. `IOSDCard::SpeedMode::kMinSpeed`), /// indicating that the caller has tried all possible speed modes but the card still failed to initialize thus should abort the initialization process. /// The caller may use the return value of this function to implement a graceful fallback mechanism. /// @note Port: This function replaces `mmc_sd_init_card()` defined in `sd.c`. /// IOReturn IOSDCard::initializeCard(UInt32 ocr, SpeedMode& speedMode) { // =============================== // | BEGIN PORTED mmc_sd_get_cid | // =============================== // The initialization routine may change the OCR value UInt32 pocr = ocr; pinfo("Initializing the SD card with OCR = 0x%08x.", ocr); pinfo("The speed mode suggested by the host driver = %u.", speedMode); // Tell the card to go to the idle state if (this->driver->CMD0() != kIOReturnSuccess) { perr("Failed to tell the card to go back to the idle state."); return kIOReturnAborted; } pinfo("The card is now in the idle state."); // Check whether the card supports SD 2.0 if (this->driver->CMD8(ocr) == kIOReturnSuccess) { pinfo("Found a SD 2.0 compliant card."); ocr |= OCR::kCardCapacityStatus; } // Check whether the host supports the UHS-I mode // If so, we assume that the card also supports the UHS-I mode // and request the card to switch to 1.8V signal voltage // Later the card will return an OCR value indicating whether it supports the UHS-I mode if (this->driver->hostSupportsUltraHighSpeedMode()) { pinfo("The host supports UHS-I mode and will try to request the card to switch to 1.8V signal voltage."); ocr |= OCR::kRequest1d8V; } // Check whether users request to initialize the card at 3.3V if (UNLIKELY(UserConfigs::Card::InitAt3v3)) { pinfo("User requests to initialize the card at 3.3V. Will not request the card to switch to 1.8V."); ocr &= (~OCR::kRequest1d8V); } // Check whether the suggested speed mode is a lower one if (speedMode != SpeedMode::kUltraHighSpeed) { pinfo("The host driver suggests to initialize the card at a lower speed mode = %u.", speedMode); ocr &= (~OCR::kRequest1d8V); } // Check whether the host can supply more than 150mA at the current voltage level // If so, we must follow the specification to set the XPC bit if (this->driver->getHostMaxCurrent() > 150) { pinfo("The host can supply more than 150mA."); ocr |= OCR::kSDXCPowerControl; } // Send the new OCR value UInt32 rocr = 0; pinfo("Sending the new OCR value 0x%08x to start the card initialization process...", ocr); if (this->driver->ACMD41(ocr, rocr) != kIOReturnSuccess) { perr("Failed to send the new OCR value. The card initialization process will be aborted."); return kIOReturnAborted; } pinfo("OCR value returned from the card is 0x%08x.", rocr); // Check whether the card accepts the 1.8V signal voltage if (BitOptions(rocr).contains(OCR::kCardCapacityStatus | OCR::kAccepted1d8V)) { pinfo("The card has accepted the 1.8V signal voltage."); // Tell the card and the host to switch to 1.8V if (!this->enableUltraHighSpeedSignalVoltage(pocr)) { perr("Failed to switch the host and the card to 1.8V."); pinfo("Will try again and initialize the card at a lower speed mode.") return kIOReturnNotResponding; } pinfo("Both the host and the card has switched to the 1.8V signal voltage."); } // Fetch and parse the card identification data pinfo("Fetching the card identification data..."); if (this->driver->CMD2(this->cid) != kIOReturnSuccess) { perr("Failed to fetch the card identification data."); // Some cards may not respond to any command after being switched to 1.8V // We will gracefully try again and initialize the card at a lower speed mode // If the host driver is initializing the card at the standard speed mode, // it will abort the initialization sequence in `IOSDHostDriver::attachCardAtFrequency()`. return kIOReturnNotResponding; } pinfo("The card identification data has been fetched and decoded."); // =============================== // | END PORTED mmc_sd_get_cid | // =============================== // ================================= // | BEGIN PORTED mmc_sd_init_card | // ================================= // Ask the card to publish its relative address pinfo("Requesting the card relative address..."); if (this->driver->CMD3(this->rca) != kIOReturnSuccess) { perr("Failed to fetch the card relative address."); return kIOReturnAborted; } pinfo("The card relative address is 0x%08x.", this->rca); // Fetch the card specific data pinfo("Fetching the card specific data..."); if (this->driver->CMD9(this->rca, this->csd) != kIOReturnSuccess) { perr("Failed to fetch the card specific data."); return kIOReturnAborted; } pinfo("The card specific data has been fetched and decoded."); // Select the card: Will enter into the transfer state pinfo("Asking the card to enter into the transfer state..."); if (this->driver->CMD7(this->rca) != kIOReturnSuccess) { perr("Failed to select the card."); return kIOReturnAborted; } pinfo("The card is now in the transfer state."); // ================================== // | BEGIN PORTED mmc_sd_setup_card | // ================================== // Fetch and parse the SD configuration data from the card pinfo("Fetching the card configuration data..."); if (this->driver->ACMD51(this->rca, this->scr) != kIOReturnSuccess) { perr("Failed to fetch the SD configuration data."); return kIOReturnAborted; } pinfo("The card configuration data has been fetched and decoded."); // Fetch the SD status register value from the card pinfo("Fetching the SD status register value..."); if (this->driver->ACMD13(this->rca, this->ssr) != kIOReturnSuccess) { perr("Failed to fetch the SD status data."); return kIOReturnAborted; } pinfo("The SD status register value has been fetched."); // The Linux driver initializes the erase function here, // but our driver does not support this feature. // Fetch the switch information from the card pinfo("Fetching the switch capabilities from the card..."); if (!this->readSwitchCapabilities()) { perr("Failed to fetch the switch information from the card."); return kIOReturnAborted; } pinfo("The switch capabilities have been fetched."); // The Linux driver checks whether the card is already running under 1.8V. // Our driver detaches and powers off the card when the machine goes to sleep. // When the machines wakes up, the driver powers on the card and initializes it. // So the card is always power cycled, so it should never be running under 1.8V at this moment. // Please submit an issue if this is not true when you are testing this driver. // TODO: It seems that some newer cards do operate at 1.8V by default when they are powered on. BitOptions currentBusMode = this->switchCaps.sd3BusMode; if (currentBusMode.containsOneOf(SwitchCaps::BusMode::kModeUHSSDR50, SwitchCaps::BusMode::kModeUHSSDR104, SwitchCaps::BusMode::kModeUHSDDR50) && this->driver->getHostDevice()->getHostBusConfig().signalVoltage != IOSDBusConfig::SignalVoltage::k1d8V) { pinfo("The card is already operating at 1.8V but the host does not."); pinfo("Abort the initialization. Should never happen. Not implemented."); return kIOReturnAborted; } // Guard: Check whether the card supports the high speed mode if (this->scr.spec < SCR::Spec::kVersion1d1x) { pinfo("The card does not support SD 1.10+. High Speed mode is not supported."); return this->initializeCardAtDefaultSpeedMode(speedMode); } // Guard: Check whether the card supports switch functions if (!BitOptions(this->csd.cardCommandClasses).contains(CSD::CommandClass::kSwitch)) { pinfo("The card does not support switch functions. High Speed mode is not supported."); return this->initializeCardAtDefaultSpeedMode(speedMode); } // Guard: Check whether the host supports the high speed mode if (!this->driver->hostSupportsHighSpeedMode()) { pinfo("The host does not support the high speed mode."); return this->initializeCardAtDefaultSpeedMode(speedMode); } // Guard: Check the card switch functionality if (this->switchCaps.maxClockFrequencies.highSpeedMode == 0) { pinfo("The maximum clock frequency value for the high speed mode is zero."); return this->initializeCardAtDefaultSpeedMode(speedMode); } // Guard: Check whether the user requests to initialize the card at the default speed mode if (UNLIKELY(UserConfigs::Card::InitAtDefaultSpeed)) { pinfo("User requests to initialize the card at the default speed mode."); return this->initializeCardAtDefaultSpeedMode(speedMode); } // Guard: Check whether the host driver suggests to initialize the card at the default speed mode if (speedMode == SpeedMode::kDefaultSpeed) { pinfo("The host driver suggests to initialize the card at the default speed mode.") return this->initializeCardAtDefaultSpeedMode(speedMode); } // Guard: Check whether the card supports the UHS-I mode if (BitOptions(rocr).contains(OCR::kAccepted1d8V) && this->driver->hostSupportsUltraHighSpeedMode()) { pinfo("Both the host and the card support the ultra high speed mode."); do { // Guard: Check whether the user requests to initialize the card at the high speed mode if (UNLIKELY(UserConfigs::Card::InitAtHighSpeed)) { pinfo("User requests to initialize the card at the high speed mode."); break; } // Guard: Check whether the host driver suggests to initialize the card at the high speed mode if (speedMode == SpeedMode::kHighSpeed) { pinfo("The host driver suggests to initialize the card at the high speed mode."); break; } // Try to initialize the card at the fastest mode return this->initializeCardAtUltraHighSpeedMode(speedMode); } while (false); } // Guard: Tell the card to switch to the high speed mode pinfo("Asking the card to switch to the high speed mode..."); UInt8 status[64] = {}; if (this->driver->CMD6(1, 0, SwitchCaps::BusSpeed::kSpeedHighSpeed, status) != kIOReturnSuccess) { perr("Failed to issue the CMD6 while the card supports switch functions."); return kIOReturnAborted; } // Guard: Check the card status if ((status[16] & 0xF) == SwitchCaps::BusSpeed::kSpeedHighSpeed) { pinfo("The card has switched to the high speed mode."); return this->initializeCardAtHighSpeedMode(speedMode); } else { perr("The card fails to switch to the high speed mode. Will use the default speed mode."); return this->initializeCardAtDefaultSpeedMode(speedMode); } } // // MARK: - IOService Implementations // /// /// Start the SD card /// /// @param provider An instance of the host driver /// @return `true` on success, `false` otherwise. /// bool IOSDCard::start(IOService* provider) { // Start the super class if (!super::start(provider)) { perr("Failed to start the super class."); return false; } // Get the host driver this->driver = OSDynamicCast(IOSDHostDriver, provider); if (this->driver == nullptr) { perr("The provider is not a valid host driver."); return false; } this->driver->retain(); return true; } /// /// Stop the SD card /// /// @param provider An instance of the host driver /// void IOSDCard::stop(IOService* provider) { OSSafeReleaseNULL(this->driver); super::stop(provider); } <|start_filename|>RealtekCardReader/IOSDCard-CID.hpp<|end_filename|> // // IOSDCard-CID.hpp // RealtekCardReader // // Created by FireWolf on 12/24/21. // #ifndef IOSDCard_CID_hpp #define IOSDCard_CID_hpp #include "Utilities.hpp" /// Card identification data (16 bytes) struct PACKED CID { /// The manufacturer ID UInt8 manufacturer; /// The OEM application ID UInt16 oem; /// The product name SInt8 name[5]; /// The product revision (hardware) UInt8 hwrevision: 4; /// The product revision (firmware) UInt8 fwrevision: 4; /// The product serial number UInt32 serial; /// Reserved 4 bits UInt8 reserved: 4; /// Manufacturing date (year) UInt8 year: 8; /// Manufacturing date (month) UInt8 month: 4; /// CRC7 checksum and the end bit UInt8 end; /// Get the manufacturing year inline UInt32 getYear() const { return this->year + 2000; } /// Get a non-null vendor string inline const char* getVendorString() const { // CID List: https://www.cameramemoryspeed.com/sd-memory-card-faq/reading-sd-card-cid-serial-psn-internal-numbers/ switch (this->manufacturer) { case 0x01: { return "Panasonic"; } case 0x02: { return "Toshiba"; } case 0x03: { return "SanDisk"; } case 0x1b: { return "Samsung"; } case 0x1d: { return "ADATA"; } case 0x27: { return "Phison"; } case 0x28: { return "Lexar"; } case 0x31: { return "Silicon Power"; } case 0x41: { return "Kingston"; } case 0x74: { return "Transcend"; } case 0x76: { return "Patriot"; } case 0x82: { return "Sony"; } default: { return "Unknown"; } } } /// /// Decode from the given raw data /// /// @param data An array of 4 integers encoded in big endian /// @param pcid The parsed card identification data /// @return `true` on success, `false` otherwise. /// static bool decode(const UInt32* data, CID& pcid) { pcid.manufacturer = UNSTUFF_BITS(data, 120, 8); pcid.oem = UNSTUFF_BITS(data, 104, 16); pcid.name[0] = UNSTUFF_BITS(data, 96, 8); pcid.name[1] = UNSTUFF_BITS(data, 88, 8); pcid.name[2] = UNSTUFF_BITS(data, 80, 8); pcid.name[3] = UNSTUFF_BITS(data, 72, 8); pcid.name[4] = UNSTUFF_BITS(data, 64, 8); pcid.hwrevision = UNSTUFF_BITS(data, 60, 4); pcid.fwrevision = UNSTUFF_BITS(data, 56, 4); pcid.serial = UNSTUFF_BITS(data, 24, 32); pcid.year = UNSTUFF_BITS(data, 12, 8); pcid.month = UNSTUFF_BITS(data, 8, 4); return true; } /// Equatable IMP friend bool operator==(const CID& lhs, const CID& rhs) { return memcmp(&lhs, &rhs, sizeof(CID)) == 0; } friend bool operator!=(const CID& lhs, const CID& rhs) { return !(lhs == rhs); } /// Check whether the card identification data is empty inline bool isEmpty() const { auto uint64s = reinterpret_cast<const UInt64*>(this); return uint64s[0] == 0 && uint64s[1] == 0; } /// Reset the card identification data to zeros inline void reset() { auto uint64s = reinterpret_cast<UInt64*>(this); uint64s[0] = 0; uint64s[1] = 0; } }; static_assert(sizeof(CID) == 16, "CID should be 16 bytes long."); #endif /* IOSDCard_CID_hpp */ <|start_filename|>RealtekCardReader/IOSDCard.hpp<|end_filename|> // // IOSDCard.hpp // RealtekCardReader // // Created by FireWolf on 6/3/21. // #ifndef IOSDCard_hpp #define IOSDCard_hpp #include <IOKit/IOService.h> #include "IOSDCard-CID.hpp" #include "IOSDCard-CSD.hpp" #include "IOSDCard-OCR.hpp" #include "IOSDCard-SCR.hpp" #include "IOSDCard-SSR.hpp" #include "IOSDCard-SwitchCaps.hpp" #include "BitOptions.hpp" /// Forward declaration class IOSDHostDriver; /// IORegistry Keys static const char* kIOSDCardCharacteristics = "Card Characteristics"; static const char* kIOSDCardPresent = "Card Present"; static const char* kIOSDCardSpeedMode = "Card Speed Mode"; static const char* kIOSDCardInitFailures = "Card Init Failures"; /// Represents a generic SD(SC/HC/XC) card class IOSDCard: public IOService { // // MARK: - Constructors & Destructors // OSDeclareDefaultStructors(IOSDCard); using super = IOService; // // MARK: - Constants and Definitions // private: /// The specification table static const Pair<SPEC, const char*> kSpecTable[13]; public: /// /// Enumerates all possible speed modes /// /// @note The host driver provides a fallback mechanism so that cards do not work /// at a given speed mode will be initialized at the next lower speed mode. /// enum SpeedMode: UInt32 { // Supported modes kUltraHighSpeed = 2, kHighSpeed = 1, kDefaultSpeed = 0, // Speed ranges kMaxSpeed = kUltraHighSpeed, kMinSpeed = kDefaultSpeed, }; /// /// Get the next lower speed mode /// /// @param speedMode The current speed mode /// @return The next lower speed mode. /// @warning The caller should ensure that the given speed mode is not the lowest one. /// static inline SpeedMode nextLowerSpeedMode(SpeedMode speedMode) { return static_cast<SpeedMode>(speedMode - 1); } // // MARK: - Card Properties // private: /// The host driver IOSDHostDriver* driver; /// The card identification data CID cid; /// The card specification data CSD csd; /// SD configuration data SCR scr; /// SD status data SSR ssr; /// Switch capabilities SwitchCaps switchCaps; /// The card relative address UInt32 rca; // // MARK: - Query Card Properties // public: /// Get the card identification data inline const CID& getCID() const { return this->cid; } /// Get the card specification data inline const CSD& getCSD() const { return this->csd; } /// Get the SD configuration data inline const SCR& getSCR() const { return this->scr; } /// Get the SD status data inline const SSR& getSSR() const { return this->ssr; } /// Get the card relative address inline UInt32 getRCA() const { return this->rca; } /// Get the card type inline const char* getCardType() const { if (!this->csd.isBlockAddressed) { return "SDSC"; } if (!this->csd.hasExtendedCapacity) { return "SDHC"; } else { return "SDXC"; } } /// Get the specification version string inline const char* getSpecificationVersion() const { SPEC spec = this->scr.getCardSpecLevel(); for (const auto& entry : kSpecTable) { if (spec == entry.first) { return entry.second; } } return "Unknown"; } /// /// Get the card product name /// /// @param name A non-null buffer that can hold at least 8 bytes. /// @param length The buffer length /// @return `true` on success, `false` if the buffer is NULL or too small. /// inline bool getCardName(char* name, IOByteCount length) const { if (name == nullptr || length < 8) { return false; } bzero(name, length); memcpy(name, this->cid.name, sizeof(this->cid.name)); return true; } /// /// Get the card revision value /// /// @param revision A non-null buffer that can hold at least 8 bytes. /// @param length The buffer length /// @return `true` on success, `false` if the buffer is NULL or too small. /// inline bool getCardRevision(char* revision, IOByteCount length) const { if (revision == nullptr || length < 8) { return false; } bzero(revision, length); snprintf(revision, length, "%d.%d", this->cid.hwrevision, this->cid.fwrevision); return true; } /// /// Get the card manufacture date /// /// @param date A non-null buffer that can hold at least 8 bytes. /// @param length The buffer length /// @return `true` on success, `false` if the buffer is NULL or too small. /// inline bool getCardProductionDate(char* date, IOByteCount length) const { if (date == nullptr || length < 8) { return false; } bzero(date, length); snprintf(date, length, "%04d.%02d", this->cid.getYear(), this->cid.month); return true; } /// /// Get the card characteristics /// /// @return A dictionary that contains card characteristics which can be recognized by the System Profiler. /// @note The caller is responsible for releasing the returned dictionary. /// OSDictionaryPtr getCardCharacteristics() const; // // MARK: - Card Event Utilities // /// /// Type of a completion routine that is called once an asynchronous card event is processed by the host driver /// /// @param target An opaque client-supplied pointer (or the instance pointer for a C++ callback) /// @param parameter An opaque client-supplied parameter pointer /// @param status `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// using CompletionAction = void (*)(void* target, void* parameter, IOReturn status, OSDictionary* characteristics); /// /// Describe the completion routine to be called when the host driver has processed an asynchronous card event /// struct Completion { private: /// An opaque client-supplied pointer (or the instance pointer for a C++ callback) void* target; /// A non-null completion routine CompletionAction action; /// An opaque client-supplied parameter pointer void* parameter; public: /// /// Default constructor /// Completion() = default; /// /// Create a completion routine /// Completion(void* target, CompletionAction action, void* parameter = nullptr) : target(target), action(action), parameter(parameter) {} /// /// Invoke the completion routine /// /// @param status Pass `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// @warning This function prints a warning message if the action routine is null. /// inline void invoke(IOReturn status, OSDictionary* characteristics) { if (this->action != nullptr) { (*this->action)(this->target, this->parameter, status, characteristics); } else { pwarning("The action routine is null."); } } /// /// Reset the completion routine /// inline void reset() { this->target = nullptr; this->action = nullptr; this->parameter = nullptr; } /// /// Create a completion descriptor with the given member function /// /// @param self The instance pointer for the given C++ callback function /// @param function A C++ callback function /// @param parameter An optional opaque parameter pointer /// @return The completion routine. /// template <typename Function> static Completion withMemberFunction(OSObject* self, Function function, void* parameter = nullptr) { return { self, OSMemberFunctionCast(CompletionAction, self, function), parameter }; } }; /// /// Invoke the given completion routine /// /// @param completion A nullable completion routine /// @param status Pass `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// @note This function is a noop if the given completion is null. /// static inline void complete(Completion* completion, IOReturn status, OSDictionary* characteristics = nullptr) { if (completion != nullptr) { completion->invoke(status, characteristics); } } /// /// Type of the card event options /// using EventOptions = BitOptions<UInt32>; /// /// Enumerate all card event options that can be passed to the handler at the host driver layer /// enum EventOption: UInt32 { /// Indicate that the card event handler is invoked by the interrupt service routine kInterruptContext = 0, /// Indicate that the card event handler is invoked by the power management routine kPowerManagementContext = 1, }; // // MARK: - Card Initialization Process // private: /// /// [Helper] Initialize the card with Default Speed Mode enabled /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces the default speed portion of `mmc_sd_init_card()` defined in `sd.c`. /// bool initDefaultSpeedMode(); /// /// [Helper] Initialize the card with High Speed Mode enabled /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces the high speed portion of `mmc_sd_init_card()` defined in `sd.c`. /// bool initHighSpeedMode(); /// /// [Helper] Initialize the card with UHS-I Mode enabled /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_sd_init_uhs_card()` defined in `sd.c`. /// bool initUltraHighSpeedMode(); /// /// [Helper] Read the card switch capabilities /// /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_read_switch()` defined in `sd.c`. /// bool readSwitchCapabilities(); /// /// [Helper] Enable the 4-bit wide bus for data transfer /// /// @return `true` on success, `false` otherwise. /// bool enable4BitWideBus(); /// /// [Helper] Enable the signal voltage for the UHS-I mode /// /// @param ocr The current operating condition register value /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `mmc_set_uhs_voltage()` defined in `core.c`. /// bool enableUltraHighSpeedSignalVoltage(UInt32 ocr); /// /// [Helper] Select the bus speed for the UHS-I mode /// /// @return The bus speed supported by both the card and the host. /// @note Port: This function replaces `sd_update_bus_speed_mode()` defined in `sd.c`. /// SwitchCaps::BusSpeed selectUltraHighSpeedBusSpeed(); /// /// [Helper] Set the driver strength for the UHS-I card /// /// @param busSpeed The bus speed /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `sd_select_driver_type()` defined in `sd.c`. /// @note This function is a part of the UHS-I card initialization routine `initUltraHighSpeedMode()`. /// bool setUHSDriverType(SwitchCaps::BusSpeed busSpeed); /// /// [Helper] Set the current limit for the UHS-I card /// /// @param busSpeed The bus speed /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `sd_set_current_limit()` defined in `sd.c`. /// @note This function is a part of the UHS-I card initialization routine `initUltraHighSpeedMode()`. /// bool setUHSCurrentLimit(SwitchCaps::BusSpeed busSpeed); /// /// [Helper] Set the bus speed for the UHS-I card /// /// @param busSpeed The bus speed /// @return `true` on success, `false` otherwise. /// @note Port: This function replaces `sd_set_bus_speed_mode()` defined in `sd.c`. /// @note This function is a part of the UHS-I card initialization routine `initUltraHighSpeedMode()`. /// bool setUHSBusSpeedMode(SwitchCaps::BusSpeed busSpeed); /// /// [Helper] Initialize the card at the default speed mode /// /// @param speedMode Set to `IOSDCard::SpeedMode::kDefaultSpeed` on return /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note This function is a wrapper of `IOSDCard::initDefaultSpeedMode()` to support the new fallback mechanism as of v0.9.7. /// @note The return value of this function is inherited from the caller `IOSDCard::initializeCard(ocr:speedMode:)`. /// @seealso `IOSDCard::initializeCard(ocr:speedMode:)` and `IOSDCard::initDefaultSpeedMode()`. /// IOReturn initializeCardAtDefaultSpeedMode(SpeedMode& speedMode); /// /// [Helper] Initialize the card at the high speed mode /// /// @param speedMode Set to `IOSDCard::SpeedMode::kHighSpeed` on return /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note This function is a wrapper of `IOSDCard::initHighSpeedMode()` to support the new fallback mechanism as of v0.9.7. /// @note The return value of this function is inherited from the caller `IOSDCard::initializeCard(ocr:speedMode:)`. /// @seealso `IOSDCard::initializeCard(ocr:speedMode:)` and `IOSDCard::initHighSpeedMode()`. /// IOReturn initializeCardAtHighSpeedMode(SpeedMode& speedMode); /// /// [Helper] Initialize the card at the ultra high speed mode /// /// @param speedMode Set to `IOSDCard::SpeedMode::kUltraHighSpeed` on return /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note This function is a wrapper of `IOSDCard::initUltraHighSpeedMode()` to support the new fallback mechanism as of v0.9.7. /// @note The return value of this function is inherited from the caller `IOSDCard::initializeCard(ocr:speedMode:)`. /// @seealso `IOSDCard::initializeCard(ocr:speedMode:)` and `IOSDCard::initUltraHighSpeedMode()`. /// IOReturn initializeCardAtUltraHighSpeedMode(SpeedMode& speedMode); public: /// /// Initialize the card with the given OCR register value /// /// @param ocr The current operating condition register value /// @param speedMode The suggested speed mode (see below) /// @return `kIOReturnSuccess` on success, /// `kIOReturnNotResponding` if the host driver should invoke this function again to initialize the card at a lower speed mode, /// `kIOReturnAborted` if the host driver should abort the initialization of the attached card. /// @note The given speed mode is treated as a hint and may be overridden by user configurations or the capability of the card. /// The caller should always invoke this function with the maximum speed mode (i.e. `IOSDCard::SpeedMode::kMaxSpeed`) at the beginning. /// If this function returns `kIOReturnNotResponding`, `speedMode` is set to the speed mode at which the card has failed to initialize. /// The caller may repeatedly invoke this function with a lower speed mode until one of the following scenarios occurs. /// (1) The function returns `kIOReturnSuccess`, indicating that the card has been initialized successfully. /// (2) The function returns `kIOReturnAborted`, indicating that the card failed to initialize thus the caller should abort the initialization process. /// (3) The function returns `kIOReturnNotResponding` with `speedMode` set to the minimum speed mode (i.e. `IOSDCard::SpeedMode::kMinSpeed`), /// indicating that the caller has tried all possible speed modes but the card still failed to initialize thus should abort the initialization process. /// The caller may use the return value of this function to implement a graceful fallback mechanism. /// @note Port: This function replaces `mmc_sd_init_card()` defined in `sd.c`. /// IOReturn initializeCard(UInt32 ocr, SpeedMode& speedMode); // // MARK: - IOService Implementations // public: /// /// Start the SD card /// /// @param provider An instance of the host driver /// @return `true` on success, `false` otherwise. /// bool start(IOService* provider) override; /// /// Stop the SD card /// /// @param provider An instance of the host driver /// void stop(IOService* provider) override; }; #endif /* IOSDCard_hpp */ <|start_filename|>RealtekCardReader/IOSDCard-OCR.hpp<|end_filename|> // // IOSDCard-OCR.hpp // RealtekCardReader // // Created by FireWolf on 12/24/21. // #ifndef IOSDCard_OCR_hpp #define IOSDCard_OCR_hpp #include <libkern/OSTypes.h> /// Operating condition register value struct OCR { /// Register value as a place holder UInt32 value; /// Bit 24 is set if the host requests the card to switch to 1.8V static constexpr UInt32 kRequest1d8V = 1 << 24; /// Bit 24 is set if the card accepts 1.8V switching static constexpr UInt32 kAccepted1d8V = 1 << 24; /// Bit 28 is set if the host can supply more than 150mA static constexpr UInt32 kSDXCPowerControl = 1 << 28; /// Bit 30 is set if the card is SDHC/SDXC and clear if the card is SDSC static constexpr UInt32 kCardCapacityStatus = 1 << 30; }; #endif /* IOSDCard_OCR_hpp */ <|start_filename|>RealtekCardReader/IOSDCard-SCR.hpp<|end_filename|> // // IOSDCard-SCR.hpp // RealtekCardReader // // Created by FireWolf on 12/24/21. // #ifndef IOSDCard_SCR_hpp #define IOSDCard_SCR_hpp #include "BitOptions.hpp" #include "Utilities.hpp" /// Card specification level struct PACKED SPEC { UInt8 spec, spec3, spec4, spec5; friend bool operator==(const SPEC& lhs, const SPEC& rhs) { return *reinterpret_cast<const UInt32*>(&lhs) == *reinterpret_cast<const UInt32*>(&rhs); } }; /// SD configuration register value (8 bytes) struct PACKED SCR { /// The structure version UInt8 version: 4; /// SD card specification version UInt8 spec: 4; enum Spec { /// SD Specification 1.0 - 1.01 kVersion1x = 0, /// SD Specification 1.10 kVersion1d1x = 1, /// SD Specification 2.00 - 3.0X kVersion2x = 2, }; /// The data status after erase UInt8 dataStatusAfterErase: 1; /// The security specification version UInt8 security: 3; /// The bus widths supported by the card (Bit 0: 1 bit, Bit 2: 4 bits) UInt8 busWidths: 4; enum BusWidth { k1Bit = 1 << 0, k4Bit = 1 << 2, }; /// SD card specification version 3.00+ UInt8 spec3: 1; /// Extended security support UInt8 extendedSecurity: 4; /// SD card specification version 4.00+ UInt8 spec4: 1; /// SD card specification version 5.00+ UInt8 spec5: 4; /// Reserved 2 bits UInt8 reserved0: 2; /// Supported commands (CMD58/59) bool supportsCMD5859: 1; /// Supported commands (CMD48/49) bool supportsCMD4849: 1; /// Supported commands (CMD23) bool supportsCMD23: 1; /// Supported commands (CMD20) bool supportsCMD20: 1; /// Reserved 32 bits for manufacturer usage UInt32 reserved1; /// /// Extract the card specification level from the SCR register value /// /// @return The card specification level /// inline SPEC getCardSpecLevel() const { return { this->spec, this->spec3, this->spec4, this->spec5 }; } /// /// Decode from the given raw data /// /// @param data An array of 2 integers encoded in big endian /// @param pscr The parsed SD configuration register value /// @return `true` on success, `false` otherwise. /// static bool decode(const UInt8* data, SCR& pscr) { pscr.version = (data[0] & 0xF0) >> 4; if (pscr.version != 0) { printf("Unrecogized SCR struct version 0x%02x.\n", pscr.version); return false; } pscr.busWidths = data[1] & 0x0F; if (!BitOptions<UInt32>(pscr.busWidths).contains(BusWidth::k1Bit) || !BitOptions<UInt32>(pscr.busWidths).contains(BusWidth::k4Bit)) { printf("All cards should set at least bit 0 and bit 2 in the bus widths field (= 0x%x).\n", pscr.busWidths); return false; } pscr.spec = data[0] & 0x0F; pscr.dataStatusAfterErase = (data[1] & 0x80) >> 7; pscr.security = (data[1] & 0x70) >> 4; pscr.spec3 = (data[2] & 0x80) >> 7; pscr.extendedSecurity = (data[2] & 0x78) >> 3; pscr.spec4 = (data[2] & 0x04) >> 2; pscr.spec5 = (data[2] & 0x03) << 2; pscr.spec5 |= (data[3] & 0xC0) >> 6; pscr.supportsCMD5859 = (data[3] & 0x0F) >> 3; pscr.supportsCMD4849 = (data[3] & 0x0F) >> 2; pscr.supportsCMD23 = (data[3] & 0x0F) >> 1; pscr.supportsCMD20 = (data[3] & 0x0F) >> 0; return true; } }; static_assert(sizeof(SPEC) == sizeof(UInt32), "SPEC should be 4 bytes long."); static_assert(sizeof(SCR) == 8, "SCR should be 8 bytes long."); #endif /* IOSDCard_SCR_hpp */ <|start_filename|>RealtekCardReader/IOSDHostDevice.cpp<|end_filename|> // // IOSDHostDevice.cpp // RealtekCardReader // // Created by FireWolf on 6/5/21. // #include "IOSDHostDevice.hpp" #include "IOSDHostDriver.hpp" // // MARK: - Meta Class Definitions // OSDefineMetaClassAndAbstractStructors(IOSDHostDevice, IOService); // // MARK: - SD Request Processors // /// /// Preprocess the given SD command request /// /// @param request A SD command request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `sdmmc_pre_req()` defined in `rtsx_pci_sdmmc.c`. /// IOReturn IOSDHostDevice::preprocessRequest(IOSDHostRequest& request) { return kIOReturnSuccess; } /// /// Postprocess the given SD command request /// /// @param request A SD command request /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `sdmmc_post_req()` defined in `rtsx_pci_sdmmc.c`. /// IOReturn IOSDHostDevice::postprocessRequest(IOSDHostRequest& request) { return kIOReturnSuccess; } // // MARK: - Card Events Callbacks // /// /// [Completion] Notify the host device when the host driver has processed a card insertion event /// /// @param parameter An opaque client-supplied parameter pointer /// @param status `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// void IOSDHostDevice::onSDCardInsertedCompletion(void* parameter, IOReturn status, OSDictionary* characteristics) { pinfo("The card insertion event has been processed. Result = 0x%08x.", status); // Publish the card characteristics if (status == kIOReturnSuccess && characteristics != nullptr) { this->setProperty(kIOSDCardCharacteristics, characteristics); pinfo("The card characteristics have been published."); } // Invoke the completion routine supplied by the controller IOSDCard::complete(reinterpret_cast<IOSDCard::Completion*>(parameter), status, characteristics); } /// /// [Completion] Notify the host device when the host driver has processed a card removal event /// /// @param parameter An opaque client-supplied parameter pointer /// @param status `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// void IOSDHostDevice::onSDCardRemovedCompletion(void* parameter, IOReturn status, OSDictionary* characteristics) { pinfo("The card removal event has been processed. Result = 0x%08x.", status); // Remove the card characteristics this->removeProperty(kIOSDCardCharacteristics); // Invoke the completion routine supplied by the controller IOSDCard::complete(reinterpret_cast<IOSDCard::Completion*>(parameter), status, characteristics); } /// /// [UPCALL] Notify the host device when a SD card is inserted /// /// @param completion A nullable completion routine to be invoked when the card is attached /// @param options An optional value passed to the host driver /// @note This callback function runs in a gated context provided by the underlying card reader controller. /// The host device should implement this function without any blocking operations. /// A default implementation that notifies the host driver is provided. /// void IOSDHostDevice::onSDCardInsertedGated(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { auto chainedCompletion = IOSDCard::Completion::withMemberFunction(this, &IOSDHostDevice::onSDCardInsertedCompletion, completion); passert(this->driver != nullptr, "The host driver should not be null."); this->driver->onSDCardInsertedGated(&chainedCompletion, options); this->setProperty(kIOSDCardPresent, true); } /// /// [UPCALL] Notify the host device when a SD card is removed /// /// @param completion A nullable completion routine to be invoked when the card is attached /// @param options An optional value passed to the host driver /// @note This callback function runs in a gated context provided by the underlying card reader controller. /// The host device should implement this function without any blocking operations. /// A default implementation that notifies the host driver is provided. /// void IOSDHostDevice::onSDCardRemovedGated(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { auto chainedCompletion = IOSDCard::Completion::withMemberFunction(this, &IOSDHostDevice::onSDCardRemovedCompletion, completion); passert(this->driver != nullptr, "The host driver should not be null."); this->driver->onSDCardRemovedGated(&chainedCompletion, options); this->setProperty(kIOSDCardPresent, false); } // // MARK: - IOService Implementation // /// /// Initialize the host device /// /// @param dictionary A nullable matching dictionary /// @return `true` on success, `false` otherwise. /// bool IOSDHostDevice::init(OSDictionary* dictionary) { if (!super::init(dictionary)) { return false; } this->setProperty(kIOSDCardPresent, false); return true; } <|start_filename|>RealtekCardReader/RealtekRTS8411SeriesController.cpp<|end_filename|> // // RealtekRTS8411SeriesController.cpp // RealtekCardReader // // Created by FireWolf on 6/20/21. // #include "RealtekRTS8411SeriesController.hpp" // // MARK: - Meta Class Definitions // OSDefineMetaClassAndAbstractStructors(RealtekRTS8411SeriesController, RealtekPCICardReaderController); // // MARK: - LED Management // /// /// Turn on the LED /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `turn_on_led()` defined in `struct pcr_ops`. /// The base controller class implements this function by changing the value of `GPIO_CTL`. /// RTS5209, 5260, 5286, 5287 and 5289 controllers must override this function. /// IOReturn RealtekRTS8411SeriesController::turnOnLED() { using namespace RTSX::PCR::Chip; return this->writeChipRegister(CARD::rGPIO, CARD::GPIO::kLEDMask, CARD::GPIO::kLEDOn); } /// /// Turn off the LED /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `turn_off_led()` defined in `struct pcr_ops`. /// The base controller class implements this function by changing the value of `GPIO_CTL`. /// RTS5209, 5260, 5286, 5287 and 5289 controllers must override this function. /// IOReturn RealtekRTS8411SeriesController::turnOffLED() { using namespace RTSX::PCR::Chip; return this->writeChipRegister(CARD::rGPIO, CARD::GPIO::kLEDMask, CARD::GPIO::kLEDOff); } /// /// Enable LED blinking /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `enable_auto_blink()` defined in `struct pcr_ops`. /// The base controller class implements this function by changing the value of `OLT_LED_CTL`. /// RTS5209, 5286, 5287 and 5289 controllers must override this function. /// IOReturn RealtekRTS8411SeriesController::enableLEDBlinking() { using namespace RTSX::PCR::Chip; return this->writeChipRegister(CARD::rBLINK, 0xFF, 0x0D); } /// /// Disable LED blinking /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `enable_auto_blink()` defined in `struct pcr_ops`. /// The base controller class implements this function by changing the value of `OLT_LED_CTL`. /// RTS5209, 5286, 5287 and 5289 controllers must override this function. /// IOReturn RealtekRTS8411SeriesController::disableLEDBlinking() { using namespace RTSX::PCR::Chip; return this->writeChipRegister(CARD::rBLINK, 0x08, 0x00); } // // MARK: - Card Power Management // /// /// Power on the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_pci_card_power_on()` defined in `rtsx_psr.c`. /// IOReturn RealtekRTS8411SeriesController::powerOnCard() { using namespace RTSX::PCR::Chip; pinfo("Powering on the card partially (5%%)..."); const ChipRegValuePair ppairs[] = { { CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPower5PercentOn }, { LDO::rCTL, LDO::CTL::kBppLDOMask, LDO::CTL::kBppLDOSuspend }, }; IOReturn retVal = this->transferWriteRegisterCommands(SimpleRegValuePairs(ppairs)); if (retVal != kIOReturnSuccess) { perr("Failed to power on the card partially (5%%). Error = 0x%x.", retVal); return retVal; } IOSleep(5); pinfo("Powering on the card partially (10%%)..."); retVal = this->writeChipRegister(CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPower10PercentOn); if (retVal != kIOReturnSuccess) { perr("Failed to power on the card partially (10%%). Error = 0x%x.", retVal); return retVal; } IOSleep(5); pinfo("Powering on the card partially (15%%)..."); retVal = this->writeChipRegister(CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPower15PercentOn); if (retVal != kIOReturnSuccess) { perr("Failed to power on the card partially (15%%). Error = 0x%x.", retVal); return retVal; } IOSleep(5); pinfo("Powering on the card fully..."); const ChipRegValuePair fpairs[] = { { CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPowerOn }, { LDO::rCTL, LDO::CTL::kBppLDOMask, LDO::CTL::kBppLDOOn }, }; retVal = this->writeChipRegisters(SimpleRegValuePairs(fpairs)); if (retVal != kIOReturnSuccess) { perr("Failed to fully power on the card. Error = 0x%x.", retVal); return retVal; } pinfo("The card power is fully on."); return kIOReturnSuccess; } /// /// Power off the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_pci_card_power_off()` defined in `rtsx_psr.c`. /// IOReturn RealtekRTS8411SeriesController::powerOffCard() { using namespace RTSX::PCR::Chip; const ChipRegValuePair pairs[] = { { CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPowerOff }, { LDO::rCTL, LDO::CTL::kBppLDOMask, LDO::CTL::kBppLDOSuspend }, }; return this->writeChipRegisters(SimpleRegValuePairs(pairs)); } /// /// [Helper, Common] Switch to the given output voltage /// /// @param outputVoltage The new output voltage /// @param shift Shift `kBppRegTuned18` by the given value /// @param asic The ASIC value for the 1.8V output voltage /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtl8411_do_switch_output_voltage()` defined in `rts8411.c`. /// IOReturn RealtekRTS8411SeriesController::switchOutputVoltage(OutputVoltage outputVoltage, UInt8 shift, UInt8 asic) { using namespace RTSX::PCR::Chip; UInt8 selector; UInt8 mask = (LDO::CTL::kBppTuned18 << shift) | LDO::CTL::kBppPadMask; UInt8 value; if (outputVoltage == OutputVoltage::k3d3V) { selector = this->parameters.sd30DriveSelector3d3V; value = (LDO::CTL::kBppAsic3V3 << shift) | LDO::CTL::kBppPad3V3; } else { selector = this->parameters.sd30DriveSelector1d8V; value = (asic << shift) | LDO::CTL::kBppPad1V8; } const ChipRegValuePair pairs[] = { { CARD::SD30::DRVSEL::rCFG, 0x07, selector }, { LDO::rCTL, mask, value }, }; return this->writeChipRegisters(SimpleRegValuePairs(pairs)); } /// /// Switch to the given output voltage /// /// @param outputVoltage The new output voltage /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_pci_switch_output_voltage()` defined in `rtsx_psr.c`. /// @note Port: This function replaces `rtl8411_switch_output_voltage()` definde in `rts8411.c`. /// RTS5286 controller must override this function and provide the correct shift and ASIC values. /// IOReturn RealtekRTS8411SeriesController::switchOutputVoltage(OutputVoltage outputVoltage) { using namespace RTSX::PCR::Chip; return this->switchOutputVoltage(outputVoltage, LDO::CTL::kBppTuned18Shift_8411, LDO::CTL::kBppAsic1V8); } // // MARK: - Card Detection and Write Protection // /// /// Check whether a card is present /// /// @return `true` if a card exists, `false` otherwise. /// @note Port: This function replaces `rtsx_pci_card_exist()` and `cd_deglitch()` defined in `rtsx_psr.c`. /// @warning: This function supports SD cards only. /// bool RealtekRTS8411SeriesController::isCardPresent() { using namespace RTSX::PCR::Chip; if (!super::isCardPresent()) { const ChipRegValuePair pairs[] = { // Enable the card { CARD::rPADCTL, CARD::PADCTL::kDisableMask, CARD::PADCTL::kEnableAll }, // Enable the card interrupt { EFUSE::rCONTENT, 0xE0, 0x00 }, }; psoftassert(this->writeChipRegisters(SimpleRegValuePairs(pairs)) == kIOReturnSuccess, "Failed to enable the card."); return false; } psoftassert(this->writeChipRegister(CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPower5PercentOn) == kIOReturnSuccess, "Failed to power on the card partially (5%%)."); IOSleep(100); bool present = super::isCardPresent(); psoftassert(this->writeChipRegister(CARD::rPWRCTRL, CARD::PWRCTRL::kBppPowerMask, CARD::PWRCTRL::kBppPowerOff) == kIOReturnSuccess, "Failed to power off the card."); if (present) { // Disable the MS card interrupts const ChipRegValuePair pairs[] = { { EFUSE::rCONTENT, 0xE0, 0x80 }, { CARD::rPADCTL, CARD::PADCTL::kDisableMask, CARD::PADCTL::kEnableSD } }; psoftassert(this->writeChipRegisters(SimpleRegValuePairs(pairs)) == kIOReturnSuccess, "Disable the MS card interrupt."); } return present; } // // MARK: - Card Clock Configurations // /// /// Convert the given SSC clock to the divider N /// /// @param clock The SSC clock in MHz /// @return The divider N. /// @note Port: This function replaces `conv_clk_and_div_n()` defined in `rtsx_psr.c`. /// RTL8411 series controllers must override this function. /// UInt32 RealtekRTS8411SeriesController::sscClock2DividerN(UInt32 clock) { return clock * 4 / 5 - 2; } /// /// Convert the given divider N back to the SSC clock /// /// @param n The divider N /// @return The SSC clock in MHz. /// @note Port: This function replaces `conv_clk_and_div_n()` defined in `rtsx_psr.c`. /// RTL8411 series controllers must override this function. /// UInt32 RealtekRTS8411SeriesController::dividerN2SSCClock(UInt32 n) { return (n + 2) * 5 / 4; } // // MARK: - Power Management // /// /// Power down the controller forcedly /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_base_force_power_down()` defined in `rtsx_psr.c` and `*_force_power_down()` defined in each controller file. /// IOReturn RealtekRTS8411SeriesController::forcePowerDown() { return this->writeChipRegister(RTSX::PCR::Chip::rFPDCTL, 0x07, 0x07); } // // MARK: - Hardware Initialization and Configuration // /// /// Get the IC revision /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `*_get_ic_version()` defined in each controller file. /// IOReturn RealtekRTS8411SeriesController::getRevision(Revision& revision) { pinfo("Fetching the chip revision..."); UInt8 value; IOReturn retVal = this->readChipRegister(RTSX::PCR::Chip::rSYSVER, value); if (retVal != kIOReturnSuccess) { perr("Failed to fetch the chip revision. Error = 0x%x.", retVal); return retVal; } revision = Revision::parse(value & 0x0F); pinfo("Chip revision has been fetched: Rev %s.", revision.stringify()); return kIOReturnSuccess; } /// /// Initialize hardware-specific parameters /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `*_init_params()` defined in each controller file. /// @note Port: This function replaces `rtl8411_init_common_params()` defined in `rts8411.c`. /// Concrete controllers must override and extend this function to set the pull control tables. /// IOReturn RealtekRTS8411SeriesController::initParameters() { pinfo("Initializing the device-specific parameters..."); IOReturn retVal = this->getRevision(this->parameters.revision); if (retVal != kIOReturnSuccess) { perr("Failed to get the IC revision. Error = 0x%x.", retVal); return retVal; } this->parameters.numSlots = 2; this->parameters.caps.supportsSDSDR50 = true; this->parameters.caps.supportsSDSDR104 = true; this->parameters.isSocketReversed = false; this->parameters.cardDriveSelector = RTSX::PCR::Chip::CARD::DRVSEL::kDefault_8411; this->parameters.sd30DriveSelector1d8V = RTSX::PCR::Chip::CARD::SD30::DRVSEL::CFG::kDriverTypeB; this->parameters.sd30DriveSelector3d3V = RTSX::PCR::Chip::CARD::SD30::DRVSEL::CFG::kDriverTypeD; this->parameters.initialTxClockPhase = {23, 7, 14}; this->parameters.initialRxClockPhase = {4, 3, 10}; this->parameters.ocp.enable = false; this->parameters.pm.isASPML1Enabled = true; pinfo("Device-specific parameters have been initialized."); return kIOReturnSuccess; } /// /// Initialize vendor-specific parameters /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `fetch_vendor_settings()` defined in the `pcr->ops`. /// @note Port: This function replaces `rtl8411_fetch_vendor_settings()` defined in `rts8411.c`. /// RTS5287 controller must override this function. /// IOReturn RealtekRTS8411SeriesController::initVendorSpecificParameters() { pinfo("Initializing the vendor-specific parameters..."); // PCR Config 1 UInt32 regVal = this->device->configRead32(RTSX::PCR::kSREG1); pinfo("PCR Config 1 = 0x%08x.", regVal); if (!this->vsIsRegisterValueValid(regVal)) { perr("Vendor settings are invalid."); return kIOReturnError; } this->parameters.pm.isASPML1Enabled = this->vsIsASPML1Enabled(regVal); this->parameters.sd30DriveSelector1d8V = this->vsMapDriveSelector(this->vsGetSD30DriveSelector1d8V(regVal)); this->parameters.cardDriveSelector &= 0x3F; this->parameters.cardDriveSelector |= this->vsGetCardDriveSelector(regVal); pinfo("PCR CFG1: RegVal = 0x%08x.", regVal); pinfo("PCR CFG1: ASPM L1 Enabled: %s.", YESNO(this->parameters.pm.isASPML1Enabled)); pinfo("PCR CFG1: SD30 Drive Selector (1.8V) = %d.", this->parameters.sd30DriveSelector1d8V); pinfo("PCR CFG1: SD Card Drive Selector = 0x%x.", this->parameters.cardDriveSelector); // PCR Config 3 regVal = this->device->configRead8(RTSX::PCR::kSREG3); pinfo("PCR Config 3 = 0x%08x.", regVal); this->parameters.sd30DriveSelector3d3V = this->vsGetSD30DriveSelector3d3V(regVal); pinfo("PCR CFG3: RegVal = 0x%08x.", regVal); pinfo("PCR CFG3: SD30 Drive Selector (3.3V) = %d.", this->parameters.sd30DriveSelector3d3V); pinfo("Vendor-specific parameters have been initialized."); return kIOReturnSuccess; } /// /// Initialize the hardware (Extra Part) /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `extra_init_hw()` defined in defined in the `pcr->ops`. /// @note Port: This function replaces `rtl8411_extra_init_hw()` defined in `rts8411.c`. /// RTS5287 controller must override this function. /// IOReturn RealtekRTS8411SeriesController::initHardwareExtra() { using namespace RTSX::PCR::Chip; const ChipRegValuePair pairs[] = { // Set the initial driving selector { CARD::SD30::DRVSEL::rCFG, 0xFF, this->parameters.sd30DriveSelector3d3V }, // Enable the card { CARD::rPADCTL, CARD::PADCTL::kDisableMask | CARD::PADCTL::kAutoDisable, CARD::PADCTL::kEnableAll }, }; return this->transferWriteRegisterCommands(SimpleRegValuePairs(pairs)); } <|start_filename|>RealtekCardReader/IOSDCardEventSource.cpp<|end_filename|> // // IOSDCardEventSource.cpp // RealtekCardReader // // Created by FireWolf on 6/9/21. // #include "IOSDCardEventSource.hpp" #include "Debug.hpp" // // MARK: - Meta Class Definitions // OSDefineMetaClassAndStructors(IOSDCardEventSource, IOEventSource); /// /// Check whether an action needs to perform to handle the card event /// /// @return `false` always. The owner must explictly invoke `IOSDCardEventSource::enable()` to trigger another action. /// bool IOSDCardEventSource::checkForWork() { pinfo("The card event source is invoked by the processor work loop."); if (this->action == nullptr) { perr("Detected inconsistency: The action routine should never be null."); return false; } if (!this->enabled) { pinfo("The event source is disabled."); return false; } // Acknowledge the card event super::disable(); pinfo("Processing the card event..."); (*reinterpret_cast<Action>(this->action))(this->owner, &this->completion, this->options); pinfo("The card event has been processed."); return false; } /// /// Enable the event source /// /// @param completion A nullable completion routine to be invoked when the card event has been processed /// @param options An optional value passed to the host driver /// void IOSDCardEventSource::enable(IOSDCard::Completion* completion, IOSDCard::EventOptions options) { super::enable(); if (completion != nullptr) { this->completion = *completion; } this->options = options; } /// /// Disable the event source /// void IOSDCardEventSource::disable() { super::disable(); this->completion.reset(); } /// /// Create a card event source with the given action /// /// @param owner Owner of the returned instance; the first parameter of the action routine /// @param action A non-null action to process the card insertion or removal event /// @return A non-null event source on success, `nullptr` otherwise. /// IOSDCardEventSource* IOSDCardEventSource::createWithAction(OSObject* owner, Action action) { if (action == nullptr) { perr("The action routine must be non-null."); return nullptr; } auto instance = OSTypeAlloc(IOSDCardEventSource); if (instance == nullptr) { return nullptr; } if (!instance->init(owner, reinterpret_cast<IOEventSource::Action>(action))) { instance->release(); return nullptr; } return instance; } <|start_filename|>RealtekCardReader/RealtekUSBCardReaderController.hpp<|end_filename|> // // RealtekUSBCardReaderController.hpp // RealtekCardReader // // Created by FireWolf on 7/9/21. // #ifndef RealtekUSBCardReaderController_hpp #define RealtekUSBCardReaderController_hpp #include <IOKit/IOTimerEventSource.h> #include "RealtekCardReaderController.hpp" #include "IOUSBHostDevice.hpp" #include "IOUSBHostInterface.hpp" #include "Utilities.hpp" /// /// Represents the USB-based card reader controller /// class RealtekUSBCardReaderController: public RealtekCardReaderController { // // MARK: - Constructors & Destructors // OSDeclareDefaultStructors(RealtekUSBCardReaderController); using super = RealtekCardReaderController; // // MARK: - Constants: SSC Clock Properties // /// The minimum SSC clock N value static constexpr UInt32 kMinSSCClockN = 60; /// The maximum SSC clock N value static constexpr UInt32 kMaxSSCClockN = 120; /// The amount of time in microseconds to wait until the SSC clock becomes stable static constexpr UInt32 kWaitStableSSCClock = 130; /// The minimum SSC clock frequency in MHz static constexpr UInt32 kMinSSCClockFrequencyMHz = 2; // // MARK: - Constants: Tuning Configurations // /// The number of phases static constexpr UInt32 kTuningNumPhases = 16; /// The controller should not enable the 80 clocks timeout static constexpr UInt32 kTuningEnable80ClocksTimes = false; // // MARK: - Constants: Bus Timing Tables // /// A sequence of chip registers to switch the bus speed mode to UHS-I SDR50/SDR104 static const ChipRegValuePair kBusTimingTablePairsSDR50[]; static const SimpleRegValuePairs kBusTimingTableSDR50; /// A sequence of chip registers to switch the bus speed mode to UHS-I DDR50 static const ChipRegValuePair kBusTimingTablePairsDDR50[]; static const SimpleRegValuePairs kBusTimingTableDDR50; /// A sequence of chip registers to switch the bus speed mode to High Speed static const ChipRegValuePair kBusTimingTablePairsHighSpeed[]; static const SimpleRegValuePairs kBusTimingTableHighSpeed; /// A sequence of chip registers to switch the bus speed mode to Default Speed static const ChipRegValuePair kBusTimingTablePairsDefaultSpeed[]; static const SimpleRegValuePairs kBusTimingTableDefaultSpeed; // // MARK: - Constants: SD Pull Control Tables // /// A sequence of chip registers to enable SD pull control (LQFP48 Package) static const ChipRegValuePair kSDEnablePullControlTablePairs_lqfp48[]; static const SimpleRegValuePairs kSDEnablePullControlTable_lqfp48; /// A sequence of chip registers to enable SD pull control (QFN24 Package) static const ChipRegValuePair kSDEnablePullControlTablePairs_qfn24[]; static const SimpleRegValuePairs kSDEnablePullControlTable_qfn24; /// A sequence of chip registers to disable SD pull control (LQFP48 Package) static const ChipRegValuePair kSDDisablePullControlTablePairs_lqfp48[]; static const SimpleRegValuePairs kSDDisablePullControlTable_lqfp48; /// A sequence of chip registers to disable SD pull control (QFN24 Package) static const ChipRegValuePair kSDDisablePullControlTablePairs_qfn24[]; static const SimpleRegValuePairs kSDDisablePullControlTable_qfn24; // // MARK: - Constants: Host Command & Data Buffer // /// Special host buffer offset enum Offset: IOByteCount { /// Offset 0: Header tag "R" kHeaderTag0 = 0, /// Offset 1: Header tag "T" kHeaderTag1 = 1, /// Offset 2: Header tag "C" kHeaderTag2 = 2, /// Offset 3: Header tag "R" kHeaderTag3 = 3, /// /// Offset 4: Packet type /// /// @see `enum class PacketType` /// kPacketType = 4, /// /// Offset 5: Item count (High 8 bits) /// /// @note If the packet type is `kBatchCommand`, /// the item count is the number of commands in the host buffer, /// otherwise it is the number of registers to access sequentially. /// kItemCntH8b = 5, /// /// Offset 6: Item count (Low 8 bits) /// /// @note If the packet type is `kBatchCommand`, /// the item count is the number of commands in the host buffer, /// otherwise it is the number of registers to access sequentially. /// kItemCntL8b = 6, /// /// Offset 7: The stage flags /// /// @see `enum class Flag` /// kStageFlags = 7, /// /// Offset 8: The host command /// /// @note Each command is 4 bytes long, starting at the offset 0x08. /// kHostCmdOff = 8, /// /// Offset 12: A sequence of register values if the packet type is `kSeqWriteCommand` /// /// @note The sequence write command resides at the offset 0x08. /// The list of register values start at the offset 0x0C. /// kSeqRegsVal = 12, }; /// The host buffer size (by default 1024 bytes) static constexpr IOByteCount kHostBufferSize = 1024; /// The host buffer can hold up to 254 commands static constexpr IOItemCount kMaxNumCommands = (kHostBufferSize - Offset::kHostCmdOff) / 4; // // MARK: - Data Structures (Private) // /// Represents a packet in the host buffer struct PACKED Packet { /// The header value static constexpr UInt32 kHeader = 0x52435452; /// Enumerates all possible packet types enum class Type: UInt8 { /// The packet contains a batch of commands to access chip registers kBatchCommand = 0, /// The packet contains a command to read from a contiguous sequence of registers kSeqReadCommand = 1, /// The packet contains a command to write to a contiguous sequence of registers kSeqWriteCommand = 2, }; /// Stage bits in the host command buffer enum Stage: UInt8 { kRead = 0x01, kDirectionIn = 0x02, kDirectionOut = 0x04, kStatusMS = 0x08, kStatusXD = 0x10, }; /// Flags value passed to `endCommandTransfer()` enum Flags: UInt8 { /// Send out a sequence of commands kC = 0x00, /// Send out a sequence of commands and expect the response kCR = Stage::kRead, /// Send out a sequence of commands, initiate an inbound DMA transfer and expect the response kCDIR = Stage::kRead | Stage::kDirectionIn, /// Send out a sequence of commands, initiate an outbound DMA transfer and expect the response kCDOR = Stage::kRead | Stage::kDirectionOut, }; /// The header "RTCR" UInt32 header; /// The packet type Type type; /// The item count (encoded in big endian) UInt16 itemCount; /// The stage flags Flags flags; /// Create a packet Packet(Type type, UInt16 itemCount, Flags flags) : header(kHeader), type(type), itemCount(OSSwapInt16(itemCount)), flags(flags) {} /// /// [Convenient] Create a packet for issuing a batch of commands to access chip registers /// /// @param ncmds The number of commands in the host buffer /// @param flags The stage flags /// @note Port: This function partially replaces `rtsx_usb_init_cmd()` defined in `rtsx_usb.h`. /// static inline Packet forBatchCommand(UInt16 ncmds, Flags flags) { return Packet(Type::kBatchCommand, ncmds, flags); } /// /// [Convenient] Create a packet for issuing a command to read a contiguous sequence of registers /// /// @param nregs The number of registers to read /// @note Port: This function partially replaces `rtsx_usb_seq_cmd_hdr()` defined in `rtsx_usb.c`. /// static inline Packet forSeqReadCommand(UInt16 nregs) { return Packet(Type::kSeqReadCommand, nregs, Flags::kCR); } /// /// [Convenient] Create a packet for issuing a command to write a contiguous sequence of registers /// /// @param nregs The number of registers to write /// @note Port: This function partially replaces `rtsx_usb_seq_cmd_hdr()` defined in `rtsx_usb.c`. /// static inline Packet forSeqWriteCommand(UInt16 nregs) { return Packet(Type::kSeqWriteCommand, nregs, Flags::kC); } }; /// ABI Checks static_assert(sizeof(Packet) == Offset::kHostCmdOff, "ABI Error: The packet is not 8 bytes long."); static_assert(offsetof(Packet, header) == Offset::kHeaderTag0, "ABI Error: Header offset is not 0"); static_assert(offsetof(Packet, type) == Offset::kPacketType, "ABI Error: Packet type offset is not 5."); static_assert(offsetof(Packet, itemCount) == Offset::kItemCntH8b, "ABI Error: Item count offset is not 6."); static_assert(offsetof(Packet, flags) == Offset::kStageFlags, "ABI Error: Flags offset is not 7."); /// A namespace that defines constants and utilities related to USB endpoints struct Endpoints { /// The control endpoint struct Control { /// Constants static constexpr UInt16 kOperationShift = 14; static constexpr UInt16 kReadRegister = 2; static constexpr UInt16 kWriteRegister = 3; /// USB vendor request (DeviceRequest::bRequest value) enum VendorRequest: UInt8 { /// Register operation kRegister = 0x00, /// Poll operation kPoll = 0x02, }; /// /// Get the value for a control request to read a chip register /// /// @param address The register address /// @return The value of `DeviceRequest::wValue`. /// static inline UInt16 deviceRequestValueForReadRegisterCommand(UInt16 address) { address |= (kReadRegister << kOperationShift); return OSSwapInt16(address); } /// /// Get the value for a control request to write a chip register /// /// @param address The register address /// @return The value of `DeviceRequest::wValue`. /// static inline UInt16 deviceRequestValueForWriteRegisterCommand(UInt16 address) { address |= (kWriteRegister << kOperationShift); return OSSwapInt16(address); } }; }; /// /// Defines bits in the card status /// /// @see `RealtekUSBCardReaderController::getCardStatus()` /// enum CardStatus: UInt16 { /// A SD card is present kSDPresent = 0x01, /// A MS card is present kMSPresent = 0x02, /// A XD card is present kXDPresent = 0x04, /// A card is present kCardPresent = kSDPresent | kMSPresent | kXDPresent, /// The SD card is write protected kSDWriteProtected = 0x08, }; // // MARK: - IOKit Basics // /// The USB host device (provider) IOUSBHostDevice* device; /// The USB host interface IOUSBHostInterface* interface; /// The input bulk pipe IOUSBHostPipe* inputPipe; /// The output bulk pipe IOUSBHostPipe* outputPipe; /// A timer that polls the device status every 100ms IOTimerEventSource* timer; // // MARK: - Host States // /// True if the card is present (cached) bool isCardPresentBefore; /// True if the packet is LQFT48 bool isLQFT48; /// True if the chip is RTS5179 bool isRTS5179; /// Chip revision UInt8 revision; /// Non-zero if a card event is being processed thus the polling function should pause UInt32 cardEventLock; /// The completion descriptor that defines the callback routine when a card event has been processed IOSDCard::Completion cardEventCompletion; // // MARK: - Access Chip Registers (Common, Final) // /// /// Read a byte from the chip register at the given address /// /// @param address The register address /// @param value The register value on return /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_read_register()` defined in `rtsx_usb.c`. /// IOReturn readChipRegister(UInt16 address, UInt8& value) override final; /// /// Write a byte to the chip register at the given address /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_write_register()` defined in `rtsx_usb.c`. /// IOReturn writeChipRegister(UInt16 address, UInt8 mask, UInt8 value) override final; /// /// Read from a contiguous sequence of chip registers /// /// @param address The starting register address /// @param count The number of registers to read /// @param destination A non-null buffer that stores the registers value on return /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_seq_read_register()` defined in `rtsx_usb.c`. /// IOReturn readChipRegistersSequentially(UInt16 address, UInt16 count, UInt8* destination); /// /// Write to a contiguous sequence of chip registers /// /// @param address The starting register address /// @param count The number of registers to write /// @param source A non-null buffer that contains the registers value /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_seq_read_register()` defined in `rtsx_usb.c`. /// IOReturn writeChipRegistersSequentially(UInt16 address, UInt16 count, const UInt8* source); /// /// Read from a contiguous sequence of chip registers /// /// @param address The starting register address /// @param count The number of registers to read /// @param destination A non-null buffer that stores the registers value on return /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_seq_read_register()` defined in `rtsx_usb.c`. /// IOReturn readChipRegistersSequentially(UInt16 address, UInt16 count, IOMemoryDescriptor* destination); /// /// Write to a contiguous sequence of chip registers /// /// @param address The starting register address /// @param count The number of registers to write /// @param source A non-null buffer that contains the registers value /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_seq_read_register()` defined in `rtsx_usb.c`. /// IOReturn writeChipRegistersSequentially(UInt16 address, UInt16 count, IOMemoryDescriptor* source); /// /// Read a byte from the chip register at the given address via the control endpoint /// /// @param address The register address /// @param value The register value on return /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_ep0_write_register()` defined in `rtsx_usb.c`. /// IOReturn readChipRegisterViaControlEndpoint(UInt16 address, UInt8& value); /// /// Write a byte to the chip register at the given address via the control endpoint /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// @note Port: This function replaces `rtsx_usb_ep0_read_register()` defined in `rtsx_usb.c`. /// IOReturn writeChipRegisterViaControlEndpoint(UInt16 address, UInt8 mask, UInt8 value); // // MARK: - Access Physical Layer Registers // /// /// Write a byte to the physical layer register at the given address /// /// @param address The register address /// @param value The register value /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_usb_write_phy_register()` defined in `rtsx_usb.c`. /// IOReturn writePhysRegister(UInt8 address, UInt8 value); // // MARK: - Host Buffer Management // /// /// Read from the host buffer into the given buffer /// /// @param offset A byte offset into the host buffer /// @param buffer A non-null buffer /// @param length The number of bytes to read /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function runs in a gated context. /// IOReturn readHostBufferGated(IOByteCount offset, void* buffer, IOByteCount length) override final; /// /// Write to the host buffer form the given buffer /// /// @param offset A byte offset into the host buffer /// @param buffer A non-null buffer /// @param length The number of bytes to write /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function runs in a gated context. /// IOReturn writeHostBufferGated(IOByteCount offset, const void* buffer, IOByteCount length) override final; /// /// Write the given packet to the host buffer /// /// @param packet The packet to write /// @note This function runs in a gated context. /// inline void writePacketToHostBufferGated(const Packet& packet) { this->writeHostBufferValueGated(Offset::kHeaderTag0, packet); } // // MARK: - Host Command Management (Core) // /// /// Enqueue a command /// /// @param command The command /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_usb_add_cmd()` defined in `rtsx_usb.c`. /// @note This function runs in a gated context. /// IOReturn enqueueCommandGated(const Command& command) override final; /// /// Finish the existing host command transfer session /// /// @param timeout Specify the amount of time in milliseconds /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_usb_send_cmd()` and `rtsx_usb_get_rsp()` defined in `rtsx_usb.c`. /// Unlike PCIe-based card reader controllers, USB-based controllers must explictly specify the response length /// and issue an inbound bulk transfer to retrieve the response to a command transfer session. /// This is handled by the function `rtsx_usb_get_rsp()` defined in `rtsx_usb.c`, /// and the response length is the sum of number of read and check register commands. /// Our card reader controller keeps track of how many read and check register commands are in the host buffer, /// so `endCommandTransfer()` can initiate an inbound bulk transfer to load the response automatically, /// after it has completed the outbound bulk transfer that sends the host commands to the card reader. /// As such, the host device avoids the explict invocation of `rtsx_usb_get_rsp()` after `rtsx_usb_send_cmd()`, /// which makes the host device implementation independent of the card reader controller as much as possible. /// @note This function sends all commands in the queue to the device and initiates an inbound bulk transfer /// if and only if the current transfer session contains at least one read or check register command. /// @note This function runs in a gated context. /// IOReturn endCommandTransferGated(UInt32 timeout, UInt32 flags) override final; /// /// Finish the existing host command transfer session without waiting for the response /// /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, other values if failes to send the command to the device. /// @note Port: This function replaces `rtsx_pci_send_cmd_no_wait()` defined in `rtsx_psr.c`. /// @note Port: This function replaces `rtsx_usb_send_cmd()` (the original version) defined in `rtsx_usb.c`. /// @note This function sends all commands in the queue to the device. /// @note This function runs in a gated context. /// IOReturn endCommandTransferNoWaitGated(UInt32 flags) override final; /// /// Load the response to the existing host command transfer session /// /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, other values otherwise. /// @note Port: This function is a noop and returns `kIOReturnSuccess` for PCIe-based card reader controllers. /// @note Port: This function replaces `rtsx_usb_get_rsp()` (the original version) defined in `rtsx_usb.c`. /// @note This function runs in a gated context. /// IOReturn loadCommandTransferResponseGated(UInt32 timeout) override final; // // MARK: - Host Data Management // /// /// Perform a DMA read operation /// /// @param descriptor A non-null, perpared memory descriptor /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// IOReturn performDMARead(IOMemoryDescriptor* descriptor, UInt32 timeout) override final; /// /// Perform a DMA write operation /// /// @param descriptor A non-null, perpared memory descriptor /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// IOReturn performDMAWrite(IOMemoryDescriptor* descriptor, UInt32 timeout) override final; // // MARK: - Clear Error // /// /// Clear any transfer error on the card side /// /// @note Port: This function replaces the code block that stops the card and clears the card errorin `sd_clear_error()` defined in `rtsx_pci/usb_sdmmc.c`. /// void clearCardError() override final; /// /// Clear any transfer error on the host side /// /// @note This function is invoked when a command or data transfer has failed. /// @note Port: This function replaces `rtsx_usb_clear_fsm_err()` and `rtsx_usb_clear_dma_err()` defined in `rtsx_usb.h`. /// void clearHostError() override final; // // MARK: - LED Management // /// /// Turn on the LED /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_usb_turn_on_led()` defined in `rtsx_usb.h`. /// IOReturn turnOnLED() override; /// /// Turn off the LED /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_usb_turn_off_led()` defined in `rtsx_usb.h`. /// IOReturn turnOffLED() override; /// /// Enable LED blinking /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: USB-based card reader controllers do not support this feature, /// so this function simply returns `kIOReturnSuccess`. /// IOReturn enableLEDBlinking() override; /// /// Disable LED blinking /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: USB-based card reader controllers do not support this feature, /// so this function simply returns `kIOReturnSuccess`. /// IOReturn disableLEDBlinking() override; // // MARK: - Card Selection, Share Mode and Transfer Properties // /// /// Select the SD card /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn selectCard() override; /// /// Select the data source for the SD card /// /// @param ppbuf `True` if the data source should be set to the ping pong buffer; /// `False` if the data source should be the ring buffer instead /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn selectCardDataSource(bool ppbuf) override; /// /// Configure the card share mode /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn configureCardShareMode() override; /// /// Setup the properties for a DMA transfer session /// /// @param length The number of bytes to be transferred /// @param direction `kIODirectionIn` if it is an inbound DMA transfer; /// `kIODirectionOut` if it is an outbound DMA transfer /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// @note The given direction is guaranteed to be either `kIODirectionIn` or `kIODirectionOut`. /// IOReturn setupCardDMATransferProperties(UInt32 length, IODirection direction) override; // // MARK: - Card Power Management // /// /// Enable the card clock /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn enableCardClock() override; /// /// Disable the card clock /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn disableCardClock() override; /// /// Enable the card output /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn enableCardOutput() override; /// /// Disable the card output /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// IOReturn disableCardOutput() override; /// /// Power on the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the code block that powers on the card in `sd_power_on()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn powerOnCard() override; /// /// Power off the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the code block that powers off the card in `sd_power_off()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn powerOffCard() override; /// /// Switch to the given output voltage /// /// @param outputVoltage The new output voltage /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the code block that changes the voltage in `sdmmc_switch_voltage()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn switchOutputVoltage(OutputVoltage outputVoltage) override; // // MARK: - Card Clock Configurations // /// /// Calculate the number of MCUs from the given SSC clock /// /// @param clock The SSC clock in MHz /// @return The MCU count. /// @note Port: This function replaces the code block that calculates the MCU count in `rtsx_pci/usb_switch_clock()` defined in `rtsx_psr/usb.c`. /// @note Concrete controllers must ensure that the returned MCU count is less than or equal to 15. /// UInt32 sscClock2MCUCount(UInt32 clock) override; /// /// Convert the given SSC depth to the actual register value /// /// @param depth The SSC depth /// @return The register value. /// UInt8 sscDepth2RegValue(SSCDepth depth) override; /// /// Revise the given SSC depth register value /// /// @param depth The SSC depth register value /// @param divider The SSC clock divider value /// @return The revised SSC depth register value. /// UInt8 reviseSSCDepthRegValue(UInt8 depth, UInt8 divider) override; /// /// Switch to the given SSC clock /// /// @param depth The SSC depth register value /// @param n The SSC clock n value /// @param divider The SSC clock divider /// @param mcus The number of MCUs /// @param vpclock `true` if VPCLOCK should be used /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function does the actual clock switching and is controller-dependent. /// IOReturn switchCardClock(UInt8 depth, UInt8 n, UInt8 divider, UInt8 mcus, bool vpclock) override; // // MARK: - Card Detection and Write Protection // /// /// [Helper] Get the card status via the control endpoint /// /// @param status The card status on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the branch where `polling_pipe` is 0 in `rtsx_usb_get_card_status()` defined in `rtsx_usb.c`. /// IOReturn getCardStatusViaControlEndpoint(UInt16& status); /// /// [Helper] Get the card status via a bulk transfer /// /// @param status The card status on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_get_status_with_bulk()` defined in `rtsx_usb.c`. /// IOReturn getCardStatusViaBulkTransfer(UInt16& status); /// /// Get the card status /// /// @param status The card status on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_get_card_status()` defined in `rtsx_usb.c`. /// IOReturn getCardStatus(UInt16& status); /// /// Check whether the card has write protection enabled /// /// @return `true` if the card is write protected, `false` otherwise. /// bool isCardWriteProtected() override; /// /// Check whether a card is present /// /// @return `true` if a card exists, `false` otherwise. /// @note Port: This function replaces `sdmmc_get_cd()` defined in `rtsx_usb_sdmmc.c`. /// @warning: This function supports SD cards only. /// bool isCardPresent() override; /// /// Check whether the command line of the card is busy /// /// @return `true` if the card CMD line is busy, `false` otherwise. /// @warning This function returns `true` if failed to read the register. /// bool isCardCommandLineBusy() override; /// /// Check whether the data line of the card is busy /// /// @return `true` if the card DAT lines are busy, `false` otherwise. /// @warning This function returns `true` if failed to read the register. /// bool isCardDataLineBusy() override; // // MARK: - Card Pull Control Management // /// /// Enable pull control for the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `sd_pull_ctl_enable_*()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn enablePullControlForSDCard() override; /// /// Disable pull control for the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `sd_pull_ctl_disable_*()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn disablePullControlForSDCard() override; // // MARK: - Card Tuning & Phase Management // /// /// Change the Rx phase /// /// @param samplePoint The sample point value /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the Rx portion of `sd_change_phase()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn changeRxPhase(UInt8 samplePoint) override; /// /// Change the Tx phase /// /// @param samplePoint The sample point value /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the Tx portion of `sd_change_phase()` defined in `rtsx_usb_sdmmc.c`. /// IOReturn changeTxPhase(UInt8 samplePoint) override; // // MARK: - Ping Pong Buffer // /// /// Read from the ping pong buffer /// /// @param destination The buffer to store bytes /// @param length The number of bytes to read (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_read_ppbuf()` defined in `rtsx_usb.c`. /// IOReturn readPingPongBuffer(UInt8* destination, IOByteCount length) override final; /// /// Write to the ping pong buffer /// /// @param source The buffer to write /// @param length The number of bytes to write (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_write_ppbuf()` defined in `rtsx_usb.c`. /// IOReturn writePingPongBuffer(const UInt8* source, IOByteCount length) override final; /// /// Read from the ping pong buffer /// /// @param destination The buffer to store bytes /// @param length The number of bytes to read (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_read_ppbuf()` defined in `rtsx_usb.c`. /// IOReturn readPingPongBuffer(IOMemoryDescriptor* destination, IOByteCount length) override final; /// /// Write to the ping pong buffer /// /// @param source The buffer to write /// @param length The number of bytes to write (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_write_ppbuf()` defined in `rtsx_usb.c`. /// IOReturn writePingPongBuffer(IOMemoryDescriptor* source, IOByteCount length) override final; // // MARK: - USB Bulk Transfer // /// /// [Helper] Perform a data transfer on the bulk endpoint /// /// @param pipe The bulk endpoint /// @param buffer A memory descriptor that contains the data of interest /// @param length The total number of bytes to transfer /// @param timeout Specify the amount of time in milliseconds /// @param retries Abort and return an error if the pipe is still stalled after a certain number of attempts /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function increases the timeout to 600 ms if the given timeout is less than 600 ms. /// @note This function returns an error if the actual number of bytes transferred is not identical to the given `length`. /// @note Port: This function in a sense replaces `rtsx_usb_transfer_data()` and `rtsx_usb_bulk_transfer_sglist()` defined in `rtsx_usb.c`. /// @note This function runs in a gated context. /// IOReturn performBulkTransferGated(IOUSBHostPipe* pipe, IOMemoryDescriptor* buffer, IOByteCount length, UInt32 timeout, UInt32 retries = 3); /// /// [Helper] Perform a data transfer on the bulk endpoint /// /// @param pipe The bulk endpoint /// @param buffer A memory descriptor that contains the data of interest /// @param length The total number of bytes to transfer /// @param timeout Specify the amount of time in milliseconds /// @param retries Abort and return an error if the pipe is still stalled after a certain number of attempts /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function increases the timeout to 600 ms if the given timeout is less than 600 ms. /// @note This function returns an error if the actual number of bytes transferred is not identical to the given `length`. /// @note Port: This function in a sense replaces `rtsx_usb_transfer_data()` and `rtsx_usb_bulk_transfer_sglist()` defined in `rtsx_usb.c`. /// IOReturn performBulkTransfer(IOUSBHostPipe* pipe, IOMemoryDescriptor* buffer, IOByteCount length, UInt32 timeout, UInt32 retries = 3); /// /// Perform an inbound transfer on the bulk endpoint /// /// @param buffer A memory descriptor that stores the data transferred /// @param length The total number of bytes to transfer /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function increases the timeout to 600 ms if the given timeout is less than 600 ms. /// @note This function returns an error if the actual number of bytes transferred is not identical to the given `length`. /// @note Port: This function in a sense replaces `rtsx_usb_transfer_data()` and `rtsx_usb_bulk_transfer_sglist()` defined in `rtsx_usb.c`. /// inline IOReturn performInboundBulkTransfer(IOMemoryDescriptor* buffer, IOByteCount length, UInt32 timeout) { pinfo("Initiating an inbound bulk transfer with length = %llu bytes and timeout = %u ms...", length, timeout); return this->performBulkTransfer(this->inputPipe, buffer, length, timeout); } /// /// Perform an inbound transfer on the bulk endpoint /// /// @param buffer A non-null buffer that stores the data transferred /// @param length The total number of bytes to transfer /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function increases the timeout to 600 ms if the given timeout is less than 600 ms. /// @note This function returns an error if the actual number of bytes transferred is not identical to the given `length`. /// @note Port: This function in a sense replaces `rtsx_usb_transfer_data()` and `rtsx_usb_bulk_transfer_sglist()` defined in `rtsx_usb.c`. /// IOReturn performInboundBulkTransfer(void* buffer, IOByteCount length, UInt32 timeout); /// /// Perform an outbound transfer on the bulk endpoint /// /// @param buffer A memory descriptor that contains the data to transfer /// @param length The total number of bytes to transfer /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function increases the timeout to 600 ms if the given timeout is less than 600 ms. /// @note This function returns an error if the actual number of bytes transferred is not identical to the given `length`. /// @note Port: This function in a sense replaces `rtsx_usb_transfer_data()` and `rtsx_usb_bulk_transfer_sglist()` defined in `rtsx_usb.c`. /// inline IOReturn performOutboundBulkTransfer(IOMemoryDescriptor* buffer, IOByteCount length, UInt32 timeout) { pinfo("Initiating an outbound bulk transfer with length = %llu bytes and timeout = %u ms...", length, timeout); return this->performBulkTransfer(this->outputPipe, buffer, length, timeout); } /// /// Perform an outbound transfer on the bulk endpoint /// /// @param buffer A memory descriptor that contains the data to transfer /// @param length The total number of bytes to transfer /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function increases the timeout to 600 ms if the given timeout is less than 600 ms. /// @note This function returns an error if the actual number of bytes transferred is not identical to the given `length`. /// @note Port: This function in a sense replaces `rtsx_usb_transfer_data()` and `rtsx_usb_bulk_transfer_sglist()` defined in `rtsx_usb.c`. /// IOReturn performOutboundBulkTransfer(const void* buffer, IOByteCount length, UInt32 timeout); // // MARK: - Power Management // /// /// Prepare to enter the sleep state /// /// @note Port: This function replaces `rtsx_usb_suspend()` defined in `rtsx_usb.c`. /// void prepareToSleep() override; /// /// Prepare to wake up from sleep /// /// @note Port: This function replaces `rtsx_usb_resume()` defined in `rtsx_usb.c`. /// void prepareToWakeUp() override; // // MARK: - Hardware Initialization and Configuration // /// /// Reset the card reader chip /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_reset_chip()` defined in `rtsx_usb.c`. /// IOReturn resetHardware(); /// /// Initialize the card reader chip /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_usb_init_chip()` defined in `rtsx_usb.c`. /// IOReturn initHardware(); /// /// Set the device properties /// void setDeviceProperties(); // // MARK: - Polling Device Status // public: /// /// Stop polling the device status /// void pausePollingThread(); /// /// Resume polling the device status /// void resumePollingThread(); protected: /// /// [Completion] Notify the host device when the host driver has processed a card event /// /// @param parameter An opaque client-supplied parameter pointer /// @param status `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// void onSDCardEventProcessedCompletion(void* parameter, IOReturn status, OSDictionary* characteristics); /// /// Fetch the device status periodically /// /// @param sender The timer event source /// @note This funtion runs in a gated context. /// void fetchDeviceStatusGated(IOTimerEventSource* sender); // // MARK: - Startup Routines // /// /// Setup the USB device and configurations /// /// @param provider The provider /// @return `true` on success, `false` otherwise. /// bool setupUSBHostDevice(IOService* provider); /// /// Setup the USB interface and endpoints /// /// @return `true` on success, `false` otherwise. /// bool setupUSBHostInterface(); /// /// Setup the host command and buffer management module /// /// @return `true` on success, `false` otherwise. /// bool setupHostBuffer(); /// /// Setup the polling timer /// /// @return `true` on success, `false` otherwise. /// @note This function does not enable the timer automatically. /// bool setupPollingTimer(); // // MARK: - Teardown Routines // /// /// Tear down the USB device and configurations /// void tearDownUSBHostDevice(); /// /// Tear down the USB interface and endpoints /// void tearDownUSBHostInterface(); /// /// Tear down the host command and buffer management module /// void tearDownHostBuffer(); /// /// Destroy the polling timer /// void tearDownPollingTimer(); public: // // MARK: - IOService Implementations // /// /// Initialize the controller /// /// @return `true` on success, `false` otherwise. /// bool init(OSDictionary* dictionary = nullptr) override; /// /// Start the controller /// /// @param provider An instance of USB host device that represents the card reader /// @return `true` on success, `false` otherwise. /// bool start(IOService* provider) override; /// /// Stop the controller /// /// @param provider An instance of USB host device that represents the card reader /// void stop(IOService* provider) override; }; #endif /* RealtekUSBCardReaderController_hpp */ <|start_filename|>RealtekCardReader/IOSDBlockStorageDevice.cpp<|end_filename|> // // IOSDBlockStorageDevice.cpp // RealtekCardReader // // Created by FireWolf on 6/2/21. // #include "IOSDBlockStorageDevice.hpp" #include <IOKit/storage/IOBlockStorageDriver.h> // // MARK: - Meta Class Definitions // OSDefineMetaClassAndStructors(IOSDBlockStorageDevice, IOBlockStorageDevice); // // MARK: - Card Characteristics // /// /// Fetch the card characteristics /// /// @return `true` on success, `false` otherwise. /// bool IOSDBlockStorageDevice::fetchCardCharacteristics() { // 1. Block Size if (this->driver->getCardBlockLength(this->blockSize) != kIOReturnSuccess) { perr("Failed to fetch the card block size."); return false; } // 2. Block Number if (this->driver->getCardNumBlocks(this->numBlocks) != kIOReturnSuccess) { perr("Failed to fetch the number of blocks on the card."); return false; } // 3. Card Name if (this->driver->getCardName(this->name, sizeof(this->name)) != kIOReturnSuccess) { perr("Failed to fetch the card name."); return false; } // 4. Card Revision if (this->driver->getCardRevision(this->revision, sizeof(this->revision)) != kIOReturnSuccess) { perr("Failed to fetch the card revision."); return false; } // 5. Card Serial Number if (this->driver->getCardSerialNumber(this->serialNumber) != kIOReturnSuccess) { perr("Failed to fetch the card serial number."); return false; } snprintf(this->serialString, sizeof(this->serialString), "%08X", this->serialNumber); pinfo("Card Vendor = %s; Name = %s; Revision = %s; Serial Number = 0x%08X.", this->driver->getCardVendor(), this->name, this->revision, this->serialNumber); pinfo("Card Block Size = %llu Bytes; NumBlocks = %llu; Capacity = %llu Bytes.", this->blockSize, this->numBlocks, this->blockSize * this->numBlocks); return true; } // // MARK: - Card Events // /// /// Receives a generic message delivered from an attached provider /// /// @param type The message type /// @param provider The provider from which the message originates /// @param argument The message argument /// @return The status of the message. /// IOReturn IOSDBlockStorageDevice::message(UInt32 type, IOService* provider, void* argument) { // Guard: Check whether the message type is of interest if (type == kIOMessageMediaParametersHaveChanged) { pinfo("Received a notification that the media parameters have changed."); return this->messageClients(type, argument); } if (type != kIOMessageMediaStateHasChanged) { return super::message(type, provider, argument); } // Received a card event notification from the host driver auto state = static_cast<IOMediaState>(reinterpret_cast<uintptr_t>(argument)); switch (state) { case kIOMediaStateOnline: { pinfo("Received a notification that a SD card has been inserted."); psoftassert(this->fetchCardCharacteristics(), "Failed to fetch characteristics of the card inserted."); break; } case kIOMediaStateOffline: { pinfo("Received a notification that a SD card has been removed."); break; } default: { perr("Received a notification with an unsupported media state = %u.", state); break; } } // Notify the rest of the storage subsystem return this->messageClients(type, argument); } // // MARK: - Block Storage Protocol Implementations // /// /// Eject the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDBlockStorageDevice::doEjectMedia() { pinfo("The storage subsystem requests to eject the media."); this->driver->onSDCardRemovedGated(); return kIOReturnSuccess; } /// /// Format the media to the given byte capacity /// /// @param byteCapacity The byte capacity to which the device is to be formatted /// @return `kIOReturnSuccess` on success, other values otherwise. /// @npte This function always returns `kIOReturnUnsupported` since our driver does not support it. /// IOReturn IOSDBlockStorageDevice::doFormatMedia(UInt64 byteCapacity) { pinfo("The storage subsystem requests to format the media to the capacity %llu bytes.", byteCapacity); return kIOReturnUnsupported; } /// /// Get the allowable formatting byte capacities /// /// @param capacities A list of capacities /// @param capacitiesMaxCount The number of values that can be stored in `capacities` /// @return The number of capacity values returned in `capacities`; /// The total number of capacity values available if `capacities` is NULL. /// @note This function always returns `kIOReturnUnsupported` since our driver does not support it. /// UInt32 IOSDBlockStorageDevice::doGetFormatCapacities(UInt64* capacities, UInt32 capacitiesMaxCount) const { pinfo("The storage subsystem requests to fetch all supported capacities."); return kIOReturnUnsupported; } /// /// Get the vendor of the SD card /// /// @return The vendor name. /// char* IOSDBlockStorageDevice::getVendorString() { pinfo("The storage subsystem requests the vendor of the media."); return const_cast<char*>(this->driver->getCardVendor()); } /// /// Get the name of the SD card /// /// @return The product name. /// char* IOSDBlockStorageDevice::getProductString() { pinfo("The storage subsystem requests the name of the media."); return this->name; } /// /// Get the revision of the SD card /// /// @return The card revision value. /// char* IOSDBlockStorageDevice::getRevisionString() { pinfo("The storage subsystem requests the revision of the media."); return this->revision; } /// /// Get additional information of the SD card /// /// @return The additional information. /// char* IOSDBlockStorageDevice::getAdditionalDeviceInfoString() { pinfo("The storage subsystem requests the addition information of the media."); return this->serialString; } /// /// Report the block size of the SD card /// /// @param blockSize The block size in bytes on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The block size should always be 512 bytes. /// IOReturn IOSDBlockStorageDevice::reportBlockSize(UInt64* blockSize) { pinfo("The storage subsystem requests the block size of the media."); return this->driver->getCardBlockLength(*blockSize); } /// /// Report whether the SD card is ejectable /// /// @param isEjectable Set to `true` if the card can be ejected, `false` otherwise. /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The card is always ejectable. /// IOReturn IOSDBlockStorageDevice::reportEjectability(bool* isEjectable) { pinfo("The storage subsystem asks whether the media is ejectable."); *isEjectable = true; return kIOReturnSuccess; } /// /// Report the index of the highest valid block of the SD card /// /// @param maxBlock The block index on return /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDBlockStorageDevice::reportMaxValidBlock(UInt64* maxBlock) { pinfo("The storage subsystem requests the index of the maximum block on the media."); return this->driver->getCardMaxBlockIndex(*maxBlock); } /// /// Report the state of the SD card /// /// @param mediaPresent Set to `true` if the SD card is present, `false` otherwise /// @param changedState Set to `true` if the state has changed since the last query /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDBlockStorageDevice::reportMediaState(bool* mediaPresent, bool* changedState) { pinfo("The storage subsystem requests the state of the media."); if (changedState != nullptr) { *changedState = false; } return this->driver->isCardPresent(*mediaPresent); } /// /// Report whether the SD card is removable /// /// @param isRemovable Set to `true` if the card can be removed, `false` otherwise. /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The card is always removable. /// IOReturn IOSDBlockStorageDevice::reportRemovability(bool* isRemovable) { pinfo("The storage subsystem asks whether the media is removable."); *isRemovable = true; return kIOReturnSuccess; } /// /// Report whether the SD card is write protected /// /// @param isWriteProtected Set to `true` if the card is write protected, `false` otherwise /// @return `kIOReturnSuccess` on success, other values otherwise. /// IOReturn IOSDBlockStorageDevice::reportWriteProtection(bool* isWriteProtected) { pinfo("The storage subsystem asks whether the media is write protected."); return this->driver->isCardWriteProtected(*isWriteProtected); } /// /// Submit an asynchronous I/O request /// /// @param buffer The data transfer buffer /// @param block The starting block number /// @param nblks The number of blocks to transfer /// @param attributes Attributes of the data transfer /// @param completion The completion routine to call once the data transfer completes /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The data direction is contained in the given memory descriptor. /// @warning The given `completion` is allocated on the caller stack and thus is non-null. /// However, since this function is asynchronous, the host driver must copy the completion to somewhere else, /// otherwise a page fault will occur when the host driver invokes `IOStorage::complete()` on the completion object. /// @seealso `IOBlockStorageDriver::breakUpRequestExecute()` and `IOBlockStorageDriver::executeRequest()`. /// @ref https://opensource.apple.com/source/IOStorageFamily/IOStorageFamily-260.100.1/IOBlockStorageDriver.cpp.auto.html /// IOReturn IOSDBlockStorageDevice::doAsyncReadWrite(IOMemoryDescriptor* buffer, UInt64 block, UInt64 nblks, IOStorageAttributes* attributes, IOStorageCompletion* completion) { // Request to access the SD card pinfo("The storage subsystem requests to do asynchronous I/O transfer."); // Guard: Reject the request if the block device has been terminated if (this->isInactive()) { perr("The block storage device has been terminated."); return kIOReturnNotAttached; } // Guard: Check the buffer direction IODirection direction = buffer->getDirection(); if (Value::of(direction).isNotOneOf(kIODirectionIn, kIODirectionOut)) { perr("The buffer direction %d is invalid.", direction); return kIOReturnBadArgument; } // Guard: Ensure that the request does not access an out-of-bounds block if (block + nblks > this->numBlocks) { perr("The incoming request attempts to access an out-of-bounds block."); return kIOReturnBadArgument; } // Examine and submit the request if (direction == kIODirectionIn) { // This is a read request if (nblks == 1) { // Request to read a single block pinfo("The storage subsystem requests to read a single block from the block at %llu.", block); return this->driver->submitReadBlockRequest(buffer, block, nblks, attributes, completion); } else { // Request to read multiple blocks pinfo("The storage subsystem requests to read %llu blocks from the block at %llu.", nblks, block); return this->driver->submitReadBlocksRequest(buffer, block, nblks, attributes, completion); } } else { // This is a write request if (nblks == 1) { // Request to write a single block pinfo("The storage subsystem requests to write a single block to the block at %llu.", block); return this->driver->submitWriteBlockRequest(buffer, block, nblks, attributes, completion); } else { // Request to write multiple blocks pinfo("The storage subsystem requests to write %llu blocks to the block at %llu.", nblks, block); return this->driver->submitWriteBlocksRequest(buffer, block, nblks, attributes, completion); } } } // // MARK: - IOService Implementations // /// /// Start the block storage device /// /// @param provider An instance of the host driver /// @return `true` on success, `false` otherwise. /// bool IOSDBlockStorageDevice::start(IOService* provider) { pinfo("======================================="); pinfo("Starting the SD block storage device..."); pinfo("======================================="); if (!super::start(provider)) { perr("Failed to start the super class."); return false; } // Fetch the host driver this->driver = OSDynamicCast(IOSDHostDriver, provider); if (this->driver == nullptr) { perr("The provider is not a valid host driver instance."); return false; } this->driver->retain(); // Publish the service to start the storage subsystem this->registerService(); pinfo("===================================="); pinfo("The SD block storage device started."); pinfo("===================================="); return true; } /// /// Stop the block storage device /// /// @param provider An instance of the host driver /// void IOSDBlockStorageDevice::stop(IOService* provider) { OSSafeReleaseNULL(this->driver); super::stop(provider); } <|start_filename|>RealtekCardReader/IOSDCardEventSource.hpp<|end_filename|> // // IOSDCardEventSource.hpp // RealtekCardReader // // Created by FireWolf on 6/9/21. // #ifndef IOSDCardEventSource_hpp #define IOSDCardEventSource_hpp #include <IOKit/IOEventSource.h> #include "IOSDCard.hpp" /// An event source to signal the workloop to process the card insertion or removal event class IOSDCardEventSource: public IOEventSource { /// Constructors & Destructors OSDeclareDefaultStructors(IOSDCardEventSource); using super = IOEventSource; /// The completion routine IOSDCard::Completion completion; /// An optional value passed to the event handler IOSDCard::EventOptions options; /// /// Check whether an action needs to perform to handle the card event /// /// @return `false` always. The owner must explictly invoke `IOSDCardEventSource::enable()` to trigger another action. /// bool checkForWork() override; public: /// /// Type of the function that processes a card event /// /// @param owner The owner of the event source /// @param completion A non-null completion routine to be invoked when the card event has been processed /// @param options An optional value passed to the event handler /// using Action = void (*)(OSObject* owner, IOSDCard::Completion* completion, IOSDCard::EventOptions options); /// /// Enable the event source /// /// @param completion A nullable completion routine to be invoked when the card event has been processed /// @param options An optional value passed to the host driver /// void enable(IOSDCard::Completion* completion, IOSDCard::EventOptions options); /// /// Disable the event source /// void disable() override; /// /// Create a card event source with the given action /// /// @param owner Owner of the returned instance; the first parameter of the action routine /// @param action A non-null action to process the card insertion or removal event /// @return A non-null event source on success, `nullptr` otherwise. /// static IOSDCardEventSource* createWithAction(OSObject* owner, Action action); }; #endif /* IOSDCardEventSource_hpp */ <|start_filename|>RealtekCardReader/RealtekCardReaderController.hpp<|end_filename|> // // RealtekCardReaderController.hpp // RealtekCardReader // // Created by FireWolf on 7/10/21. // #ifndef RealtekCardReaderController_hpp #define RealtekCardReaderController_hpp #include <IOKit/IOBufferMemoryDescriptor.h> #include <IOKit/IOWorkLoop.h> #include "IOCommandGate.hpp" #include "WolfsSDXC.hpp" #include "IOSDCard.hpp" #include "ClosedRange.hpp" #include "Utilities.hpp" #include "Debug.hpp" /// Forward Declaration (Client of the card reader controller) class RealtekSDXCSlot; /// /// Represents the abstract card reader controller /// /// @note This is the base class of all Realtek PCIe/USB-based card reader controllers /// and defines the interface for the controller-independent host device. /// class RealtekCardReaderController: public WolfsSDXC { // // MARK: - Constructors & Destructors // OSDeclareAbstractStructors(RealtekCardReaderController); using super = WolfsSDXC; // // MARK: - Controller-Independent Data Structures (Public) // public: /// Represents a pair of register address and its value struct ChipRegValuePair { /// The register address UInt16 address; /// The register value mask UInt8 mask; /// The register value UInt8 value; /// Create a pair ChipRegValuePair(UInt16 address, UInt8 mask, UInt8 value) : address(address), mask(mask), value(value) {} /// Create a pair with mask set to 0xFF ChipRegValuePair(UInt16 address, UInt8 value) : ChipRegValuePair(address, 0xFF, value) {} /// Create a pair with both mask and value set to 0x00 ChipRegValuePair(UInt16 address) : ChipRegValuePair(address, 0x00, 0x00) {} /// Create an empty pair ChipRegValuePair() : ChipRegValuePair(0, 0, 0) {} }; /// Interface of a sequence of pairs of register address and its value struct ChipRegValuePairs { /// Virtual destructor virtual ~ChipRegValuePairs() = default; /// Retrieve the i-th register value pair virtual struct ChipRegValuePair get(size_t index) const = 0; /// Retrieve the total number of pairs virtual IOItemCount size() const = 0; /// /// Run the given action on each pair /// /// @param action A callable action that takes a chip register value pair as input /// template <typename Action> void forEach(Action action) const { for (auto index = 0; index < this->size(); index += 1) { action(this->get(index)); } } /// /// Run the given action on each pair until the return value of `action` is not expected /// /// @param action A callable action that takes a chip register value pair as input and returns the result /// @param expected The expected return value of the given action routine /// @return The expected value on success, otherwise the actual value returned by the action routine. /// @note This function aborts the loop if the action routine fails to process a chip register value pair. /// template <typename Action, typename Result> Result forEachUntil(Action action, Result expected) const { for (auto index = 0; index < this->size(); index += 1) { Result result = action(this->get(index)); if (result != expected) { perr("Failed to run the action with the chip register pair at index %u.", index); return result; } } return expected; } }; /// /// Composed of a simple array of pairs of register address and value /// /// @note Commonly used to access a small number of registers. /// struct SimpleRegValuePairs: ChipRegValuePairs { private: /// An array of pairs const ChipRegValuePair* pairs; /// The number of pair const IOItemCount count; public: /// Create a simple sequence of pairs SimpleRegValuePairs(const ChipRegValuePair* pairs, IOItemCount count) : pairs(pairs), count(count) {} /// Create a simple sequence of pairs template <size_t N> SimpleRegValuePairs(const ChipRegValuePair (&pairs)[N]) : pairs(pairs), count(N) {} /// Retrieve the i-th register value pair struct ChipRegValuePair get(size_t index) const override { return this->pairs[index]; } /// Retrieve the total number of pairs IOItemCount size() const override { return this->count; } }; /// /// Composed of the base register address to generate a forward sequence of pairs for read access dynamically /// /// @note Convenient to read a contiguous sequence of registers. /// struct ContiguousRegValuePairsForReadAccess: ChipRegValuePairs { private: /// The base register address const UInt16 baseRegister; /// The number of pairs to generate const IOItemCount count; public: /// /// Create a contiguous sequence of pairs for read access /// /// @param baseRegister The base register address /// @param count The number of registers /// ContiguousRegValuePairsForReadAccess(UInt16 baseRegister, IOItemCount count) : baseRegister(baseRegister), count(count) {} /// Retrieve the i-th register value pair struct ChipRegValuePair get(size_t index) const override { return ChipRegValuePair(static_cast<UInt16>(this->baseRegister + index), 0, 0); } /// Retrieve the total number of pairs IOItemCount size() const override { return this->count; } }; /// /// Composed of the base register address to generate a forward sequence of pairs for write access dynamically /// /// @note Convenient to read a contiguous sequence of registers. /// struct ContiguousRegValuePairsForWriteAccess: ChipRegValuePairs { private: /// The base register address const UInt16 baseRegister; /// The register value mask const UInt8 mask; /// The number of pairs to generate const IOItemCount count; /// The register values const UInt8* values; public: /// /// Create a contiguous sequence of pairs for write access /// /// @param baseRegister The base register address /// @param count The number of registers /// @param values An array of register values /// @param mask The regiter value mask, 0xFF by default /// ContiguousRegValuePairsForWriteAccess(UInt16 baseRegister, IOItemCount count, const UInt8* values, UInt8 mask = 0xFF) : baseRegister(baseRegister), mask(mask), count(count), values(values) {} /// Retrieve the i-th register value pair struct ChipRegValuePair get(size_t index) const override { return ChipRegValuePair(static_cast<UInt16>(this->baseRegister + index), this->mask, this->values[index]); } /// Retrieve the total number of pairs IOItemCount size() const override { return this->count; } }; /// Enumerates all possible SSC depth values enum class SSCDepth: UInt32 { k4M = 0, // PCIe --- k2M = 1, // PCIe USB k1M = 2, // PCIe USB k512K = 3, // ---- USB k500K = k512K, // PCIe --- k250K = 4, // PCIe --- }; /// The card output volage enum class OutputVoltage: UInt32 { k3d3V, k1d8V }; /// Defines a sequence of registers and their values to change the bus speed mode struct BusTimingTables { /// Bus timing table for SD UHS-I SDR50 and SDR104 mode const SimpleRegValuePairs* sdr50; /// Bus timing table for SD UHS-I DDR50 mode const SimpleRegValuePairs* ddr50; /// Bus timing table for SD High Speed mode const SimpleRegValuePairs* highSpeed; /// Bus timing table for SD Default Speed mode const SimpleRegValuePairs* defaultSpeed; /// Reset all tables to null inline void reset() { this->sdr50 = nullptr; this->ddr50 = nullptr; this->highSpeed = nullptr; this->defaultSpeed = nullptr; } }; /// Defines the configuration for tunning struct TuningConfig { /// The number of phases UInt32 numPhases; /// True if the controller should enable 80 clocks timeout UInt32 enable80ClocksTimeout; /// Reset all fields to zero inline void reset() { this->numPhases = 0; this->enable80ClocksTimeout = false; } }; /// /// Defines the value of flags passed to each data transfer operation /// /// @note USB-based controllers require these flags while PCIe-based ones ignore these values. /// struct DataTransferFlags { /// Flags used to issue a SD command and wait for the response UInt32 command; /// Flags used to issue a SD command that involves an inbound data transfer UInt32 commandWithInboundDataTransfer; /// Flags used to issue a SD command that involves an outbound data transfer UInt32 commandWithOutboundDataTransfer; /// Flags used to issue a SD command that involves an inbound DMA transfer UInt32 commandWithInboundDMATransfer; /// Flags used to issue a SD command that involves an inbound DMA transfer UInt32 commandWithOutboundDMATransfer; /// Reset all flags to zero inline void reset() { this->command = 0; this->commandWithInboundDataTransfer = 0; this->commandWithOutboundDataTransfer = 0; this->commandWithInboundDMATransfer = 0; this->commandWithOutboundDMATransfer = 0; } }; // // MARK: - Controller-Independent Data Structures (Private) // protected: /// Represents a command in the host command buffer struct Command { private: /// The 32-bit value that will be written to the command buffer UInt32 value; public: /// All supported command types enum Type { kReadRegister = 0, kWriteRegister = 1, kCheckRegister = 2, }; /// /// Create a command of the given type and arguments /// /// @param type The command type /// @param address The register address /// @param mask The register value mask (ignored if `type` is `kReadRegister`) /// @param value The register value (ignored if `type` is `kReadRegister`) /// Command(Type type, UInt16 address, UInt8 mask, UInt8 value) { this->value = 0; this->value |= static_cast<UInt32>(type & 0x03) << 30; this->value |= static_cast<UInt32>(address & 0x3FFF) << 16; this->value |= static_cast<UInt32>(mask) << 8; this->value |= static_cast<UInt32>(value); } /// /// Create a command for reading from the chip register at the given address /// /// @param address The register address /// @return The host command. /// static inline Command forReadRegister(UInt16 address) { return Command(kReadRegister, address, 0, 0); } /// /// Create a command for writing to the chip register at the given address /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return The host command. /// static inline Command forWriteRegister(UInt16 address, UInt8 mask, UInt8 value) { return Command(kWriteRegister, address, mask, value); } /// /// Create a command for checking the value of the chip register at the given address /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return The host command. /// static inline Command forCheckRegister(UInt16 address, UInt8 mask, UInt8 value) { return Command(kCheckRegister, address, mask, value); } /// Get the command type inline Type getType() const { return static_cast<Type>((this->value >> 30) & 0x03); } /// Get the raw command value inline UInt32 getValue() const { return this->value; } }; /// ABI Checks static_assert(sizeof(Command) == 4, "ABI Error: Host command is not 4 bytes long."); /// Count the number of commands in the host buffer struct HostCommandCounter { /// Total number of read register commands IOItemCount nreads; /// Total number of write register commands IOItemCount nwrites; /// Total number of check register commands IOItemCount nchecks; /// Total number of commands IOItemCount total; /// Reset the counter inline void reset() { this->nreads = 0; this->nwrites = 0; this->nchecks = 0; this->total = 0; } /// /// Increment the counter of the given command type /// /// @note This function automatically increments the total number of commands. /// @warning The caller must ensure that the given type is valid. /// inline void increment(Command::Type type) { // Use the given type as the index to the storage array passert(type <= Command::Type::kCheckRegister, "The given command type is invalid."); reinterpret_cast<UInt32*>(this)[type] += 1; this->total += 1; } /// Get the length of the response to a command transfer session inline IOItemCount getResponseLength() { // The card reader replies to the read and the check register command return this->nreads + this->nchecks; } }; /// Host limitations on the internal SSC clock struct SSCClockLimits { /// The maximum and the minimum SSC clock N values ClosedRange<UInt32> rangeN; /// The maximum and the minimum clock divider register values (CLK_DIV) ClosedRange<UInt32> rangeDivider; /// The minimum SSC clock in MHz UInt32 minFrequencyMHz; /// Reserved field UInt32 reserved; /// Reset the limits to zeros inline void reset() { this->rangeN = {0, 0}; this->rangeDivider = {0, 0}; this->minFrequencyMHz = 0; this->reserved = 0; } /// Print the limits inline void print() { pinfo("SSC Clock Limits:"); pinfo("|- N = [%u, %u]", this->rangeN.lowerBound, this->rangeN.upperBound); pinfo("|- Divider = [%u, %u]", this->rangeDivider.lowerBound, this->rangeDivider.upperBound); pinfo("|- Min Freq = %u MHz", this->minFrequencyMHz); } }; /// Host UHS-I capabilities struct UHSCapabilities { /// True if the card reader supports UHS-I SDR104 bool sdr104; /// True if the card reader supports UHS-I SDR50 bool sdr50; /// True if the card reader supports UHS-I DDR50 bool ddr50; /// Reserved bool reserved; /// Reset all capabilities to false inline void reset() { this->sdr104 = false; this->sdr50 = false; this->ddr50 = false; this->reserved = false; } }; // // MARK: - IOKit Basics // /// /// The SD card slot (client) /// /// @note The concrete controller is responsible for managing the lifecycle of the card slot. /// RealtekSDXCSlot* slot; /// /// Protect shared resources and serialize operations /// /// @note The base controller creates the workloop and manages its lifecycle. /// IOWorkLoop* workLoop; /// /// A command gate to serialize executions with respect to the work loop /// /// @note This command gate is not associated with any specific actions. /// The caller should use `runAction` to execute a function in a gated context. /// @note The target action is still executed in the context of the calling thread. /// @note The base controller creates the command gate and manages its lifecycle. /// IOCommandGate* commandGate; // // MARK: - Host Command & Data Buffer // /// /// A descriptor that allocates the host command and data buffer /// /// @note The buffer remains "prepared" until the driver is stopped by the system. /// The lifecycle is managed by `setupHostBuffer()` and `tearDownHostBuffer()`. /// @note The buffer direction is set to be `kIODirectionInOut`. /// @note The actual buffer content and format are determined by the concrete controller. /// @note The concrete controller is responsible for managing the lifecycle of the host buffer. /// IOBufferMemoryDescriptor* hostBufferDescriptor; /// /// The number of commands in the host command buffer /// /// @note The counter is reset automatically each time the caller initiates a new transfer session. /// @see `RealtekCardReaderController::beginCommandTransfer()`. /// HostCommandCounter hostCommandCounter; // // MARK: - Host Capabilities // /// /// Host limitations on the internal SSC clock /// /// @note The concrete controller is responsbile for initializing its content, otherwise clock switches will fail. /// @see `RealtekCardReaderController::switchCardClock()`. /// SSCClockLimits sscClockLimits; /// Host UHS-I capabilities UHSCapabilities uhsCaps; // // MARK: - Host States // /// /// The current SSC clock in MHz /// /// @note The cached SSC clock is 0 at the beginning and is updated each time the caller requests to switch the clock. /// @see `RealtekCardReaderController::switchCardClock()`. /// UInt32 currentSSCClock; /// Bus timing tables BusTimingTables busTimingTables; /// Tuning configurations TuningConfig tuningConfig; /// Flags passed to each data transfer operation DataTransferFlags dataTransferFlags; /// /// The current card status /// /// @note `true` if the card is present before the computer sleeps, `false` otherwise. /// Other values are reserved at this moment. /// UInt32 currentCardStatus; // // MARK: - Query UHS-I Capabilities // public: /// Check whether the card reader supports the UHS-I SDR104 mode inline bool supportsSDR104() { return this->uhsCaps.sdr104; } /// Check whether the card reader supports the UHS-I SDR50 mode inline bool supportsSDR50() { return this->uhsCaps.sdr50; } /// Check whether the card reader supports the UHS-I DDR50 mode inline bool supportsDDR50() { return this->uhsCaps.ddr50; } /// Get the bus timing tables inline const BusTimingTables& getBusTimingTables() { return this->busTimingTables; } /// Get the tuning configurations inline const TuningConfig& getTuningConfig() { return this->tuningConfig; } // // MARK: - Query Data Transfer Properties // public: /// Get the flags passed to each data transfer operation inline const DataTransferFlags& getDataTransferFlags() { return this->dataTransferFlags; } // // MARK: - Access Chip Registers // public: /// /// Read a byte from the chip register at the given address /// /// @param address The register address /// @param value The register value on return /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out. /// virtual IOReturn readChipRegister(UInt16 address, UInt8& value) = 0; /// /// Write a byte to the chip register at the given address /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return `kIOReturnSuccess` on success; /// `kIOReturnTimeout` if timed out; /// `kIOReturnError` if the new register value is not `value`. /// virtual IOReturn writeChipRegister(UInt16 address, UInt8 mask, UInt8 value) = 0; /// /// Dump the chip registers in the given range /// /// @param range The range of register addresses /// void dumpChipRegisters(ClosedRange<UInt16> range); // // MARK: - Host Buffer Management // protected: /// /// Read from the host buffer into the given buffer /// /// @param offset A byte offset into the host buffer /// @param buffer A non-null buffer /// @param length The number of bytes to read /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function runs in a gated context. /// virtual IOReturn readHostBufferGated(IOByteCount offset, void* buffer, IOByteCount length) = 0; /// /// Write to the host buffer form the given buffer /// /// @param offset A byte offset into the host buffer /// @param buffer A non-null buffer /// @param length The number of bytes to write /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function runs in a gated context. /// virtual IOReturn writeHostBufferGated(IOByteCount offset, const void* buffer, IOByteCount length) = 0; /// /// Read a value from the host buffer conveniently /// /// @tparam T Specify a value type, e.g., S/UInt{8, 16, 32, 64} /// @param offset A byte offset into the host command buffer /// @return The value. /// @note This function will trigger a kernel panic if the given offset is invalid. /// @note This function runs in a gated context. /// template <typename T> T readHostBufferValueGated(IOByteCount offset) { T value; passert(this->readHostBufferGated(offset, &value, sizeof(T)) == kIOReturnSuccess, "Failed to peek %lu bytes at offset %llu.", sizeof(T), offset); return value; } /// /// Write a value to the host buffer conveniently /// /// @param offset A byte offset into the host buffer /// @param value A value /// @note This function will trigger a kernel panic if the given offset is invalid. /// @note This function runs in a gated context. /// template <typename T> void writeHostBufferValueGated(IOByteCount offset, T value) { passert(this->writeHostBufferGated(offset, &value, sizeof(T)) == kIOReturnSuccess, "Failed to write %lu bytes at offset %llu.", sizeof(T), offset); } public: /// /// Read from the host buffer into the given buffer /// /// @param offset A byte offset into the host buffer /// @param buffer A non-null buffer /// @param length The number of bytes to read /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function coordinates all accesses to the host buffer. /// IOReturn readHostBuffer(IOByteCount offset, void* buffer, IOByteCount length); /// /// Write to the host buffer form the given buffer /// /// @param offset A byte offset into the host buffer /// @param buffer A non-null buffer /// @param length The number of bytes to write /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function coordinates all accesses to the host buffer. /// IOReturn writeHostBuffer(IOByteCount offset, const void* buffer, IOByteCount length); /// /// Read a value from the host buffer conveniently /// /// @tparam T Specify a value type, e.g., S/UInt{8, 16, 32, 64} /// @param offset A byte offset into the host command buffer /// @return The value. /// @note This function will trigger a kernel panic if the given offset is invalid. /// template <typename T> T readHostBufferValue(IOByteCount offset) { T value; passert(this->readHostBuffer(offset, &value, sizeof(T)) == kIOReturnSuccess, "Failed to peek %lu bytes at offset %llu.", sizeof(T), offset); return value; } /// /// Write a value to the host buffer conveniently /// /// @tparam T Specify a value type, e.g., S/UInt{8, 16, 32, 64} /// @param offset A byte offset into the host buffer /// @param value A value /// @note This function will trigger a kernel panic if the given offset is invalid. /// template <typename T> void writeHostBufferValue(IOByteCount offset, T value) { passert(this->writeHostBuffer(offset, &value, sizeof(T)) == kIOReturnSuccess, "Failed to write %lu bytes at offset %llu.", sizeof(T), offset); } /// /// Dump the host buffer contents /// /// @param offset A byte offset into the host data buffer /// @param length The number of bytes to dump /// @param column The number of columns to print /// void dumpHostBuffer(IOByteCount offset, IOByteCount length, IOByteCount column = 8); // // MARK: - Host Command Management (Core) // public: /// /// Start a new host command transfer session /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note The caller must invoke this function before any subsequent calls to `enqueue*Command()`. /// Any commands enqueued before this function call will be overwritten. /// Once all commands are enqueued, the caller should invoke `endCommandTransfer()` to send commands to the device. /// @note Port: This function replaces `rtsx_pci/usb_init_cmd()` defined in `rtsx_pci/usb.h`. /// IOReturn beginCommandTransfer(); protected: /// /// Enqueue a command /// /// @param command The command /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_pci/usb_add_cmd()` defined in `rtsx_pcr/usb.c`. /// @note This function runs in a gated context. /// virtual IOReturn enqueueCommandGated(const Command& command) = 0; /// /// Finish the existing host command transfer session /// /// @param timeout Specify the amount of time in milliseconds /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_pci/usb_send_cmd()` defined in `rtsx_pcr/usb.c`. /// @note This function sends all commands in the queue to the device. /// @note This function runs in a gated context. /// virtual IOReturn endCommandTransferGated(UInt32 timeout, UInt32 flags) = 0; /// /// Finish the existing host command transfer session without waiting for the response /// /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, other values if failes to send the command to the device. /// @note Port: This function replaces `rtsx_pci_send_cmd_no_wait()` defined in `rtsx_psr.c`. /// @note Port: This function replaces `rtsx_usb_send_cmd()` (the original version) defined in `rtsx_usb.c`. /// @note This function sends all commands in the queue to the device. /// @note This function runs in a gated context. /// virtual IOReturn endCommandTransferNoWaitGated(UInt32 flags) = 0; /// /// Load the response to the existing host command transfer session /// /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, other values otherwise. /// @note Port: This function is a noop and returns `kIOReturnSuccess` for PCIe-based card reader controllers. /// @note Port: This function replaces `rtsx_usb_get_rsp()` (the original version) defined in `rtsx_usb.c`. /// @note This function runs in a gated context. /// virtual IOReturn loadCommandTransferResponseGated(UInt32 timeout) = 0; public: /// /// Enqueue a command /// /// @param command The command /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_pci/usb_add_cmd()` defined in `rtsx_pcr/usb.c`. /// IOReturn enqueueCommand(const Command& command); /// /// Finish the existing host command transfer session /// /// @param timeout Specify the amount of time in milliseconds /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note Port: This function replaces `rtsx_pci/usb_send_cmd()` defined in `rtsx_pcr/usb.c`. /// @note This function sends all commands in the queue to the device. /// IOReturn endCommandTransfer(UInt32 timeout = 100, UInt32 flags = 0); /// /// Finish the existing host command transfer session without waiting for the response /// /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, other values if failes to send the command to the device. /// @note Port: This function replaces `rtsx_pci_send_cmd_no_wait()` defined in `rtsx_psr.c`. /// @note Port: This function replaces `rtsx_usb_send_cmd()` (the original version) defined in `rtsx_usb.c`. /// @note This function sends all commands in the queue to the device. /// IOReturn endCommandTransferNoWait(UInt32 flags = 0); /// /// Load the response to the existing host command transfer session /// /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, other values otherwise. /// @note Port: This function is a noop and returns `kIOReturnSuccess` for PCIe-based card reader controllers. /// @note Port: This function replaces `rtsx_usb_get_rsp()` (the original version) defined in `rtsx_usb.c`. /// IOReturn loadCommandTransferResponse(UInt32 timeout); /// /// Launch a custom command transfer session conveniently /// /// @param action A callable action that enqueues any host commands and returns an `IOReturn` code /// @param timeout Specify the amount of time in milliseconds /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note This function provides an elegant way to start a command transfer session and handle errors. /// Same as calling `startCommandTransfer`, a sequence of enqueue invocations and `endCommandTransfer`. /// @note Signature of the action: `IOReturn operator()()`. /// template <typename Action> IOReturn withCustomCommandTransfer(Action action, UInt32 timeout = 100, UInt32 flags = 0) { // Guard: Begin command transfer IOReturn retVal = this->beginCommandTransfer(); if (retVal != kIOReturnSuccess) { perr("Failed to initiate a new command transfer session. Error = 0x%x.", retVal); return retVal; } // Guard: Enqueue commands retVal = action(); if (retVal != kIOReturnSuccess) { perr("Failed to enqueue the given sequence of commands. Error = 0x%x.", retVal); return retVal; } // Guard: Transfer commands return this->endCommandTransfer(timeout, flags); } // // MARK: - Host Command Management (Convenient) // public: /// /// Enqueue a command to read the register at the given address conveniently /// /// @param address The register address /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full. /// @note Port: This function replaces `rtsx_pci/usb_add_cmd()` defined in `rtsx_psr/usb.c`. /// inline IOReturn enqueueReadRegisterCommand(UInt16 address) { pinfo("Enqueue: Address = 0x%04x; Mask = 0x%02x; Value = 0x%02x.", address, 0, 0); return this->enqueueCommand(Command::forReadRegister(address)); } /// /// Enqueue a command to write a value to the register at the given address conveniently /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full. /// @note Port: This function replaces `rtsx_pci/usb_add_cmd()` defined in `rtsx_psr/usb.c`. /// inline IOReturn enqueueWriteRegisterCommand(UInt16 address, UInt8 mask, UInt8 value) { pinfo("Enqueue: Address = 0x%04x; Mask = 0x%02x; Value = 0x%02x.", address, mask, value); return this->enqueueCommand(Command::forWriteRegister(address, mask, value)); } /// /// Enqueue a command to check the value of the register at the given address conveniently /// /// @param address The register address /// @param mask The register value mask /// @param value The register value /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full. /// @note Port: This function replaces `rtsx_pci/usb_add_cmd()` defined in `rtsx_psr/usb.c`. /// inline IOReturn enqueueCheckRegisterCommand(UInt16 address, UInt8 mask, UInt8 value) { pinfo("Enqueue: Address = 0x%04x; Mask = 0x%02x; Value = 0x%02x.", address, mask, value); return this->enqueueCommand(Command::forCheckRegister(address, mask, value)); } /// /// Enqueue a sequence of commands to read registers conveniently /// /// @param pairs A sequence of pairs of register address and value /// @return `kIOReturnSuccess` on success, `kIOReturnError` otherwise. /// @note This function provides an elegant way to enqueue multiple commands and handle errors. /// inline IOReturn enqueueReadRegisterCommands(const ChipRegValuePairs& pairs) { // Enqueue a command auto action = [&](ChipRegValuePair pair) -> IOReturn { return this->enqueueReadRegisterCommand(pair.address); }; return pairs.forEachUntil(action, kIOReturnSuccess); } /// /// Enqueue a sequence of commands to write registers conveniently /// /// @param pairs A sequence of pairs of register address and value /// @return `kIOReturnSuccess` on success, `kIOReturnError` otherwise. /// @note This function provides an elegant way to enqueue multiple commands and handle errors. /// inline IOReturn enqueueWriteRegisterCommands(const ChipRegValuePairs& pairs) { // Enqueue a command auto action = [&](ChipRegValuePair pair) -> IOReturn { return this->enqueueWriteRegisterCommand(pair.address, pair.mask, pair.value); }; return pairs.forEachUntil(action, kIOReturnSuccess); } /// /// Transfer a sequence of commands to read registers conveniently /// /// @param pairs A sequence of pairs of register address and value /// @param timeout Specify the amount of time in milliseconds /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, `kIOReturnError` otherwise. /// @note This function provides an elegant way to start a command transfer session and handle errors. /// Same as calling `startCommandTransfer`, a sequence of `enqueueReadRegisterCommand` and `endCommandTransfer`. /// inline IOReturn transferReadRegisterCommands(const ChipRegValuePairs& pairs, UInt32 timeout = 100, UInt32 flags = 0) { // Enqueue commands auto action = [&]() -> IOReturn { return this->enqueueReadRegisterCommands(pairs); }; return this->withCustomCommandTransfer(action, timeout, flags); } /// /// Transfer a sequence of commands to write registers conveniently /// /// @param pairs A sequence of pairs of register address and value /// @param timeout Specify the amount of time in milliseconds /// @param flags An optional flag, 0 by default /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// @note This function provides an elegant way to start a command transfer session and handle errors. /// Same as calling `startCommandTransfer`, a sequence of `enqueueWriteRegisterCommand` and `endCommandTransfer`. /// inline IOReturn transferWriteRegisterCommands(const ChipRegValuePairs& pairs, UInt32 timeout = 100, UInt32 flags = 0) { // Enqueue commands auto action = [&]() -> IOReturn { return this->enqueueWriteRegisterCommands(pairs); }; return this->withCustomCommandTransfer(action, timeout, flags); } // // MARK: - Host Data Management // public: /// /// Perform a DMA read operation /// /// @param descriptor A non-null, perpared memory descriptor /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// virtual IOReturn performDMARead(IOMemoryDescriptor* descriptor, UInt32 timeout) = 0; /// /// Perform a DMA write operation /// /// @param descriptor A non-null, perpared memory descriptor /// @param timeout Specify the amount of time in milliseconds /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// virtual IOReturn performDMAWrite(IOMemoryDescriptor* descriptor, UInt32 timeout) = 0; // // MARK: - Clear Error // protected: /// /// Clear any transfer error on the card side /// /// @note Port: This function replaces the code block that stops the card and clears the card errorin `sd_clear_error()` defined in `rtsx_pci/usb_sdmmc.c`. /// virtual void clearCardError() = 0; /// /// Clear any transfer error on the host side /// /// @note This function is invoked when a command or data transfer has failed. /// virtual void clearHostError() = 0; public: /// /// Clear any transfere error on the both sides /// /// @note This function invokes `clearCardError()` and `clearHostError()`. /// @note Port: This function replaces `sd_clear_error()` defined in `rtsx_pci/usb_sdmmc.c`. /// void clearError(); // // MARK: - LED Management // public: /// /// Turn on the LED /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// virtual IOReturn turnOnLED() = 0; /// /// Turn off the LED /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// virtual IOReturn turnOffLED() = 0; /// /// Enable LED blinking /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// virtual IOReturn enableLEDBlinking() = 0; /// /// Disable LED blinking /// /// @return `kIOReturnSuccess` on success, `kIOReturnTimeout` if timed out, `kIOReturnError` otherwise. /// virtual IOReturn disableLEDBlinking() = 0; // // MARK: - Card Selection, Share Mode and Transfer Properties // public: /// /// Select the SD card /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn selectCard() = 0; /// /// Select the data source for the SD card /// /// @param ppbuf `True` if the data source should be set to the ping pong buffer; /// `False` if the data source should be the ring buffer instead /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn selectCardDataSource(bool ppbuf) = 0; /// /// Select the data source to the ping pong buffer for the SD card conveniently /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// inline IOReturn selectCardDataSourceToPingPongBuffer() { return this->selectCardDataSource(true); } /// /// Select the data source to the ring buffer for the SD card conveniently /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// inline IOReturn selectCardDataSourceToRingBuffer() { return this->selectCardDataSource(false); } /// /// Configure the card share mode /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn configureCardShareMode() = 0; /// /// Setup the properties for a DMA transfer session /// /// @param length The number of bytes to be transferred /// @param direction `kIODirectionIn` if it is an inbound DMA transfer; /// `kIODirectionOut` if it is an outbound DMA transfer /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// @note The given direction is guaranteed to be either `kIODirectionIn` or `kIODirectionOut`. /// virtual IOReturn setupCardDMATransferProperties(UInt32 length, IODirection direction) = 0; // // MARK: - Card Power Management // public: /// /// Enable the card clock /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn enableCardClock() = 0; /// /// Disable the card clock /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn disableCardClock() = 0; /// /// Enable the card output /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn enableCardOutput() = 0; /// /// Disable the card output /// /// @return `kIOReturnSuccess` on success, `kIOReturnBusy` if the command buffer is full, `kIOReturnError` otherwise. /// @note This function invokes `enqueueWriteRegisterCommand()` thus must be invoked between `beginCommandTransfer()` and `endCommandTransfer()`. /// @note The caller may use `withCustomCommandTransfer()` to combine this operation with other ones. /// virtual IOReturn disableCardOutput() = 0; /// /// Power on the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn powerOnCard() = 0; /// /// Power off the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn powerOffCard() = 0; /// /// Switch to the given output voltage /// /// @param outputVoltage The new output voltage /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn switchOutputVoltage(OutputVoltage outputVoltage) = 0; // // MARK: - Card Clock Configurations // protected: /// /// Get the card clock and the divider for the initial mode /// /// @return A pair of card clock in Hz (first) and the clock divider register value (second). /// @note This function uses a 30 MHz carc clock and a divider of 128 as the default values. /// RTS5261 controller must override this function to set a higher initial card clock /// and divider for chips whose revision is higher than C. /// virtual Pair<UInt32, UInt32> getInitialCardClockAndDivider(); /// /// Adjust the card clock if DMA transfer errors occurred /// /// @param cardClock The current card clock in Hz /// @return The adjusted card clock. /// @note Port: This function replaces the code block that reduces the card clock in `rtsx_pci_switch_clock()` defined in `rtsx_psr.c`. /// By default, this function does not adjust the card clock and return the given clock. /// RTS5227 controller must override this function. /// virtual UInt32 getAdjustedCardClockOnDMAError(UInt32 cardClock); /// /// Convert the given SSC clock to the divider N /// /// @param clock The SSC clock in MHz /// @return The divider N. /// @note Port: This function replaces `conv_clk_and_div_n()` defined in `rtsx_psr.c` and the code block in `rtsx_usb_switch_clock()` defined in `rtsx_usb.c`. /// RTL8411 series controllers must override this function. /// virtual UInt32 sscClock2DividerN(UInt32 clock); /// /// Convert the given divider N back to the SSC clock /// /// @param n The divider N /// @return The SSC clock in MHz. /// @note Port: This function replaces `conv_clk_and_div_n()` defined in `rtsx_psr.c` and the code block in `rtsx_usb_switch_clock()` defined in `rtsx_usb.c`. /// RTL8411 series controllers must override this function. /// virtual UInt32 dividerN2SSCClock(UInt32 n); /// /// Calculate the number of MCUs from the given SSC clock /// /// @param clock The SSC clock in MHz /// @return The MCU count. /// @note Port: This function replaces the code block that calculates the MCU count in `rtsx_pci/usb_switch_clock()` defined in `rtsx_psr/usb.c`. /// @note Concrete controllers must ensure that the returned MCU count is less than or equal to 15. /// virtual UInt32 sscClock2MCUCount(UInt32 clock) = 0; /// /// Convert the given SSC depth to the actual register value /// /// @param depth The SSC depth /// @return The register value. /// virtual UInt8 sscDepth2RegValue(SSCDepth depth) = 0; /// /// Revise the given SSC depth register value /// /// @param depth The SSC depth register value /// @param divider The SSC clock divider value /// @return The revised SSC depth register value. /// virtual UInt8 reviseSSCDepthRegValue(UInt8 depth, UInt8 divider) = 0; /// /// Switch to the given SSC clock /// /// @param depth The SSC depth register value /// @param n The SSC clock n value /// @param divider The SSC clock divider /// @param mcus The number of MCUs /// @param vpclock `true` if VPCLOCK should be used /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note This function does the actual clock switching and is controller-dependent. /// virtual IOReturn switchCardClock(UInt8 depth, UInt8 n, UInt8 divider, UInt8 mcus, bool vpclock) = 0; public: /// /// Switch to the given card clock /// /// @param cardClock The card clock in Hz /// @param sscDepth The SSC depth value /// @param initialMode Pass `true` if the card is at its initial stage /// @param doubleClock Pass `true` if the SSC clock should be doubled /// @param vpclock Pass `true` if VPCLOCK is used /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces `rtsx_pci/usb_switch_clock()` defined in `rtsx_psr/usb.c`. /// IOReturn switchCardClock(UInt32 cardClock, SSCDepth sscDepth, bool initialMode, bool doubleClock, bool vpclock); // // MARK: - Card Detection and Write Protection // public: /// /// Check whether the card has write protection enabled /// /// @return `true` if the card is write protected, `false` otherwise. /// virtual bool isCardWriteProtected() = 0; /// /// Check whether a card is present /// /// @return `true` if a card exists, `false` otherwise. /// @warning: This function supports SD cards only. /// virtual bool isCardPresent() = 0; /// /// Check whether the command line of the card is busy /// /// @return `true` if the card CMD line is busy, `false` otherwise. /// @warning This function returns `true` if failed to read the register. /// virtual bool isCardCommandLineBusy() = 0; /// /// Check whether the data line of the card is busy /// /// @return `true` if the card DAT lines are busy, `false` otherwise. /// @warning This function returns `true` if failed to read the register. /// virtual bool isCardDataLineBusy() = 0; // // MARK: - Card Pull Control Management // public: /// /// Enable pull control for the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn enablePullControlForSDCard() = 0; /// /// Disable pull control for the SD card /// /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn disablePullControlForSDCard() = 0; // // MARK: - Card Tuning & Phase Management // public: /// /// Change the Rx phase /// /// @param samplePoint The sample point value /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the Rx portion of `sd_change_phase()` defined in `rtsx_pci/usb_sdmmc.c`. /// virtual IOReturn changeRxPhase(UInt8 samplePoint) = 0; /// /// Change the Tx phase /// /// @param samplePoint The sample point value /// @return `kIOReturnSuccess` on success, other values otherwise. /// @note Port: This function replaces the Tx portion of `sd_change_phase()` defined in `rtsx_pci/usb_sdmmc.c`. /// virtual IOReturn changeTxPhase(UInt8 samplePoint) = 0; // // MARK: - Ping Pong Buffer // public: /// /// Read from the ping pong buffer /// /// @param destination The buffer to store bytes /// @param length The number of bytes to read (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// DEPRECATE("Use readPingPongBuffer(IOIOMemoryDescriptor*, IOByteCount) to avoid unnecessary buffer copies.") virtual IOReturn readPingPongBuffer(UInt8* destination, IOByteCount length) = 0; /// /// Write to the ping pong buffer /// /// @param source The buffer to write /// @param length The number of bytes to write (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// DEPRECATE("Use readPingPongBuffer(IOIOMemoryDescriptor*, IOByteCount) to avoid unnecessary buffer copies.") virtual IOReturn writePingPongBuffer(const UInt8* source, IOByteCount length) = 0; /// /// Read from the ping pong buffer /// /// @param destination The buffer to store bytes /// @param length The number of bytes to read (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn readPingPongBuffer(IOMemoryDescriptor* destination, IOByteCount length) = 0; /// /// Write to the ping pong buffer /// /// @param source The buffer to write /// @param length The number of bytes to write (cannot exceed 512 bytes) /// @return `kIOReturnSuccess` on success, other values otherwise. /// virtual IOReturn writePingPongBuffer(IOMemoryDescriptor* source, IOByteCount length) = 0; // // MARK: - Active State Power Management // public: /// /// Notify the card reader to enter into the worker state /// virtual void enterWorkerState() {}; // // MARK: - Power Management // protected: /// /// Prepare to enter the sleep state /// /// @note The base class provides an implementation that detaches the card. /// Concrete controllers must call this function before turning off the card reader. /// virtual void prepareToSleep(); /// /// Prepare to wake up from sleep /// /// @note The base class provides an implementation that attaches the card if present. /// Concrete controllers must turn on the card reader before calling this function. /// virtual void prepareToWakeUp(); public: /// /// Adjust the power state in response to system-wide power events /// /// @param powerStateOrdinal The number in the power state array of the state the driver is being instructed to switch to /// @param whatDevice A pointer to the power management object which registered to manage power for this device /// @return `kIOPMAckImplied` always. /// IOReturn setPowerState(unsigned long powerStateOrdinal, IOService* whatDevice) override; // // MARK: - Interrupt Service Routines // protected: /// /// Helper interrupt service routine when a SD card is inserted /// /// @param completion A nullable completion routine to be invoked when the card is attached /// @param options An optional value passed to the host driver /// @note This interrupt service routine runs in a gated context. /// @note Port: This function replaces `rtsx_pci_card_detect()` defined in `rtsx_psr.c` but has a completely different design and implementation. /// This function is invoked by the polling thread when a SD card has been inserted to the USB card reader. /// void onSDCardInsertedGated(IOSDCard::Completion* completion = nullptr, IOSDCard::EventOptions options = 0); /// /// Helper interrupt service routine when a SD card is removed /// /// @param completion A nullable completion routine to be invoked when the card is detached /// @param options An optional value passed to the host driver /// @note This interrupt service routine runs in a gated context. /// @note Port: This function replaces `rtsx_pci_card_detect()` defined in `rtsx_psr.c` but has a completely different design and implementation. /// This function is invoked by the polling thread when a SD card has been removed from the USB card reader. /// void onSDCardRemovedGated(IOSDCard::Completion* completion = nullptr, IOSDCard::EventOptions options = 0); private: /// /// Helper interrupt service routine that runs synchronously when a SD card is inserted /// /// @param options An optional value passed to the host driver /// @return `kIOReturnSuccess` if the card has been initialized and attached successfully, other values otherwise. /// @note This interrupt service routine runs in a gated context. /// @note This function simply invokes the asynchronous interrupt service routine `onSDCardInsertedGated()` and /// calls `IOCommandGate::commandSleep()` to wait until the host driver finishes processing the event. /// IOReturn onSDCardInsertedSyncGated(IOSDCard::EventOptions options = 0); /// /// Helper interrupt service routine that runs synchronously when a SD card is removed /// /// @param options An optional value passed to the host driver /// @return `kIOReturnSuccess` if the card has been detached and removed successfully, other values otherwise. /// @note This interrupt service routine runs in a gated context. /// @note This function simply invokes the asynchronous interrupt service routine `onSDCardRemovedGated()` and /// calls `IOCommandGate::commandSleep()` to wait until the host driver finishes processing the event. /// IOReturn onSDCardRemovedSyncGated(IOSDCard::EventOptions options = 0); /// /// The completion action used by synchronous card interrupt service routines /// /// @param parameter An opaque client-supplied parameter pointer /// @param status `kIOReturnSuccess` if the card event has been processed without errors, other values otherwise. /// @param characteristics A non-null dictionary that contains characteristics of the card inserted and initialized successfully, /// `nullptr` if the card inserted by users cannot be initialized or has been removed from the card slot. /// void onSDCardEventProcessedSyncCompletion(void* parameter, IOReturn status, OSDictionary* characteristics); /// /// Helper interrupt service routine that runs synchronously when a SD card is inserted /// /// @param options An optional value passed to the host driver /// @return `kIOReturnSuccess` if the card has been initialized and attached successfully, other values otherwise. /// inline IOReturn onSDCardInsertedSync(IOSDCard::EventOptions options = 0) { auto action = [&]() -> IOReturn { return this->onSDCardInsertedSyncGated(options); }; return IOCommandGateRunAction(this->commandGate, action); } /// /// Helper interrupt service routine that runs synchronously when a SD card is removed /// /// @param options An optional value passed to the host driver /// @return `kIOReturnSuccess` if the card has been detached and removed successfully, other values otherwise. /// inline IOReturn onSDCardRemovedSync(IOSDCard::EventOptions options = 0) { auto action = [&]() -> IOReturn { return this->onSDCardRemovedSyncGated(options); }; return IOCommandGateRunAction(this->commandGate, action); } // // MARK: - Startup Routines // private: /// /// Setup the power management /// /// @param provider The provider /// @return `true` on success, `false` otherwise. /// bool setupPowerManagement(IOService* provider); /// /// Setup the workloop /// /// @return `true` on success, `false` otherwise. /// bool setupWorkLoop(); /// /// Create the card slot and publish it /// /// @return `true` on success, `false` otherwise. /// @note This function is a private helper of `RealtekCardReaderController::createCardSlot().` /// @note When this function is called, the card slot is guaranteed to be non-null. /// bool setupCardSlot(); protected: /// /// Create the card slot and publish it /// /// @tparam Slot Specify the class of the card slot /// @return `true` on success, `false` otherwise. /// @note Concrete controllers must invoke this function after the hardware is initialized. /// template <typename Slot> bool createCardSlot() { pinfo("Allocating the card slot..."); this->slot = OSTypeAlloc(Slot); if (this->slot != nullptr) { return this->setupCardSlot(); } else { perr("Failed to allocate the card slot."); return false; } } // // MARK: - Teardown Routines // private: /// /// Tear down the power management /// void tearDownPowerManagement(); /// /// Tear down the workloop /// void tearDownWorkLoop(); protected: /// /// Destroy the card slot /// void destroyCardSlot(); // // MARK: - IOService Implementations // public: /// /// Initialize the controller /// /// @return `true` on success, `false` otherwise. /// bool init(OSDictionary* dictionary = nullptr) override; /// /// Start the controller /// /// @param provider The provider /// @return `true` on success, `false` otherwise. /// bool start(IOService* provider) override; /// /// Stop the controller /// /// @param provider The provider /// void stop(IOService* provider) override; }; #endif /* RealtekCardReaderController_hpp */ <|start_filename|>RealtekCardReader/IOSDHostDriverUserConfigs.hpp<|end_filename|> // // IOSDHostDriverUserConfigs.hpp // RealtekCardReader // // Created by FireWolf on 8/20/21. // #ifndef IOSDHostDriverUserConfigs_hpp #define IOSDHostDriverUserConfigs_hpp #include <IOKit/IOTypes.h> /// Boot arguments that customize the card initialization and the host driver behavior namespace UserConfigs::Card { /// `True` if the card should be initialized at 3.3V extern bool InitAt3v3; /// `True` if the card should be initialized at the default speed mode extern bool InitAtDefaultSpeed; /// `True` if the card should be initialized at the high speed mode extern bool InitAtHighSpeed; /// `True` if the driver should separate each CMD18/25 request into multiple CMD17/24 ones extern bool SeparateAccessBlocksRequest; /// `True` if the driver should not issue the ACMD23 command when processing CMD25 requests extern bool NoACMD23; /// Specify the maximum number of attempts to retry an application command extern UInt32 ACMDMaxNumAttempts; } #endif /* IOSDHostDriverUserConfigs_hpp */
0xFireWolf/RealtekCardReader
<|start_filename|>Makefile<|end_filename|> test: @echo "---- Running tests ----" @./vendor/bin/phpunit test-coverage: @echo "---- Running tests with coverage report ----" @./vendor/bin/phpunit --coverage-text
rafaelfragosom/php-haversine-formula
<|start_filename|>gpath_test.go<|end_filename|> package gpath_test import ( "fmt" "reflect" "testing" . "github.com/tenntenn/gpath" ) type Hoge struct { Foo *Foo } type Foo struct { Bar *Bar } type Bar struct { N int } func ExampleAt() { type Bar struct { N []int } type Foo struct { Bar *Bar } f := &Foo{ Bar: &Bar{ N: []int{100}, }, } v, err := At(f, `Bar.N[0]`) if err != nil { fmt.Println(err) } else { fmt.Println(v) } // Output: // 100 } func TestAt(t *testing.T) { data := []struct { d interface{} p string e interface{} hasErr bool }{ { d: struct { A int }{ A: 100, }, p: "A", e: 100, }, { d: struct { A []int }{ A: []int{100, 200}, }, p: "A[1]", e: 200, }, { d: struct { A map[string][]int }{ A: map[string][]int{ "foo": {100, 200}, }, }, p: `A["foo"][1]`, e: 200, }, { d: struct { A map[int][]int }{ A: map[int][]int{ 200: {100, 200}, }, }, p: `A[200][1]`, e: 200, }, { d: struct { A struct { B int } }{ A: struct { B int }{ B: 100, }, }, p: `A.B`, e: 100, }, { d: struct { A struct { B int } }{ A: struct { B int }{ B: 100, }, }, p: `A.C`, hasErr: true, }, { d: &Hoge{ Foo: &Foo{ Bar: &Bar{ N: 100, }, }, }, p: `Foo.Bar`, e: &Bar{N: 100}, }, { d: struct { N []int }{ N: []int{100}, }, p: `N[0]`, e: 100, }, { p: `import "fmt"`, hasErr: true, }, { p: `Call()`, hasErr: true, }, { d: struct { N map[int]int }{ N: map[int]int{-1: 100}, }, p: `N[-1]`, e: 100, }, { d: struct { N map[int]int }{ N: map[int]int{0: 100}, }, p: `N[1-1]`, e: 100, }, { d: struct { N map[int]int }{ N: map[int]int{0: 100}, }, p: `N[(0)]`, e: 100, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[true]`, e: 100, }, { d: struct { N map[bool]int }{ N: map[bool]int{false: 100}, }, p: `N[false]`, e: 100, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[100 > 0]`, e: 100, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[true]`, e: 100, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[1 + f()]`, hasErr: true, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[T]`, hasErr: true, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[-T]`, hasErr: true, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N[T - 1]`, hasErr: true, }, { d: struct { N map[bool]int }{ N: map[bool]int{true: 100}, }, p: `N["key" + 1]`, hasErr: true, }, { d: struct { N map[int]int }{ N: map[int]int{10: 100}, }, p: `N[99999999999999999999999999999]`, hasErr: true, }, { d: struct { N []int }{ N: []int{100}, }, p: `N[99999999999999999999999999999]`, hasErr: true, }, { d: struct { N map[float64]int }{ N: map[float64]int{1.5: 100}, }, p: `N[1.5]`, e: 100, }, { d: struct { N map[float64]int }{ N: map[float64]int{1.5: 100}, }, p: `N[99999999999999999999999999999999999.0]`, hasErr: true, }, { d: struct { N map[int]int }{ N: map[int]int{100: 100}, }, p: `N[0]`, e: nil, }, { d: 100, p: `N[0]`, hasErr: true, }, { d: 100, p: `A.B[0]`, hasErr: true, }, { d: struct { N int }{ N: 100, }, p: `N[0]`, hasErr: true, }, } for i := range data { a, err := At(data[i].d, data[i].p) if data[i].hasErr { if err == nil { t.Errorf("expected error did not occur") continue } } else if err != nil { t.Errorf("unexpected error: %v", err) continue } if !reflect.DeepEqual(a, data[i].e) { t.Errorf("case %d: got %v want %v", i, a, data[i].e) } } } <|start_filename|>gpath.go<|end_filename|> package gpath import ( "errors" "go/ast" "go/constant" "go/parser" "reflect" ) // At access a field of v by a path. // v must be struct or pointer of struct. // A path is represented by Go's expression which can be parsed by go/parser.ParseExpr. // You can use selectors and indexes in a path. // Slice and arrays index allow only expressions of int. // Maps key allow only expressions of string, int and float64. func At(v interface{}, path string) (interface{}, error) { path = "v." + path expr, err := parser.ParseExpr(path) if err != nil { return nil, err } ev, err := at(reflect.ValueOf(v), expr) if err != nil { return nil, err } if ev == (reflect.Value{}) { return nil, nil } return ev.Interface(), nil } func at(v reflect.Value, expr ast.Expr) (reflect.Value, error) { switch v.Kind() { case reflect.Ptr, reflect.Interface: return at(v.Elem(), expr) } switch expr := expr.(type) { case *ast.Ident: return v, nil case *ast.SelectorExpr: return atBySelector(v, expr) case *ast.IndexExpr: return atByIndex(v, expr) default: return reflect.Value{}, errors.New("does not support expr") } } func direct(v reflect.Value) reflect.Value { switch v.Kind() { case reflect.Ptr, reflect.Interface: return v.Elem() default: return v } } func atBySelector(v reflect.Value, expr *ast.SelectorExpr) (reflect.Value, error) { ev, err := at(v, expr.X) if err != nil { return reflect.Value{}, err } ev = direct(ev) switch ev.Kind() { case reflect.Struct: fv := ev.FieldByName(expr.Sel.Name) if fv == (reflect.Value{}) { return reflect.Value{}, errors.New("cannot find field") } return fv, nil default: return reflect.Value{}, errors.New("does not support selector type") } } func atByIndex(v reflect.Value, expr *ast.IndexExpr) (reflect.Value, error) { ev, err := at(v, expr.X) if err != nil { return reflect.Value{}, err } ev = direct(ev) idx, err := evalExpr(expr.Index) if err != nil { return reflect.Value{}, err } switch ev.Kind() { case reflect.Slice, reflect.Array: i, ok := constant.Int64Val(idx) if !ok { return reflect.Value{}, errors.New("does not support index type") } return ev.Index(int(i)), nil case reflect.Map: switch idx.Kind() { case constant.Int: k, ok := constant.Int64Val(idx) if !ok { return reflect.Value{}, errors.New("does not support index type") } return ev.MapIndex(reflect.ValueOf(int(k))), nil case constant.Float: k, ok := constant.Float64Val(idx) if !ok { return reflect.Value{}, errors.New("does not support index type") } return ev.MapIndex(reflect.ValueOf(k)), nil case constant.String: k := constant.StringVal(idx) return ev.MapIndex(reflect.ValueOf(k)), nil case constant.Bool: k := constant.BoolVal(idx) return ev.MapIndex(reflect.ValueOf(k)), nil default: return reflect.Value{}, errors.New("does not support index type") } default: return reflect.Value{}, errors.New("does not support expr type") } } <|start_filename|>eval.go<|end_filename|> package gpath import ( "errors" "fmt" "go/ast" "go/constant" "go/token" ) func evalExpr(expr ast.Expr) (v constant.Value, rerr error) { defer func() { if r := recover(); r != nil { v, rerr = constant.MakeUnknown(), fmt.Errorf("%v", r) } }() switch e := expr.(type) { case *ast.ParenExpr: return evalExpr(e.X) case *ast.BinaryExpr: return evalBinaryExpr(e) case *ast.UnaryExpr: return evalUnaryExpr(e) case *ast.BasicLit: return constant.MakeFromLiteral(e.Value, e.Kind, 0), nil case *ast.Ident: return evalIdent(e) } return constant.MakeUnknown(), errors.New("unknown node") } func evalBinaryExpr(expr *ast.BinaryExpr) (constant.Value, error) { x, err := evalExpr(expr.X) if err != nil { return constant.MakeUnknown(), err } y, err := evalExpr(expr.Y) if err != nil { return constant.MakeUnknown(), err } switch expr.Op { case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ: return constant.MakeBool(constant.Compare(x, expr.Op, y)), nil } return constant.BinaryOp(x, expr.Op, y), nil } func evalUnaryExpr(expr *ast.UnaryExpr) (constant.Value, error) { x, err := evalExpr(expr.X) if err != nil { return constant.MakeUnknown(), err } return constant.UnaryOp(expr.Op, x, 0), nil } func evalIdent(expr *ast.Ident) (constant.Value, error) { switch { case expr.Name == "true": return constant.MakeBool(true), nil case expr.Name == "false": return constant.MakeBool(false), nil } return constant.MakeUnknown(), errors.New("unknown ident") }
tenntenn/gpath
<|start_filename|>easydata/src/main/java/com/ali77gh/easydata/repos/ByteDAO.kt<|end_filename|> package com.ali77gh.easydata.repos import android.content.Context import android.os.Handler import android.os.Looper import java.io.* /** * Created by ali on 8/20/18. */ class ByteDAO( context: Context, mode: RootMode ) : GRepo(context, mode) { fun load(filename: String): ByteArray? { val path = "$root/$filename" val size = File(path).length().toInt() val bytes = ByteArray(size) try { val buf = BufferedInputStream(FileInputStream(path)) buf.read(bytes, 0, bytes.size) buf.close() return bytes } catch (e: IOException) { e.printStackTrace() } return null } fun loadAsync(filename: String, callback: (bytes:ByteArray?)->Unit) { Thread { val bytes = load(filename) Handler(Looper.getMainLooper()).post { callback(bytes) } }.start() } fun save(filename: String, bytes: ByteArray) { val path = "$root/$filename" val out = FileOutputStream(path) out.write(bytes) out.flush() out.close() } fun saveAsync(filename: String, bytes: ByteArray, callback: ()->Unit={}) { Thread { save(filename, bytes) Handler(Looper.getMainLooper()).post { callback() } }.start() } } <|start_filename|>app/src/main/java/com/ali77gh/easydataexample/User.kt<|end_filename|> package com.ali77gh.easydataexample import android.content.Context import com.ali77gh.easydata.IORun import com.ali77gh.easydata.sqlite.EasyTable import com.ali77gh.easydata.sqlite.Model /** * Created by ali on 8/23/18. */ class Loc(val lat:Double,val lng:Double) class User( override var id: String, var hashPass: String, var name: String, var age :Int, var role:String, var money:Int, var marks :List<Float>?=null, var locations: List<Loc>?=null ) : Model { class UserTable(context: Context) : EasyTable<User>(context, User::class.java,autoSetId = false) { // custom queries here fun getByName(name: String) = filter { it.name==name } val admins get() = filter { it.role=="admin" } fun isAdmin(id: String) = any { it.id==id && it.role=="admin" } // reusable val top5Richs get() = sortedByDescending { it.money }.subList(0,5) fun checkPassword(id:String, hashPass:String) = getById(id)!!.hashPass==hashPass fun isUnderAge(id:String) = any{ it.id==id && it.age<18 } fun removeUnderAges() = deleteWhere { it.age < 18 } fun increaseAges1() = updateAll { it.age++ return@updateAll it } fun increaseAges2() = updateAll {it.age++;it} fun increaseAges3() = updateAll {it.apply{ age++ }} fun increaseRoleOfAlis() = updateWhere({it.name=="ali"},{it.role="admin";it}) fun asyncGetByName(name:String,cb:(user: User)->Unit) = IORun( {filter { it.name==name }[0]} , cb ) } // repo singleton companion object { private var repo: UserTable? = null fun getRepo(context: Context): UserTable { if (repo ==null) repo = UserTable(context) return repo!! } } } <|start_filename|>app/src/main/java/com/ali77gh/easydataexample/Settings.kt<|end_filename|> package com.ali77gh.easydataexample import android.content.Context import com.ali77gh.easydata.repos.StringDAO class Settings private constructor(context: Context) { private val repo = StringDAO(context) var theme get() = repo.load("theme","dark") set(value) = repo.save("theme",value) var notification : Boolean get() = repo.load("notification","true").toBoolean() set(value) = repo.save("notification",value.toString()) var lastLogin : Long get() = repo.load("lastLogin","0").toLong() set(value) = repo.save("lastLogin",value.toString()) enum class DateSystem{Jalali,Hijri,Gregorian} var dateSystem : DateSystem get() = DateSystem.valueOf(repo.load("dateSystem", DateSystem.Jalali.name)) set(value) = repo.save("dateSystem",value.name) companion object{ var settings: Settings?= null fun get(context: Context): Settings { if (settings ==null) settings = Settings(context) return settings!! } } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/repos/BitmapDAO.kt<|end_filename|> package com.ali77gh.easydata.repos import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Handler import android.os.Looper import java.io.File import java.io.FileOutputStream /** * Created by ali on 8/20/18. */ class BitmapDAO( context: Context, mode: RootMode ) : GRepo(context, mode) { @SuppressWarnings("loading bitmap in main thread not recommended (use loadSync)") fun load(fileName: String): Bitmap? { val path = "$root/$fileName" val f = File(path) return if (f.exists()) BitmapFactory.decodeFile(path) else null } fun loadAsync(filename: String, callback: (bitmap:Bitmap?)->Unit) { Thread { val bitmap = load(filename) Handler(Looper.getMainLooper()).post { callback(bitmap) } }.start() } @SuppressWarnings("loading bitmap in main thread not recommended (use saveAsync)") fun save( filename: String, bitmap: Bitmap, quality:Int=100, width:Int=bitmap.width, height:Int=bitmap.height ) { val path = "$root/$filename" val out = FileOutputStream(path) val resized = Bitmap.createScaledBitmap(bitmap,width , height, false) resized.compress(Bitmap.CompressFormat.PNG, quality, out) out.flush() out.close() } fun saveAsync( filename: String, bitmap: Bitmap, quality:Int=100, width:Int=bitmap.width, height:Int=bitmap.height, callback: ()->Unit ) { Thread { save(filename, bitmap,quality,width,height) Handler(Looper.getMainLooper()).post { callback() } }.start() } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/repos/ObjectDAO.kt<|end_filename|> package com.ali77gh.easydata.repos import android.content.Context import android.os.Handler import android.os.Looper import com.google.gson.Gson /** * Created by ali on 8/22/18. */ class ObjectDAO( context: Context, mode: RootMode ) : GRepo(context,mode) { private val gson = Gson() private val stringRepo = StringDAO(context,mode) fun load(filename: String, type: Class<*>) = gson.fromJson( stringRepo.load(filename), type ) fun loadAsync(filename: String, type: Class<*>, callback: (data:Any)->Unit) { Thread { val obj = load(filename, type) Handler(Looper.getMainLooper()).post { callback(obj) } }.start() } fun save(filename: String, obj: Any) = stringRepo.save(filename, gson.toJson(obj)) fun saveAsync(filename: String, obj: Any, callback: ()->Unit={}) { Thread { save(filename, obj) Handler(Looper.getMainLooper()).post { callback() } }.start() } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/sqlite/EasyTable.kt<|end_filename|> package com.ali77gh.easydata.sqlite import android.content.Context import java.util.* import kotlin.collections.ArrayList abstract class EasyTable<T : Model>( context: Context, private val type: Class<T>, tableName: String = type.simpleName, private var autoSetId: Boolean = false ) : KeyValDb(context,tableName) , Iterable<T>{ // Insert open fun insert(row: T) { if (autoSetId) row.id = UUID.randomUUID().toString() add(row.id, row) } open fun insertMany(rows:Iterable<T>) = rows.forEach { insert(it) } // Update open fun update(row: T) = super.update(row.id, row) open fun updateMany(rows: Iterable<T>) = rows.forEach { update(it.id, it) } open fun updateAll(change:(row:T)->T) = updateMany(map(change)) open fun updateWhere(condition: (obj: T) -> Boolean, change:(row:T)->T) = updateMany(filter(condition).map(change)) //Delete open fun deleteWhere(condition: (obj: T) -> Boolean) = deleteMany(filter(condition).map { it.id }.toTypedArray()) //Read open fun toList(): ArrayList<T> { val list = ArrayList<T>() val itr = iterator() while (itr.hasNext()) list.add(itr.next()) return list } /** * @return null if not found */ open fun getById(id: String) = gson.fromJson<T>(super.getByIdStr(id),type) /** * this is faster then filter { it.id = ids.contains() } */ open fun getByIds(id: List<String>) = super.getByIdsStr(id).map { gson.fromJson(it,type) } /** * @return null if not found */ open fun getOne(condition: (obj: T) -> Boolean):T?{ for(row in this) if (condition(row)) return row return null } override fun iterator(): Iterator<T> { val itr = super.innerIterator() return object : Iterator<T> { override fun hasNext(): Boolean { return itr.hasNext() } override fun next(): T { return gson.fromJson( itr.next(), type ) as T } } } } <|start_filename|>app/src/main/java/com/ali77gh/easydataexample/TestActivity.kt<|end_filename|> package com.ali77gh.easydataexample import android.app.Activity import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.util.Log import android.widget.ImageView import android.widget.TextView import com.ali77gh.easydataexample.R import com.ali77gh.easydata.repos.* import com.ali77gh.easydata.security.DeviceKeyGenerator import com.google.gson.Gson import java.util.* import kotlin.system.measureTimeMillis class TestActivity : Activity() { private var log: TextView? = null private var image: ImageView? = null // Tools private val bitmapForTest: Bitmap get() = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) private fun log(msg: String){ Log.d("test",msg) log!!.append("$msg\n") } private fun logTitle(title:String) = log("\n----- $title -----") private fun test(name:String,bool:Boolean) = log(name+"\t\t\t" + if (bool) " passed!" else " failed! ") private fun test(name:String,a:Any,b:Any) = test(name,a==b) fun logUI(msg:String)=runOnUiThread { log(msg) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test) log = findViewById(R.id.logger) image = findViewById(R.id.image) // bitmapTest() // byteTest() // stringTest() // objectTest() // genericDAOTest() // genericDAOTestHeavy() // testSafeBox() // performanceTest() testSettings() } private fun bitmapTest() { logTitle("bitmap test") val bitmapDAO = BitmapDAO(this, RootMode.LOCAL) // Sync bitmapDAO.save("testBitmap.bmp",bitmapForTest,100) test("testBitmap.bmp",bitmapDAO.checkExist("testBitmap.bmp")) bitmapDAO.save("testBitmap50.bmp",bitmapForTest,50) test("testBitmap50.bmp",bitmapDAO.checkExist("testBitmap50.bmp")) bitmapDAO.save("testBitmap10px.bmp",bitmapForTest, width=10, height=10) test("testBitmap10px.bmp",bitmapDAO.checkExist("testBitmap10px.bmp")) // Async bitmapDAO.saveAsync("testBitmapAsync.bmp", bitmapForTest, callback = { test("testBitmapAsync.bmp",bitmapDAO.checkExist("testBitmapAsync.bmp")) }) Thread.sleep(1000) log("bitmap tests all done!") } private fun byteTest() { logTitle("byte test") val byteDAO = ByteDAO(this, RootMode.LOCAL) val bytes = ByteArray(4) bytes[0] = 1 bytes[1] = 1 bytes[2] = 0 bytes[3] = 1 // saving byteDAO.save("test", bytes) test("saving",byteDAO.checkExist("test")) // loading val loadedBytes: ByteArray = byteDAO.load("test")!! test("byte eq:",loadedBytes[0],bytes[0]) // removing byteDAO.remove("test") test("removing",!byteDAO.checkExist("test")) } private fun stringTest() { logTitle("string test") val stringDAO = StringDAO(this, RootMode.LOCAL) val string = "write this file" //saving stringDAO.save("test", string) test("saving",stringDAO.checkExist("test")) // loading val loadedString: String = stringDAO.load("test") test("byte eq:",loadedString,string) // removing stringDAO.remove("test") test("removing",!stringDAO.checkExist("test")) // default test("default",stringDAO.load("test","def"),"def") } private fun objectTest() { logTitle("object test") val dao = ObjectDAO(this, RootMode.LOCAL) val user = User("id","<PASSWORD>","ali",18,"admin",1000) dao.save("test", user) test("saving",dao.checkExist("test")) // loading val loaded: User = dao.load("test", User::class.java) as User test("equality:",loaded.name,user.name) // removing dao.remove("test") test("removing",!dao.checkExist("test")) } private fun genericDAOTest() { logTitle("generic test") val users = User.getRepo(this) val g = Gson() log("---before delete---") for(user in users) log(user.name) users.deleteWhere { true } log("---after delete---") for(user in users) log(user.name) //insert val u = User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000) users.insert(u) log("---after insert---") for(user in users) log(user.id) test("insert",users.getById(u.id)!!.name,"ali") //read test("read",users.toList().size,1) //update u.name = "hasan" users.update(u) test("update",users.getById(u.id)!!.name,"hasan") //delete users.deleteWhere { it.id==u.id } test("delete",users.toList().size,0) } private fun genericDAOTestHeavy() { logTitle("generic test heavy") val users = User.getRepo(this) users.deleteWhere { true } log("---after delete all") for(user in users) log(user.id) users.filter { true } //insert users.insert(User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000)) users.insert(User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000)) users.insert(User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000)) users.insert(User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000)) log("---after 4 inserts---") for(user in users) log(user.id) log("---filter---") for(user in users.filter { it.id.contains("e") }) log(user.id) log(users.sumBy { it.age }.toString()) } private fun performanceTest(){ logTitle("performance") Thread{ val users = User.getRepo(this) logUI("users size: ${users.toList().size}") val L = 10000 val g = Gson() val serializeTime = measureTimeMillis { for(i in 0..L){ val user = User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000) g.toJson(user) } } logUI("serializeTime: $serializeTime") val user = User(UUID.randomUUID().toString(),"pass","<PASSWORD>",18,"admin",1000) val str = g.toJson(user) val deserializeTime = measureTimeMillis { for(i in 0..L){ g.fromJson<User>(str, User::class.java) } } logUI("deserializeTime: $deserializeTime") val r = Random() val insertTime = measureTimeMillis { for(i in 0..L) users.insert(User(UUID.randomUUID().toString(),"pass","ali",18,"admin",1000)) } logUI("users size: ${users.toList().size}") logUI(" insert: $insertTime ms") val lastId = users.toList().last().id val getById = measureTimeMillis { users.getById(lastId) } logUI(" getById: $getById ms") val getWithFalsyFilter = measureTimeMillis { users.filter { false } } logUI(" getWithFalsyFilter: $getWithFalsyFilter ms") val readAllTime = measureTimeMillis { users.toList() } logUI(" readAllTime: $readAllTime ms") val readWithFilterTime = measureTimeMillis { users.filter { it.name=="ali" } } logUI(" readWithFilterTime: $readWithFilterTime ms") val readWithFilterAndMapTime = measureTimeMillis { users.filter { it.name=="ali" }.map { it.role } } logUI(" readWithFilterAndMapTime: $readWithFilterAndMapTime ms") val readWithMapAndFilterTime = measureTimeMillis { users.map { it.name }.filter { it=="ali" } } logUI(" readWithMapAndFilterTime: $readWithMapAndFilterTime ms") val updateAll = measureTimeMillis { users.updateWhere({it.name=="ali"},{it.apply { it.age=23 }}) } logUI(" updateAll: $updateAll ms") val updateOne = measureTimeMillis { users.updateWhere({it.id==lastId},{it.apply { it.age=25 }}) } logUI(" updateOne: $updateOne ms") val removeOne = measureTimeMillis { users.deleteWhere { it.id==lastId } } logUI(" removeOne: $removeOne ms") val removeAll = measureTimeMillis { users.deleteWhere { true } } logUI(" removeAll: $removeAll ms") }.start() } private fun testSafeBox() { logTitle("safebox test") val key = DeviceKeyGenerator.Generate(this) val safeBox = SafeBox(this, key) safeBox.save("password", "<PASSWORD>") var readed = safeBox.load("password") test("read eq",readed=="myPassword") safeBox.save("password", "<PASSWORD>") readed = safeBox.load("password") test("utf8",readed=="سلام") } private fun testSettings(){ logTitle("settings test") val now = Date().time Settings.get(this).theme = "dark" Settings.get(this).dateSystem = Settings.DateSystem.Gregorian Settings.get(this).notification = true Settings.get(this).lastLogin = now test("theme", Settings.get(this).theme, "dark") test("dateSystem", Settings.get(this).dateSystem, Settings.DateSystem.Gregorian) test("notif", Settings.get(this).notification, true) test("lastLogin", Settings.get(this).lastLogin, now) } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/sqlite/KeyValDb.kt<|end_filename|> package com.ali77gh.easydata.sqlite import android.content.ContentValues import android.content.Context import android.database.CursorIndexOutOfBoundsException import com.google.gson.Gson import kotlin.collections.ArrayList /** * Created by ali on 9/17/18. */ open class KeyValDb( context: Context, private var table: String="default" ){ private val db = context.openOrCreateDatabase("easydb", Context.MODE_PRIVATE, null) val gson: Gson = Gson() init { db.execSQL("CREATE TABLE IF NOT EXISTS $table(id VARCHAR PRIMARY KEY,value VARCHAR);") } fun add(id: String, obj: Any){ db.execSQL("INSERT INTO $table VALUES('$id','${gson.toJson(obj)}');") } val isEmpty: Boolean get() { val resultSet = db.rawQuery("Select * from $table;", null) resultSet.moveToFirst() return try { resultSet.getString(1) false } catch (e: CursorIndexOutOfBoundsException) { true } } protected fun update(id: String, obj: Any) { val contentValues = ContentValues().apply { put("value", gson.toJson(obj)) } db.update(table, contentValues, "id = ? ", arrayOf(id)) } protected fun getByIdStr(id:String):String?{ val cursor = db.rawQuery("Select value from $table where id='$id';", null)!! cursor.moveToFirst() if (cursor.isAfterLast) return null return cursor.getString(0) } /* * this is faster way because have no gson deserialize insides */ protected fun getByIdsStr(ids:List<String>):List<String>{ val idsMap = ids.associateBy { it } val result = ArrayList<String>() val cursor = db.rawQuery("Select * from $table;", null)!! cursor.moveToFirst() while (!cursor.isAfterLast) if (idsMap.containsKey(cursor.getString(0))) result.add(cursor.getString(1)) return result } fun delete(id: String) = db.delete(table, "id = ? ", arrayOf(id)) protected fun deleteMany(ids: Array<String>) = ids.forEach { delete(it) } fun drop() = db.execSQL("DROP TABLE IF EXISTS $table") // Iterable APIs protected fun innerIterator() :Iterator<String>{ val resultSet = db.rawQuery("Select value from $table;", null)!! resultSet.moveToFirst() return object : Iterator<String> { override fun hasNext(): Boolean { return !resultSet.isAfterLast } override fun next(): String { val str = resultSet.getString(0) resultSet.moveToNext() return str } } } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/repos/SafeBox.kt<|end_filename|> package com.ali77gh.easydata.repos import android.content.Context import com.ali77gh.easydata.security.Encryption import com.ali77gh.easydata.security.Encryption.generateKey import javax.crypto.SecretKey /** * Created by ali on 8/30/18. */ class SafeBox(context: Context, key: String) { private var secretKey: SecretKey = generateKey(key) private val byteRepo: ByteDAO = ByteDAO(context, RootMode.LOCAL) fun save(fileName: String, sensitiveData: String) = byteRepo.save( fileName, Encryption.encrypt(sensitiveData, secretKey) ) fun load(fileName: String) = Encryption.decrypt( byteRepo.load(fileName), secretKey ) } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/security/Encryption.kt<|end_filename|> package com.ali77gh.easydata.security import java.lang.RuntimeException import javax.crypto.* import javax.crypto.spec.SecretKeySpec /** * Created by ali on 8/12/18. */ object Encryption { //key should be 16 or 32 bytes fun generateKey(key: String): SecretKey { return when(key.length){ 0->throw RuntimeException("empty key") 32 -> SecretKeySpec(key.toByteArray(), "AES") in 1..32 -> generateKey(key + key) else -> generateKey(key.substring(0,32)) } } fun encrypt(message: String, secret: SecretKey): ByteArray { val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding") cipher.init(Cipher.ENCRYPT_MODE, secret) return cipher.doFinal(message.toByteArray()) } fun decrypt(cipherText: ByteArray?, secret: SecretKey): String { val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding") cipher.init(Cipher.DECRYPT_MODE, secret) return String(cipher.doFinal(cipherText)) } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/repos/StringDAO.kt<|end_filename|> package com.ali77gh.easydata.repos import android.content.Context import android.os.Handler import android.os.Looper import android.util.Log import java.io.* /** * Created by ali on 8/22/18. */ class StringDAO( context: Context, rootMode: RootMode = RootMode.LOCAL ) : GRepo(context,rootMode) { /** * @param default default value of default is "" * @return default if not exist */ fun load(fileName: String,default:String=""): String { if (!checkExist(fileName)) return default val path = "$root/$fileName" val inputStream = FileInputStream(File(path)) val inputStreamReader = InputStreamReader(inputStream) val bufferedReader = BufferedReader(inputStreamReader) var receiveString: String? val stringBuilder = StringBuilder() while (bufferedReader.readLine().also { receiveString = it } != null) { stringBuilder.append(receiveString) } inputStream.close() return stringBuilder.toString() } fun loadAsync(filename: String, callback: (data:String)->Unit) { Thread { val data = load(filename) Handler(Looper.getMainLooper()).post { callback(data) } }.start() } fun save(fileName: String, data: String) { val path = "$root/$fileName" Log.d("yohogooo_path",path) val outputStreamWriter = OutputStreamWriter(FileOutputStream(File(path))) outputStreamWriter.write(data) outputStreamWriter.close() } fun saveAsync(filename: String, data: String, callback: ()->Unit={}) { Thread { save(filename,data) Handler(Looper.getMainLooper()).post { callback() } }.start() } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/IORun.kt<|end_filename|> package com.ali77gh.easydata import android.os.Handler import android.os.Looper fun <T> IORun(run:()->T,cb:(v:T)->Unit){ Thread{ val result = run() Handler(Looper.getMainLooper()).post { cb(result) } }.start() } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/sqlite/Model.kt<|end_filename|> package com.ali77gh.easydata.sqlite interface Model { var id: String } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/sqlite/FastTable.kt<|end_filename|> package com.ali77gh.easydata.sqlite import android.content.Context import kotlin.collections.ArrayList import kotlin.collections.HashMap abstract class FastTable<T : Model>( context: Context, private val type: Class<T>, tableName: String = type.simpleName, autoSetId: Boolean = false ) : EasyTable<T>(context ,type,tableName,autoSetId){ // private var IOWriteTasks = ArrayList<()->Unit>() private val cache : HashMap<String,T> init { if (CachePool.containsKey(tableName)) cache = CachePool[tableName] as HashMap<String, T> else{ cache = HashMap() for (row in super.toList()) cache[row.id] = row CachePool[tableName] = cache as HashMap<String, Model> } // Thread{ // while (true){ // if (IOWriteTasks.size != 0){ // IOWriteTasks[0].invoke() // IOWriteTasks.removeAt(0) // } else Thread.sleep(100) // CPU need to sleep sometimes :) (for battery life) // } // }.start() } override fun insert(row: T) { cache[row.id] = row super.insert(row) } override fun insertMany(rows:Iterable<T>){ for (row in rows) cache[row.id] = row super.insertMany(rows) } // Update override fun update(row: T){ cache[row.id] = row super.update(row) } override fun updateMany(rows: Iterable<T>){ for (row in rows) cache[row.id] = row super.updateMany(rows) } override fun updateAll(change:(row:T)->T){ for (row in this) cache[row.id] = change(row) super.updateAll(change) } override fun updateWhere(condition: (obj: T) -> Boolean, change:(row:T)->T){ super.updateWhere(condition, change) for (row in this) if (condition(row)) cache[row.id] = change(row) } //Delete override fun deleteWhere(condition: (obj: T) -> Boolean){ super.deleteWhere(condition) // this will not work if you put it after loop for (row in this.toList()) if (condition(row)) cache.remove(row.id) } //Read override fun toList() = ArrayList<T>().apply { for (row in this@FastTable) this@apply.add(row) } /** * @return null if not found * */ override fun getById(id: String):T?{ return cache[id] } /** * @return null if not found * */ override fun getOne(condition: (obj: T) -> Boolean):T?{ val iterator = this.iterator() while (iterator.hasNext()){ val row = iterator.next() if (condition(row)) return row } return null } override fun iterator(): Iterator<T> { val iterator = cache.iterator() return object : Iterator<T> { override fun hasNext() = iterator.hasNext() override fun next() : T = iterator.next().value } } companion object{ private val CachePool = HashMap<String,HashMap<String,Model>>() fun clearCache(tableName:String){ CachePool.remove(tableName) } fun clearCache(type:Class<Model>){ clearCache(type.simpleName) } } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/security/DeviceKeyGenerator.kt<|end_filename|> package com.ali77gh.easydata.security import android.content.Context import android.provider.Settings.Secure /** * Created by ali on 8/30/18. */ object DeviceKeyGenerator { fun Generate(context: Context): String { return Secure.getString(context.contentResolver, Secure.ANDROID_ID) } //recommended fun Generate(context: Context, secret: String): String { val id = Secure.getString(context.contentResolver, Secure.ANDROID_ID) return id.substring(secret.length) + secret } } <|start_filename|>easydata/src/main/java/com/ali77gh/easydata/repos/GRepo.kt<|end_filename|> package com.ali77gh.easydata.repos import android.content.Context import android.os.Environment import java.io.File /** * Created by ali on 8/20/18. */ /** * this needs permission and runtime permission */ enum class RootMode { LOCAL, CACHE, EXTERNAL } abstract class GRepo(context: Context, mode: RootMode) { protected var root: File = when (mode) { RootMode.LOCAL -> context.filesDir RootMode.CACHE -> context.cacheDir RootMode.EXTERNAL -> Environment.getExternalStorageDirectory() } fun checkExist(fileName: String) = File("$root/$fileName").exists() /** * @param filename be careful about user files in external storage mode */ fun remove(filename: String) { val f = File("$root/$filename") if (f.exists()) f.delete() } }
ali77gh/EasyDataAndroid
<|start_filename|>lib/widgets/picker_fields/card_settings_number_picker.dart<|end_filename|> // Copyright (c) 2018, codegrue. All rights reserved. Use of this source code // is governed by the MIT license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import '../../card_settings.dart'; import '../../interfaces/common_field_properties.dart'; /// This is a list picker that allows for a range of numbers to be speficied as pptions. class CardSettingsNumberPicker extends StatelessWidget implements ICommonFieldProperties { CardSettingsNumberPicker({ Key? key, this.label: 'Label', this.labelAlign, this.labelWidth, this.initialValue, this.contentAlign, this.icon, this.requiredIndicator, required this.min, required this.max, this.stepInterval: 1, this.autovalidateMode: AutovalidateMode.onUserInteraction, this.enabled: true, this.validator, this.onSaved, this.onChanged, this.visible: true, this.showMaterialonIOS, this.fieldPadding, }) : assert(min < max); /// The text to identify the field to the user @override final String label; /// The alignment of the label paret of the field. Default is left. @override final TextAlign? labelAlign; /// controls how the widget in the content area of the field is aligned @override final TextAlign? contentAlign; /// The icon to display to the left of the field content @override final Icon? icon; /// A widget to show next to the label if the field is required @override final Widget? requiredIndicator; /// the initial value fo the picker to be placed on final int? initialValue; /// the lowest value that will be shown final int min; /// the highest value that will be shown final int max; /// the interval for the values. Default is 1 final int stepInterval; /// places the field into auto validation mode @override final AutovalidateMode autovalidateMode; /// If false hides the widget on the card setting panel @override final bool visible; /// Force the widget to use Material style on an iOS device @override final bool? showMaterialonIOS; /// If false, grays out the field and makes it unresponsive final bool enabled; /// The width of the field label. If provided overrides the global setting. @override final double? labelWidth; /// provides padding to wrap the entire field @override final EdgeInsetsGeometry? fieldPadding; /// fires when validation is requested @override final FormFieldValidator<int>? validator; /// vires when the enclosing for is saved @override final FormFieldSetter<int>? onSaved; /// firest when the content is changed @override final ValueChanged<int?>? onChanged; @override Widget build(BuildContext context) { return CardSettingsListPicker<int>( key: key, label: this.label, showMaterialonIOS: showMaterialonIOS, fieldPadding: fieldPadding, labelAlign: labelAlign, labelWidth: labelWidth, contentAlign: contentAlign, visible: visible, enabled: enabled, initialItem: initialValue, icon: icon, requiredIndicator: requiredIndicator, items: List<int>.generate( (max - min) ~/ stepInterval + 1, (i) => (i * stepInterval + min), ), autovalidateMode: autovalidateMode, validator: _safeValidator, onSaved: _safeOnSaved, onChanged: _safeOnChanged, ); } String? _safeValidator(int? value) { if (validator == null) return null; return validator!(intelligentCast<int>(value)); } void _safeOnSaved(int? value) { if (onSaved == null) return; onSaved!(intelligentCast<int>(value)); } void _safeOnChanged(int value) { if (onChanged == null) return; onChanged!(intelligentCast<int>(value)); } } <|start_filename|>test/card_settings_list_picker_test.dart<|end_filename|> import 'package:card_settings/card_settings.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CardSettingsListPicker', () { Widget widgetTree = Container(); var label = "PickOne"; var iconData = Icons.home; var option1 = PickerModel("Aaa", code: "A", icon: Icon(iconData)); var option2 = PickerModel("Bbb", code: "B", icon: Icon(iconData)); var option3 = PickerModel("Ccc", code: "C", icon: Icon(iconData)); var items = [option1, option2, option3]; var requiredIndicator = "#"; var initialValue = option1; setUpAll(() async { widgetTree = MaterialApp( home: CardSettings( children: [ CardSettingsSection( children: [ CardSettingsSelectionPicker<PickerModel>( label: label, initialItem: initialValue, items: items, iconizer: (item) => item.icon, requiredIndicator: Text(requiredIndicator), ) ], ), ], ), ); }); testWidgets('displays properties', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // assert expect(find.text(label), findsOneWidget); expect(find.text(option1.name), findsOneWidget); //expect(find.byIcon(iconData), findsOneWidget); expect(find.text(requiredIndicator), findsOneWidget); }); testWidgets('picks from dialog', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // act await tester.tap(find.text(option1.name)); // tap field await tester.pumpAndSettle(); await tester.tap(find.text(option2.name)); // tap item in dialog await tester.pumpAndSettle(); await tester.tap(find.text("OK")); await tester.pumpAndSettle(); // assert expect(find.text(option1.name), findsNothing); expect(find.text(option2.name), findsOneWidget); expect(find.text(option3.name), findsNothing); }); }); } <|start_filename|>lib/helpers/platform_functions.dart<|end_filename|> import 'dart:io'; import 'package:card_settings/widgets/card_settings_panel.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// this centralizes code to determine if we want to display the cupertino /// version or the material version, since this can be determined by /// several settings throughout the package bool showCupertino( BuildContext? context, bool? showMaterialonIOS, { bool mockIOS = false, }) { bool defaultValue = false; // don't show on web if (kIsWeb) return defaultValue; // if we are on iOS then determine if we want material if (mockIOS || Platform.isIOS) { // if showMaterialonIOS not specified calculate it if (showMaterialonIOS == null) { showMaterialonIOS = defaultValue; if (context != null) // set showMaterialOnIOS to parent CardSettings value showMaterialonIOS = CardSettings.of(context)?.showMaterialonIOS ?? defaultValue; } return !showMaterialonIOS; } // material by default return defaultValue; } /// This centralizes the style calculations for field labels, used by almost all widgets in this package TextStyle? labelStyle(BuildContext context, bool enabled) { var theme = Theme.of(context); var style = theme.textTheme.subtitle1; if (!enabled) style = style?.copyWith(color: theme.disabledColor); return style; } /// This centralizes the style calculations for content, used by almost all widgets in this package TextStyle? contentStyle(BuildContext context, dynamic value, bool enabled) { var theme = Theme.of(context); var style = theme.textTheme.subtitle1?.copyWith( color: (value == null) ? theme.hintColor : theme.textTheme.subtitle1?.color); if (!enabled) style = style?.copyWith(color: theme.disabledColor); return style; } <|start_filename|>lib/widgets/text_fields/card_settings_text.dart<|end_filename|> // Copyright (c) 2018, codegrue. All rights reserved. Use of this source code // is governed by the MIT license that can be found in the LICENSE file. import 'package:card_settings/helpers/platform_functions.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:extended_masked_text/extended_masked_text.dart'; import 'package:flutter_cupertino_settings/flutter_cupertino_settings.dart'; import 'package:flutter/cupertino.dart'; import '../../card_settings.dart'; import '../../interfaces/common_field_properties.dart'; import '../../interfaces/text_field_properties.dart'; /// This is a standard one line text entry It's based on the [TextFormField] widget. class CardSettingsText extends FormField<String> implements ICommonFieldProperties, ITextFieldProperties { CardSettingsText({ Key? key, String? initialValue, bool autovalidate: false, AutovalidateMode autovalidateMode: AutovalidateMode.onUserInteraction, this.enabled = true, this.onSaved, this.validator, this.onChanged, this.controller, this.textCapitalization = TextCapitalization.none, this.keyboardType = TextInputType.text, this.maxLengthEnforcement: MaxLengthEnforcement.enforced, this.inputMask, this.inputFormatters, this.onFieldSubmitted, this.style, this.focusNode, this.inputAction, this.inputActionNode, this.label = 'Label', this.contentOnNewLine = false, this.maxLength = 20, this.numberOfLines = 1, this.showCounter = false, this.visible = true, this.autocorrect = true, this.obscureText = false, this.autofocus = false, this.contentAlign, this.hintText, this.icon, this.labelAlign, this.labelWidth, this.prefixText, this.requiredIndicator, this.unitLabel, this.showMaterialonIOS, this.showClearButtonIOS = OverlayVisibilityMode.never, this.fieldPadding, this.contentPadding = const EdgeInsets.all(0.0), }) : assert(maxLength > 0), assert(controller == null || inputMask == null), super( key: key, initialValue: initialValue, onSaved: onSaved, validator: validator, autovalidateMode: autovalidateMode, builder: (FormFieldState<String> field) => (field as _CardSettingsTextState)._build(field.context), ); @override final ValueChanged<String>? onChanged; final TextEditingController? controller; final String? inputMask; final FocusNode? focusNode; final TextInputAction? inputAction; final FocusNode? inputActionNode; final TextInputType keyboardType; final TextCapitalization textCapitalization; final TextStyle? style; // If false the field is grayed out and unresponsive @override // If false, grays out the field and makes it unresponsive final bool enabled; final MaxLengthEnforcement? maxLengthEnforcement; final ValueChanged<String>? onFieldSubmitted; final List<TextInputFormatter>? inputFormatters; // The text to identify the field to the user @override final String label; // The alignment of the label paret of the field. Default is left. @override final TextAlign? labelAlign; // The width of the field label. If provided overrides the global setting. @override final double? labelWidth; // controls how the widget in the content area of the field is aligned @override final TextAlign? contentAlign; final String? unitLabel; final String? prefixText; @override // text to display to guide the user on what to enter final String? hintText; // The icon to display to the left of the field content @override final Icon? icon; // A widget to show next to the label if the field is required @override final Widget? requiredIndicator; final bool contentOnNewLine; final int maxLength; final int numberOfLines; final bool showCounter; // If false hides the widget on the card setting panel @override final bool visible; final bool autofocus; final bool obscureText; final bool autocorrect; // Force the widget to use Material style on an iOS device @override final bool? showMaterialonIOS; // provides padding to wrap the entire field @override final EdgeInsetsGeometry? fieldPadding; final EdgeInsetsGeometry contentPadding; ///Since the CupertinoTextField does not support onSaved, please use [onChanged] or [onFieldSubmitted] instead @override final FormFieldSetter<String>? onSaved; ///In material mode this shows the validation text under the field ///In cupertino mode, it shows a [red] [Border] around the [CupertinoTextField] @override final FormFieldValidator<String>? validator; final OverlayVisibilityMode showClearButtonIOS; @override _CardSettingsTextState createState() => _CardSettingsTextState(); } class _CardSettingsTextState extends FormFieldState<String> { TextEditingController? _controller; @override CardSettingsText get widget => super.widget as CardSettingsText; @override void initState() { super.initState(); _initController(widget.initialValue); } @override void didUpdateWidget(CardSettingsText oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) { oldWidget.controller?.removeListener(_handleControllerChanged); _initController(oldWidget.controller?.value.toString()); } } void _initController(String? initialValue) { if (widget.controller == null) { if (widget.inputMask == null) { _controller = TextEditingController(text: initialValue); } else { _controller = MaskedTextController(mask: widget.inputMask!, text: initialValue); } } else { _controller = widget.controller; } _controller!.addListener(_handleControllerChanged); } @override void dispose() { widget.controller?.removeListener(_handleControllerChanged); super.dispose(); } @override void reset() { super.reset(); setState(() { _controller!.text = widget.initialValue ?? ''; }); } void _handleControllerChanged() { if (_controller!.text != value) { didChange(_controller!.text); } } void _handleOnChanged(String value) { if (widget.onChanged != null) { // `value` doesn't apple any masks when this is called, so the controller has the actual formatted value widget.onChanged!(_controller!.value.text); } } void _onFieldSubmitted(String value) { if (this.widget.focusNode != null) this.widget.focusNode!.unfocus(); if (this.widget.inputActionNode != null) { this.widget.inputActionNode!.requestFocus(); return; } if (this.widget.onFieldSubmitted != null) this.widget.onFieldSubmitted!(value); } Widget _build(BuildContext context) { if (showCupertino(context, widget.showMaterialonIOS)) return _buildCupertinoTextbox(context); else return _buildMaterialTextbox(context); } Container _buildCupertinoTextbox(BuildContext context) { bool hasError = false; if (widget.validator != null) { String? errorMessage = widget.validator!(value); hasError = (errorMessage != null); } final ls = labelStyle(context, widget.enabled); final _child = Container( child: CupertinoTextField( prefix: widget.prefixText == null ? null : Text( widget.prefixText ?? '', style: ls, ), suffix: widget.unitLabel == null ? null : Text( widget.unitLabel ?? '', style: ls, ), controller: _controller, focusNode: widget.focusNode, textInputAction: widget.inputAction, keyboardType: widget.keyboardType, textCapitalization: widget.textCapitalization, style: contentStyle(context, value, widget.enabled), decoration: hasError ? BoxDecoration( border: Border.all(color: Colors.red), borderRadius: BorderRadius.all( Radius.circular(4.0), ), ) : BoxDecoration( border: Border( top: BorderSide( color: CupertinoColors.lightBackgroundGray, style: BorderStyle.solid, width: 0.0, ), bottom: BorderSide( color: CupertinoColors.lightBackgroundGray, style: BorderStyle.solid, width: 0.0, ), left: BorderSide( color: CupertinoColors.lightBackgroundGray, style: BorderStyle.solid, width: 0.0, ), right: BorderSide( color: CupertinoColors.lightBackgroundGray, style: BorderStyle.solid, width: 0.0, ), ), borderRadius: BorderRadius.all( Radius.circular(4.0), ), ), clearButtonMode: widget.showClearButtonIOS, placeholder: widget.hintText, textAlign: widget.contentAlign ?? TextAlign.end, autofocus: widget.autofocus, obscureText: widget.obscureText, autocorrect: widget.autocorrect, maxLengthEnforcement: widget.maxLengthEnforcement, maxLines: widget.numberOfLines, maxLength: (widget.showCounter) ? widget.maxLength : null, // if we want counter use default behavior onChanged: _handleOnChanged, onSubmitted: _onFieldSubmitted, inputFormatters: widget.inputFormatters ?? [ // if we don't want the counter, use this maxLength instead LengthLimitingTextInputFormatter(widget.maxLength) ], enabled: widget.enabled, ), ); return Container( child: widget.visible == false ? null : widget.contentOnNewLine == true ? Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ CSControl( nameWidget: widget.requiredIndicator != null ? Text( (widget.label) + ' *', style: ls, ) : Text(widget.label, style: ls), contentWidget: Container(), style: CSWidgetStyle(icon: widget.icon), ), Container( padding: EdgeInsets.all(5.0), child: _child, color: Theme.of(context).brightness == Brightness.dark ? null : CupertinoColors.white, ), Container( padding: widget.showCounter ? EdgeInsets.all(5.0) : null, color: Theme.of(context).brightness == Brightness.dark ? null : CupertinoColors.white, child: widget.showCounter ? Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text( "${_controller?.text.length ?? 0}/${widget.maxLength}", style: TextStyle( color: CupertinoColors.inactiveGray, ), ), ], ) : null, ), ], ) : Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ CSControl( nameWidget: Container( width: widget.labelWidth ?? CardSettings.of(context)?.labelWidth ?? 120.0, child: widget.requiredIndicator != null ? Text((widget.label) + ' *', style: ls) : Text(widget.label, style: ls), ), contentWidget: Expanded( child: Container( padding: EdgeInsets.only(left: 10.0), child: _child, ), ), style: CSWidgetStyle(icon: widget.icon), ), Container( padding: widget.showCounter ? EdgeInsets.all(5.0) : null, color: Theme.of(context).brightness == Brightness.dark ? null : CupertinoColors.white, child: widget.showCounter ? Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text( "${_controller?.text.length ?? 0}/${widget.maxLength}", style: TextStyle( color: CupertinoColors.inactiveGray, ), ), ], ) : null, ), ], ), ); } CardSettingsField _buildMaterialTextbox(BuildContext context) { return CardSettingsField( label: widget.label, labelAlign: widget.labelAlign, labelWidth: widget.labelWidth, visible: widget.visible, unitLabel: widget.unitLabel, icon: widget.icon, requiredIndicator: widget.requiredIndicator, contentOnNewLine: widget.contentOnNewLine, enabled: widget.enabled, fieldPadding: widget.fieldPadding, content: TextField( controller: _controller, focusNode: widget.focusNode, keyboardType: widget.keyboardType, textInputAction: widget.inputAction, textCapitalization: widget.textCapitalization, enabled: widget.enabled, readOnly: !widget.enabled, style: contentStyle(context, value, widget.enabled), decoration: InputDecoration( contentPadding: widget.contentPadding, border: InputBorder.none, errorText: errorText, prefixText: widget.prefixText, hintText: widget.hintText, isDense: true, ), textAlign: widget.contentAlign ?? CardSettings.of(context)!.contentAlign, autofocus: widget.autofocus, obscureText: widget.obscureText, autocorrect: widget.autocorrect, maxLengthEnforcement: widget.maxLengthEnforcement, maxLines: widget.numberOfLines, maxLength: (widget.showCounter) ? widget.maxLength : null, // if we want counter use default behavior onChanged: _handleOnChanged, onSubmitted: _onFieldSubmitted, inputFormatters: widget.inputFormatters ?? [ // if we don't want the counter, use this maxLength instead LengthLimitingTextInputFormatter(widget.maxLength) ], ), ); } } <|start_filename|>test/platform_functions_test.dart<|end_filename|> import 'package:card_settings/helpers/platform_functions.dart'; import 'package:card_settings/widgets/card_settings_panel.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; void main() { group('showCupertino', () { testWidgets('returns false on non-iOS', (WidgetTester tester) async { var showMaterialonIOS = true; bool isIOS = true; var result = showCupertino(null, showMaterialonIOS, mockIOS: isIOS); expect(result, false); }); test('on iOS, returns false if showMaterialonIOS true', () { var showMaterialonIOS = true; bool isIOS = true; var result = showCupertino(null, showMaterialonIOS, mockIOS: isIOS); expect(result, false); }); test( 'on iOS, returns true if showMaterialonIOS null and context not provided', () { bool? showMaterialonIOS; // null bool isIOS = true; var result = showCupertino(null, showMaterialonIOS, mockIOS: isIOS); expect(result, true); }); test( 'on iOS, returns showMaterialonIOS of CardSettings if showMaterialonIOS not provided', () { // set up mocks var context = MockContext(); when(context.dependOnInheritedWidgetOfExactType<CardSettings>()) .thenReturn( CardSettings( children: [ CardSettingsSection(), ], ), ); bool? showMaterialonIOS; // null bool isIOS = true; var result = showCupertino(context, showMaterialonIOS, mockIOS: isIOS); expect(result, true); }); }); group('labelStyle', () { test('enabled uses textTheme.subtitle1 color', () { // Arrange bool enabled = true; var context = MockContext(); // Act var result = labelStyle(context, enabled); // Assert var expectedColor = Theme.of(context).textTheme.subtitle1?.color; expect(result?.color, expectedColor); }); test('disabled uses disabledColor', () { // Arrange bool enabled = false; var context = MockContext(); // Act var result = labelStyle(context, enabled); // Assert var expectedColor = Theme.of(context).disabledColor; expect(result?.color, expectedColor); }); }); group('contentStyle', () { test('enabled uses textTheme.subtitle1 color if value is present', () { // Arrange bool enabled = true; String value = "Some text"; var context = MockContext(); // Act var result = contentStyle(context, value, enabled); // Assert var expectedColor = Theme.of(context).textTheme.subtitle1?.color; expect(result?.color, expectedColor); }); test('enabled uses textTheme.hintColor if value not present', () { // Arrange bool enabled = true; String? value; // null var context = MockContext(); // Act var result = contentStyle(context, value, enabled); // Assert var expectedColor = Theme.of(context).hintColor; expect(result?.color, expectedColor); }); test('disabled uses disabledColor', () { // Arrange bool enabled = false; String value = "Some text"; var context = MockContext(); // Act var result = contentStyle(context, value, enabled); // Assert var expectedColor = Theme.of(context).disabledColor; expect(result?.color, expectedColor); }); }); } class MockContext extends Mock implements BuildContext {} <|start_filename|>lib/interfaces/common_field_properties.dart<|end_filename|> import 'package:flutter/material.dart'; import 'minimum_field_properties.dart'; /// Interface to ensure that all widgets implement this minimum /// set of properties abstract class ICommonFieldProperties extends IMinimumFieldSettings { final String? label = null; final double? labelWidth = null; final TextAlign? labelAlign = null; final TextAlign? contentAlign = null; final EdgeInsetsGeometry? fieldPadding = null; final Icon? icon = null; final Widget? requiredIndicator = null; final Function? onChanged = null; final Function? onSaved = null; final Function? validator = null; //final bool autovalidate = null; final AutovalidateMode autovalidateMode = AutovalidateMode.onUserInteraction; } <|start_filename|>lib/interfaces/minimum_field_properties.dart<|end_filename|> import '../widgets/card_settings_widget.dart'; /// abstract class to ensure that all widgets implement the base /// set of properties expected buy the settings panel wrapper abstract class IMinimumFieldSettings implements CardSettingsWidget { @override final bool? showMaterialonIOS = null; @override final bool? visible = null; } <|start_filename|>example/lib/plumbing/model.dart<|end_filename|> // example viewmodel for the form import 'dart:typed_data'; import 'package:card_settings/card_settings.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class PonyModel { String name = '<NAME>'; PickerModel type = ponyTypes[1]; //TODO, bind by value int age = 7; PickerModel gender = ponyGenders[1]; //TODO: "F"; String coatColor = 'D19FE4'; String maneColor = '273873'; bool hasSpots = false; String spotColor = 'FF5198'; String description = 'An intelligent and dutiful scholar with an avid love of learning and skill in unicorn magic such as levitation, teleportation, and the creation of force fields.'; List<String> hobbies = <String>[ 'flying', 'singing', 'exploring', 'hiding', 'coloring' ]; double height = 3.5; int weight = 45; PickerModel style = ponyStyles[1]; // TODO: "MG"; DateTime showDateTime = DateTime(2010, 10, 10, 20, 30); double ticketPrice = 65.99; int boxOfficePhone = 18005551212; String email = '<EMAIL>'; String password = '<PASSWORD>'; double rating = 0.25; Uint8List photo; Uint8List video = Uint8List(1024 * 1024 * 15); Uint8List audio = Uint8List(1024 * 4); Uint8List customFile = Uint8List(4); void loadMedia() async { photo = (await rootBundle.load('assets/twilight_sparkle.png')) .buffer .asUint8List(); } } const List<String> allHobbies = <String>[ 'running', 'flying', 'coloring', 'jumping', 'eating', 'hiding', 'exploring', 'singing', 'dancing', 'acting', 'cleaning', 'shopping', 'sewing', 'cooking', ]; const List<PickerModel> ponyTypes = <PickerModel>[ PickerModel('Earth', code: 'E'), PickerModel('Unicorn', code: 'U'), PickerModel('Pegasi', code: 'P'), PickerModel('Alicorn', code: 'A'), ]; const List<PickerModel> ponyGenders = <PickerModel>[ PickerModel('Male', code: 'M'), PickerModel('Female', code: 'F'), ]; const List<PickerModel> ponyStyles = <PickerModel>[ PickerModel('Majestic', code: 'MG', icon: Icon(Icons.sort)), PickerModel('Scrawny', code: 'SC', icon: Icon(Icons.clear_all)), PickerModel('Sleek', code: 'SL', icon: Icon(Icons.swap_calls)), ]; <|start_filename|>test/card_settings_text_test.dart<|end_filename|> import 'package:card_settings/card_settings.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CardSettingsText', () { Widget widgetTree = Container(); var key = GlobalKey(); var label = "MeInput"; var initialValue = "Hello World"; var icon = Icons.home; var requiredIndicator = "#"; var hintText = "Show me the world!"; var focusNode = FocusNode(); var inputActionNode = FocusNode(); var inputAction = TextInputAction.next; setUpAll(() async { widgetTree = MaterialApp( home: CardSettings( children: [ CardSettingsSection( children: [ CardSettingsText( key: key, label: label, initialValue: initialValue, icon: Icon(icon), requiredIndicator: Text(requiredIndicator), hintText: hintText, focusNode: focusNode, inputAction: inputAction, inputActionNode: inputActionNode, ), CardSettingsText(focusNode: inputActionNode) ], ), ], ), ); }); testWidgets('displays properties', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // assert final labelFinder = find.text(label); expect(labelFinder, findsOneWidget); final valueFinder = find.text(initialValue); expect(valueFinder, findsOneWidget); final iconFinder = find.byIcon(icon); expect(iconFinder, findsOneWidget); final requiredIndicatorFinder = find.text(requiredIndicator); expect(requiredIndicatorFinder, findsOneWidget); }); testWidgets('changes text', (WidgetTester tester) async { // arrange var newText = "Brave new world"; await tester.pumpWidget(widgetTree); // act await tester.enterText(find.byKey(key), newText); // assert final valueFinder = find.text(newText); expect(valueFinder, findsOneWidget); }); testWidgets('shows hintText', (WidgetTester tester) async { // arrange var newText = ""; await tester.pumpWidget(widgetTree); // act await tester.enterText(find.byKey(key), newText); // assert final hintFinder = find.text(hintText); expect(hintFinder, findsOneWidget); }); testWidgets('focusNode is focused', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // act await tester.showKeyboard(find.byKey(key)); // assert expect(focusNode.hasFocus, isTrue); }); testWidgets('input action unfocuses focusNode', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // act await tester.showKeyboard(find.byKey(key)); await tester.testTextInput.receiveAction(inputAction); await tester.pump(); // assert expect(focusNode.hasFocus, isFalse); }); testWidgets('input action focuses inputActionNode', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // act await tester.showKeyboard(find.byKey(key)); await tester.testTextInput.receiveAction(inputAction); await tester.pump(); // assert expect(inputActionNode.hasFocus, isTrue); }); }); } <|start_filename|>lib/widgets/picker_fields/card_settings_checkbox_picker.dart<|end_filename|> // Copyright (c) 2018, codegrue. All rights reserved. Use of this source code // is governed by the MIT license that can be found in the LICENSE file. import 'package:card_settings/helpers/platform_functions.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_cupertino_settings/flutter_cupertino_settings.dart'; import 'package:flutter_material_pickers/flutter_material_pickers.dart'; import '../../card_settings.dart'; import '../../interfaces/common_field_properties.dart'; /// This is a selection widget that allows an arbitrary list of options to be provided. class CardSettingsCheckboxPicker<T> extends FormField<List<T>> implements ICommonFieldProperties { CardSettingsCheckboxPicker({ Key? key, List<T>? initialItems, FormFieldSetter<List<T>>? onSaved, FormFieldValidator<List<T>>? validator, AutovalidateMode autovalidateMode: AutovalidateMode.onUserInteraction, this.enabled = true, this.onChanged, this.label = 'Select', this.visible = true, this.contentAlign, this.icon, this.labelAlign, this.labelWidth, this.requiredIndicator, required this.items, this.showMaterialonIOS, this.fieldPadding, }) : super( key: key, initialValue: initialItems, onSaved: onSaved, validator: validator, autovalidateMode: autovalidateMode, builder: (FormFieldState<List<T>> field) => (field as _CardSettingsCheckboxPickerState)._build(field.context), ); /// The text to identify the field to the user @override final String label; /// If false the field is grayed out and unresponsive @override final bool enabled; /// The alignment of the label paret of the field. Default is left. @override final TextAlign? labelAlign; /// The width of the field label. If provided overrides the global setting. @override final double? labelWidth; /// controls how the widget in the content area of the field is aligned @override final TextAlign? contentAlign; /// The icon to display to the left of the field content @override final Icon? icon; /// A widget to show next to the label if the field is required @override final Widget? requiredIndicator; /// a list of items to display in the picker final List<T> items; /// If false hides the widget on the card setting panel @override final bool visible; /// Fires when the picked values are changed @override final ValueChanged<List<T>>? onChanged; /// Force the widget to use Material style on an iOS device @override final bool? showMaterialonIOS; /// provides padding to wrap the entire field @override final EdgeInsetsGeometry? fieldPadding; @override _CardSettingsCheckboxPickerState<T> createState() => _CardSettingsCheckboxPickerState<T>(); } class _CardSettingsCheckboxPickerState<T> extends FormFieldState<List<T>> { @override CardSettingsCheckboxPicker<T> get widget => super.widget as CardSettingsCheckboxPicker<T>; List<T> items = List<T>.empty(); void _showDialog(String label) { if (showCupertino(context, widget.showMaterialonIOS)) _showCupertinoSelectPicker(label); else _showMaterialCheckboxPicker(label); } void _showMaterialCheckboxPicker(String label) { showMaterialCheckboxPicker( context: context, title: label, items: items, selectedItems: value, onChanged: (List<T>? selectedItems) { if (selectedItems != null) { didChange(selectedItems); if (widget.onChanged != null) widget.onChanged!(selectedItems); } }, ); } void _showCupertinoSelectPicker(String label) { Navigator.push<List<T>>( context, MaterialPageRoute( builder: (context) => _CupertinoSelect( initialItems: value!, items: items, label: label, ), fullscreenDialog: true, ), ).then((selectedValues) { if (selectedValues != null) { didChange(selectedValues); if (widget.onChanged != null) widget.onChanged!(selectedValues); } }); } Widget _build(BuildContext context) { // make local mutable copies of values and options items = widget.items; if (showCupertino(context, widget.showMaterialonIOS)) return _cupertinoSettingsMultiselect(); else return _materialSettingsMultiselect(); } Widget _cupertinoSettingsMultiselect() { final ls = labelStyle(context, widget.enabled); return Container( child: widget.visible == false ? null : GestureDetector( onTap: () { if (widget.enabled) _showDialog(widget.label); }, child: CSControl( nameWidget: Container( width: widget.labelWidth ?? CardSettings.of(context)?.labelWidth ?? 120.0, child: widget.requiredIndicator != null ? Text( (widget.label) + ' *', style: ls, ) : Text( widget.label, style: ls, ), ), contentWidget: Text( value == null || value!.isEmpty ? "none selected" : value!.length == 1 ? "${value![0]}" : "${value![0]} & ${value!.length - 1} more", style: contentStyle(context, value, widget.enabled), ), style: CSWidgetStyle(icon: widget.icon), ), ), ); } Widget _materialSettingsMultiselect() { return GestureDetector( onTap: () { if (widget.enabled) _showDialog(widget.label); }, child: CardSettingsField( label: widget.label, labelAlign: widget.labelAlign, labelWidth: widget.labelWidth, enabled: widget.enabled, visible: widget.visible, icon: widget.icon, requiredIndicator: widget.requiredIndicator, errorText: errorText, contentOnNewLine: true, fieldPadding: widget.fieldPadding, content: Wrap( alignment: WrapAlignment.start, spacing: 4.0, runSpacing: 0.0, children: value! .map( (s) => Chip( label: Text(s.toString(), style: contentStyle(context, value, widget.enabled))), ) .toList(), ), pickerIcon: (widget.enabled) ? Icons.arrow_drop_down : null, ), ); } } class _CupertinoSelect<T> extends StatefulWidget { _CupertinoSelect({ required this.label, this.initialItems, required this.items, }); final List<T>? initialItems; final List<T> items; final String label; @override _CupertinoSelectState<T> createState() => _CupertinoSelectState<T>(); } class _CupertinoSelectState<T> extends State<_CupertinoSelect<T>> { List<T> _selected = []; @override void initState() { _selected = widget.initialItems ?? []; super.initState(); } @override Widget build(BuildContext context) { return DefaultTextStyle( style: const TextStyle( fontFamily: '.SF UI Text', inherit: false, fontSize: 17.0, color: CupertinoColors.black, ), child: Scaffold( appBar: CupertinoNavigationBar( // We're specifying a back label here because the previous page is a // Material page. CupertinoPageRoutes could auto-populate these back // labels. previousPageTitle: 'Cupertino', middle: Text('Select ' + widget.label), trailing: GestureDetector( child: Text( 'Save', style: TextStyle( color: CupertinoColors.activeBlue, fontWeight: FontWeight.bold, ), ), onTap: () { Navigator.of(context, rootNavigator: true).pop(_selected); }, ), ), body: ListView.builder( itemCount: widget.items.length, itemBuilder: (BuildContext context, int index) { T i = widget.items[index]; final bool select = _selected.contains(i); return ListTile( leading: select ? const Icon(CupertinoIcons.check_mark) : Icon(Icons.info, color: Colors.transparent), title: Text(i.toString()), onTap: () { setState(() { if (select) { _selected.remove(i); } else { _selected.add(i); } }); }, ); }, ), ), ); } } <|start_filename|>test/card_settings_header_test.dart<|end_filename|> import 'package:card_settings/card_settings.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CardSettingsHeader', () { Widget widgetTree = Container(); var label = "ArbitraryTitle"; setUpAll(() async { widgetTree = MaterialApp( home: CardSettings( children: [ CardSettingsSection( header: CardSettingsHeader( label: label, ), ), ], ), ); }); testWidgets('displays properties', (WidgetTester tester) async { // arrange await tester.pumpWidget(widgetTree); // assert final labelFinder = find.text(label); expect(labelFinder, findsOneWidget); }); }); } <|start_filename|>lib/widgets/numeric_fields/card_settings_currency.dart<|end_filename|> // Copyright (c) 2018, codegrue. All rights reserved. Use of this source code // is governed by the MIT license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:extended_masked_text/extended_masked_text.dart'; import 'package:intl/intl.dart'; import '../../card_settings.dart'; import '../../interfaces/common_field_properties.dart'; /// This is a currency field. class CardSettingsCurrency extends StatefulWidget implements ICommonFieldProperties { CardSettingsCurrency({ Key? key, this.label: 'Label', this.labelAlign, this.labelWidth, this.contentAlign, this.initialValue: 0.0, this.icon, this.requiredIndicator, this.currencySymbol: '\$', this.currencyName: 'USD', this.decimalSeparator: '.', this.thousandSeparator: ',', this.maxLength: 16, this.visible: true, this.enabled: true, this.autofocus: false, this.obscureText: false, this.autovalidateMode: AutovalidateMode.onUserInteraction, this.validator, this.onSaved, this.onChanged, this.controller, this.focusNode, this.inputAction, this.inputActionNode, this.keyboardType, this.style, this.maxLengthEnforcement: MaxLengthEnforcement.enforced, this.onFieldSubmitted, this.inputFormatters, this.showMaterialonIOS, this.fieldPadding, this.locale, }); /// The text to identify the field to the user @override final String label; /// The alignment of the label paret of the field. Default is left. @override final TextAlign? labelAlign; /// The width of the field label. If provided overrides the global setting. @override final double? labelWidth; /// controls how the widget in the content area of the field is aligned @override final TextAlign? contentAlign; /// The initial value to display final double initialValue; /// The icon to display to the left of the field content @override final Icon? icon; /// A widget to show next to the label if the field is required @override final Widget? requiredIndicator; /// The symbol to use for the currency final String currencySymbol; /// the name of the currency. E.g. USD final String currencyName; /// the character to use for decimal separation final String decimalSeparator; /// the character to use for the thousands place. final String thousandSeparator; /// The maxinum length of the value in characters final int maxLength; /// If false hides the widget on the card setting panel @override final bool visible; /// If false, grays out the field and makes it unresponsive final bool enabled; final bool autofocus; final bool obscureText; @override final AutovalidateMode autovalidateMode; @override final FormFieldValidator<double>? validator; @override final FormFieldSetter<double>? onSaved; @override final ValueChanged<double?>? onChanged; final TextEditingController? controller; final FocusNode? focusNode; final TextInputAction? inputAction; final FocusNode? inputActionNode; final TextInputType? keyboardType; final TextStyle? style; final MaxLengthEnforcement? maxLengthEnforcement; final ValueChanged<String>? onFieldSubmitted; final List<TextInputFormatter>? inputFormatters; final Locale? locale; // Force the widget to use Material style on an iOS device @override final bool? showMaterialonIOS; // provides padding to wrap the entire field @override final EdgeInsetsGeometry? fieldPadding; @override _CardSettingsCurrencyState createState() { return _CardSettingsCurrencyState(); } } class _CardSettingsCurrencyState extends State<CardSettingsCurrency> { MoneyMaskedTextController? _moneyController; @override void initState() { super.initState(); if (widget.controller == null) { _moneyController = MoneyMaskedTextController( decimalSeparator: widget.decimalSeparator, thousandSeparator: widget.thousandSeparator); _moneyController!.updateValue(widget.initialValue); } } @override Widget build(BuildContext context) { Locale myLocale = widget.locale ?? Localizations.localeOf(context); var pattern = "#,###.##"; var formatter = NumberFormat(pattern, myLocale.languageCode); return CardSettingsText( showMaterialonIOS: widget.showMaterialonIOS, fieldPadding: widget.fieldPadding, label: widget.label, labelAlign: widget.labelAlign, labelWidth: widget.labelWidth, contentAlign: widget.contentAlign, initialValue: widget.initialValue.toString(), unitLabel: widget.currencyName, prefixText: widget.currencySymbol, icon: widget.icon, requiredIndicator: widget.requiredIndicator, maxLength: widget.maxLength, visible: widget.visible, enabled: widget.enabled, autofocus: widget.autofocus, obscureText: widget.obscureText, autovalidateMode: widget.autovalidateMode, validator: (val) => _safeValidator(val, formatter), onSaved: (val) => _safeOnSaved(val, formatter), onChanged: (val) => _safeOnChanged(val, formatter), controller: widget.controller ?? _moneyController, focusNode: widget.focusNode, inputAction: widget.inputAction, inputActionNode: widget.inputActionNode, keyboardType: widget.keyboardType ?? TextInputType.numberWithOptions(decimal: false), style: widget.style, maxLengthEnforcement: widget.maxLengthEnforcement, onFieldSubmitted: widget.onFieldSubmitted, inputFormatters: widget.inputFormatters, ); } String? _safeValidator(String? value, NumberFormat formatter) { if (widget.validator == null) return null; num? number = (value == "") ? null : formatter.parse(value!); return widget.validator!(intelligentCast<double>(number)); } void _safeOnSaved(String? value, NumberFormat formatter) { if (widget.onSaved == null) return; num? number = (value == "") ? null : formatter.parse(value!); widget.onSaved!(intelligentCast<double>(number)); } void _safeOnChanged(String? value, NumberFormat formatter) { if (widget.onChanged == null) return; if (_moneyController != null) { widget.onChanged!(_moneyController!.numberValue); } else { num? number = (value == "") ? null : formatter.parse(value!); widget.onChanged!(intelligentCast<double>(number)); } } }
dimitristaufer/card_settings
<|start_filename|>Assets/ColorThief/Scripts/ColorThieft.Shared/Color.cs<|end_filename|> using System; namespace ColorThief { /// <summary> /// Defines a color in RGB space. /// </summary> public struct Color { /// <summary> /// Get or Set the Alpha component value for sRGB. /// </summary> public byte A; /// <summary> /// Get or Set the Blue component value for sRGB. /// </summary> public byte B; /// <summary> /// Get or Set the Green component value for sRGB. /// </summary> public byte G; /// <summary> /// Get or Set the Red component value for sRGB. /// </summary> public byte R; /// <summary> /// Get HSL color. /// </summary> /// <returns></returns> public HslColor ToHsl() { const double toDouble = 1.0 / 255; var r = toDouble * R; var g = toDouble * G; var b = toDouble * B; var max = Math.Max(Math.Max(r, g), b); var min = Math.Min(Math.Min(r, g), b); var chroma = max - min; double h1; // ReSharper disable CompareOfFloatsByEqualityOperator if(chroma == 0) { h1 = 0; } else if(max == r) { h1 = (g - b) / chroma % 6; } else if(max == g) { h1 = 2 + (b - r) / chroma; } else //if (max == b) { h1 = 4 + (r - g) / chroma; } var lightness = 0.5 * (max - min); var saturation = chroma == 0 ? 0 : chroma / (1 - Math.Abs(2 * lightness - 1)); HslColor ret; ret.H = 60 * h1; ret.S = saturation; ret.L = lightness; ret.A = toDouble * A; return ret; // ReSharper restore CompareOfFloatsByEqualityOperator } } } <|start_filename|>Assets/ColorThief/Scripts/ColorThieft.Shared/CMap.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; namespace ColorThief { /// <summary> /// Color map /// </summary> internal class CMap { private readonly List<VBox> vboxes = new List<VBox>(); private List<QuantizedColor> palette; public void Push(VBox box) { palette = null; vboxes.Add(box); } public List<QuantizedColor> GeneratePalette() { if(palette == null) { palette = (from vBox in vboxes let rgb = vBox.Avg(false) let color = FromRgb(rgb[0], rgb[1], rgb[2]) select new QuantizedColor(color, vBox.Count(false))).ToList(); } return palette; } public int Size() { return vboxes.Count; } public int[] Map(int[] color) { foreach(var vbox in vboxes.Where(vbox => vbox.Contains(color))) { return vbox.Avg(false); } return Nearest(color); } public int[] Nearest(int[] color) { var d1 = double.MaxValue; int[] pColor = null; foreach(var t in vboxes) { var vbColor = t.Avg(false); var d2 = Math.Sqrt(Math.Pow(color[0] - vbColor[0], 2) + Math.Pow(color[1] - vbColor[1], 2) + Math.Pow(color[2] - vbColor[2], 2)); if(d2 < d1) { d1 = d2; pColor = vbColor; } } return pColor; } public VBox FindColor(double targetLuma, double minLuma, double maxLuma, double targetSaturation, double minSaturation, double maxSaturation) { VBox max = null; double maxValue = 0; var highestPopulation = vboxes.Select(p => p.Count(false)).Max(); foreach(var swatch in vboxes) { var avg = swatch.Avg(false); var hsl = FromRgb(avg[0], avg[1], avg[2]).ToHsl(); var sat = hsl.S; var luma = hsl.L; if(sat >= minSaturation && sat <= maxSaturation && luma >= minLuma && luma <= maxLuma) { var thisValue = Mmcq.CreateComparisonValue(sat, targetSaturation, luma, targetLuma, swatch.Count(false), highestPopulation); if(max == null || thisValue > maxValue) { max = swatch; maxValue = thisValue; } } } return max; } public Color FromRgb(int red, int green, int blue) { var color = new Color { A = 255, R = (byte)red, G = (byte)green, B = (byte)blue }; return color; } } } <|start_filename|>Assets/ColorThief/Scripts/Demo.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Demo : MonoBehaviour { public Texture2D texture; public RawImage image; public Image dominantColor; public Image[] paletteColors; public InputField urlField; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void Download() { StartCoroutine(DownloadImage()); } IEnumerator DownloadImage() { WWW www = new WWW(urlField.text); yield return www; if(string.IsNullOrEmpty(www.error)) { texture = www.texture; image.texture = texture; float ratio = 700f/texture.height; float w = texture.width * ratio; float h = texture.height * ratio; image.rectTransform.sizeDelta = new Vector2(w, h); var dominant = new ColorThief.ColorThief(); dominantColor.color = dominant.GetColor(texture).UnityColor; var palette = new ColorThief.ColorThief(); List<ColorThief.QuantizedColor> colors = palette.GetPalette(texture, paletteColors.Length); for(int i=0; i<colors.Count; i++) paletteColors[i].color = colors[i].UnityColor; } else Debug.Log(www.error); } } <|start_filename|>Assets/ColorThief/Scripts/Core/ColorThief.cs<|end_filename|> using System; using System.Collections.Generic; // using System.Drawing; using System.Linq; using UnityEngine; namespace ColorThief { public class ColorThief { private const int DefaultColorCount = 5; private const int DefaultQuality = 10; private const bool DefaultIgnoreWhite = true; /// <summary> /// Use the median cut algorithm to cluster similar colors and return the base color from the largest cluster. /// </summary> /// <param name="sourceImage">The source image.</param> /// <param name="quality"> /// 0 is the highest quality settings. 10 is the default. There is /// a trade-off between quality and speed. The bigger the number, /// the faster a color will be returned but the greater the /// likelihood that it will not be the visually most dominant color. /// </param> /// <param name="ignoreWhite">if set to <c>true</c> [ignore white].</param> /// <returns></returns> public QuantizedColor GetColor(Texture2D sourceImage, int quality = DefaultQuality, bool ignoreWhite = DefaultIgnoreWhite) { var palette = GetPalette(sourceImage, DefaultColorCount, quality, ignoreWhite); var dominantColor = palette.FirstOrDefault(); return dominantColor; } /// <summary> /// Use the median cut algorithm to cluster similar colors. /// </summary> /// <param name="sourceImage">The source image.</param> /// <param name="colorCount">The color count.</param> /// <param name="quality"> /// 0 is the highest quality settings. 10 is the default. There is /// a trade-off between quality and speed. The bigger the number, /// the faster a color will be returned but the greater the /// likelihood that it will not be the visually most dominant color. /// </param> /// <param name="ignoreWhite">if set to <c>true</c> [ignore white].</param> /// <returns></returns> /// <code>true</code> public List<QuantizedColor> GetPalette(Texture2D sourceImage, int colorCount = DefaultColorCount, int quality = DefaultQuality, bool ignoreWhite = DefaultIgnoreWhite) { var cmap = GetColorMap(sourceImage, colorCount, quality, ignoreWhite); return cmap != null ? cmap.GeneratePalette() : new List<QuantizedColor>(); } /// <summary> /// Use the median cut algorithm to cluster similar colors. /// </summary> /// <param name="sourceImage">The source image.</param> /// <param name="colorCount">The color count.</param> /// <param name="quality"> /// 0 is the highest quality settings. 10 is the default. There is /// a trade-off between quality and speed. The bigger the number, /// the faster a color will be returned but the greater the /// likelihood that it will not be the visually most dominant color. /// </param> /// <param name="ignoreWhite">if set to <c>true</c> [ignore white].</param> /// <returns></returns> private CMap GetColorMap(Texture2D sourceImage, int colorCount, int quality = DefaultQuality, bool ignoreWhite = DefaultIgnoreWhite) { var pixelArray = GetPixelsFast(sourceImage, quality, ignoreWhite); // Send array to quantize function which clusters values using median // cut algorithm var cmap = Mmcq.Quantize(pixelArray, colorCount); return cmap; } private IEnumerable<int> GetIntFromPixel(Texture2D bmp) { Color32[] clrs = bmp.GetPixels32(); for(int i=0; i<clrs.Length; i++) { Color32 clr = clrs[i]; yield return clr.b; yield return clr.g; yield return clr.r; yield return clr.a; } // for(var x = 0; x < bmp.Width; x++) // { // for(var y = 0; y < bmp.Height; y++) // { // var clr = bmp.GetPixel(x, y); // yield return clr.B; // yield return clr.G; // yield return clr.R; // yield return clr.A; // } // } } private int[][] GetPixelsFast(Texture2D sourceImage, int quality, bool ignoreWhite) { var imageData = GetIntFromPixel(sourceImage); var pixels = imageData.ToArray(); var pixelCount = sourceImage.width * sourceImage.height; const int colorDepth = 4; var expectedDataLength = pixelCount * colorDepth; if(expectedDataLength != pixels.Length) { throw new ArgumentException("(expectedDataLength = " + expectedDataLength + ") != (pixels.length = " + pixels.Length + ")"); } // Store the RGB values in an array format suitable for quantize // function // numRegardedPixels must be rounded up to avoid an // ArrayIndexOutOfBoundsException if all pixels are good. var numRegardedPixels = (quality <= 0) ? 0 : (pixelCount + quality - 1) / quality; var numUsedPixels = 0; var pixelArray = new int[numRegardedPixels][]; for(var i = 0; i < pixelCount; i += quality) { var offset = i * 4; var b = pixels[offset]; var g = pixels[offset + 1]; var r = pixels[offset + 2]; var a = pixels[offset + 3]; // If pixel is mostly opaque and not white if(a >= 125 && !(ignoreWhite && r > 250 && g > 250 && b > 250)) { pixelArray[numUsedPixels] = new[] {r, g, b}; numUsedPixels++; } } // Remove unused pixels from the array var copy = new int[numUsedPixels][]; Array.Copy(pixelArray, copy, numUsedPixels); return copy; } } } <|start_filename|>Assets/ColorThief/Scripts/ColorThieft.Shared/Mmcq.cs<|end_filename|> using System; using System.Collections.Generic; namespace ColorThief { internal static class Mmcq { public const int Sigbits = 5; public const int Rshift = 8 - Sigbits; public const int Mult = 1 << Rshift; public const int Histosize = 1 << (3 * Sigbits); public const int VboxLength = 1 << Sigbits; public const double FractByPopulation = 0.75; public const int MaxIterations = 1000; public const double WeightSaturation = 3d; public const double WeightLuma = 6d; public const double WeightPopulation = 1d; private static readonly VBoxComparer ComparatorProduct = new VBoxComparer(); private static readonly VBoxCountComparer ComparatorCount = new VBoxCountComparer(); public static int GetColorIndex(int r, int g, int b) { return (r << (2 * Sigbits)) + (g << Sigbits) + b; } /// <summary> /// Gets the histo. /// </summary> /// <param name="pixels">The pixels.</param> /// <returns>Histo (1-d array, giving the number of pixels in each quantized region of color space), or null on error.</returns> private static int[] GetHisto(IEnumerable<int[]> pixels) { var histo = new int[Histosize]; foreach(var pixel in pixels) { var rval = pixel[0] >> Rshift; var gval = pixel[1] >> Rshift; var bval = pixel[2] >> Rshift; var index = GetColorIndex(rval, gval, bval); histo[index]++; } return histo; } private static VBox VboxFromPixels(IList<int[]> pixels, int[] histo) { int rmin = 1000000, rmax = 0; int gmin = 1000000, gmax = 0; int bmin = 1000000, bmax = 0; // find min/max var numPixels = pixels.Count; for(var i = 0; i < numPixels; i++) { var pixel = pixels[i]; var rval = pixel[0] >> Rshift; var gval = pixel[1] >> Rshift; var bval = pixel[2] >> Rshift; if(rval < rmin) { rmin = rval; } else if(rval > rmax) { rmax = rval; } if(gval < gmin) { gmin = gval; } else if(gval > gmax) { gmax = gval; } if(bval < bmin) { bmin = bval; } else if(bval > bmax) { bmax = bval; } } return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo); } private static VBox[] DoCut(char color, VBox vbox, IList<int> partialsum, IList<int> lookaheadsum, int total) { int vboxDim1; int vboxDim2; switch(color) { case 'r': vboxDim1 = vbox.R1; vboxDim2 = vbox.R2; break; case 'g': vboxDim1 = vbox.G1; vboxDim2 = vbox.G2; break; default: vboxDim1 = vbox.B1; vboxDim2 = vbox.B2; break; } for(var i = vboxDim1; i <= vboxDim2; i++) { if(partialsum[i] > total / 2) { var vbox1 = vbox.Clone(); var vbox2 = vbox.Clone(); var left = i - vboxDim1; var right = vboxDim2 - i; var d2 = left <= right ? Math.Min(vboxDim2 - 1, Math.Abs(i + right / 2)) : Math.Max(vboxDim1, Math.Abs(Convert.ToInt32(i - 1 - left / 2.0))); // avoid 0-count boxes while(d2 < 0 || partialsum[d2] <= 0) { d2++; } var count2 = lookaheadsum[d2]; while(count2 == 0 && d2 > 0 && partialsum[d2 - 1] > 0) { count2 = lookaheadsum[--d2]; } // set dimensions switch(color) { case 'r': vbox1.R2 = d2; vbox2.R1 = d2 + 1; break; case 'g': vbox1.G2 = d2; vbox2.G1 = d2 + 1; break; default: vbox1.B2 = d2; vbox2.B1 = d2 + 1; break; } return new[] {vbox1, vbox2}; } } throw new Exception("VBox can't be cut"); } private static VBox[] MedianCutApply(IList<int> histo, VBox vbox) { if(vbox.Count(false) == 0) { return null; } if(vbox.Count(false) == 1) { return new[] {vbox.Clone(), null}; } // only one pixel, no split var rw = vbox.R2 - vbox.R1 + 1; var gw = vbox.G2 - vbox.G1 + 1; var bw = vbox.B2 - vbox.B1 + 1; var maxw = Math.Max(Math.Max(rw, gw), bw); // Find the partial sum arrays along the selected axis. var total = 0; var partialsum = new int[VboxLength]; // -1 = not set / 0 = 0 for(var l = 0; l < partialsum.Length; l++) { partialsum[l] = -1; } // -1 = not set / 0 = 0 var lookaheadsum = new int[VboxLength]; for(var l = 0; l < lookaheadsum.Length; l++) { lookaheadsum[l] = -1; } int i, j, k, sum, index; if(maxw == rw) { for(i = vbox.R1; i <= vbox.R2; i++) { sum = 0; for(j = vbox.G1; j <= vbox.G2; j++) { for(k = vbox.B1; k <= vbox.B2; k++) { index = GetColorIndex(i, j, k); sum += histo[index]; } } total += sum; partialsum[i] = total; } } else if(maxw == gw) { for(i = vbox.G1; i <= vbox.G2; i++) { sum = 0; for(j = vbox.R1; j <= vbox.R2; j++) { for(k = vbox.B1; k <= vbox.B2; k++) { index = GetColorIndex(j, i, k); sum += histo[index]; } } total += sum; partialsum[i] = total; } } else /* maxw == bw */ { for(i = vbox.B1; i <= vbox.B2; i++) { sum = 0; for(j = vbox.R1; j <= vbox.R2; j++) { for(k = vbox.G1; k <= vbox.G2; k++) { index = GetColorIndex(j, k, i); sum += histo[index]; } } total += sum; partialsum[i] = total; } } for(i = 0; i < VboxLength; i++) { if(partialsum[i] != -1) { lookaheadsum[i] = total - partialsum[i]; } } // determine the cut planes return maxw == rw ? DoCut('r', vbox, partialsum, lookaheadsum, total) : maxw == gw ? DoCut('g', vbox, partialsum, lookaheadsum, total) : DoCut('b', vbox, partialsum, lookaheadsum, total); } /// <summary> /// Inner function to do the iteration. /// </summary> /// <param name="lh">The lh.</param> /// <param name="comparator">The comparator.</param> /// <param name="target">The target.</param> /// <param name="histo">The histo.</param> /// <exception cref="System.Exception">vbox1 not defined; shouldn't happen!</exception> private static void Iter(List<VBox> lh, IComparer<VBox> comparator, int target, IList<int> histo) { var ncolors = 1; var niters = 0; while(niters < MaxIterations) { var vbox = lh[lh.Count - 1]; if(vbox.Count(false) == 0) { lh.Sort(comparator); niters++; continue; } lh.RemoveAt(lh.Count - 1); // do the cut var vboxes = MedianCutApply(histo, vbox); var vbox1 = vboxes[0]; var vbox2 = vboxes[1]; if(vbox1 == null) { throw new Exception( "vbox1 not defined; shouldn't happen!"); } lh.Add(vbox1); if(vbox2 != null) { lh.Add(vbox2); ncolors++; } lh.Sort(comparator); if(ncolors >= target) { return; } if(niters++ > MaxIterations) { return; } } } public static CMap Quantize(int[][] pixels, int maxcolors) { // short-circuit if(pixels.Length == 0 || maxcolors < 2 || maxcolors > 256) { return null; } var histo = GetHisto(pixels); // get the beginning vbox from the colors var vbox = VboxFromPixels(pixels, histo); var pq = new List<VBox> {vbox}; // Round up to have the same behaviour as in JavaScript var target = (int)Math.Ceiling(FractByPopulation * maxcolors); // first set of colors, sorted by population Iter(pq, ComparatorCount, target, histo); // Re-sort by the product of pixel occupancy times the size in color // space. pq.Sort(ComparatorProduct); // next set - generate the median cuts using the (npix * vol) sorting. Iter(pq, ComparatorProduct, maxcolors - pq.Count, histo); // Reverse to put the highest elements first into the color map pq.Reverse(); // calculate the actual colors var cmap = new CMap(); foreach(var vb in pq) { cmap.Push(vb); } return cmap; } public static double CreateComparisonValue(double saturation, double targetSaturation, double luma, double targetLuma, int population, int highestPopulation) { return WeightedMean(InvertDiff(saturation, targetSaturation), WeightSaturation, InvertDiff(luma, targetLuma), WeightLuma, population / (double)highestPopulation, WeightPopulation); } private static double WeightedMean(params double[] values) { double sum = 0; double sumWeight = 0; for(var i = 0; i < values.Length; i += 2) { var value = values[i]; var weight = values[i + 1]; sum += value * weight; sumWeight += weight; } return sum / sumWeight; } private static double InvertDiff(double value, double targetValue) { return 1 - Math.Abs(value - targetValue); } } }
chiutse/ColorThief
<|start_filename|>package.json<|end_filename|> { "name": "github-action-gitflow-release-workflow", "version": "2.0.0", "main": "index.js", "author": "<NAME> <<EMAIL>>", "license": "MIT" }
nodamu/github-action-gitflow-release-workflow
<|start_filename|>node_modules/hyper-iceberg/index.js<|end_filename|> exports.decorateConfig = (config) => { return Object.assign({}, config, { backgroundColor: '#161821', borderColor: '#272c42', colors: { black: '#1e2132', red: '#e27878', green: '#b4be82', yellow: '#e2a478', blue: '#84a0c6', magenta: '#a093c7', cyan: '#89b8c2', white: '#c6c8d1', lightBlack: '#6b7089', lightRed: '#e98989', lightGreen: '#c0ca8e', lightYellow: '#e9b189', lightBlue: '#91acd1', lightMagenta: '#ada0d3', lightCyan: '#95c4ce', lightWhite: '#d2d4de', }, css: ` ${config.css || ''} .tab_tab { transition: background-color 0.2s ease-out; } .tab_tab:hover { background-color: #1e2132; } .tab_icon { color: #6b7089; transition: background-color 0.2s ease-out, color 0.2s ease-out; } .tab_icon:hover { background-color: rgba(198, 200, 209, 0.2); color: #c6c8d1; } .tab_text { color: #6b7089; } `, cursorColor: '#c6c8d1', foregroundColor: '#c6c8d1', }); }
monji05/gurunavi
<|start_filename|>velero-plugin-for-gcp/object_store_test.go<|end_filename|> /* Copyright 2018 the Velero contributors. 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 main import ( "errors" "io" "strings" "testing" "cloud.google.com/go/storage" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" velerotest "github.com/vmware-tanzu/velero/pkg/test" ) type mockWriteCloser struct { closeErr error writeErr error } func (m *mockWriteCloser) Close() error { return m.closeErr } func (m *mockWriteCloser) Write(b []byte) (int, error) { return len(b), m.writeErr } func newMockWriteCloser(writeErr, closeErr error) *mockWriteCloser { return &mockWriteCloser{writeErr: writeErr, closeErr: closeErr} } type fakeWriter struct { wc *mockWriteCloser attrsErr error } func newFakeWriter(wc *mockWriteCloser) *fakeWriter { return &fakeWriter{wc: wc} } func (fw *fakeWriter) getWriteCloser(bucket, name string) io.WriteCloser { return fw.wc } func (fw *fakeWriter) getAttrs(bucket, key string) (*storage.ObjectAttrs, error) { return new(storage.ObjectAttrs), fw.attrsErr } func TestPutObject(t *testing.T) { tests := []struct { name string writeErr error closeErr error expectedErr error }{ { name: "No errors returns nil", closeErr: nil, writeErr: nil, expectedErr: nil, }, { name: "Close() errors are returned", closeErr: errors.New("error closing"), expectedErr: errors.New("error closing"), }, { name: "Write() errors are returned", writeErr: errors.New("error writing"), expectedErr: errors.New("error writing"), }, { name: "Write errors supercede close errors", writeErr: errors.New("error writing"), closeErr: errors.New("error closing"), expectedErr: errors.New("error writing"), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { wc := newMockWriteCloser(test.writeErr, test.closeErr) o := newObjectStore(velerotest.NewLogger()) o.bucketWriter = newFakeWriter(wc) err := o.PutObject("bucket", "key", strings.NewReader("contents")) assert.Equal(t, test.expectedErr, err) }) } } func TestObjectExists(t *testing.T) { tests := []struct { name string errorResponse error expectedExists bool expectedError string }{ { name: "exists", errorResponse: nil, expectedExists: true, }, { name: "doesn't exist", errorResponse: storage.ErrObjectNotExist, expectedExists: false, }, { name: "error checking for existence", errorResponse: errors.New("bad"), expectedExists: false, expectedError: "bad", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { o := newObjectStore(velerotest.NewLogger()) w := newFakeWriter(nil) o.bucketWriter = w w.attrsErr = tc.errorResponse bucket := "b" key := "k" exists, err := o.ObjectExists(bucket, key) if tc.expectedError != "" { assert.EqualError(t, err, tc.expectedError) return } require.NoError(t, err) assert.Equal(t, tc.expectedExists, exists) }) } } <|start_filename|>tilt-provider.json<|end_filename|> { "plugin_name": "velero-plugin-for-gcp", "context": ".", "image": "velero/velero-plugin-for-gcp", "live_reload_deps": [ "velero-plugin-for-gcp" ], "go_main": "./velero-plugin-for-gcp" }
reasonerjt/velero-plugin-for-gcp
<|start_filename|>01_P/P_2_1_2_02/sketch.js<|end_filename|> // P_2_1_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing module color and positions in a grid * * MOUSE * position x : offset x * position y : offset y * left click : random position * * KEYS * 1-3 : different sets of colors * 0 : default * arrow up/down : background module size * arrow left/right : foreground module size * s : save png */ 'use strict'; var tileCount = 20; var actRandomSeed = 0; var moduleColorBackground; var moduleColorForeground; var moduleAlphaBackground = 100; var moduleAlphaForeground = 100; var moduleRadiusBackground = 30; var moduleRadiusForeground = 15; var backgroundColor; function setup() { createCanvas(600, 600); colorMode(HSB, 360, 100, 100, 100); noStroke(); moduleColorBackground = color(0, 0, 0, moduleAlphaBackground); moduleColorForeground = color(0, 0, 100, moduleAlphaForeground); backgroundColor = color(0, 0, 100); } function draw() { translate(width / tileCount / 2, height / tileCount / 2); background(backgroundColor); randomSeed(actRandomSeed); for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = width / tileCount * gridX; var posY = height / tileCount * gridY; var shiftX = random(-1, 1) * mouseX / 20; var shiftY = random(-1, 1) * mouseY / 20; fill(moduleColorBackground); ellipse(posX + shiftX, posY + shiftY, moduleRadiusBackground, moduleRadiusBackground); } } for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = width / tileCount * gridX; var posY = height / tileCount * gridY; fill(moduleColorForeground); ellipse(posX, posY, moduleRadiusForeground, moduleRadiusForeground); } } } function mousePressed() { actRandomSeed = random(100000); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') { if (colorsEqual(moduleColorBackground, color(0, 0, 0, moduleAlphaBackground))) { moduleColorBackground = color(273, 73, 51, moduleAlphaBackground); } else { moduleColorBackground = color(0, 0, 0, moduleAlphaBackground); } } if (key == '2') { if (colorsEqual(moduleColorForeground, color(360, 100, 100, moduleAlphaForeground))) { moduleColorForeground = color(323, 100, 77, moduleAlphaForeground); } else { moduleColorForeground = color(360, 100, 100, moduleAlphaForeground); } } if (key == '3') { if (moduleAlphaBackground == 100) { moduleAlphaBackground = 50; moduleAlphaForeground = 50; } else { moduleAlphaBackground = 100; moduleAlphaForeground = 100; } moduleColorBackground = color( hue(moduleColorBackground), saturation(moduleColorBackground), brightness(moduleColorBackground), moduleAlphaBackground ); moduleColorForeground = color( hue(moduleColorForeground), saturation(moduleColorForeground), brightness(moduleColorForeground), moduleAlphaForeground ); } if (key == '0') { moduleRadiusBackground = 30; moduleRadiusForeground = 15; moduleAlphaBackground = 100; moduleAlphaForeground = 100; moduleColorBackground = color(0, 0, 0, moduleAlphaBackground); moduleColorForeground = color(0, 0, 100, moduleAlphaForeground); } if (keyCode == UP_ARROW) moduleRadiusBackground += 2; if (keyCode == DOWN_ARROW) moduleRadiusBackground = max(moduleRadiusBackground - 2, 10); if (keyCode == LEFT_ARROW) moduleRadiusForeground = max(moduleRadiusForeground - 2, 5); if (keyCode == RIGHT_ARROW) moduleRadiusForeground += 2; } function colorsEqual(col1, col2) { return col1.toString() == col2.toString(); } <|start_filename|>03_A/Cover_Barcode/lib/barcodeInfo.js<|end_filename|> barcodeInfo = [ { x: 12.5, y: 7.4, width: 1.8, height: 71.3 }, { x: 15.9, y: 7.4, width: 2.6, height: 71.3 }, { x: 20.2, y: 7.4, width: 5.8, height: 71.3 }, { x: 28.6, y: 7.4, width: 3.2, height: 71.3 }, { x: 37.7, y: 7.4, width: 2.6, height: 71.3 }, { x: 43.7, y: 7.4, width: 2.4, height: 71.3 }, { x: 47.8, y: 7.4, width: 2.6, height: 71.3 }, { x: 57.8, y: 7.4, width: 1.8, height: 71.3 }, { x: 62.1, y: 7.4, width: 3.4, height: 71.3 }, { x: 67.9, y: 7.4, width: 6, height: 71.3 }, { x: 78, y: 7.4, width: 1.8, height: 71.3 }, { x: 85.7, y: 7.4, width: 1.6, height: 71.3 }, { x: 89.9, y: 7.4, width: 1.6, height: 71.3 }, { x: 97.4, y: 7.4, width: 4.2, height: 71.3 }, { x: 103.2, y: 7.4, width: 2.6, height: 71.3 }, { x: 107.4, y: 7.4, width: 1.8, height: 71.3 }, { x: 111.7, y: 7.4, width: 1.6, height: 71.3 }, { x: 120.9, y: 7.4, width: 2.4, height: 71.3 }, { x: 125.2, y: 7.4, width: 5.8, height: 71.3 }, { x: 133.4, y: 7.4, width: 1.8, height: 71.3 }, { x: 139.5, y: 7.4, width: 5.8, height: 71.3 }, { x: 146.8, y: 7.4, width: 1.8, height: 71.3 }, { x: 152.8, y: 7.4, width: 5.8, height: 71.3 }, { x: 162.9, y: 7.4, width: 1.8, height: 71.3 }, { x: 167.1, y: 7.4, width: 3.4, height: 71.3 }, { x: 172.9, y: 7.4, width: 4.2, height: 71.3 }, { x: 180.6, y: 7.4, width: 5.8, height: 71.3 }, { x: 188.9, y: 7.4, width: 1.8, height: 71.3 }, { x: 194.9, y: 7.4, width: 1.6, height: 71.3 }, { x: 198.1, y: 7.4, width: 2.6, height: 71.3 } ]; <|start_filename|>01_P/P_2_1_2_04/sketch.js<|end_filename|> // P_2_1_2_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * moving corners of rectangles in a grid * * MOUSE * position x : corner position offset x * position y : corner position offset y * left click : random position * * KEYS * s : save png */ 'use strict'; var tileCount = 20; var actRandomSeed = 0; var rectSize = 30; function setup() { createCanvas(600, 600); colorMode(HSB, 360, 100, 100, 100); noStroke(); fill(192, 100, 64, 60); } function draw() { clear(); randomSeed(actRandomSeed); for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = width / tileCount * gridX; var posY = height / tileCount * gridY; var shiftX1 = mouseX / 20 * random(-1, 1); var shiftY1 = mouseY / 20 * random(-1, 1); var shiftX2 = mouseX / 20 * random(-1, 1); var shiftY2 = mouseY / 20 * random(-1, 1); var shiftX3 = mouseX / 20 * random(-1, 1); var shiftY3 = mouseY / 20 * random(-1, 1); var shiftX4 = mouseX / 20 * random(-1, 1); var shiftY4 = mouseY / 20 * random(-1, 1); push(); translate(posX, posY); beginShape(); vertex(shiftX1, shiftY1); vertex(rectSize + shiftX2, shiftY2); vertex(rectSize + shiftX3, rectSize + shiftY3); vertex(shiftX4, rectSize + shiftY4); endShape(); pop(); } } } function mousePressed() { actRandomSeed = random(100000); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>02_M/M_2_3_01/sketch.js<|end_filename|> // M_2_3_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draws an amplitude modulated oscillator * * KEYS * i : toggle draw info signal * c : toggle draw carrier signal * 1/2 : info signal frequency -/+ * arrow left/right : info signal phi -/+ * 7/8 : carrier signal frequency -/+ (modulation frequency) * s : save png */ 'use strict'; var sketch = function(p) { var pointCount = 600; var freq = 2; var phi = 0; var modFreq = 12; var drawFrequency = true; var drawModulation = true; var drawCombination = true; var angle; var y; p.setup = function() { p.createCanvas(p.windowWidth,800); p.noFill(); pointCount = p.width; }; p.draw = function() { p.background(255); p.strokeWeight(1); p.translate(0, p.height / 2); // draw oscillator with freq and phi if (drawFrequency) { p.beginShape(); for (var i = 0; i <= pointCount; i++) { angle = p.map(i, 0, pointCount, 0, p.TAU); y = p.sin(angle * freq + p.radians(phi)); y *= p.height / 4; p.vertex(i,y); } p.endShape(); } // draw oscillator with modFreq if (drawModulation) { p.stroke(0,130,164,128); p.beginShape(); for (var i = 0; i <= pointCount; i++) { angle = p.map(i, 0, pointCount, 0, p.TAU); y = p.cos(angle * modFreq); y *= p.height / 4; p.vertex(i,y); } p.endShape(); } // draw both combined p.stroke(0); p.strokeWeight(2); p.beginShape(); for (var i = 0; i <= pointCount; i++) { angle = p.map(i, 0, pointCount, 0, p.TAU); var info = p.sin(angle * freq + p.radians(phi)); var carrier = p.cos(angle * modFreq); y = info * carrier; y *= p.height / 4; p.vertex(i,y); } p.endShape(); }; p.keyPressed = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); if (p.key == 'i' || p.key == 'I') drawFrequency = !drawFrequency; if (p.key == 'c' || p.key == 'C') drawModulation = !drawModulation; if (p.key == '1') freq--; if (p.key == '2') freq++; freq = p.max(freq,1); if (p.keyCode == p.LEFT_ARROW) phi -= 15; if (p.keyCode == p.RIGHT_ARROW) phi += 15; if (p.key == '7') modFreq--; if (p.key == '8') modFreq++; modFreq = p.max(modFreq,1); console.log('freq: ' + freq + ', phi: ' + phi + ', modFreq: ' + modFreq); }; }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_2_2_6_05/sketch.js<|end_filename|> // P_2_2_6_05 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Drawing tool that moves a branching pendulum contraption along paths drawn by the mouse. * The last joint of the pendulum leaves behind its own vertex, which is used to draw the * letters of a sentence. * * MOUSE * mouse : click and drag to create a path to draw a pendulum along with * * KEYS * 1 : toggle path line * 2 : toggle pendulum * 3 : toggle pendulum path * - : decrease gravity * + : increase gravity * arrow down : decrease length of lines * arrow up : increase length of lines * arrow left : decrease joints * arrow right : increase joints * del, backspace : clear screen * s : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) */ 'use strict'; var shapes = []; var newShape; var joints = 4; var lineLength = 128; var resolution = 0.04; var gravity = 0.094; var damping = 0.998; var showPath = true; var showPendulum = true; var showPendulumPath = true; var font = 'Georgia'; var letters = 'Sie hören nicht die folgenden Gesänge, Die Seelen, denen ich die ersten sang, Zerstoben ist das freundliche Gedränge, Verklungen ach! der erste Wiederklang.'; var fontSizeMin = 6; function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); strokeWeight(1); textFont(font, fontSizeMin); } function draw() { background(0, 0, 100); shapes.forEach(function(shape) { shape.draw(); shape.update(); }); if (newShape) { newShape.addPos(mouseX, mouseY); newShape.draw(); newShape.update(); } } function Shape(pendulumPathColor) { this.shapePath = []; this.pendulumPath = []; this.pendulumPathColor = pendulumPathColor; this.iterator = 0; this.lineLength = lineLength; this.resolution = resolution; this.pendulum = new Pendulum(this.lineLength, joints); this.letterIndex = 0; Shape.prototype.addPos = function(x, y) { var newPos = createVector(x, y); this.shapePath.push(newPos); }; Shape.prototype.draw = function() { strokeWeight(0.8); stroke(0, 10); if (showPath) { beginShape(); this.shapePath.forEach(function(pos) { vertex(pos.x, pos.y); }); endShape(); } if (showPendulumPath && this.pendulumPath.length) { noStroke(); fill(this.pendulumPathColor); this.letterIndex = 0; this.pendulumPath.forEach(function(pos, posIndex) { var newLetter = letters.charAt(this.letterIndex); var nextPosIndex = this.pendulumPath.findIndex(function(nextPos, nextPosIndex) { if (nextPosIndex > posIndex) { var d = p5.Vector.dist(nextPos, pos); textSize(max(fontSizeMin, d)); return d > textWidth(newLetter); } }); var nextPos = this.pendulumPath[nextPosIndex]; if (nextPos) { var angle = atan2(nextPos.y - pos.y, nextPos.x - pos.x); push(); translate(pos.x, pos.y); rotate(angle); text(newLetter, 0, 0); pop(); this.letterIndex++; if (this.letterIndex >= letters.length) { this.letterIndex = 0; } } }.bind(this)); noFill(); } if (this.iterator < this.shapePath.length) { var currentIndex = floor(this.iterator); var currentPos = this.shapePath[currentIndex]; var previousPos = this.shapePath[currentIndex - 1]; if (previousPos) { var offsetPos = p5.Vector.lerp(previousPos, currentPos, this.iterator - currentIndex); var heading = atan2(currentPos.y - previousPos.y, currentPos.x - previousPos.x) - HALF_PI; push(); translate(offsetPos.x, offsetPos.y); this.pendulum.update(heading); if (showPendulum) { this.pendulum.draw(); } pop(); this.pendulumPath.push(this.pendulum.getTrail(offsetPos)); } } }; Shape.prototype.update = function() { this.iterator += this.resolution; this.iterator = constrain(this.iterator, 0, this.shapePath.length); }; } function Pendulum(size, hierarchy) { this.hierarchy = hierarchy - 1; this.pendulumArm; this.size = size; this.angle = random(TAU); this.origin = createVector(0, 0); this.end = createVector(0, 0); this.gravity = gravity; this.damping = damping; this.angularAcceleration = 0; this.angularVelocity = 0; if (this.hierarchy > 0) { this.pendulumArm = new Pendulum(this.size / 1.5, this.hierarchy); } Pendulum.prototype.update = function(heading) { this.end.set(this.origin.x + this.size * sin(this.angle), this.origin.y + this.size * cos(this.angle)); this.angularAcceleration = (-this.gravity / this.size) * sin(this.angle + heading); this.angle += this.angularVelocity; this.angularVelocity += this.angularAcceleration; this.angularVelocity *= this.damping; if (this.pendulumArm) { this.pendulumArm.update(heading); } }; Pendulum.prototype.getTrail = function(offset, end) { if (this.pendulumArm) { if (end) { end.add(this.end); } else { end = this.end.copy(); } return this.pendulumArm.getTrail(offset, end); } else { return this.end.copy().add(end).add(offset); } }; Pendulum.prototype.draw = function() { stroke(0, 40); beginShape(); vertex(this.origin.x, this.origin.y); vertex(this.end.x, this.end.y); endShape(); fill(0, 20); ellipse(this.end.x, this.end.y, 2, 2); noFill(); if (this.pendulumArm) { push(); translate(this.end.x, this.end.y); this.pendulumArm.draw(); pop(); } }; } function mousePressed() { newShape = new Shape(color(random(360), 80, 60)); newShape.addPos(mouseX, mouseY); } function mouseReleased() { shapes.push(newShape); newShape = undefined; } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) { shapes = []; newShape = undefined; } if (keyCode == UP_ARROW) lineLength += 2; if (keyCode == DOWN_ARROW) lineLength -= 2; if (keyCode == LEFT_ARROW) { joints--; joints = max(1, joints); } if (keyCode == RIGHT_ARROW) { joints++; joints = max(1, joints); } if (key == '1') showPath = !showPath; if (key == '2') showPendulum = !showPendulum; if (key == '3') showPendulumPath = !showPendulumPath; if (key == '-') gravity -= 0.001; if (key == '+') gravity += 0.001; } <|start_filename|>libraries/setup.js<|end_filename|> var fs = require('fs-sync'); var path = require('path'); var glob = require('glob'); var pkg = fs.readJSON('../package.json'); var sources = pkg.install.sources; // copy dependencies from ./node_modules to ./libraries for (var libName in sources) { var sourcePaths = sources[libName]; for (var sourcePath of sourcePaths) { var fileName = path.basename(sourcePath); var filePath = path.join('..', sourcePath); var targetPath = path.join(libName, fileName); console.log('Copy:', filePath, '->', targetPath); fs.copy(filePath, targetPath, {force: true}); } } // generate index.html file with links to all sketches var sketches = glob.sync('../0*/*_*/sketch.js'); var html = '<head>\n'; html += '\t<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:600" rel="stylesheet">\n'; html += '\t<link href="styles/list.css" rel="stylesheet" type="text/css">\n'; html += '</head>\n<body>\n<section><nav>\n'; var currentFolder = ''; sketches.forEach(function(sketchPath) { var url = path.dirname(path.relative('../', sketchPath)); var dir = path.dirname(url).split(path.sep).pop(); var name = path.basename(url); if (currentFolder !== dir) { html += '</nav>\n<h3>' + dir + '</h3>\n<nav>\n'; currentFolder = dir; } html += '<a class="sketch" href="' + url + '/index.html" title="' + name + '">\n'; html += '\t<div class="sketch__img">\n'; html += '\t\t<img src="' + url + '/' + name + '.png" alt="' + name + '" />\n'; html += '\t</div>\n'; html += '\t<span class="btn--link">' + name + '</span>\n'; html += '</a>\n'; }); html += '</nav></section>\n</body>'; fs.write('../index.html', html); <|start_filename|>01_P/P_2_2_4_02_class_version/sketch.js<|end_filename|> // P_2_2_4_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * limited diffusion aggregation * * KEYS * 1 : toggle draw original position of circles * s : save png */ 'use strict'; var shapes = []; var maxCount = 5000; // max count of the cirlces var x = []; var y = []; var r = []; var x2 = []; var y2 = []; var drawGhosts = false; function setup() { createCanvas(800, 800); // first circle shapes.push(new Shape(width / 2, height / 2, 360)); } function draw() { clear(); strokeWeight(0.5); noFill(); // create a random set of parameters var newR = random(1, 7); var newX = random(newR, width - newR); var newY = random(newR, height - newR); var closestDist = Number.MAX_VALUE; var closestIndex = 0; // which shape is the closest? var closestShape; shapes.forEach(function(shape) { var newDist = dist(newX, newY, shape.x, shape.y); if (newDist < closestDist) { closestDist = newDist; closestShape = shape; } }); // align it to the closest circle outline var angle = atan2(newY - closestShape.y, newX - closestShape.x); shapes.push(new Shape( closestShape.x + cos(angle) * (closestShape.r + newR), closestShape.y + sin(angle) * (closestShape.r + newR), newR, newX, newY )); // draw circles at random position and lines shapes.forEach(function(shape, index) { if (drawGhosts) { fill(230); ellipse(shape.newX, shape.newY, shape.r * 2); line(shape.newX, shape.newY, shape.x, shape.y); } if (index == 0) { noFill(); } else { fill(50); } ellipse(shape.x, shape.y, shape.r * 2); }); if (shapes.length >= maxCount) noLoop(); } function Shape(x, y, r, newX, newY) { this.x = x; this.y = y; this.r = r; this.newX = newX; this.newY = newY; } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') drawGhosts = !drawGhosts; } <|start_filename|>01_P/P_2_1_4_02/sketch.js<|end_filename|> // P_2_1_4_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Use a video to check on/off a grid of checkboxes * Shout out to Dan Shiffman's checkbox mirror example * * * SLIDER * drag : drag the slider to adjust the image threshold * * CONTRIBUTED BY * [<NAME>](http://jk-lee.com) * * INSPIRED BY * [<NAME>](http://shiffman.net/) */ 'use strict'; var video; var slider; var cols = 40; var rows = 40; var boxes; var boxHolder; function preload(){ video = createVideo('data/ball.mov'); } function setup() { noCanvas(); pixelDensity(1); boxHolder = createDiv(''); boxHolder.id('mirror'); boxes = []; video.size(cols, rows); // slider threshold at 200 slider = createSlider(0, 255, 200); for (var y = 0; y < rows; y++) { for (var x = 0; x < cols; x++) { var box = createCheckbox(); box.style('display', 'inline'); box.parent('mirror'); boxes.push(box); } var linebreak = createSpan('<br/>'); linebreak.parent('mirror'); } // play the video in a loop video.loop(); } function draw() { video.loadPixels(); for (var y = 0; y < video.height; y++) { for (var x = 0; x < video.width; x++) { // get the video pixel location var index = (x + (y * video.height)) * 4; var r = video.pixels[index]; var g = video.pixels[index + 1]; var b = video.pixels[index + 2]; var bright = (r + g + b) / 3; var threshold = slider.value(); var checkIndex = x + y * cols; if (bright > threshold - 1) { boxes[checkIndex].checked(false); } else { boxes[checkIndex].checked(true); } } } } <|start_filename|>01_P/P_2_1_1_04/sketch.js<|end_filename|> // P_2_1_1_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * shapes in a grid, that are always facing the mouse * * MOUSE * position x/y : position to face * * KEYS * 1-7 : choose shapes * arrow up/down : scale of shapes * arrow left/right : additional rotation of shapes * d : toggle size depending on distance * g : toggle grid resolution * s : save png */ 'use strict'; var tileCount = 10; var tileWidth; var tileHeight; var shapeSize = 50; var newShapeSize = shapeSize; var shapeAngle = 0; var maxDist; var currentShape; var shapes; var sizeMode = 0; function preload() { shapes = []; shapes.push(loadImage('data/module_1.svg')); shapes.push(loadImage('data/module_2.svg')); shapes.push(loadImage('data/module_3.svg')); shapes.push(loadImage('data/module_4.svg')); shapes.push(loadImage('data/module_5.svg')); shapes.push(loadImage('data/module_6.svg')); shapes.push(loadImage('data/module_7.svg')); } function setup() { createCanvas(600, 600); imageMode(CENTER); // set the current shape to the first in the array currentShape = shapes[0]; tileWidth = width / tileCount; tileHeight = height / tileCount; maxDist = sqrt(pow(width, 2) + pow(height, 2)); } function draw() { clear(); for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = tileWidth * gridX + tileWidth / 2; var posY = tileHeight * gridY + tileWidth / 2; // calculate angle between mouse position and actual position of the shape var angle = atan2(mouseY - posY, mouseX - posX) + (shapeAngle * (PI / 180)); if (sizeMode == 0) newShapeSize = shapeSize; if (sizeMode == 1) newShapeSize = shapeSize * 1.5 - map(dist(mouseX, mouseY, posX, posY), 0, 500, 5, shapeSize); if (sizeMode == 2) newShapeSize = map(dist(mouseX, mouseY, posX, posY), 0, 500, 5, shapeSize); push(); translate(posX, posY); rotate(angle); noStroke(); image(currentShape, 0, 0, newShapeSize, newShapeSize); pop(); } } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'd' || key == 'D') sizeMode = (sizeMode + 1) % 3; if (key == 'g' || key == 'G') { tileCount += 5; if (tileCount > 20) { tileCount = 10; } tileWidth = width / tileCount; tileHeight = height / tileCount; } if (key == '1') currentShape = shapes[0]; if (key == '2') currentShape = shapes[1]; if (key == '3') currentShape = shapes[2]; if (key == '4') currentShape = shapes[3]; if (key == '5') currentShape = shapes[4]; if (key == '6') currentShape = shapes[5]; if (key == '7') currentShape = shapes[6]; if (keyCode == UP_ARROW) shapeSize += 5; if (keyCode == DOWN_ARROW) shapeSize = max(shapeSize - 5, 5); if (keyCode == LEFT_ARROW) shapeAngle += 5; if (keyCode == RIGHT_ARROW) shapeAngle -= 5; } <|start_filename|>01_P/P_3_1_4_02/sketch.js<|end_filename|> // P_3_1_4_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Counting the words of a text and display them in a treemap diagram. * All words with the same number of letters are grouped in a nested treemap. * Only words with less than 10 letters are stored. * * KEYS * r : toggle random mode * h : only horizontal rows * v : only vertical rows * b : both kind of rows * 1-9 : switch on and off words with this number of letters * 0 : show all words * s : save png */ 'use strict'; var joinedText; var treemap; var font; var doSort = true; var rowDirection = 'both'; function preload() { font = loadFont('data/miso-bold.ttf'); joinedText = loadStrings('data/pride_and_prejudice.txt'); } function setup() { createCanvas(windowWidth, windowHeight); // createCanvas(windowWidth, round(windowWidth*1.343)); // createCanvas(windowWidth*2, round(windowWidth*1.343)*2); joinedText = joinedText.join(' '); // If you want to get rid of all number chars too, just uncomment the following line // joinedText = joinedText.replace(/\d+/g, ''); var words = joinedText.match(/\w+/g); // create the main treemap treemap = new gd.Treemap(1, 1, width - 3, height - 3, { sort: doSort, direction: rowDirection, padding: 2, ignore: [] }); // make an array for the nested treemaps var subTreemaps = []; // count words for (var i = 0; i < words.length; i++) { var w = words[i].toLowerCase(); var index = w.length; // Add only words with less than 10 letters if (index < 10) { var t = subTreemaps[index]; if (t == undefined) { t = treemap.addTreemap(index); subTreemaps[index] = t; } t.addData(w); } } treemap.calculate(); } function draw() { background(255); textAlign(CENTER, BASELINE); // colorMode(HSB, 360, 100, 100, 100); strokeWeight(1); for (var i = 0; i < treemap.items.length; i++) { var subTreemap = treemap.items[i]; if (!subTreemap.ignored) { // var h = map(i, 0, treemap.items.length, 50, 150); for (var j = 0; j < subTreemap.items.length; j++) { var item = subTreemap.items[j]; // var s = map(subTreemap.items[j].count, 0, subTreemap.maxCount, 10, 30); // fill(h, s, 100); // stroke(h, s + 20, 90); noFill(); stroke(0); rect(item.x, item.y, item.w, item.h); var word = subTreemap.items[j].data; textFont(font, 100); var textW = textWidth(word); var fontSize = 100 * (item.w * 0.9) / textW; fontSize = min(fontSize, (item.h * 0.9)); textFont(font, fontSize); fill(0); noStroke(); text(word, item.x + item.w / 2, item.y + item.h * 0.8); } } } noLoop(); } function keyTyped() { // export png if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'r' || key == 'R') { doSort = !doSort; treemap.options.sort = doSort; treemap.calculate(); loop(); } if (key == 'h' || key == 'H') { rowDirection = 'horizontal'; treemap.options.direction = rowDirection; treemap.calculate(); loop(); } if (key == 'v' || key == 'V') { rowDirection = 'vertical'; treemap.options.direction = rowDirection; treemap.calculate(); loop(); } if (key == 'b' || key == 'B') { rowDirection = 'both'; treemap.options.direction = rowDirection; treemap.calculate(); loop(); } // number key 1 - 9 if (keyCode >= 49 && keyCode <= 57) { var num = keyCode - 48; // search for the pressed number in the ignore array var i = treemap.options.ignore.indexOf(num); if (i >= 0) { // found value, so remove it treemap.options.ignore.splice(i, 1); } else { // not found, so add to array treemap.options.ignore.push(num); } treemap.calculate(); loop(); } if (key == '0') { treemap.options.ignore = []; treemap.calculate(); loop(); } } function keyPressed() { // if (keyCode == RIGHT_ARROW); } <|start_filename|>02_M/M_6_1_02/sketch.js<|end_filename|> // M_6_1_02 // Spring.js // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * two nodes and a spring * * MOUSE * click, drag : postion of one of the nodes * * KEYS * s : save png */ 'use strict'; var sketch = function(p) { var nodeA, nodeB; var spring; p.setup = function() { p.createCanvas(p.windowWidth, p.windowHeight); p.noStroke(); p.fill(0); nodeA = new Node(p.width / 2 + p.random(-50, 50), p.height / 2 + p.random(-50, 50)); nodeB = new Node(p.width / 2 + p.random(-50, 50), p.height / 2 + p.random(-50, 50)); nodeA.damping = 0.1; nodeB.damping = 0.1; spring = new Spring(nodeA, nodeB); spring.length = 100; spring.stiffness = 0.6; spring.damping = 0.3; }; p.draw = function() { p.background(255); if (p.mouseIsPressed == true) { nodeA.x = p.mouseX; nodeA.y = p.mouseY; } // update spring spring.update(); // update node positions nodeA.update(); nodeB.update(); // draw spring p.stroke(0, 130, 164); p.strokeWeight(4); p.line(nodeA.x, nodeA.y, nodeB.x, nodeB.y); // draw nodes p.noStroke(); p.fill(0); p.ellipse(nodeA.x, nodeA.y, 20, 20); p.ellipse(nodeB.x, nodeB.y, 20, 20); }; p.keyPressed = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); }; }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_3_1_3_04/sketch.js<|end_filename|> // P_3_1_3_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * analysing and sorting the letters of a text * connecting subsequent letters with lines * * MOUSE * position x : interpolate between normal text and sorted position * * KEYS * 1 : toggle grey lines on/off * 2 : toggle colored lines on/off * 3 : toggle text on/off * 4 : switch all letters off * 5 : switch all letters on * a-z : switch letter on/off * ctrl : save png */ 'use strict'; var joinedText; var charSet; var counters = []; var drawLetters = []; var posX; var posY; var drawGreyLines = false; var drawColoredLines = true; var drawText = true; function preload() { joinedText = loadStrings('data/faust_kurz.txt'); } function setup() { createCanvas(1200, windowHeight); colorMode(HSB, 360, 100, 100, 100); textFont('monospace', 18); fill(0); joinedText = joinedText.join(' '); charSet = getUniqCharacters(); for (var i = 0; i < charSet.length; i++) { counters[i] = 0; drawLetters[i] = true; } countCharacters(); } function draw() { background(360); translate(50, 0); noStroke(); posX = 0; posY = 200; var oldX = 0; var oldY = 0; var sortPositionsX = []; var oldPositionsX = []; var oldPositionsY = []; for (var i = 0; i < joinedText.length; i++) { sortPositionsX[i] = 0; oldPositionsX[i] = 0; oldPositionsY[i] = 0; } // draw counters if (mouseX >= width - 50) { textSize(10); for (var i = 0; i < charSet.length; i++) { textAlign(LEFT); text(charSet.charAt(i), -15, i * 20 + 40); textAlign(RIGHT); text(counters[i], -20, i * 20 + 40); } textAlign(LEFT); textSize(18); } // go through all characters in the text to draw them for (var i = 0; i < joinedText.length; i++) { // again, find the index of the current letter in the character set var upperCaseChar = joinedText.charAt(i).toUpperCase(); var index = charSet.indexOf(upperCaseChar); if (index < 0) continue; var m = map(mouseX, 50, width - 50, 0, 1); m = constrain(m, 0, 1); var sortX = sortPositionsX[index]; var interX = lerp(posX, sortX, m); var sortY = index * 20 + 40; var interY = lerp(posY, sortY, m); if (drawLetters[index]) { if (drawGreyLines) { if (oldX != 0 && oldY != 0) { stroke(0, 10); line(oldX, oldY, interX, interY); } oldX = interX; oldY = interY; } if (drawColoredLines) { if (oldPositionsX[index] != 0 && oldPositionsY[index] != 0) { stroke(index * 10, 80, 60, 50); line(oldPositionsX[index], oldPositionsY[index], interX, interY); } oldPositionsX[index] = interX; oldPositionsY[index] = interY; } if (drawText) { text(joinedText.charAt(i), interX, interY); } } else { oldX = 0; oldY = 0; } sortPositionsX[index] += textWidth(joinedText.charAt(i)); posX += textWidth(joinedText.charAt(i)); if (posX >= width - 200 && upperCaseChar == ' ') { posY += 40; posX = 0; } } } function getUniqCharacters() { var charsArray = joinedText.toUpperCase().split(''); var uniqCharsArray = charsArray.filter(function(char, index) { return charsArray.indexOf(char) == index; }).sort(); return uniqCharsArray.join(''); } function countCharacters() { for (var i = 0; i < joinedText.length; i++) { // get one character from the text and turn it to uppercase var index = charSet.indexOf(joinedText.charAt(i).toUpperCase()); // increacre the respective counter if (index >= 0) counters[index]++; } } function keyReleased() { if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); if (key == '1') drawGreyLines = !drawGreyLines; if (key == '2') drawColoredLines = !drawColoredLines; if (key == '3') drawText = !drawText; if (key == '4') { for (var i = 0; i < charSet.length; i++) { drawLetters[i] = false; } } if (key == '5') { for (var i = 0; i < charSet.length; i++) { drawLetters[i] = true; } } var index = charSet.indexOf(key.toUpperCase()); if (index >= 0) { drawLetters[index] = !drawLetters[index]; } } <|start_filename|>01_P/P_2_1_2_01/sketch.js<|end_filename|> // P_2_1_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing size and position of circles in a grid * * MOUSE * position x : circle position * position y : circle size * left click : random position * * KEYS * s : save png */ 'use strict'; var tileCount = 20; var actRandomSeed = 0; var circleAlpha = 130; var circleColor; function setup() { createCanvas(600, 600); noFill(); circleColor = color(0, 0, 0, circleAlpha); } function draw() { translate(width / tileCount / 2, height / tileCount / 2); background(255); randomSeed(actRandomSeed); stroke(circleColor); strokeWeight(mouseY / 60); for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = width / tileCount * gridX; var posY = height / tileCount * gridY; var shiftX = random(-mouseX, mouseX) / 20; var shiftY = random(-mouseX, mouseX) / 20; ellipse(posX + shiftX, posY + shiftY, mouseY / 15, mouseY / 15); } } } function mousePressed() { actRandomSeed = random(100000); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>01_P/P_2_3_6_01/sketch.js<|end_filename|> // P_2_3_6_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw tool. draws a specific module according to * its east, south, west and north neighbours. * * MOUSE * drag left : draw new module * drag right : delete a module * * KEYS * del, backspace : clear screen * g : toggle show grid * d : toggle show module values * s : save png */ 'use strict'; var modules; var tileSize = 30; var gridResolutionX; var gridResolutionY; var tiles = []; var doDrawGrid = true; var isDebugMode = false; function preload() { // load SVG modules modules = []; // METHOD 1: Looping through local files is efficient // for (var i = 0; i < 16; i++) { // modules[i] = loadImage('data/' + nf(i, 2) + '.svg'); // } // METHOD 2: Read files one-by-one modules[0] = loadImage('data/00.svg'); modules[1] = loadImage('data/01.svg'); modules[2] = loadImage('data/02.svg'); modules[3] = loadImage('data/03.svg'); modules[4] = loadImage('data/04.svg'); modules[5] = loadImage('data/05.svg'); modules[6] = loadImage('data/06.svg'); modules[7] = loadImage('data/07.svg'); modules[8] = loadImage('data/08.svg'); modules[9] = loadImage('data/09.svg'); modules[10] = loadImage('data/10.svg'); modules[11] = loadImage('data/11.svg'); modules[12] = loadImage('data/12.svg'); modules[13] = loadImage('data/13.svg'); modules[14] = loadImage('data/14.svg'); modules[15] = loadImage('data/15.svg'); } function setup() { // use full window size createCanvas(windowWidth, windowHeight); cursor(CROSS); rectMode(CENTER); imageMode(CENTER); strokeWeight(0.15); textSize(8); textAlign(CENTER, CENTER); gridResolutionX = round(width / tileSize) + 2; gridResolutionY = round(height / tileSize) + 2; initTiles(); } function draw() { background(255); if (mouseIsPressed) { if (mouseButton == LEFT) setTile(); if (mouseButton == RIGHT) unsetTile(); } if (doDrawGrid) drawGrid(); drawModules(); } function initTiles() { for (var gridX = 0; gridX < gridResolutionX; gridX++) { tiles[gridX] = []; for (var gridY = 0; gridY < gridResolutionY; gridY++) { tiles[gridX][gridY] = 0; } } } function setTile() { // convert mouse position to grid coordinates var gridX = floor(mouseX / tileSize) + 1; gridX = constrain(gridX, 1, gridResolutionX - 2); var gridY = floor(mouseY / tileSize) + 1; gridY = constrain(gridY, 1, gridResolutionY - 2); tiles[gridX][gridY] = 1; } function unsetTile() { var gridX = floor(mouseX / tileSize) + 1; gridX = constrain(gridX, 1, gridResolutionX - 2); var gridY = floor(mouseY / tileSize) + 1; gridY = constrain(gridY, 1, gridResolutionY - 2); tiles[gridX][gridY] = 0; } function drawGrid() { for (var gridX = 0; gridX < gridResolutionX; gridX++) { for (var gridY = 0; gridY < gridResolutionY; gridY++) { var posX = tileSize * gridX - tileSize / 2; var posY = tileSize * gridY - tileSize / 2; fill(255); if (isDebugMode) { if (tiles[gridX][gridY] == 1) fill(220); } rect(posX, posY, tileSize, tileSize); } } } function drawModules() { for (var gridX = 0; gridX < gridResolutionX - 1; gridX++) { for (var gridY = 0; gridY < gridResolutionY - 1; gridY++) { // use only active tiles if (tiles[gridX][gridY] == 1) { // check the four neightbours, each can be true or false var NORTH = str(tiles[gridX][gridY - 1]); var WEST = str(tiles[gridX - 1][gridY]); var SOUTH = str(tiles[gridX][gridY + 1]); var EAST = str(tiles[gridX + 1][gridY]); // create binary result out of it var binaryResult = NORTH + WEST + SOUTH + EAST; // convert binary string to a decimal value from 0 - 15 var decimalResult = parseInt(binaryResult, 2); var posX = tileSize * gridX - tileSize / 2; var posY = tileSize * gridY - tileSize / 2; // decimalResult is also the index for the shape array image(modules[decimalResult], posX, posY, tileSize, tileSize); if (isDebugMode) { fill(150); text(decimalResult + '\n' + binaryResult, posX, posY); } } } } } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) initTiles(); if (key == 'g' || key == 'G') doDrawGrid = !doDrawGrid; if (key == 'd' || key == 'D') isDebugMode = !isDebugMode; } <|start_filename|>02_M/M_1_5_01/sketch.js<|end_filename|> // M_1_5_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * how to transform noise values into directions (angles) and brightness levels * * MOUSE * position x/y : specify noise input range * * KEYS * d : toogle display brightness circles on/off * arrow up : noise falloff + * arrow down : noise falloff - * arrow left : noise octaves - * arrow right : noise octaves + * space : new noise seed * s : save png */ 'use strict'; var sketch = function(p) { var octaves = 4; var falloff = 0.5; var tileSize = 40; var gridResolutionX; var gridResolutionY; var debugMode = true; var arrow; p.preload = function() { // preload svg arrow = p.loadImage('data/arrow.svg'); }; p.setup = function() { p.createCanvas(800,800); p.cursor(p.CROSS); gridResolutionX = p.round(p.width / tileSize); gridResolutionY = p.round(p.height / tileSize); p.strokeCap(p.SQUARE); }; p.draw = function() { p.background(255); p.noiseDetail(octaves,falloff); var noiseXRange = p.mouseX / 100; var noiseYRange = p.mouseY / 100; for (var gY = 0; gY <= gridResolutionY; gY++) { for (var gX = 0; gX <= gridResolutionX; gX++) { var posX = tileSize * gX; var posY = tileSize * gY; // get noise value var noiseX = p.map(gX, 0, gridResolutionX, 0, noiseXRange); var noiseY = p.map(gY, 0, gridResolutionY, 0, noiseYRange); var noiseValue = p.noise(noiseX, noiseY); var angle = noiseValue * p.TAU; p.push(); p.translate(posX, posY); // debug heatmap if (debugMode) { p.noStroke(); p.fill(noiseValue * 255); p.ellipse(0, 0, tileSize * 0.25, tileSize * 0.25); } // arc p.noFill(); p.strokeWeight(1); p.stroke(0,130,164,100); p.arc(0, 0, tileSize * 0.75, tileSize * 0.75, 0, angle); // arrow p.stroke(0); p.strokeWeight(0.75); p.rotate(angle); p.image(arrow, 0, 0, tileSize * 0.75, tileSize * 0.75); p.scale(1,-1); // mirror the other half of arrow shape p.image(arrow, 0, 0, tileSize * 0.75, tileSize * 0.75); p.pop(); } } console.log('octaves: ' + octaves + ' falloff: ' + falloff + ' noiseXRange: 0-' + noiseXRange + ' noiseYRange: 0-' + noiseYRange); }; p.keyReleased = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); if (p.key == 'd' || p.key == 'D') debugMode = !debugMode; if (p.key == ' ') p.noiseSeed(p.random(100000)); }; p.keyPressed = function() { if (p.keyCode == p.UP_ARROW) falloff += 0.05; if (p.keyCode == p.DOWN_ARROW) falloff -= 0.05; if (falloff > 1) falloff = 1; if (falloff < 0) falloff = 0; if (p.keyCode == p.LEFT_ARROW) octaves--; if (p.keyCode == p.RIGHT_ARROW) octaves++; if (octaves < 0) octaves = 0; }; }; var myp5 = new p5(sketch); <|start_filename|>libraries/concatenator.js<|end_filename|> // https://www.npmjs.com/package/concat // to run: npm install -g concat const { exec } = require('child_process'); /* ./filesaver/FileSaver.js ./g.js/g.js ./generative-design-library/generative-design-library.js ./gif.js/gif.js ./gif.js/gif.worker.js ./kd-tree/kdTree.js ./quantize/quantize.js ./quicksettings/quicksettings.js ./treemap-squarify/treemap-squarify.js */ const cmd = 'concat -o ./gg-dep-bundle/gg-dep-bundle.js ./filesaver/FileSaver.js ./g.js/g.js ./generative-design-library/generative-design-library.js ./gif.js/gif.js ./gif.js/gif.worker.js ./kd-tree/kdTree.js ./quantize/quantize.js ./quicksettings/quicksettings.js ./treemap-squarify/treemap-squarify.js' exec(cmd, (err, stdout, stderr) => { if (err) { // node couldn't execute the command return; } // the *entire* stdout and stderr (buffered) console.log("Bundled!"); }); <|start_filename|>01_P/P_4_2_2_01/sketch.js<|end_filename|> // P_4_2_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * simple tabular overview of a video file. * * KEYS * s : save png */ 'use strict'; // horizontal and vertical grid count // take care of the aspect ratio ... here 4:3 var tileCountX = 9; var tileCountY = 12; var tileWidth; var tileHeight; var imageCount = tileCountX * tileCountY; var currentImage = 0; var gridX = 0; var gridY = 0; var movie; function preload() { movie = createVideo(['data/video.mp4', 'data/video.ogg']); movie.hide(); } function setup() { createCanvas(1024, 1024); background(0); tileWidth = width / tileCountX; tileHeight = height / tileCountY; print(movie.width + ' • ' + movie.height); } function draw() { if (movie.elt.readyState == 4) { var posX = tileWidth * gridX; var posY = tileHeight * gridY; // draw video image(movie, posX, posY, tileWidth, tileHeight); currentImage++; // seek the video to next time var nextTime = map(currentImage, 0, imageCount, 0, movie.duration()); print('seek to: ' + movie.time()); movie.time(nextTime); // new grid position gridX++; if (gridX >= tileCountX) { gridX = 0; gridY++; } if (currentImage >= imageCount) noLoop(); } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>01_P/P_4_3_3_01/sketch.js<|end_filename|> // P_4_3_3_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * generating a drawing by analysing the pixels of a live video input * * MOUSE * position x : drawing speed * position y : diffusion * * KEYS * arrow up : number of curve points + * arrow down : number of curve points - * q : stop drawing * w : continue drawing * DEL/BACKSPACE : clear display * s : save png */ 'use strict'; var video; var x; var y; var curvePointX = 0; var curvePointY = 0; var pointCount = 1; var diffusion = 50; var streamReady = false; function setup() { createCanvas(640, 480); background(255); x = width / 2; y = height / 2; video = createCapture(VIDEO, function() { streamReady = true; }); video.size(width * pixelDensity(), height * pixelDensity()); video.hide(); noFill(); } function draw() { if (streamReady) { for (var j = 0; j <= mouseX / 50; j++) { // Retrieve color from capture device var c = color(video.get(width - x, y)); // convert color c to HSV var cHSV = chroma(red(c), green(c), blue(c)); strokeWeight(cHSV.get('hsv.h') / 50); stroke(c); diffusion = map(mouseY, 0, height, 5, 100); beginShape(); curveVertex(x, y); curveVertex(x, y); for (var i = 0; i < pointCount; i++) { var rx = int(random(-diffusion, diffusion)); curvePointX = constrain(x + rx, 0, width - 1); var ry = int(random(-diffusion, diffusion)); curvePointY = constrain(y + ry, 0, height - 1); curveVertex(curvePointX, curvePointY); } curveVertex(curvePointX, curvePointY); endShape(); x = curvePointX; y = curvePointY; } } } function keyReleased() { if (keyCode == DELETE || keyCode == BACKSPACE) clear(); if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'q' || key == 'Q') noLoop(); if (key == 'w' || key == 'W') loop(); if (keyCode == UP_ARROW) pointCount = min(pointCount + 1, 30); if (keyCode == DOWN_ARROW) pointCount = max(pointCount - 1, 1); } <|start_filename|>03_A/Cover_Lines/lib/Ribbon.js<|end_filename|> function Ribbon(colorPoints, additionalN, options) { this.colorPoints = []; this.additionalN = additionalN || 0; for (var i = 0; i < colorPoints.length; i++) { this.colorPoints.push(new ColorPoint(colorPoints[i].col)); // make some more colorPoints to lerp the color if (i < colorPoints.length - 1) { for (var j = 0; j < this.additionalN; j++) { var t = j / this.additionalN; var col = lerpColor(colorPoints[i].col, colorPoints[i + 1].col, t); this.colorPoints.push(new ColorPoint(col)); } } } this.options = options; Ribbon.prototype.draw = function(x, y) { penX = x; penY = y; penA = 0; penW = 50; for (var i = 0; i < this.colorPoints.length; i++) { var t = map(i, 0, this.colorPoints.length - 1, 0, 1); this.colorPoints[i].draw(t, options); } }; } function ColorPoint(col) { this.col = col; this.hueIndex = 0; this.alphaIndex = 0; ColorPoint.prototype.draw = function(t, opt) { // strokeCap(SQUARE); strokeWeight(0.3); stroke(this.col); noFill(); var r = red(this.col); var g = green(this.col); var b = blue(this.col); var a = alpha(this.col); var newA = penA + angleDifference(radians(hue(this.col)), penA) * 0.02; var newX = penX + cos(newA) * opt.step; var newY = penY + sin(newA) * opt.step; var newW = penW + (map(alpha(this.col), 0, 255, opt.minW, opt.maxW) - penW) * 0.05; var x1o = penX + cos(penA - HALF_PI) * penW / 2; var y1o = penY + sin(penA - HALF_PI) * penW / 2; var x1u = penX + cos(penA + HALF_PI) * penW / 2; var y1u = penY + sin(penA + HALF_PI) * penW / 2; var x2o = newX + cos(newA - HALF_PI) * newW / 2; var y2o = newY + sin(newA - HALF_PI) * newW / 2; var x2u = newX + cos(newA + HALF_PI) * newW / 2; var y2u = newY + sin(newA + HALF_PI) * newW / 2; for (var i = 0; i <= opt.n; i++) { var t = i / opt.n; var x1 = lerp(x1o, x1u, t); var y1 = lerp(y1o, y1u, t); var x2 = lerp(x2o, x2u, t); var y2 = lerp(y2o, y2u, t); var afac = 1 - 2 * abs(t - 0.5); // var afac = 1 - pow(2 * (t - 0.5), 2); var alph = a * afac; alph = pow(alph / 255, 0.75) * 255; stroke(r, g, b, alph); line(x1, y1, x2, y2); } penX = newX; penY = newY; penA = newA; penW = newW; }; } function angleDifference(theAngle1, theAngle2) { var a1 = (theAngle1 % TWO_PI + TWO_PI) % TWO_PI; var a2 = (theAngle2 % TWO_PI + TWO_PI) % TWO_PI; if (a2 > a1) { var d1 = a2 - a1; var d2 = a1 + TWO_PI - a2; if (d1 <= d2) { return -d1; } else { return d2; } } else { var d1 = a1 - a2; var d2 = a2 + TWO_PI - a1; if (d1 <= d2) { return d1; } else { return -d2; } } } <|start_filename|>01_P/P_3_2_1_01/sketch.js<|end_filename|> // P_3_2_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. // CREDITS // FreeSans.otf (GNU FreeFont), see the readme files in data folder. /** * typo outline displayed as dots and lines * * KEYS * a-z : text input (keyboard) * backspace : delete last typed letter * ctrl : save png */ var textTyped = 'Type ...!'; var font; function setup() { createCanvas(windowWidth, windowHeight); noLoop(); opentype.load('data/FreeSans.otf', function(err, f) { if (err) { console.log(err); } else { font = f; loop(); } }); } function draw() { if (!font) return; background(255); // margin border translate(20, 220); if (textTyped.length > 0) { // get a path from OpenType.js var fontPath = font.getPath(textTyped, 0, 0, 200); // convert it to a g.Path object var path = new g.Path(fontPath.commands); // resample it with equidistant points path = g.resampleByLength(path, 11); // path = g.resampleByAmount(path, 500); // lines stroke(181, 157, 0); strokeWeight(1.0); var l = 5; for (var i = 0; i < path.commands.length; i++) { var pnt = path.commands[i]; line(pnt.x - l, pnt.y - l, pnt.x + l, pnt.y + l); } // dots fill(0); noStroke(); var diameter = 7; for (var i = 0; i < path.commands.length; i++) { var pnt = path.commands[i]; // on every 2nd point if (i % 2 == 0) { ellipse(pnt.x, pnt.y, diameter, diameter); } } } noLoop(); } function keyReleased() { // export png if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); } function keyPressed() { if (keyCode == DELETE || keyCode == BACKSPACE) { if (textTyped.length > 0) { textTyped = textTyped.substring(0, textTyped.length - 1); loop(); } } } function keyTyped() { if (keyCode >= 32) { textTyped += key; loop(); } } <|start_filename|>libraries/concatenator-with-sourcemap.js<|end_filename|> var fs = require("fs") var path = require("path") var concat = require("source-map-concat") var resolveSourceMapSync = require("source-map-resolve").resolveSourceMapSync var createDummySourceMap = require("source-map-dummy") var jsFiles = ["./filesaver/FileSaver.js","./g.js/g.js","./generative-design-library/generative-design-library.js","./gif.js/gif.js","./gif.js/gif.worker.js","./kd-tree/kdTree.js","./quantize/quantize.js","./quicksettings/quicksettings.js","./treemap-squarify/treemap-squarify.js"] jsFiles = jsFiles.map(function(file) { return { source: file, code: fs.readFileSync(file).toString() } }) jsFiles.forEach(function(file) { var previousMap = resolveSourceMapSync(file.code, file.source, fs.readFileSync) if (previousMap) { file.map = previousMap.map file.sourcesRelativeTo = previousMap.sourcesRelativeTo } else { file.map = createDummySourceMap(file.code, {source: file.source, type: "js"}) } }) function wrap(node, file) { node.prepend("void function(){\n// File: " + file.source + "\n") node.add("}();") } var output = "./gg-dep-bundle/gg-dep-bundle.js" var concatenated = concat(jsFiles, { delimiter: "\n", process: wrap, mapPath: output + ".map" }) var result = concatenated.toStringWithSourceMap({ file: path.basename(output) }) fs.writeFileSync(output, result.code) fs.writeFileSync(output + ".map", result.map.toString()) <|start_filename|>01_P/P_3_1_4_01/sketch.js<|end_filename|> // P_3_1_4_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * counting the words of a text and display them in a treemap diagram. * * KEYS * r : toggle random mode * h : only horizontal rows * v : only vertical rows * b : both kind of rows * s : save png */ 'use strict'; var joinedText; var treemap; var font; var doSort = true; var rowDirection = 'both'; function preload() { font = loadFont('data/miso-bold.ttf'); joinedText = loadStrings('data/pride_and_prejudice.txt'); } function setup() { createCanvas(windowWidth, windowHeight); // createCanvas(windowWidth, round(windowWidth*1.343)); // createCanvas(windowWidth*2, round(windowWidth*1.343)*2); joinedText = joinedText.join(' '); // If you want to get rid of all number chars too, just uncomment the following line // joinedText = joinedText.replace(/\d+/g, ''); var words = joinedText.match(/\w+/g); treemap = new gd.Treemap(1, 1, width - 3, height - 3, {sort: doSort, direction: rowDirection}); // count words for (var i = 0; i < words.length; i++) { var w = words[i].toLowerCase(); treemap.addData(w); } treemap.calculate(); } function draw() { background(255); textAlign(CENTER, BASELINE); for (var i = 0; i < treemap.items.length; i++) { var item = treemap.items[i]; fill(255); stroke(0); strokeWeight(1); rect(item.x, item.y, item.w, item.h); var word = item.data; textFont(font, 100); var textW = textWidth(word); var fontSize = 100 * (item.w * 0.9) / textW; fontSize = min(fontSize, (item.h * 0.9)); textFont(font, fontSize); fill(0); noStroke(); text(word, item.x + item.w / 2, item.y + item.h * 0.8); } noLoop(); } function keyTyped() { // export png if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'r' || key == 'R') { doSort = !doSort; treemap.options.sort = doSort; treemap.calculate(); loop(); } if (key == 'h' || key == 'H') { rowDirection = 'horizontal'; treemap.options.direction = rowDirection; treemap.calculate(); loop(); } if (key == 'v' || key == 'V') { rowDirection = 'vertical'; treemap.options.direction = rowDirection; treemap.calculate(); loop(); } if (key == 'b' || key == 'B') { rowDirection = 'both'; treemap.options.direction = rowDirection; treemap.calculate(); loop(); } } <|start_filename|>01_P/P_2_0_01/sketch.js<|end_filename|> // P_2_0_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * drawing a filled circle with lines. * * MOUSE * position x : length * position y : thickness and number of lines * * KEYS * s : save png */ 'use strict'; function setup() { createCanvas(550, 550); strokeCap(SQUARE); } function draw() { background(255); translate(width / 2, height / 2); var circleResolution = int(map(mouseY, 0, height, 2, 80)); var radius = mouseX - width / 2; var angle = TAU / circleResolution; strokeWeight(mouseY / 20); for (var i = 0; i <= circleResolution; i++) { var x = cos(angle * i) * radius; var y = sin(angle * i) * radius; line(0, 0, x, y); } } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>01_P/P_2_1_5_01/sketch.js<|end_filename|> // P_2_1_5_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Simple moire effect demonstration by moving, rotating * and scaling a shape of densely packed lines over * a background also consisting of densely packed lines. * * MOUSE * mouseX : overlay rotation or position x * mouseY : overlay scaling * * KEYS * 1-2 : switch draw mode * s : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) */ 'use strict'; var drawMode = 1; function setup() { createCanvas(800, 800); noFill(); } function draw() { background(255); translate(width / 2, height / 2); // first shape (fixed) strokeWeight(3); overlay(); // second shape (dynamically translated/rotated and scaled) var x = map(mouseX, 0, width, -50, 50); var a = map(mouseX, 0, width, -0.5, 0.5); var s = map(mouseY, 0, height, 0.7, 1); if (drawMode == 1) rotate(a); if (drawMode == 2) translate(x, 0); scale(s); strokeWeight(2); overlay(); } function overlay() { var w = width - 100; var h = height - 100; if (drawMode == 1) { for (var i = -w / 2; i < w / 2; i += 5) { line(i, -h / 2, i, h / 2); } } else if (drawMode == 2) { for (var i = 0; i < w; i += 10) { ellipse(0, 0, i); } } } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); // change draw mode if (key == '1') drawMode = 1; if (key == '2') drawMode = 2; } <|start_filename|>libraries/help-tooltip.js<|end_filename|> ;(function($, window, document, undefined) { $.get('sketch.js', function(data) { var helpText = getCommentBlock(data); if (helpText) createHelp(helpText); }, 'text'); function getCommentBlock(data) { // RegEx from https://github.com/yavorskiy/comment-parser/blob/master/parser.js var RE_COMMENT_START = /^\s*\/\*\*\s*$/m; var RE_COMMENT_END = /^\s*\*\/\s*$/m; var commentStart = data.match(RE_COMMENT_START); var commentEnd = data.match(RE_COMMENT_END); if (commentStart && commentEnd) { var commentBlock = data.substring(commentStart['index'] + 4, commentEnd['index']); commentBlock = commentBlock.replace(/\*/g, ''); commentBlock = commentBlock.trim(); return commentBlock; } else { return null; } } function getSketchName() { var loc = window.location.pathname; var dir = loc.split('/'); return dir[dir.length-2]; } function linkMarkdown2Html(text) { // replace [link text](http://example.com) with ahref link return String(text).replace(/\[([^\]]*)\]\(([^(]*)\)/, '<a target="_blank" href="$2">$1</a>'); } function createHelp(helpText) { var text = helpText.split('\n'); var lines = text.map(function (l) { return linkMarkdown2Html(l).trim(); }); var htmlString = [ '<div style="display: none;">', '<div id="help-content">', getSketchName(), lines.join('\n'), '\n', '</div>', ' </div>', ].join('\n'); document.title = getSketchName(); $('body').append($.parseHTML(htmlString)); $('#help').tooltipster({ theme: 'tooltipster-noir', animation: 'fade', animationDuration: 100, distance: '10', trigger: 'click', interactive: true }); } })($, window, document); <|start_filename|>01_P/P_2_1_5_04/sketch.js<|end_filename|> // P_2_1_5_04 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Drawing tool for creating moire effect compositions using * smooth path of any length, width, smoothness and colour. * * MOUSE * mouse : click and drag to draw moire pattern path * * KEYS * 1 : set color to red * 2 : set color to green * 3 : set color to blue * 4 : set color to black * arrow right : increase smoothness * arrow left : decrease smoothness * arrow up : increase rectangle width * arrow down : decrease rectangle width * s : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) */ 'use strict'; var shapes = []; var density = 2.5; var shapeHeight = 64; var shapeColor; var smoothness = 0; var newShape; function setup() { createCanvas(800, 800); noFill(); shapeColor = color(0); } function draw() { background(255); shapes.forEach(function(shape) { shape.draw(); }); if (newShape) { newShape.h = shapeHeight; newShape.c = shapeColor; newShape.addPos(mouseX, mouseY); newShape.draw(); } } function Shape(h, c) { this.shapePath = []; this.h = h; this.c = c; Shape.prototype.addPos = function(x, y) { var newPos = createVector(x, y); var lastPos = this.getLastPos(); if ( this.shapePath.length == 0 || lastPos && p5.Vector.dist(newPos, lastPos) > smoothness ) { this.shapePath.push(newPos); } }; Shape.prototype.getLastPos = function() { return this.shapePath[this.shapePath.length - 1]; }; Shape.prototype.draw = function() { stroke(this.c); for (var i = -this.h / 2; i < this.h / 2; i += density) { beginShape(); this.shapePath.forEach(function(pos, index, shapePath) { var previousPos = shapePath[index - 1]; if (previousPos) { var a = atan2(previousPos.y - pos.y, previousPos.x - pos.x); var offsetPos = p5.Vector.fromAngle(a); offsetPos.add(0, i); offsetPos.rotate(a); offsetPos.add(pos); curveVertex(offsetPos.x, offsetPos.y); } }); endShape(); } }; } function mousePressed() { newShape = new Shape(shapeHeight, shapeColor); newShape.addPos(mouseX, mouseY); } function mouseReleased() { shapes.push(newShape); newShape = undefined; } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') shapeColor = color(255, 0, 0); if (key == '2') shapeColor = color(0, 255, 0); if (key == '3') shapeColor = color(0, 0, 255); if (key == '4') shapeColor = color(0); if (key == ' ') { shapes = []; redraw(); } if (keyCode == RIGHT_ARROW) smoothness += density; if (keyCode == LEFT_ARROW) smoothness -= density; if (keyCode == UP_ARROW) shapeHeight += density; if (keyCode == DOWN_ARROW) shapeHeight -= density; } <|start_filename|>01_P/P_4_2_2_02/sketch.js<|end_filename|> // P_4_2_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * simple timelapse camera, after each intervalTime a picture is saved. * */ 'use strict'; var cam; // intervalTime in sec., here 30 seconds var intervalTime = 30; var secondsSinceStart = 0; var startTime = gd.timestamp(); var counter = 0; var doSave = true; var streamReady = false; function setup() { createCanvas(640, 480); cam = createCapture(VIDEO, function() { streamReady = true; }); cam.hide(); noStroke(); } function draw() { if (streamReady) { image(cam, 0, 0, width, width * cam.height / cam.width); secondsSinceStart = millis() / 1000; var interval = int(secondsSinceStart % intervalTime); if (interval == 0 && doSave == true) { var saveFileName = startTime + '-' + nf(counter, 5, 0); saveCanvas(saveFileName, 'png'); doSave = false; counter++; } else if (interval != 0) { doSave = true; } // visualize the time to the next shot fill(random(0, 255), random(0, 255), random(0, 255)); rect(map(interval, 0, intervalTime, 0, width), 0, 5, 5); } } <|start_filename|>01_P/P_3_1_3_03/sketch.js<|end_filename|> // P_3_1_3_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * analysing and sorting the letters of a text * drawing the letters frequency with lines and ellipses * * MOUSE * position x : random angle * position y : line length, size of ellipses, tracking * * KEYS * 1 : toggle alpha mode * 2 : toggle drawing of lines * 3 : toggle drawing of ellipses * 4 : toggle drawing of text * s : save png */ 'use strict'; var joinedText; var charSet; var counters = []; var posX; var posY; var tracking = 29; var actRandomSeed = 0; var drawAlpha = true; var drawLines = true; var drawEllipses = true; var drawText = false; function preload() { joinedText = loadStrings('data/faust_short.txt'); } function setup() { createCanvas(1400, windowHeight); colorMode(HSB, 360, 100, 100, 100); textFont('monospace', 20); noStroke(); joinedText = joinedText.join(joinedText, ' '); charSet = getUniqCharacters(); for (var i = 0; i < charSet.length; i++) { counters[i] = 0; } countCharacters(); } function draw() { background(360); posX = 80; posY = 300; randomSeed(actRandomSeed); // go through all characters in the text to draw them for (var i = 0; i < joinedText.length; i++) { // again, find the index of the current letter in the character set var upperCaseChar = joinedText.charAt(i).toUpperCase(); var index = charSet.indexOf(upperCaseChar); if (index < 0) continue; // calculate parameters var charAlpha = 100; if (drawAlpha) { charAlpha = counters[index]; } var my = map(mouseY, 50, height - 50, 0, 1); my = constrain(my, 0, 1); var charSize = counters[index] * my * 3; var mx = map(mouseX, 50, width - 50, 0, 1); mx = constrain(mx, 0, 1); var lineLength = charSize; var lineAngle = random(-PI, PI) * mx - HALF_PI; var newPosX = lineLength * cos(lineAngle); var newPosY = lineLength * sin(lineAngle); // draw elements push(); translate(posX, posY); stroke(273, 73, 51, charAlpha); if (drawLines) { line(0, 0, newPosX, newPosY); } noStroke(); fill(52, 100, 71, charAlpha); if (drawEllipses) { ellipse(0, 0, charSize / 10, charSize / 10); } if (drawText) { fill(0, charAlpha); text(joinedText.charAt(i), newPosX, newPosY); } pop(); posX += textWidth(joinedText.charAt(i)); if (posX >= width - 200 && upperCaseChar == ' ') { posY += int(tracking * my + 30); posX = 80; } } } function getUniqCharacters() { var charsArray = joinedText.toUpperCase().split(''); var uniqCharsArray = charsArray.filter(function(char, index) { return charsArray.indexOf(char) == index; }).sort(); return uniqCharsArray.join(''); } function countCharacters() { for (var i = 0; i < joinedText.length; i++) { // get one character from the text and turn it to uppercase var index = charSet.indexOf(joinedText.charAt(i).toUpperCase()); // increacre the respective counter if (index >= 0) counters[index]++; } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') drawAlpha = !drawAlpha; if (key == '2') drawLines = !drawLines; if (key == '3') drawEllipses = !drawEllipses; if (key == '4') drawText = !drawText; } <|start_filename|>02_M/M_1_3_02/sketch.js<|end_filename|> // M_1_3_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * creates a texture based on random values * * MOUSE * click : new noise line * * KEYS * s : save png */ 'use strict'; var sketch = function(p) { var actRandomSeed = 0; p.setup = function() { p.createCanvas(512,512); }; p.draw = function() { p.background(0); p.randomSeed(actRandomSeed); for (var x = 0; x < p.width; x++) { for (var y = 0; y < p.height; y++) { p.set(x, y, p.random(255)); } } p.updatePixels(); }; p.mousePressed = function() { actRandomSeed = p.random(100000); }; p.keyReleased = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); }; }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_1_2_3_02/sketch.js<|end_filename|> // P_1_2_3_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * generates a specific color palette and some random "rect-tilings" * * MOUSE * left click : new composition * * KEYS * s : save png * c : save color palette */ 'use strict'; var colorCount = 20; var hueValues = []; var saturationValues = []; var brightnessValues = []; var actRandomSeed = 0; function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); noStroke(); } function draw() { noLoop(); randomSeed(actRandomSeed); // ------ colors ------ // create palette for (var i = 0; i < colorCount; i++) { if (i % 2 == 0) { hueValues[i] = random(130, 220); saturationValues[i] = 100; brightnessValues[i] = random(15, 100); } else { hueValues[i] = 195; saturationValues[i] = random(20, 100); brightnessValues[i] = 100; } } // ------ area tiling ------ // count tiles var counter = 0; // row count and row height var rowCount = int(random(5, 30)); var rowHeight = height / rowCount; // seperate each line in parts for (var i = rowCount; i >= 0; i--) { // how many fragments var partCount = i + 1; var parts = []; for (var ii = 0; ii < partCount; ii++) { // sub fragments or not? if (random() < 0.075) { // take care of big values var fragments = int(random(2, 20)); partCount = partCount + fragments; for (var iii = 0; iii < fragments; iii++) { parts.push(random(2)); } } else { parts.push(random(2, 20)); } } // add all subparts var sumPartsTotal = 0; for (var ii = 0; ii < partCount; ii++) { sumPartsTotal += parts[ii]; } // draw rects var sumPartsNow = 0; for (var ii = 0; ii < parts.length; ii++) { sumPartsNow += parts[ii]; var x = map(sumPartsNow, 0, sumPartsTotal, 0, width); var y = rowHeight * i; var w = -map(parts[ii], 0, sumPartsTotal, 0, width); var h = rowHeight; var index = counter % colorCount; var col = color(hueValues[index], saturationValues[index], brightnessValues[index]); fill(col); rect(x, y, w, h); counter++; } } } function mouseReleased() { actRandomSeed = random(100000); loop(); } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'c' || key == 'C') { // -- save an ase file (adobe swatch export) -- var colors = []; for (var i = 0; i < hueValues.length; i++) { colors.push(color(hueValues[i], saturationValues[i], brightnessValues[i])); } writeFile([gd.ase.encode(colors)], gd.timestamp(), 'ase'); } } <|start_filename|>01_P/P_3_2_2_01/sketch.js<|end_filename|> // P_3_2_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * fontgenerator with dynamic elements * * MOUSE * position x : curve rotation * position y : curve height * * KEYS * a-z : text input (keyboard) * del, backspace : remove last letter * alt : toggle fill style * ctrl : save png */ var textTyped = '<NAME>'; var font; var filled = false; function setup() { createCanvas(windowWidth, windowHeight); noLoop(); opentype.load('data/FreeSans.otf', function(err, f) { if (err) { print(err); } else { font = f; loop(); } }); } function draw() { if (!font) return; background(255); if (filled) { noStroke(); fill(0); } else { noFill(); stroke(0); strokeWeight(2); } // margin border translate(20, 260); if (textTyped.length > 0) { // get a path from OpenType.js var fontPath = font.getPath(textTyped, 0, 0, 200); // convert it to a g.Path object var path = new g.Path(fontPath.commands); // resample it with equidistant points path = g.resampleByLength(path, 11); // path = g.resampleByAmount(path, 500); // map mouse axis var addToAngle = map(mouseX, 0, width, -PI, PI); var curveHeight = map(mouseY, 0, height, 0.1, 2); for (var i = 0; i < path.commands.length - 1; i++) { var pnt0 = path.commands[i]; var pnt1 = path.commands[i + 1]; var d = dist(pnt0.x, pnt0.y, pnt1.x, pnt1.y); // create a gap between each letter if (d > 20) continue; // alternate in every step from -1 to 1 var stepper = map(i % 2, 0, 1, -1, 1); var angle = atan2(pnt1.y - pnt0.y, pnt1.x - pnt0.x); angle = angle + addToAngle; var cx = pnt0.x + cos(angle * stepper) * d * 4 * curveHeight; var cy = pnt0.y + sin(angle * stepper) * d * 3 * curveHeight; bezier(pnt0.x, pnt0.y, cx, cy, cx, cy, pnt1.x, pnt1.y); } } } function keyReleased() { // export png if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); if (keyCode == ALT) filled = !filled; } function keyPressed() { if (keyCode == DELETE || keyCode == BACKSPACE) { if (textTyped.length > 0) { textTyped = textTyped.substring(0, textTyped.length - 1); } } } function keyTyped() { if (keyCode >= 32) { textTyped += key; } } <|start_filename|>01_P/P_3_1_3_01/sketch.js<|end_filename|> // P_3_1_3_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * analysing and sorting the letters of a text * changing the letters alpha value in relation to frequency * * MOUSE * position x : interpolate between normal text and sorted position * * KEYS * a : toggle alpha mode * s : save png */ 'use strict'; var joinedText; var alphabet = 'ABCDEFGHIJKLMNORSTUVWYZÄÖÜß,.;!? '; var counters = []; var posX; var posY; var drawAlpha = true; function preload() { joinedText = loadStrings('data/faust_kurz.txt'); } function setup() { createCanvas(620, windowHeight); noStroke(); textFont('monospace', 18); joinedText = joinedText.join(' '); // use the following command, to collect all characters in the text automatically // alphabet = getUniqCharacters(); for (var i = 0; i < alphabet.length; i++) { counters[i] = 0; } countCharacters(); } function draw() { background(255); posX = 20; posY = 40; // go through all characters in the text to draw them for (var i = 0; i < joinedText.length; i++) { // again, find the index of the current letter in the character set var upperCaseChar = joinedText.charAt(i).toUpperCase(); var index = alphabet.indexOf(upperCaseChar); if (index < 0) continue; if (drawAlpha) { fill(87, 35, 129, counters[index] * 3); } else { fill(87, 35, 129); } var sortY = index * 20 + 40; var m = map(mouseX, 50, width - 50, 0, 1); m = constrain(m, 0, 1); var interY = lerp(posY, sortY, m); text(joinedText.charAt(i), posX, interY); posX += textWidth(joinedText.charAt(i)); if (posX >= width - 200 && upperCaseChar == ' ') { posY += 30; posX = 20; } } } function countCharacters() { for (var i = 0; i < joinedText.length; i++) { // get one character from the text and turn it to uppercase var c = joinedText.charAt(i); var upperCaseChar = c.toUpperCase(); var index = alphabet.indexOf(upperCaseChar); // increase the respective counter if (index >= 0) counters[index]++; } } function getUniqCharacters() { var charsArray = joinedText.toUpperCase().split(''); var uniqCharsArray = charsArray.filter(function(char, index) { return charsArray.indexOf(char) == index; }).sort(); return uniqCharsArray.join(''); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'a' || key == 'A') drawAlpha = !drawAlpha; } <|start_filename|>03_A/Cover_Barcode/sketch.js<|end_filename|> // Cover_Barcode // // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * KEYS * s : save png */ 'use strict'; var colorPoints = []; var ribbon; // chose 8 for print quality (caution: very slow) var mmToPx = 3; // these are in mm: var coverWidth = 400; var coverHeight = 400; var barcodeNumbers = [9, 9, 7, 8, 3, 8, 7, 4, 3, 9, 9, 0, 2, 9]; function setup() { createCanvas(coverWidth * mmToPx, coverHeight * mmToPx); // create colorPoints for (var i = 0; i < barcodeNumbers.length; i++) { var n = barcodeNumbers[i]; var r = imageColors[n].r; var g = imageColors[n].g; var b = imageColors[n].b; var a = imageColors[n].a * map(i, 0, barcodeNumbers.length - 1, 1, 0.05); var col = color(r, g, b, a); colorPoints.push(new ColorPoint(n, col, 1)); } // Barcode ribbon = new Ribbon(colorPoints, 150, { n: barcodeInfo.length - 1, step: 0.15, damp: 0.02, minW: 10, maxW: 50 }); } function draw() { // background(255); translate(150 * mmToPx, 50 * mmToPx); rotate(radians(180)); scale(mmToPx); ribbon.draw(); noLoop(); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>01_P/P_2_1_2_03/sketch.js<|end_filename|> // P_2_1_2_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing size of circles in a rad grid depending the mouseposition * * MOUSE * position x/y : module size and offset z * * KEYS * s : save png */ 'use strict'; var tileCount = 20; var moduleColor; var moduleAlpha = 180; var maxDistance = 500; function setup() { createCanvas(600, 600); noFill(); strokeWeight(3); moduleColor = color(0, 0, 0, moduleAlpha); } function draw() { clear(); stroke(moduleColor); for (var gridY = 0; gridY < width; gridY += 25) { for (var gridX = 0; gridX < height; gridX += 25) { var diameter = dist(mouseX, mouseY, gridX, gridY); diameter = diameter / maxDistance * 40; push(); translate(gridX, gridY, diameter * 5); rect(0, 0, diameter, diameter); // also nice: ellipse(...) pop(); } } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>01_P/P_1_2_2_01/sketch.js<|end_filename|> // P_1_2_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * extract and sort the color palette of an image * * MOUSE * position x : resolution * * KEYS * 1-4 : load different images * 5 : no color sorting * 6 : sort colors on hue * 7 : sort colors on saturation * 8 : sort colors on brightness * 9 : sort colors on greyscale (luminance) * s : save png * c : save color palette */ 'use strict'; var img; var colors = []; var sortMode = null; function preload() { loadImage('data/pic1.jpg', setImage); } function setup() { createCanvas(600, 600); noCursor(); noStroke(); } function draw() { var tileCount = floor(width / max(mouseX, 5)); var rectSize = width / tileCount; img.loadPixels(); colors = []; for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var px = int(gridX * rectSize); var py = int(gridY * rectSize); var i = (py * img.width + px) * 4; var c = color(img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]); colors.push(c); } } gd.sortColors(colors, sortMode); var i = 0; for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { fill(colors[i]); rect(gridX * rectSize, gridY * rectSize, rectSize, rectSize); i++; } } } function keyReleased() { if (key == 'c' || key == 'C') writeFile([gd.ase.encode(colors)], gd.timestamp(), 'ase'); if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') loadImage('data/pic1.jpg', setImage); if (key == '2') loadImage('data/pic2.jpg', setImage); if (key == '3') loadImage('data/pic3.jpg', setImage); if (key == '4') loadImage('data/pic4.jpg', setImage); if (key == '5') sortMode = null; if (key == '6') sortMode = gd.HUE; if (key == '7') sortMode = gd.SATURATION; if (key == '8') sortMode = gd.BRIGHTNESS; if (key == '9') sortMode = gd.GRAYSCALE; } function setImage(loadedImageFile) { img = loadedImageFile; } <|start_filename|>03_A/Cover_Barcode/lib/imageColors.js<|end_filename|> imageColors = [{ 'n': 0, 'r': 214, 'g': 0, 'b': 100, 'a': 40 }, { 'n': 1, 'r': 196, 'g': 39, 'b': 0, 'a': 90 }, { 'n': 2, 'r': 0, 'g': 85, 'b': 150, 'a': 20 }, { 'n': 3, 'r': 100, 'g': 207, 'b': 148, 'a': 50 }, { 'n': 4, 'r': 150, 'g': 10, 'b': 120, 'a': 40 }, { 'n': 5, 'r': 60, 'g': 140, 'b': 120, 'a': 30 }, { 'n': 6, 'r': 170, 'g': 70, 'b': 140, 'a': 10 }, { 'n': 7, 'r': 80, 'g': 185, 'b': 185, 'a': 20 }, { 'n': 8, 'r': 255, 'g': 176, 'b': 0, 'a': 30 }, { 'n': 9, 'r': 100, 'g': 120, 'b': 160, 'a': 100 } ]; <|start_filename|>01_P/P_4_0_01/sketch.js<|end_filename|> // P_4_0_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw a grid of streched copies of an image * * MOUSE * position x : tile count horizontally * position y : tile count vertically * * KEYS * s : save png */ 'use strict'; var img; function preload() { img = loadImage('data/image.jpg'); } function setup() { createCanvas(650, 450); } function draw() { var tileCountX = mouseX / 3 + 1; var tileCountY = mouseY / 3 + 1; var stepX = width / tileCountX; var stepY = height / tileCountY; for (var gridY = 0; gridY < height; gridY += stepY) { for (var gridX = 0; gridX < width; gridX += stepX) { image(img, gridX, gridY, stepX, stepY); } } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>02_M/M_2_5_01/sketch.js<|end_filename|> // M_2_5_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw lissajous figures with all points connected * * KEYS * 1/2 : frequency x -/+ * 3/4 : frequency y -/+ * arrow left/right : phi -/+ * 7/8 : modulation frequency x -/+ * 9/0 : modulation frequency y -/+ * s : save png */ 'use strict'; var sketch = function(p) { var pointCount = 1000; var lissajousPoints = []; var freqX = 4; var freqY = 7; var phi = 15; var modFreqX = 3; var modFreqY = 2; var lineWeight = 0.1; var lineColor; var lineAlpha = 50; var connectionRadius = 100; var connectionRamp = 6; p.setup = function() { p.createCanvas(800,800); p.colorMode(p.RGB, 255, 255, 255, 100); p.noFill(); lineColor = p.color(0, 50); calculateLissajousPoints(); drawLissajous(); }; function calculateLissajousPoints() { for (var i = 0; i <= pointCount; i++) { var angle = p.map(i, 0, pointCount, 0, p.TAU); var x = p.sin(angle * freqX + p.radians(phi)) * p.cos(angle * modFreqX); var y = p.sin(angle * freqY) * p.cos(angle * modFreqY); x *= p.width / 2 - 30; y *= p.height / 2 - 30; lissajousPoints[i] = p.createVector(x,y); } } function drawLissajous() { p.background(255); p.strokeWeight(lineWeight); p.push(); p.translate(p.width / 2, p.height / 2); for (var i1 = 0; i1 < pointCount; i1++) { for (var i2 = 0; i2 < i1; i2++) { var d = lissajousPoints[i1].dist(lissajousPoints[i2]); var a = p.pow(1 / (d / connectionRadius + 1), 6); if (d <= connectionRadius) { p.stroke(lineColor, a * lineAlpha); p.line( lissajousPoints[i1].x, lissajousPoints[i1].y, lissajousPoints[i2].x, lissajousPoints[i2].y ); } } } p.pop(); } p.keyPressed = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); if (p.key == '1') freqX--; if (p.key == '2') freqX++; freqX = p.max(freqX,1); if (p.key == '3') freqY--; if (p.key == '4') freqY++; freqY = p.max(freqY,1); if (p.keyCode == p.LEFT_ARROW) phi -= 15; if (p.keyCode == p.RIGHT_ARROW) phi += 15; if (p.key == '7') modFreqX--; if (p.key == '8') modFreqX++; modFreqX = p.max(modFreqX,1); if (p.key == '9') modFreqY--; if (p.key == '0') modFreqY++; modFreqY = p.max(modFreqY,1); calculateLissajousPoints(); drawLissajous(); console.log('freqX: ' + freqX + ', freqY: ' + freqY + ', phi: ' + phi + ', modFreqX: ' + modFreqX + ', modFreqY: ' + modFreqY); }; }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_2_2_5_02/sketch.js<|end_filename|> // P_2_2_5_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * pack as many cirlces as possible together * * MOUSE * press + position x/y : move area of interest * * KEYS * 1 : show/hide circles * 2 : show/hide lines * 3 : show/hide svg modules * arrow up/down : resize area of interest * f : freeze process. on/off * s : save png */ 'use strict'; var circles = []; var minRadius = 3; var maxRadius = 50; // for mouse and up/down-arrow interaction var mouseRect = 15; var freeze = false; // svg vector import var module1; var module2; // style selector, hotkeys 1, 2, 3 var showCircle = false; var showLine = false; var showSVG = true; function preload() { module1 = loadImage('data/01.svg'); module2 = loadImage('data/02.svg'); } function setup() { createCanvas(windowWidth, windowHeight); noFill(); cursor(CROSS); ellipseMode(RADIUS); rectMode(RADIUS); imageMode(CENTER); } function draw() { background(255); // Choose a random or the current mouse position var newX = random(maxRadius, width - maxRadius); var newY = random(maxRadius, height - maxRadius); if (mouseIsPressed && mouseButton == LEFT) { newX = random(mouseX - mouseRect, mouseX + mouseRect); newY = random(mouseY - mouseRect, mouseY + mouseRect); } // Try to fit the largest possible circle at the current location without overlapping for (var newR = maxRadius; newR >= minRadius; newR--) { var intersection = circles.some(function(circle) { return dist(newX, newY, circle.x, circle.y) < circle.r + newR; }); if (!intersection) { circles.push(new Circle(newX, newY, newR)); break; } } // Draw all circles circles.forEach(function(circle) { if (showLine) { // Try to find an adjacent circle to the current one and draw a connecting line between the two var closestCircle = circles.find(function(otherCircle) { return dist(circle.x, circle.y, otherCircle.x, otherCircle.y) <= circle.r + otherCircle.r + 1; }); if (closestCircle) { stroke(100, 230, 100); strokeWeight(0.75); line(circle.x, circle.y, closestCircle.x, closestCircle.y); } } // Draw the circle itself. circle.draw(); }); // Visualise the random range of the current mouse position if (mouseIsPressed && mouseButton == LEFT) { stroke(100, 230, 100); strokeWeight(2); rect(mouseX, mouseY, mouseRect, mouseRect); } } function Circle(x, y, r) { this.x = x; this.y = y; this.r = r; this.rotation = random(TAU); Circle.prototype.draw = function() { if (showSVG) { push(); translate(this.x, this.y); rotate(this.rotation); if (this.r == maxRadius) { image(module1, 0, 0, this.r * 2, this.r * 2); } else { image(module2, 0, 0, this.r * 2, this.r * 2); } pop(); } if (showCircle) { stroke(0); strokeWeight(1.5); ellipse(this.x, this.y, this.r); } }; } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == UP_ARROW) mouseRect += 4; if (keyCode == DOWN_ARROW) mouseRect -= 4; // toggle freeze drawing if (key == 'f' || key == 'F') { freeze = !freeze; if (freeze) { noLoop(); } else { loop(); } } // toggle style if (key == '1') showCircle = !showCircle; if (key == '2') showLine = !showLine; if (key == '3') showSVG = !showSVG; } <|start_filename|>01_P/P_4_2_3_03/gui.js<|end_filename|> function createGUI() { gui = QuickSettings.create(10, 10, document.title); gui.addFileChooser('video', 'video file', 'video/*', selectVideoFile); gui.addFileChooser('subtitles', 'subtitle file', undefined, selectSubtitleFile); gui.addText('searchQuery', searchQuery, setSearchQuery); gui.addButton('generateMontage', generateMontage); gui.addProgressBar('searchResults', searchResults.length, 0, 'numbers'); gui.addProgressBar('video time', video.duration(), video.time(), 'numbers'); gui.addHTML('time', '00:00:00'); gui.addHTML('dialog', ''); gui.addButton('togglePlayback', togglePlayback); gui.addBoolean('tileMode', tileMode, setTileMode); video.elt.ontimeupdate = updateGUI; } function updateGUI() { gui.setProgressMax('searchResults', searchResults.length); gui.setValue('searchResults', searchResults.indexOf(currentResult) + 1); gui.setProgressMax('video time', round(video.duration())); gui.setValue('video time', round(video.time())); subtitles.forEach(function(subtitle) { if (video.time() > subtitle.startTime && video.time() < subtitle.endTime) { gui.setValue('time', '<code>' + subtitle.startTimeStamp + '</code>'); gui.setValue('dialog', '<code>' + subtitle.dialog + '</code>'); } }); } function setSearchQuery(newSearchQuery) { searchQuery = newSearchQuery; } function selectVideoFile(file) { videoSrc = URL.createObjectURL(file); reset(); } function selectSubtitleFile(file) { subtitleSrc = URL.createObjectURL(file); reset(); } function setTileMode() { tileMode = !tileMode; reset(); } function reset() { gui.destroy(); remove(); new p5; } <|start_filename|>01_P/P_2_1_1_01/sketch.js<|end_filename|> // P_2_1_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing strokeweight and strokecaps on diagonals in a grid * * MOUSE * position x : left diagonal strokeweight * position y : right diagonal strokeweight * left click : new random layout * * KEYS * 1 : round strokecap * 2 : square strokecap * 3 : project strokecap * s : save png */ 'use strict'; var tileCount = 20; var actRandomSeed = 0; var actStrokeCap; function setup() { createCanvas(600, 600); actStrokeCap = ROUND; } function draw() { clear(); strokeCap(actStrokeCap); randomSeed(actRandomSeed); for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = width / tileCount * gridX; var posY = height / tileCount * gridY; var toggle = int(random(0, 2)); if (toggle == 0) { strokeWeight(mouseX / 20); line(posX, posY, posX + width / tileCount, posY + height / tileCount); } if (toggle == 1) { strokeWeight(mouseY / 20); line(posX, posY + width / tileCount, posX + height / tileCount, posY); } } } } function mousePressed() { actRandomSeed = random(100000); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') actStrokeCap = ROUND; if (key == '2') actStrokeCap = SQUARE; if (key == '3') actStrokeCap = PROJECT; } <|start_filename|>01_P/P_2_1_1_03/sketch.js<|end_filename|> // P_2_1_1_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing number, color and strokeweight on diagonals in a grid * * MOUSE * position x : diagonal strokeweight * position y : number diagonals * left click : new random layout * * KEYS * s : save png * 1 : color left diagonal * 2 : color right diagonal * 3 : switch transparency left diagonal on/off * 4 : switch transparency right diagonal on/off * 0 : default */ 'use strict'; var tileCount = 1; var actRandomSeed = 0; var colorLeft; var colorRight; var alphaLeft = 0; var alphaRight = 100; var transparentLeft = false; var transparentRight = false; function setup() { createCanvas(600, 600); colorMode(HSB, 360, 100, 100, 100); colorRight = color(0, 0, 0, alphaRight); colorLeft = color(323, 100, 77, alphaLeft); } function draw() { clear(); strokeWeight(mouseX / 15); randomSeed(actRandomSeed); tileCount = mouseY / 15; for (var gridY = 0; gridY < tileCount; gridY++) { for (var gridX = 0; gridX < tileCount; gridX++) { var posX = width / tileCount * gridX; var posY = height / tileCount * gridY; alphaLeft = transparentLeft ? gridY * 10 : 100; colorLeft = color(hue(colorLeft), saturation(colorLeft), brightness(colorLeft), alphaLeft); alphaRight = transparentRight ? 100 - gridY * 10 : 100; colorRight = color(hue(colorRight), saturation(colorRight), brightness(colorRight), alphaRight); var toggle = int(random(0, 2)); if (toggle == 0) { stroke(colorLeft); line(posX, posY, posX + (width / tileCount) / 2, posY + height / tileCount); line(posX + (width / tileCount) / 2, posY, posX + (width / tileCount), posY + height / tileCount); } if (toggle == 1) { stroke(colorRight); line(posX, posY + width / tileCount, posX + (height / tileCount) / 2, posY); line(posX + (height / tileCount) / 2, posY + width / tileCount, posX + (height / tileCount), posY); } } } } function mousePressed() { actRandomSeed = random(100000); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') { if (colorsEqual(colorLeft, color(273, 73, 51, alphaLeft))) { colorLeft = color(323, 100, 77, alphaLeft); } else { colorLeft = color(273, 73, 51, alphaLeft); } } if (key == '2') { if (colorsEqual(colorRight, color(0, 0, 0, alphaRight))) { colorRight = color(192, 100, 64, alphaRight); } else { colorRight = color(0, 0, 0, alphaRight); } } if (key == '3') { transparentLeft = !transparentLeft; } if (key == '4') { transparentRight = !transparentRight; } if (key == '0') { transparentLeft = false; transparentRight = false; colorLeft = color(323, 100, 77, alphaLeft); colorRight = color(0, 0, 0, alphaRight); } } function colorsEqual(col1, col2) { return col1.toString() == col2.toString(); } <|start_filename|>01_P/P_2_1_5_02/sketch.js<|end_filename|> // P_2_1_5_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Place stacked circles of randomised heights at the mouse position * to create a moire effect drawing * * MOUSE * mouse : place circle * * KEYS * s : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) */ 'use strict'; var shapes = []; var minRadius = 5; var maxRadius = 250; var density = 5; function setup() { createCanvas(800, 800); noFill(); shapes.push(new Shape(width / 2, height / 2, width)); } function draw() { background(255); shapes.forEach(function(shape) { shape.draw(); }); } function Shape(x, y, r) { this.x = x; this.y = y; this.r = r; Shape.prototype.draw = function() { for (var i = 0; i < this.r; i += density) { ellipse(this.x, this.y, i); } }; } function mouseReleased() { shapes.push(new Shape(mouseX, mouseY, random(minRadius, maxRadius))); } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>01_P/P_2_2_3_02/sketch.js<|end_filename|> // P_2_2_3_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * form mophing process by connected random agents * two forms: circle and line * * MOUSE * click : start a new circe * position x/y : direction and speed of floating * * KEYS * 1-2 : fill styles * 3-4 : form styles circle/line * arrow up/down : step size +/- * f : freeze. loop on/off * Delete/Backspace : clear display * s : save png */ 'use strict'; var formResolution = 15; var stepSize = 2; var distortionFactor = 1; var initRadius = 150; var centerX; var centerY; var x = []; var y = []; var filled = false; var freeze = false; var drawMode = 1; function setup() { createCanvas(windowWidth, windowHeight); // init shape centerX = width / 2; centerY = height / 2; var angle = radians(360 / formResolution); for (var i = 0; i < formResolution; i++) { x.push(cos(angle * i) * initRadius); y.push(sin(angle * i) * initRadius); } stroke(0, 50); strokeWeight(0.75); background(255); } function draw() { // floating towards mouse position centerX += (mouseX - centerX) * 0.01; centerY += (mouseY - centerY) * 0.01; // calculate new points for (var i = 0; i < formResolution; i++) { x[i] += random(-stepSize, stepSize); y[i] += random(-stepSize, stepSize); } if (filled) { fill(random(255)); } else { noFill(); } switch (drawMode) { case 1: // circle beginShape(); // start controlpoint curveVertex(x[formResolution - 1] + centerX, y[formResolution - 1] + centerY); // only these points are drawn for (var i = 0; i < formResolution; i++) { curveVertex(x[i] + centerX, y[i] + centerY); } curveVertex(x[0] + centerX, y[0] + centerY); // end controlpoint curveVertex(x[1] + centerX, y[1] + centerY); endShape(); break; case 2: // line beginShape(); // start controlpoint curveVertex(x[0] + centerX, y[0] + centerY); // only these points are drawn for (var i = 0; i < formResolution; i++) { curveVertex(x[i] + centerX, y[i] + centerY); } // end controlpoint curveVertex(x[formResolution - 1] + centerX, y[formResolution - 1] + centerY); endShape(); break; } } function mousePressed() { // init shape on mouse position centerX = mouseX; centerY = mouseY; switch (drawMode) { case 1: // circle var angle = radians(360 / formResolution); var radius = initRadius * random(0.5, 1); for (var i = 0; i < formResolution; i++) { x[i] = cos(angle * i) * radius; y[i] = sin(angle * i) * radius; } break; case 2: // line var radius = initRadius * random(0.5, 5); var angle = random(PI); var x1 = cos(angle) * radius; var y1 = sin(angle) * radius; var x2 = cos(angle - PI) * radius; var y2 = sin(angle - PI) * radius; for (var i = 0; i < formResolution; i++) { x[i] = lerp(x1, x2, i / formResolution); y[i] = lerp(y1, y2, i / formResolution); } break; } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) background(255); if (key == '1') filled = false; if (key == '2') filled = true; if (key == '3') drawMode = 1; if (key == '4') drawMode = 2; if (keyCode == UP_ARROW) stepSize++; if (keyCode == DOWN_ARROW) stepSize--; stepSize = max(stepSize, 1); // pause/play draw loop if (key == 'f' || key == 'F') freeze = !freeze; if (freeze) { noLoop(); } else { loop(); } } <|start_filename|>01_P/P_4_1_2_01/sketch.js<|end_filename|> // P_4_1_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * image feedback process. * * KEYS * del, backspace : clear screen * s : save png */ 'use strict'; var img; function preload() { img = loadImage('data/pic.png'); } function setup() { createCanvas(1024, 780); image(img, 0, 100); } function draw() { var x1 = floor(random(width)); var y1 = 50; var x2 = round(x1 + random(-7, 7)); var y2 = round(y1 + random(-5, 5)); var w = floor(random(10, 40)); var h = height - 100; set(x2, y2, get(x1, y1, w, h)); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) { clear(); image(img, 0, 100); } } <|start_filename|>01_P/P_3_1_2_02/sketch.js<|end_filename|> // P_3_1_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * typewriter. uses input (text) as blueprint for a visual composition. * * MOUSE * click + drag : move canvas * * KEYS * a-z : text input (keyboard) * ,.!? : curves * space : random straight / small curve * :+-xz : icons * o : station with the last 7 typed letters as name * a u : stop * del, backspace : remove last letter * arrow up : zoom canvas + * arrow down : zoom canvas - * alt : new random layout * ctrl : save png */ 'use strict'; var textTyped = 'Was hier folgt ist Tet! So asnt, und mag. Ich mag Tet sehr.'; var font; var shapeSpace; var shapeSpace2; var shapePeriod; var shapeComma; var shapeQuestionmark; var shapeExclamationmark; var shapeReturn; var icon1; var icon2; var icon3; var icon4; var icon5; var centerX; var centerY; var offsetX; var offsetY; var zoom; var actRandomSeed; var palette = [ [253, 195, 0], [0, 0, 0], [0, 158, 224], [99, 33, 129], [121, 156, 19], [226, 0, 26], [224, 134, 178] ]; var actColorIndex = 0; function preload() { font = loadFont('data/miso-bold.ttf'); shapeSpace = loadImage('data/space.svg'); shapeSpace2 = loadImage('data/space2.svg'); shapePeriod = loadImage('data/period.svg'); shapeComma = loadImage('data/comma.svg'); shapeExclamationmark = loadImage('data/exclamationmark.svg'); shapeQuestionmark = loadImage('data/questionmark.svg'); shapeReturn = loadImage('data/return.svg'); icon1 = loadImage('data/icon1.svg'); icon2 = loadImage('data/icon2.svg'); icon3 = loadImage('data/icon3.svg'); icon4 = loadImage('data/icon4.svg'); icon5 = loadImage('data/icon5.svg'); } function setup() { createCanvas(windowWidth, windowHeight); centerX = width / 2; centerY = height / 2; offsetX = 0; offsetY = 0; zoom = 0.75; actRandomSeed = 6; cursor(HAND); textFont(font, 25); textAlign(LEFT, BASELINE); noStroke(); fill(0); } function windowResized() { resizeCanvas(windowWidth, windowHeight); } function draw() { background(255); if (mouseIsPressed && mouseButton == LEFT) { centerX = mouseX - offsetX; centerY = mouseY - offsetY; } // allways produce the same sequence of random numbers randomSeed(actRandomSeed); translate(centerX, centerY); scale(zoom); push(); actColorIndex = 0; fill(palette[actColorIndex][0], palette[actColorIndex][1], palette[actColorIndex][2]); rect(0, -25, 10, 35); for (var i = 0; i < textTyped.length; i++) { var letter = textTyped.charAt(i); var letterWidth = textWidth(letter); // ------ letter rule table ------ switch (letter) { case ' ': // space var dir = floor(random(5)); if (dir == 0) { image(shapeSpace, 0, -15); translate(2, 0); rotate(QUARTER_PI); } if (dir == 1) { image(shapeSpace2, 0, -15); translate(13, -5); rotate(-QUARTER_PI); } break; case ',': image(shapeComma, 0, -15); translate(33, 15); rotate(QUARTER_PI); break; case '.': image(shapePeriod, 0, -56); translate(56, -56); rotate(-HALF_PI); break; case '!': image(shapeExclamationmark, 0, -30); translate(43, -18); rotate(-QUARTER_PI); break; case '?': image(shapeQuestionmark, 0, -30); translate(43, -18); rotate(-QUARTER_PI); break; case '\n': // start a new line at a random position near the center rect(0, -25, 10, 35); pop(); push(); translate(random(-300, 300), random(-300, 300)); rotate(floor(random(8)) * QUARTER_PI); actColorIndex = (actColorIndex + 1) % palette.length; fill(palette[actColorIndex][0], palette[actColorIndex][1], palette[actColorIndex][2]); rect(0, -25, 10, 35); break; case 'o': // Station big rect(0, -15, letterWidth + 1, 15); push(); fill(0); var station = textTyped.substring(i - 10, i - 1); station = station.toLowerCase(); station = station.replace(/\s+/g, ''); station = station.substring(0, 1).toUpperCase() + station.substring(1, station.length - 1); text(station, -10, 40); ellipse(-5, -7, 33, 33); fill(255); ellipse(-5, -7, 25, 25); pop(); translate(letterWidth, 0); break; case 'a': // Station small left rect(0, 0 - 15, letterWidth + 1, 25); rect(0, 0 - 15, letterWidth + 1, 15); translate(letterWidth, 0); break; case 'u': // Station small right rect(0, 0 - 25, letterWidth + 1, 25); rect(0, 0 - 15, letterWidth + 1, 15); translate(letterWidth, 0); break; case ':': // icon image(icon1, 0, -60, 30, 30); break; case '+': // icon image(icon2, 0, -60, 35, 30); break; case '-': // icon image(icon3, 0, -60, 30, 30); break; case 'x': // icon image(icon4, 0, -60, 30, 30); break; case 'z': // icon image(icon5, 0, -60, 30, 30); break; default: // all others rect(0, -15, letterWidth + 1, 15); translate(letterWidth, 0); } } // blink cursor after text fill(200, 30, 40); if (frameCount / 6 % 2 == 0) rect(0, 0, 15, 2); pop(); } function mousePressed() { offsetX = mouseX - centerX; offsetY = mouseY - centerY; } function keyReleased() { if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); if (keyCode == ALT) actRandomSeed++; } function keyPressed() { switch (keyCode) { case DELETE: case BACKSPACE: textTyped = textTyped.substring(0, textTyped.length - 1); print(textTyped); break; case ENTER: case RETURN: textTyped += '\n'; break; case UP_ARROW: zoom += 0.05; break; case DOWN_ARROW: zoom -= 0.05; break; } } function keyTyped() { if (keyCode >= 32) { textTyped += key; print(textTyped); } } <|start_filename|>01_P/P_4_3_1_02/sketch.js<|end_filename|> // P_4_3_1_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * pixel mapping. each pixel is translated into a new element (svg file). * take care to sort the svg file according to their greyscale value. * * KEYS * s : save png */ 'use strict'; var shapes; var img; function preload() { img = loadImage('data/pic.png'); shapes = []; shapes.push(loadImage('data/056.svg')); shapes.push(loadImage('data/076.svg')); shapes.push(loadImage('data/082.svg')); shapes.push(loadImage('data/096.svg')); shapes.push(loadImage('data/117.svg')); shapes.push(loadImage('data/148.svg')); shapes.push(loadImage('data/152.svg')); shapes.push(loadImage('data/157.svg')); shapes.push(loadImage('data/164.svg')); shapes.push(loadImage('data/166.svg')); shapes.push(loadImage('data/186.svg')); shapes.push(loadImage('data/198.svg')); shapes.push(loadImage('data/224.svg')); } function setup() { createCanvas(600, 900); image(img); } function draw() { background(255); for (var gridX = 0; gridX < img.width; gridX++) { for (var gridY = 0; gridY < img.height; gridY++) { // grid position + title size var titleWidth = 603 / img.width; var titleHeight = 873 / img.height; var posX = titleWidth * gridX; var posY = titleHeight * gridY; // get current color img.loadPixels(); var c = img.get(min(gridX, img.width - 1), gridY); // greyscale conversion var greyscale = round(red(c) * 0.222 + green(c) * 0.707 + blue(c) * 0.071); var gradientToIndex = round(map(greyscale, 0, 255, 0, shapes.length - 1)); image(shapes[gradientToIndex], posX, posY, titleWidth, titleHeight); } } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>03_A/Cover_Lines/lib/imageColors.js<|end_filename|> imageColors = [{ 'r': 153, 'g': 0, 'b': 158, 'a': 199 }, { 'r': 0, 'g': 75, 'b': 226, 'a': 26 }, { 'r': 144, 'g': 0, 'b': 0, 'a': 219 }, { 'r': 175, 'g': 0, 'b': 195, 'a': 98 }, { 'r': 144, 'g': 0, 'b': 0, 'a': 219 }, { 'r': 41, 'g': 186, 'b': 0, 'a': 219 }, { 'r': 41, 'g': 186, 'b': 0, 'a': 219 }, { 'r': 38, 'g': 0, 'b': 154, 'a': 211 }, { 'r': 235, 'g': 198, 'b': 0, 'a': 141 }, { 'r': 113, 'g': 0, 'b': 166, 'a': 135 }, { 'r': 0, 'g': 178, 'b': 175, 'a': 251 }, { 'r': 218, 'g': 200, 'b': 0, 'a': 224 }, { 'r': 0, 'g': 135, 'b': 200, 'a': 126 }, { 'r': 0, 'g': 67, 'b': 203, 'a': 15 }, { 'r': 0, 'g': 156, 'b': 183, 'a': 238 }, { 'r': 206, 'g': 93, 'b': 0, 'a': 63 }, { 'r': 0, 'g': 146, 'b': 178, 'a': 251 }, { 'r': 0, 'g': 226, 'b': 103, 'a': 98 }, { 'r': 0, 'g': 250, 'b': 205, 'a': 179 }, { 'r': 250, 'g': 0, 'b': 23, 'a': 171 }, { 'r': 209, 'g': 0, 'b': 65, 'a': 179 }, { 'r': 0, 'g': 191, 'b': 218, 'a': 174 }, { 'r': 245, 'g': 177, 'b': 0, 'a': 135 }, { 'r': 0, 'g': 113, 'b': 174, 'a': 231 }, { 'r': 0, 'g': 173, 'b': 192, 'a': 236 }, { 'r': 248, 'g': 197, 'b': 0, 'a': 191 }, { 'r': 0, 'g': 75, 'b': 226, 'a': 26 }, { 'r': 195, 'g': 0, 'b': 204, 'a': 114 }, { 'r': 128, 'g': 0, 'b': 183, 'a': 111 }, { 'r': 232, 'g': 215, 'b': 0, 'a': 195 }, { 'r': 0, 'g': 152, 'b': 228, 'a': 106 }, { 'r': 250, 'g': 25, 'b': 0, 'a': 172 }, { 'r': 214, 'g': 107, 'b': 0, 'a': 18 }, { 'r': 255, 'g': 0, 'b': 0, 'a': 2 }, { 'r': 255, 'g': 0, 'b': 0, 'a': 2 }, { 'r': 234, 'g': 89, 'b': 0, 'a': 37 }, { 'r': 0, 'g': 63, 'b': 207, 'a': 16 }, { 'r': 196, 'g': 19, 'b': 0, 'a': 13 }, { 'r': 207, 'g': 79, 'b': 0, 'a': 16 }, { 'r': 0, 'g': 234, 'b': 109, 'a': 239 }, { 'r': 47, 'g': 219, 'b': 0, 'a': 195 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 247, 'b': 118, 'a': 98 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 246, 'b': 112, 'a': 86 }, { 'r': 237, 'g': 47, 'b': 0, 'a': 42 }, { 'r': 225, 'g': 0, 'b': 0, 'a': 34 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 200, 'g': 80, 'b': 0, 'a': 50 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 207, 'g': 69, 'b': 0, 'a': 58 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 67, 'g': 254, 'b': 0, 'a': 15 }, { 'r': 0, 'g': 247, 'b': 123, 'a': 98 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 249, 'g': 222, 'b': 0, 'a': 147 }, { 'r': 0, 'g': 10, 'b': 254, 'a': 203 }, { 'r': 27, 'g': 255, 'b': 0, 'a': 223 }, { 'r': 0, 'g': 10, 'b': 254, 'a': 203 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 116, 'g': 251, 'b': 0, 'a': 227 }, { 'r': 255, 'g': 10, 'b': 0, 'a': 199 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 240, 'g': 0, 'b': 0, 'a': 50 }, { 'r': 179, 'g': 38, 'b': 0, 'a': 131 }, { 'r': 0, 'g': 128, 'b': 205, 'a': 159 }, { 'r': 245, 'g': 24, 'b': 0, 'a': 82 }, { 'r': 0, 'g': 52, 'b': 211, 'a': 57 }, { 'r': 0, 'g': 121, 'b': 245, 'a': 205 }, { 'r': 0, 'g': 190, 'b': 246, 'a': 220 }, { 'r': 77, 'g': 0, 'b': 169, 'a': 250 }, { 'r': 241, 'g': 0, 'b': 225, 'a': 237 }, { 'r': 0, 'g': 188, 'b': 188, 'a': 26 }, { 'r': 0, 'g': 250, 'b': 192, 'a': 191 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 214, 'g': 0, 'b': 47, 'a': 171 }, { 'r': 0, 'g': 243, 'b': 108, 'a': 65 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 129, 'b': 178, 'a': 63 }, { 'r': 198, 'g': 0, 'b': 205, 'a': 159 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 238, 'b': 107, 'a': 78 }, { 'r': 245, 'g': 22, 'b': 0, 'a': 80 }, { 'r': 0, 'g': 98, 'b': 217, 'a': 155 }, { 'r': 0, 'g': 244, 'b': 111, 'a': 73 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 198, 'g': 0, 'b': 205, 'a': 159 }, { 'r': 211, 'g': 0, 'b': 19, 'a': 195 }, { 'r': 244, 'g': 0, 'b': 27, 'a': 74 }, { 'r': 194, 'g': 54, 'b': 0, 'a': 41 }, { 'r': 0, 'g': 231, 'b': 102, 'a': 55 }, { 'r': 0, 'g': 243, 'b': 113, 'a': 243 }, { 'r': 131, 'g': 0, 'b': 187, 'a': 163 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 250, 'b': 118, 'a': 155 }, { 'r': 0, 'g': 241, 'b': 124, 'a': 114 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 242, 'g': 34, 'b': 0, 'a': 58 }, { 'r': 248, 'g': 0, 'b': 43, 'a': 187 }, { 'r': 237, 'g': 0, 'b': 0, 'a': 42 }, { 'r': 0, 'g': 244, 'b': 111, 'a': 73 }, { 'r': 249, 'g': 0, 'b': 47, 'a': 188 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 233, 'g': 0, 'b': 0, 'a': 34 }, { 'r': 0, 'g': 245, 'b': 114, 'a': 78 }, { 'r': 180, 'g': 140, 'b': 0, 'a': 50 }, { 'r': 177, 'g': 177, 'b': 0, 'a': 23 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 29, 'g': 0, 'b': 174, 'a': 34 }, { 'r': 87, 'g': 0, 'b': 174, 'a': 34 }, { 'r': 0, 'g': 240, 'b': 120, 'a': 50 }, { 'r': 233, 'g': 0, 'b': 0, 'a': 34 }, { 'r': 0, 'g': 242, 'b': 138, 'a': 58 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 255, 'g': 0, 'b': 0, 'a': 2 }, { 'r': 0, 'g': 243, 'b': 91, 'a': 66 }, { 'r': 0, 'g': 107, 'b': 214, 'a': 18 }, { 'r': 214, 'g': 0, 'b': 107, 'a': 18 }, { 'r': 196, 'g': 39, 'b': 0, 'a': 13 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 214, 'g': 0, 'b': 107, 'a': 18 }, { 'r': 194, 'g': 0, 'b': 121, 'a': 245 }, { 'r': 203, 'g': 138, 'b': 0, 'a': 155 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 177, 'g': 0, 'b': 177, 'a': 23 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 174, 'g': 0, 'b': 204, 'a': 34 }, { 'r': 138, 'g': 0, 'b': 188, 'a': 103 }, { 'r': 188, 'g': 0, 'b': 188, 'a': 26 }, { 'r': 161, 'g': 214, 'b': 0, 'a': 18 }, { 'r': 242, 'g': 34, 'b': 0, 'a': 58 }, { 'r': 180, 'g': 0, 'b': 186, 'a': 175 }, { 'r': 130, 'g': 97, 'b': 0, 'a': 251 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 233, 'g': 0, 'b': 0, 'a': 34 }, { 'r': 0, 'g': 0, 'b': 255, 'a': 2 }, { 'r': 0, 'g': 240, 'b': 122, 'a': 52 }, { 'r': 0, 'g': 242, 'b': 109, 'a': 63 }, { 'r': 233, 'g': 0, 'b': 0, 'a': 34 }, { 'r': 0, 'g': 245, 'b': 114, 'a': 78 }, { 'r': 23, 'g': 0, 'b': 187, 'a': 87 }, { 'r': 0, 'g': 240, 'b': 105, 'a': 53 }, { 'r': 0, 'g': 247, 'b': 123, 'a': 98 }, { 'r': 0, 'g': 222, 'b': 105, 'a': 87 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 4, 'b': 157, 'a': 207 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 226, 'g': 0, 'b': 75, 'a': 26 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 246, 'g': 212, 'b': 0, 'a': 119 }, { 'r': 243, 'g': 19, 'b': 0, 'a': 159 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 233, 'g': 0, 'b': 0, 'a': 34 }, { 'r': 145, 'g': 0, 'b': 254, 'a': 7 }, { 'r': 255, 'g': 0, 'b': 0, 'a': 2 }, { 'r': 214, 'g': 0, 'b': 0, 'a': 18 }, { 'r': 185, 'g': 0, 'b': 23, 'a': 10 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 207, 'g': 34, 'b': 0, 'a': 58 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 242, 'b': 117, 'a': 63 }, { 'r': 0, 'g': 148, 'b': 191, 'a': 12 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 80, 'b': 214, 'a': 18 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 0, 'b': 255, 'a': 2 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 174, 'g': 0, 'b': 204, 'a': 34 }, { 'r': 177, 'g': 0, 'b': 177, 'a': 23 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 236, 'b': 113, 'a': 82 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 128, 'g': 0, 'b': 184, 'a': 127 }, { 'r': 128, 'g': 0, 'b': 184, 'a': 127 }, { 'r': 0, 'g': 21, 'b': 191, 'a': 12 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 107, 'b': 214, 'a': 18 }, { 'r': 228, 'g': 8, 'b': 0, 'a': 29 }, { 'r': 0, 'g': 244, 'b': 108, 'a': 74 }, { 'r': 0, 'g': 247, 'b': 121, 'a': 98 }, { 'r': 232, 'g': 15, 'b': 0, 'a': 211 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 226, 'b': 123, 'a': 98 }, { 'r': 0, 'g': 188, 'b': 48, 'a': 41 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 213, 'g': 122, 'b': 0, 'a': 152 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 242, 'g': 122, 'b': 0, 'a': 197 }, { 'r': 203, 'g': 146, 'b': 0, 'a': 247 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 132, 'b': 215, 'a': 122 }, { 'r': 0, 'g': 19, 'b': 247, 'a': 106 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 207, 'g': 75, 'b': 0, 'a': 26 }, { 'r': 0, 'g': 100, 'b': 168, 'a': 173 }, { 'r': 0, 'g': 197, 'b': 197, 'a': 207 }, { 'r': 170, 'g': 0, 'b': 165, 'a': 191 }, { 'r': 0, 'g': 36, 'b': 211, 'a': 111 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 245, 'b': 110, 'a': 81 }, { 'r': 161, 'g': 0, 'b': 194, 'a': 63 }, { 'r': 92, 'g': 0, 'b': 223, 'a': 187 }, { 'r': 207, 'g': 51, 'b': 0, 'a': 58 }, { 'r': 0, 'g': 33, 'b': 171, 'a': 243 }, { 'r': 0, 'g': 52, 'b': 217, 'a': 235 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 21, 'g': 191, 'b': 0, 'a': 12 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 114, 'b': 190, 'a': 106 }, { 'r': 0, 'g': 82, 'b': 229, 'a': 111 }, { 'r': 0, 'g': 138, 'b': 222, 'a': 147 }, { 'r': 183, 'g': 26, 'b': 0, 'a': 39 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 247, 'b': 121, 'a': 98 }, { 'r': 0, 'g': 245, 'b': 111, 'a': 78 }, { 'r': 0, 'g': 213, 'b': 101, 'a': 243 }, { 'r': 0, 'g': 237, 'b': 97, 'a': 73 }, { 'r': 0, 'g': 245, 'b': 98, 'a': 82 }, { 'r': 0, 'g': 245, 'b': 98, 'a': 82 }, { 'r': 4, 'g': 0, 'b': 146, 'a': 223 }, { 'r': 0, 'g': 240, 'b': 120, 'a': 50 }, { 'r': 231, 'g': 0, 'b': 121, 'a': 251 }, { 'r': 203, 'g': 135, 'b': 0, 'a': 15 }, { 'r': 203, 'g': 135, 'b': 0, 'a': 15 }, { 'r': 0, 'g': 141, 'b': 92, 'a': 36 }, { 'r': 183, 'g': 0, 'b': 121, 'a': 174 }, { 'r': 0, 'g': 156, 'b': 200, 'a': 249 }, { 'r': 0, 'g': 160, 'b': 214, 'a': 245 }, { 'r': 195, 'g': 0, 'b': 113, 'a': 251 }, { 'r': 226, 'g': 0, 'b': 120, 'a': 251 }, { 'r': 223, 'g': 184, 'b': 0, 'a': 155 }, { 'r': 191, 'g': 162, 'b': 0, 'a': 206 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 231, 'g': 23, 'b': 0, 'a': 32 }, { 'r': 0, 'g': 21, 'b': 191, 'a': 12 }, { 'r': 0, 'g': 0, 'b': 185, 'a': 10 }, { 'r': 177, 'g': 133, 'b': 0, 'a': 23 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 177, 'g': 133, 'b': 0, 'a': 23 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }, { 'r': 216, 'g': 0, 'b': 116, 'a': 46 }, { 'r': 203, 'g': 135, 'b': 0, 'a': 15 }, { 'r': 0, 'g': 185, 'b': 185, 'a': 10 }]; <|start_filename|>libraries/encapsulate.js<|end_filename|> var fs = require('fs-extra'); var path = require('path'); var cheerio = require('cheerio'); // get the root directory; var rootDirectory = path.dirname(__dirname); // create a meaningful dirname add "-for-editor" to indicate var codePackageCopyName = rootDirectory.split("/").slice(-1).pop() + "-for-editor"; // create a path to the parent directory of the root var copyPathDirectory = path.join(__dirname, '../../', codePackageCopyName) console.log(rootDirectory) console.log(copyPathDirectory) // check if the folder exists, if so remove it! // NOTE: any changes to that dir will be removed! // So be sure to always write changes to the main repo if(fs.existsSync(copyPathDirectory)){ fs.removeSync(copyPathDirectory) } /* Here's where the magic happens */ // first make of copy of the sketches copyFolderContents(rootDirectory, copyPathDirectory) // then get the directories for the 01_P and 02_M sketches var pDirs = getDirectories(copyPathDirectory+"/01_P/").map(function(dir){return copyPathDirectory +"/01_P/" + dir}); // var pNewDirs = getDirectories(copyPathDirectory+"/01_P_NEW/").map(function(dir){return copyPathDirectory +"/01_P_NEW/" + dir}); var mDirs = getDirectories(copyPathDirectory+"/02_M/").map(function(dir){return copyPathDirectory +"/02_M/" + dir}); // copy the libs and fix the paths make(copyPathDirectory, pDirs) // make(copyPathDirectory, pNewDirs) make(copyPathDirectory, mDirs) /* @@@ make Put it all together, Run through each sketch and copy over the dependencies */ function make(newCodePackagePath,sketches){ sketches.forEach(function(dir){ if(dir.endsWith("_footage") == false){ if(fs.existsSync(dir+'/index.html')){ var dirIndex = dir+'/index.html' var sketchDeps = getSketchDependencies(dirIndex); copyDependencies(newCodePackagePath, sketchDeps, dir) } else{ console.log("no index file for: " + dir) } } }) } /* @@@ getSketchDependencies get the js & css dependencies based on the index.html file */ function getSketchDependencies(path){ var indexFile = fs.readFileSync(path, "utf8"); var reqSrcs = []; $ = cheerio.load(indexFile); // get the script tags $('script').each(function(i, elem) { var libsrc = $(elem)[0].attribs.src; if(libsrc !== undefined ){ if(libsrc.split("/")[0] == ".."){ libsrc = libsrc.split("/").slice(2).join("/"); reqSrcs.push(libsrc); } } $(this).attr("src", libsrc); }) // get the links $('link').each(function(i, elem) { var libhref = $(elem)[0].attribs.href; libhref = libhref.split("/").slice(2).join("/"); reqSrcs.push(libhref); $(this).attr("href", libhref); }) // console.log($.html()) // console.log(reqSrcs) // write out the file fs.writeFileSync(path, $.html()) return reqSrcs; } /* @@@ copyDependencies copy over all the dependencies in a loop feeding in the lib array and the current sketch */ function copyDependencies(newCodePackagePath,myLibs, currentSketch){ // copyFolderContents(codePackageCopyPath + sketchDeps[0], pDirs[0] + "/" + sketchDeps[0]) myLibs.forEach(function(lib){ copyFolderContents(newCodePackagePath+"/"+lib, currentSketch + "/" + lib); }) } /* @@@ getDirectories return the path names */ function getDirectories(path) { return fs.readdirSync(path).filter(function (file) { return fs.statSync(path+'/'+file).isDirectory(); }); } /* @@@ copyFolderContents copy the folder contents */ function copyFolderContents(fromFolder, toFolder){ // Sync: try { fs.copySync(fromFolder, toFolder, {overwrite: true}) // console.log('success!') } catch (err) { console.error(err) } } <|start_filename|>01_P/P_2_1_5_03/sketch.js<|end_filename|> // P_2_1_5_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Drawing tool for creating moire effect compositions using * rectangles of various widths, lengths, angles and colours. * * MOUSE * mouse : place moire effect rectangle * * KEYS * 1 : set color to red * 2 : set color to green * 3 : set color to blue * 4 : set color to black * arrow up : increase rectangle width * arrow down : decrease rectangle width * s : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) */ 'use strict'; var shapes = []; var density = 2.5; var shapeHeight = 64; var shapeColor; var newShape; function setup() { createCanvas(800, 800); noFill(); shapeColor = color(0); } function draw() { background(255); shapes.forEach(function(shape) { shape.draw(); }); if (newShape) { newShape.x2 = mouseX; newShape.y2 = mouseY; newShape.h = shapeHeight; newShape.c = shapeColor; newShape.draw(); } } function Shape(x1, y1, x2, y2, h, c) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.h = h; this.c = c; Shape.prototype.draw = function() { var w = dist(this.x1, this.y1, this.x2, this.y2); var a = atan2(this.y2 - this.y1, this.x2 - this.x1); stroke(this.c); push(); translate(this.x1, this.y1); rotate(a); translate(0, -this.h / 2); for (var i = 0; i < this.h; i += density) { line(0, i, w, i); } pop(); }; } function mousePressed() { newShape = new Shape(pmouseX, pmouseY, mouseX, mouseY, shapeHeight, shapeColor); } function mouseReleased() { shapes.push(newShape); newShape = undefined; } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') shapeColor = color(255, 0, 0); if (key == '2') shapeColor = color(0, 255, 0); if (key == '3') shapeColor = color(0, 0, 255); if (key == '4') shapeColor = color(0); if (keyCode == UP_ARROW) shapeHeight += density; if (keyCode == DOWN_ARROW) shapeHeight -= density; } <|start_filename|>02_M/M_1_5_03/sketch.js<|end_filename|> // M_1_5_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * noise values (noise 3d) are used to animate a bunch of agents. * * KEYS * 1-2 : switch noise mode * space : new noise seed * backspace : clear screen * s : save png */ 'use strict'; var sketch = function(p) { var agents = []; var agentCount = 4000; var noiseScale = 100; var noiseStrength = 10; var noiseZRange = 0.4; var noiseZVelocity = 0.01; var overlayAlpha = 10; var agentAlpha = 90; var strokeWidth = 0.3; var drawMode = 1; p.setup = function() { p.createCanvas(p.windowWidth, p.windowHeight); for (var i = 0; i < agentCount; i++) { agents[i] = new Agent(noiseZRange); } }; p.draw = function() { p.fill(255, overlayAlpha); p.noStroke(); p.rect(0, 0, p.width, p.height); // Draw agents p.stroke(0, agentAlpha); for (var i = 0; i < agentCount; i++) { if (drawMode == 1) { agents[i].update1(strokeWidth, noiseScale, noiseStrength, noiseZVelocity); } else { agents[i].update2(strokeWidth, noiseScale, noiseStrength, noiseZVelocity); } } }; p.keyReleased = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); if (p.key == '1') drawMode = 1; if (p.key == '2') drawMode = 2; if (p.key == ' ') { var newNoiseSeed = p.floor(p.random(10000)); console.log('newNoiseSeed', newNoiseSeed); p.noiseSeed(newNoiseSeed); } if (p.keyCode == p.DELETE || p.keyCode == p.BACKSPACE) p.background(255); }; }; var myp5 = new p5(sketch); <|start_filename|>02_M/M_6_1_03/sketch.js<|end_filename|> // M_6_1_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * more nodes and more springs * * KEYS * r : reset positions * s : save png * p : save pdf */ 'use strict'; var sketch = function(p) { // an array for the nodes var nodeCount = 100; var nodes = []; // an array for the springs var springs = []; // dragged node var selectedNode = null; var nodeDiameter = 16; p.setup = function() { p.createCanvas(p.windowWidth, p.windowHeight); p.background(255); p.noStroke(); initNodesAndSprings(); }; p.draw = function() { p.background(255); // let all nodes repel each other for (var i = 0; i < nodes.length; i++) { nodes[i].attractNodes(nodes); } // apply spring forces for (var i = 0; i < springs.length; i++) { springs[i].update(); } // apply velocity vector and update position for (var i = 0; i < nodes.length; i++) { nodes[i].update(); } if (selectedNode != null) { selectedNode.x = p.mouseX; selectedNode.y = p.mouseY; } // draw nodes p.stroke(0, 130, 164); p.strokeWeight(2); for (var i = 0; i < springs.length; i++) { p.line(springs[i].fromNode.x, springs[i].fromNode.y, springs[i].toNode.x, springs[i].toNode.y); } // draw nodes p.noStroke(); for (var i = 0; i < nodes.length; i++) { p.fill(255); p.ellipse(nodes[i].x, nodes[i].y, nodeDiameter, nodeDiameter); p.fill(0); p.ellipse(nodes[i].x, nodes[i].y, nodeDiameter - 4, nodeDiameter - 4); } }; var initNodesAndSprings = function() { // init nodes nodes = []; var rad = nodeDiameter / 2; for (var i = 0; i < nodeCount; i++) { var newNode = new Node(p.width / 2 + p.random(-200, 200), p.height / 2 + p.random(-200, 200)); newNode.minX = rad; newNode.minY = rad; newNode.maxX = p.width - rad; newNode.maxY = p.height - rad; newNode.radius = 100; newNode.strength = -5; nodes.push(newNode); } // set springs randomly springs = []; for (var j = 0; j < nodes.length - 1; j++) { var rCount = p.floor(p.random(1, 2)); for (var i = 0; i < rCount; i++) { var r = p.floor(p.random(j + 1, nodes.length)); var newSpring = new Spring(nodes[j], nodes[r]); newSpring.length = 20; newSpring.stiffness = 1; springs.push(newSpring); } } }; p.mousePressed = function() { // Ignore anything greater than this distance var maxDist = 20; for (var i = 0; i < nodes.length; i++) { var checkNode = nodes[i]; var d = p.dist(p.mouseX, p.mouseY, checkNode.x, checkNode.y); if (d < maxDist) { selectedNode = checkNode; maxDist = d; } } }; p.mouseReleased = function() { if (selectedNode != null) { selectedNode = null; } }; p.keyPressed = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); if (key == 'r' || key == 'R') { p.background(255); initNodesAndSprings(); } }; }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_2_3_1_01/sketch.js<|end_filename|> // P_2_3_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw tool. draw with a rotating line. * * MOUSE * drag : draw * * KEYS * 1-4 : switch default colors * delete/backspace : clear screen * d : reverse direction and mirrow angle * space : new random color * arrow left : rotaion speed - * arrow right : rotaion speed + * arrow up : line length + * arrow down : line length - * s : save png */ 'use strict'; var c; var lineLength = 0; var angle = 0; var angleSpeed = 1; function setup() { createCanvas(windowWidth, windowHeight); background(255); cursor(CROSS); strokeWeight(1); c = color(181, 157, 0); } function draw() { if (mouseIsPressed && mouseButton == LEFT) { push(); translate(mouseX, mouseY); rotate(radians(angle)); stroke(c); line(0, 0, lineLength, 0); pop(); angle += angleSpeed; } } function mousePressed() { // create a new random line length each new press lineLength = random(70, 200); } function keyPressed() { if (keyCode == UP_ARROW) lineLength += 5; if (keyCode == DOWN_ARROW) lineLength -= 5; if (keyCode == LEFT_ARROW) angleSpeed -= 0.5; if (keyCode == RIGHT_ARROW) angleSpeed += 0.5; } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) background(255); // reverse direction and mirror angle if (key == 'd' || key == 'D') { angle += 180; angleSpeed *= -1; } // change color if (key == ' ') c = color(random(255), random(255), random(255), random(80, 100)); // default colors from 1 to 4 if (key == '1') c = color(181, 157, 0); if (key == '2') c = color(0, 130, 164); if (key == '3') c = color(87, 35, 129); if (key == '4') c = color(197, 0, 123); } <|start_filename|>01_P/P_2_2_6_01/sketch.js<|end_filename|> // P_2_2_6_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * A chain of linked pendulums. Each a little shorter and faster than the one it's linked to. * Each joint of the pendulum leaves behind its own trail. * * KEYS * 1 : toggle pendulum * 2 : toggle pendulum path * - : decrease speed relation * + : increase speed relation * arrow down : decrease length of lines * arrow up : increase length of lines * arrow left : decrease joints * arrow right : increase joints * del, backspace : clear screen * s : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) */ 'use strict'; var shape; var joints = 5; var lineLength = 100; var speedRelation = 2; var center; var pendulumPath; var angle = 0; var maxAngle = 360; var speed; var showPendulum = true; var showPendulumPath = true; function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); noFill(); strokeWeight(1); center = createVector(width / 2, height / 2); startDrawing(); } function startDrawing() { pendulumPath = []; // new empty array for each joint for (var i = 0; i < joints; i++) { pendulumPath.push([]); } angle = 0; speed = (8 / pow(1.75, joints - 1) / pow(2, speedRelation - 1)); } function draw() { background(0, 0, 100); angle += speed; // each frame, create new positions for each joint if (angle <= maxAngle + speed) { // start at the center position var pos = center.copy(); for (var i = 0; i < joints; i++) { var a = angle * pow(speedRelation, i); if (i % 2 == 1) a = -a; var nextPos = p5.Vector.fromAngle(radians(a)); nextPos.setMag((joints - i) / joints * lineLength); nextPos.add(pos); if (showPendulum) { noStroke(); fill(0, 10); ellipse(pos.x, pos.y, 4, 4); noFill(); stroke(0, 10); line(pos.x, pos.y, nextPos.x, nextPos.y); } pendulumPath[i].push(nextPos); pos = nextPos; } } // draw the path for each joint if (showPendulumPath) { strokeWeight(1.6); for (var i = 0; i < pendulumPath.length; i++) { var path = pendulumPath[i]; beginShape(); var hue = map(i, 0, joints, 120, 360); stroke(hue, 80, 60, 50); for (var j = 0; j < path.length; j++) { vertex(path[j].x, path[j].y); } endShape(); } } } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) startDrawing(); if (keyCode == UP_ARROW) { lineLength += 2; startDrawing(); } if (keyCode == DOWN_ARROW) { lineLength -= 2; startDrawing(); } if (keyCode == LEFT_ARROW) { joints--; if (joints < 1) joints = 1; startDrawing(); } if (keyCode == RIGHT_ARROW) { joints++; if (joints > 10) joints = 10; startDrawing(); } if (key == '+') { speedRelation += 0.5; if (speedRelation > 5) speedRelation = 5; startDrawing(); } if (key == '-') { speedRelation -= 0.5; if (speedRelation < 2) speedRelation = 2; startDrawing(); } if (key == '1') showPendulum = !showPendulum; if (key == '2') showPendulumPath = !showPendulumPath; } <|start_filename|>01_P/P_2_2_1_02/sketch.js<|end_filename|> // P_2_2_1_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw the path of a stupid agent * * MOUSE * position x : drawing speed * * KEYS * 1-3 : draw mode of the agent * DEL/BACKSPACE : clear display * s : save png */ 'use strict'; var NORTH = 0; var NORTHEAST = 1; var EAST = 2; var SOUTHEAST = 3; var SOUTH = 4; var SOUTHWEST = 5; var WEST = 6; var NORTHWEST = 7; var direction; var stepSize = 1; var diameter = 1; var posX; var posY; var drawMode = 1; var counter = 0; function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); noStroke(); posX = width / 2; posY = height / 2; } function draw() { for (var i = 0; i <= mouseX; i++) { counter++; // random number for the direction of the next step if (drawMode == 2) { direction = int(random(3)); } else { direction = int(random(7)); } if (direction == NORTH) { posY -= stepSize; } else if (direction == NORTHEAST) { posX += stepSize; posY -= stepSize; } else if (direction == EAST) { posX += stepSize; } else if (direction == SOUTHEAST) { posX += stepSize; posY += stepSize; } else if (direction == SOUTH) { posY += stepSize; } else if (direction == SOUTHWEST) { posX -= stepSize; posY += stepSize; } else if (direction == WEST) { posX -= stepSize; } else if (direction == NORTHWEST) { posX -= stepSize; posY -= stepSize; } if (posX > width) posX = 0; if (posX < 0) posX = width; if (posY < 0) posY = height; if (posY > height) posY = 0; if (drawMode == 3) { if (counter >= 100) { counter = 0; fill(192, 100, 64, 80); ellipse(posX + stepSize / 2, posY + stepSize / 2, diameter + 7, diameter + 7); } } fill(0, 40); ellipse(posX + stepSize / 2, posY + stepSize / 2, diameter, diameter); } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) clear(); if (key == '1') { drawMode = 1; stepSize = 1; diameter = 1; } if (key == '2') { drawMode = 2; stepSize = 1; diameter = 1; } if (key == '3') { drawMode = 3; stepSize = 10; diameter = 5; } } <|start_filename|>01_P/P_3_1_3_05/sketch.js<|end_filename|> // P_3_1_3_05 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * analysing and sorting the words of a text by Part of Speech * connecting subsequent letters with lines. * * MOUSE * position x : interpolate between normal text and sorted position * * KEYS * 1 : toggle grey lines on/off * 2 : toggle colored lines on/off * 3 : toggle text on/off * 4 : switch all letters off * 5 : switch all letters on * a-z : switch letter on/off * ctrl : save png * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) * Adapted from P_3_1_3_04 */ 'use strict'; var joinedText; var textPOSTags = []; // Alphabetical list of PENN part-of-speech tags // source: https://rednoise.org/rita/reference/PennTags.html var allPOSTags = [ 'cc', 'cd', 'dt', 'ex', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nns', 'nnp', 'nnps', 'pdt', 'pos', 'prp', 'prp$', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'wdt', 'wp', 'wp$', 'wrb' ]; var allPOSTagsFull = [ 'Coordinating conjunction', 'Cardinal number', 'Determiner', 'Existential there', 'Foreign word', 'Preposition or subordinating conjunction', 'Adjective', 'Adjective, comparative', 'Adjective, superlative', 'List item marker', 'Modal', 'Noun, singular or mass', 'Noun, plural', 'Proper noun, singular', 'Proper noun, plural', 'Predeterminer', 'Possessive ending', 'Personal pronoun', 'Possessive pronoun', 'Adverb', 'Adverb, comparative', 'Adverb, superlative', 'Particle', 'Symbol', 'to', 'Interjection', 'Verb, base form', 'Verb, past tense', 'Verb, gerund or present participle', 'Verb, past participle', 'Verb, non-3rd person singular present', 'Verb, 3rd person singular present', 'Wh-determiner', 'Wh-pronoun', 'Possessive wh-pronoun', 'Wh-adverb' ]; var counters = []; var posX; var posY; var drawGreyLines = false; var drawColoredLines = true; var drawText = true; function preload() { joinedText = loadStrings('data/AllTheWorldsAStage.txt'); } function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); textFont('monospace', 18); fill(0); for (var i = 0; i < allPOSTags.length; i++) { counters.push(0); } joinedText = joinedText.join(' '); joinedText = joinedText.split(/\s+/); for (var i = 0; i < joinedText.length; i++) { var wordPOSTag = RiTa.getPosTags(RiTa.stripPunctuation(joinedText[i]))[0]; textPOSTags.push(wordPOSTag); var tagIndex = allPOSTags.indexOf(wordPOSTag); if (tagIndex >= 0) { counters[tagIndex]++; } joinedText[i] += ' '; } } function draw() { background(360); translate(50, 0); noStroke(); posX = 0; posY = 50; var sortPositionsX = []; var oldPositionsX = []; var oldPositionsY = []; for (var i = 0; i < joinedText.length; i++) { sortPositionsX[i] = 0; oldPositionsX[i] = 0; oldPositionsY[i] = 0; } var oldX = 0; var oldY = 0; // draw counters if (mouseX >= width - 50) { textSize(10); for (var i = 0; i < allPOSTags.length; i++) { textAlign(LEFT); text(allPOSTags[i] + ' (' + allPOSTagsFull[i] + ')', -20, i * 20 + 40); textAlign(RIGHT); text(counters[i], -25, i * 20 + 40); } textAlign(LEFT); textSize(18); } translate(256, 0); // go through all characters in the text to draw them for (var i = 0; i < joinedText.length; i++) { // again, find the index of the current letter in the alphabet var wordPOSTag = textPOSTags[i]; var index = allPOSTags.indexOf(wordPOSTag); if (index < 0) continue; var m = map(mouseX, 50, width - 50, 0, 1); m = constrain(m, 0, 1); var sortX = sortPositionsX[index]; var interX = lerp(posX, sortX, m); var sortY = index * 20 + 40; var interY = lerp(posY, sortY, m); if (drawGreyLines) { if (oldX != 0 && oldY != 0) { stroke(0, 10); line(oldX, oldY, interX, interY); } oldX = interX; oldY = interY; } if (drawColoredLines) { if (oldPositionsX[index] != 0 && oldPositionsY[index] != 0) { stroke(index * 10, 80, 60, 50); line(oldPositionsX[index], oldPositionsY[index], interX, interY); } oldPositionsX[index] = interX; oldPositionsY[index] = interY; } if (drawText) { text(joinedText[i], interX, interY); } sortPositionsX[index] += textWidth(joinedText[i]); posX += textWidth(joinedText[i]); if (posX >= min(width, 1000)) { posY += 40; posX = 0; } } } function keyReleased() { if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); if (key == '1') drawGreyLines = !drawGreyLines; if (key == '2') drawColoredLines = !drawColoredLines; if (key == '3') drawText = !drawText; } <|start_filename|>01_P/P_3_2_5_01/sketch.js<|end_filename|> // P_3_2_5_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Animated type using loadPixels() method to get font area * * MOUSE * position x/y : affect randomness * * KEYS * A-Z : type letters * Arrow left/right : toggle through draw modes * Arrow up/down : increase/decrease point density * CONTROL : save png * * CONTRIBUTED BY * [<NAME>](http://jk-lee.com) */ 'use strict'; var font; var textTyped = 'TYPE & CODE'; var drawMode = 1; var fontSize = 250; var padding = 10; var nOff = 0; var pointDensity = 8; var colors; var paths; var textImg; function preload() { font = loadFont('data/FiraSansCompressed-Bold.otf'); } function setup() { createCanvas(1600, 800); frameRate(25); rectMode(CENTER); colors = [color(65, 105, 185), color(245, 95, 80), color(15, 233, 118)]; pixelDensity(1); setupText(); } function setupText() { // create an offscreen graphics object to draw the text into textImg = createGraphics(width, height); textImg.pixelDensity(1); textImg.background(255); textImg.textFont(font); textImg.textSize(fontSize); textImg.text(textTyped, 100, fontSize + 50); textImg.loadPixels(); } function draw() { background(255); nOff++; for (var x = 0; x < textImg.width; x += pointDensity) { for (var y = 0; y < textImg.height; y += pointDensity) { // Calculate the index for the pixels array from x and y var index = (x + y * textImg.width) * 4; // Get the red value from image var r = textImg.pixels[index]; if (r < 128) { if (drawMode == 1){ strokeWeight(1); var noiseFac = map(mouseX, 0, width, 0, 1); var lengthFac = map(mouseY, 0, height, 0.01, 1); var num = noise((x + nOff) * noiseFac, y * noiseFac); if (num < 0.6) { stroke(colors[0]); } else if (num < 0.7) { stroke(colors[1]); } else { stroke(colors[2]); } push(); translate(x, y); rotate(radians(frameCount)); line(0, 0, fontSize * lengthFac, 0); pop(); } if (drawMode == 2){ stroke(0, 0, 0); strokeWeight(1); noStroke(); push(); translate(x, y); var num = noise((x + nOff) / 10, y / 10); if (num < 0.6) { fill(colors[0]); } else if (num < 0.7) { fill(colors[1]); } else { fill(colors[2]); } var w = noise((x - nOff) / 10, (y + nOff * 0.1) / 10) * 20; var h = noise((x - nOff) / 10, (y + nOff * 0.1) / 10) * 10; ellipse(0, 0, w, h); // rect() is cool too pop(); } if (drawMode == 3){ stroke(0, 0, 0); strokeWeight(1); noStroke(); var num = random(1); if (num < 0.6) { fill(colors[0]); } else if (num < 0.7) { fill(colors[1]); } else { fill(colors[2]); } push(); beginShape(); for (var i = 0; i < 3; i++){ var ox = (noise((i * 1000 + x - nOff) / 30, (i * 3000 + y + nOff) / 30) - 0.5) * pointDensity * 6; var oy = (noise((i * 2000 + x - nOff) / 30, (i * 4000 + y + nOff) / 30) - 0.5) * pointDensity * 6; vertex(x + ox, y + oy); } endShape(CLOSE); pop(); } if (drawMode == 4){ stroke(colors[0]); strokeWeight(3); point(x - 10, y - 10); point(x, y); point(x + 10, y + 10); for (var i = 0; i < 5; i++){ if (i == 1) { stroke(colors[1]); } else if (i == 3) { stroke(colors[2]); } if (i % 2 == 0){ var ox = noise((10000 + i * 100 + x - nOff) / 10) * 10; var oy = noise((20000 + i * 100 + x - nOff) / 10) * 10; point(x + ox, y + oy); } else { var ox = noise((30000 + i * 100 + x - nOff) / 10) * 10; var oy = noise((40000 + i * 100 + x - nOff) / 10) * 10; point(x - ox, y - oy); } } } } } } } function keyPressed() { if (keyCode === CONTROL) saveCanvas(gd.timestamp(), 'png'); if (keyCode === DELETE || keyCode === BACKSPACE) { textTyped = textTyped.substring(0,max(0,textTyped.length - 1)); setupText(); } if (keyCode === ENTER || keyCode === RETURN) { textTyped += '\n'; setupText(); } if (keyCode === LEFT_ARROW) { drawMode--; if (drawMode < 1) drawMode = 4; } if (keyCode === RIGHT_ARROW) { drawMode++; if (drawMode > 4) drawMode = 1; } if (keyCode === DOWN_ARROW) { pointDensity--; if (pointDensity < 4) pointDensity = 4; } if (keyCode === UP_ARROW) { pointDensity++; } } function keyTyped() { if (keyCode >= 32){ textTyped += key; setupText(); } } <|start_filename|>01_P/P_4_2_3_02/sketch.js<|end_filename|> // P_4_2_3_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Create montage of video with a search query for Part Of Speech. * * CONTRIBUTED BY * [<NAME>](http://NielsPoldervaart.nl) * * VIDEO CREDITS * European Space Agency. (2016, December 23). The amazing adventures of Rosetta and Philae. Retrieved from http://m.esa.int/spaceinvideos/Videos/2016/12/The_amazing_adventures_of_Rosetta_and_Philae */ 'use strict'; // You have to download the video file first // Please see https://github.com/generative-design/Code-Package-p5.js/tree/master/data var videoSrc = '../../data/P_4_2_3_supercut-media/video.mp4'; var video; var subtitleSrc = '../../data/P_4_2_3_supercut-media/subs.vtt'; var subtitles; // List space-seperated PENN tags (see https://rednoise.org/rita/reference/PennTags.html) var searchQuery = 'nns jjr'; var searchResults = []; var currentResult; var fragmentTimer; var row = 0; var col = 0; var frameWidth; var frameHeight; var tileMode = true; var gui; function preload() { video = createVideo(videoSrc); loadStrings(subtitleSrc, parseSubtitles); } function parseSubtitles(lines) { subtitles = []; var timecodeRegEx = new RegExp(/((\d{2}:){2}\d{2}(,|\.)\d{3})\s-->\s((\d{2}:){2}\d{2}(,|\.)\d{3})/); var subtitleObject; var startTime; var endTime; var dialog; lines.forEach(function(line, i) { if (timecodeRegEx.test(line) || i === lines.length) { if (dialog) { subtitles.push(new SubTitleObject(startTime, endTime, dialog)); } if (i < lines.length) { startTime = line.replace(/\s.+$/, ''); endTime = line.replace(/^.+\s/, ''); dialog = ''; } } else { if (startTime && endTime) { dialog += line + ' '; } } }); print(subtitles); } function SubTitleObject(startTime, endTime, dialog) { this.startTimeStamp = startTime; this.endTimeStamp = endTime; this.startTime = getTimeInSeconds(startTime); this.endTime = getTimeInSeconds(endTime); this.dialog = dialog.replace(/\s\d+\s$|<(?:.)*?>/g, '').trim(); this.duration = this.endTime - this.startTime; this.dialogPOS = RiTa.getPosTags(this.dialog); } function getTimeInSeconds(timeString) { var hours = parseInt(timeString.replace(/:.+$/, '')); var minutes = parseInt(timeString.replace(/^\d.+?:|:\d.+$/, '')); var seconds = parseInt(timeString.replace(/^\d.+:|(\,|\.).+$/, '')); var milSeconds = parseInt(timeString.replace(/^.+(\,|\.)/, '')); return (hours * 60 * 60) + (minutes * 60) + seconds + (milSeconds / 1000); } function findSubtiles(searchPattern) { searchPattern = searchPattern.split(' '); var results = subtitles.filter(function(subtitle) { return searchPattern.every(function(searchGroup) { return subtitle.dialogPOS.indexOf(searchGroup) !== -1; }); }); return results; } function generateMontage() { clearTimeout(fragmentTimer); video.stop(); selectAll('.subtitle').forEach(function(dialogElement) { dialogElement.remove(); }); video.elt.style.width = tileMode ? '25%' : '100%'; video.position(0, 0); video.show(); clear(); row = 0; col = 0; searchResults = findSubtiles(searchQuery); print( 'Found ' + searchResults.length + ' results for search query ' + searchQuery, searchResults ); if (searchResults.length) { resizeCanvas(windowWidth, searchResults.length * video.size().height); queryResultMontage(searchResults, 0); } } function queryResultMontage(searchResults, i) { currentResult = searchResults[i]; var duration = currentResult.duration; video.play(); video.time(currentResult.startTime); print(currentResult.startTimeStamp, currentResult.dialog); fragmentTimer = setTimeout(function() { video.pause(); if (tileMode) { var framePos = getFramePos(); var img = video.get(); image(img, framePos.x, framePos.y, frameWidth, frameHeight); var dialogElement = createSpan(currentResult.dialog); dialogElement.addClass('subtitle'); dialogElement.size(frameWidth, frameHeight); dialogElement.position(framePos.x, framePos.y); text(currentResult.endTimeStamp, framePos.x, framePos.y); col++; framePos = getFramePos(); video.position(framePos.x, framePos.y); } if (i < searchResults.length - 1) { queryResultMontage(searchResults, i + 1); } else { clearTimeout(fragmentTimer); } }, duration * 1000); } function togglePlayback() { clearTimeout(fragmentTimer); if (video.elt.paused) { video.play(); } else { video.pause(); } } function getFramePos() { frameWidth = video.size().width; frameHeight = video.size().height; var x = frameWidth * col; var y = frameHeight * row; if (x + frameWidth > width) { col = 0; row++; x = frameWidth * col; y = frameHeight * row; } return createVector(x, y); } function setup() { createCanvas(windowWidth, 1000); fill(255); stroke(0); textSize(10); textAlign(LEFT, TOP); createGUI(); generateMontage(searchQuery); } <|start_filename|>02_M/M_6_1_01/sketch.js<|end_filename|> // M_6_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * distribute nodes on the display by letting them repel each other * * KEYS * r : reset positions * s : save png */ 'use strict'; var sketch = function(p) { // An array with nodes var nodes = []; var nodeCount = 200; p.setup = function() { p.createCanvas(p.windowWidth, p.windowHeight); p.noStroke(); // Create nodes createNodes(); }; p.draw = function() { p.fill(255, 20); p.rect(0, 0, p.width, p.height); p.fill(0); for (var i = 0; i < nodes.length; i++) { // Let all nodes repel each other nodes[i].attractNodes(nodes); // Apply velocity vector and update position nodes[i].update(); // Draw node p.ellipse(nodes[i].x, nodes[i].y, 10, 10); } }; p.keyPressed = function() { if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); if (p.key == 'r' || p.key == 'R') { p.background(255); createNodes(); } }; function createNodes() { nodes = []; for (var i = 0; i < nodeCount; i++) { nodes.push(new Node( p.width / 2 + p.random(-1, 1), p.height / 2 + p.random(-1, 1), 5, p.width - 5, 5, p.height - 5 )); } } }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_2_2_4_01/sketch.js<|end_filename|> // P_2_2_4_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * limited diffusion aggregation * * KEYS * s : save png */ 'use strict'; var maxCount = 5000; // max count of the cirlces var currentCount = 1; var x = []; var y = []; var r = []; function setup() { createCanvas(800, 800); strokeWeight(0.5); // first circle x[0] = width / 2; y[0] = height / 2; r[0] = 10; } function draw() { clear(); // create a random set of parameters var newR = random(1, 7); var newX = random(newR, width - newR); var newY = random(newR, height - newR); var closestDist = Number.MAX_VALUE; var closestIndex = 0; // which circle is the closest? for (var i = 0; i < currentCount; i++) { var newDist = dist(newX, newY, x[i], y[i]); if (newDist < closestDist) { closestDist = newDist; closestIndex = i; } } // show original position of the circle and a line to the new position // fill(230); // ellipse(newX, newY, newR * 2, newR * 2); // line(newX, newY, x[closestIndex], y[closestIndex]); // aline it to the closest circle outline var angle = atan2(newY - y[closestIndex], newX - x[closestIndex]); x[currentCount] = x[closestIndex] + cos(angle) * (r[closestIndex] + newR); y[currentCount] = y[closestIndex] + sin(angle) * (r[closestIndex] + newR); r[currentCount] = newR; currentCount++; // draw them for (var i = 0; i < currentCount; i++) { fill(50); ellipse(x[i], y[i], r[i] * 2, r[i] * 2); } if (currentCount >= maxCount) noLoop(); } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); } <|start_filename|>02_M/M_1_5_03/Agent.js<|end_filename|> var Agent = function(noiseZRange) { this.vector = myp5.createVector(myp5.random(myp5.width), myp5.random(myp5.height)); this.vectorOld = this.vector.copy(); this.stepSize = myp5.random(1, 5); this.angle; this.noiseZ = myp5.random(noiseZRange); }; Agent.prototype.update = function(strokeWidth, noiseZVelocity) { this.vector.x += myp5.cos(this.angle) * this.stepSize; this.vector.y += myp5.sin(this.angle) * this.stepSize; if (this.vector.x < -10) this.vector.x = this.vectorOld.x = myp5.width + 10; if (this.vector.x > myp5.width + 10) this.vector.x = this.vectorOld.x = -10; if (this.vector.y < -10) this.vector.y = this.vectorOld.y = myp5.height + 10; if (this.vector.y > myp5.height + 10) this.vector.y = this.vectorOld.y = -10; myp5.strokeWeight(strokeWidth * this.stepSize); myp5.line(this.vectorOld.x, this.vectorOld.y, this.vector.x, this.vector.y); this.vectorOld = this.vector.copy(); this.noiseZ += noiseZVelocity; }; Agent.prototype.update1 = function(strokeWidth, noiseScale, noiseStrength, noiseZVelocity) { this.angle = myp5.noise(this.vector.x / noiseScale, this.vector.y / noiseScale, this.noiseZ) * noiseStrength; this.update(strokeWidth, noiseZVelocity); }; Agent.prototype.update2 = function(strokeWidth, noiseScale, noiseStrength, noiseZVelocity) { this.angle = myp5.noise(this.vector.x / noiseScale, this.vector.y / noiseScale, this.noiseZ) * 24; this.angle = (this.angle - myp5.floor(this.angle)) * noiseStrength; this.update(strokeWidth, noiseZVelocity); }; <|start_filename|>01_P/P_3_1_1_01/sketch.js<|end_filename|> // P_3_1_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * typewriter. time reactive. * * MOUSE * position y : adjust spacing (line height) * * KEYS * a-z : text input (keyboard) * backspace/delete : delete last typed letter * ctrl : save png */ 'use strict'; var textTyped = 'Type slow and fast!'; var fontSizes = [textTyped.length]; var minFontSize = 15; var maxFontSize = 800; var newFontSize = 0; var pMillis = 0; var maxTimeDelta = 5000.0; var spacing = 2; // line height var tracking = 0; // between letters var font; function setup() { createCanvas(800, 600); font = 'Arial'; noCursor(); noStroke(); // init fontSizes for (var i = 0; i < textTyped.length; i++) { fontSizes[i] = minFontSize; } } function draw() { background(255); textAlign(LEFT); fill(0); spacing = map(mouseY, 0, height, 0, 120); translate(0, 200 + spacing); var x = 0; var y = 0; var fontSize = 20; for (var i = 0; i < textTyped.length; i++) { // get fontsize for the actual letter from the array fontSize = fontSizes[i]; textFont(font, fontSize); var letter = textTyped.charAt(i); var letterWidth = textWidth(letter) + tracking; if (x + letterWidth > width) { // start new line and add line height x = 0; y += spacing; } // draw letter text(letter, x, y); // update x-coordinate for next letter x += letterWidth; } // blinking cursor after text var timeDelta = millis() - pMillis; newFontSize = map(timeDelta, 0, maxTimeDelta, minFontSize, maxFontSize); newFontSize = min(newFontSize, maxFontSize); fill(200, 30, 40); if (int(frameCount / 10) % 2 == 0) fill(255); rect(x, y, newFontSize / 2, newFontSize / 20); } function keyReleased() { // export png if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); } function keyTyped() { if (keyCode >= 32) { textTyped += key; fontSizes.push(newFontSize); } else if (keyCode == BACKSPACE || keyCode == DELETE) { if (textTyped.length > 0) { textTyped = textTyped.substring(0, max(0, textTyped.length - 1)); fontSizes.pop(); } } // reset timer pMillis = millis(); } <|start_filename|>01_P/P_2_0_03/sketch.js<|end_filename|> // P_2_0_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * drawing with a changing shape by draging the mouse. * * MOUSE * position x : length * position y : thickness and number of lines * drag : draw * * KEYS * 1-3 : stroke color * del, backspace : erase * s : save png */ 'use strict'; var strokeColor; function setup() { createCanvas(720, 720); colorMode(HSB, 360, 100, 100, 100); noFill(); strokeWeight(2); strokeColor = color(0, 10); } function draw() { if (mouseIsPressed && mouseButton == LEFT) { push(); translate(width / 2, height / 2); var circleResolution = int(map(mouseY + 100, 0, height, 2, 10)); var radius = mouseX - width / 2; var angle = TAU / circleResolution; stroke(strokeColor); beginShape(); for (var i = 0; i <= circleResolution; i++) { var x = cos(angle * i) * radius; var y = sin(angle * i) * radius; vertex(x, y); } endShape(); pop(); } } function keyReleased() { if (keyCode == DELETE || keyCode == BACKSPACE) background(0, 0, 100); if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') strokeColor = color(0, 10); if (key == '2') strokeColor = color(192, 100, 64, 10); if (key == '3') strokeColor = color(52, 100, 71, 10); } <|start_filename|>01_P/P_2_1_4_01/sketch.js<|end_filename|> // P_2_1_4_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Use an image to check on/off a grid of checkboxes * Shout out to Dan Shiffman's checkbox mirror example * Image credits: Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL. * * KEYS * 1 : load image shapes * 2 : load image letters * 3 : load image map * * SLIDER * drag : drag the slider to adjust the image threshold * * CONTRIBUTED BY * [<NAME>](http://jk-lee.com) * * INSPIRED BY * [<NAME>](http://shiffman.net/) */ 'use strict'; var img; var img1; var img2; var img3; var slider; var cols = 40; var rows = 40; var boxes; var boxHolder; // preload the images to be used for the checkboxes function preload(){ img1 = loadImage('data/shapes.png'); img2 = loadImage('data/draw.png'); img3 = loadImage('data/toner.png'); } function setup() { // the html dom elements are not rendered on canvas noCanvas(); // set pixel density to 1 pixelDensity(1); boxHolder = createDiv(''); boxHolder.id('mirror'); boxes = []; // set the current img img = img1; img.resize(cols, rows); img.loadPixels(); for (var y = 0; y < rows; y++) { for (var x = 0; x < cols; x++) { var box = createCheckbox(); box.style('display', 'inline'); box.parent('mirror'); boxes.push(box); } var linebreak = createSpan('<br/>'); linebreak.parent('mirror'); } // add a slider to adjust the pixel threshold slider = createSlider(0, 255, 0); } function draw() { for (var y = 0; y < img.height; y++) { for (var x = 0; x < img.height; x++) { var c = color(img.get(x, y)); var bright = (red(c) + green(c) + blue(c)) / 3; // get the threshold from the slider var threshold = slider.value(); var checkIndex = x + y * cols; if (bright > threshold) { boxes[checkIndex].checked(false); } else { boxes[checkIndex].checked(true); } } } } function keyPressed() { if (key == '1') img = img1; if (key == '2') img = img2; if (key == '3') img = img3; img.resize(cols, rows); img.loadPixels(); } <|start_filename|>01_P/P_2_3_4_01/sketch.js<|end_filename|> // P_2_3_4_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw tool. shows how to draw with dynamic elements. * * MOUSE * drag : draw * * KEYS * 1-9 : switch module * del, backspace : clear screen * arrow up : module size + * arrow down : module size - * arrow left : step size - * arrow right : step size + * s : save png */ 'use strict'; var x = 0; var y = 0; var stepSize = 5.0; var moduleSize = 25; var lineModule; var elements; function preload() { // preload svg for line module elements = []; elements[0] = loadImage('data/01.svg'); elements[1] = loadImage('data/02.svg'); elements[2] = loadImage('data/03.svg'); elements[3] = loadImage('data/04.svg'); elements[4] = loadImage('data/05.svg'); elements[5] = loadImage('data/06.svg'); elements[6] = loadImage('data/07.svg'); elements[7] = loadImage('data/08.svg'); elements[8] = loadImage('data/09.svg'); } function setup() { // use full screen size createCanvas(displayWidth, displayHeight); background(255); cursor(CROSS); x = mouseX; y = mouseY; lineModule = elements[0]; } function draw() { if (mouseIsPressed && mouseButton == LEFT) { var d = dist(x, y, mouseX, mouseY); if (d > stepSize) { var angle = atan2(mouseY - y, mouseX - x); push(); translate(mouseX, mouseY); rotate(angle + PI); image(lineModule, 0, 0, d, moduleSize); pop(); x = x + cos(angle) * stepSize; y = y + sin(angle) * stepSize; } } } function mousePressed() { x = mouseX; y = mouseY; } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (keyCode == DELETE || keyCode == BACKSPACE) background(255); if (key == '1') lineModule = elements[0]; if (key == '2') lineModule = elements[1]; if (key == '3') lineModule = elements[2]; if (key == '4') lineModule = elements[3]; if (key == '5') lineModule = elements[4]; if (key == '6') lineModule = elements[5]; if (key == '7') lineModule = elements[6]; if (key == '8') lineModule = elements[7]; if (key == '9') lineModule = elements[8]; } function keyPressed() { // moduleSize arrowkeys up/down if (keyCode == UP_ARROW) moduleSize += 5; if (keyCode == DOWN_ARROW) moduleSize -= 5; // stepSize arrowkeys left/right stepSize = max(stepSize, 0.5); if (keyCode == LEFT_ARROW) stepSize -= 0.5; if (keyCode == RIGHT_ARROW) stepSize += 0.5; print('moduleSize:', moduleSize, 'stepSize:', stepSize); } <|start_filename|>01_P/P_1_2_3_01/sketch.js<|end_filename|> // P_1_2_3_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * generates specific color palettes * * MOUSE * position x/y : row and coloum count * * KEYS * 0-9 : creates specific color palettes * s : save png * c : save color palette */ 'use strict'; var tileCountX = 50; var tileCountY = 10; var hueValues = []; var saturationValues = []; var brightnessValues = []; function setup() { createCanvas(windowWidth, windowHeight); colorMode(HSB, 360, 100, 100, 100); noStroke(); // init with random values for (var i = 0; i < tileCountX; i++) { hueValues[i] = random(360); saturationValues[i] = random(100); brightnessValues[i] = random(100); } } function draw() { // white back background(0, 0, 100); // limit mouse coordinates to canvas var mX = constrain(mouseX, 0, width); var mY = constrain(mouseY, 0, height); // tile counter var counter = 0; // map mouse to grid resolution var currentTileCountX = int(map(mX, 0, width, 1, tileCountX)); var currentTileCountY = int(map(mY, 0, height, 1, tileCountY)); var tileWidth = width / currentTileCountX; var tileHeight = height / currentTileCountY; for (var gridY = 0; gridY < tileCountY; gridY++) { for (var gridX = 0; gridX < tileCountX; gridX++) { var posX = tileWidth * gridX; var posY = tileHeight * gridY; var index = counter % currentTileCountX; // get component color values fill(hueValues[index], saturationValues[index], brightnessValues[index]); rect(posX, posY, tileWidth, tileHeight); counter++; } } } function keyPressed() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == 'c' || key == 'C') { // -- save an ase file (adobe swatch export) -- var colors = []; for (var i = 0; i < hueValues.length; i++) { colors.push(color(hueValues[i], saturationValues[i], brightnessValues[i])); } writeFile([gd.ase.encode(colors)], gd.timestamp(), 'ase'); } if (key == '1') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = random(360); saturationValues[i] = random(100); brightnessValues[i] = random(100); } } if (key == '2') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = random(360); saturationValues[i] = random(100); brightnessValues[i] = 100; } } if (key == '3') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = random(360); saturationValues[i] = 100; brightnessValues[i] = random(100); } } if (key == '4') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = 0; saturationValues[i] = 0; brightnessValues[i] = random(100); } } if (key == '5') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = 195; saturationValues[i] = 100; brightnessValues[i] = random(100); } } if (key == '6') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = 195; saturationValues[i] = random(100); brightnessValues[i] = 100; } } if (key == '7') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = random(180); saturationValues[i] = random(80, 100); brightnessValues[i] = random(50, 90); } } if (key == '8') { for (var i = 0; i < tileCountX; i++) { hueValues[i] = random(180, 360); saturationValues[i] = random(80, 100); brightnessValues[i] = random(50, 90); } } if (key == '9') { for (var i = 0; i < tileCountX; i++) { if (i % 2 == 0) { hueValues[i] = random(360); saturationValues[i] = 100; brightnessValues[i] = random(100); } else { hueValues[i] = 195; saturationValues[i] = random(100); brightnessValues[i] = 100; } } } if (key == '0') { for (var i = 0; i < tileCountX; i++) { if (i % 2 == 0) { hueValues[i] = 140; saturationValues[i] = random(30, 100); brightnessValues[i] = random(40, 100); } else { hueValues[i] = 210; saturationValues[i] = random(40, 100); brightnessValues[i] = random(50, 100); } } } } <|start_filename|>01_P/P_2_1_3_02/sketch.js<|end_filename|> // P_2_1_3_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw a module made of lines in a grid * * MOUSE * position x : number of tiles horizontally * position y : number of tiles vertically * * KEYS * 1-3 : draw mode * s : save png */ 'use strict'; var count = 10; var colorStep = 20; var lineWeight = 0; var strokeColor = 0; var backgroundColor = 0; var drawMode = 1; function setup() { createCanvas(windowWidth, windowHeight); } function draw() { background(backgroundColor); var tileCountX = mouseX / 30 + 1; var tileCountY = mouseY / 30 + 1; var tileWidth = width / tileCountX; var tileHeight = height / tileCountY; for (var gridY = 0; gridY <= tileCountY; gridY++) { for (var gridX = 0; gridX <= tileCountX; gridX++) { var posX = tileWidth * gridX; var posY = tileHeight * gridY; var x1 = tileWidth / 2; var y1 = tileHeight / 2; var x2 = 0; var y2 = 0; push(); translate(posX, posY); for (var side = 0; side < 4; side++) { for (var i = 0; i < count; i++) { // move end point around the four sides of the tile switch (side) { case 0: x2 += tileWidth / count; y2 = 0; break; case 1: x2 = tileWidth; y2 += tileHeight / count; break; case 2: x2 -= tileWidth / count; y2 = tileHeight; break; case 3: x2 = 0; y2 -= tileHeight / count; break; } // adjust weight and color of the line if (i < count / 2) { lineWeight += 1; strokeColor += 60; } else { lineWeight -= 1; strokeColor -= 60; } // set colors depending on draw mode switch (drawMode) { case 1: backgroundColor = 255; stroke(0); break; case 2: backgroundColor = 255; stroke(0); strokeWeight(lineWeight); break; case 3: backgroundColor = 0; stroke(strokeColor); strokeWeight(mouseX / 100); break; } // draw the line line(x1, y1, x2, y2); } } pop(); } } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); if (key == '1') drawMode = 1; if (key == '2') drawMode = 2; if (key == '3') drawMode = 3; } <|start_filename|>01_P/P_4_3_1_01/sketch.js<|end_filename|> // P_4_3_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * pixel mapping. each pixel is translated into a new element * * MOUSE * position x/y : various parameters (depending on draw mode) * * KEYS * 1-9 : switch draw mode * s : save png */ 'use strict'; var drawMode = 1; var img; function preload() { img = loadImage('data/pic.png'); } function setup() { createCanvas(603, 873); print(img.width + ' • ' + img.height); } function draw() { background(255); var mouseXFactor = map(mouseX, 0, width, 0.05, 1); var mouseYFactor = map(mouseY, 0, height, 0.05, 1); for (var gridX = 0; gridX < img.width; gridX++) { for (var gridY = 0; gridY < img.height; gridY++) { // grid position + tile size var tileWidth = width / img.width; var tileHeight = height / img.height; var posX = tileWidth * gridX; var posY = tileHeight * gridY; // get current color img.loadPixels(); var c = color(img.get(gridX, gridY)); // greyscale conversion var greyscale = round(red(c) * 0.222 + green(c) * 0.707 + blue(c) * 0.071); switch (drawMode) { case 1: // greyscale to stroke weight var w1 = map(greyscale, 0, 255, 15, 0.1); stroke(0); strokeWeight(w1 * mouseXFactor); line(posX, posY, posX + 5, posY + 5); break; case 2: // greyscale to ellipse area fill(0); noStroke(); var r2 = 1.1284 * sqrt(tileWidth * tileWidth * (1 - greyscale / 255)); r2 *= mouseXFactor * 3; ellipse(posX, posY, r2, r2); break; case 3: // greyscale to line length var l3 = map(greyscale, 0, 255, 30, 0.1); l3 *= mouseXFactor; stroke(0); strokeWeight(10 * mouseYFactor); line(posX, posY, posX + l3, posY + l3); break; case 4: // greyscale to rotation, line length and stroke weight stroke(0); var w4 = map(greyscale, 0, 255, 10, 0); strokeWeight(w4 * mouseXFactor + 0.1); var l4 = map(greyscale, 0, 255, 35, 0); l4 *= mouseYFactor; push(); translate(posX, posY); rotate(greyscale / 255 * PI); line(0, 0, 0 + l4, 0 + l4); pop(); break; case 5: // greyscale to line relief var w5 = map(greyscale, 0, 255, 5, 0.2); strokeWeight(w5 * mouseYFactor + 0.1); // get neighbour pixel, limit it to image width var c2 = color(img.get(min(gridX + 1, img.width - 1), gridY)); stroke(c2); var greyscale2 = floor(red(c2) * 0.222 + green(c2) * 0.707 + blue(c2) * 0.071); var h5 = 50 * mouseXFactor; var d1 = map(greyscale, 0, 255, h5, 0); var d2 = map(greyscale2, 0, 255, h5, 0); line(posX - d1, posY + d1, posX + tileWidth - d2, posY + d2); break; case 6: // pixel color to fill, greyscale to ellipse size var w6 = map(greyscale, 0, 255, 25, 0); noStroke(); fill(c); ellipse(posX, posY, w6 * mouseXFactor, w6 * mouseXFactor); break; case 7: stroke(c); var w7 = map(greyscale, 0, 255, 5, 0.1); strokeWeight(w7); fill(255, 255 * mouseXFactor); push(); translate(posX, posY); rotate(greyscale / 255 * PI * mouseYFactor); rect(0, 0, 15, 15); pop(); break; case 8: noStroke(); fill(greyscale, greyscale * mouseXFactor, 255 * mouseYFactor); rect(posX, posY, 3.5, 3.5); rect(posX + 4, posY, 3.5, 3.5); rect(posX, posY + 4, 3.5, 3.5); rect(posX + 4, posY + 4, 3.5, 3.5); break; case 9: stroke(255, greyscale, 0); noFill(); push(); translate(posX, posY); rotate(greyscale / 255 * PI); strokeWeight(1); rect(0, 0, 15 * mouseXFactor, 15 * mouseYFactor); var w9 = map(greyscale, 0, 255, 15, 0.1); strokeWeight(w9); stroke(0, 70); ellipse(0, 0, 10, 5); pop(); break; } } } } function keyReleased() { if (key == 's' || key == 'S') saveCanvas(gd.timestamp(), 'png'); // change draw mode if (key == '1') drawMode = 1; if (key == '2') drawMode = 2; if (key == '3') drawMode = 3; if (key == '4') drawMode = 4; if (key == '5') drawMode = 5; if (key == '6') drawMode = 6; if (key == '7') drawMode = 7; if (key == '8') drawMode = 8; if (key == '9') drawMode = 9; } <|start_filename|>02_M/M_1_3_01/sketch.js<|end_filename|> // M_1_3_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draws a chart based on noise values. * * MOUSE * position x : specify noise input range * click : new noise line * * KEYS * s : save png */ 'use strict'; var sketch = function(p) { p.setup = function() { p.createCanvas(1024,256); p.strokeWeight(1); p.strokeJoin(p.ROUND); }; p.draw = function() { p.background(255); // line p.stroke(0,130,164); p.noFill(); var noiseXRange = p.mouseX / 10; console.log('noiseXRange: 0 - ' + noiseXRange); p.beginShape(); for (var x = 0; x < p.width; x += 10) { var noiseX = p.map(x, 0, p.width, 0, noiseXRange); var y = p.noise(noiseX) * p.height; p.vertex(x,y); }; p.endShape(); // dots p.noStroke(); p.fill(0); for (var x = 0; x < p.width; x += 10) { var noiseX = p.map(x, 0, p.width, 0, noiseXRange); var y = p.noise(noiseX) * p.height; p.ellipse(x,y,3,3); } }; p.mousePressed = function() { p.noiseSeed(p.random(100000)); }; p.keyReleased = function(){ if (p.key == 's' || p.key == 'S') p.saveCanvas(gd.timestamp(), 'png'); }; }; var myp5 = new p5(sketch); <|start_filename|>01_P/P_3_2_3_01/sketch.js<|end_filename|> // P_3_2_3_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * fontgenerator with dynamic elements. letter ouline consist of linked agents. * * MOUSE * press + position x : letter distortion * * KEYS * a-z : text input (keyboard) * alt : freeze current state * del, backspace : clear screen * ctrl : save png */ var typedKey = 'a'; var fontPath; var spacing = 20; var spaceWidth = 80; // width of letter ' ' var fontSize = 200; var lineSpacing = fontSize * 1.2; var textW = 0; var letterX = 50 + spacing; var letterY = lineSpacing; var stepSize = 2; var danceFactor = 1; var font; var pnts; var freeze = false; function setup() { createCanvas(windowWidth, windowHeight); noLoop(); opentype.load('data/FreeSansNoPunch.otf', function(err, f) { if (err) { print(err); } else { font = f; pnts = getPoints(typedKey); loop(); } }); } function draw() { if (!font) return; noFill(); push(); // translation according the actual writing position translate(letterX, letterY); // distortion on/off danceFactor = 1; if (mouseIsPressed && mouseButton == LEFT) danceFactor = map(mouseX, 0, width, 0, 3); // are there points to draw? if (pnts.length > 0) { // let the points dance for (var i = 0; i < pnts.length; i++) { pnts[i].x += random(-stepSize, stepSize) * danceFactor; pnts[i].y += random(-stepSize, stepSize) * danceFactor; } // ------ lines: connected straight ------ strokeWeight(0.1); stroke(0); beginShape(); for (var i = 0; i < pnts.length; i++) { vertex(pnts[i].x, pnts[i].y); ellipse(pnts[i].x, pnts[i].y, 7, 7); } vertex(pnts[0].x, pnts[0].y); endShape(); // ------ lines: connected rounded ------ /* strokeWeight(0.08); beginShape(); // start controlpoint curveVertex(pnts[pnts.length-1].x, pnts[pnts.length-1].y); // only these points are drawn for (var i = 0; i < pnts.length; i++) { curveVertex(pnts[i].x, pnts[i].y); } curveVertex(pnts[0].x, pnts[0].y); // end controlpoint curveVertex(pnts[1].x, pnts[1].y); endShape(); */ } pop(); } function getPoints() { fontPath = font.getPath(typedKey, 0, 0, 200); var path = new g.Path(fontPath.commands); path = g.resampleByLength(path, 25); textW = path.bounds().width; // remove all commands without a coordinate for (var i = path.commands.length - 1; i >= 0 ; i--) { if (path.commands[i].x == undefined) { path.commands.splice(i, 1); } } return path.commands; } function keyReleased() { // export png if (keyCode == CONTROL) saveCanvas(gd.timestamp(), 'png'); if (keyCode == ALT) { // switch loop on/off freeze = !freeze; if (freeze) { noLoop(); } else { loop(); } } } function keyPressed() { switch (keyCode) { case ENTER: case RETURN: typedKey = ''; pnts = getPoints(typedKey); letterY += lineSpacing; letterX = 50; break; case BACKSPACE: case DELETE: background(255); typedKey = ''; pnts = getPoints(typedKey); letterX = 50; letterY = lineSpacing; freeze = false; loop(); break; } } function keyTyped() { if (keyCode >= 32) { if (keyCode == 32) { typedKey = ''; letterX += textW + spaceWidth; pnts = getPoints(typedKey); } else { typedKey = key; letterX += textW + spacing; pnts = getPoints(typedKey); } freeze = false; loop(); } } <|start_filename|>02_M/M_6_1_03/Node.js<|end_filename|> var Node = function(x, y, minX, maxX, minY, maxY) { p5.Vector.call(this, x, y, 0); this.minX = Number.MIN_VALUE || minX; this.maxX = Number.MAX_VALUE || maxX; this.minY = Number.MIN_VALUE || minY; this.maxY = Number.MAX_VALUE || maxY; this.radius = 200; // Radius of impact this.ramp = 1; // Influences the shape of the function this.strength = -1; // Strength: positive value attracts, negative value repels this.damping = 0.5; this.velocity = myp5.createVector(); this.pVelocity = myp5.createVector(); this.maxVelocity = 10; }; Node.prototype = Object.create(p5.Vector.prototype); Node.prototype.attractNodes = function(nodeArray) { for (var i = 0; i < nodeArray.length; i++) { var otherNode = nodeArray[i]; // Stop when empty if (otherNode === undefined) break; // Continue from the top when node is itself if (otherNode === this) continue; this.attract(otherNode); } }; Node.prototype.attract = function(otherNode) { var thisNodeVector = myp5.createVector(this.x, this.y); var otherNodeVector = myp5.createVector(otherNode.x, otherNode.y); var d = thisNodeVector.dist(otherNodeVector); if (d > 0 && d < this.radius) { var s = myp5.pow(d / this.radius, 1 / this.ramp); var f = s * 9 * this.strength * (1 / (s + 1) + ((s - 3) / 4)) / d; var df = thisNodeVector.sub(otherNodeVector); df.mult(f); otherNode.velocity.x += df.x; otherNode.velocity.y += df.y; } }; Node.prototype.update = function() { this.velocity.limit(this.maxVelocity); this.x += this.velocity.x; this.y += this.velocity.y; if (this.x < this.minX) { this.x = this.minX - (this.x - this.minX); this.velocity.x = -this.velocity.x; } if (this.x > this.maxX) { this.x = this.maxX - (this.x - this.maxX); this.velocity.x = -this.velocity.x; } if (this.y < this.minY) { this.y = this.minY - (this.y - this.minY); this.velocity.y = -this.velocity.y; } if (this.y > this.maxY) { this.y = this.maxY - (this.y - this.maxY); this.velocity.y = -this.velocity.y; } this.velocity.mult(1 - this.damping); }; Node.prototype.constructor = Node; <|start_filename|>01_P/P_2_1_4_03/sketch.js<|end_filename|> // P_2_1_4_03 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // <NAME>, <NAME>, <NAME>, <NAME> // with contributions by <NAME> and <NAME> // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * Sliders arranged in a pattern * * DRAG : move the sliders around * * CONTRIBUTED BY * [<NAME>](http://jk-lee.com) * * INSPIRED BY * [<NAME>](http://shiffman.net/) */ 'use strict'; var w = 600; var h = 600; var sliderCount; var sliderWidth; var sliderHeight = 17; var padding = 10; var sliderMin = 0; var sliderMax = 100; function setup() { createCanvas(800,800); // get the number of sliders based on w & h sliderWidth = w / 2; sliderCount = ceil(sliderWidth / sliderHeight); noLoop(); } function draw() { background(48, 58, 118); // topleft - horizontal for (var i = 0; i <= sliderCount; i++){ var sval = map(i, sliderCount,0, sliderMin, sliderMax); createSlider(sliderMin, sliderMax, sval) .position(padding, i * sliderHeight + padding) .style('width', sliderWidth + 'px'); } // bottomright - horizontal for (var i = 0; i <= sliderCount; i++){ var sval = map(i, sliderCount,0, sliderMin, sliderMax); createSlider(sliderMin, sliderMax, sval) .position(sliderWidth + padding * 3, sliderWidth + padding * 2 + i * sliderHeight) .style('width', sliderWidth + 'px'); } // topright - vertical for (var i = 0; i <= sliderCount; i++){ var sval = map(i, 0,sliderCount, sliderMin, sliderMax); createSlider(sliderMin, sliderMax, sval) .position(sliderWidth / 2 + padding * 2 + i * sliderHeight, sliderWidth / 2 + padding) .style('width', sliderWidth + 'px').style('transform', 'rotate(' + 90 + 'deg)'); } // bottomleft - vertical for (var i = 0; i <= sliderCount; i++){ var sval = map(i, sliderCount,0, sliderMin, sliderMax); createSlider(sliderMin, sliderMax, sval) .position(sliderWidth / 2 - i * sliderHeight + padding * 2, sliderWidth + sliderWidth / 2 + padding * 3) .style('width', sliderWidth + 'px').style('transform', 'rotate(' + 90 + 'deg)'); } }
GangsHub/Code-Package-p5.js
<|start_filename|>Pods/Target Support Files/NibDesignable/NibDesignable-umbrella.h<|end_filename|> #import <UIKit/UIKit.h> FOUNDATION_EXPORT double NibDesignableVersionNumber; FOUNDATION_EXPORT const unsigned char NibDesignableVersionString[];
rdgborges/VivaRating
<|start_filename|>Assets/Editor/Vuforia/SampleOrientationSetter.cs<|end_filename|> /*=============================================================================== Copyright (c) 2016 PTC Inc. All Rights Reserved. Confidential and Proprietary - Protected under copyright and other laws. Vuforia is a trademark of PTC Inc., registered in the United States and other countries. ===============================================================================*/ using System.IO; using UnityEditor; using UnityEngine; [InitializeOnLoad] public static class SampleOrientationSetter { private static readonly string VUFORIA_SAMPLE_ORIENTATION_SETTINGS = "VUFORIA_SAMPLE_ORIENTATION_SETTINGS"; static SampleOrientationSetter() { EditorApplication.update += UpdateOrientationSettings; } static void UpdateOrientationSettings() { // Unregister callback (executed only once) EditorApplication.update -= UpdateOrientationSettings; BuildTargetGroup androidBuildTarget = BuildTargetGroup.Android; string androidSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(androidBuildTarget); androidSymbols = androidSymbols ?? ""; if (!androidSymbols.Contains(VUFORIA_SAMPLE_ORIENTATION_SETTINGS)) { // Set default orientation to portrait Debug.Log("Setting default orientation to Portrait."); PlayerSettings.defaultInterfaceOrientation = UIOrientation.Portrait; // Here we set the scripting define symbols for Android // so we can remember that the settings were set once. PlayerSettings.SetScriptingDefineSymbolsForGroup(androidBuildTarget, androidSymbols + ";" + VUFORIA_SAMPLE_ORIENTATION_SETTINGS); } } }
Wact/Impulse
<|start_filename|>infoview/src/main/java/com/marcoscg/infoview/InfoView.java<|end_filename|> package com.marcoscg.infoview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /** * Created by marco on 02/10/2017. */ public class InfoView extends RelativeLayout { private TextView title, message; private ImageView image; private Button tryAgain; private OnTryAgainClickListener onTryAgainClickListener; public interface OnTryAgainClickListener { public void onTryAgainClick(); } public InfoView(Context context) { super(context); init(null, 0); } public InfoView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public InfoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } public InfoView setTitle(String title) { if (this.title != null) this.title.setText(title); return this; } public InfoView setTitleRes(@StringRes int titleRes) { if (this.title != null) this.title.setText(getStr(titleRes)); return this; } public InfoView setMessage(String message) { if (this.message != null) this.message.setText(message); return this; } public InfoView setMessageRes(@StringRes int messageRes) { if (this.message != null) this.message.setText(getStr(messageRes)); return this; } public InfoView setIconDrawable(Drawable iconDrawable) { if (this.image != null) this.image.setImageDrawable(iconDrawable); return this; } public InfoView setIconBitmap(Bitmap iconBitmap) { if (this.image != null) this.image.setImageBitmap(iconBitmap); return this; } public InfoView setIconRes(@DrawableRes int iconRes) { if (this.image != null) this.image.setImageResource(iconRes); return this; } public InfoView setButtonText(String buttonText) { if (this.tryAgain != null) this.tryAgain.setText(buttonText); return this; } public InfoView setButtonTextRes(@StringRes int buttonTextRes) { if (this.tryAgain != null) this.tryAgain.setText(getStr(buttonTextRes)); return this; } public InfoView setButtonTextColor(@ColorInt int textColor) { if (this.tryAgain != null) this.tryAgain.setTextColor(textColor); return this; } public InfoView setButtonTextColorRes(@ColorRes int textColor) { if (this.tryAgain != null) this.tryAgain.setTextColor(ContextCompat.getColor(getContext(), textColor)); return this; } public InfoView setOnTryAgainClickListener(OnTryAgainClickListener listener) { onTryAgainClickListener = listener; return this; } public InfoView setProgress(boolean setProgress) { if (setProgress) { findViewById(R.id.iv_container).setVisibility(INVISIBLE); findViewById(R.id.iv_progress_bar).setVisibility(VISIBLE); } else { findViewById(R.id.iv_container).setVisibility(VISIBLE); findViewById(R.id.iv_progress_bar).setVisibility(GONE); } return this; } public InfoView setShowButton(boolean showButton) { if (showButton) tryAgain.setVisibility(VISIBLE); else tryAgain.setVisibility(GONE); return this; } private void init(AttributeSet attrs, int defStyle) { inflate(getContext(), R.layout.info_view_layout, this); title = (TextView) findViewById(R.id.iv_title); message = (TextView) findViewById(R.id.iv_message); image = (ImageView) findViewById(R.id.iv_image); tryAgain = (Button) findViewById(R.id.iv_try_again); tryAgain.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (onTryAgainClickListener!=null) onTryAgainClickListener.onTryAgainClick(); } }); if (attrs != null) { String title = "", message = "", buttonText = ""; Drawable icon = null; int buttonTextColor = 0; TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.InfoView, defStyle, 0); try { title = a.getString(R.styleable.InfoView_iv_title); message = a.getString(R.styleable.InfoView_iv_message); icon = a.getDrawable(R.styleable.InfoView_iv_icon); buttonText = a.getString(R.styleable.InfoView_iv_buttonText); buttonTextColor = a.getColor(R.styleable.InfoView_iv_buttonTextColor, 0); setShowButton(a.getBoolean(R.styleable.InfoView_iv_showButton, true)); } finally { a.recycle(); } this.title.setText(title); this.message.setText(message); if (icon != null) this.image.setImageDrawable(icon); this.tryAgain.setText(buttonText); if (buttonTextColor != 0) { this.tryAgain.setTextColor(buttonTextColor); } } } private String getStr (@StringRes int resId) { return getContext().getResources().getString(resId); } } <|start_filename|>app/src/main/java/com/marcoscg/infoviewsample/MainActivity.java<|end_filename|> package com.marcoscg.infoviewsample; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.marcoscg.infoview.InfoView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final InfoView infoView = (InfoView) findViewById(R.id.info_view); /* infoView.setTitle("Oops!"); infoView.setMessage("That should not have happened."); infoView.setButtonText("Try again"); infoView.setButtonTextColorRes(R.color.colorAccent); */ infoView.setOnTryAgainClickListener(new InfoView.OnTryAgainClickListener() { @Override public void onTryAgainClick() { Toast.makeText(MainActivity.this, "Try again clicked!", Toast.LENGTH_SHORT).show(); emulateLoading(infoView); } }); // This will simulate a 3 seconds loading process emulateLoading(infoView); } private void emulateLoading(final InfoView infoView) { infoView.setProgress(true); new Handler().postDelayed(new Runnable() { @Override public void run() { infoView.setProgress(false); } }, 3000); } }
marcoscgdev/InfoView
<|start_filename|>src/pers/adlered/liteftpd/logger/enums/Levels.java<|end_filename|> package pers.adlered.liteftpd.logger.enums; public enum Levels { ERROR, WARN, INFO, DEBUG } <|start_filename|>src/pers/adlered/liteftpd/logger/enums/Types.java<|end_filename|> package pers.adlered.liteftpd.logger.enums; public enum Types { /* SYS: System message; RECV: Receive task status; SEND: Send task status; TRANS: Transition task status; */ SYS, RECV, SEND, TRANS } <|start_filename|>src/pers/adlered/liteftpd/dict/Dict.java<|end_filename|> package pers.adlered.liteftpd.dict; import pers.adlered.liteftpd.tool.GoodXX; import pers.adlered.liteftpd.variable.Variable; /** * <h3>LiteFTPD-UNIX</h3> * <p>Store status messages with response format.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class Dict { private static String lang = "en_us"; public static void init(String lang) { lang = lang.toLowerCase(); Dict.lang = lang; } public static String gbEncodeOK(String ip) { if (lang.equals("zh_cn")) return StatusCode.SERVICEREADY + "-LiteFTPD" + Dict.newLine + ">>> 编码已适应Windows FTP客户端,您现在看到的这条信息应是正常的简体中文。" + Dict.newLine + ">>> 你的IP地址: " + ip + "" + Dict.newLine + "220" + " :) " + Variable.welcomeMessage + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.SERVICEREADY + "-LiteFTPD" + Dict.newLine + ">>> 编码已适应Windows FTP客户端,您现在看到的这条信息应是正常的简体中文。" + Dict.newLine + ">>> Your IP address: " + ip + "" + Dict.newLine + "220" + " :) " + Variable.welcomeMessage + "" + Dict.newLine; return null; } public static String rest(String restAt) { if (lang.equals("zh_cn")) return StatusCode.WAIT + " 断点续传已设定于 " + restAt + ". 发送 STORE 或 RETRIEVE 以继续." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.WAIT + " Restarting at " + restAt + ". Send STORE or RETRIEVE." + Dict.newLine; return null; } public static String noSuchFile(String path) { if (lang.equals("zh_cn")) return StatusCode.ERRTARGET + " " + path + ": 没有这个文件." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.ERRTARGET + " " + path + ": No such file." + Dict.newLine; return null; } public static String fileSize(long size) { if (lang.equals("zh_cn")) return StatusCode.FILESTATUS + " " + size + Dict.newLine; if (lang.equals("en_us")) return StatusCode.FILESTATUS + " " + size + Dict.newLine; return null; } public static String openAscii(String path) { if (lang.equals("zh_cn")) return StatusCode.STATUSOK + " 为 " + path + " 开启 ASCII 模式传输数据." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.STATUSOK + " Opening ASCII mode data connection for " + path + "." + Dict.newLine; return null; } public static String openBin(String path) { if (lang.equals("zh_cn")) return StatusCode.STATUSOK + " 为 " + path + " 开启 BINARY 模式传输数据." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.STATUSOK + " Opening BINARY mode data connection for " + path + "." + Dict.newLine; return null; } public static String pasvDataFailed() { if (lang.equals("zh_cn")) return StatusCode.UNAVAILABLE + " 被动模式接口无连接." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.UNAVAILABLE + " Passive port is not connected." + Dict.newLine; return null; } public static String openPasvAscii(String path, long fileLength) { if (lang.equals("zh_cn")) return StatusCode.STATUSOK + " 启动 ASCII 模式数据传输: " + path + " (" + fileLength + " 字节)" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.STATUSOK + " Opening ASCII mode data connection for " + path + " (" + fileLength + " Bytes)" + Dict.newLine; return null; } public static String openPasvBin(String path, long fileLength) { if (lang.equals("zh_cn")) return StatusCode.STATUSOK + " 启动 BINARY 模式数据传输: " + path + " (" + fileLength + " 字节)" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.STATUSOK + " Opening BINARY mode data connection for " + path + " (" + fileLength + " Bytes)" + Dict.newLine; return null; } public static String pasvMode(String[] IPADD, int calcPort, int randomSub) { if (lang.equals("zh_cn")) return StatusCode.PASSIVE + " Entering Passive Mode " + "(" + IPADD[0] + "," + IPADD[1] + "," + IPADD[2] + "," + IPADD[3] + "," + calcPort + "," + randomSub + ")" + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.PASSIVE + " Entering Passive Mode " + "(" + IPADD[0] + "," + IPADD[1] + "," + IPADD[2] + "," + IPADD[3] + "," + calcPort + "," + randomSub + ")" + "" + Dict.newLine; return null; } public static String portSuccess() { if (lang.equals("zh_cn")) return StatusCode.SUCCESS + " PORT 命令已执行." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.SUCCESS + " PORT Command successful." + Dict.newLine; return null; } public static String rntoSuccess() { if (lang.equals("zh_cn")) return StatusCode.CORRECT + " RNTO 命令已执行." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CORRECT + " RNTO command successful." + Dict.newLine; return null; } public static String rnfrSuccess() { if (lang.equals("zh_cn")) return StatusCode.WAIT + " 文件或文件夹已选定, 请提供目标位置." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.WAIT + " File or directory exists, ready for destination name." + Dict.newLine; return null; } public static String deleSuccess() { if (lang.equals("zh_cn")) return StatusCode.CORRECT + " DELE 命令已执行." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CORRECT + " DELE command successful." + Dict.newLine; return null; } public static String rmdSuccess() { if (lang.equals("zh_cn")) return StatusCode.CORRECT + " RMD 命令已执行." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CORRECT + " RMD command successful." + Dict.newLine; return null; } public static String createFailed(String path) { if (lang.equals("zh_cn")) return StatusCode.ERRTARGET + " " + path + ": 创建失败." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.ERRTARGET + " " + path + ": Failed to create." + Dict.newLine; return null; } public static String dirCreated(String path) { if (lang.equals("zh_cn")) return StatusCode.CPATH + " 目录 \"" + path + "\" 已创建." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CPATH + " \"" + path + "\" directory created." + Dict.newLine; return null; } public static String commandOK() { if (lang.equals("zh_cn")) return StatusCode.SUCCESS + " 命令已执行." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.SUCCESS + " Command okay." + Dict.newLine; return null; } public static String unixType() { if (lang.equals("zh_cn")) return StatusCode.NAME + " UNIX Type: L8" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.NAME + " UNIX Type: L8" + Dict.newLine; return null; } public static String unknownCommand() { if (lang.equals("zh_cn")) return StatusCode.CMDUNKNOWN + " 未知命令." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CMDUNKNOWN + " Command don't understood." + Dict.newLine; return null; } public static String notFound(String path) { if (lang.equals("zh_cn")) return StatusCode.ERRTARGET + " " + path + ": 文件或文件夹不存在." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.ERRTARGET + " " + path + ": No such file or directory." + Dict.newLine; return null; } public static String changeDir(String path) { if (lang.equals("zh_cn")) return StatusCode.CORRECT + " 目录已更改至 " + path + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CORRECT + " Directory changed to " + path + Dict.newLine; return null; } public static String list() { if (lang.equals("zh_cn")) return StatusCode.STATUSOK + " 正在传输 ASCII 数据, 请稍候." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.STATUSOK + " Opening ASCII mode data, please wait." + Dict.newLine; return null; } public static String type(String type) { if (lang.equals("zh_cn")) return StatusCode.SUCCESS + " 传输模式已设定为 " + type + "." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.SUCCESS + " Type set to " + type + "." + Dict.newLine; return null; } public static String currentDir(String path) { if (lang.equals("zh_cn")) return StatusCode.CPATH + " \"" + path + "\" 是当前的目录." + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CPATH + " \"" + path + "\" is current directory." + "" + Dict.newLine; return null; } public static String notSupportSITE() { if (lang.equals("zh_cn")) return StatusCode.ERRSYNTAX + " SITE 选项不受支持." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.ERRSYNTAX + " SITE option not supported." + Dict.newLine; return null; } public static String features() { if (lang.equals("zh_cn")) return StatusCode.STATUS + "-特性:" + Dict.newLine + "UTF8" + Dict.newLine + StatusCode.STATUS + " 结束" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.STATUS + "-Features:" + Dict.newLine + "UTF8" + Dict.newLine + StatusCode.STATUS + " End" + Dict.newLine; return null; } public static String alreadyLogIn() { if (lang.equals("zh_cn")) return StatusCode.CMDUNKNOWN + " 你已经登录过了." + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CMDUNKNOWN + " You have already logged in." + "" + Dict.newLine; return null; } public static String wrongPassword() { if (lang.equals("zh_cn")) return StatusCode.NOTLOGIN + " 抱歉, 密码错误." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.NOTLOGIN + " Sorry, the password is wrong." + Dict.newLine; return null; } public static String loggedIn(String username) { if (lang.equals("zh_cn")) return StatusCode.LOGGED + "-" + Dict.newLine + "===------===" + Dict.newLine + ">>> :) Good " + GoodXX.getTimeAsWord() + ", " + username + "!" + Dict.newLine + ">>> LiteFTPD https://github.com/AdlerED/LiteFTPD-UNIX" + Dict.newLine + "===------===" + Dict.newLine + "IS THE CHINESE ON THE RIGHT NORMAL? -> 中文 <- If not, type \"quote gb\" to change the encode type." + Dict.newLine + "230 OK" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.LOGGED + "-" + "" + Dict.newLine + "===------===" + Dict.newLine + ">>> :) Good " + GoodXX.getTimeAsWord() + ", " + username + "!" + Dict.newLine + ">>> LiteFTPD https://github.com/AdlerED/LiteFTPD-UNIX" + Dict.newLine + "===------===" + Dict.newLine + "IS THE CHINESE ON THE RIGHT NORMAL? -> 中文 <- If not, type \"quote gb\" to change the encode type." + Dict.newLine + "230 OK" + Dict.newLine; return null; } public static String tooMuchLoginInUser(String username) { if (lang.equals("zh_cn")) return StatusCode.NOTLOGIN + " 抱歉, 用户 \"" + username + "\" 连接数过多, 请稍候重试." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.NOTLOGIN + " Sorry, user \"" + username + "\" has too much login, please try again at later." + Dict.newLine; return null; } public static String utf8(boolean status) { if (lang.equals("zh_cn")) { if (status) return StatusCode.SUCCESS + " OPTS UTF8 命令已执行 - UTF8 编码现在已开启." + Dict.newLine; else return StatusCode.SUCCESS + " OPTS UTF8 命令已执行 - UTF8 编码现在已停用." + Dict.newLine; } if (lang.equals("en_us")) { if (status) return StatusCode.SUCCESS + " OPTS UTF8 command successful - UTF8 encoding now ON." + Dict.newLine; else return StatusCode.SUCCESS + " OPTS UTF8 command successful - UTF8 encoding now OFF." + Dict.newLine; } return null; } public static String bye() { if (lang.equals("zh_cn")) return StatusCode.SERVICESTOP + " :) 再见!" + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.SERVICESTOP + " :) See ya!" + "" + Dict.newLine; return null; } public static String passwordRequired(String username) { if (lang.equals("zh_cn")) return StatusCode.PASSREQ + " 请输入用户 " + username + " 的密码." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.PASSREQ + " Password required for " + username + "." + Dict.newLine; return null; } public static String permissionDenied() { if (lang.equals("zh_cn")) return StatusCode.ERRTARGET + " 没有执行此操作的权限." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.ERRTARGET + " Permission denied." + Dict.newLine; return null; } public static String transferCompleteInAsciiMode(long fileLength, long time, float averageTime) { if (lang.equals("zh_cn")) return StatusCode.CLOSED + "-传输完毕. " + fileLength + " 字节在 " + time + " 秒内传输完成. 平均 " + averageTime + " KB/秒." + Dict.newLine + StatusCode.CLOSED + " 你正在使用 ASCII 模式传输文件. 如果你的文件是损坏的, 输入 \"binary\" 然后再重试一次." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CLOSED + "-Transfer complete. " + fileLength + " bytes saved in " + time + " second. " + averageTime + " KB/sec." + Dict.newLine + StatusCode.CLOSED + " You are using ASCII mode to transfer files. If you find that the file is corrupt, type \"binary\" and try again." + Dict.newLine; return null; } public static String transferComplete(long fileLength, long time, float averageTime) { if (lang.equals("zh_cn")) return StatusCode.CLOSED + " 传输完毕. " + fileLength + " 字节在 " + time + " 秒内传输完毕. 平均 " + averageTime + " KB/秒." + Dict.newLine; if (lang.equals("en_us")) return StatusCode.CLOSED + " Transfer complete. " + fileLength + " bytes saved in " + time + " second. " + averageTime + " KB/sec." + Dict.newLine; return null; } public static String connectedMessage(String ip) { if (lang.equals("zh_cn")) return StatusCode.SERVICEREADY + "-LiteFTPD" + Dict.newLine + ">>> 请登录." + Dict.newLine + ">>> 你的IP地址: " + ip + Dict.newLine + "220" + " :) " + Variable.welcomeMessage + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.SERVICEREADY + "-LiteFTPD" + Dict.newLine + ">>> Please log in." + Dict.newLine + ">>> Your IP address: " + ip + Dict.newLine + "220" + " :) " + Variable.welcomeMessage + "" + Dict.newLine; return null; } public static String closedInReason(String reason) { if (lang.equals("zh_cn")) return "LiteFTPD > :( 抱歉, 服务端已经关闭了连接! 原因: " + reason + "." + Dict.newLine; if (lang.equals("en_us")) return "LiteFTPD > :( Sorry, the connection is closed from server! Reason: " + reason + "." + Dict.newLine; return null; } public static String outOfOnlineLimit() { if (lang.equals("zh_cn")) return StatusCode.NOTLOGIN + " :( 在线用户数过多." + "" + Dict.newLine; if (lang.equals("en_us")) return StatusCode.NOTLOGIN + " :( Too much users online." + "" + Dict.newLine; return null; } public static String onlineStr() { if (lang.equals("zh_cn")) return "在线"; if (lang.equals("en_us")) return "Online"; return null; } public static String clearStr() { if (lang.equals("zh_cn")) return "清除"; if (lang.equals("en_us")) return "Clear"; return null; } public static String actionStr() { if (lang.equals("zh_cn")) return "操作"; if (lang.equals("en_us")) return "Action"; return null; } public static String connectionsStr() { if (lang.equals("zh_cn")) return "连接数"; if (lang.equals("en_us")) return "Connection"; return null; } public static String t() { if (lang.equals("zh_cn")) return ""; if (lang.equals("en_us")) return ""; return null; } public static final String newLine = "\r\n"; } <|start_filename|>src/pers/adlered/liteftpd/tool/GoodXX.java<|end_filename|> package pers.adlered.liteftpd.tool; import java.text.SimpleDateFormat; import java.util.Date; /** * <h3>LiteFTPD-UNIX</h3> * <p>Greetings for users.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class GoodXX { public static String getTimeAsWord() { Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat("HH"); String str = df.format(date); int a = Integer.parseInt(str); if (a >= 0 && a <= 12) { return "morning"; } if (a > 12 && a <= 13) { return "noon"; } if (a > 13 && a <= 17) { return "afternoon"; } if (a > 17 && a <= 19) { return "evening"; } if (a > 19 && a <= 24) { return "night"; } return ""; } } <|start_filename|>src/pers/adlered/liteftpd/variable/OnlineUserController.java<|end_filename|> package pers.adlered.liteftpd.variable; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.user.status.Online; /** * <h3>LiteFTPD-UNIX</h3> * <p>Variable bean.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class OnlineUserController { public static void printOnline() { int ipSize = Online.ipRuleOnline.size(); int userSize = Online.userRuleOnline.size(); Logger.log(Types.SYS, Levels.INFO, "Online Users: " + userSize + " Connections: " + ipSize); } public static void reduceOnline(String ipAddress, String username) { ; for (int i = 0; i < Online.ipRuleOnline.size(); i++) { if (Online.ipRuleOnline.get(i).getIp().equals(ipAddress)) { Online.ipRuleOnline.remove(i); break; } } for (int i = 0; i < Online.userRuleOnline.size(); i++) { if (Online.userRuleOnline.get(i).getUsername().equals(username)) { Online.userRuleOnline.remove(i); break; } } } } <|start_filename|>src/pers/adlered/liteftpd/logger/Filter.java<|end_filename|> package pers.adlered.liteftpd.logger; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.variable.Variable; /** * <h3>LiteFTPD-UNIX</h3> * <p>When Logger received a log, Filter will check it's level to decide display or not.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 15:17 **/ public class Filter { public static boolean fil(Levels level) { boolean status = false; switch (level) { case DEBUG: if (Variable.debugLevel >= 4) { status = true; } break; case ERROR: if (Variable.debugLevel >= 3) { status = true; } break; case WARN: if (Variable.debugLevel >= 2) { status = true; } break; case INFO: if (Variable.debugLevel >= 1) { status = true; } break; } return status; } } <|start_filename|>src/pers/adlered/liteftpd/user/status/bind/IPAddressBind.java<|end_filename|> package pers.adlered.liteftpd.user.status.bind; /** * <h3>LiteFTPD-UNIX</h3> * <p>A bind of server/client IP Address.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class IPAddressBind { private String IPADD; private String SRVIPADD; public IPAddressBind(String IPADD, String SRVIPADD) { this.IPADD = IPADD; this.SRVIPADD = SRVIPADD; } public String getIPADD() { return IPADD; } public void setIPADD(String IPADD) { this.IPADD = IPADD; } public String getSRVIPADD() { return SRVIPADD; } public void setSRVIPADD(String SRVIPADD) { this.SRVIPADD = SRVIPADD; } } <|start_filename|>src/pers/adlered/liteftpd/user/info/bind/UserInfoBind.java<|end_filename|> package pers.adlered.liteftpd.user.info.bind; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import pers.adlered.liteftpd.user.status.bind.UserLimitBind; /** * <h3>LiteFTPD-UNIX</h3> * <p>存储在线用户详细信息</p> * * @author : https://github.com/AdlerED * @date : 2019-10-05 21:41 **/ public class UserInfoBind { private IpLimitBind ipLimitBind; private UserLimitBind userLimitBind; public UserInfoBind(IpLimitBind ipLimitBind, UserLimitBind userLimitBind) { this.ipLimitBind = ipLimitBind; this.userLimitBind = userLimitBind; } public IpLimitBind getIpLimitBind() { return ipLimitBind; } public void setIpLimitBind(IpLimitBind ipLimitBind) { this.ipLimitBind = ipLimitBind; } public UserLimitBind getUserLimitBind() { return userLimitBind; } public void setUserLimitBind(UserLimitBind userLimitBind) { this.userLimitBind = userLimitBind; } } <|start_filename|>src/pers/adlered/liteftpd/variable/Variable.java<|end_filename|> package pers.adlered.liteftpd.variable; /** * <h3>LiteFTPD-UNIX</h3> * <p>User interface settings.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class Variable { public static String user = "1;anonymous;;r;2;admin;123456;r"; public static String ipOnlineLimit = ""; public static String userOnlineLimit = ""; public static String speedLimit=""; public static int debugLevel = 4; public static int online = 0; public static long maxUserLimit = 100; public static int timeout = 100; public static int maxTimeout = 21600; public static boolean smartEncode = true; public static String defaultEncode = "UTF-8"; public static int port = 21; public static String welcomeMessage = ""; public static int minPort = 10240; public static int maxPort = 20480; } <|start_filename|>src/pers/adlered/liteftpd/tool/LocalAddress.java<|end_filename|> package pers.adlered.liteftpd.tool; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; /** * <h3>LiteFTPD-UNIX</h3> * <p>Get IP Address of the server.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class LocalAddress { public static List<String> getLocalIPList() { List<String> ipList = new ArrayList<String>(); try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); NetworkInterface networkInterface; Enumeration<InetAddress> inetAddresses; InetAddress inetAddress; String ip; while (networkInterfaces.hasMoreElements()) { networkInterface = networkInterfaces.nextElement(); inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { inetAddress = inetAddresses.nextElement(); if (inetAddress != null && inetAddress instanceof Inet4Address) { ip = inetAddress.getHostAddress(); ipList.add(ip); } } } } catch (SocketException e) { e.printStackTrace(); } return ipList; } } <|start_filename|>src/pers/adlered/liteftpd/wizard/init/PauseListen.java<|end_filename|> package pers.adlered.liteftpd.wizard.init; import pers.adlered.liteftpd.analyze.CommandAnalyze; import pers.adlered.liteftpd.analyze.PrivateVariable; import pers.adlered.liteftpd.user.status.bind.IPAddressBind; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.tool.Status; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import pers.adlered.liteftpd.variable.OnlineUserController; import pers.adlered.liteftpd.variable.Variable; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * <h3>LiteFTPD-UNIX</h3> * <p>Listening thread shutdown signal, and recycle the threads of this connection.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class PauseListen extends Thread { private PrivateVariable privateVariable = null; private Socket socket = null; private BufferedOutputStream bufferedOutputStream = null; private OutputStream outputStream = null; private BufferedInputStream bufferedInputStream = null; private InputStream inputStream = null; private IPAddressBind ipAddressBind = null; private Send send = null; private CommandAnalyze commandAnalyze = null; private Receive receive = null; private IpLimitBind ipLimitBind = null; private int timeout = 0; private boolean running = true; public PauseListen(PrivateVariable privateVariable, Socket socket, BufferedOutputStream bufferedOutputStream, OutputStream outputStream, BufferedInputStream bufferedInputStream, InputStream inputStream, IPAddressBind ipAddressBind, CommandAnalyze commandAnalyze, Receive receive, IpLimitBind ipLimitBind) { this.privateVariable = privateVariable; this.socket = socket; this.bufferedOutputStream = bufferedOutputStream; this.outputStream = outputStream; this.bufferedInputStream = bufferedInputStream; this.inputStream = inputStream; this.ipAddressBind = ipAddressBind; this.send = send; this.commandAnalyze = commandAnalyze; this.receive = receive; this.ipLimitBind = ipLimitBind; } public void setSend(Send send) { this.send = send; } @Override public void run() { String reason = "User quit manually"; int skipCount = 0; while (!privateVariable.interrupted) { if (privateVariable.isTimeoutLock()) { ++skipCount; resetTimeout(); } if (skipCount % 10 == 0 && skipCount != 0) { Logger.log(Types.SYS, Levels.DEBUG, ipAddressBind.getIPADD() + " skipped timeout: " + skipCount); if (skipCount > Variable.maxTimeout) { reason = "Time is out while in transmission."; break; } } // Display log every 10 seconds. if (timeout % 10 == 0 && timeout != 0) { Logger.log(Types.SYS, Levels.DEBUG, ipAddressBind.getIPADD() + " timeout: " + timeout + "=>" + Variable.timeout); } if (timeout >= Variable.timeout) { reason = "Time is out"; break; } try { ++timeout; Thread.sleep(1000); } catch (InterruptedException IE) { break; } } if (privateVariable.reason != null) { reason = privateVariable.reason; privateVariable.reason = null; } send.send(Dict.closedInReason(reason)); Logger.log(Types.SYS, Levels.INFO, "Shutting down " + ipAddressBind.getIPADD() + ", reason: " + reason); // Shutdown this hole connection. running = false; OnlineUserController.reduceOnline(socket.getInetAddress().getHostAddress(), privateVariable.getUsername()); OnlineUserController.printOnline(); try { // BufferedStream bufferedInputStream.close(); bufferedOutputStream.close(); // Stream inputStream.close(); outputStream.close(); // Socket socket.close(); } catch (Exception E) { E.getCause(); Logger.log(Types.SYS, Levels.WARN, "Shutting " + ipAddressBind.getIPADD() + " with errors."); } finally { // Variables bufferedInputStream = null; bufferedOutputStream = null; inputStream = null; outputStream = null; ipAddressBind = null; socket = null; privateVariable = null; send = null; commandAnalyze = null; receive = null; ipLimitBind = null; Logger.log(Types.SYS, Levels.DEBUG, "Called Garbage Collection."); System.gc(); Logger.log(Types.SYS, Levels.INFO, "Memory used: " + Status.memoryUsed()); } } public void resetTimeout() { timeout = 0; } public boolean isRunning() { return running; } } <|start_filename|>src/pers/adlered/liteftpd/user/UserProps.java<|end_filename|> package pers.adlered.liteftpd.user; /** * <h3>LiteFTPD-UNIX</h3> * <p>用户信息</p> * * @author : https://github.com/AdlerED * @date : 2019-10-04 19:16 **/ public class UserProps { private String password; private String permission; private String permitDir; private String defaultDir; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public String getPermitDir() { return permitDir; } public void setPermitDir(String permitDir) { this.permitDir = permitDir; } public String getDefaultDir() { return defaultDir; } public void setDefaultDir(String defaultDir) { this.defaultDir = defaultDir; } } <|start_filename|>src/pers/adlered/liteftpd/tool/CharsetSelector.java<|end_filename|> package pers.adlered.liteftpd.tool; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.variable.Variable; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; /** * <h3>LiteFTPD-UNIX</h3> * <p>Analyze string's encode.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class CharsetSelector { public static String getCharset(byte[] bytes) { // return guessEncoding(bytes); int UTF8ERR = 0; int GB2312ERR = 0; String UTF8 = null; String GB2312 = null; try { UTF8 = new String(bytes, StandardCharsets.UTF_8); GB2312 = new String(bytes, "GB2312"); } catch (UnsupportedEncodingException UEE) { // TODO UEE.printStackTrace(); } if (UTF8 != null) { int fromIndex = 0; int count = 0; while (true) { int index = UTF8.indexOf("�", fromIndex); if (-1 != index) { fromIndex = index + 1; count++; } else { break; } } while (true) { int index = UTF8.indexOf("ţ", fromIndex); if (-1 != index) { fromIndex = index + 1; count++; } else { break; } } while (true) { int index = UTF8.indexOf("Ƥ", fromIndex); if (-1 != index) { fromIndex = index + 1; count++; } else { break; } } UTF8ERR = count; Logger.log(Types.SYS, Levels.DEBUG, "UTF8 " + count); } if (GB2312 != null) { int fromIndex = 0; int count = 0; while (true) { int index = GB2312.indexOf("�", fromIndex); if (-1 != index) { fromIndex = index + 1; count++; } else { break; } } GB2312ERR = count; Logger.log(Types.SYS, Levels.DEBUG, "GB2312 " + count); } if (UTF8ERR < GB2312ERR) { return "UTF-8"; } else if (UTF8ERR > GB2312ERR) { return "GB2312"; } else { return Variable.defaultEncode; } } } <|start_filename|>src/pers/adlered/liteftpd/mode/PORT.java<|end_filename|> package pers.adlered.liteftpd.mode; import pers.adlered.liteftpd.analyze.PrivateVariable; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.user.status.bind.SpeedLimitBind; import pers.adlered.liteftpd.wizard.init.PauseListen; import pers.adlered.liteftpd.wizard.init.Send; import pers.adlered.liteftpd.variable.Variable; import java.io.*; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; /** * <h3>LiteFTPD-UNIX</h3> * <p>Passive mode.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class PORT extends Thread { private Socket socket = null; private Send send = null; private PrivateVariable privateVariable = null; private PauseListen pauseListen = null; private String listening = null; private File file = null; private String path = null; private String ip = null; private int port = -1; private boolean isASCII = true; SpeedLimitBind speedLimitBind = null; public PORT(Send send, PrivateVariable privateVariable, PauseListen pauseListen, String type, SpeedLimitBind speedLimitBind) { this.send = send; this.privateVariable = privateVariable; this.pauseListen = pauseListen; if (type.equals("I")) { isASCII = false; } this.speedLimitBind = speedLimitBind; } public void setTarget(String ip, int port) { this.ip = ip; this.port = port; } private boolean connect() { boolean result = true; try { Logger.log(Types.SYS, Levels.DEBUG, "Connecting to " + ip + ":" + port + "..."); Socket socket = new Socket(ip, port); this.socket = socket; } catch (UnknownHostException UHE) { result = false; } catch (IllegalArgumentException IAE) { result = false; } catch (IOException IOE) { result = false; } return result; } @Override public void run() { if (connect()) { try { Logger.log(Types.SYS, Levels.DEBUG, "Connected. Translating with " + socket.getLocalSocketAddress() + " to " + socket.getRemoteSocketAddress() + "..."); privateVariable.setTimeoutLock(true); if (pauseListen.isRunning()) { Logger.log(Types.SYS, Levels.DEBUG, "Port mode is in transmission."); long startTime = System.currentTimeMillis(); float kb = 0; long bts = 0; if (listening != null) { // To avoid bare line feeds. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream()); listening = listening.replaceAll("" + Dict.newLine, "\n"); listening = listening.replaceAll("\n", "" + Dict.newLine); if (Variable.smartEncode) { bufferedOutputStream.write(listening.getBytes(privateVariable.encode)); } else { bufferedOutputStream.write(listening.getBytes(Variable.defaultEncode)); } bufferedOutputStream.flush(); bufferedOutputStream.close(); bts = (listening.getBytes(privateVariable.encode)).length; } else if (file != null) { if (speedLimitBind.getDownloadSpeed() != 0) { FileInputStream fileInputStream = new FileInputStream(file); OutputStream outputStream = new DataOutputStream(socket.getOutputStream()); byte[] bytes = new byte[speedLimitBind.getDownloadSpeed() * 1024]; int len = -1; if (privateVariable.getRest() == 0l) { if (!isASCII) { // Not rest mode while ((len = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); Thread.sleep(1000); } outputStream.flush(); fileInputStream.close(); outputStream.close(); bts = file.length(); } else { FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); int length = -1; char[] chars = new char[speedLimitBind.getUploadSpeed() * 1024]; while ((length = bufferedReader.read(chars)) != -1) { outputStreamWriter.write(String.valueOf(chars, 0, length).replaceAll("\r", "").replaceAll("\n", "\r\n")); Thread.sleep(1000); } outputStreamWriter.flush(); fileReader.close(); outputStreamWriter.close(); outputStream.close(); bts = file.length(); } } else { // Rest mode on fileInputStream.skip(privateVariable.getRest()); while ((len = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); Thread.sleep(1000); } outputStream.flush(); fileInputStream.close(); outputStream.close(); bts = file.length() - privateVariable.getRest(); privateVariable.resetRest(); } } else { FileInputStream fileInputStream = new FileInputStream(file); OutputStream outputStream = new DataOutputStream(socket.getOutputStream()); byte[] bytes = new byte[8192]; int len = -1; if (privateVariable.getRest() == 0l) { if (!isASCII) { // Not rest mode while ((len = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } outputStream.flush(); fileInputStream.close(); outputStream.close(); bts = file.length(); } else { FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); String line; while ((line = bufferedReader.readLine()) != null) { outputStreamWriter.write(line + "\r\n"); } outputStreamWriter.flush(); fileReader.close(); outputStreamWriter.close(); outputStream.close(); bts = file.length(); } } else { // Rest mode on fileInputStream.skip(privateVariable.getRest()); while ((len = fileInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } outputStream.flush(); fileInputStream.close(); outputStream.close(); bts = file.length() - privateVariable.getRest(); privateVariable.resetRest(); } } } else if (path != null) { Logger.log(Types.RECV, Levels.DEBUG, "Port mode store. Path: " + path); File file = new File(path); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } FileOutputStream fileOutputStream = null; if (privateVariable.getRest() == 0l) { boolean deleted = file.delete(); Logger.log(Types.RECV, Levels.DEBUG, "The file is already exists but deleted: " + deleted); fileOutputStream = new FileOutputStream(file, false); } else { Logger.log(Types.RECV, Levels.DEBUG, "Continue file receive."); fileOutputStream = new FileOutputStream(file, true); } // FileOutputStream will be create a new file auto. if (speedLimitBind.getUploadSpeed() == 0) { if (!isASCII) { try { InputStream inputStream = socket.getInputStream(); byte[] bytes = new byte[8192]; int len = -1; long sTime = System.currentTimeMillis(); while ((len = inputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); } long eTime = (System.currentTimeMillis() - sTime) / 1000; if (eTime == 0) eTime = 1; float pSecond = file.length() / eTime; fileOutputStream.flush(); send.send(Dict.transferComplete(file.length(), eTime, pSecond)); inputStream.close(); fileOutputStream.close(); } catch (FileNotFoundException FNFE) { send.send(Dict.permissionDenied()); FNFE.printStackTrace(); } } else { try { FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); InputStream inputStream = socket.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; long sTime = System.currentTimeMillis(); while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line + "\n"); } long eTime = (System.currentTimeMillis() - sTime) / 1000; if (eTime == 0) eTime = 1; float pSecond = file.length() / eTime; bufferedWriter.flush(); send.send(Dict.transferCompleteInAsciiMode(file.length(), eTime, pSecond)); bufferedReader.close(); inputStreamReader.close(); inputStream.close(); bufferedWriter.close(); fileWriter.close(); } catch (FileNotFoundException FNFE) { send.send(Dict.permissionDenied()); FNFE.printStackTrace(); } } } else { if (!isASCII) { try { InputStream inputStream = socket.getInputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, speedLimitBind.getUploadSpeed() * 1024); int len = -1; long sTime = System.currentTimeMillis(); byte[] bytes = new byte[speedLimitBind.getUploadSpeed() * 1024]; while ((len = bufferedInputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); Thread.sleep(1000); } long eTime = (System.currentTimeMillis() - sTime) / 1000; if (eTime == 0) eTime = 1; float pSecond = file.length() / eTime; fileOutputStream.flush(); send.send(Dict.transferComplete(file.length(), eTime, pSecond)); inputStream.close(); fileOutputStream.close(); } catch (FileNotFoundException FNFE) { send.send(Dict.permissionDenied()); FNFE.printStackTrace(); } } else { try { FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); InputStream inputStream = socket.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); int len = -1; long sTime = System.currentTimeMillis(); char[] chars = new char[speedLimitBind.getUploadSpeed() * 1024]; while ((len = bufferedReader.read(chars)) != -1) { bufferedWriter.write(String.valueOf(chars, 0, len).replaceAll("\r\n", "\n")); Thread.sleep(1000); } long eTime = (System.currentTimeMillis() - sTime) / 1000; if (eTime == 0) eTime = 1; float pSecond = file.length() / eTime; bufferedWriter.flush(); send.send(Dict.transferCompleteInAsciiMode(file.length(), eTime, pSecond)); bufferedReader.close(); inputStreamReader.close(); inputStream.close(); bufferedWriter.close(); fileWriter.close(); } catch (FileNotFoundException FNFE) { send.send(Dict.permissionDenied()); FNFE.printStackTrace(); } } } privateVariable.resetRest(); } if (path != null) { socket.close(); } else { kb = bts / 1000; socket.close(); long endTime = (System.currentTimeMillis() - startTime) / 1000; if (endTime == 0) endTime = 1; float perSecond = kb / endTime; if (isASCII && listening == null) { send.send(Dict.transferCompleteInAsciiMode(bts, endTime, perSecond)); } else { send.send(Dict.transferComplete(bts, endTime, perSecond)); } } } } catch (SocketException SE) { Logger.log(Types.SYS, Levels.ERROR, "Listening stopped."); } catch (IOException IOE) { //TODO IOE.printStackTrace(); } catch (Exception E) { E.printStackTrace(); } finally { if (pauseListen.isRunning()) { privateVariable.setTimeoutLock(false); } send = null; privateVariable = null; pauseListen = null; socket = null; listening = null; file = null; Logger.log(Types.SYS, Levels.DEBUG, "PORT Closed."); } } else { privateVariable.setInterrupted(true); } } public void hello(String message) { listening = message; } public void hello(File file) { this.file = file; } public void helloSTOR(String path) { this.path = path; } public void stopSocket() { try { socket.shutdownInput(); socket.shutdownOutput(); socket.close(); Logger.log(Types.SYS, Levels.DEBUG, "Socket on " + socket.getLocalSocketAddress() + "stopped."); } catch (IOException IOE) { IOE.printStackTrace(); } catch (NullPointerException NPE) { Logger.log(Types.SYS, Levels.WARN, "Latest port mode port not connected. Closing forced."); } } } <|start_filename|>src/pers/adlered/liteftpd/logger/Logger.java<|end_filename|> package pers.adlered.liteftpd.logger; import pers.adlered.liteftpd.graphic.main.model.MainModels; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.enums.Types; /** * <h3>LiteFTPD-UNIX</h3> * <p>All logs will through here.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 15:18 **/ public class Logger { public static boolean log(Types type, Levels level, String log) { if (Filter.fil(level)) { // Can be logged System.out.println("[" + level + "]" + " " + "[" + type + "]" + " >> " + log); if (MainModels.guiReady) { MainModels.console.append("[" + level + "]" + " " + "[" + type + "]" + " >> " + log + "\n"); MainModels.console.setCaretPosition(MainModels.console.getDocument().getLength()); } return true; } else { // Cannot log return false; } } } <|start_filename|>src/pers/adlered/liteftpd/tool/AutoInputStream.java<|end_filename|> package pers.adlered.liteftpd.tool; /** * <h3>LiteFTPD-UNIX</h3> * <p>AutoInputStream can analyze Chinese encoding from InputStream, and print it out correctly.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ import pers.adlered.liteftpd.analyze.PrivateVariable; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class AutoInputStream { private InputStream inputStream = null; private int cacheSize = 0; private PrivateVariable privateVariable = null; public AutoInputStream(InputStream inputStream, int cacheSize, PrivateVariable privateVariable) { this.inputStream = inputStream; this.cacheSize = cacheSize; this.privateVariable = privateVariable; } public String readLineAuto() throws IOException { byte[] storage = new byte[cacheSize]; int c2Cursor = 0; while (true) { int available = 0; try { while (available == 0) { available = inputStream.available(); Thread.sleep(5); } } catch (IOException IOE) { Logger.log(Types.SEND, Levels.WARN, "Auto Input Stream stopped."); break; } catch (InterruptedException IE) { } byte[] cache = new byte[available]; inputStream.read(cache); int cursor = 0; int relativeLength = c2Cursor + cache.length; if (relativeLength <= cacheSize) { for (int i = c2Cursor; i < relativeLength; i++) { storage[i] = cache[cursor]; ++cursor; ++c2Cursor; } // Check if space exists, break it. if (new String(storage, StandardCharsets.UTF_8).indexOf("\n") != -1) { break; } } else { break; } } // Clean wasted space int storageCursor = 0; int firstEmptyMark = -1; boolean marked = false; for (byte i : storage) { if (i == 0) { if (!marked) { marked = true; firstEmptyMark = storageCursor; } } ++storageCursor; } if (firstEmptyMark == -1) firstEmptyMark = storage.length; // Init a fit size bytes. byte[] cleaned = new byte[firstEmptyMark]; for (int i = 0; i < firstEmptyMark; i++) { cleaned[i] = storage[i]; } String UTF8 = new String(cleaned, StandardCharsets.UTF_8); String GB2312 = new String(cleaned, "GB2312"); String charset = CharsetSelector.getCharset(cleaned); if (!privateVariable.isEncodeLock()) { privateVariable.setEncode(charset); if (charset.equals("GB2312")) { privateVariable.setEncodeLock(true); } } String bestMatch = new String(cleaned, charset); return bestMatch; } public String readLineInUTF8() throws IOException { return ""; } public String readLineInGB2312() throws IOException { return ""; } } <|start_filename|>src/pers/adlered/liteftpd/pool/handler/HandlerPool.java<|end_filename|> package pers.adlered.liteftpd.pool.handler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * <h3>LiteFTPD-UNIX</h3> * <p>Public class to store thread pools.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class HandlerPool { public static ExecutorService handlerPool = Executors.newCachedThreadPool(); } <|start_filename|>src/pers/adlered/liteftpd/tool/Status.java<|end_filename|> package pers.adlered.liteftpd.tool; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; /** * <h3>LiteFTPD-UNIX</h3> * <p>Get information of the server.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class Status { public static String memoryUsed() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage(); return (memoryUsage.getUsed() / 1048576) + "MB"; } } <|start_filename|>src/pers/adlered/liteftpd/analyze/CommandAnalyze.java<|end_filename|> package pers.adlered.liteftpd.analyze; import pers.adlered.liteftpd.user.status.bind.IPAddressBind; import pers.adlered.liteftpd.dict.StatusCode; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.wizard.init.PauseListen; import pers.adlered.liteftpd.wizard.init.Send; import pers.adlered.liteftpd.mode.PASV; import pers.adlered.liteftpd.mode.PORT; import pers.adlered.liteftpd.tool.GoodXX; import pers.adlered.liteftpd.tool.RandomNum; import pers.adlered.liteftpd.user.User; import pers.adlered.liteftpd.user.UserProps; import pers.adlered.liteftpd.user.info.OnlineInfo; import pers.adlered.liteftpd.user.info.bind.UserInfoBind; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import pers.adlered.liteftpd.user.status.bind.UserLimitBind; import pers.adlered.liteftpd.user.verify.OnlineRules; import pers.adlered.liteftpd.variable.OnlineUserController; import pers.adlered.liteftpd.variable.Variable; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.HashMap; import java.util.Map; /** * <h3>LiteFTPD-UNIX</h3> * <p>To analyze user input into command, and execute it.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class CommandAnalyze { /** * Step 1: Required username; * Step 2: Required password; * Step 3: Logged in. */ private int step = 1; private String loginUser = null; private String loginPass = null; private String SRVIPADD = null; private Send send = null; private File file = null; private PASV passiveMode = null; private PORT portMode = null; private String mode = null; private String currentPath = null; private String lockPath = null; private String RNFR = null; //Trans type default A //A: ASCII I: BINARY private String type = "A"; //To change timeout when command input private PauseListen pauseListen = null; private IPAddressBind ipAddressBind = null; private PrivateVariable privateVariable = null; private UserProps userProps = null; private IpLimitBind ipLimitBind = null; private UserLimitBind userLimitBind = null; public CommandAnalyze(Send send, String SRVIPADD, PrivateVariable privateVariable, PauseListen pauseListen, IPAddressBind ipAddressBind, IpLimitBind ipLimitBind) { this.send = send; this.SRVIPADD = SRVIPADD; this.privateVariable = privateVariable; this.pauseListen = pauseListen; this.ipAddressBind = ipAddressBind; this.ipLimitBind = ipLimitBind; } public static boolean isPortUsing(String host, int port) { boolean flag = false; try { Socket socket = new Socket(host, port); flag = true; socket.close(); } catch (IOException IOE) { Logger.log(Types.SYS, Levels.DEBUG, "Port " + port + " already in use, re-generating..."); } return flag; } public static void delFolder(String folderPath) { try { delAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath; java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //删除空文件夹 } catch (Exception e) { e.printStackTrace(); } } public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件 delFolder(path + "/" + tempList[i]);//再删除空文件夹 flag = true; } } return flag; } public void analyze(String command) { pauseListen.resetTimeout(); String cmd = null; String arg1 = null; String arg2 = null; String[] split = null; try { split = command.split(" "); for (int i = 0; i < split.length; i++) { split[i] = split[i].replaceAll("(\r|\n)", ""); } cmd = split[0]; if (split.length == 2) { arg1 = split[1]; } else if (split.length > 2) { arg1 = split[1]; arg2 = split[2]; } } catch (Exception E) { //TODO E.printStackTrace(); } if (cmd != null) { cmd = cmd.toUpperCase(); switch (step) { case 1: if (cmd.equals("USER")) { if (arg1 == null) { arg1 = "anonymous"; } privateVariable.setUsername(arg1); Logger.log(Types.SYS, Levels.DEBUG, Thread.currentThread() + " User login: " + arg1); loginUser = arg1; send.send(Dict.passwordRequired(loginUser)); step = 2; } else if (cmd.equals("BYE") || cmd.equals("QUIT")) { send.send(Dict.bye()); privateVariable.setInterrupted(true); } else if (cmd.equals("OPTS")) { if (arg1 != null) { arg1 = arg1.toUpperCase(); if (arg1.equals("UTF8")) { if (arg2 != null) { arg2 = arg2.toUpperCase(); if (arg2.equals("ON")) { privateVariable.setEncode("UTF-8"); privateVariable.setEncodeLock(true); send.send(Dict.utf8(true)); } else if (arg2.equals("OFF")) { privateVariable.setEncode(Variable.defaultEncode); privateVariable.setEncodeLock(true); send.send(Dict.utf8(false)); } } } } } else { unknownCommand(); } break; case 2: if (cmd.equals("PASS")) { Logger.log(Types.SYS, Levels.DEBUG, "User " + loginUser + "'s password: " + arg1); loginPass = arg1; userLimitBind = OnlineRules.checkUsername(loginUser); if (userLimitBind.getUsername() == null) { send.send(Dict.tooMuchLoginInUser(loginUser)); privateVariable.reason = "user \"" + loginUser + "\" has too much login"; privateVariable.setInterrupted(true); } else { try { userProps = User.getUserProps(loginUser); if ((loginUser.equals("anonymous") && userProps.getPermission() != null) || User.checkPassword(loginUser, loginPass)) { OnlineInfo.usersOnlineInfo.add(new UserInfoBind(ipLimitBind, userLimitBind)); send.send(Dict.loggedIn(loginUser)); Logger.log(Types.SYS, Levels.INFO, "User " + loginUser + " logged in."); lockPath = userProps.getPermitDir(); currentPath = userProps.getDefaultDir(); OnlineUserController.printOnline(); step = 3; } else { send.send(Dict.wrongPassword()); privateVariable.setInterrupted(true); } } catch (NullPointerException NPE) { send.send(Dict.wrongPassword()); privateVariable.setInterrupted(true); } } } else if (cmd.equals("BYE") || cmd.equals("QUIT")) { send.send(Dict.bye()); privateVariable.setInterrupted(true); } else { unknownCommand(); } break; case 3: if (cmd.equals("USER") || cmd.equals("PASS")) { send.send(Dict.alreadyLogIn()); } /** * INFO COMMANDS */ else if (cmd.equals("FEAT")) { send.send(Dict.features()); } else if (cmd.equals("SITE")) { send.send(Dict.notSupportSITE()); } /** * NORMAL COMMANDS */ else if (cmd.equals("PWD")) { //if (file.isDirectory()) { send.send(Dict.currentDir(getLockPath(currentPath, lockPath))); //} else { // send.send(Dict.isFile + file.getName() + "" + Dict.newLine); //} } else if (cmd.equals("TYPE")) { arg1 = arg1.toUpperCase(); type = arg1; send.send(Dict.type(arg1)); } else if (cmd.equals("BINARY")) { type = "I"; send.send(Dict.type("I")); } else if (cmd.equals("ASCII")) { type = "A"; send.send(Dict.type("A")); } else if (cmd.equals("BYE") || cmd.equals("QUIT") || cmd.equals("EXIT")) { send.send(Dict.bye()); privateVariable.setInterrupted(true); } else if (cmd.equals("LIST")) { send.send(Dict.list()); privateVariable.setTimeoutLock(true); try { Process process = Runtime.getRuntime().exec(new String[]{"ls", "-l", currentPath}); process.waitFor(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; StringBuilder result = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { result.append(line).append('\n'); } if (mode != null) { Logger.log(Types.TRANS, Levels.DEBUG, "Reset mode."); String mode = this.mode; this.mode = null; Logger.log(Types.TRANS, Levels.DEBUG, "Hello " + mode + " mode."); switch (mode) { case "port": portMode.hello(result.toString()); portMode.start(); break; case "passive": passiveMode.hello(result.toString()); break; } } } catch (IOException IOE) { //TODO IOE.printStackTrace(); } catch (InterruptedException IE) { //TODO IE.printStackTrace(); } } else if (cmd.equals("CDUP")) { upperDirectory(); send.send(Dict.changeDir(getLockPath(currentPath, lockPath))); } else if (cmd.equals("CWD")) { if (arg1 != null) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { //Make "/Users/$" to "/Users$" if (i == split.length - 1) { split[i] = split[i].replaceAll("/$", ""); } //Add completePath += " " + split[i]; } } if (completePath.equals("..")) { upperDirectory(); send.send(Dict.changeDir(getLockPath(currentPath, lockPath))); } else { if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); File file = new File(completePath); if (file.exists()) { if (file.isFile()) { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } else { currentPath = completePath; send.send(Dict.changeDir(getLockPath(currentPath, lockPath))); } } else { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } } } else { send.send(Dict.unknownCommand()); } } else if (cmd.equals("SYST")) { send.send(Dict.unixType()); } else if (cmd.equals("NOOP")) { privateVariable.setTimeoutLock(true); send.send(Dict.commandOK()); } else if (cmd.equals("MKD")) { if (userProps.getPermission().contains("c")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); File file = new File(completePath); if (!file.exists()) { file.mkdirs(); send.send(Dict.dirCreated(getLockPath(completePath, lockPath))); } else { send.send(Dict.createFailed(getLockPath(completePath, lockPath))); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("RMD")) { if (userProps.getPermission().contains("d")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); File file = new File(completePath); if (file.isDirectory()) { delFolder(completePath); send.send(Dict.rmdSuccess()); } else if (file.isFile()) { file.delete(); send.send(Dict.rmdSuccess()); } else { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("DELE")) { if (userProps.getPermission().contains("d")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); File file = new File(completePath); if (file.isFile()) { file.delete(); send.send(Dict.deleSuccess()); } else { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("RNFR")) { if (userProps.getPermission().contains("m")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); File file = new File(completePath); if (file.exists()) { RNFR = completePath; send.send(Dict.rnfrSuccess()); } else { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("RNTO")) { if (userProps.getPermission().contains("m")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); File file = new File(RNFR); if (file.renameTo(new File(completePath))) { send.send(Dict.rntoSuccess()); } else { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } RNFR = null; } else { send.send(Dict.permissionDenied()); } } /** * TRANSMISSION COMMANDS */ else if (cmd.equals("PORT")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } String[] analyzeStep1 = completePath.split(","); int[] analyzeStep2 = new int[analyzeStep1.length]; for (int i = 0; i < analyzeStep1.length; i++) { analyzeStep2[i] = Integer.parseInt(analyzeStep1[i]); } String ip = ""; int port = -1; try { for (int i = 0; i < 4; i++) { if (i < 3) { ip += analyzeStep2[i] + "."; } else { ip += analyzeStep2[i]; } } port = (analyzeStep2[4] * 256) + analyzeStep2[5]; } catch (ArrayIndexOutOfBoundsException AIOOBE) { AIOOBE.printStackTrace(); } if (portMode != null) { portMode.stopSocket(); } portMode = new PORT(send, privateVariable, pauseListen, type, OnlineRules.getSpeedLimit(loginUser)); portMode.setTarget(ip, port); send.send(Dict.portSuccess()); mode = "port"; } else if (cmd.equals("PASV")) { if (passiveMode != null) { passiveMode.stopSocket(); } passiveMode = new PASV(send, privateVariable, pauseListen, type, OnlineRules.getSpeedLimit(loginUser)); int randomPort; int randomSub; int calcPort; int finalPort; do { Map<String, Integer> map = generatePort(); randomPort = map.get("randomPort"); randomSub = map.get("randomSub"); calcPort = map.get("calcPort"); finalPort = map.get("finalPort"); } while (!passiveMode.listen(finalPort)); String[] IPADD = (SRVIPADD.split(":")[0]).split("\\."); send.send(Dict.pasvMode(IPADD, calcPort, randomSub)); passiveMode.start(); mode = "passive"; } else if (cmd.equals("RETR")) { if (userProps.getPermission().contains("r")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); try { File file = new File(completePath); if (file.exists()) { if (type.equals("I")) { send.send(Dict.openPasvBin(getLockPath(completePath, lockPath), file.length())); } else { send.send(Dict.openPasvAscii(getLockPath(completePath, lockPath), file.length())); } if (mode != null) { Logger.log(Types.TRANS, Levels.DEBUG, "Reset mode."); String mode = this.mode; this.mode = null; Logger.log(Types.TRANS, Levels.DEBUG, "Hello " + mode + " mode."); switch (mode) { case "port": portMode.hello(file); portMode.start(); break; case "passive": passiveMode.hello(file); break; } } } else { send.send(Dict.notFound(getLockPath(completePath, lockPath))); } } catch (NullPointerException NPE) { send.send(Dict.pasvDataFailed()); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("STOR")) { if (userProps.getPermission().contains("w")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } if (completePath.indexOf("../") != -1) { completePath = completePath.replaceAll("\\.\\./", ""); } completePath = getAbsolutePath(completePath); if (type.equals("I")) { send.send(Dict.openBin(getLockPath(completePath, lockPath))); } else { send.send(Dict.openAscii(getLockPath(completePath, lockPath))); } try { if (mode != null) { Logger.log(Types.TRANS, Levels.DEBUG, "Reset mode."); String mode = this.mode; this.mode = null; Logger.log(Types.TRANS, Levels.DEBUG, "Hello " + mode + " mode."); switch (mode) { case "port": portMode.helloSTOR(completePath); portMode.start(); break; case "passive": passiveMode.helloSTOR(completePath); break; } } } catch (NullPointerException NPE) { send.send(Dict.pasvDataFailed()); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("SIZE")) { if (userProps.getPermission().contains("r")) { String completePath = arg1; if (arg2 != null) { for (int i = 2; i < split.length; i++) { completePath += " " + split[i]; } } completePath = getAbsolutePath(completePath); File file = new File(completePath); if (file.exists() && file.isFile()) { send.send(Dict.fileSize(file.length())); } else { send.send(Dict.noSuchFile(completePath)); } } else { send.send(Dict.permissionDenied()); } } else if (cmd.equals("OPTS")) { if (arg1 != null) { arg1 = arg1.toUpperCase(); if (arg1.equals("UTF8")) { if (arg2 != null) { arg2 = arg2.toUpperCase(); if (arg2.equals("ON")) { privateVariable.setEncode("UTF-8"); privateVariable.setEncodeLock(true); send.send(Dict.utf8(true)); } else if (arg2.equals("OFF")) { privateVariable.setEncode(Variable.defaultEncode); privateVariable.setEncodeLock(true); send.send(Dict.utf8(false)); } } } } } else if (cmd.equals("REST")) { if (arg1 != null) { send.send(Dict.rest(arg1)); try { privateVariable.setRest(Long.parseLong(arg1)); } catch (Exception E) { E.printStackTrace(); } } } else if (cmd.equals("ABOR")) { send.send(Dict.bye()); privateVariable.setInterrupted(true); } else if (cmd.equals("GB")) { privateVariable.setEncode("GB2312"); privateVariable.setEncodeLock(true); send.send(Dict.gbEncodeOK(ipAddressBind.getIPADD())); } else { unknownCommand(); } break; } } } public boolean unknownCommand() { send.send(Dict.unknownCommand()); return true; } /* 根据绝对目录和锁定目录,计算相对目录 */ public String getLockPath(String absolutePath, String lockPath) { String resolve = absolutePath.replaceAll("^(" + lockPath + ")", ""); if (resolve.isEmpty()) resolve = "/"; if (!resolve.startsWith("/")) resolve = "/" + resolve; return resolve; } public void upperDirectory() { //Depart && Re-part path if (!getLockPath(currentPath, lockPath).equals("/")) { String[] dir = currentPath.split("/"); currentPath = ""; for (int i = 0; i < dir.length - 1; i++) { Logger.log(Types.SYS, Levels.DEBUG, "len: " + dir.length + " cur: " + i); if (i == dir.length - 2) { currentPath += dir[i]; } else { currentPath += dir[i] + "/"; } } if (currentPath.isEmpty()) currentPath = "/"; } Logger.log(Types.SYS, Levels.DEBUG, currentPath); } /* 根据CWD定位的目录,计算绝对目录的位置。 */ @SuppressWarnings("deprecation") public String getAbsolutePath(String path) { //path = URLDecoder.decode(path); if (path.matches("^(./).*")) { path = path.replaceAll("^(./)", ""); //Not totally equals "./" if (path.isEmpty()) { path = currentPath; } else { path = currentPath + "/" + path; } } else if (path.matches("^(/).*")) { path = path.replaceAll("^(/)", ""); if (path.isEmpty()) { path = lockPath; } else { path = lockPath + "/" + path; } } else { path = currentPath + "/" + path; } path = path.replaceAll("//", "/"); Logger.log(Types.SYS, Levels.DEBUG, "Absolute path: " + path); return path; } public Map<String, Integer> generatePort() { Map<String, Integer> map = new HashMap(); int randomPort; int randomSub; int calcPort; int finalPort; int count = 0; do { randomPort = RandomNum.sumIntger(Variable.minPort, Variable.maxPort, false); randomSub = RandomNum.sumIntger(0, 64, false); calcPort = (randomPort - randomSub) / 256; finalPort = calcPort * 256 + randomSub; ++count; } while (finalPort < Variable.minPort || finalPort > Variable.maxPort || randomSub < 0 || randomSub > 64); Logger.log(Types.SYS, Levels.DEBUG, count + " times while generating port: " + finalPort); map.put("randomPort", randomPort); map.put("randomSub", randomSub); map.put("calcPort", calcPort); map.put("finalPort", finalPort); return map; } } <|start_filename|>src/pers/adlered/liteftpd/graphic/main/GraphicMain.java<|end_filename|> package pers.adlered.liteftpd.graphic.main; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.graphic.main.model.MainModels; import pers.adlered.liteftpd.graphic.update.RunningUpdate; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * <h3>LiteFTPD-UNIX</h3> * <p>图形界面初始类</p> * * @author : https://github.com/AdlerED * @date : 2019-10-06 21:55 **/ public class GraphicMain extends JFrame implements Runnable, ActionListener { // Options JMenuItem clear = null; @Override public void run() { // Initialize setSize(800, 340); setLocationRelativeTo(null); setTitle("LiteFTPD-UNIX"); setLayout(new BorderLayout()); // Panel JPanel westPanel = new JPanel(new BorderLayout()); JPanel eastPanel = new JPanel(new BorderLayout()); // Console MainModels.console.setEditable(false); JScrollPane scrollPane = new JScrollPane(MainModels.console); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Menu bar JMenuBar jMenuBar = new JMenuBar(); JMenu action = new JMenu(Dict.actionStr()); clear = new JMenuItem(Dict.clearStr()); clear.addActionListener(this); action.add(clear); jMenuBar.add(action); // Data MainModels.data.setEditable(false); MainModels.console.setLineWrap(true); JScrollPane dataPane = new JScrollPane(MainModels.data); dataPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); dataPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Add Models westPanel.add(scrollPane, BorderLayout.NORTH); eastPanel.add(dataPane, BorderLayout.NORTH); // Add Panels add(jMenuBar, BorderLayout.NORTH); add(westPanel, BorderLayout.WEST); add(eastPanel, BorderLayout.EAST); // Must the end setVisible(true); MainModels.guiReady = true; // Data update Thread dataUpdateThread = new Thread(new RunningUpdate()); dataUpdateThread.start(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == clear) { MainModels.console.setText(""); } } } <|start_filename|>src/pers/adlered/liteftpd/user/info/OnlineInfo.java<|end_filename|> package pers.adlered.liteftpd.user.info; import pers.adlered.liteftpd.user.info.bind.UserInfoBind; import java.util.ArrayList; import java.util.List; /** * <h3>LiteFTPD-UNIX</h3> * <p>存储所有在线用户详细信息的数组</p> * * @author : https://github.com/AdlerED * @date : 2019-10-05 21:47 **/ public class OnlineInfo { public static final List<UserInfoBind> usersOnlineInfo = new ArrayList<>(); } <|start_filename|>src/pers/adlered/liteftpd/user/status/bind/UserLimitBind.java<|end_filename|> package pers.adlered.liteftpd.user.status.bind; /** * <h3>LiteFTPD-UNIX</h3> * <p>用户限制</p> * * @author : https://github.com/AdlerED * @date : 2019-10-05 21:02 **/ public class UserLimitBind { String username; String rule; public UserLimitBind(String username, String rule) { this.username = username; this.rule = rule; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } } <|start_filename|>src/pers/adlered/liteftpd/user/User.java<|end_filename|> package pers.adlered.liteftpd.user; import pers.adlered.liteftpd.variable.Variable; import java.util.HashMap; import java.util.Map; /** * <h3>LiteFTPD-UNIX</h3> * <p>Store users.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class User { private static Map<String, UserProps> users = null; // 读取用户配置,并写入到users中。启动时必须配置! public static void initUsers() { users = new HashMap<>(); String[] userList = Variable.user.split(";"); for (int i = 0; i < userList.length; i += 5) { UserProps userProps = new UserProps(); userProps.setPassword(userList[i + 1]); userProps.setPermission(userList[i + 2]); userProps.setPermitDir(userList[i + 3]); userProps.setDefaultDir(userList[i + 4]); users.put(userList[i], userProps); } } public static boolean checkPassword(String username, String password) { try { if (users.get(username).getPassword().equals(password)) { return true; } } catch (NullPointerException NPE) { return false; } return false; } public static UserProps getUserProps(String username) { return users.get(username); } } <|start_filename|>src/pers/adlered/liteftpd/user/verify/OnlineRules.java<|end_filename|> package pers.adlered.liteftpd.user.verify; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import pers.adlered.liteftpd.user.status.Online; import pers.adlered.liteftpd.user.status.bind.SpeedLimitBind; import pers.adlered.liteftpd.user.status.bind.UserLimitBind; import pers.adlered.liteftpd.variable.Variable; /** * <h3>LiteFTPD-UNIX</h3> * <p>检测连接数限制,返回True或者False决定是否接受连接。</p> * * @author : https://github.com/AdlerED * @date : 2019-10-05 14:49 **/ public class OnlineRules { /** * 检查IP地址是否可以登录 * * @param ipAddress * @return 返回生成后的IP Bind,用于进一步获取登录用户信息 */ public static IpLimitBind checkIpAddress(String ipAddress) { boolean onList = false; String onListRule = ""; int onListLimit = -1; String[] ipRules = Variable.ipOnlineLimit.split(";"); String[] ip = ipAddress.split("\\."); for (int i = 0; i < ipRules.length; i += 2) { if (ipRules[i].equals("0.0.0.0")) { onList = true; onListRule = ipRules[i]; onListLimit = Integer.parseInt(ipRules[i + 1]); } String[] ruleIp = ipRules[i].split("\\."); // 首先,第一位需要相等 if (ruleIp[0].equals(ip[0]) || ruleIp[0].toLowerCase().equals("x")) { if (ruleIp[1].equals(ip[1]) || ruleIp[1].toLowerCase().equals("x")) { if (ruleIp[2].equals(ip[2]) || ruleIp[2].toLowerCase().equals("x")) { if (ruleIp[3].equals(ip[3]) || ruleIp[3].toLowerCase().equals("x")) { onList = true; onListRule = ipRules[i]; onListLimit = Integer.parseInt(ipRules[i + 1]); } } } } } if (onList) { if (onListLimit == 0) { return new IpLimitBind(null, null); } else { int count = 0; for (IpLimitBind ipRule : Online.ipRuleOnline) { if (ipRule.getRule().equals(onListRule)) { ++count; } } if (count < onListLimit) { IpLimitBind ipLimitBind = new IpLimitBind(ipAddress, onListRule); Online.ipRuleOnline.add(ipLimitBind); return ipLimitBind; } else { return new IpLimitBind(null, null); } } } else { IpLimitBind ipLimitBind = new IpLimitBind(ipAddress, onListRule); Online.ipRuleOnline.add(ipLimitBind); return ipLimitBind; } } /** * 检查用户名是否达到了上限 * * @param username * @return 禁止登录返回null */ public static UserLimitBind checkUsername(String username) { boolean onList = false; String onListRule = ""; int onListLimit = -1; String[] userRules = Variable.userOnlineLimit.split(";"); // 先检测,再执行,通配符优先级最高 for (int i = 0; i < userRules.length; i += 2) { if (userRules[i].equals("%")) { onList = true; onListRule = userRules[i]; onListLimit = Integer.parseInt(userRules[i + 1]); } if (userRules[i].equals(username)) { onList = true; onListRule = userRules[i]; onListLimit = Integer.parseInt(userRules[i + 1]); } } if (onList) { if (onListLimit == 0) { return new UserLimitBind(null, null); } else { int count = 0; for (UserLimitBind userRule : Online.userRuleOnline) { if (userRule.getRule().equals(onListRule)) { ++count; } } if (count < onListLimit) { UserLimitBind userLimitBind = new UserLimitBind(username, onListRule); Online.userRuleOnline.add(userLimitBind); return userLimitBind; } else { return new UserLimitBind(null, null); } } } else { UserLimitBind userLimitBind = new UserLimitBind(username, onListRule); Online.userRuleOnline.add(userLimitBind); return userLimitBind; } } public static SpeedLimitBind getSpeedLimit(String username) { String[] speedRules = Variable.speedLimit.split(";"); for (int i = 0; i < speedRules.length; i += 3) { String currentUser = speedRules[i]; if (currentUser.equals(username)) { int uploadSpeed; if (speedRules[i + 1].isEmpty() || speedRules[i + 1].equals("0")) { uploadSpeed = 0; } else { uploadSpeed = Integer.parseInt(speedRules[i + 1]); } int downloadSpeed; if (speedRules[i + 2].isEmpty() || speedRules[i + 2].equals("0")) { downloadSpeed = 0; } else { downloadSpeed = Integer.parseInt(speedRules[i + 2]); } return new SpeedLimitBind(uploadSpeed, downloadSpeed); } } return new SpeedLimitBind(0, 0); } } <|start_filename|>src/pers/adlered/liteftpd/dict/StatusCode.java<|end_filename|> package pers.adlered.liteftpd.dict; /** * <h3>LiteFTPD-UNIX</h3> * <p>Status code.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class StatusCode { /** * Preliminary affirmative reply */ // Service is ready, will be start in ? min. public static final int READY = 120; // Data connection opened, transmission is starting. public static final int OPEN = 125; // File status OK, ready to open data connect. public static final int STATUSOK = 150; /** * A definite and complete answer */ // Command success. public static final int SUCCESS = 200; // Cannot execute command, too much command at the same time. public static final int MUCHCOMMAND = 202; // System status / System helping answer. public static final int STATUS = 211; // Directory status. public static final int DIRSTATUS = 212; // File status. public static final int FILESTATUS = 213; // Helping message. public static final int HELPING = 214; // NAME System type. public static final int NAME = 215; // Service is ready, can execute new user's request. public static final int SERVICEREADY = 220; // Service stopped control connection. public static final int SERVICESTOP = 221; // Data connection opened, no any transmission running. public static final int DATAOPEN = 225; // Data connection closed with successful. public static final int CLOSED = 226; // Enter passive mode. public static final int PASSIVE = 227; // User logged in. public static final int LOGGED = 230; // File request correct, done. public static final int CORRECT = 250; // Created "PATHNAME". public static final int CPATH = 257; /** * Intermediate affirmative response */ // Password required. public static final int PASSREQ = <PASSWORD>; // Need login. public static final int LOGIN = 332; // Waiting for file execution response. public static final int WAIT = 350; /** * Complete Answer to Transient Negation */ // Cannot open data connection. public static final int CANTOPEN = 425; // Connection closed; Transfer aborted. public static final int ABORTED = 426; //File unavailable。 public static final int UNAVAILABLE = 450; //Processing local errors. public static final int ERRORS = 451; //Not enough storage space. public static final int OUTOFSPACE = 452; /** * Permanent negative completion reply */ //Command not understood. public static final int CMDUNKNOWN = 500; //A syntax error in the argument public static final int ERRSYNTAX = 501; //Command not executed. public static final int NOTRUN = 502; //Error command sequence. public static final int ERRSEQUENCE = 503; //Command arguments not executed. public static final int ERRARGS = 504; //Not logged in. public static final int NOTLOGIN = 530; //Need account while uploading files. public static final int NEEDACCOUNT = 532; //File not found / no permission. public static final int ERRTARGET = 550; //Unknown type of the page. public static final int UNTYPE = 551; //Out of storage space distribution. public static final int OUTSPACELIMIT = 552; //Filename not allowed. public static final int INVALIDFILENAME = 553; } <|start_filename|>src/pers/adlered/liteftpd/wizard/init/Send.java<|end_filename|> package pers.adlered.liteftpd.wizard.init; import pers.adlered.liteftpd.analyze.PrivateVariable; import pers.adlered.liteftpd.user.status.bind.IPAddressBind; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; /** * <h3>LiteFTPD-UNIX</h3> * <p>Send method can be called by other threads in the same thread pool, and send a message to client.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class Send { private OutputStream outputStream = null; private PauseListen pauseListen = null; private PrivateVariable privateVariable = null; private IPAddressBind ipAddressBind = null; public Send(OutputStream outputStream, PauseListen pauseListen, PrivateVariable privateVariable, IPAddressBind ipAddressBind) { this.outputStream = outputStream; this.pauseListen = pauseListen; this.privateVariable = privateVariable; this.ipAddressBind = ipAddressBind; send(Dict.connectedMessage(ipAddressBind.getIPADD())); } public boolean send(String message) { if (!privateVariable.isInterrupted()) { Logger.log(Types.SEND, Levels.DEBUG, "Encode is: " + privateVariable.getEncode()); try { Logger.log(Types.SEND, Levels.INFO, ipAddressBind.getIPADD() + " <== [ " + privateVariable.encode + " ] " + ipAddressBind.getSRVIPADD() + ": " + message.replaceAll("\r|\n", "")); pauseListen.resetTimeout(); // WELCOME MESSAGE try { outputStream.write(message.getBytes(privateVariable.encode)); } catch (SocketException SE) { Logger.log(Types.SYS, Levels.ERROR, "Client " + ipAddressBind.getIPADD() + " socket write failed. This fake client may running port scan (such as \"nmap\"), please attention."); privateVariable.reason = "Anti-scanner?"; privateVariable.setInterrupted(true); } outputStream.flush(); return true; } catch (IOException IOE) { // TODOx IOE.printStackTrace(); return false; } } else { return false; } } } <|start_filename|>src/pers/adlered/liteftpd/wizard/init/SocketHandler.java<|end_filename|> package pers.adlered.liteftpd.wizard.init; import pers.adlered.liteftpd.analyze.CommandAnalyze; import pers.adlered.liteftpd.analyze.PrivateVariable; import pers.adlered.liteftpd.user.status.bind.IPAddressBind; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import java.io.*; import java.net.Socket; /** * <h3>LiteFTPD-UNIX</h3> * <p>Split Socket to a few models, and execute the functions of new thread.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class SocketHandler extends Thread { Send send = null; CommandAnalyze commandAnalyze = null; Receive receive = null; PrivateVariable privateVariable = null; private InputStream inputStream = null; private OutputStream outputStream = null; private BufferedInputStream bufferedInputStream = null; private BufferedOutputStream bufferedOutputStream = null; private Socket socket = null; private IPAddressBind ipAddressBind = null; private String IPADD = null; private String SRVIPADD = null; private IpLimitBind ipLimitBind = null; public SocketHandler(Socket socket, IpLimitBind ipLimitBind) { try { IPADD = socket.getInetAddress().getHostAddress() + ":" + socket.getPort(); SRVIPADD = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort(); // Import data streams. inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); // Input stream use buffer, but output is not because of trans situations. bufferedInputStream = new BufferedInputStream(inputStream); bufferedOutputStream = new BufferedOutputStream(outputStream); this.socket = socket; privateVariable = new PrivateVariable(); this.ipLimitBind = ipLimitBind; } catch (IOException IOE) { // TODO IOE.printStackTrace(); } } @Override public void run() { Logger.log(Types.SYS, Levels.INFO, IPADD + " has been mounted into " + Thread.currentThread()); ipAddressBind = new IPAddressBind(IPADD, SRVIPADD); // Process while user quit forced or manually. PauseListen pauseListen = new PauseListen( privateVariable, socket, bufferedOutputStream, outputStream, bufferedInputStream, inputStream, ipAddressBind, commandAnalyze, receive, ipLimitBind ); // Start model send = new Send(outputStream, pauseListen, privateVariable, ipAddressBind); pauseListen.setSend(send); commandAnalyze = new CommandAnalyze(send, SRVIPADD, privateVariable, pauseListen, ipAddressBind, ipLimitBind); receive = new Receive(inputStream, commandAnalyze, pauseListen, privateVariable, ipAddressBind); receive.start(); pauseListen.start(); } } <|start_filename|>src/pers/adlered/liteftpd/user/status/bind/SpeedLimitBind.java<|end_filename|> package pers.adlered.liteftpd.user.status.bind; /** * <h3>LiteFTPD-UNIX</h3> * <p>限速Bind</p> * * @author : https://github.com/AdlerED * @date : 2019-10-12 16:12 **/ public class SpeedLimitBind { private int uploadSpeed; private int downloadSpeed; public SpeedLimitBind(int uploadSpeed, int downloadSpeed) { this.uploadSpeed = uploadSpeed; this.downloadSpeed = downloadSpeed; } public int getUploadSpeed() { return uploadSpeed; } public void setUploadSpeed(int uploadSpeed) { this.uploadSpeed = uploadSpeed; } public int getDownloadSpeed() { return downloadSpeed; } public void setDownloadSpeed(int downloadSpeed) { this.downloadSpeed = downloadSpeed; } } <|start_filename|>src/pers/adlered/liteftpd/graphic/main/model/MainModels.java<|end_filename|> package pers.adlered.liteftpd.graphic.main.model; import javax.swing.*; /** * <h3>LiteFTPD-UNIX</h3> * <p>存放主界面控件</p> * * @author : https://github.com/AdlerED * @date : 2019-10-06 22:14 **/ public class MainModels { public static boolean guiReady = false; public static JTextArea console = new JTextArea(18, 31); public static JTextArea data = new JTextArea(3, 32); } <|start_filename|>src/pers/adlered/liteftpd/user/status/Online.java<|end_filename|> package pers.adlered.liteftpd.user.status; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import pers.adlered.liteftpd.user.status.bind.UserLimitBind; import java.util.ArrayList; import java.util.List; /** * <h3>LiteFTPD-UNIX</h3> * <p>记录在线的用户信息,用于限制连接数和读取信息。</p> * * @author : https://github.com/AdlerED * @date : 2019-10-05 14:51 **/ public class Online { // 存储指定规则的在线IP数量 public static final List<IpLimitBind> ipRuleOnline = new ArrayList<>(); // 存储制定规则的在线用户数量 public static final List<UserLimitBind> userRuleOnline = new ArrayList<>(); } <|start_filename|>src/pers/adlered/liteftpd/user/status/bind/IpLimitBind.java<|end_filename|> package pers.adlered.liteftpd.user.status.bind; /** * <h3>LiteFTPD-UNIX</h3> * <p>IP地址限制</p> * * @author : https://github.com/AdlerED * @date : 2019-10-05 15:14 **/ public class IpLimitBind { String ip; String rule; public IpLimitBind(String ip, String rule) { this.ip = ip; this.rule = rule; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } } <|start_filename|>src/pers/adlered/liteftpd/graphic/update/RunningUpdate.java<|end_filename|> package pers.adlered.liteftpd.graphic.update; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.graphic.main.model.MainModels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.user.status.Online; import pers.adlered.liteftpd.user.status.bind.UserLimitBind; import java.util.*; /** * <h3>LiteFTPD-UNIX</h3> * <p>实时更新数据,并显示在界面上</p> * * @author : https://github.com/AdlerED * @date : 2019-10-06 22:55 **/ public class RunningUpdate implements Runnable { @Override public void run() { try { while (true) { List<String> list = new ArrayList<>(); // ** Collect ** // Online list.add(" ● " + Dict.onlineStr() + " " + Online.userRuleOnline.size() + " ● " + Dict.connectionsStr() + " " + Online.ipRuleOnline.size()); // Users Map<String, Integer> userMap = new HashMap<>(); for (UserLimitBind userLimitBind : Online.userRuleOnline) { String username = userLimitBind.getUsername(); if (userMap.get(username) != null) { int count = userMap.get(username); ++count; userMap.put(username, count); } else { userMap.put(username, 1); } } String users = ""; for (Map.Entry<String, Integer> entry : userMap.entrySet()) { users += entry.getKey() + " (" + entry.getValue() + ") | "; } users = users.replaceAll("( \\| )$", ""); list.add(users); // ** Update ** String text = ""; for (String i : list) { text += i + "\n"; } MainModels.data.setText(text); Thread.sleep(1000); } } catch (InterruptedException IE) { IE.printStackTrace(); } } } <|start_filename|>src/pers/adlered/liteftpd/analyze/PrivateVariable.java<|end_filename|> package pers.adlered.liteftpd.analyze; /** * <h3>LiteFTPD-UNIX</h3> * <p>Store values when service is running to make sure every model works together.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class PrivateVariable { public boolean interrupted = false; public String encode = "UTF-8"; public String reason = null; private String username = null; //When translating, turn the timeout on to avoid timeout & disconnect. private boolean timeoutLock = false; //If Encode Lock is on, smart encode will not working. private boolean encodeLock = false; //Rest private long rest = 0l; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public boolean isEncodeLock() { return encodeLock; } public void setEncodeLock(boolean encodeLock) { this.encodeLock = encodeLock; } public boolean isTimeoutLock() { return timeoutLock; } public void setTimeoutLock(boolean timeoutLock) { this.timeoutLock = timeoutLock; } public boolean isInterrupted() { return interrupted; } public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; } public String getEncode() { return encode; } public void setEncode(String encode) { this.encode = encode; } public long getRest() { return rest; } public void setRest(long rest) { this.rest = rest; } public void resetRest() { rest = 0l; } } <|start_filename|>src/pers/adlered/liteftpd/main/Main.java<|end_filename|> package pers.adlered.liteftpd.main; import pers.adlered.liteftpd.dict.Dict; import pers.adlered.liteftpd.graphic.main.GraphicMain; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.pool.handler.HandlerPool; import pers.adlered.liteftpd.tool.ConsoleTable; import pers.adlered.liteftpd.tool.LocalAddress; import pers.adlered.liteftpd.tool.Status; import pers.adlered.liteftpd.user.User; import pers.adlered.liteftpd.user.status.Online; import pers.adlered.liteftpd.user.status.bind.IpLimitBind; import pers.adlered.liteftpd.user.status.bind.SpeedLimitBind; import pers.adlered.liteftpd.user.verify.OnlineRules; import pers.adlered.liteftpd.variable.OnlineUserController; import pers.adlered.liteftpd.variable.Variable; import pers.adlered.liteftpd.wizard.config.Prop; import pers.adlered.liteftpd.wizard.init.SocketHandler; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * <h3>LiteFTPD-UNIX</h3> * <p>Main method of LiteFTPD, listening connections and create a new thread into thread pool.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class Main { public static void main(String[] args) { Main.init(args); ServerSocket serverSocket = null; try { Logger.log(Types.SYS, Levels.INFO, "LiteFTPD by AdlerED <- GitHub"); // Listen socket connections, handle with SocketHandler. serverSocket = new ServerSocket(Variable.port); Logger.log(Types.SYS, Levels.INFO, "Listening " + serverSocket.getLocalSocketAddress()); Logger.log(Types.SYS, Levels.INFO, "You can connect to the FTP Server via following IP address:"); ConsoleTable consoleTable = new ConsoleTable(LocalAddress.getLocalIPList().size(), true); consoleTable.appendRow(); consoleTable.appendColum("Listening IP:Port") .appendColum("github.com/AdlerED"); consoleTable.appendRow(); if (Variable.debugLevel >= 1) { for (String i : LocalAddress.getLocalIPList()) { consoleTable.appendColum(i + ":" + serverSocket.getLocalPort()); } } Logger.log(Types.SYS, Levels.INFO, "\n" + consoleTable.toString()); } catch (IOException IOE) { // TODO IOE.printStackTrace(); } while (true) { try { Logger.log(Types.SYS, Levels.INFO, "Memory used: " + Status.memoryUsed()); Socket socket = serverSocket.accept(); // Online limit checking String hostAdd = socket.getInetAddress().getHostAddress(); IpLimitBind ipLimitBind = OnlineRules.checkIpAddress(hostAdd); if (((ipLimitBind.getIp() == null) || Variable.online >= Variable.maxUserLimit) && Variable.maxUserLimit != 0) { for (int i = 0; i < Online.ipRuleOnline.size(); i++) { if (Online.ipRuleOnline.get(i).getIp().equals(hostAdd)) { Online.ipRuleOnline.remove(i); break; } } BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream()); bufferedOutputStream.write(Dict.outOfOnlineLimit().getBytes()); bufferedOutputStream.flush(); bufferedOutputStream.close(); socket.close(); } else { HandlerPool.handlerPool.execute(new SocketHandler(socket, ipLimitBind)); OnlineUserController.printOnline(); } } catch (IOException IOE) { // TODO IOE.printStackTrace(); } } } public static void init(String[] args) { // 设置LiteFTPD关闭时的操作 Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread() { @Override public void run() { Logger.log(Types.SYS, Levels.INFO, "LiteFTPD stopped."); } }); // 读取配置文件 Prop.getInstance(); // 检测传值,执行指定操作 for (int i = 0; i < args.length; i++) { String variable = args[i]; if (variable.equals("-l")) { String value = args[i + 1]; value = value.replaceAll("-", "_"); if (value.equals("en_us")) { Logger.log(Types.SYS, Levels.INFO, "Language option detected. Init language as \"English\"."); Dict.init(value); } else if (value.equals("zh_cn")) { Logger.log(Types.SYS, Levels.INFO, "Language option detected. Init language as \"简体中文\"."); Dict.init(value); } else { Logger.log(Types.SYS, Levels.WARN, "Cannot support customize language \"" + value + "\". Using default \"English\"."); Logger.log(Types.SYS, Levels.WARN, "Supported language: zh_cn en_us"); } } else if (variable.equals("-g")) { Logger.log(Types.SYS, Levels.INFO, "Launching graphic interface..."); Thread GUI = new Thread(new GraphicMain()); GUI.run(); } } // 初始化用户信息 User.initUsers(); } } <|start_filename|>src/pers/adlered/liteftpd/wizard/config/Prop.java<|end_filename|> package pers.adlered.liteftpd.wizard.config; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.variable.Variable; import java.io.*; import java.lang.reflect.Field; import java.util.*; /** * <h3>LiteFTPD-UNIX</h3> * <p>配置文件读写操作类</p> * * @author : https://github.com/AdlerED * @date : 2019-10-03 23:45 **/ public class Prop { private static Properties properties = new Properties(); private static Prop prop = null; private Prop() { try { BufferedReader bufferedReader = new BufferedReader(new FileReader("config.prop")); properties.load(bufferedReader); Logger.log(Types.SYS, Levels.INFO, "Profile \"config.prop\" loaded successfully."); } catch (FileNotFoundException FNFE) { Logger.log(Types.SYS, Levels.WARN, "Cannot found properties file \"config.prop\" at the root path, re-generating default..."); try { File file = new File("config.prop"); file.createNewFile(); // Set default props addAnnotation("# ================================================================================================") .addAnnotation("# ================================================================================================") .addAnnotation("# >>> LiteFTPD-UNIX Configure File") .addAnnotation("# ") .addAnnotation("# >> debugLevel") .addAnnotation("# ") .addAnnotation("# Too high level can affect performance!") .addAnnotation("# 0: NONE;") .addAnnotation("# 1: INFO;") .addAnnotation("# 2: WARN && INFO;") .addAnnotation("# 3: ERROR && WARN && INFO;") .addAnnotation("# 4: DEBUG && ERROR && WARN && INFO.") .addAnnotation("# ") .addAnnotation("# Debug等级,调整过高可能会影响性能!") .addAnnotation("# 0:无输出;") .addAnnotation("# 1:输出 INFO 信息;") .addAnnotation("# 2:输出 WARN 及 INFO 信息;") .addAnnotation("# 3:输出 ERROR 、 WARN 及 INFO 信息;") .addAnnotation("# 4:输出 DEBUG 、 ERROR 、 WARN 及 INFO 信息。") .addAnnotation("# ") .addAnnotation("# >> maxUserLimit") .addAnnotation("# ") .addAnnotation("# Set to 0, will be ignore the limit. Too small value may make multi-thread ftp client not working.") .addAnnotation("# ") .addAnnotation("# 同时连接数限制。设置至0代表不限制。过小的值可能会导致多线程的FTP客户端无法正常工作。") .addAnnotation("# ") .addAnnotation("# >> timeout") .addAnnotation("# ") .addAnnotation("# Timeout in second.") .addAnnotation("# ") .addAnnotation("# 连接空闲超时时间。") .addAnnotation("# ") .addAnnotation("# >> maxTimeout") .addAnnotation("# ") .addAnnotation("# On mode timeout when client is on passive or initiative mode. (default: 21600 sec = 6 hrs)") .addAnnotation("# ") .addAnnotation("# 传输时最高的超时时间。(默认:21600秒 = 6小时)") .addAnnotation("# ") .addAnnotation("# >> smartEncode") .addAnnotation("# ") .addAnnotation("# Smart choose transmission encode.") .addAnnotation("# ") .addAnnotation("# 开启后,LiteFTPD会自动检测编码,以兼容各种系统的FTP客户端。") .addAnnotation("# ") .addAnnotation("# >> defaultEncode") .addAnnotation("# ") .addAnnotation("# Set the default translating encode. Unix is UTF-8, Windows is GB2312.") .addAnnotation("# ") .addAnnotation("# 设置默认的传输编码。 Unix系统为UTF-8,Windows为GB2312。") .addAnnotation("# ") .addAnnotation("# >> port") .addAnnotation("# ") .addAnnotation("# FTP Server listening tcp port.") .addAnnotation("# ") .addAnnotation("# FTP服务监听的TCP端口号。") .addAnnotation("# ") .addAnnotation("# >> welcomeMessage") .addAnnotation("# ") .addAnnotation("# Customize welcome message when user visited.") .addAnnotation("# ") .addAnnotation("# 自定义用户连接时的欢迎信息。") .addAnnotation("# ") .addAnnotation("# >> minPort && maxPort") .addAnnotation("# ") .addAnnotation("# Appoint passive mode port range.") .addAnnotation("# Recommend 100+ ports in the range to make sure generation have high-performance!") .addAnnotation("# ") .addAnnotation("# 自定义被动模式使用的端口范围。") .addAnnotation("# 建议在范围中有100个端口以上,以确保FTP服务端的性能。") .addAnnotation("# ") .addAnnotation("# >> user") .addAnnotation("# ") .addAnnotation("# Multi users. Format:") .addAnnotation("# user=[username];[password];[permission];[permitDir];[defaultDir]; ...") .addAnnotation("# username: User's login name.") .addAnnotation("# password: <PASSWORD>.") .addAnnotation("# permission:") .addAnnotation("# r = read") .addAnnotation("# w = write") .addAnnotation("# d = delete") .addAnnotation("# c = create") .addAnnotation("# m = move") .addAnnotation("# Example: rw means read and write permission.") .addAnnotation("# permitDir: Set dir that user can access.") .addAnnotation("# Example: \"/\" means user can access the hole disk; \"/home\" means user can access folder/subFolder/files under \"/home\" directory.") .addAnnotation("# defaultDir: The default dir will be re-directed when user logged.") .addAnnotation("# ") .addAnnotation("# 多用户管理。格式:") .addAnnotation("# user=[用户名];[密码];[权限];[允许访问的目录];[登录时的默认目录]; ...") .addAnnotation("# 权限:") .addAnnotation("# r = 读") .addAnnotation("# w = 写") .addAnnotation("# d = 删除") .addAnnotation("# c = 创建") .addAnnotation("# m = 移动") .addAnnotation("# 举例:rw 代表读和写的权限。") .addAnnotation("# 允许访问的目录:设置用户可以访问的目录。") .addAnnotation("# 举例:“/”代表用户可以访问整个硬盘;“/home”代表用户可以访问在“/home”目录下的所有子目录、目录和文件。") .addAnnotation("# 登录时的默认目录:登录成功后,用户所在的默认目录。") .addAnnotation("# ") .addAnnotation("# >> ipOnlineLimit") .addAnnotation("# ") .addAnnotation("# Max connections limit for specify IP Address.") .addAnnotation("# ipOnlineLimit=[IP];[Limit];[IP];[Limit]; ...") .addAnnotation("# If you defined IP Address as \"0.0.0.0\", priority will be given to limiting the number of connections per IP address to a specified number (Except for IP Address that have been set up separately).") .addAnnotation("# \"x\" means \"All\". If you defined \"192.168.x.x\", that connections from range \"192.168.0-255.0-255\" all will be refused.") .addAnnotation("# BlackList for Ip Address? Set limit to \"0\"!") .addAnnotation("# !!! Please note! The higher the configuration, the lower the weight of the connection limit (meaning that the more forward, the less likely it is to match). It is recommended to write the configuration of the specified IP at the end, and write the IP configuration using the wildcard in the front. !!!") .addAnnotation("# For example, =127.0.0.1; 1; 0.0.0.0; 100; When 127.0.0.1 is connected to the server, the maximum number of simultaneous connections allowed is 100! The configuration should be modified to =0.0.0.0;100;127.0.0.1;1;") .addAnnotation("# ") .addAnnotation("# 限制指定IP地址的最大同时连接数。") .addAnnotation("# ipOnlineLimit=[IP地址];[最大连接数];[IP地址];[最大连接数]; ...") .addAnnotation("# 如果你将IP地址定义为“0.0.0.0”,服务端将把最大连接数规则应用到所有的IP地址中(除非指定IP地址也被单独定义了)。") .addAnnotation("# “x”代表“所有”。如果你定义为“192.168.x.x”,那么来自“192.168.0-255.0-255”范围的所有IP地址都将受到该规则的限制。") .addAnnotation("# 想将指定IP地址拉黑?把最大连接数限制为“0”!") .addAnnotation("# !!! 请注意!配置越往前,连接数限制的权重越低(意味着越往前,匹配到的可能性越小)。建议将指定IP的配置写在最后面,将使用通配符的IP配置写在前面。 !!!") .addAnnotation("# 例如 =127.0.0.1;1;0.0.0.0;100; 当127.0.0.1连接服务端时,最终获取到允许同时的连接数最大为100!应将配置修改为 =0.0.0.0;100;127.0.0.1;1;") .addAnnotation("# ") .addAnnotation("# >> userOnlineLimit") .addAnnotation("# ") .addAnnotation("# Max connections limit for specify User.") .addAnnotation("# userOnlineLimit=[username];[Limit];[username];[Limit]; ...") .addAnnotation("# If you defined User as \"%\", priority will be given to limiting the number of connections per User to a specified number (Except for users that have been set up separately).") .addAnnotation("# BlackList for User? Set limit to \"0\"!") .addAnnotation("# !!! Please note! The higher the configuration, the lower the weight of the connection limit (meaning that the more forward, the less likely it is to match). It is recommended to write the configuration of the specified user to the end, and write the user configuration using the wildcard to the front. !!!") .addAnnotation("# For example, =admin;1;%;100; When logging in to the user admin, the maximum number of connections allowed to log in at the same time is 100! The configuration should be modified to =%;100;admin;1;") .addAnnotation("# ") .addAnnotation("# 限制指定用户的最大同时连接数。") .addAnnotation("# userOnlineLimit=[用户名];[最大连接数];[用户名];[最大连接数]; ...") .addAnnotation("# 如果你将用户名定义为“%”,服务端讲把最大连接数规则应用到所有的用户中(除非指定用户也被单独定义了)。") .addAnnotation("# 想将指定用户拉黑?把最大连接数限制为“0”!") .addAnnotation("# !!! 请注意!配置越往前,连接数限制的权重越低(意味着越往前,匹配到的可能性越小)。建议将指定用户的配置写在最后面,将使用通配符的用户配置写在前面。 !!!") .addAnnotation("# 例如 =admin;1;%;100; 当登录用户admin时,最终获取到允许同时登录的连接数最大为100!应将配置修改为 =%;100;admin;1;") .addAnnotation("# ") .addAnnotation("# >> speedLimit") .addAnnotation("# ") .addAnnotation("# Limit user's upload & download speed. There is no limit") .addAnnotation("# format: speedLimit=[username];[upload(kb/s)];[download(kb/s)]; ...") .addAnnotation("# ") .addAnnotation("# 限制用户的上传和下载速度。数值为0或不填时不限制。") .addAnnotation("# 格式:speedList=[用户名];[上传速度(kb/秒)];[下载速度(kb/秒)]; ...") .addAnnotation("# ") .addAnnotation("# ================================================================================================") .addAnnotation("# = ↓ CONFIG ↓ =") .addAnnotation("# ================================================================================================") .addAnnotation("# "); addProperty("user", "anonymous;;r;/;/;admin;123456;r;/;/root;") .addProperty("ipOnlineLimit", "0.0.0.0;100;127.x.x.x;100;192.168.1.x;100;") .addProperty("userOnlineLimit", "%;100;anonymous;100;admin;100;") .addProperty("speedLimit", "anonymous;0;10240;admin;;20480;") .addProperty("debugLevel", "3") .addProperty("maxUserLimit", "100") .addProperty("timeout", "100") .addProperty("maxTimeout", "21600") .addProperty("smartEncode", "true") .addProperty("defaultEncode", "UTF-8") .addProperty("port", "21") .addProperty("welcomeMessage", "オレは ルフィ、海賊王になる男だ") .addProperty("minPort", "10240") .addProperty("maxPort", "20480"); BufferedReader bufferedReader = new BufferedReader(new FileReader("config.prop")); properties.load(bufferedReader); } catch (IOException IOE) { IOE.printStackTrace(); } } catch (IOException IOE) { IOE.printStackTrace(); } // 反射并应用配置 try { Class clazz = Variable.class; Set<Object> keys = properties.keySet(); for (Object key : keys) { Field field = clazz.getDeclaredField(key.toString()); switch (field.getType().toString()) { case "int": field.set(clazz, Integer.parseInt(getProperty(key.toString()))); break; case "long": field.set(clazz, Long.parseLong(getProperty(key.toString()))); break; case "boolean": field.set(clazz, Boolean.parseBoolean(getProperty(key.toString()))); break; case "class java.lang.String": field.set(clazz, getProperty(key.toString())); break; } } } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } public static Prop getInstance() { if (prop == null) { prop = new Prop(); } return prop; } private Prop addAnnotation(String annotation) { try { FileOutputStream fileOutputStream = new FileOutputStream(new File("config.prop"), true); fileOutputStream.write((annotation + "\n").getBytes()); fileOutputStream.flush(); fileOutputStream.close(); } catch (FileNotFoundException FNFE) { FNFE.printStackTrace(); } catch (IOException IOE) { IOE.printStackTrace(); } return this; } private Prop addProperty(String key, String value) { try { FileOutputStream fileOutputStream = new FileOutputStream(new File("config.prop"), true); fileOutputStream.write((key + "=" + value + "\n").getBytes()); fileOutputStream.flush(); fileOutputStream.close(); } catch (FileNotFoundException FNFE) { FNFE.printStackTrace(); } catch (IOException IOE) { IOE.printStackTrace(); } return this; } private String getProperty(String key) { return properties.getProperty(key); } } <|start_filename|>src/pers/adlered/liteftpd/wizard/init/Receive.java<|end_filename|> package pers.adlered.liteftpd.wizard.init; import pers.adlered.liteftpd.analyze.CommandAnalyze; import pers.adlered.liteftpd.analyze.PrivateVariable; import pers.adlered.liteftpd.user.status.bind.IPAddressBind; import pers.adlered.liteftpd.logger.enums.Levels; import pers.adlered.liteftpd.logger.Logger; import pers.adlered.liteftpd.logger.enums.Types; import pers.adlered.liteftpd.tool.AutoInputStream; import java.io.IOException; import java.io.InputStream; /** * <h3>LiteFTPD-UNIX</h3> * <p>To receive commands.</p> * * @author : https://github.com/AdlerED * @date : 2019-09-19 09:21 **/ public class Receive extends Thread { private InputStream inputStream = null; private CommandAnalyze commandAnalyze = null; private PauseListen pauseListen = null; private PrivateVariable privateVariable = null; private IPAddressBind ipAddressBind = null; public Receive(InputStream inputStream, CommandAnalyze commandAnalyze, PauseListen pauseListen, PrivateVariable privateVariable, IPAddressBind ipAddressBind) { this.inputStream = inputStream; this.commandAnalyze = commandAnalyze; this.pauseListen = pauseListen; this.privateVariable = privateVariable; this.ipAddressBind = ipAddressBind; } @Override public void run() { try { // READ AutoInputStream autoInputStream = new AutoInputStream(inputStream, 1024, privateVariable); while (true) { String autoLine = autoInputStream.readLineAuto(); if (!pauseListen.isRunning()) { Logger.log(Types.RECV, Levels.WARN, "Receive stopped."); break; } Logger.log(Types.RECV, Levels.INFO, ipAddressBind.getIPADD() + " ==> " + ipAddressBind.getSRVIPADD() + ": " + autoLine.replaceAll("\r|\n", "")); commandAnalyze.analyze(autoLine); } } catch (IOException IOE) { // TODO IOE.printStackTrace(); } } }
LFM-Closed/LiteFTPD-UNIX
<|start_filename|>src/Greeting/Greeting.js<|end_filename|> export default class Greeting { constructor(name) { this.name = name || 'Guest'; } hello() { return `Welcome, ${this.name}!`; } }
balabukha/babel-starter-kit
<|start_filename|>src/main/java/com/servlet/MyStreamServlet.java<|end_filename|> package com.servlet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.util.Enumeration; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import com.constants.Constants; public class MyStreamServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub try { preview(req,resp); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void preview(HttpServletRequest req,HttpServletResponse resp) throws ClassNotFoundException, IOException { String fpath=req.getParameter("fpath"); if(fpath==null) return; String filename=Constants.HDFSAddress+fpath; Configuration config=new Configuration(); FileSystem fs = null; FSDataInputStream in=null; try { fs = FileSystem.get(URI.create(filename),config); in=fs.open(new Path(filename)); } catch (IOException e) { e.printStackTrace(); } final long fileLen = fs.getFileStatus(new Path(filename)).getLen(); String range=req.getHeader("Range"); resp.setHeader("Content-type","video/mp4"); OutputStream out=resp.getOutputStream(); if(range==null) { filename=fpath.substring(fpath.lastIndexOf("/")+1); resp.setHeader("Content-Disposition", "attachment; filename="+filename); resp.setContentType("application/octet-stream"); resp.setContentLength((int)fileLen); IOUtils.copyBytes(in, out, fileLen, false); } else { long start=Integer.valueOf(range.substring(range.indexOf("=")+1, range.indexOf("-"))); long count=fileLen-start; long end; if(range.endsWith("-")) end=fileLen-1; else end=Integer.valueOf(range.substring(range.indexOf("-")+1)); String ContentRange="bytes "+String.valueOf(start)+"-"+end+"/"+String.valueOf(fileLen); resp.setStatus(206); resp.setContentType("video/mpeg4"); resp.setHeader("Content-Range",ContentRange); in.seek(start); try{ IOUtils.copyBytes(in, out, count, false); } catch(Exception e) { throw e; } } in.close(); in = null; out.close(); out = null; } }
HorseLord-Abrek4yp7j/yeleaveszi9
<|start_filename|>test/docker-test/dockerfiles/redhat6/Dockerfile<|end_filename|> # syntax=docker/dockerfile:1.0.0-experimental FROM registry.access.redhat.com/rhel6 RUN --mount=type=secret,id=creds,required subscription-manager register --username=$(sed -n 1p /run/secrets/creds) --password=$(sed -n 2p /run/secrets/creds) RUN mkdir /home/temp \ && echo exit 0 > /usr/sbin/policy-rc.d \ && subscription-manager attach --auto \ && yum update -y \ && yum upgrade -y \ && yum localinstall -y http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm \ && yum install -y sudo gcc curl git net-tools python-ctypes gnupg2 cronie vim openssl systemd rsyslog dos2unix httpd wget mysql-community-server <|start_filename|>test/docker-test/dockerfiles/redhat8py3/Dockerfile<|end_filename|> # syntax=docker/dockerfile:1.0.0-experimental FROM registry.access.redhat.com/ubi8 RUN --mount=type=secret,id=creds,required subscription-manager register --username=$(sed -n 1p /run/secrets/creds) --password=$(sed -n 2p /run/secrets/creds) # Due to difficulty in finding the right MySQL package to trigger the mysql-cimprov package install, # this step is skipped (though MySQL logs are still configured and collected, since they are simply custom logs). # TODO when python2/3 coexistence is complete, remove alternatives command RUN mkdir /home/temp \ && subscription-manager attach --auto \ && yum update -y \ && yum upgrade -y \ && yum install -y sudo gcc git net-tools cronie openssl dos2unix wget httpd rsyslog python3 initscripts hostname iproute ENTRYPOINT ["/usr/sbin/init"] <|start_filename|>test/docker-test/dockerfiles/redhat7/Dockerfile<|end_filename|> # syntax=docker/dockerfile:1.0.0-experimental FROM registry.access.redhat.com/rhel7 RUN --mount=type=secret,id=creds,required subscription-manager register --username=$(sed -n 1p /run/secrets/creds) --password=$(sed -n 2p /run/secrets/creds) RUN mkdir /home/temp \ && subscription-manager attach --auto \ && yum update -y \ && yum upgrade -y \ && yum localinstall -y http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm \ && yum install -y sudo gcc curl git net-tools gnupg2 cronie vim openssl systemd dos2unix wget httpd rsyslog python-ctypes hostname initscripts mysql-community-server ENTRYPOINT ["/usr/sbin/init"] <|start_filename|>test/docker-test/dockerfiles/ubuntu20py3/Dockerfile<|end_filename|> FROM ubuntu:20.04 # Due to difficulty in finding the right MySQL package to trigger the mysql-cimprov package install, # this step is skipped (though MySQL logs are still configured and collected, since they are simply custom logs). ARG DEBIAN_FRONTEND=noninteractive RUN mkdir /home/temp \ && echo exit 0 > /usr/sbin/policy-rc.d \ && apt-get update \ && apt-get install -y sudo gcc curl git net-tools python3 gnupg2 cron rsyslog vim dos2unix wget apache2 systemd tzdata iproute2 <|start_filename|>test/docker-test/dockerfiles/centos8/Dockerfile<|end_filename|> FROM centos:8 # Due to difficulty in finding the right MySQL package to trigger the mysql-cimprov package install, # this step is skipped (though MySQL logs are still configured and collected, since they are simply custom logs). # TODO when python2/3 coexistence is complete, remove alternatives command RUN mkdir /home/temp \ && yum update -y \ && yum upgrade -y \ && yum install -y sudo gcc git net-tools cronie openssl dos2unix wget httpd rsyslog python2 initscripts hostname systemd vim gnupg2 curl \ && alternatives --set python /usr/bin/python2 ENTRYPOINT ["/usr/sbin/init"] <|start_filename|>test/docker-test/dockerfiles/centos8py3/Dockerfile<|end_filename|> FROM centos:8 # Due to difficulty in finding the right MySQL package to trigger the mysql-cimprov package install, # this step is skipped (though MySQL logs are still configured and collected, since they are simply custom logs). RUN mkdir /home/temp \ && yum update -y \ && yum upgrade -y \ && yum install -y sudo gcc git net-tools cronie openssl dos2unix wget httpd rsyslog python3 initscripts hostname systemd vim gnupg2 curl ENTRYPOINT ["/usr/sbin/init"] <|start_filename|>test/docker-test/dockerfiles/debian10/Dockerfile<|end_filename|> FROM debian:10 # Debian 10 Container image does not come with any python. Here we will mimic the Azure VM image and install python2 as python. # Due to difficulty in finding the right MySQL package to trigger the mysql-cimprov package install, # this step is skipped (though MySQL logs are still configured and collected, since they are simply custom logs). RUN mkdir /home/temp \ && apt-get update \ && echo exit 0 > /usr/sbin/policy-rc.d \ && apt-get install -y --reinstall sudo gcc curl git net-tools python2 gnupg2 cron vim procps rsyslog dos2unix systemd wget apache2 \ && update-alternatives --install /usr/bin/python python /usr/bin/python2 1
antomatody/OMS-Agent-for-Linux
<|start_filename|>index.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content="An easy way to generate a Diceware passphase or password." /> <link rel="shortcut icon" href="favicon.ico" /> <title>Diceware Secure Passphrase and Password Generator</title> <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css" type="text/css" integrity="<KEY>" crossorigin="anonymous" /> <link rel="stylesheet" href="css/app.css" type="text/css" integrity="<KEY>" crossorigin="anonymous" /> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar" > <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#eff">Diceware</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li> <a href="#" class="listSelectionLink" data-list="eff">EFF (EN)</a> </li> <li> <a href="#" class="listSelectionLink" data-list="diceware" >Diceware (EN)</a > </li> <li> <a href="#" class="listSelectionLink" data-list="alternative" >Diceware Alt (EN)</a > </li> <li> <a href="#" class="listSelectionLink" data-list="basque" >Basque</a > </li> <li> <a href="#" class="listSelectionLink" data-list="catalan" >Catalan</a > </li> <li> <a href="#" class="listSelectionLink" data-list="czech">Czech</a> </li> <li> <a href="#" class="listSelectionLink" data-list="danish" >Danish</a > </li> <li> <a href="#" class="listSelectionLink" data-list="dutch">Dutch</a> </li> <li> <a href="#" class="listSelectionLink" data-list="esperanto" >Esperanto</a > </li> </ul> <ul class="nav navbar-nav"> <li> <a href="#" class="listSelectionLink" data-list="finnish" >Finnish</a > </li> <li> <a href="#" class="listSelectionLink" data-list="french" >French</a > </li> <li> <a href="#" class="listSelectionLink" data-list="german-dereko" >German (DeReKo)</a > </li> <li> <a href="#" class="listSelectionLink" data-list="german-tenne" >German (Tenne)</a > </li> <li> <a href="#" class="listSelectionLink" data-list="hungarian" >Hungarian</a > </li> <li> <a href="#" class="listSelectionLink" data-list="italian" >Italian</a > </li> <li> <a href="#" class="listSelectionLink" data-list="japanese" >Japanese</a > </li> <li> <a href="#" class="listSelectionLink" data-list="maori">Maori</a> </li> <li> <a href="#" class="listSelectionLink" data-list="norwegian" >Norwegian</a > </li> <li> <a href="#" class="listSelectionLink" data-list="polish" >Polish</a > </li> <li> <a href="#" class="listSelectionLink" data-list="russian" >Russian</a > </li> <li> <a href="#" class="listSelectionLink" data-list="spanish" >Spanish</a > </li> <li> <a href="#" class="listSelectionLink" data-list="swedish" >Swedish</a > </li> </ul> </div> <!--/.nav-collapse --> </div> </nav> <div class="container"> <div class="page-header"> <h1 id="listTitleHeader"> <span class="text-capitalize"></span>&nbsp;<small>wordlist</small> </h1> <p class="lead"> <a href="http://world.std.com/~reinhold/diceware.html" target="_blank" rel="noopener" >Diceware</a > is used to generate cryptographically strong passphrases. Don't let that frighten you away though, a passphrase is just a password made of words you can remember. It is based on the principle that truly random selection of words from a <a href="http://world.std.com/~reinhold/diceware.wordlist.asc" target="_blank" rel="noopener" >wordlist</a >, can result in easily memorable passwords that are also extremely resistant to attack. Traditional Diceware uses rolls of physical dice, this application uses a strong random number generator in place of the dice. Passwords that are <a href="http://world.std.com/~reinhold/dicewarefaq.html#howlong" target="_blank" rel="noopener" >six words</a > or longer are thought to be safe for any very high security applications. </p> </div> <div class="btn-group" role="group" aria-label="Add random words group"> <button type="button" class="btn btn-warning genWordsButton" data-words="5" data-rolls="5" data-reset="1" > <span class="glyphicon glyphicon-random" aria-hidden="true"></span> 5 Words </button> <button type="button" class="btn btn-success genWordsButton" data-words="6" data-rolls="5" data-reset="1" > <span class="glyphicon glyphicon-random" aria-hidden="true"></span> 6 Words </button> <button type="button" class="btn btn-success genWordsButton" data-words="7" data-rolls="5" data-reset="1" > <span class="glyphicon glyphicon-random" aria-hidden="true"></span> 7 Words </button> <button type="button" class="btn btn-success genWordsButton" data-words="8" data-rolls="5" data-reset="1" > <span class="glyphicon glyphicon-random" aria-hidden="true"></span> 8 Words </button> <button type="button" class="btn btn-success genWordsButton" data-words="9" data-rolls="5" data-reset="1" > <span class="glyphicon glyphicon-random" aria-hidden="true"></span> 9 Words </button> <button type="button" class="btn btn-success genWordsButton" data-words="10" data-rolls="5" data-reset="1" > <span class="glyphicon glyphicon-random" aria-hidden="true"></span> 10 Words </button> <button type="button" class="btn btn-default genWordsButton" data-words="1" data-rolls="5" data-reset="0" > <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Word </button> <button type="button" class="btn btn-default genWordsButton" data-words="1" data-rolls="2" data-reset="0" > <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Symbol </button> </div> <br /> <br /> <form id="addFiveDieRollWordForm" class="form-inline" data-toggle="validator" > <div class="form-group"> <label class="sr-only" for="addFiveDieRollWord" >Add Two or Five Die Roll</label > <div class="input-group"> <div class="input-group-addon">#</div> <input type="text" class="form-control" id="addFiveDieRollWord" placeholder="+ 2x or 5x die roll" maxlength="5" pattern="^[1-6]{2,5}$" autocomplete="off" autofocus /> </div> <span class="help-block with-errors"></span> </div> </form> <br /> <br /> <ul id="diceWords" class="list-inline"></ul> <br /> <br /> <div id="diceWordsCopyableContainer" class="well well-sm"> <span class="label label-default" >copyable text with spaces or dashes</span ><br /><br /> <code id="diceWordsCopyableSpace"></code> <button class="btn btn-default btn-xs copy-button" data-clipboard-action="copy" data-clipboard-target="#diceWordsCopyableSpace" > Copy</button ><br /> <code id="diceWordsCopyableDash"></code> <button class="btn btn-default btn-xs copy-button" data-clipboard-target="#diceWordsCopyableDash" > Copy </button> <br /> </div> <div id="entropyEstimateContainer" class="well well-sm"> <span class="label label-default">entropy stats</span><br /><br /> <p> There are <code id="totalWords"></code> words in your password, resulting in ~<code id="totalEntropy"></code> bits of entropy (~<code >12.92 bits/word</code >, ~<code>10 bits/letter</code>, and ~<code>5.16 bits/symbol</code>). That many words equates to a total keyspace of ~<code id="crackTimeResultsKeySpace" ></code> possible phrases <code>(7776^WordsInPhrase)</code>. An adversary might get lucky and guess your phrase on the first try, though the chances of that happening are very slim. On the other hand, the brute-force attacker might be forced to try all of the keys in the keyspace to finally find that the last guess was the correct one. On average, it takes trying 50% of all phrases in the keyspace to find your phrase. The time it takes to discover your passphrase is based on how many guesses per second your attacker can muster. At the lower end in 2016 a small cluster of GPU's have <a href="https://gist.github.com/epixoip/a83d38f412b4737e99bbef804a270c40/revisions" target="_blank" rel="noopener" >demonstrated the ability to crack</a > ~<code>350</code> billion hashes/second. A nation state actor like the NSA <a href="https://pthree.org/2013/04/16/password-attacks-part-i-the-brute-force-attack/" target="_blank" rel="noopener" >may be able to perform quadrillions/second</a >. Conservatively assuming a professional adversary can guess passwords at the rate of a <code id="crackTimeResultsGuessesPerSecond"></code> keys/second (<NAME> <a href="http://www.nytimes.com/2013/08/18/magazine/laura-poitras-snowden.html?pagewanted=all&_r=0" target="_blank" rel="noopener" >suggests being prepared for a Trillion guesses per second</a >), an exhaustive brute-force search on 50% of the total keyspace might take: </p> <p>~<code id="crackTimeResultsSeconds"></code> seconds</p> <p>~<code id="crackTimeResultsMinutes"></code> minutes</p> <p>~<code id="crackTimeResultsHours"></code> hours</p> <p>~<code id="crackTimeResultsDays"></code> days</p> <p>~<code id="crackTimeResultsYears"></code> years</p> <p> ~<code id="crackTimeResultsHumanLifetimes"></code> x avg. lifespan </p> <p>~<code id="crackTimeResultsMillenia"></code> millenia</p> <p> ~<code id="crackTimeResultsUniverseLifetimes"></code> x age Universe </p> <a href="http://world.std.com/~reinhold/dicewarefaq.html#calculatingentropy" target="_blank" rel="noopener" >Learn more about calculating entropy</a > </div> <hr /> <h2 class="text-muted">Frequently Asked Questions</h2> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">How do I use it?</h3> </div> <div class="panel-body"> <p> Click on one of the numbered passphrase generator buttons above. Click again to generate a totally new passphrase. </p> <p> The <code>+ Word</code> or <code>+ Symbol</code> buttons will enhance the strength of the existing passphrase. </p> <p> For extra security you can manually roll physical dice (two or five die rolls for each symbol or word respectively) and enter the results to add a word to your passphrase. </p> <p> Each word or symbol displayed is shown with the index number that was used to look it up in the diceware word list. </p> <p> You can copy the generated passphrase from the copyable string on the page. You should store it somewhere safe and secure. You might want to write it down and refer to the written version until you can remember it. </p> <p> Close your browser window once you're done so others can't discover your passphrase. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">What inspired you to create this?</h3> </div> <div class="panel-body"> I have been using Diceware for several years but its kind of a hassle for everyday passphrases. I wanted something that was easy to use, and yet secure for all but the most extreme security needs. Micah Lee's excellent overview in his article entitled <a href="https://firstlook.org/theintercept/2015/03/26/passphrases-can-memorize-attackers-cant-guess/" target="_blank" rel="noopener" >Passphrases That You Can Memorize — But That Even The NSA Can't Guess</a > is a great read on the topic. For me, this is about 'scratching my own itch' and using a tool I know I can trust. </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Is it safe?</h3> </div> <div class="panel-body"> It depends. Are you the target of a nation-state level adversary? If so, you should probably not use this and should instead use Diceware to roll real physical dice and look up the words from the wordlist manually. This is the official recommendation of the <a href="http://world.std.com/~reinhold/dicewarefaq.html#electronic" target="_blank" rel="noopener" >Diceware FAQ</a >. As a normal person, even if you have high security needs like protecting long term cryptographic keys, you should be safe using this tool. Using real dice is the most secure way, but relying on the random number generator should be safe as well. </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> Does this use a cryptographically strong random number generator to choose the words? </h3> </div> <div class="panel-body"> The JavaScript <code>window.crypto.getRandomValues()</code> CSPRNG that ships with modern browsers to get random bytes is used. You can learn more about <code ><a href="https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues" target="_blank" rel="noopener" >window.crypto.getRandomValues()</a ></code > and make your own determination as to its suitability. Many cryptographic library authors are now targeting the browser environment and most are using this API as their primary source of entropy so you are in good company. </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> What URL should I be using to access this application? </h3> </div> <div class="panel-body"> The canonical link for this version is <a href="https://www.rempe.us/diceware/" target="_blank" rel="noopener" >https://www.rempe.us/diceware/</a >. </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> Does this application send any data anywhere? </h3> </div> <div class="panel-body"> <p> No security sensitive information such as your selected passphrase size, die rolls, or the generated passphrase ever leaves your browser or is logged anywhere. Ever. Once the initial page is loaded as static files everything is done locally in your browser. In fact, once you load this application in your browser you can turn off your network connection and it should work just fine. Of course these guarantess only apply if you are viewing this page from a rempe.us domain. I don't suggest you use any other hosted version of this page unless you hosted it yourself. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> Where is the code for this application being served from? </h3> </div> <div class="panel-body"> The entire application is just HTML, JavaScript and CSS. There is no server side component and no database. All of the JavaScript and other assets are versioned in the repository and no code is served from outside of the repository. </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">How should I use this most safely?</h3> </div> <div class="panel-body"> <p>You should ensure that:</p> <ul> <li> You <a href="http://world.std.com/~reinhold/diceware.html" target="_blank" rel="noopener" >read about Diceware</a > and understand the strengths and limitations of this approach. </li> <li> Don't generate passphrases on a machine you don't own and control. No public machines! </li> <li> Make sure no one else is in the room with you that can 'shoulder surf'. </li> <li>You close the browser window, when you are done.</li> <li> You always visit this site over a TLS (HTTPS) connection. This is enforced with HSTS. A non-TLS HTTP connection opens you up to trivial man-in-the-middle attack on the code or the wordlists. </li> <li> You are using the <a href="http://www.whatismybrowser.com/" target="_blank" rel="noopener" >latest version of a modern browser</a >. </li> </ul> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Why is the EFF English word list the default?</h3> </div> <div class="panel-body"> <p> The <a href="https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases">EFF word list</a> provides a thoughtful word list that aligns with the goals of Diceware. Making memorable, harder to confuse, passphrases. Other word lists are provided, in various languages, for you to choose from. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">What is entropy?</h3> </div> <div class="panel-body"> <blockquote> <p> Entropy is a measure of the uncertainty or randomness of a system. The concept is a difficult one to grasp fully and is confusing, even to experts. Strictly speaking, any given passphrase has an entropy of zero because it is already chosen. It is the method you use to randomly select your passphrase that has entropy. Entropy tells how hard it will be to guess the passphrase itself even if an attacker knows the method you used to select your passphrase. A passphrase is more secure if it is selected using a method that has more entropy. </p> <p> Entropy is measured in bits. The outcome of a single coin toss -- "heads or tails" -- has one bit of entropy. </p> <footer> <NAME>. Reinhold - <cite title="Diceware FAQ" >Diceware <a href="http://world.std.com/~reinhold/dicewarefaq.html#entropy" target="_blank" rel="noopener" >FAQ</a ></cite > </footer> </blockquote> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">How are you measuring entropy?</h3> </div> <div class="panel-body"> <p> Each standard Diceware word is assigned ~12.92 bits of entropy (<code>Math.log2(7776)</code>), each special character added is ~5.16 bits (<code>Math.log2(36)</code>). The total is the sum of the entropy in each full word or special character. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> Is the source code available and can I run my own copy locally? </h3> </div> <div class="panel-body"> <p> <strong>Yes!</strong> The source code is <a href="https://github.com/grempe/diceware" target="_blank" rel="noopener" >available on Github</a >. Its a simple static HTML application and you can clone and run it by opening the <code>index.html</code> file in your browser. When run locally it should work when your computer is completely offline. The latest commits in the git repository are signed with my <a href="https://www.rempe.us/keys" target="_blank" rel="noopener" >public code signing key</a >. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Would XKCD approve?</h3> </div> <div class="panel-body"> <p> Yes, <a href="https://xkcd.com/936/" target="_blank" rel="noopener" >I believe so</a >. </p> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Who created this?</h3> </div> <div class="panel-body"> <ul> <li> <NAME> created Diceware. You can <a href="http://world.std.com/~reinhold/" target="_blank" rel="noopener" >find him online here</a >. </li> <li> <a href="http://www.iamben.co.uk/" target="_blank" rel="noopener" ><NAME></a > (<a href="http://twitter.com/yesiamben" target="_blank" rel="noopener" >@yesiamben</a >) created the first version of this application and did a really nice job of it. </li> <li> <a href="https://www.rempe.us/" target="_blank" rel="noopener" ><NAME></a > (<a href="http://twitter.com/grempe" target="_blank" rel="noopener" >@grempe</a >) was inspired by Ben's idea, enhanced its security, updated the code, and created a new user interface. </li> </ul> </div> </div> </div> <!-- /.container --> <!-- load third party libraries --> <script src="node_modules/jquery/dist/jquery.min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script src="node_modules/big.js/big.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script src="node_modules/bootstrap/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script src="node_modules/bootstrap-validator/dist/validator.min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script src="node_modules/clipboard/dist/clipboard.min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <!-- load the primary wordlist synchronously --> <script src="lists/special-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script src="lists/diceware-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script src="lists/eff.js" integrity="<KEY>" crossorigin="anonymous" ></script> <!-- load the secondary languages async --> <script async src="lists/alternative-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/basque-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/catalan-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/czech-min.js" integryty="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/danish.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/dutch-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/esperanto-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/finnish.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/french-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/german-dereko-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/german-tenne-min.js" integrity="<KEY> crossorigin="anonymous" ></script> <script async src="lists/hungarian-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/italian-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/japanese-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/maori-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/norwegian.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/polish-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/russian-min.js" integryty="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/spanish-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <script async src="lists/swedish-min.js" integrity="<KEY>" crossorigin="anonymous" ></script> <!-- core application JS --> <script src="index.js" integrity="<KEY>" crossorigin="anonymous" ></script> </body> </html>
curtsheller/diceware
<|start_filename|>hashmerge/combine_test.go<|end_filename|> // Copyright 2015, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package hashmerge import ( "hash/adler32" "hash/crc32" "hash/crc64" "strings" "testing" ) // shortString truncates long strings into something more human readable. func shortString(s string) string { if len(s) > 220 { s = s[:100] + "..." + s[len(s)-100:] } return s } func TestCombineAdler32(t *testing.T) { var golden = []struct { out uint32 in string }{ {0x00000001, ""}, {0x00620062, "a"}, {0x012600c4, "ab"}, {0x024d0127, "abc"}, {0x03d8018b, "abcd"}, {0x05c801f0, "abcde"}, {0x081e0256, "abcdef"}, {0x0adb02bd, "abcdefg"}, {0x0e000325, "abcdefgh"}, {0x118e038e, "abcdefghi"}, {0x158603f8, "abcdefghij"}, {0x3f090f02, "Discard medicine more than two years old."}, {0x46d81477, "He who has a shady past knows that nice guys finish last."}, {0x40ee0ee1, "I wouldn't marry him with a ten foot pole."}, {0x16661315, "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, {0x5b2e1480, "The days of the digital watch are numbered. -<NAME>"}, {0x8c3c09ea, "Nepal premier won't resign."}, {0x45ac18fd, "For every action there is an equal and opposite government program."}, {0x53c61462, "His money is twice tainted: 'taint yours and 'taint mine."}, {0x7e511e63, "There is no reason for any individual to have a computer in their home. -<NAME>, 1977"}, {0xe4801a6a, "It's a tiny change to the code and not completely disgusting. - <NAME>"}, {0x61b507df, "size: a.out: bad magic"}, {0xb8631171, "The major problem is with sendmail. -<NAME>"}, {0x8b5e1904, "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, {0x7cc6102b, "If the enemy is within range, then so are you."}, {0x700318e7, "It's well we cannot hear the screams/That we create in others' dreams."}, {0x1e601747, "You remind me of a TV show, but that's all right: I watch it anyway."}, {0xb55b0b09, "C is as portable as Stonehedge!!"}, {0x39111dd0, "Even if I could be Shakespeare, I think I should still choose to be Faraday. - <NAME>"}, {0x91dd304f, "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, {0x2e5d1316, "How can you write a big system without C++? -<NAME>"}, {0xd0201df6, "'Invariant assertions' is the most elegant programming technique! -<NAME>"}, {0x211297c8, strings.Repeat("\xff", 5548) + "8"}, {0xbaa198c8, strings.Repeat("\xff", 5549) + "9"}, {0x553499be, strings.Repeat("\xff", 5550) + "0"}, {0xf0c19abe, strings.Repeat("\xff", 5551) + "1"}, {0x8d5c9bbe, strings.Repeat("\xff", 5552) + "2"}, {0x2af69cbe, strings.Repeat("\xff", 5553) + "3"}, {0xc9809dbe, strings.Repeat("\xff", 5554) + "4"}, {0x69189ebe, strings.Repeat("\xff", 5555) + "5"}, {0x86af0001, strings.Repeat("\x00", 1e5)}, {0x79660b4d, strings.Repeat("a", 1e5)}, {0x110588ee, strings.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1e4)}, } for _, g := range golden { var splits = []int{ 0 * (len(g.in) / 1), 1 * (len(g.in) / 4), 2 * (len(g.in) / 4), 3 * (len(g.in) / 4), 1 * (len(g.in) / 1), } for _, i := range splits { p1, p2 := []byte(g.in[:i]), []byte(g.in[i:]) in1, in2 := shortString(g.in[:i]), shortString(g.in[i:]) len2 := int64(len(p2)) if got := CombineAdler32(adler32.Checksum(p1), adler32.Checksum(p2), len2); got != g.out { t.Errorf("CombineAdler32(Checksum(%q), Checksum(%q), %d) = 0x%x, want 0x%x", in1, in2, len2, got, g.out) } } } } func TestCombineCRC32(t *testing.T) { var golden = []struct { ieee, castagnoli, koopman uint32 in string }{ {0x00000000, 0x00000000, 0x00000000, ""}, {0xe8b7be43, 0xc1d04330, 0x0da2aa8a, "a"}, {0x9e83486d, 0xe2a22936, 0x31ec935a, "ab"}, {0x352441c2, 0x364b3fb7, 0xba2322ac, "abc"}, {0xed82cd11, 0x92c80a31, 0xe0a6bcf7, "abcd"}, {0x8587d865, 0xc450d697, 0xac046415, "abcde"}, {0x4b8e39ef, 0x53bceff1, 0x7589981b, "abcdef"}, {0x312a6aa6, 0xe627f441, 0x7999acb5, "abcdefg"}, {0xaeef2a50, 0x0a9421b7, 0xd5cc0e40, "abcdefgh"}, {0x8da988af, 0x2ddc99fc, 0x39080d0d, "abcdefghi"}, {0x3981703a, 0xe6599437, 0xd6205881, "abcdefghij"}, {0x6b9cdfe7, 0xb2cc01fe, 0x418f6bac, "Discard medicine more than two years old."}, {0xc90ef73f, 0x0e28207f, 0x847e1e04, "He who has a shady past knows that nice guys finish last."}, {0xb902341f, 0xbe93f964, 0x606bf5a6, "I wouldn't marry him with a ten foot pole."}, {0x042080e8, 0x9e3be0c3, 0x1521d7b7, "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, {0x154c6d11, 0xf505ef04, 0xe238d024, "The days of the digital watch are numbered. -<NAME>"}, {0x4c418325, 0x85d3dc82, 0x5423e28a, "Nepal premier won't resign."}, {0x33955150, 0xc5142380, 0x97f7c3a6, "For every action there is an equal and opposite government program."}, {0x26216a4b, 0x75eb77dd, 0xe4543ac6, "His money is twice tainted: 'taint yours and 'taint mine."}, {0x1abbe45e, 0x91ebe9f7, 0x48ec4d9a, "There is no reason for any individual to have a computer in their home. -<NAME>, 1977"}, {0xc89a94f7, 0xf0b1168e, 0xc75afda4, "It's a tiny change to the code and not completely disgusting. - <NAME>"}, {0xab3abe14, 0x572b74e2, 0x6db40154, "size: a.out: bad magic"}, {0xbab102b6, 0x8a58a6d5, 0x4c148ba0, "The major problem is with sendmail. -<NAME>"}, {0x999149d7, 0x9c426c50, 0x9be6c237, "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, {0x6d52a33c, 0x735400a4, 0x52f8abfc, "If the enemy is within range, then so are you."}, {0x90631e8d, 0xbec49c95, 0xf98e0b1d, "It's well we cannot hear the screams/That we create in others' dreams."}, {0x78309130, 0xa95a2079, 0x6a1d5514, "You remind me of a TV show, but that's all right: I watch it anyway."}, {0x7d0a377f, 0xde2e65c5, 0xd88bc947, "C is as portable as Stonehedge!!"}, {0x8c79fd79, 0x297a88ed, 0x5e625378, "Even if I could be Shakespeare, I think I should still choose to be Faraday. - <NAME>"}, {0xa20b7167, 0x66ed1d8b, 0xbd1004ed, "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, {0x8e0bb443, 0xdcded527, 0xd4575591, "How can you write a big system without C++? -<NAME>"}, } var ChecksumIEEE = func(data []byte) uint32 { return crc32.ChecksumIEEE(data) } var ChecksumCastagnoli = func(data []byte) uint32 { return crc32.Checksum(data, crc32.MakeTable(crc32.Castagnoli)) } var ChecksumKoopman = func(data []byte) uint32 { return crc32.Checksum(data, crc32.MakeTable(crc32.Koopman)) } for _, g := range golden { var splits = []int{ 0 * (len(g.in) / 1), 1 * (len(g.in) / 4), 2 * (len(g.in) / 4), 3 * (len(g.in) / 4), 1 * (len(g.in) / 1), } for _, i := range splits { p1, p2 := []byte(g.in[:i]), []byte(g.in[i:]) in1, in2 := g.in[:i], g.in[i:] len2 := int64(len(p2)) if got := CombineCRC32(crc32.IEEE, ChecksumIEEE(p1), ChecksumIEEE(p2), len2); got != g.ieee { t.Errorf("CombineCRC32(IEEE, ChecksumIEEE(%q), ChecksumIEEE(%q), %d) = 0x%x, want 0x%x", in1, in2, len2, got, g.ieee) } if got := CombineCRC32(crc32.Castagnoli, ChecksumCastagnoli(p1), ChecksumCastagnoli(p2), len2); got != g.castagnoli { t.Errorf("CombineCRC32(Castagnoli, ChecksumCastagnoli(%q), ChecksumCastagnoli(%q), %d) = 0x%x, want 0x%x", in1, in2, len2, got, g.castagnoli) } if got := CombineCRC32(crc32.Koopman, ChecksumKoopman(p1), ChecksumKoopman(p2), len2); got != g.koopman { t.Errorf("CombineCRC32(Koopman, ChecksumKoopman(%q), ChecksumKoopman(%q), %d) = 0x%x, want 0x%x", in1, in2, len2, got, g.koopman) } } } } func TestCombineCRC64(t *testing.T) { var golden = []struct { iso, ecma uint64 in string }{ {0x0000000000000000, 0x0000000000000000, ""}, {0x3420000000000000, 0x330284772e652b05, "a"}, {0x36c4200000000000, 0xbc6573200e84b046, "ab"}, {0x3776c42000000000, 0x2cd8094a1a277627, "abc"}, {0x336776c420000000, 0x3c9d28596e5960ba, "abcd"}, {0x32d36776c4200000, 0x040bdf58fb0895f2, "abcde"}, {0x3002d36776c42000, 0xd08e9f8545a700f4, "abcdef"}, {0x31b002d36776c420, 0xec20a3a8cc710e66, "abcdefg"}, {0x0e21b002d36776c4, 0x67b4f30a647a0c59, "abcdefgh"}, {0x8b6e21b002d36776, 0x9966f6c89d56ef8e, "abcdefghi"}, {0x7f5b6e21b002d367, 0x32093a2ecd5773f4, "abcdefghij"}, {0x8ec0e7c835bf9cdf, 0x8a0825223ea6d221, "Discard medicine more than two years old."}, {0xc7db1759e2be5ab4, 0x8562c0ac2ab9a00d, "He who has a shady past knows that nice guys finish last."}, {0xfbf9d9603a6fa020, 0x3ee2a39c083f38b4, "I wouldn't marry him with a ten foot pole."}, {0xeafc4211a6daa0ef, 0x1f603830353e518a, "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, {0x3e05b21c7a4dc4da, 0x02fd681d7b2421fd, "The days of the digital watch are numbered. -<NAME>"}, {0x5255866ad6ef28a6, 0x790ef2b16a745a41, "Nepal premier won't resign."}, {0x8a79895be1e9c361, 0x3ef8f06daccdcddf, "For every action there is an equal and opposite government program."}, {0x8878963a649d4916, 0x049e41b2660b106d, "His money is twice tainted: 'taint yours and 'taint mine."}, {0xa7b9d53ea87eb82f, 0x561cc0cfa235ac68, "There is no reason for any individual to have a computer in their home. -<NAME>, 1977"}, {0xdb6805c0966a2f9c, 0xd4fe9ef082e69f59, "It's a tiny change to the code and not completely disgusting. - <NAME>"}, {0xf3553c65dacdadd2, 0xe3b5e46cd8d63a4d, "size: a.out: bad magic"}, {0x9d5e034087a676b9, 0x865aaf6b94f2a051, "The major problem is with sendmail. -<NAME>"}, {0xa6db2d7f8da96417, 0x7eca10d2f8136eb4, "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, {0x325e00cd2fe819f9, 0xd7dd118c98e98727, "If the enemy is within range, then so are you."}, {0x88c6600ce58ae4c6, 0x70fb33c119c29318, "It's well we cannot hear the screams/That we create in others' dreams."}, {0x28c4a3f3b769e078, 0x57c891e39a97d9b7, "You remind me of a TV show, but that's all right: I watch it anyway."}, {0xa698a34c9d9f1dca, 0xa1f46ba20ad06eb7, "C is as portable as Stonehedge!!"}, {0xf6c1e2a8c26c5cfc, 0x7ad25fafa1710407, "Even if I could be Shakespeare, I think I should still choose to be Faraday. - <NAME>"}, {0x0d402559dfe9b70c, 0x73cef1666185c13f, "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, {0xdb6efff26aa94946, 0xb41858f73c389602, "How can you write a big system without C++? -<NAME>"}, } var ChecksumISO = func(data []byte) uint64 { return crc64.Checksum(data, crc64.MakeTable(crc64.ISO)) } var ChecksumECMA = func(data []byte) uint64 { return crc64.Checksum(data, crc64.MakeTable(crc64.ECMA)) } for _, g := range golden { var splits = []int{ 0 * (len(g.in) / 1), 1 * (len(g.in) / 4), 2 * (len(g.in) / 4), 3 * (len(g.in) / 4), 1 * (len(g.in) / 1), } for _, i := range splits { p1, p2 := []byte(g.in[:i]), []byte(g.in[i:]) in1, in2 := g.in[:i], g.in[i:] len2 := int64(len(p2)) if got := CombineCRC64(crc64.ISO, ChecksumISO(p1), ChecksumISO(p2), len2); got != g.iso { t.Errorf("CombineCRC64(ISO, ChecksumISO(%q), ChecksumISO(%q), %d) = 0x%x, want 0x%x", in1, in2, len2, got, g.iso) } if got := CombineCRC64(crc64.ECMA, ChecksumECMA(p1), ChecksumECMA(p2), len2); got != g.ecma { t.Errorf("CombineCRC64(ECMA, ChecksumECMA(%q), ChecksumECMA(%q), %d) = 0x%x, want 0x%x", in1, in2, len2, got, g.ecma) } } } } <|start_filename|>cron/cron_test.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package cron import ( "testing" "time" ) func TestSchedule(t *testing.T) { tests := []struct { schedule string events [][2]time.Time wantFail bool }{{ schedule: "daily", wantFail: true, }, { schedule: " 1-1,1,1,1,1,1 1,2,3,4,5,6,7,8,9,10,11,12 13 1-12,JAN-DEC 0-6,MON-FRI ", }, { schedule: "* * * * 7", // 7 does not represent SUN wantFail: true, }, { schedule: "423432432 * * * 0", wantFail: true, }, { schedule: "* * * * * *", wantFail: true, }, { schedule: "* * * * *", // Every minute events: [][2]time.Time{ {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC), time.Date(2000, 1, 2, 0, 1, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 1, 0, 0, time.UTC), time.Date(2000, 1, 2, 0, 2, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local), time.Date(2000, 1, 2, 0, 1, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 1, 0, 0, time.Local), time.Date(2000, 1, 2, 0, 2, 0, 0, time.Local)}, }, }, { schedule: "@daily", events: [][2]time.Time{ {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC), time.Date(2000, 1, 3, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local), time.Date(2000, 1, 3, 0, 0, 0, 0, time.Local)}, }, }, { schedule: "@weekly", events: [][2]time.Time{ {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC), time.Date(2000, 1, 9, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local), time.Date(2000, 1, 9, 0, 0, 0, 0, time.Local)}, }, }, { schedule: "0,15,30,45 * * * *", // Every 15 minutes events: [][2]time.Time{ {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC), time.Date(2000, 1, 2, 0, 15, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 15, 0, 0, time.UTC), time.Date(2000, 1, 2, 0, 30, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 30, 0, 0, time.UTC), time.Date(2000, 1, 2, 0, 45, 0, 0, time.UTC)}, {time.Date(2000, 1, 2, 0, 45, 0, 0, time.UTC), time.Date(2000, 1, 2, 1, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local), time.Date(2000, 1, 2, 0, 15, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 15, 0, 0, time.Local), time.Date(2000, 1, 2, 0, 30, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 30, 0, 0, time.Local), time.Date(2000, 1, 2, 0, 45, 0, 0, time.Local)}, {time.Date(2000, 1, 2, 0, 45, 0, 0, time.Local), time.Date(2000, 1, 2, 1, 0, 0, 0, time.Local)}, }, }, { schedule: "30 11-13 * MAR *", // Every 11th, 12th, and 13th hour in March events: [][2]time.Time{ {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 3, 1, 11, 30, 0, 0, time.UTC)}, {time.Date(2000, 3, 1, 11, 30, 0, 0, time.UTC), time.Date(2000, 3, 1, 12, 30, 0, 0, time.UTC)}, {time.Date(2000, 3, 1, 12, 30, 0, 0, time.UTC), time.Date(2000, 3, 1, 13, 30, 0, 0, time.UTC)}, {time.Date(2000, 3, 1, 13, 30, 0, 0, time.UTC), time.Date(2000, 3, 2, 11, 30, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.Local), time.Date(2000, 3, 1, 11, 30, 0, 0, time.Local)}, {time.Date(2000, 3, 1, 11, 30, 0, 0, time.Local), time.Date(2000, 3, 1, 12, 30, 0, 0, time.Local)}, {time.Date(2000, 3, 1, 12, 30, 0, 0, time.Local), time.Date(2000, 3, 1, 13, 30, 0, 0, time.Local)}, {time.Date(2000, 3, 1, 13, 30, 0, 0, time.Local), time.Date(2000, 3, 2, 11, 30, 0, 0, time.Local)}, }, }, { schedule: "0 0 * * MON-FRI", // Every work day at midnight events: [][2]time.Time{ {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 3, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 3, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 4, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 4, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 5, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 5, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 6, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 6, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 7, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 7, 23, 59, 59, 999999999, time.UTC), time.Date(2000, 1, 10, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 3, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 3, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 4, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 4, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 5, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 5, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 6, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 6, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 7, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 1, 7, 23, 59, 59, 999999999, time.Local), time.Date(2000, 1, 10, 0, 0, 0, 0, time.Local)}, }, }, { schedule: "0 0 29 2 *", // Feb 29th is only on leap year events: [][2]time.Time{ {time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(2000, 2, 29, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 2, 29, 0, 0, 0, 0, time.UTC), time.Date(2004, 2, 29, 0, 0, 0, 0, time.UTC)}, {time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local), time.Date(2000, 2, 29, 0, 0, 0, 0, time.Local)}, {time.Date(2000, 2, 29, 0, 0, 0, 0, time.Local), time.Date(2004, 2, 29, 0, 0, 0, 0, time.Local)}, }, }, { schedule: "0 0 30,31 2 *", // Feb 30th or 31st does not exist events: [][2]time.Time{ {time.Now(), time.Time{}}, }, }} for _, tt := range tests { s, err := ParseSchedule(tt.schedule) if gotFail := err != nil; gotFail != tt.wantFail { if gotFail { t.Errorf("ParseSchedule(%s) failure, want success", tt.schedule) } else { t.Errorf("ParseSchedule(%s) success, want failure", tt.schedule) } continue } for _, tc := range tt.events { in, want := tc[0], tc[1] if got := s.NextAfter(in); !got.Equal(want) { t.Errorf("ParseSchedule(%v).NextAfter(%v):\ngot %v\nwant %v", s, in, got, want) } } } } <|start_filename|>bufpipe/example_test.go<|end_filename|> // Copyright 2014, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package bufpipe_test import "io" import "fmt" import "time" import "sync" import "math/rand" import "github.com/dsnet/golib/bufpipe" func randomChars(cnt int, rand *rand.Rand) string { data := make([]byte, cnt) for idx := range data { char := byte(rand.Intn(10 + 26 + 26)) if char < 10 { data[idx] = '0' + char } else if char < 10+26 { data[idx] = 'A' + char - 10 } else { data[idx] = 'a' + char - 36 } } return string(data) } // In LineMono mode, the consumer cannot see the written data until the pipe is // closed. Thus, it is possible for the producer to go back to the front of the // pipe and record the total number of bytes written out. This functionality is // useful in cases where a file format's header contains information that is // dependent on what is eventually written. func ExampleBufferPipe_lineMono() { // The buffer is small enough such that the producer does hit the limit. buffer := bufpipe.NewBufferPipe(make([]byte, 256), bufpipe.LineMono) rand := rand.New(rand.NewSource(0)) group := new(sync.WaitGroup) group.Add(2) // Producer routine. go func() { defer group.Done() defer buffer.Close() // In LineMono mode only, it is safe to store a reference to written // data and modify later. header, _, err := buffer.WriteSlices() if err != nil { panic(err) } totalCnt, _ := buffer.Write([]byte("#### ")) for idx := 0; idx < 8; idx++ { data := randomChars(rand.Intn(64), rand) + "\n" // So long as the amount of data written has not exceeded the size // of the buffer, Write will never fail. cnt, err := buffer.Write([]byte(data)) totalCnt += cnt if err == io.ErrShortWrite { break } time.Sleep(100 * time.Millisecond) } // Write the header afterwards copy(header[:4], fmt.Sprintf("%04d", totalCnt)) }() // Consumer routine. go func() { defer group.Done() // In LineMono mode only, a call to ReadSlices is guaranteed to block // until the channel is closed. All written data will be made available. data, _, _ := buffer.ReadSlices() buffer.ReadMark(len(data)) // Technically, this is optional fmt.Println(string(data)) }() group.Wait() // Output: // 0256 kdUhQzHYs2LjaukXEC292UgLOCAPQTCNAKfc0XMNCUuJbsqiHmm6GJMFck // whxMYR1k // zhMYzktxIv10mIPqBCCwm646E6chwIFZfpX0fjqMu0YKLDhfIMnDq8w9J // fQhkT1qEkJfEI0jtbDnIrEXx6G4xMgXEB6auAyBUjPk2jMSgCMVZf8L1VgJemin // 2Quy1C5aA00KbYqawNeuXYTvgeUXGu3zyjMUoEIrOx7 // ecE4dY3ZaTrX03xBY } // In LineDual mode, the consumer sees produced data immediately as it becomes // available. The producer is only allowed to write as much data as the size of // the underlying buffer. The amount that can be written is independent of the // operation of the consumer. func ExampleBufferPipe_lineDual() { // The buffer is small enough such that the producer does hit the limit. buffer := bufpipe.NewBufferPipe(make([]byte, 256), bufpipe.LineDual) rand := rand.New(rand.NewSource(0)) group := new(sync.WaitGroup) group.Add(2) // Producer routine. go func() { defer group.Done() defer buffer.Close() buffer.Write([]byte("#### ")) // Write a fake header for idx := 0; idx < 8; idx++ { data := randomChars(rand.Intn(64), rand) + "\n" // So long as the amount of data written has not exceeded the size // of the buffer, Write will never fail. if _, err := buffer.Write([]byte(data)); err == io.ErrShortWrite { break } time.Sleep(100 * time.Millisecond) } }() // Consumer routine. go func() { defer group.Done() for { // Reading can be also done using ReadSlices and ReadMark pairs. data, _, err := buffer.ReadSlices() if err == io.EOF { break } else if err != nil { panic(err) } buffer.ReadMark(len(data)) fmt.Print(string(data)) } fmt.Println() }() group.Wait() // Output: // #### kdUhQzHYs2LjaukXEC292UgLOCAPQTCNAKfc0XMNCUuJbsqiHmm6GJMFck // whxMYR1k // zhMYzktxIv10mIPqBCCwm646E6chwIFZfpX0fjqMu0YKLDhfIMnDq8w9J // fQhkT1qEkJfEI0jtbDnIrEXx6G4xMgXEB6auAyBUjPk2jMSgCMVZf8L1VgJemin // 2Quy1C5aA00KbYqawNeuXYTvgeUXGu3zyjMUoEIrOx7 // ecE4dY3ZaTrX03xBY } // In RingBlock mode, the consumer sees produced data immediately as it becomes // available. The producer is allowed to write as much data as it wants so long // as the consumer continues to read the data in the pipe. func ExampleBufferPipe_ringBlock() { // Intentionally small buffer to show that data written into the buffer // can exceed the size of the buffer itself. buffer := bufpipe.NewBufferPipe(make([]byte, 64), bufpipe.RingBlock) rand := rand.New(rand.NewSource(0)) group := new(sync.WaitGroup) group.Add(2) // Producer routine. go func() { defer group.Done() defer buffer.Close() buffer.Write([]byte("#### ")) // Write a fake header for idx := 0; idx < 8; idx++ { data := randomChars(rand.Intn(64), rand) + "\n" // So long as the amount of data written has not exceeded the size // of the buffer, Write will never fail. buffer.Write([]byte(data)) time.Sleep(100 * time.Millisecond) } }() // Consumer routine. go func() { defer group.Done() data := make([]byte, 64) for { // Reading can also be done using the Read method. cnt, err := buffer.Read(data) fmt.Print(string(data[:cnt])) if err == io.EOF { break } } fmt.Println() }() group.Wait() // Output: // #### kdUhQzHYs2LjaukXEC292UgLOCAPQTCNAKfc0XMNCUuJbsqiHmm6GJMFck // whxMYR1k // zhMYzktxIv10mIPqBCCwm646E6chwIFZfpX0fjqMu0YKLDhfIMnDq8w9J // <KEY> // <KEY> // <KEY> // <KEY> // <KEY> } <|start_filename|>jsonfmt/jsonfmt.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. // +build ignore package main import ( "flag" "io/ioutil" "log" "os" "path/filepath" "github.com/dsnet/golib/jsonfmt" ) func main() { minify := flag.Bool("minify", false, "produce minified output") standardize := flag.Bool("standardize", false, "produce ECMA-404 compliant output") flag.Parse() var opts []jsonfmt.Option if *minify { opts = append(opts, jsonfmt.Minify()) } if *standardize { opts = append(opts, jsonfmt.Standardize()) } if len(flag.Args()) > 0 { for _, path := range flag.Args() { in, err := ioutil.ReadFile(path) if err != nil { log.Fatalf("ioutil.ReadFile error: %v", err) } out, err := jsonfmt.Format(in, opts...) if err != nil { log.Fatalf("jsonfmt.Format error: %v", err) } if err := replaceFile(path, out); err != nil { log.Fatalf("replaceFile error: %v", err) } } } else { in, err := ioutil.ReadAll(os.Stdin) if err != nil { log.Fatalf("ioutil.ReadAll error: %v", err) } out, err := jsonfmt.Format(in, opts...) if err != nil { log.Fatalf("jsonfmt.Format error: %v", err) } if _, err := os.Stdout.Write(out); err != nil { log.Fatalf("os.Stdout.Write error: %v", err) } } } func replaceFile(path string, b []byte) error { fi, err := os.Stat(path) if err != nil { return err } f, err := ioutil.TempFile(filepath.Dir(path), "tmp") if err != nil { return err } defer os.Remove(f.Name()) if err := f.Chmod(fi.Mode()); err != nil { return err } if _, err := f.Write(b); err != nil { return err } if err := f.Close(); err != nil { return err } return os.Rename(f.Name(), path) } <|start_filename|>jsonfmt/parse.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package jsonfmt import ( "bytes" "fmt" "math" "regexp" "strconv" "unicode/utf8" ) var ( stringRx = `"(\\(["\\\/bfnrt]|u[a-fA-F0-9]{4})|[^"\\\x00-\x1f\x7f]+)*"` numberRx = `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?` literalRx = `(true|false|null)` commentRx = `(/\*([^\n]|\n)*?\*/|//[^\n]*\n?)` spaceRx = `[ \r\n\t]*` stringRegex = regexp.MustCompile("^" + stringRx) numberRegex = regexp.MustCompile("^" + numberRx) literalRegex = regexp.MustCompile("^" + literalRx) commentRegex = regexp.MustCompile("^" + commentRx) spaceRegex = regexp.MustCompile("^" + spaceRx) ) func (s *state) parse(in []byte) (err error) { defer func() { if ex := recover(); ex != nil { if je, ok := ex.(jsonError); ok { // Insert line/column information to the error message. parsed := in[:len(in)-len(s.in)] je.line = bytes.Count(parsed, newlineBytes) + 1 if i := bytes.LastIndexByte(parsed, '\n'); i >= 0 { parsed = parsed[i+len("\n"):] } je.column = len(parsed) + 1 err = je // Insert the remainder input to the last node. switch js := s.last.(type) { case *jsonValue: *js = jsonInvalid(s.in) case *jsonMeta: *js = append(*js, jsonInvalid(s.in)) } s.in = nil } else { panic(ex) } } }() s.in = in s.parseMeta(&s.preVal) s.parseValue(&s.val) s.parseMeta(&s.postVal) if len(s.in) > 0 { panic(s.errorf("unexpected trailing input: %s", bytesPreview(s.in))) } return } func (s *state) parseValue(js *jsonValue) { s.last = js switch s.nextChar() { case '{': s.parseObject(js) case '[': s.parseArray(js) case '"': s.parseString(js) case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': s.parseNumber(js) case 't', 'f', 'n': s.parseLiteral(js) default: if len(s.in) == 0 { panic(s.errorf("unable to parse value: unexpected EOF")) } panic(s.errorf("unable to parse value: unexpected %q", s.in[0])) } } func (s *state) parseObject(js *jsonValue) { obj := new(jsonObject) *js = obj var trailingComma bool s.parseChar('{', "object") s.parseMeta(&obj.preRecords) for s.nextChar() != '}' { obj.records = append(obj.records, jsonRecord{}) rec := &obj.records[len(obj.records)-1] s.parseString(&rec.key) s.parseMeta(&rec.postKey) s.parseChar(':', "object") s.parseMeta(&rec.preVal) s.parseValue(&rec.val) s.parseMeta(&rec.postVal) if s.nextChar() == '}' { rec.postVal, rec.postComma = nil, rec.postVal trailingComma = false break } s.parseChar(',', "object") s.parseMeta(&rec.postComma) trailingComma = true } s.parseChar('}', "object") s.trailingComma = s.trailingComma || trailingComma var meta jsonMeta obj.preRecords, meta = splitMeta(obj.preRecords) for i := range obj.records { obj.records[i].preKey = meta obj.records[i].postComma, meta = splitMeta(obj.records[i].postComma) } obj.postRecords = meta } func (s *state) parseArray(js *jsonValue) { arr := new(jsonArray) *js = arr var trailingComma bool s.parseChar('[', "array") s.parseMeta(&arr.preElems) for s.nextChar() != ']' { arr.elems = append(arr.elems, jsonElement{}) elem := &arr.elems[len(arr.elems)-1] s.parseValue(&elem.val) s.parseMeta(&elem.postVal) if s.nextChar() == ']' { elem.postVal, elem.postComma = nil, elem.postVal trailingComma = false break } s.parseChar(',', "array") s.parseMeta(&elem.postComma) trailingComma = true } s.parseChar(']', "array") s.trailingComma = s.trailingComma || trailingComma var meta jsonMeta arr.preElems, meta = splitMeta(arr.preElems) for i := range arr.elems { arr.elems[i].preVal = meta arr.elems[i].postComma, meta = splitMeta(arr.elems[i].postComma) } arr.postElems = meta } func (s *state) parseString(js *jsonValue) { b := stringRegex.Find(s.in) if len(b) == 0 { panic(s.errorf("unable to parse string: %s", bytesPreview(s.in))) } *js, s.in = jsonString(recodeString(b)), s.in[len(b):] } func (s *state) parseNumber(js *jsonValue) { b := numberRegex.Find(s.in) if len(b) == 0 { panic(s.errorf("unable to parse number: %s", bytesPreview(s.in))) } *js, s.in = jsonNumber(recodeNumber(b)), s.in[len(b):] } func (s *state) parseLiteral(js *jsonValue) { b := literalRegex.Find(s.in) if len(b) == 0 { panic(s.errorf("unable to parse literal: %s", bytesPreview(s.in))) } *js, s.in = jsonLiteral(b), s.in[len(b):] } func (s *state) parseMeta(js *jsonMeta) { s.last = js for { if b := commentRegex.Find(s.in); len(b) > 0 { b = bytes.TrimRight(b, "\n") if !s.standardize { *js = append(*js, jsonComment(b)) } s.in = s.in[len(b):] continue } if b := spaceRegex.Find(s.in); len(b) > 0 { if !s.minify { if n := bytes.Count(b, newlineBytes); n > 0 { if len(*js) == 0 { *js = append(*js, jsonNewlines(n)) } else if nl, ok := (*js)[len(*js)-1].(jsonNewlines); ok { (*js)[len(*js)-1] = nl + jsonNewlines(n) } else { *js = append(*js, jsonNewlines(n)) } } } s.in = s.in[len(b):] continue } break } } // parseChar parses the next character for want. // If the next char is not want, this panics with a descriptive jsonError. func (s *state) parseChar(want byte, what string) { if got := s.nextChar(); got != want { if len(s.in) == 0 { panic(s.errorf("unable to parse %s: unexpected EOF", what)) } panic(s.errorf("unable to parse %s: got %q, expected %q", what, got, want)) } s.in = s.in[1:] } // nextChat reports the next character in the input, returning 0 if EOF. func (s *state) nextChar() byte { if len(s.in) == 0 { return 0 } return s.in[0] } func (s *state) errorf(f string, x ...interface{}) error { return jsonError{message: fmt.Sprintf(f, x...)} } var hexLUT = [256]rune{ '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, } // recodeString decodes a JSON string and re-encodes it such that it uses // UTF-8 when possible instead of the \uXXXX notation. // This assumes that the input has already been validated. // This does not mutate the input, but may alias it. func recodeString(in []byte) (out []byte) { // TODO: Support other string encoding options: // * Verbatim: return input as is. // * SafeJS: escapes U+2028 and U+2029 with the \u notation. // * SafeHTML: escapes '<', '>', and '&' with the \u notation. // * OnlyASCII: escapes all Unicode with \u notation. var rb [utf8.UTFMax]byte out = append(out, '"') in = in[1 : len(in)-1] for len(in) > 0 { switch c := in[0]; { case c == '\\': switch in[1] { case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': out = append(out, in[:2]...) // Copy ad-verbatim in = in[2:] case 'u': r := (hexLUT[in[2]] << 12) + (hexLUT[in[3]] << 8) + (hexLUT[in[4]] << 4) + (hexLUT[in[5]] << 0) out = append(out, rb[:utf8.EncodeRune(rb[:], r)]...) in = in[6:] } continue case c < utf8.RuneSelf: out = append(out, c) // Copy ad-verbatim in = in[1:] default: r, n := utf8.DecodeRune(in) // Copy ad-verbatim except for rune errors out = append(out, rb[:utf8.EncodeRune(rb[:], r)]...) in = in[n:] } } return append(out, '"') } // recodeNumber re-encodes the number is a possibly shorter form. // This does not mutate the input, but may alias it. func recodeNumber(in []byte) (out []byte) { // TODO: Support other float encoding options: // * Verbatim: return input as is. // * Precision: control bit precision. f, err := strconv.ParseFloat(string(in), 64) if err != nil { return in } if abs := math.Abs(f); abs != 0 && abs < 1e-6 || abs >= 1e21 { out = strconv.AppendFloat(nil, f, 'e', -1, 64) } else { out = strconv.AppendFloat(nil, f, 'f', -1, 64) } if len(in) < len(out) { return in } return out } // splitMeta splits the input such that any meta nodes without newlines are // split off as the second pair. func splitMeta(js jsonMeta) (jsonMeta, jsonMeta) { for i := len(js) - 1; i >= 0; i-- { if _, ok := js[i].(jsonNewlines); ok { return js[:i+1], js[i+1:] } } return nil, js } func bytesPreview(b []byte) string { const prevLen = 8 if len(b) > prevLen { return fmt.Sprintf("%q...", b[:prevLen]) } return fmt.Sprintf("%q", b) } <|start_filename|>memfile/file_test.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package memfile import ( "io" "io/ioutil" "os" "strings" "testing" ) func TestFile(t *testing.T) { type ( testRead struct { cnt int wantData string wantErr error } testReadAt struct { cnt int pos int64 wantData string wantErr error } testWrite struct { data string wantCnt int wantErr error } testWriteAt struct { data string pos int64 wantCnt int wantErr error } testSeek struct { offset int64 whence int wantPos int64 wantErr error } testTruncate struct { size int64 wantErr error } testBytes struct { wantData string } ) sz := func(n int) string { return strings.Repeat("\x00", n) } tests := []interface{}{ // []T where T is one of the testX types above testRead{10, "", io.EOF}, testSeek{5, io.SeekEnd, 5, nil}, testSeek{5, io.SeekEnd, 5, nil}, testWrite{"abcdefghijklmnopqrstuvwxyz", 26, nil}, testTruncate{25, nil}, testBytes{sz(5) + "abcdefghijklmnopqrst"}, testTruncate{-1, errInvalid}, testTruncate{10, nil}, testWriteAt{"ABCDE", 15, 5, nil}, testBytes{sz(5) + "abcde" + sz(5) + "ABCDE"}, testReadAt{10, 15, "ABCDE", io.EOF}, testReadAt{10, -15, "", errInvalid}, testWriteAt{"ABCDE", -15, 0, errInvalid}, testReadAt{8, 3, sz(2) + "abcde" + sz(1), nil}, testSeek{0, io.SeekCurrent, 31, nil}, testSeek{-32, io.SeekCurrent, 0, errInvalid}, testSeek{-11, io.SeekCurrent, 20, nil}, testWrite{"#", 1, nil}, testBytes{sz(5) + "abcde" + sz(5) + "ABCDE#"}, testTruncate{0, nil}, testWrite{"#", 1, nil}, testBytes{sz(21) + "#"}, testSeek{5, io.SeekStart, 5, nil}, testWrite{"12345", 5, nil}, testSeek{5, io.SeekStart, 5, nil}, testRead{5, "12345", nil}, testSeek{-23, io.SeekEnd, 0, errInvalid}, testSeek{0, io.SeekEnd, 22, nil}, testSeek{-22, io.SeekEnd, 0, nil}, testRead{10, sz(5) + "12345", nil}, testSeek{0, io.SeekCurrent, 10, nil}, testTruncate{0, nil}, testBytes{""}, } // Create a new File that emulates a file's operations. fb := new(File) // Open a temporary file to match behavior with. ft, err := ioutil.TempFile("", "") if err != nil { t.Fatal(err) } defer ft.Close() defer os.Remove(ft.Name()) for i, tt := range tests { switch tt := tt.(type) { case testRead: b := make([]byte, tt.cnt) n, gotErr := readFull(fb, b) gotData := string(b[:n]) if gotData != tt.wantData || gotErr != tt.wantErr { t.Fatalf("test %d, Read():\ngot (%q, %v)\nwant (%q, %v)", i, gotData, gotErr, tt.wantData, tt.wantErr) } n, wantErr := readFull(ft, b) wantData := string(b[:n]) if gotData != wantData || (gotErr == nil) != (wantErr == nil) { t.Fatalf("test %d, Read():\ngot (%q, %v)\nwant (%q, %v)", i, gotData, gotErr, wantData, wantErr) } case testReadAt: b := make([]byte, tt.cnt) n, gotErr := fb.ReadAt(b, tt.pos) gotData := string(b[:n]) if gotData != tt.wantData || gotErr != tt.wantErr { t.Fatalf("test %d, ReadAt():\ngot (%q, %v)\nwant (%q, %v)", i, gotData, gotErr, tt.wantData, tt.wantErr) } n, wantErr := ft.ReadAt(b, tt.pos) wantData := string(b[:n]) if gotData != wantData || (gotErr == nil) != (wantErr == nil) { t.Fatalf("test %d, ReadAt():\ngot (%q, %v)\nwant (%q, %v)", i, gotData, gotErr, wantData, wantErr) } case testWrite: gotCnt, gotErr := fb.Write([]byte(tt.data)) if gotCnt != tt.wantCnt || gotErr != tt.wantErr { t.Fatalf("test %d, Write():\ngot (%d, %v)\nwant (%d, %v)", i, gotCnt, gotErr, tt.wantCnt, tt.wantErr) } wantCnt, wantErr := ft.Write([]byte(tt.data)) if gotCnt != wantCnt || (gotErr == nil) != (wantErr == nil) { t.Fatalf("test %d, Write():\ngot (%d, %v)\nwant (%d, %v)", i, gotCnt, gotErr, wantCnt, wantErr) } case testWriteAt: gotCnt, gotErr := fb.WriteAt([]byte(tt.data), tt.pos) if gotCnt != tt.wantCnt || gotErr != tt.wantErr { t.Fatalf("test %d, WriteAt():\ngot (%d, %v)\nwant (%d, %v)", i, gotCnt, gotErr, tt.wantCnt, tt.wantErr) } wantCnt, wantErr := ft.WriteAt([]byte(tt.data), tt.pos) if gotCnt != wantCnt || (gotErr == nil) != (wantErr == nil) { t.Fatalf("test %d, WriteAt():\ngot (%d, %v)\nwant (%d, %v)", i, gotCnt, gotErr, wantCnt, wantErr) } case testSeek: gotPos, gotErr := fb.Seek(tt.offset, tt.whence) if gotPos != tt.wantPos || gotErr != tt.wantErr { t.Fatalf("test %d, Seek():\ngot (%d, %v)\nwant (%d, %v)", i, gotPos, gotErr, tt.wantPos, tt.wantErr) } wantPos, wantErr := ft.Seek(tt.offset, tt.whence) if gotPos != wantPos || (gotErr == nil) != (wantErr == nil) { t.Fatalf("test %d, Seek():\ngot (%d, %v)\nwant (%d, %v)", i, gotPos, gotErr, wantPos, wantErr) } case testTruncate: gotErr := fb.Truncate(tt.size) if gotErr != tt.wantErr { t.Fatalf("test %d, Truncate() = %v, want %v", i, gotErr, tt.wantErr) } wantErr := ft.Truncate(tt.size) if (gotErr == nil) != (wantErr == nil) { t.Fatalf("test %d, Truncate() = %v, want %v", i, gotErr, wantErr) } case testBytes: gotData := string(fb.Bytes()) if gotData != tt.wantData { t.Fatalf("test %d, Bytes():\ngot %q\nwant %q", i, gotData, tt.wantData) } wantData, err := ioutil.ReadFile(ft.Name()) if err != nil { t.Fatalf("test %d, unexpected ReadFile error: %v", i, err) } if gotData != string(wantData) { t.Fatalf("test %d, Bytes():\ngot %q\nwant %q", i, gotData, wantData) } default: t.Fatalf("test %d, unknown test operation: %T", i, tt) } } } func readFull(r io.Reader, b []byte) (n int, err error) { b0 := b for len(b) > 0 && err == nil { n, err = r.Read(b) b = b[n:] } if len(b) == 0 && err == io.EOF { err = nil } return len(b0) - len(b), err } <|start_filename|>jsonfmt/align.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package jsonfmt import ( "bytes" "fmt" "regexp" "strings" ) // tokenRegex is a regexp for any valid JSON token (not including comments). var tokenRegex = regexp.MustCompile(fmt.Sprintf("^(%s)", strings.Join([]string{stringRx, numberRx, literalRx, spaceRx}, "|"))) // alignJSON inserts spaces into certain lines in the input to // to achieve some form of vertical alignment across related lines. func alignJSON(in []byte, alignLimit int) (out []byte) { if alignLimit <= 0 { return in } // Parse the JSON structure on a line-by-line basis. // TODO: Should we just record this information in format? lines := bytes.Split(in, newlineBytes) infos := make([]lineInfo, len(lines)) var inBlockComment bool for i, line := range lines { nl := len(line) info := &infos[i] if inBlockComment { info.numIndents = -1 // Invalidate alignment for this line } else { info.numIndents = len(indentPrefix(line)) } var hasTokens bool var lastComma bool for len(line) > 0 { if inBlockComment { if j := bytes.Index(line, []byte("*/")); j >= 0 { inBlockComment = false line = line[j+len("*/"):] } else { line = nil } continue } if b := tokenRegex.Find(line); len(b) > 0 { hasTokens = true line = line[len(b):] // Ignore any other JSON token continue } switch line[0] { case '/': // Handle comments inBlockComment = len(line) > 1 && line[1] == '*' if !inBlockComment { if hasTokens { // First comment is not "end" comment info.commentOffset = nl - len(line) } line = nil // Rest of line is comment } continue case '{', '[': // Record open braces info.bracesBalance++ case '}', ']': // Record close braces info.bracesBalance-- case ':', ',': // Record alignment markers if len(info.alignOffsets) > 0 && info.alignBracesLevel == info.bracesBalance { info.alignOffsets = append(info.alignOffsets, nl-len(line)+1) lastComma = line[0] == ',' } else if len(info.alignOffsets) == 0 && line[0] == ':' { info.alignOffsets = append(info.alignOffsets, nl-len(line)+1) info.alignBracesLevel = info.bracesBalance } default: return in // Invalid JSON } line = line[1:] } if lastComma { info.alignOffsets = info.alignOffsets[:len(info.alignOffsets)-1] } } // For each indented group, align according to each marker and end comment. for i := 0; i < len(infos); { infoGroup := nextGroup(infos[i:]) if len(infoGroup) > 1 { var maxAligns int // Maximum number of align markers for _, li := range infoGroup { if len(li.alignOffsets) > maxAligns { maxAligns = len(li.alignOffsets) } } lineGroup := lines[i : i+len(infoGroup)] for j := 0; j < maxAligns; j++ { alignPositions(lineGroup, infoGroup, j, alignLimit) // Align markers } alignPositions(lineGroup, infoGroup, -1, alignLimit) // Align comments } i += len(infoGroup) } return bytes.Join(lines, newlineBytes) } type lineInfo struct { numIndents int // Number of preceding indents bracesBalance int // Incremented for '{' or '['; decremented for '}' or ']' alignBracesLevel int // Value of bracesBalance at first append alignOffsets []int // Offset of ':' and ',' in same brace level commentOffset int // Offset of trailing comment } // alignOffset returns the offset into the line for the i-th align marker. // A negative i returns the offset of the end comment. // An offset of zero implies that it is invalid. func (li *lineInfo) alignOffset(i int) int { if i < 0 { return li.commentOffset } if i < len(li.alignOffsets) { return li.alignOffsets[i] } return 0 } // insertSpaces inserts n spaces at pos into line. // This also updates lineInfo to account for the shifted offsets. func (li *lineInfo) insertSpaces(line []byte, pos, n int) []byte { if n <= 0 || pos >= len(line) { return line } for i, p := range li.alignOffsets { if p > pos { li.alignOffsets[i] = p + n } } if li.commentOffset > pos { li.commentOffset += n } // TODO: This is inefficient because of repeated copying. line = append(line[:pos:pos], append(bytes.Repeat(spaceBytes, n), line[pos:]...)...) return line } // nextGroup returns the next set of infos that are grouped together // based on their indent level. This always returns a non-empty slice // if the input is non-empty. func nextGroup(infos []lineInfo) []lineInfo { if len(infos) <= 1 { return infos } li0 := infos[0] n := 1 if li0.numIndents < 0 || li0.bracesBalance != 0 { return infos[:n] } for _, li := range infos[1:] { if li.numIndents != li0.numIndents || li.bracesBalance != 0 { return infos[:n] } n++ } return infos[:n] } // alignPositions takes in a set of lines (and their associated lineInfos) // and aligns each line for the idx-th (-1 for end comment) align marker. // The limit controls the maximum number of spaces added to achieve alignment. func alignPositions(lines [][]byte, infos []lineInfo, idx int, limit int) { for len(infos) > 1 { li0 := infos[0] pos0 := li0.alignOffset(idx) if pos0 == 0 { infos, lines = infos[1:], lines[1:] continue } // Cluster infos into a subgroup to align together. n := 1 maxPos := pos0 for _, li := range infos[1:] { pos := li.alignOffset(idx) if pos == 0 || pos > pos0+limit || pos < pos0-limit { break } if maxPos < pos { maxPos = pos } n++ } // Align the subgroup. for i, li := range infos[:n] { pos := li.alignOffset(idx) lines[i] = infos[i].insertSpaces(lines[i], pos, maxPos-pos) } infos, lines = infos[n:], lines[n:] } } <|start_filename|>unitconv/example_test.go<|end_filename|> // Copyright 2015, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package unitconv_test import ( "fmt" "github.com/dsnet/golib/unitconv" ) func ExampleAppendPrefix() { b1 := []byte("Distance from SF to LA: ") b1 = unitconv.AppendPrefix(b1, 616379, unitconv.SI, -1) b1 = append(b1, 'm') fmt.Println(string(b1)) b2 := []byte("Capacity of a DVD: ") b2 = unitconv.AppendPrefix(b2, 4.7*unitconv.Giga, unitconv.IEC, 2) b2 = append(b2, 'B') fmt.Println(string(b2)) // Output: // Distance from SF to LA: 616.379km // Capacity of a DVD: 4.38GiB } func ExampleFormatPrefix() { s1 := unitconv.FormatPrefix(unitconv.Tebi, unitconv.SI, 3) fmt.Printf("1 tebibyte in SI: %sB\n", s1) s2 := unitconv.FormatPrefix(unitconv.Tera, unitconv.IEC, 3) fmt.Printf("1 terabyte in IEC: %sB\n", s2) // Output: // 1 tebibyte in SI: 1.100TB // 1 terabyte in IEC: 931.323GiB } func ExampleParsePrefix() { if s, err := unitconv.ParsePrefix("2.99792458E8", unitconv.AutoParse); err == nil { fmt.Printf("Speed of light: %.0fm/s\n", s) } if s, err := unitconv.ParsePrefix("616.379k", unitconv.SI); err == nil { fmt.Printf("Distance from LA to SF: %.0fm\n", s) } if s, err := unitconv.ParsePrefix("32M", unitconv.Base1024); err == nil { fmt.Printf("Max FAT12 partition size: %.0fB\n", s) } if s, err := unitconv.ParsePrefix("1Ti", unitconv.IEC); err == nil { fmt.Printf("Number of bytes in tebibyte: %.0fB\n", s) } // Output: // Speed of light: 299792458m/s // Distance from LA to SF: 616379m // Max FAT12 partition size: 33554432B // Number of bytes in tebibyte: 1099511627776B } <|start_filename|>bufpipe/bufpipe.go<|end_filename|> // Copyright 2014, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. // Package bufpipe implements a buffered pipe. package bufpipe import "io" import "sync" // There are a number of modes of operation that BufferPipe can operate in. // // As such, there are 4 different (and mostly orthogonal) flags that can be // bitwise ORed together to create the mode of operation. Thus, with 4 flags, // there are technically 16 different possible combinations (although, some of // them are illogical). All 16 combinations are allowed, even if no sensible // programmer should be using them. // // The first flag determines the buffer's structure (linear vs. ring). In linear // mode, a writer can only write up to the internal buffer length's worth of // data. On the other hand, in ring mode, the buffer is treated like a circular // buffer and allow indefinite reading and writing. // // The second flag determines concurrent access to the pipe (mono vs. dual). // In mono access mode, the writer has sole access to the pipe. Only after the // Close method is called can a reader start reading data. In dual access // mode, readers can read written data the moment it is ready. // // The third and fourth flag determines waiting protocol for reading and writing // (polling vs. blocking). In blocking mode, a writer or reader will block until // there is available buffer space or valid data to consume. In polling mode, // read and write operations return immediately, possibly with an ErrShortWrite // or ErrNoProgress error. // // Combining Ring with Mono is an illogical combination. Mono access dictates // that no reader can drain the pipe until it is closed. However, the benefit // of a Ring buffer is that it can circularly write data as a reader consumes // the input. Ring with Mono is effectively Line with Mono. // // Combining Line with BlockI is an illogical combination. In Line mode, the // amount that can be written is fixed and independent of how much is read. // Thus, using BlockI in this case will cause the writer to block forever when // the buffer is full. // // With all illogical combinations removed, there are only 8 logical // combinations that programmers should use. const ( Ring = 1 << iota // Ring buffer vs. linear buffer Dual // Dual access IO vs. mono access IO BlockI // Blocking input vs. polling input BlockO // Blocking output vs. polling output // The below flags are the inverse of the ones above. They exist to make it // obvious what the inverse is. Line = 0 // Inverse of Ring Mono = 0 // Inverse of Dual PollI = 0 // Inverse of BlockI PollO = 0 // Inverse of BlockO ) // The most common combination of flags are predefined with convenient aliases. const ( LineMono = Line | Mono | PollI | BlockO LineDual = Line | Dual | PollI | BlockO RingPoll = Ring | Dual | PollI | PollO RingBlock = Ring | Dual | BlockI | BlockO ) type BufferPipe struct { buf []byte mode int rdPtr int64 wrPtr int64 closed bool err error mutex sync.Mutex rdCond sync.Cond wrCond sync.Cond } // BufferPipe is similar in operation to io.Pipe and is intended to be the // communication channel between producer and consumer routines. There are some // specific use cases for BufferPipes over io.Pipe. // // First, in cases where a writer may need to go back a modify a portion of the // past "written" data before allowing the reader to consume it. // Second, for performance applications, where the cost of copying of data is // noticeable. Thus, it would be more efficient to read/write data from/to the // internal buffer directly. // // See the defined constants for more on the buffer mode of operation. func NewBufferPipe(buf []byte, mode int) *BufferPipe { b := new(BufferPipe) b.buf = buf b.mode = mode b.rdCond.L = &b.mutex b.wrCond.L = &b.mutex return b } // The entire internal buffer. Be careful when touching the raw buffer. // Line buffers are always guaranteed to be aligned to be front of the slice. // Ring buffers use wrap around logic and could be physically split apart. func (b *BufferPipe) Buffer() []byte { return b.buf } // The BufferPipe mode of operation. func (b *BufferPipe) Mode() int { return b.mode } // The internal pointer values. func (b *BufferPipe) Pointers() (rdPtr, wrPtr int64) { return b.rdPtr, b.wrPtr } // The total number of bytes the buffer can store. func (b *BufferPipe) Capacity() int { return len(b.buf) } // The number of valid bytes that can be read. func (b *BufferPipe) Length() int { b.mutex.Lock() defer b.mutex.Unlock() return int(b.wrPtr - b.rdPtr) } func (b *BufferPipe) writeWait() int { var rdZero int64 // Zero value isLine := b.mode&Ring == 0 isBlock := b.mode&BlockI > 0 rdPtr := &b.rdPtr if isLine { rdPtr = &rdZero // Amount read has no effect on amount available } if isBlock { for !b.closed && len(b.buf) == int(b.wrPtr-(*rdPtr)) { b.wrCond.Wait() } } if b.closed { return 0 // Closed buffer is never available } return len(b.buf) - int(b.wrPtr-(*rdPtr)) } // Slices of available buffer that can be written to. This does not advance the // internal write pointer. All of the available write space is the logical // concatenation of the two slices. // // In linear buffers, the first slice obtained is guaranteed to be the entire // available writable buffer slice. // // In LineMono mode only, slices obtained may still be modified even after // WriteMark has been called and before Close. This is valid because this mode // blocks readers until the buffer has been closed. // // In ring buffers, the first slice obtained may not represent all of the // available buffer space since slices always represent a contiguous pieces of // memory. However, the first slice is guaranteed to be a non-empty slice if // space is available. // // In the Block mode, this method blocks until there is available space in // the buffer to write. Poll mode, on the contrary, will return empty slices if // the buffer is full. func (b *BufferPipe) WriteSlices() (bufLo, bufHi []byte, err error) { if b == nil { return nil, nil, nil } b.mutex.Lock() defer b.mutex.Unlock() return b.writeSlices() } func (b *BufferPipe) writeSlices() (bufLo, bufHi []byte, err error) { availCnt := b.writeWait() // Block until there is available buffer offLo := 0 if len(b.buf) > 0 { // Prevent division by zero offLo = int(b.wrPtr) % len(b.buf) } offHi := offLo + availCnt if modCnt := offHi - len(b.buf); modCnt > 0 { offHi = len(b.buf) bufHi = b.buf[:modCnt] // Upper half (possible for Ring) } bufLo = b.buf[offLo:offHi] // Bottom half (will contain all data for Line) // Restrict the capacity to prevent users from accidentally going past end. bufLo = bufLo[:len(bufLo):len(bufLo)] bufHi = bufHi[:len(bufHi):len(bufHi)] // Check error status if len(bufLo) == 0 { switch { case b.err != nil: err = b.err case b.closed: err = io.ErrClosedPipe default: err = io.ErrShortWrite } } return } // Advances the write pointer. // // The amount that can be advanced must be non-negative and be less than the // length of the slices returned by the previous WriteSlices. Calls to Write // may not be done between these two calls. Also, another call to WriteMark is // invalid until WriteSlices has been called again. // // If WriteMark is being used, only one writer routine is allowed. func (b *BufferPipe) WriteMark(cnt int) { if b == nil && cnt == 0 { return } b.mutex.Lock() defer b.mutex.Unlock() b.writeMark(cnt) } func (b *BufferPipe) writeMark(cnt int) { availCnt := b.writeWait() if cnt < 0 || cnt > availCnt { panic("invalid mark increment value") } b.wrPtr += int64(cnt) b.rdCond.Signal() } // Write data to the buffer. // // In linear buffers, the length of the data slice may not exceed the capacity // of the buffer. Otherwise, an ErrShortWrite error will be returned. // // In ring buffers, the length of the data slice may exceed the capacity. // // Under Block mode, this operation will block until all data has been written. // If there is no consumer of the data, then this method may block forever. func (b *BufferPipe) Write(data []byte) (cnt int, err error) { b.mutex.Lock() defer b.mutex.Unlock() for cnt < len(data) { buf, _, err := b.writeSlices() if err != nil { return cnt, err } copyCnt := copy(buf, data[cnt:]) b.writeMark(copyCnt) cnt += copyCnt } return cnt, nil } // Continually read the contents of the reader and write them to the pipe. func (b *BufferPipe) ReadFrom(rd io.Reader) (cnt int64, err error) { for { b.mutex.Lock() buf, _, wrErr := b.writeSlices() rdPtr, rdErr := rd.Read(buf) b.writeMark(rdPtr) b.mutex.Unlock() cnt += int64(rdPtr) switch { case wrErr != nil: return cnt, wrErr case rdErr == io.EOF: return cnt, nil case rdErr != nil: return cnt, rdErr } } } func (b *BufferPipe) readWait() int { isBlock := b.mode&BlockO > 0 isMono := b.mode&Dual == 0 if isBlock { for !b.closed && b.rdPtr == b.wrPtr { b.rdCond.Wait() } for isMono && !b.closed { b.rdCond.Wait() } } if isMono && !b.closed { return 0 } return int(b.wrPtr - b.rdPtr) } // Slices of valid data that can be read. This does not advance the internal // read pointer. All of the valid readable data is the logical concatenation of // the two slices. // // In linear buffers, the first slice obtained is guaranteed to be the entire // valid readable buffer slice. // // In ring buffers, the first slice obtained may not represent all of the // valid buffer data since slices always represent a contiguous pieces of // memory. However, the first slice is guaranteed to be a non-empty slice if // space is available. // // Under the Block mode, this method blocks until there is at least some valid // data to read. The Mono mode is special in that, none of the data is // considered ready for reading until the writer closes the channel. func (b *BufferPipe) ReadSlices() (bufLo, bufHi []byte, err error) { if b == nil { return nil, nil, nil } b.mutex.Lock() defer b.mutex.Unlock() return b.readSlices() } func (b *BufferPipe) readSlices() (bufLo, bufHi []byte, err error) { validCnt := b.readWait() // Block until there is valid buffer offLo := 0 if len(b.buf) > 0 { // Prevent division by zero offLo = int(b.rdPtr) % len(b.buf) } offHi := offLo + validCnt if modCnt := offHi - len(b.buf); modCnt > 0 { offHi = len(b.buf) bufHi = b.buf[:modCnt] // Upper half (possible for Ring) } bufLo = b.buf[offLo:offHi] // Bottom half (will contain all data for Line) // Restrict the capacity to prevent users from accidentally going past end. bufLo = bufLo[:len(bufLo):len(bufLo)] bufHi = bufHi[:len(bufHi):len(bufHi)] // Check error status if len(bufLo) == 0 { switch { case b.err != nil: err = b.err case b.closed: err = io.EOF default: err = io.ErrNoProgress } } return } // Advances the read pointer. // // The amount that can be advanced must be non-negative and be less than the // length of the slices returned by the previous ReadSlices. Calls to Read // may not be done between these two calls. Also, another call to ReadMark is // invalid until ReadSlices has been called again. // // If ReadMark is being used, only one reader routine is allowed. func (b *BufferPipe) ReadMark(cnt int) { if b == nil && cnt == 0 { return } b.mutex.Lock() defer b.mutex.Unlock() b.readMark(cnt) } func (b *BufferPipe) readMark(cnt int) { validCnt := b.readWait() if cnt < 0 || cnt > validCnt { panic("invalid mark increment value") } b.rdPtr += int64(cnt) b.wrCond.Signal() } // Read data from the buffer. // // In all modes, the length of the data slice may exceed the capacity of // the buffer. The operation will block until all data has been read or until // the EOF is hit. // // Under Block mode, this method may block forever if there is no producer. func (b *BufferPipe) Read(data []byte) (cnt int, err error) { b.mutex.Lock() defer b.mutex.Unlock() for cnt < len(data) { buf, _, err := b.readSlices() if err != nil { return cnt, err } copyCnt := copy(data[cnt:], buf) b.readMark(copyCnt) cnt += copyCnt } return cnt, nil } // Continually read the contents of the pipe and write them to the writer. func (b *BufferPipe) WriteTo(wr io.Writer) (cnt int64, err error) { for { b.mutex.Lock() data, _, rdErr := b.readSlices() wrPtr, wrErr := wr.Write(data) b.readMark(wrPtr) b.mutex.Unlock() cnt += int64(wrPtr) switch { case wrErr != nil: return cnt, wrErr case rdErr == io.EOF: return cnt, nil case rdErr != nil: return cnt, rdErr } } } // Close the buffer down. // // All write operations have no effect after this, while all read operations // will drain remaining data in the buffer. This operation is somewhat similar // to how Go channels operate. // // Writers should close the buffer to indicate to readers to mark end-of-stream. // // Readers should only close the buffer in the event of unexpected termination. // The mechanism allows readers to inform writers of consumer termination and // prevents the producer from potentially being blocked forever. func (b *BufferPipe) Close() error { return b.CloseWithError(nil) } // Closes the pipe with the given error. This sets the error value for the pipe // and returns the previous error value. func (b *BufferPipe) CloseWithError(err error) (errPre error) { b.mutex.Lock() defer b.mutex.Unlock() errPre, b.err = b.err, err b.closed = true b.rdCond.Broadcast() b.wrCond.Broadcast() return errPre } // Roll back the write pointer and return the number of bytes rolled back. // If successful, this effectively makes the valid length zero. In order to // prevent race conditions with the reader, this action is only valid in Mono // access mode before the channel is closed. func (b *BufferPipe) Rollback() int { b.mutex.Lock() defer b.mutex.Unlock() if b.closed || b.mode&Dual > 0 { return 0 } cnt := b.wrPtr - b.rdPtr b.wrPtr = b.rdPtr return int(cnt) } // Makes the buffer ready for use again by opening the pipe for writing again. // The read and write pointers will be reset to zero and errors will be cleared. func (b *BufferPipe) Reset() { b.mutex.Lock() defer b.mutex.Unlock() b.wrPtr, b.rdPtr = 0, 0 b.err, b.closed = nil, false } // TODO(jtsai): Allow BufferPipe to be grown. This is safe at Reset time and // before the first call to Write. When else is this safe? // TODO(jtsai): Double check why some methods allow the BufferPipe pointer to // be nil. // TODO(jtsai): Why are some methods not protected by a mutex? <|start_filename|>jsonfmt/format.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package jsonfmt import ( "bytes" "unicode" ) func (s *state) format() (out []byte) { defer func() { if ex := recover(); ex != nil { if js, ok := ex.(jsonInvalid); ok { s.flushAppend(js...) } else { panic(ex) } } if s.hasNewlines { s.out = append(s.out, '\n') } out = s.out }() s.out = nil s.formatMeta(s.preVal) s.formatValue(s.val) s.formatMeta(s.postVal) return } func (s *state) formatValue(js jsonValue) { switch v := js.(type) { case *jsonObject: s.formatObject(v) case *jsonArray: s.formatArray(v) case jsonString: s.flushAppend(v...) case jsonNumber: s.flushAppend(v...) case jsonLiteral: s.flushAppend(v...) case jsonInvalid: panic(v) } } func (s *state) formatObject(js *jsonObject) { s.flushAppend('{') indentOuter := hasNewlines(js.preRecords) if indentOuter { s.pushIndent() } s.formatMeta(js.preRecords) for i, rec := range js.records { s.formatMeta(rec.preKey) s.formatValue(rec.key) s.formatMeta(rec.postKey) s.flushAppend(':') indentInner := hasNewlines(rec.preVal) if indentInner { s.pushIndent() } s.formatMeta(rec.preVal) s.formatValue(rec.val) s.formatMeta(rec.postVal) if i < len(js.records)-1 || s.emitTrailingComma(rec.postComma, js.postRecords) { s.flushAppend(',') } if indentInner { s.popIndent() } s.formatMeta(rec.postComma) } s.formatMeta(js.postRecords) if indentOuter { s.popIndent() } s.flushAppend('}') } func (s *state) formatArray(js *jsonArray) { s.flushAppend('[') indentOuter := hasNewlines(js.preElems) if indentOuter { s.pushIndent() } s.formatMeta(js.preElems) for i, rec := range js.elems { s.formatMeta(rec.preVal) s.formatValue(rec.val) s.formatMeta(rec.postVal) if i < len(js.elems)-1 || s.emitTrailingComma(rec.postComma, js.postElems) { s.flushAppend(',') } s.formatMeta(rec.postComma) } s.formatMeta(js.postElems) if indentOuter { s.popIndent() } s.flushAppend(']') } func (s *state) formatMeta(js jsonMeta) { for _, m := range js { switch m := m.(type) { case jsonComment: s.flushSpaces('/') s.formatComment(m) case jsonNewlines: for i := 0; i < int(m); i++ { s.newlines = append(s.newlines, '\n') } case jsonInvalid: panic(m) } } } func (s *state) formatComment(js jsonComment) { if s.standardize { return // Comments are not valid in ECMA-404 } bs := bytes.Split(js, newlineBytes) prefix := indentPrefix(bs[len(bs)-1]) allStars := len(bs) > 1 for i, b := range bs { bs[i] = bytes.TrimRightFunc(bytes.TrimPrefix(b, prefix), unicode.IsSpace) if i > 0 { allStars = allStars && len(bs[i]) > 0 && bs[i][0] == '*' } } if allStars { // Line up stars in block comments for i, b := range bs { if i > 0 { bs[i] = append(spaceBytes, b...) } } } js = bytes.Join(bs, append(newlineBytes, s.indents...)) s.hasNewlines = s.hasNewlines || len(bs) > 1 s.out = append(s.out, js...) } // flushAppend calls flushSpaces before appending b to the output. func (s *state) flushAppend(b ...byte) { if len(b) > 0 { s.flushSpaces(b[0]) s.out = append(s.out, b...) } } // flushSpaces determines how many spaces and newlines to output using // information from the previous and next non-whitespace characters. func (s *state) flushSpaces(next byte) { if s.minify { return } var prev byte if len(s.out) > 0 { prev = s.out[len(s.out)-1] } else { s.newlines = s.newlines[:0] // Avoid leading empty lines } if len(s.newlines) > 2 { s.newlines = s.newlines[:2] // Avoid more than 1 empty line } if len(s.newlines) > 1 && (prev == '{' || prev == '[' || next == '}' || next == ']') { s.newlines = s.newlines[:1] // Avoid empty lines after open brace or before closing brace } if len(s.newlines) > 1 && prev == ':' { s.newlines = s.newlines[:1] // Avoid empty lines after lines ending with colon } if next == ':' || next == ',' { s.newlines = s.newlines[:0] // Avoid starting lines with a colon or comma } if (prev == '{' && next == '}') || (prev == '[' && next == ']') { s.newlines = s.newlines[:0] // Always collapse empty objects and arrays } if len(s.newlines) > 0 { s.hasNewlines = true s.out = append(s.out, s.newlines...) s.out = append(s.out, s.indents...) s.newlines = s.newlines[:0] } else if prev > 0 && (prev == ':' || prev == ',' || prev == '/' || next == '/') { s.out = append(s.out, ' ') } } // emitTrailingComma reports whether a trailing comma should be emitted. // Only emit trailing commas if the source had trailing commas, // and there is at least one newline until the closing brace. func (s *state) emitTrailingComma(postComma, postVals jsonMeta) bool { if s.trailingComma && !s.standardize { return hasNewlines(postComma) || hasNewlines(postVals) } return false } func hasNewlines(js jsonMeta) bool { for _, m := range js { switch m := m.(type) { case jsonComment: if bytes.IndexByte(m, '\n') > 0 { return true } case jsonNewlines: if m > 0 { return true } } } return false } func indentPrefix(s []byte) []byte { n := len(s) - len(bytes.TrimLeft(s, " \t")) return s[:n] } <|start_filename|>jsonfmt/common.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. // Package jsonfmt provides functionality for formatting JSON. package jsonfmt import "fmt" var ( newlineBytes = []byte{'\n'} spaceBytes = []byte{' '} ) type ( jsonValue interface { isValue() // Satisfied by (*jsonObject | *jsonArray | jsonString | jsonNumber | jsonLiteral | jsonInvalid) } jsonObject struct { // '{' preRecords jsonMeta // If non-empty, ends with jsonNewlines records []jsonRecord postRecords jsonMeta // Never contains jsonNewlines // '}' } jsonRecord struct { preKey jsonMeta // Never contains jsonNewlines key jsonValue postKey jsonMeta // ':' preVal jsonMeta val jsonValue postVal jsonMeta // ',' postComma jsonMeta // If non-empty, ends with jsonNewlines } jsonArray struct { // '[' preElems jsonMeta // If non-empty, ends with jsonNewlines elems []jsonElement postElems jsonMeta // Never contains jsonNewlines // ']' } jsonElement struct { preVal jsonMeta // Never contains jsonNewlines val jsonValue postVal jsonMeta // ',' postComma jsonMeta // If non-empty, ends with jsonNewlines } jsonString []byte // Quoted string jsonNumber []byte // Numeric value jsonLiteral []byte // "true" | "false" | "null" jsonMeta []interface { isMeta() // Implemented by (jsonComment | jsonNewlines | jsonInvalid) } jsonComment []byte // Comment of either "//" or "/**/" form without trailing newlines jsonNewlines int // Number of newlines // When a parsing error occurs, then the remainder of the input is stored // as jsonInvalid in the AST. jsonInvalid []byte // May possibly be an empty string ) func (*jsonObject) isValue() {} func (*jsonArray) isValue() {} func (jsonString) isValue() {} func (jsonNumber) isValue() {} func (jsonLiteral) isValue() {} func (jsonInvalid) isValue() {} func (jsonComment) isMeta() {} func (jsonNewlines) isMeta() {} func (jsonInvalid) isMeta() {} // Option configures how to format JSON. type Option interface { option() } type ( minify struct{ Option } standardize struct{ Option } ) // TODO: Make these an user Option? const defaultColumnLimit = 80 const defaultAlignLimit = 20 // Minify configures Format to produce the minimal representation of the input. // If Format returns no error, then the output is guaranteed to be valid JSON, func Minify() Option { return minify{} } // Standardize configures Format to produce valid JSON according to ECMA-404. // This strips any comments and trailing commas. func Standardize() Option { return standardize{} } // Format parses and formats the input JSON according to provided Options. // If err is non-nil, then the output is a best effort at processing the input. // // This function accepts a superset of the JSON specification that allows // comments and trailing commas after the last element in an object or array. func Format(in []byte, opts ...Option) (out []byte, err error) { // Process the provided options. var st state for _, opt := range opts { switch opt.(type) { case minify: st.minify = true st.standardize = true case standardize: st.standardize = true default: panic(fmt.Sprintf("unknown option: %#v", opt)) } } // Attempt to parse and format the JSON data. err = st.parse(in) if !st.minify { expandAST(st.val, defaultColumnLimit) } out = st.format() if !st.minify { out = alignJSON(out, defaultAlignLimit) } return out, err } type state struct { in []byte preVal jsonMeta val jsonValue postVal jsonMeta last interface{} // T where T = (*jsonValue | *jsonMeta) out []byte // Parsing and formatting options. minify bool // If set, implies standardize is set too standardize bool // If set, output will be ECMA-404 compliant trailingComma bool // Set by parser if any trailing commas detected hasNewlines bool // Set by formatter if any newlines are emitted newlines []byte // Pending newlines to output indents []byte // Indents to output per line } func (s *state) pushIndent() { s.indents = append(s.indents, '\t') } func (s *state) popIndent() { s.indents = s.indents[:len(s.indents)-1] } type jsonError struct { line, column int message string } func (e jsonError) Error() string { if e.line > 0 && e.column > 0 { return "jsonfmt: " + e.message } return fmt.Sprintf("jsonfmt: line %d, column %d: %v", e.line, e.column, e.message) } <|start_filename|>hashmerge/combine.go<|end_filename|> // Copyright 2015, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. // Package hashmerge provides functionality for merging hashes. package hashmerge // The origin of the CombineAdler32, CombineCRC32, and CombineCRC64 functions // in this package is the adler32_combine, crc32_combine, gf2_matrix_times, // and gf2_matrix_square functions found in the zlib library and was translated // from C to Go. Thanks goes to the authors of zlib: // <NAME> and <NAME>. // // See the following: // http://www.zlib.net/ // https://github.com/madler/zlib/blob/master/adler32.c // https://github.com/madler/zlib/blob/master/crc32.c // https://stackoverflow.com/questions/23122312/crc-calculation-of-a-mostly-static-data-stream/23126768#23126768 // // ==================================================== // Copyright (C) 1995-2013 <NAME> and <NAME> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // <NAME> <NAME> // <EMAIL> <EMAIL> // ==================================================== // CombineAdler32 combines two Adler-32 checksums together. // Let AB be the string concatenation of two strings A and B. Then Combine // computes the checksum of AB given only the checksum of A, the checksum of B, // and the length of B: // adler32.Checksum(AB) == CombineAdler32(adler32.Checksum(A), adler32.Checksum(B), len(B)) func CombineAdler32(adler1, adler2 uint32, len2 int64) uint32 { if len2 < 0 { panic("hashmerge: negative length") } const mod = 65521 var sum1, sum2, rem uint32 rem = uint32(len2 % mod) sum1 = adler1 & 0xffff sum2 = rem * sum1 sum2 %= mod sum1 += (adler2 & 0xffff) + mod - 1 sum2 += (adler1 >> 16) + (adler2 >> 16) + mod - rem if sum1 >= mod { sum1 -= mod } if sum1 >= mod { sum1 -= mod } if sum2 >= mod<<1 { sum2 -= mod << 1 } if sum2 >= mod { sum2 -= mod } return sum1 | (sum2 << 16) } // CombineCRC32 combines two CRC-32 checksums together. // Let AB be the string concatenation of two strings A and B. Then Combine // computes the checksum of AB given only the checksum of A, the checksum of B, // and the length of B: // tab := crc32.MakeTable(poly) // crc32.Checksum(AB, tab) == CombineCRC32(poly, crc32.Checksum(A, tab), crc32.Checksum(B, tab), len(B)) func CombineCRC32(poly, crc1, crc2 uint32, len2 int64) uint32 { if len2 < 0 { panic("hashmerge: negative length") } // Translation of gf2_matrix_times from zlib. var matrixMult = func(mat *[32]uint32, vec uint32) uint32 { var sum uint32 for n := 0; n < 32 && vec > 0; n++ { if vec&1 > 0 { sum ^= mat[n] } vec >>= 1 } return sum } // Translation of gf2_matrix_square from zlib. var matrixSquare = func(square, mat *[32]uint32) { for n := 0; n < 32; n++ { square[n] = matrixMult(mat, mat[n]) } } // Even and odd power-of-two zeros operators. var even, odd [32]uint32 // Put operator for one zero bit in odd. var row uint32 = 1 odd[0] = poly for n := 1; n < 32; n++ { odd[n] = row row <<= 1 } // Put operator for two zero bits in even. matrixSquare(&even, &odd) // Put operator for four zero bits in odd. matrixSquare(&odd, &even) // Apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even). for { // Apply zeros operator for this bit of len2. matrixSquare(&even, &odd) if len2&1 > 0 { crc1 = matrixMult(&even, crc1) } len2 >>= 1 if len2 == 0 { break } // Another iteration of the loop with odd and even swapped. matrixSquare(&odd, &even) if len2&1 > 0 { crc1 = matrixMult(&odd, crc1) } len2 >>= 1 if len2 == 0 { break } } return crc1 ^ crc2 } // CombineCRC64 combines two CRC-64 checksums together. // Let AB be the string concatenation of two strings A and B. Then Combine // computes the checksum of AB given only the checksum of A, the checksum of B, // and the length of B: // tab := crc64.MakeTable(poly) // crc64.Checksum(AB, tab) == CombineCRC64(poly, crc64.Checksum(A, tab), crc64.Checksum(B, tab), len(B)) func CombineCRC64(poly, crc1, crc2 uint64, len2 int64) uint64 { if len2 < 0 { panic("hashmerge: negative length") } // Translation of gf2_matrix_times from zlib. var matrixMult = func(mat *[64]uint64, vec uint64) uint64 { var sum uint64 for n := 0; n < 64 && vec > 0; n++ { if vec&1 > 0 { sum ^= mat[n] } vec >>= 1 } return sum } // Translation of gf2_matrix_square from zlib. var matrixSquare = func(square, mat *[64]uint64) { for n := 0; n < 64; n++ { square[n] = matrixMult(mat, mat[n]) } } // Even and odd power-of-two zeros operators. var even, odd [64]uint64 // Put operator for one zero bit in odd. var row uint64 = 1 odd[0] = poly for n := 1; n < 64; n++ { odd[n] = row row <<= 1 } // Put operator for two zero bits in even. matrixSquare(&even, &odd) // Put operator for four zero bits in odd. matrixSquare(&odd, &even) // Apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even). for { // Apply zeros operator for this bit of len2. matrixSquare(&even, &odd) if len2&1 > 0 { crc1 = matrixMult(&even, crc1) } len2 >>= 1 if len2 == 0 { break } // Another iteration of the loop with odd and even swapped. matrixSquare(&odd, &even) if len2&1 > 0 { crc1 = matrixMult(&odd, crc1) } len2 >>= 1 if len2 == 0 { break } } return crc1 ^ crc2 } <|start_filename|>jsonfmt/expand.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package jsonfmt import ( "bytes" "fmt" "reflect" ) // expandAST walks js and inserts newlines into jsonObject and jsonArray nodes // if the line (excluding indentation) exceeds the column limit. func expandAST(js jsonValue, limit int) { m := make(map[int][]jsonValue) for d := exploreAST(js, m, 0); d >= 0; d-- { for _, js := range m[d] { switch js := js.(type) { case *jsonObject: tryExpandObject(js, limit) case *jsonArray: tryExpandArray(js, limit) } } } } // exploreAST walks the AST of js and inserts any jsonObjects or jsonArrays // encountered into map m at the depth encountered. // It returns the maximum depth encountered. func exploreAST(js jsonValue, m map[int][]jsonValue, depth int) (maxDepth int) { maxDepth = depth switch v := js.(type) { case *jsonObject: m[depth] = append(m[depth], v) for _, rec := range v.records { if d := exploreAST(rec.val, m, depth+1); d > maxDepth { maxDepth = d } } case *jsonArray: m[depth] = append(m[depth], v) for _, elem := range v.elems { if d := exploreAST(elem.val, m, depth+1); d > maxDepth { maxDepth = d } } } return maxDepth } // tryExpandObject determines whether to expand jsonObject, and expands if so. func tryExpandObject(js *jsonObject, limit int) { if len(js.records) == 0 { return } // Only allow batching if newlines already exist in record meta nodes // and at least one record entirely lacks newlines. _, mayBatch := lineLength(+1, js.preRecords) hasBatch := false for _, rec := range js.records { _, multi := lineLength(+1, rec.postKey, rec.preVal, rec.postVal, rec.postComma) mayBatch = mayBatch || multi hasBatch = hasBatch || !multi } batch := mayBatch && hasBatch for i := range js.records { prevLen, multi1 := lineLength(-1, js.records[:i]) nextLen, multi2 := lineLength(+1, js.records[i:]) expandMulti := !batch && len(js.records) > 1 && (multi1 || multi2) if prevLen+nextLen > limit || expandMulti { expandObject(js, batch, limit) return } } } func expandObject(js *jsonObject, batch bool, limit int) { n := len(js.records) js.preRecords = appendNewline(js.preRecords) for i := 1; i < n; i++ { prevLen, _ := lineLength(-1, js.records[:i]) nextLen, _ := lineLength(+1, js.records[i:][:1]) if !batch || prevLen+nextLen > limit { js.records[i-1].postComma = appendNewline(js.records[i-1].postComma) } } js.records[n-1].postComma = appendNewline(js.records[n-1].postComma) } // tryExpandArray determines whether to expand jsonArray, and expands if so. func tryExpandArray(js *jsonArray, limit int) { if len(js.elems) == 0 { return } // Only allow batching if newlines already exist in element meta nodes // and at least one element entirely lacks newlines. _, mayBatch := lineLength(+1, js.preElems) hasBatch := false for _, elem := range js.elems { _, multi := lineLength(+1, elem.postVal, elem.postComma) mayBatch = mayBatch || multi hasBatch = hasBatch || !multi } batch := mayBatch && hasBatch for i := range js.elems { prevLen, _ := lineLength(-1, js.elems[:i]) nextLen, _ := lineLength(+1, js.elems[i:]) if prevLen+nextLen > limit { expandArray(js, batch, limit) return } } } func expandArray(js *jsonArray, batch bool, limit int) { n := len(js.elems) js.preElems = appendNewline(js.preElems) for i := 1; i < n; i++ { // Always batch primitive values together. isPrim := isPrimitive(js.elems[i-1].val) && isPrimitive(js.elems[i].val) prevLen, _ := lineLength(-1, js.elems[:i]) nextLen, _ := lineLength(+1, js.elems[i:][:1]) if !(batch || isPrim) || (prevLen+nextLen) > limit { js.elems[i-1].postComma = appendNewline(js.elems[i-1].postComma) } } js.elems[n-1].postComma = appendNewline(js.elems[n-1].postComma) } // lineLength reports the upcoming line length in the sequence of AST nodes. // It reports the length, and whether a newline was encountered. // The direction dir may only be +1 or -1 to control walking in a forward or // reverse direction. func lineLength(dir int, vs ...interface{}) (n int, multi bool) { length := func(v interface{}) (int, bool) { switch v := v.(type) { case *jsonObject: return lineLength(dir, '{', v.preRecords, v.records, v.postRecords, '}') case *jsonArray: return lineLength(dir, '[', v.preElems, v.elems, v.postElems, ']') case jsonRecord: return lineLength(dir, v.preKey, v.key, v.postKey, ':', v.preVal, v.val, v.postVal, ',', v.postComma) case jsonElement: return lineLength(dir, v.preVal, v.val, v.postVal, ',', v.postComma) case []jsonRecord, []jsonElement, jsonMeta: var args []interface{} vv := reflect.ValueOf(v) for j := 0; j < vv.Len(); j++ { args = append(args, vv.Index(j).Interface()) } return lineLength(dir, args...) case jsonString, jsonNumber, jsonLiteral: return reflect.ValueOf(v).Len(), false case jsonComment, jsonInvalid: // Add 1 to the returned result to account for preceding space. // This accounting is one too few for first block comment. b := reflect.ValueOf(v).Bytes() switch dir { case +1: if i := bytes.IndexByte(b, '\n'); i >= 0 { return 1 + i, true } case -1: if i := bytes.LastIndexByte(b, '\n'); i >= 0 { return 1 + len(b) - (i + 1), true } } return 1 + len(b), false case jsonNewlines: return 0, v > 0 case rune: if v == ':' || v == ',' { return 2, false // Implicit space added } return 1, false case nil: return 0, false default: panic(fmt.Sprintf("unable to handle type %T", v)) } } var m int switch dir { case +1: for i := 0; i < len(vs) && !multi; i++ { m, multi = length(vs[i]) n += m } case -1: for i := len(vs) - 1; i >= 0 && !multi; i-- { m, multi = length(vs[i]) n += m } default: panic("invalid direction") } return n, multi } func appendNewline(js jsonMeta) jsonMeta { if len(js) > 0 { if nl, _ := js[len(js)-1].(jsonNewlines); nl > 0 { return js } } return append(js, jsonNewlines(1)) } func isPrimitive(js jsonValue) bool { switch js.(type) { case jsonNumber, jsonString, jsonLiteral: return true default: return false } } <|start_filename|>cron/cron.go<|end_filename|> // Copyright 2017, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. // Package cron provides functionality for parsing and running cron schedules. package cron import ( "context" "errors" "strconv" "strings" "time" ) var ( monthNames = map[string]int{ "JAN": 1, "FEB": 2, "MAR": 3, "APR": 4, "MAY": 5, "JUN": 6, "JUL": 7, "AUG": 8, "SEP": 9, "OCT": 10, "NOV": 11, "DEC": 12, } dayNames = map[string]int{ "SUN": 0, "MON": 1, "TUE": 2, "WED": 3, "THU": 4, "FRI": 5, "SAT": 6, } scheduleMacros = map[string]string{ "@yearly": "0 0 1 1 *", "@annually": "0 0 1 1 *", "@monthly": "0 0 1 * *", "@weekly": "0 0 * * 0", "@daily": "0 0 * * *", "@hourly": "0 * * * *", } ) // set64 represents a set of integers containing values in 0..63. type set64 uint64 func (s *set64) set(i int) { *s |= 1 << uint(i) } func (s set64) has(i int) bool { return s&(1<<uint(i)) != 0 } // Schedule represents a cron schedule. type Schedule struct { str string mins set64 // 0-59 hours set64 // 0-23 days set64 // 1-31 months set64 // 1-12 weekDays set64 // 0-6 } // ParseSchedule parses a cron schedule, which is a space-separated list of // five fields representing: // • minutes: 0-59 // • hours: 0-23 // • days of month: 1-31 // • months: 1-12 or JAN-DEC // • days of week: 0-6 or SUN-SAT // // Each field may be a glob (e.g., "*"), representing the full range of values, // or a comma-separated list, containing individual values (e.g., "JAN") // or a dash-separated pair representing a range of values (e.g., "MON-FRI"). // // The following macros are permitted: // • @yearly: "0 0 1 1 *" // • @annually: "0 0 1 1 *" // • @monthly: "0 0 1 * *" // • @weekly: "0 0 * * 0" // • @daily: "0 0 * * *" // • @hourly: "0 * * * *" // // A given timestamp is in the schedule if the associated fields // of the timestamp matches each field specified in the schedule. // // See https://wikipedia.org/wiki/cron func ParseSchedule(s string) (Schedule, error) { s = strings.Join(strings.Fields(s), " ") sch := Schedule{str: s} if scheduleMacros[s] != "" { s = scheduleMacros[s] } var ok [5]bool if ss := strings.Fields(s); len(ss) == 5 { sch.mins, ok[0] = parseField(ss[0], 0, 59, nil) sch.hours, ok[1] = parseField(ss[1], 0, 23, nil) sch.days, ok[2] = parseField(ss[2], 1, 31, nil) sch.months, ok[3] = parseField(ss[3], 1, 12, monthNames) sch.weekDays, ok[4] = parseField(ss[4], 0, 6, dayNames) } if ok != [5]bool{true, true, true, true, true} { return Schedule{}, errors.New("cron: invalid schedule: " + s) } return sch, nil } func parseField(s string, min, max int, aliases map[string]int) (set64, bool) { var m set64 for _, s := range strings.Split(s, ",") { var lo, hi int if i := strings.IndexByte(s, '-'); i >= 0 { lo = parseToken(s[:i], min, aliases) hi = parseToken(s[i+1:], max, aliases) } else { lo = parseToken(s, min, aliases) hi = parseToken(s, max, aliases) } if lo < min || max < hi || hi < lo { return m, false } for i := lo; i <= hi; i++ { m.set(i) } } return m, true } func parseToken(s string, wild int, aliases map[string]int) int { if n, ok := aliases[strings.ToUpper(s)]; ok { return n } if s == "*" { return wild } if n, err := strconv.Atoi(s); err == nil { return n } return -1 } // NextAfter returns the next scheduled event, relative to the specified t, // taking into account t.Location. // This returns the zero value if unable to determine the next scheduled event. func (s Schedule) NextAfter(t time.Time) time.Time { if s == (Schedule{}) { return time.Time{} } // Round-up to the nearest minute. t = t.Add(time.Minute).Truncate(time.Minute) // Increment min/hour first, then increment by days. // When incrementing by days, we do not need to verify the min/hour again. t100 := t.AddDate(100, 0, 0) // Sanity bounds of 100 years for !s.mins.has(t.Minute()) && t.Before(t100) { t = t.Add(time.Minute) } for !s.hours.has(t.Hour()) && t.Before(t100) { t = t.Add(time.Hour) } for !s.matchDate(t) && t.Before(t100) { t = t.AddDate(0, 0, 1) } // Check that the date truly matches. if !s.mins.has(t.Minute()) || !s.hours.has(t.Hour()) || !s.matchDate(t) { return time.Time{} } return t } func (s Schedule) matchDate(t time.Time) bool { return s.days.has(t.Day()) && s.months.has(int(t.Month())) && s.weekDays.has(int(t.Weekday())) } func (s Schedule) String() string { return s.str } // A Cron holds a channel that delivers events based on the cron schedule. type Cron struct { C <-chan time.Time // The channel on which events are delivered cancel context.CancelFunc } // NewCron returns a new Cron containing a channel that sends the time // at every moment specified by the Schedule. // The timezone the cron job is operating in must be specified. // Stop Cron to release associated resources. func NewCron(sch Schedule, tz *time.Location) *Cron { if tz == nil { panic("cron: unspecified time.Location; consider using time.Local") } ch := make(chan time.Time, 1) ctx, cancel := context.WithCancel(context.Background()) // Start monitor goroutine. go func() { timer := time.NewTimer(0) <-timer.C for { // Schedule the next firing. now := time.Now().In(tz) next := sch.NextAfter(now) if next.IsZero() { return } timer.Reset(next.Sub(now)) // Wait until either stopped or triggered. select { case <-ctx.Done(): timer.Stop() return case t := <-timer.C: // Best-effort at forwarding the signal. select { case ch <- t: default: } } } }() return &Cron{C: ch, cancel: cancel} } // Stop turns off the cron job. After Stop, no more events will be sent. // Stop does not close the channel, to prevent a read from the channel // succeeding incorrectly. func (c *Cron) Stop() { c.cancel() }
Windblade-GR01/golib
<|start_filename|>pkg/webircgateway/transport_websocket.go<|end_filename|> package webircgateway import ( "fmt" "net" "net/http" "strings" "sync" "golang.org/x/net/websocket" ) type TransportWebsocket struct { gateway *Gateway wsServer *websocket.Server } func (t *TransportWebsocket) Init(g *Gateway) { t.gateway = g t.wsServer = &websocket.Server{Handler: t.websocketHandler, Handshake: t.checkOrigin} t.gateway.HttpRouter.Handle("/webirc/websocket/", t.wsServer) } func (t *TransportWebsocket) checkOrigin(config *websocket.Config, req *http.Request) (err error) { config.Origin, err = websocket.Origin(config, req) var origin string if config.Origin != nil { origin = config.Origin.String() } else { origin = "" } if !t.gateway.IsClientOriginAllowed(origin) { err = fmt.Errorf("Origin %#v not allowed", origin) t.gateway.Log(2, "%s. Closing connection", err) return err } return err } func (t *TransportWebsocket) websocketHandler(ws *websocket.Conn) { client := t.gateway.NewClient() client.RemoteAddr = t.gateway.GetRemoteAddressFromRequest(ws.Request()).String() clientHostnames, err := net.LookupAddr(client.RemoteAddr) if err != nil { client.RemoteHostname = client.RemoteAddr } else { // FQDNs include a . at the end. Strip it out potentialHostname := strings.Trim(clientHostnames[0], ".") // Must check that the resolved hostname also resolves back to the users IP addr, err := net.LookupIP(potentialHostname) if err == nil && len(addr) == 1 && addr[0].String() == client.RemoteAddr { client.RemoteHostname = potentialHostname } else { client.RemoteHostname = client.RemoteAddr } } if t.gateway.isRequestSecure(ws.Request()) { client.Tags["secure"] = "" } _, remoteAddrPort, _ := net.SplitHostPort(ws.Request().RemoteAddr) client.Tags["remote-port"] = remoteAddrPort client.Log(2, "New websocket client on %s from %s %s", ws.Request().Host, client.RemoteAddr, client.RemoteHostname) client.Ready() // We wait until the client send queue has been drained var sendDrained sync.WaitGroup sendDrained.Add(1) // Read from websocket go func() { for { r := make([]byte, 1024) len, err := ws.Read(r) if err == nil && len > 0 { message := string(r[:len]) client.Log(1, "client->: %s", message) select { case client.Recv <- message: default: client.Log(3, "Recv queue full. Dropping data") // TODO: Should this really just drop the data or close the connection? } } else if err != nil { client.Log(1, "Websocket connection closed (%s)", err.Error()) break } else if len == 0 { client.Log(1, "Got 0 bytes from websocket") } } close(client.Recv) }() // Process signals for the client for { signal, ok := <-client.Signals if !ok { sendDrained.Done() break } if signal[0] == "data" { line := strings.Trim(signal[1], "\r\n") client.Log(1, "->ws: %s", line) ws.Write([]byte(line)) } if signal[0] == "state" && signal[1] == "closed" { ws.Close() } } sendDrained.Wait() ws.Close() }
kiwiirc/websocketgateway
<|start_filename|>controller/test_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var async = require('async'); router.get('/', function (req, res) { async.series([ function (cb) { console.log(1); cb(null); }, function (cb) { console.log(2); cb(null); } ], function (err, result) { if (err) { res.status(400); res.json({msg: 'err message'}); } else { res.json(result); } }); }); router.get('/redis', function (req, res) { var redis = require('redis'); var config = require('../config/redis'); var redisClient = redis.createClient(config.port, config.host); // eg1 redisClient.hmset('hash', { hello: 'world', hello2: 'world2', hello3: 'world3' }); redisClient.hgetall('hash2', function (err, obj) { console.log(err); console.log(obj); }); res.end('redis'); }); router.get('/pro', function (req, res) { console.log(req.session); res.json({msg: '产品页面'}); }); router.get('/sess', function (req, res) { //req.session.user_id = req.query.user_id; //req.session.expireTime = 200; //req.session.loginTime = 100; // console.log(req.session); //console.log(req.session.id); res.json({msg: '登陆成功'}); //if (req.session.expireTime > 150) { // res.status(403); // res.json({msg: '请重新登陆'}); //} //var expireTime = req.session.cookie.or //var store = new MongoStore(require('../config/mongodb')); //req.session.userId = 222; //req.session.user = {hello: '<PASSWORD>'}; //req.session.loginTime = {hello: 'world'}; //req.session.expireTime = {hello: 'world'}; //store.set(req.session.id, req.session); // //store.get(req.session.id, function (err, sess) { // var expireTime = sess.cookie // if (1) { // 过期 // // } // // // console.log(sess); // res.json(sess); //}); //var sess = req.session; //if (sess.views) { // sess.views++ // res.setHeader('Content-Type', 'text/html') // res.write('<p>views: ' + sess.views + '</p>') // res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>') // res.end() //} else { // sess.views = 1 // res.end('welcome to the session demo. refresh!') //} }); router.get('/promise', function (req, res) { // 获取任务ID=100,然后更新字段desc='我要测试promise',然后再读取ID=101,显示给用户 // SELECT * FROM task WHERE id = 100 // UPDATE task SET desc = '我要测试promise' WHERE id = 100 // SELECT * FROM task WHERE id = 101; var TaskModel = require('../model/task_model'); TaskModel .find(100) .then(function (task) { task .update({ desc: '我要测试promise' }) .then(function () { }); }); }); module.exports = router; <|start_filename|>model/task_follow_model.js<|end_filename|> var Sequelize = require('sequelize'); var base = require('./base'); var TaskFollowModel = module.exports = base.define('task_follow', { task_id: { type: Sequelize.INTEGER, }, prev_task_id: { type: Sequelize.INTEGER, }, create_time: { type: Sequelize.INTEGER, } }, { classMethods: { } }); TaskFollowModel.idWaiting = 10; TaskFollowModel.idIng = 20; TaskFollowModel.idCompleted = 50; <|start_filename|>model/csv_model.js<|end_filename|> var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); var CsvModel = base.define('csv', { md5: { type: Sequelize.STRING, validate: { len: [32, 32] } }, size: { type: Sequelize.STRING }, mime: { type: Sequelize.STRING, validate: { len: [0, 140] } }, name: { type: Sequelize.STRING, validate: { len: [0, 140] } }, originalname: { type: Sequelize.STRING, validate: { len: [0, 140] } }, create_time: { type: Sequelize.STRING } }); module.exports = CsvModel; <|start_filename|>controller/project_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var moment = require('moment'); var ProjectModel = require('../model/project_model'); var UserModel = require('../model/user_model'); var VersionModel = require('../model/version_model'); var IterationModel = require('../model/iteration_model'); var RouterService = require('../service/router_service'); // 列表 router.get('/', function (req, res) { ProjectModel .findAndCountAll({ where: { status: ProjectModel.statusOnline }, offset: req.query.offset || 0, limit: req.query.size || 10 }) .then(function (projects) { res.json(projects); }); }); // 树形 router.get('/list', function (req, res) { ProjectModel .findAll({ offset: req.query.offset || 0, limit: req.query.limit || 0, include: [ { model: VersionModel, include: [ {model: IterationModel} ] } ], order: 'id DESC' }) .then(function (projects) { res.json(projects); }); }); // 新建 router.post('/', checkLeader); router.post('/', checkName); router.post('/', function (req, res) { ProjectModel .create(req.body) .then(function (project) { res.json({id: project.id}); }) .catch(function (err) { RouterService.json(err, res); }); }); router.use('/:id', function (req, res, next) { ProjectModel .findById(req.params.id) .then(function (project) { if (project === null) { res.status(404); res.json({msg: '项目不存在'}); } else { req.project = project; next(); } }); }); // 编辑 router.put('/:id', checkLeader); router.put('/:id', function (req, res, next) { if (req.body.name !== req.project.name) { checkName(req, res, next); } else { next(); } }); router.put('/:id', function (req, res) { req.project .update(req.body) .then(function (project) { res.json({id: project.id}); }) .catch(function (err) { RouterService.json(err, res); }); }); // 删除 router.delete('/:id', function (req, res) { req.project .update({ status: ProjectModel.statusDeleted }) .then(function () { res.json({msg: '删除成功'}); }) .catch(function (err) { RouterService.json(err, res); }); }); function checkName(req, res, next) { // 校验项目名称是否存在 ProjectModel .find({ where: {name: req.body.name} }) .then(function (project) { if (project === null) { next(); } else { res.status(400); res.json({msg: '抱歉,该项目名称已经存在'}); } }); } function checkLeader(req, res, next) { // 校验负责人 UserModel .findById(req.body.leader) .then(function (user) { if (user === null) { res.status(400); res.json({msg: '负责人不存在'}); } else { req.user = user; next(); } }); } module.exports = router; <|start_filename|>model/task_concerned_model.js<|end_filename|> var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); var TaskConcernedModel = base.define('task_concerned', { task_id: { type: Sequelize.INTEGER }, user_id: { type: Sequelize.INTEGER }, create_time: { type: Sequelize.INTEGER } }); module.exports = TaskConcernedModel; <|start_filename|>model/story_model.js<|end_filename|> var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); var StoryModel = module.exports = base.define('story', { title: { type: Sequelize.STRING, }, leader: { type: Sequelize.INTEGER, }, version_id: { type: Sequelize.INTEGER, }, priority: { type: Sequelize.INTEGER, defaultValue: 0, allowNull: false, validate: { min: 0, max: { args: 5, msg: '优先级最大值为5', }, } }, status: { type: Sequelize.INTEGER }, create_time: { type: Sequelize.INTEGER, allowNull: false, defaultValue: moment().unix() } }, { classMethods: { findByVt: function (versionId, title) { // 根据版本号,标题 return StoryModel .find({ where: { version_id: versionId, title: title } }); } } }); // 状态 StoryModel.statusOnline = 0; StoryModel.statusDeleted = 99; // 关系 var UserModel = require('./user_model'); StoryModel.belongsTo(UserModel, {foreignKey: 'leader'}); <|start_filename|>service/user_service.js<|end_filename|> // 依赖 var http = require('http'); var moment = require('moment'); var async = require('async'); var uid = require('uid-safe').sync; var redis = require('../library/redis').create(); // UserService var UserService = { setSession: function (user, req) { var sid = uid(24); var expired = moment().unix() + 7 * 24 * 60 * 60; var session = { id: sid, expired: expired, user: user.get({plain: true}), user_id: user.id }; var stringify = JSON.stringify(session); redis.set(sid, stringify); req.session = session; req.user = session.user; }, destroySession: function (req) { redis.expire(req.session.id, 0); }, checkSession: function (req, res, next) { var self = this; async.waterfall([ // get session id function (cb) { var sid = req.query.sid; if (!sid) { cb('please login first'); } else { cb(null, sid); } }, // get session function (sid, cb) { redis.get(sid, function (err, session) { if (session) { cb(null, session); } else { console.log('session empty, sid ' + sid); cb('please login first'); } }); }, // check whether session expired or not function (session, cb) { var parsed = JSON.parse(session); if (parsed.expired <= moment().unix()) { console.log('session expired, sid ' + session.id); cb('please re-login'); } else { cb(null, parsed); } }, ], function (err, session) { if (err) { res.status(403); res.json({msg: err}); } else { console.log('userid ' + session.user_id + ' session check success'); req.session = session; req.user = session.user; next(); } }); }, isMe: function (req, userId) { // is me return true; var me = req.session.user_id; return parseInt(me) === parseInt(userId); } }; module.exports = UserService; <|start_filename|>controller/version_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var async = require('async'); var VersionModel = require('../model/version_model'); var ProjectModel = require('../model/project_model'); var IterationModel = require('../model/iteration_model'); var RouterService = require('../service/router_service'); // 检查id router.use('/:id', function (req, res, next) { VersionModel .findById(req.params.id) .then(function (version) { if (version === null) { res.status(404); res.json({msg: '版本不存在'}); } else { req.version = version; next(); } }); }); // 新建 router.post('/', checkProject); router.post('/', checkPN); router.post('/', function (req, res) { VersionModel .build(req.body) .save() .then(function (version) { res.json({id: version.id}); }) .catch(function (err) { res.status(400); res.json({msg: err.errors[0].message}); }); }); // 列表 router.get('/', function (req, res) { var where = {}; if (req.query.status) { where.status = req.query.status.split(','); } else { where.status = VersionModel.statusOnline; } VersionModel .findAndCount({ where: where, include: [ {model: ProjectModel} ], order: 'id DESC', offset: req.query.offset || 0, limit: req.query.size || 10 }) .then(function (result) { res.json(result); }); }); // 编辑 router.put('/:id', checkProject); router.put('/:id', function (req, res, next) { if (req.body.name !== req.version.name) { checkPN(req, res, next); } else { next(); } }); router.put('/:id', function (req, res) { req.version .updateAttributes(req.body) .then(function (version) { res.json({id: version.id}); }) .catch(function (err) { res.status(400); res.json({msg: err.errors[0].message}); }); }); // 关闭 router.put('/:id/toggle', function (req, res, next) { req.version .toggle(req.query.status) .then(function (version) { res.json({msg: '操作成功'}); next(); }) .catch(function (err) { RouterService.json(err, res); }); }); router.put('/:id/toggle', function (req) { IterationModel .findAll({ where: {version_id: req.version.id} }) .then(function (iterations) { async.each(iterations, function (iteration, callback) { iteration .updateAttributes({ status: IterationModel.statusClosed }) .then(function (iteration) { callback(); }) .catch(function (err) { callback(err.errors[0].message); }); }, function (err) { if (err) { throw err; } }); }); }); // 删除 router.delete('/:id', function (req, res) { req.version .updateAttributes({ status: VersionModel.statusDeleted }) .then(function () { res.json({msg: '删除成功'}); }); }); function checkPN(req, res, next) { VersionModel .find({ where: { project_id: req.body.project_id, name: req.body.name } }) .then(function (version) { if (version === null) { next(); } else { res.status(404); res.json({msg: '版本号存在!'}); } }); } function checkProject(req, res, next) { ProjectModel .findById(req.body.project_id) .then(function (project) { if (project === null) { res.status(404); res.json({msg: '项目不存在!'}); } else { req.project = project; next(); } }); } module.exports = router; <|start_filename|>controller/user_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var async = require('async'); var redis = require('redis'); var moment = require('moment'); var Redis = require('../library/redis'); var UserService = require('../service/user_service'); var UserModel = require('../model/user_model'); var Msg91u = require('../library/msg91u'); // 登陆 router.post('/login2', checkLogin); router.post('/login2', function (req, res) { async.waterfall([ function (cb) { // 检查员工号+密码 UserModel .find({ where: { worker_num: req.body.name } }) .then(function (user) { cb(null, user); }); }, function (user, cb) { // 检查手机号+密码 if (user) { // 已经找到,则直接跳过手机号查找 return cb(null, user); } UserModel .find({ where: { mobile: req.body.name } }) .then(function (user) { cb(null, user); }); }, ], function (err, user) { if (user === null) { res.status(403); res.json({msg: '用户不存在'}); return; } if (!user.isPasswordValid(req.body.password)) { res.status(403); res.json({msg: '密码错误'}); return; } UserService.setSession(user, req); res.json({id: user.id, sid: req.session.id}); }); }); // 登出 router.post('/logout', UserService.checkSession); router.post('/logout', function (req, res) { UserService.destroySession(req); res.json({msg: '登出成功'}); }); // 列表 router.get('/list', function (req, res, next) { UserModel .findAll({ offset: req.query.offset || 0, limit: req.query.size || 10 }) .then(function (users) { res.json(users); }); }); // 详情 router.get('/show/:id', UserService.checkSession); router.get('/show/:id', checkUserId); router.get('/show/:id', function (req, res, next) { res.json(req.user); }); // 修改 router.put('/modi/:id', UserService.checkSession); router.put('/modi/:id', checkUserId); router.put('/modi/:id', function (req, res) { req.user .update(req.body) .then(function (user) { res.json(user); }); }); // 用户删除 router.delete('/del/:id', UserService.checkSession); router.delete('/del/:id', checkUserId); router.delete('/del/:id', function (req, res) { req.user.destroy(); res.json({msg: '操作成功'}); }); // 用户注册 步骤1 router.post('/reg_step1', checkReg); router.post('/reg_step1', checkWorkerNum); router.post('/reg_step1', function (req, res) { // 发送91u信息 var msg91u = new Msg91u(req.body.worker_num); var number = moment().format('x').substr(-6); var msg = '您正在注册看板工具,校验码:' + number; msg91u.send(msg); // 将key保存 var redisClient = Redis.create(); var key = getKey(req.body.worker_num); redisClient.hset(key, 'is_used', 0); redisClient.hset(key, 'worker_num', req.body.worker_num); redisClient.hset(key, 'password', req.body.password); redisClient.hset(key, 'num', number); redisClient.expire(key, 60); res.json({msg: '请在91u中查收验证码'}); }); // 用户注册 步骤2 router.post('/reg_step2', checkKey); router.post('/reg_step2', function (req, res) { var salt = UserModel.generateSalt(); var password = UserModel.generatePassword(salt, req.password); UserModel .create({ worker_num: req.body.worker_num, password: password, salt: salt, create_time: moment().unix() }) .then(function (user) { if (user) { res.json({id: user.id}); } else { res.status(500); res.json({msg: '注册失败'}); } }); }); function checkUserId(req, res, next) { UserModel .findById(req.params.id) .then(function (user) { if (user === null) { res.status(400); res.json({msg: '用户不存在'}); } else { req.user = user; next(); } }); } function checkWorkerNum(req, res, next) { UserModel .find({ where: { worker_num: req.body.worker_num } }) .then(function (user) { if (user) { res.status(400); res.json({msg: '工号已经注册'}); } else { next(); } }); } function checkLogin(req, res, next) { // 检查登陆状况 // name req.checkBody('name', '请提供用户名').notEmpty(); // password req.checkBody('password', '<PASSWORD>').notEmpty(); var errors = req.validationErrors(true); if (errors) { res.status(400); res.json(errors); } else { next(); } } function checkReg(req, res, next) { // name req.checkBody('worker_num', '请提供91U员工号').notEmpty(); // password req.checkBody('password', '<PASSWORD>').notEmpty(); var errors = req.validationErrors(true); if (errors) { res.status(400); res.json(errors); } else { next(); } } function checkKey(req, res, next) { // 校验验证码 var redisClient = Redis.create(); var key = getKey(req.body.worker_num); redisClient.hgetall(key, function (err, obj) { if (obj === null) { res.status(403); res.json({msg: '请核实验证码'}); return; } console.log('验证码' + req.body.number + '对应的值为' + JSON.stringify(obj)); if (parseInt(obj.is_used)) { res.status(403); res.json({msg: '验证码已使用'}); return; } if (parseInt(obj.num) !== parseInt(req.body.number)) { res.status(403); res.json({msg: '验证码错误'}); return; } req.password = <PASSWORD>; redisClient.hset(key, 'is_used', 1); next(); }); } function getKey(number) { // redis中key return 'kb_login_' + number; } module.exports = router; <|start_filename|>service/task_service.js<|end_filename|> var async = require('async'); var _ = require('underscore'); var logger = require('../library/logger'); var moment = require('moment'); var TaskStatusModel = require('../model/task_status_model'); var TaskFollowModel = require('../model/task_follow_model'); var TaskModel = require('../model/task_model'); var UserModel = require('../model/user_model'); var TaskConcernedModel = require('../model/task_concerned_model'); var StoryModel = require('../model/story_model'); var IterationModel = require('../model/iteration_model'); var Msg91uModel = require('../model/msg91u_model'); var Msg91U = require('../library/msg91u'); var Mail = require('../library/mail'); var TaskService = { sendPreTaskMsg: function(prevTask) { // send msg if you are the author of prepositive task // find task follows var findTaskFollows = function(callback) { TaskFollowModel .findAll({ where: {prev_task_id: prevTask.id} }).then(function(taskFollows) { if (taskFollows) { callback(null, taskFollows); } else { callback(true); } }); }; // find tasks var findTasks = function(taskFollows, callback) { var tasks = []; taskFollows.forEach(function (taskFollow) { TaskModel .findById(taskFollow.task_id) .then(function(task) { if (task !== null) { tasks.push(task); } }); }); callback(null, tasks); }; // find users var findUsers = function(tasks, callback) { prevTask .getUser() .then(function(prevTaskUser) { tasks.forEach(function(task) { UserModel .findById(task.user_id) .then(function(user) { var mail = new Mail(user.email); var msg = 'Prepositive task [' + prevTask.desc + '] has been completed by ' + prevTaskUser.name + '.Now you can start task[' + task.desc + '].'; mail.send(msg); }); }); }); callback(null); }; async.waterfall([findTaskFollows, findTasks, findUsers]); }, sendConcernedMsg: function (task) { // send msg if you focus on this task var findTaskUser = function (callback) { task .getUser() .then(function (user) { callback(null, user); }); }; var findTaskConcerned = function (taskUser, callback) { TaskConcernedModel .findAll({ where: { task_id: task.id } }) .then(function (taskConcerneds) { callback(null, taskConcerneds, taskUser); }); }; var findUsers = function (TaskConcerneds, taskUser, callback) { async.each(TaskConcerneds, function (taskConcerned, cb) { UserModel .findById(taskConcerned.user_id) .then(function (user) { var mail = new Mail(user.email); var msg = 'Task [' + task.desc + '] that you foucs on has been completed by ' + taskUser.name; mail.send(msg); }); cb(null); }); callback(null); }; async.waterfall([findTaskUser, findTaskConcerned, findUsers]); }, sendLeaderMsg: function (task) { // send msg if you are a leader of this task async.waterfall([ // user function (callback) { UserModel .findById(task.user_id) .then(function (user) { callback(null, user); }); }, // story function (taskUser, callback) { StoryModel .findById(task.story_id) .then(function (story) { callback(null, taskUser, story); }); }, // find leader function (taskUser, story, callback) { UserModel .findById(story.leader) .then(function (user) { callback(null, taskUser, user); }); }, // send msg function (taskUser, user, callback) { var mail = new Mail(user.email); var msg = 'Task [' + task.desc + '] has been completed by ' + taskUser.name + '.You will receive this msg because you are a leader of this task'; mail.send(msg); callback(null); } ], function (err, result) { // do nothing console.log(err) }); }, sendDeadlineMsg: function (callback) { // send msg if today is the deadline to complete var year = moment().get('year'); var month = moment().get('month') + 1; var date = moment().get('date'); var todayStart = moment(year + '-' + month + '-' + date, 'YYYY-MM-DD'); var todayEnd = moment(todayStart).add(1, 'days'); async.waterfall([ // find tasks function (callback) { TaskModel .findAll({ where: { deadline: { $between: [todayStart.unix(), todayEnd.unix()] }, status: TaskModel.statusOnline } }) .then(function (tasks) { callback(null, tasks); }); }, // find users function (tasks, callback) { async.each(tasks, function (task, cb) { UserModel .findById(task.user_id) .then(function (user) { var mail = new Mail(user.email); var msg = 'Please complete the task[' + task.desc + '], because today is the deadline'; mail.send(msg); }); cb(null); }, function (err) { callback(null); }); } ], function (err, results) { callback(err, results); }); }, sendMsgWhenAuthorChanged: function (task, currentUser, operatorUser) { // send msg if the anthor of a task is changed async.waterfall([ // find original anthor function (cb) { UserModel .findById(task.user_id) .then(function (orginalUser) { cb(null, orginalUser); }); } ], function (err, originalUser) { console.log('task:' + task.desc + ',original author:' + originalUser.name + ', current author:' + currentUser.name + ', operator:' + operatorUser.name); var originalUserMail = new Mail(originalUser.email); var originalMsg = 'Your task[' + task.desc + '] is assigned to ' + currentUser.name; originalUserMail.send(originalMsg); var currentUserMail = new Mail(currentUser.email);; var currentMsg = 'The task[' + task.desc + '] belonged to ' + originalUser.name + ' has assigned to you operated by ' + operatorUser.name; currentUserMail.send(currentMsg); }); }, upload: function (csvId, info, callback) { var props = info.split(','); logger.log('csv', '----', csvId); logger.log('csv', '任务 - 开始导入,信息为:', csvId); logger.log('csv', props.toString(), csvId); async.waterfall([ // 故事是否存在 function (callback) { StoryModel .find({ where: {title: props[4]} }) .then(function (story) { if (story === null) { callback('任务 - 项目[' + props[4] + ']不存在,忽略'); } else { callback(null, story); } }); }, // 迭代是否存在 function (story, callback) { IterationModel .find({ where: {name: props[0], version_id: story.version_id} }) .then(function (iteration) { if (iteration === null) { callback('任务 - 迭代[' + props[0] + ']不存在,忽略'); } else { callback(null, story, iteration); } }); }, // 开发者是否存在 function (story, iteration, callback) { UserModel .find({ where: {name: props[2]} }) .then(function (user) { if (user === null) { callback('任务 - 用户[' + props[2] + ']不存在,忽略'); } else { callback(null, user, story, iteration); } }); }, // 导入 function (user, story, iteration, callback) { TaskModel .create({ project_id: story.project_id, version_id: story.version_id, iteration_id: iteration.id, story_id: story.id, user_id: user.id, priority: 5, estimated_time: props[3], status_id: TaskStatusModel.WAITING, desc: props[1], create_time: 1 }) .then(function (task) { logger.log('csv', '任务 - [' + task.desc + ']导入成功,ID=' + task.id, csvId); callback(null); }) .catch(function (err) { callback(err); }); } ], function (err, result) { if (err) { logger.log('csv', err, csvId); } callback(err, result); }); } }; module.exports = TaskService; <|start_filename|>model/task_model.js<|end_filename|> // 依赖 var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); // 类 var TaskModel = module.exports = base.define('task', { project_id: { type: Sequelize.INTEGER, }, version_id: { type: Sequelize.INTEGER, }, iteration_id: { type: Sequelize.INTEGER, }, story_id: { type: Sequelize.INTEGER, }, user_id: { type: Sequelize.INTEGER, }, desc: { type: Sequelize.STRING, }, status: { type: Sequelize.INTEGER, }, is_new: { type: Sequelize.INTEGER, }, is_challenging: { type: Sequelize.INTEGER, }, priority: { type: Sequelize.INTEGER, }, estimated_time: { type: Sequelize.INTEGER, }, status_id: { type: Sequelize.INTEGER, }, remark: { type: Sequelize.STRING, defaultValue: '' }, start_time: { type: Sequelize.INTEGER, }, end_time: { type: Sequelize.INTEGER }, deadline: { type: Sequelize.INTEGER }, create_time: { type: Sequelize.INTEGER, defaultValue: moment().unix() } }, { instanceMethods: { drag: function(status_id) { // 拉动任务 // 新建操作记录 TaskHistoryModel.gen(this.id, this.status_id, status_id, this.user_id); // 修改 status_id = parseInt(status_id); if (status_id === TaskStatusModel.DEVING) { // 拉动到开发中 this.start_time = moment().unix(); } else if (status_id === TaskStatusModel.COMPLETE) { // 拉动到已完成 this.end_time = moment().unix(); } else { // do nothing } this.status_id = status_id; return this.save(); }, isCompleted: function () { // 是否完成 return this.status_id === TaskStatusModel.COMPLETE; } } }); TaskModel.statusOnline = 0; TaskModel.statusOffline = 99; // 关系 var UserModel = require('./user_model'); var TaskStatusModel = require('./task_status_model'); var TaskFollowModel = require('./task_follow_model'); var TaskHistoryModel = require('./task_history_model'); var IterationModel = require('./iteration_model'); var StoryModel = require('./story_model'); var ProjectModel = require('./project_model'); var VersionModel = require('./version_model'); var TaskConcernedModel = require('./task_concerned_model'); TaskModel.belongsTo(UserModel, {foreignKey: 'user_id'}); TaskModel.belongsTo(TaskStatusModel, {foreignKey: 'status_id'}); TaskModel.belongsTo(IterationModel, {foreignKey: 'iteration_id'}); TaskModel.belongsTo(StoryModel, {foreignKey: 'story_id'}); TaskModel.belongsTo(ProjectModel, {foreignKey: 'project_id'}); TaskModel.belongsTo(VersionModel, {foreignKey: 'version_id'}); TaskModel.hasMany(TaskFollowModel, {foreignKey: 'task_id'}); TaskModel.hasMany(TaskHistoryModel, {foreignKey: 'task_id'}); TaskModel.hasMany(TaskConcernedModel, {foreignKey: 'task_id'}); <|start_filename|>library/msg91u.js<|end_filename|> var http = require('http'); var querystring = require('querystring'); function Msg91U(workerId, config) { this.workerId = Number(workerId); this.config = this.initConfig(config); }; Msg91U.prototype.send = function(msg) { //var payload = JSON.stringify({ // sender: { // appid: this.config.appid, // permcode: this.config.permcode, // }, // msg: { // type: this.config.type, // msgtype: this.config.msgtype, // msgbody: msg, // }, // receivers: [this.workerId] //}); //var options = { // host: this.config.host, // port: this.config.port, // method: 'POST', // path: '/appmsg', //}; //var client = http.request(options); //client.write(payload); //client.end(); var payload = JSON.stringify({ data: { service: "service_ndim", method: "send", params: [ msg, [this.workerId] ] }, pack_type: "raw" }); var buf = new Buffer(payload); var options = { // hostname: 'yzb.service.192.168.94.26.xip.io', hostname: ' simulateserviceapi.xxjia.cn', method: 'POST', path: '/service/call', headers: { 'Content-Type': 'application/json;charset=utf-8', 'Content-Length': buf.length } }; var client = http.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (data) { console.log(data); }); }); client.write(buf); client.end(); }; Msg91U.prototype.initConfig = function(config) { var config = { host: '10.1.191.177', port: 1220, appid: 9209, permcode: '101', ApiKey: 'cf32cc19-cdff-4a4f-a847-cc96791120c9', receivers: [123, 124, 125], type: 0, msgtype: 0 }; return config; }; module.exports = Msg91U; <|start_filename|>controller/task_status_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var TaskStatusModel = require('../model/task_status_model'); router.get('/', function (req, res) { TaskStatusModel .findAll() .then(function (result) { res.json(result); }); }); module.exports = router; <|start_filename|>config/local.example.js<|end_filename|> // if u want to use this file, u must rename this file to local.js // local config var config = new Map(); // mysql config.set('mysql', { host: '127.0.0.1', port: 3306, user: '', // enter username password: '', // input password database: '' // input database }); // redis config.set('redis', { host: '192.168.94.26', port: 6380 }); module.exports = config; <|start_filename|>controller/iteration_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var moment = require('moment'); var VersionModel = require('../model/version_model'); var IterationModel = require('../model/iteration_model'); var ProjectModel = require('../model/project_model'); var RouterService = require('../service/router_service'); // 列表 router.get('/', function(req, res) { var where = {}; if (req.query.status) { where.status = req.query.status.split(','); } else { where.status = IterationModel.statusOnline; } if (req.query.version_id) { where.version_id = req.query.version_id; } IterationModel .findAndCount({ where: where, offset: req.query.offset || 0, limit: req.query.size || 10, order: 'id ASC', include: [ {model: VersionModel, include: [{model: ProjectModel}]} ] }) .then(function(result) { res.json(result); }); }); // 新增 router.post('/', checkVersionId, checkUniqVN); router.post('/', function(req, res) { IterationModel .build(req.body) .save() .then(function(iteration) { res.json({id: iteration.id}); }) .catch(function(err) { RouterService.json(err, res); }); }); router.use('/:id', function(req, res, next) { IterationModel .findById(req.params.id) .then(function(iteration) { if (iteration === null) { res.status(400); res.json({msg: '迭代不存在'}); } else { req.iteration = iteration; next(); } }); }); // 编辑 router.put('/:id', checkVersionId); router.put('/:id', function(req, res, next) { if ((req.iteration.name !== req.body.name) || (req.iteration.version_id !== req.body.version_id)) { checkUniqVN(req, res, next); } else { next(); } }); router.put('/:id', function(req, res) { var iteration = req.iteration; iteration .updateAttributes(req.body) .then(function() { res.json({id: iteration.id}); }) .catch(function(err) { RouterService.json(err, res); }); }); // 关闭 router.put('/:id/toggle', function (req, res) { req.iteration .toggle() .then(function () { res.json({msg: '操作成功'}); }) .catch(function (err) { RouterService.json(err, res); }); }); // 删除 router.delete('/:id', function(req, res) { var iteration = req.iteration; iteration.status = IterationModel.statusDeleted; iteration .save() .then(function() { res.json({msg: '删除成功'}); }); }); function checkVersionId(req, res, next) { // 检查版本ID是否存在 VersionModel .findById(req.body.version_id) .then(function(version) { if (version) { next(); } else { res.status(400); res.json({msg: '版本号不存在'}); } }); } function checkUniqVN(req, res, next) { // 校验迭代名称是否存在 IterationModel .find({ where: { version_id: req.body.version_id, name: req.body.name, } }) .then(function(iteration) { if (iteration) { res.status(400); res.json({msg: '迭代名称存在'}); } else { next(); } }); } module.exports = router; <|start_filename|>controller/task_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var moment = require('moment'); var async = require('async'); var _ = require('underscore'); var logger = require('../library/logger'); var IterationModel = require('../model/iteration_model'); var TaskModel = require('../model/task_model'); var VersionModel = require('../model/version_model'); var TaskFollowModel = require('../model/task_follow_model'); var UserModel = require('../model/user_model'); var TaskStatusModel = require('../model/task_status_model'); var TaskHistoryModel = require('../model/task_history_model'); var TaskConcernedModel = require('../model/task_concerned_model'); var StoryModel = require('../model/story_model'); var ProjectModel = require('../model/project_model'); var CsvModel = require('../model/csv_model'); var TaskService = require('../service/task_service'); var RouterService = require('../service/router_service'); var CsvService = require('../service/csv_service'); var UserService = require('../service/user_service'); // 全局 // router.use('/', UserService.checkSession); // 呈现列表 router.get('/', function (req, res, next) { if (req.query.iteration_id) { checkIterationId(req, res, next); } else { next(); } }); router.get('/', function (req, res, next) { if (req.query.user_id) { checkUserId(req, res, next); } else { next(); } }); router.get('/', function (req, res) { var where = { status: TaskModel.statusOnline // 在线的任务 }; if (req.query.user_id) { // 获取某个用户 where.user_id = req.query.user_id; } if (req.query.iteration_id) { // 获取迭代对应的 where.iteration_id = req.query.iteration_id; } TaskModel .findAll({ where: where, include: [ {model: UserModel}, {model: TaskStatusModel}, {model: TaskFollowModel}, {model: TaskHistoryModel}, {model: StoryModel, where: {status: StoryModel.statusOnline}}, {model: IterationModel, where: {status: IterationModel.statusOnline}}, {model: VersionModel}, {model: ProjectModel}, {model: TaskConcernedModel} ], order: 'status_id ASC', offset: req.query.offset || 0, limit: req.query.size || 10 }) .then(function (result) { res.json(result); }); }); // 新建任务 router.post('/', checkIterationId); router.post('/', checkStoryId); router.post('/', checkUserId); router.post('/', checkPrevTaskIds); router.post('/', checkTaskStausId); router.post('/', checkVersionId); router.post('/', function (req, res, next) { // 添加任务 TaskModel .create({ project_id: req.version.project_id, version_id: req.version.id, iteration_id: req.iteration.id, story_id: req.story.id, user_id: req.body.user_id, desc: req.body.desc, is_new: req.body.is_new, is_challenging: req.body.is_challenging, priority: req.body.priority, estimated_time: req.body.estimated_time, status_id: req.body.task_status_id, create_time: moment().unix(), remark: req.body.remark || '', deadline: req.body.deadline || 0 }) .then(function (task) { req.task = task; next(); }) .catch(function (err) { RouterService.json(err, res); }); }); router.post('/', function (req, res) { // 前置任务添加 async.each(req.prevTaskIds, function (prevTaskId, callback) { TaskFollowModel .create({ task_id: req.task.id, prev_task_id: prevTaskId, create_time: moment().unix() }) .then(function () { callback(); }); }, function (err) { res.json({id: req.task.id}); }); }); // 编辑任务 router.put('/:id', checkTaskId); router.put('/:id', checkIterationId); router.put('/:id', checkVersionId); router.put('/:id', checkUserId); router.put('/:id', checkStoryId); router.put('/:id', checkPrevTaskIds); router.put('/:id', function (req, res, next) { if (!UserService.isMe(req, req.body.user_id)) { TaskService.sendMsgWhenAuthorChanged(req.task, req.user, req.session.user); } next(); }); router.put('/:id', function (req, res, next) { req.task .update({ project_id: req.version.project_id, version_id: req.version.id, iteration_id: req.iteration.id, story_id: req.story.id, user_id: req.body.user_id, desc: req.body.desc, is_new: req.body.is_new, is_challenging: req.body.is_challenging, priority: req.body.priority, estimated_time: req.body.estimated_time, remark: req.body.remark || '', deadline: req.body.deadline || 0 }) .then(function (task) { next(); }) .catch(function (err) { RouterService.json(err, res); }); }); router.put('/:id', function (req, res) { // 删除老的关联 async.series([ // 是否有前置任务 function (callback) { if (req.prevTaskIds.length === 0) { callback(true); } else { callback(null); } }, // 清除老的 function (callback) { TaskFollowModel .findAll({ where: {task_id: req.task.id} }) .then(function (tasks) { tasks.forEach(function (task) { task.destroy(); }); callback(null); }); }, // 新增 function (callback) { req.prevTaskIds.forEach(function (prevTaskId) { TaskFollowModel .create({ task_id: req.task.id, prev_task_id: prevTaskId, create_time: moment().unix() }) .then(function () { callback(null); }); }); } ], function () { res.json({id: req.task.id}); }); }); // 删除任务 router.delete('/:id', checkTaskId); router.delete('/:id', function (req, res) { req.task .update({ status: TaskModel.statusOffline }) .then(function () { res.json({msg: '删除成功'}); }); }); // 拉动任务 router.put('/:id/status', checkTaskId); router.put('/:id/status', checkTaskStausId); router.put('/:id/status', function (req, res, next) { req.task .drag(req.body.task_status_id) .then(function (task) { res.json({id: task.id}); }); next(); }); router.put('/:id/status', function (req) { // 前置任务完成则推送99U // 判断是否开发完成 if (!TaskStatusModel.isDragToComplete(req.body.task_status_id)) { return; } // send msg TaskService.sendPreTaskMsg(req.task); TaskService.sendConcernedMsg(req.task); TaskService.sendLeaderMsg(req.task); }); // 任务deadline信息通知 router.get('/deadline', function (req, res) { TaskService.sendDeadlineMsg(function (err, results) { res.json({msg: '通知成功'}); }); }); // 关注任务 router.post('/:id/concerned', checkTaskId); router.post('/:id/concerned', checkUserId); router.post('/:id/concerned', function (req, res, next) { // 判断是否关注 TaskConcernedModel .find({ where: { task_id: req.params.id, user_id: req.body.user_id } }) .then(function (taskConcerned) { if (taskConcerned === null) { next(); } else { res.status(400); res.json({msg: '已关注'}); } }); }); router.post('/:id/concerned', function (req, res) { TaskConcernedModel .build({ task_id: req.params.id, user_id: req.body.user_id, create_time: moment().unix() }) .save() .then(function () { res.json({msg: '关注成功'}); }) .catch(function (err) { RouterService.json(err, res); }); }); // 取消关注 router.post('/:id/unconcerned', checkTaskId); router.post('/:id/unconcerned', checkUserId); router.post('/:id/unconcerned', function (req, res) { TaskConcernedModel .find({ where: {task_id: req.task.id, user_id: req.user.id} }) .then(function (taskConcerned) { if (taskConcerned) { taskConcerned .destroy() .then(function () { res.json({msg: '取消成功'}); }); } }); }); // 上传 router.post('/upload', function (req, res) { CsvService.upload(req.files.csv, function (err, csv) { if (err) { res.status(400); res.json(err); } else { res.json({id: csv.id}); } }); }); // 上传结果 router.get('/upload/show/:id', function (req, res, next) { CsvModel .findById(req.params.id) .then(function (csv) { if (csv === null) { res.status(400); res.json({msg: '不存在的导入'}); } else { req.csv = csv; next(); } }); }); router.get('/upload/show/:id', function (req, res) { setTimeout(function () { res.sendFile(logger.filename('csv', req.csv.id)); }, 5000); }); function checkUserId(req, res, next) { UserModel .findById(req.param('user_id')) .then(function (user) { if (user === null) { res.status(404); res.json({msg: '用户不存在'}); } else { req.user = user; next(); } }); } function checkTaskStausId(req, res, next) { TaskStatusModel .findById(req.body.task_status_id) .then(function (taskStatus) { if (taskStatus === null) { res.status(404); res.json({msg: '请提供正确的状态'}); } else { next(); } }); } function checkVersionId(req, res, next) { VersionModel .findById(req.iteration.version_id) .then(function (version) { if (version === null) { res.status(404); res.json({msg: '迭代对应的版本号记录不存在.'}); } else { req.version = version; next(); } }); } function checkStoryId(req, res, next) { StoryModel .findById(req.param('story_id')) .then(function (story) { if (story === null) { res.status(404); res.json({msg: '故事不存在'}); } else { req.story = story; next(); } }); } function checkIterationId(req, res, next) { IterationModel .findById(req.param('iteration_id')) .then(function (iteration) { if (iteration === null) { res.status(404); res.json({msg: '迭代计划不存在'}); } else { if (iteration.isClosed()) { res.status(404); res.json({msg: '迭代计划已关闭,不能进行任何操作了.'}); } else { req.iteration = iteration; next(); } } }); } function checkTaskId(req, res, next) { TaskModel .findById(req.params.id) .then(function (task) { if (task === null) { res.status(404); res.json({msg: '任务不存在'}); } else { req.task = task; next(); } }); } function checkPrevTaskIds(req, res, next) { if (req.body.prev_task_ids === undefined) { req.prevTaskIds = []; } else { req.prevTaskIds = req.body.prev_task_ids; } next(); } module.exports = router; <|start_filename|>library/session.js<|end_filename|> var uidSafe = require('uid-safe').sync; var redis = require('../library/redis').create(); function Session() { } module.exports = Session; <|start_filename|>service/story_service.js<|end_filename|> var async = require('async'); var moment = require('moment'); var logger = require('../library/logger'); var UserModel = require('../model/user_model'); var ProjectModel = require('../model/project_model'); var VersionModel = require('../model/version_model'); var StoryModel = require('../model/story_model'); var StoryService = { upload: function (csvId, info, callback) { /** * info数据格式 * 名称,负责人,时间,所属项目,所属版本 * 业务逻辑层-信息统计服务,王文生,20150416-20150516,导购app,v0.1 */ var props = info.split(','); logger.log('csv', '----', csvId); logger.log('csv', '故事 - 开始导入,信息为:', csvId); logger.log('csv', props.toString(), csvId); async.waterfall([ // 判断用户是否存在 function (callback) { UserModel .find({ where: {name: props[1]} }) .then(function (user) { if (user === null) { callback('故事 - 负责人[' + props[1] + ']不存在,忽略'); } else { callback(null, user); } }); }, // 判断项目是否存在 function (user, callback) { ProjectModel .find({ where: {name: props[2]} }) .then(function (project) { if (project === null) { callback('故事 - 项目[' + props[2] + ']不存在,忽略'); } else { callback(null, user, project); } }); }, // 判断项目下的版本是否存在 function (user, project, callback) { VersionModel .find({ where: {project_id: project.id, name: props[3]} }) .then(function (version) { if (version === null) { callback('故事 - 项目[' + props[2] + '],版本[' + props[3] + ']不存在,忽略'); } else { callback(null, user, project, version); } }); }, // 执行导入 function (user, project, version, callback) { var time = props[2].split('-'); StoryModel .findOrCreate({ where: {version_id: version.id, title: props[0]}, defaults: { leader: user.id, priority: 3, } }) .spread(function (story, created) { if (created) { logger.log('csv', '故事 - [' + story.title + ']导入成功,ID=' + story.id, csvId); } else { logger.log('csv', '故事 - [' + story.title + ']已存在,ID=' + story.id +',忽略', csvId); } callback(null); }); } ], function (err, result) { if (err) { logger.log('csv', err, csvId); } callback(err, result); }); } }; module.exports = StoryService; <|start_filename|>controller/msg_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var Msg91uModel = require('../model/msg91u_model'); var UserModel = require('../model/user_model'); router.get('/', checkUserId); router.get('/', function (req, res) { Msg91uModel .findAll({ where: {receiver: req.query.user_id}, offset: req.query.offset || 0, limit: req.query.size || 10, order: 'id DESC' }) .then(function (msgs) { res.json(msgs); }); }); function checkUserId(req, res, next) { UserModel .findById(req.query.user_id) .then(function (user) { if (user) { req.user = user; next(); } else { res.status(400); res.json({msg: '用户不存在'}); } }); } module.exports = router; <|start_filename|>model/project_model.js<|end_filename|> // 依赖 var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); // 类 var ProjectModel = module.exports = base.define('project', { leader: { type: Sequelize.INTEGER }, status: { type: Sequelize.INTEGER }, name: { type: Sequelize.STRING }, create_time: { type: Sequelize.INTEGER, defaultValue: moment().unix() } }); // 状态 ProjectModel.statusOnline = 0; ProjectModel.statusDeleted = 99; // 关系 var VersionModel = require('./version_model'); ProjectModel.hasMany(VersionModel, {foreignKey: 'project_id'}); <|start_filename|>controller/index_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var UserService = require('../service/user_service'); /* GET home page. */ router.get('/', function (req, res) { res.end('welcome!'); }); router.get('/redis', UserService.checkSession); router.get('/redis', function (req, res) { res.json(req.session); }); module.exports = router; <|start_filename|>library/mail.js<|end_filename|> var nodemailer = require('nodemailer'); var config = require('../config/global').get('email'); var transpoter = nodemailer.createTransport({ service: config.service, auth: { user: config.username, pass: <PASSWORD> } }); function Mail(toEmail) { this.toEmail = toEmail; } Mail.prototype.send = function (msg) { var mailOptions = { from: config.username, to: this.toEmail, subject: msg, text: msg, html: '<b>' + msg + '</b>' }; transpoter.sendMail(mailOptions, function (err, info) { if (err) { console.log(err); return; } console.log('message sent: ' + info.response); }); } module.exports = exports = Mail; <|start_filename|>model/post_model.js<|end_filename|> // 依赖 var Sequelize = require('sequelize'); var base = require('./base'); // 类 var PostModel = base.define('post', { title: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, content: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, create_time: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0 }, }, { paranoid: true, comment: '评论表', classMethods: { say: function() { return 'say'; } }, instanceMethods: { world: function() { return 'world'; } } }); module.exports = PostModel; <|start_filename|>model/task_status_model.js<|end_filename|> var Sequelize = require('sequelize'); var base = require('./base'); var TaskStatusModel = base.define('task_status', { name: { type: Sequelize.STRING, }, sort: { type: Sequelize.INTEGER, }, create_time: { type: Sequelize.INTEGER, }, }, { classMethods: { isDragToComplete: function(status_id) { return parseInt(status_id, 10) === TaskStatusModel.COMPLETE; } }, }); TaskStatusModel.WAITING = 10; TaskStatusModel.DEVING = 20; TaskStatusModel.COMPLETE = 50; module.exports = TaskStatusModel; <|start_filename|>library/redis.js<|end_filename|> var redis = require('redis'); var crypto = require('crypto'); var Redis = { clients: [], create: function (config) { console.log('获取redis client实例'); config = config || require('../config/global').get('redis'); console.log('redis的配置信息为' + JSON.stringify(config)); var key = this.key(config); console.log('缓存key值为' + key); if (!this.clients[key]) { console.log('缓存中没有,开始创建redis client实例'); this.clients[key] = redis.createClient(config.port, config.host); } else { console.log('读取缓存中的redis client实例'); } return this.clients[key]; }, key: function (config) { var md5 = crypto.createHash('md5'); md5.update(JSON.stringify(config)); return md5.digest('hex').substr(0, 4); } }; module.exports = Redis; <|start_filename|>library/logger.js<|end_filename|> /** * 效果: * /data/cephfs/log/board/csv-2015-02-02.log */ var fs = require('fs'); var moment = require('moment'); var sprintf = require('sprintf').sprintf; var path = require('path'); var Logger = { root: '/data/cephfs/log/board', filename: function (filename, symbol) { if (symbol === undefined) { symbol = moment().format('YYYY-MM-DD'); } return sprintf('%s/%s-%s.log', this.root, filename, symbol); }, log: function (filename, data, symbol, callback) { if (symbol === undefined) { symbol = moment().format('YYYY-MM-DD'); } var _filename = sprintf('%s/%s-%s.log', this.root, filename, symbol); fs.appendFile(_filename, data + "\n", callback); }, read: function (filename, symbol, callback) { if (symbol === undefined) { symbol = moment().format('YYYY-MM-DD'); } var _filename = sprintf('%s/%s-%s.log', this.root, filename, symbol); fs.readFile(_filename, function (err, data) { if (err) throw err; callback(err, data); }); }, init: function () { this._mkdirs(this.root, 0777, function () { console.log('success'); }); }, _mkdirs: function (dir, mode, callback) { var self = this; fs.exists(dir, function (exists) { if (exists) { callback(null); } else { self._mkdirs(path.dirname(dir), mode, function () { fs.mkdir(dir, mode, callback); }); } }); } }; Logger.init(); module.exports = Logger; <|start_filename|>model/iteration_model.js<|end_filename|> // 依赖 var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); // 类 var IterationModel = module.exports = base.define('iteration', { version_id: { type: Sequelize.INTEGER, }, name: { type: Sequelize.STRING, }, start_time: { type: Sequelize.INTEGER, defaultValue: 0, }, end_time: { type: Sequelize.INTEGER, validate: { ltStartTime: function() { if (this.start_time >= this.end_time) { throw new Error('结束时间应大于起始时间'); } } } }, status: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, validate: { isInt: { msg: '状态值为整形数值' }, isIn: { args: [[0, 1, 99]], msg: '值为非法值', }, } }, create_time: { type: Sequelize.INTEGER, defaultValue: moment().unix(), }, }, { validate: { }, classMethods: { }, instanceMethods: { isClosed: function() { return this.status === IterationModel.statusClosed; }, toggle: function () { // 关闭/打开迭代 if (this.status === 0) { this.status = 1; return this.save(); } else { this.status = 0; return this.save(); } }, getDates: function () { var startDate = moment(this.start_time, 'X'); var endDate = moment(this.end_time, 'X'); var dates = []; while (endDate.isAfter(startDate)) { dates.push(startDate.format('YYYYMMDD')); startDate.add(1, 'days'); } dates.push(endDate.format('YYYYMMDD')); return dates; } } }); // 状态 IterationModel.statusOnline = 0; // 打开 IterationModel.statusClosed = 1; // 关闭 IterationModel.statusDeleted = 99; // 删除 // 关系 var VersionModel = require('./version_model'); IterationModel.belongsTo(VersionModel, { foreignKey: 'version_id' }); <|start_filename|>config/global.js<|end_filename|> // global config var config = new Map(); // mysql config.set('mysql', { host: '127.0.0.1', port: 3306, user: '', // enter username password: '', // input password database: '' // input database }); // redis config.set('redis', { host: '127.0.0.1', port: 6379 }); // email // tips: don't use qq mail config.set('email', { service: '126', username: '<EMAIL>', password: '<PASSWORD>' }); // merge config from local.js // if local.js is existed and local.js defines the configuration is used to local's, otherwise use global's // like array_merge function in php var fs = require('fs'); if (fs.existsSync(__dirname + '/local.js')) { var customer = require('./local'); customer.forEach(function (value, key) { config.set(key, value); }); } module.exports = config; <|start_filename|>service/router_service.js<|end_filename|> var RouterService = { json: function (err, res) { res.status(400); res.json({msg: err.errors[0].message}); } } module.exports = RouterService; <|start_filename|>model/msg91u_model.js<|end_filename|> var Sequelize = require('sequelize'); var base = require('./base'); var moment = require('moment'); var Msg91uModel = module.exports = base.define('msg91u', { content: { type: Sequelize.STRING }, receiver: { type: Sequelize.INTEGER }, is_readed: { type: Sequelize.INTEGER }, create_time: { type: Sequelize.INTEGER, defaultValue: moment().unix() }, is_deleted: { type: Sequelize.INTEGER } }); <|start_filename|>service/iteration_service.js<|end_filename|> var async = require('async'); var moment = require('moment'); var logger = require('../library/logger'); var VersionModel = require('../model/version_model'); var ProjectModel = require('../model/project_model'); var IterationModel = require('../model/iteration_model'); var IterationService = { upload: function (csvId, info, callback) { /** * info数据格式 * 名称,时间,所属项目,所属版本, * 第一迭代,20150416-20150516,导购app,v0.1, */ var props = info.split(','); logger.log('csv', '----', csvId); logger.log('csv', '版本 - 开始导入,信息为:', csvId); logger.log('csv', props.toString(), csvId); async.waterfall([ // 检查项目存在否 function (callback) { ProjectModel .find({ where: {name: props[2]} }) .then(function (project) { if (project === null) { callback('迭代 - 项目[' + props[2] + ']不存在,忽略'); } else { callback(null, project); } }); }, // 检查版本存在否 function (project, callback) { VersionModel .find({ where: {project_id: project.id, name: props[3]} }) .then(function (version) { if (version === null) { callback('迭代 - 项目[' + props[2] + '],版本[' + props[3] + ']不存在,忽略'); } else { callback(null, project, version); } }); }, // 执行导入 function (project, version, callback) { var time = props[1].split('-'); IterationModel .findOrCreate({ where: {version_id: version.id, name: props[0]}, defaults: { start_time: moment(time[0], 'YYYYMMDD').format('X'), end_time: moment(time[1], 'YYYYMMDD').format('X'), } }) .spread(function (iteration, created) { if (created) { logger.log('csv', '迭代 - 项目[' + project.name + '],版本[' + version.name + '],迭代[' + iteration.name + ']导入成功,ID=' + iteration.id, csvId); } else { logger.log('csv', '迭代 - 项目[' + project.name + '],版本[' + version.name + '],已存在迭代[' + iteration.name + '],ID=' + iteration.id + ',忽略', csvId); } callback(null); }); } ], function (err, result) { // 成功 if (err) { logger.log('csv', err, csvId); } callback(err, result); }); } }; module.exports = IterationService; <|start_filename|>app.js<|end_filename|> var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var multer = require('multer'); var validator = require('express-validator'); var app = express(); // env app.set('env', 'development'); // view engine app.set('views', path.join(__dirname, 'view')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); // data validator app.use(validator({ customValidators: { // custom functions isArray: function(value) { return Array.isArray(value); } }, errorFormatter: function (param, msg, value) { // error formatter return { param: param, msg: msg, value: value }; } })); // cookie app.use(cookieParser()); // file uploader app.use(require('stylus').middleware(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); app.use(multer({ dest: '/tmp/board' })); // jsonp app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); next(); }); // router / controller var SiteController = require('./controller/index_controller'); var UserController = require('./controller/user_controller'); var ProjectController = require('./controller/project_controller'); var VersionController = require('./controller/version_controller'); var IterationController = require('./controller/iteration_controller'); var StoryController = require('./controller/story_controller'); var TaskController = require('./controller/task_controller'); var TaskStatusController = require('./controller/task_status_controller'); var StatisticController = require('./controller/statistics_controller'); var MsgController = require('./controller/msg_controller'); var TestController = require('./controller/test_controller'); app.use('/', SiteController); app.use('/user', UserController); app.use('/projects', ProjectController); app.use('/versions', VersionController); app.use('/iterations', IterationController); app.use('/stories', StoryController); app.use('/tasks', TaskController); app.use('/task_statuses', TaskStatusController); app.use('/statisticses', StatisticController); app.use('/msgs', MsgController); app.use('/test', TestController); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app; <|start_filename|>crontab/task_deadline.js<|end_filename|> var http = require('http'); var options = { host: 'dev.hbapi.hair.192.168.94.26.xip.io', port: 80, path: '/tasks/deadline', method: 'GET', headers: { 'Content-Type': 'application/json' } }; var req = http.request(options); req.end(); /** * crontab -e * 19 16 * * * /home/yangzb/bin/node /home/yangzb/1_projects/hb_dev/crontab/task_deadline.js */ <|start_filename|>controller/story_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var VersionModel2 = require('../model/version_model'); var UserModel2 = require('../model/user_model'); var StoryModel2 = require('../model/story_model'); var RouterService = require('../service/router_service'); router.post('/', checkVersionId); router.post('/', checkLeader); router.post('/', checkVt); router.post('/', function(req, res) { StoryModel2 .build(req.body) .save() .then(function(story) { res.json({id: story.id}); }) .catch(function(err) { RouterService.json(err, res); }); }); router.get('/', checkVersionId); router.get('/', function(req, res) { StoryModel2 .findAll({ where: { version_id: req.query.version_id, status: StoryModel2.statusOnline }, include: [UserModel2], order: 'id DESC' }) .then(function(stories) { res.json(stories); }); }); router.use('/:id', function (req, res, next) { StoryModel2 .findById(req.params.id) .then(function (story) { if (story === null) { res.status(400); res.json({msg: '故事不存在'}); } else { req.story = story; next(); } }); }); router.put('/:id', function (req, res, next) { if (isVtChanged(req, req.story)) { checkVt(req, res, next); } else { next(); } }); router.put('/:id', function (req, res) { req.story .updateAttributes(req.body) .then(function () { res.json({msg: '编辑成功'}); }) .catch(function (err) { RouterService.json(err, res); }); }); router.delete('/:id', function (req, res) { req.story .updateAttributes({ status: StoryModel2.statusDeleted }) .then(function () { res.json({msg: '删除成功'}); }); }); function checkVersionId(req, res, next) { VersionModel2 .findById(req.param('version_id')) .then(function(version) { if (version === null) { res.status(400); res.json({msg: '版本不存在'}); } else { req.version = version; next(); } }); } function checkLeader(req, res, next) { // 校验故事负责人是否存在 UserModel2 .findById(req.body.leader) .then(function(user) { if (user === null) { res.status(400); res.json({msg: '用户不存在'}); } else { req.user = user; next(); } }); } function checkVt(req, res, next) { // title是否已经存在 StoryModel2 .findByVt(req.body.version_id, req.body.title) .then(function (story) { if (story) { res.status(400); res.json({msg: '故事title存在'}); } else { next(); } }); } function isVtChanged(req, story) { return req.body.title !== story.title || parseInt(req.body.version_id) !== parseInt(story.version_id); } module.exports = router; <|start_filename|>service/version_service.js<|end_filename|> var async = require('async'); var moment = require('moment'); var logger = require('../library/logger'); var VersionModel = require('../model/version_model'); var ProjectModel = require('../model/project_model'); var VersionService = { upload: function (csvId, info, callback) { var props = info.split(','); logger.log('csv', '----', csvId); logger.log('csv', '版本 - 开始导入,信息为:', csvId); logger.log('csv', props.toString(), csvId); async.waterfall([ function (callback) { // 检查版本 ProjectModel .find({ where: {name: props[2]} }) .then(function (project) { if (project === null) { callback('版本 - 项目[' + props[2] + ']不存在,忽略'); } else { callback(null, project); } }); }, function (project, callback) { // 检查版本是否存在 var time = props[1].split('-'); VersionModel .findOrCreate({ where: {project_id: project.id, name: props[0]}, defaults: { start_time: moment(time[0], 'YYYYMMDD').format('X'), end_time: moment(time[1], 'YYYYMMDD').format('X'), create_time: moment().unix() } }) .spread(function (version, created) { if (created) { logger.log('csv', '版本 - [' + version.name + ']导入成功,ID=' + version.id, csvId); } else { logger.log('csv', '版本 - [' + version.name + ']已存在,ID=' + version.id +',忽略', csvId); } callback(null); }); } ], function (err, result) { if (err) { logger.log('csv', err, csvId); } callback(err, result); }); } }; module.exports = VersionService; <|start_filename|>model/base.js<|end_filename|> // 依赖 var config = require('../config/global').get('mysql'); var Sequelize = require('sequelize'); // 导出 var base = new Sequelize(config.database, config.user, config.password, { host: config.host, dialect: 'mysql', define: { engine: 'innodb', freezeTableName: true, // 使用define中的名字 timestamps: false, // 取消字段updateAt,createAt } }); console.log('链接成功'); module.exports = base; <|start_filename|>library/helper.js<|end_filename|> var Helper = { isEmptyObj: function(obj) { for (var key in obj) { return false; } return true; }, isEmptyArray: function(arr) { return arr.length === 0 ? true : false; } }; module.exports = Helper; <|start_filename|>model/version_model.js<|end_filename|> // 依赖 var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); // 类 var VersionModel = module.exports = base.define('version', { project_id: { type: Sequelize.INTEGER, }, name: { type: Sequelize.STRING, allowNull: false, defaultValue: '', validate: { min: 0, max: 10, } }, start_time: { type: Sequelize.INTEGER, validate: { isLtStartTime: function () { if (this.start_time > this.end_time) { throw new Error('结束时间应大于起始时间'); } } } }, end_time: { type: Sequelize.INTEGER, validate: { isGtStartTime: function () { if (this.start_time > this.end_time) { throw new Error('结束时间应大于起始时间'); } } } }, relaxed: { type: Sequelize.STRING, defaultValue: '', }, status: { type: Sequelize.INTEGER, defaultValue: 0, validate: { isIn: [[0, 1, 99]] } }, create_time: { type: Sequelize.INTEGER, defaultValue: 0, }, }, { instanceMethods: { toggle: function() { if (this.status === 0) { this.status = 1; return this.save(); } else { this.status = 0; return this.save(); } }, getDates: function () { // 获取版本对应的时间,去除休息段的时间 var startDate = moment(this.start_time, 'X'); var endDate = moment(this.end_time, 'X'); var dates = []; while (endDate.isAfter(startDate)) { var format = startDate.format('YYYYMMDD'); if (this.relaxed.indexOf(format) === -1) { dates.push(format); } startDate.add(1, 'days'); } dates.push(endDate.format('YYYYMMDD')); return dates; } } }); // 状态 VersionModel.statusOnline = 0; VersionModel.statusClosed = 1; VersionModel.statusDeleted = 99; // 关系 var ProjectModel = require('./project_model'); var IterationModel = require('./iteration_model'); VersionModel.belongsTo(ProjectModel, { foreignKey: 'project_id' }); VersionModel.hasMany(IterationModel, { foreignKey: 'version_id' }); <|start_filename|>controller/statistics_controller.js<|end_filename|> var express = require('express'); var router = express.Router(); var async = require('async'); var moment = require('moment'); var querystring = require('querystring'); var VersionModel = require('../model/version_model'); var RouterService = require('../service/router_service'); var TaskModel = require('../model/task_model'); var UserModel = require('../model/user_model'); var StoryModel = require('../model/story_model'); var IterationModel = require('../model/iteration_model'); var ProjectModel = require('../model/project_model'); var TaskFollowModel = require('../model/task_follow_model'); // 工时统计 router.get('/hours', function (req, res, next) { if (req.query.project_id) { checkProjectId(req, res, next); } else { next(); } }); router.get('/hours', function (req, res, next) { if (req.query.version_id) { checkVersionId(req, res, next); } else { next(); } }); router.get('/hours', function (req, res, next) { if (req.query.iteration_id) { checkIterationId(req, res, next); } else { next(); } }); router.get('/hours', function (req, res) { // 获取统计工时 var where = { status: {$ne: TaskModel.statusOffline} }; var versionWhere = { status: VersionModel.statusOnline }; var iterationWhere = { status: IterationModel.statusOnline }; if (req.query.project_id) { where.project_id = req.project_id.id; } if (req.query.version_id) { // 支持版本id where.version_id = req.version.id; } if (req.query.iteration_id) { // 支持迭代id where.iteration_id = req.query.iteration_id; } if (req.query.start_time || req.query.end_time) { where.end_time = {}; if (req.query.start_time) { where.end_time.$gte = req.query.start_time; } if (req.query.end_time) { where.end_time.$lte = req.query.end_time; } where.status_id = TaskFollowModel.idCompleted; versionWhere.status = {$between: [VersionModel.statusOnline, VersionModel.statusClosed]}; iterationWhere.status = {$between: [IterationModel.statusOnline, IterationModel.statusClosed]}; } TaskModel .findAll({ where: where, include: [ {model: UserModel}, {model: VersionModel, where: versionWhere}, {model: IterationModel, where: iterationWhere}, {model: StoryModel, where: {status: {$ne: StoryModel.statusDeleted}}} ], order: 'user_id ASC' }) .then(function (tasks) { res.json(tasks); }); }); // 故事统计 router.get('/story', checkVersionId); router.get('/story', function (req, res, next) { if (req.query.iteration_id) { checkIterationId(req, res, next); } else { next(); } }); router.get('/story', function (req, res) { async.waterfall([ function (callback) { // 获取story var where = { status: StoryModel.statusOnline }; if (req.query.version_id) { // 支持版本id where.version_id = req.version.id; } StoryModel .findAll({ where: where }) .then(function (stories) { if (stories === null) { callback('empty story'); } else { callback(null, stories); } }); }, function (stories, callback) { // 获取任务 async.map(stories, function (story, cb) { var where = { version_id: story.version_id, story_id: story.id, status: TaskModel.statusOnline }; if (req.query.iteration_id) { where.iteration_id = req.query.iteration_id; } TaskModel .findAll({ where: where }) .then(function (tasks) { story.setDataValue('tasks', tasks); cb(null, story); }); }, function (err, stories) { callback(err, stories); }); } ], function (err, result) { if (err) throw err; res.json(result); }); }); // 燃尽图 router.get('/bdc', checkVersionId); router.get('/bdc', function (req, res, next) { if (req.query.iteration_id) { checkIterationId(req, res, next); } else { next(); } }); router.get('/bdc', function (req, res) { async.waterfall([ function (callback) { // 获取X(时间)坐标 var dates = []; if (req.query.iteration_id) { dates = req.iteration.getDates(); } else { dates = req.version.getDates(); } callback(null, dates); }, function (dates, callback) { // 改造时间格式 /** * 由['20150101', '20150102', ...] => 弄成{20150101: 0, 20150102: 0, 20150103: 0, ...} */ var details = {}; dates.forEach(function (date) { details[date] = 0; }); callback(null, dates, details); }, function (dates, details, callback) { // 获取任务 var where = { version_id: req.version.id, status: {$ne: TaskModel.statusOffline} }; if (req.query.iteration_id) { where.iteration_id = req.query.iteration_id; } TaskModel .findAll({ where: where, include: [ {model: StoryModel, where: {status: {$ne: StoryModel.statusDeleted}}} ], }) .then(function (tasks) { callback(null, dates, details, tasks); }); }, function (dates, details, tasks, callback) { // 计算任务 var totalHours = 0; var msgs = []; async.each(tasks, function (task, cb) { msgs.push('-----'); // 计算总估时 totalHours += task.estimated_time; // 没有完成,则忽略 if (!task.isCompleted()) { var msg = '任务[' + task.desc + ']尚未完成。'; msgs.push(msg); cb(null); return; } // 检查结束时间 var endDate = moment(task.end_time, 'X'); if (!endDate.isValid()) { var msg = '任务[' + task.desc + ']的结束时间为[' + task.end_time + ']解析错误,因此忽略'; msgs.push(msg); cb(null); return; } var format = endDate.format('YYYYMMDD'); var msg = '任务[' + task.desc + ']开始统计工时,工时为[' + task.estimated_time + '],时间为[' + format + ']'; msgs.push(msg); // 判断时间是否在范围 if (!(format in details)) { var msg = '任务[' + task.desc + '],工时为[' + task.estimated_time + '],不在时间段内[' + dates.toString() + '],因此忽略统计。'; msgs.push(msg); cb(null); return; } // 计算完成工时 var msg = '时间[' + format + ']完成任务[' + task.desc + '],获得[' + task.estimated_time + ']小时的统计。'; msgs.push(msg); details[format] += task.estimated_time; cb(null); }, function (err) { callback(err, details, totalHours, msgs); }); } ], function (err, details, totalHours, msgs) { if (err) throw err; var result = {total: totalHours, details: details}; if (req.query.debug) { result.msgs = msgs; } res.json(result); }); }); function isGetByVersionId(req) { if (req.query.version_id && !req.query.recently) { return true; } return false; } function isGetByIterationId(req) { return req.query.iteration_id ? true : false; } function checkVersionId(req, res, next) { // 检查版本 VersionModel .findById(req.query.version_id) .then(function (version) { if (version === null) { res.status(400); res.json({msg: '版本不存在'}); } else { req.version = version; next(); } }); } function checkIterationId(req, res, next) { // 检查迭代 IterationModel .findById(req.query.iteration_id) .then(function (iteration) { if (iteration === null) { res.status(400); res.json({msg: '迭代不存在'}); } else { req.iteration = iteration; next(); } }); } function checkProjectId(req, res, next) { ProjectModel .findById(req.query.project_id) .then(function (project) { if (project === null) { res.status(400); res.json({msg: '项目不存在'}); } else { req.project = project; next(); } }); } module.exports = router; <|start_filename|>service/csv_service.js<|end_filename|> var crypto = require('crypto'); var moment = require('moment'); var fs = require('fs'); var path = require('path'); var iconv = require('iconv-lite'); var async = require('async'); var logger = require('../library/logger'); var CsvModel = require('../model/csv_model'); var ProjectService = require('../service/project_service'); var VersionService = require('../service/version_service'); var IterationService = require('../service/iteration_service'); var StoryService = require('../service/story_service'); var TaskService = require('../service/task_service'); var CsvService = { root: '/data/cephfs/board', upload: function (csv, callback) { var self = this; this.insertDb(csv, function (err, csvModel) { fs.readFile(csv.path, function (err, data) { if (err) { throw err; } self.generateAll(data, csvModel); self.mvFile(csv, data); }); callback(null, csvModel); }); }, getDir: function (name) { var key = name.split('.')[0]; var part1 = key.substr(0, 2); var part2 = key.substr(2, 2); return this.root + '/' + part1 + '/' + part2; }, mkdir: function (dir, mode, callback) { // 创建多级目录 var self = this; path.exists(dir, function (exists) { if (exists) { callback(dir); } else { self.mkdir(path.dirname(dir), mode, function () { fs.mkdir(dir, mode, callback); }); } }); }, mvFile: function (csv, data) { var dir = this.getDir(csv.name); this.mkdir(dir, 0777, function (err) { if (err) { console.log(err); throw err; } var filename = dir + '/' + csv.name; fs.writeFile(filename, data); }); }, insertDb: function (csv, callback) { // 新建记录 var md5 = crypto.createHash('md5'); md5.update(csv.path); CsvModel .build({ md5: md5.digest('hex'), size: csv.size, mime: csv.mimetype, name: csv.name, originalname: csv.originalname, create_time: moment().unix() }) .save() .then(function (csv) { callback(null, csv); }) .catch(function (err) { console.log(err.errors[0].message); throw err; }); }, generateAll: function (data, csv) { var parsedContent = this.parseContent(data); var self = this; async.series([ function (callback) { // 项目 var projects = self.filter(csv.id, parsedContent.project, '项目'); self.generateProject(csv.id, projects, function () { callback(null); }); }, function (callback) { // 版本 var versions = self.filter(csv.id, parsedContent.version, '版本'); self.generateVersion(csv.id, versions, function () { callback(null); }); }, function (callback) { // 迭代 var iterations = self.filter(csv.id, parsedContent.iteration, '迭代'); self.generateIteration(csv.id, iterations, function () { callback(null); }); }, function (callback) { // 故事 var stories = self.filter(csv.id, parsedContent.story, '故事'); self.generateStory(csv.id, stories, function () { callback(null); }); }, function (callback) { // 任务 var tasks = self.filter(csv.id, parsedContent.task, '任务'); self.generateTasks(csv.id, tasks, function () { callback(null); }); } ], function (err, result) { if (err) { console.log(err); } }); }, generateProject: function (csvId, projects, callback) { // 生成项目 async.eachSeries(projects, function (project, cb) { ProjectService.upload(csvId, project, function () { cb(null); }); }, function () { callback(null); }); }, generateVersion: function (csvId, versions, callback) { // 生成版本 async.eachSeries(versions, function (version, cb) { VersionService.upload(csvId, version, function () { cb(null); }); }, function () { callback(null); }); }, generateIteration: function (csvId, iterations, callback) { // 生成迭代 async.eachSeries(iterations, function (version, cb) { IterationService.upload(csvId, version, function () { cb(null); }); }, function () { callback(null); }); }, generateStory: function (csvId, stories, callback) { async.eachSeries(stories, function (story, cb) { StoryService.upload(csvId, story, function () { cb(null); }); }, function () { callback(null); }); }, generateTasks: function (csvId, tasks, callback) { async.eachSeries(tasks, function (task, cb) { TaskService.upload(csvId, task, function () { cb(null); }); }, function () { callback(null); }); }, filter: function (csvId, content, type) { // 没有信息 if (content.length === 0) { logger.log('csv', '----', csvId); logger.log('csv', type + ' - 没有信息导入', csvId); return []; } var self = this; var sliced = content.slice(2); // 过滤 var contents = []; async.filter(sliced, function (content, cb) { if (self.isEmptyContent(content)) { cb(false); } else { cb(true); } }, function (result) { contents = result; }); return contents; }, parseContent: function (data) { // 有没有更好的parse方式?感觉现在的方式好low var decoded = iconv.decode(data, 'gbk'); var contents = decoded.split('\r\n'); var self = this; var Parsedcontent = { project: [], version: [], iteration: [], story: [], task: [] }; var isProject = false; var isVersion = false; var isIteration = false; var isStory = false; var isTask = false; contents.forEach(function (content) { if (self.isProjectExisted(content)) { Parsedcontent.project.push(content); isProject = true; isVersion = false; isIteration = false; isStory = false; isTask = false; } else if (self.isVersionExisted(content)) { isProject = false; isVersion = true; isIteration = false; isStory = false; isTask = false; Parsedcontent.version.push(content); } else if (self.isIterationExisted(content)) { isProject = false; isVersion = false; isIteration = true; isStory = false; isTask = false; Parsedcontent.iteration.push(content); } else if (self.isStoryExisted(content)) { isProject = false; isVersion = false; isIteration = false; isStory = true; isTask = false; Parsedcontent.story.push(content); } else if (self.isTaskExisted(content)) { isProject = false; isVersion = false; isIteration = false; isStory = false; isTask = true; Parsedcontent.task.push(content); } else { // 内容 if (isProject) { Parsedcontent.project.push(content); } else if (isVersion) { Parsedcontent.version.push(content); } else if (isIteration) { Parsedcontent.iteration.push(content); } else if (isStory) { Parsedcontent.story.push(content); } else if (isTask) { Parsedcontent.task.push(content); } else { // do nothing } } }); return Parsedcontent; }, isProjectExisted: function (content) { return content.indexOf('[项目]') !== -1; }, isVersionExisted: function (content) { return content.indexOf('[版本]') !== -1; }, isIterationExisted: function (content) { return content.indexOf('[迭代]') !== -1; }, isStoryExisted: function (content) { return content.indexOf('[故事]') !== -1; }, isTaskExisted: function (content) { return content.indexOf('[任务]') !== -1; }, isEmptyContent: function (content) { var parts = content.split(','); for (var key in parts) { if (parts[key] !== '') { return false; } } return true; } }; module.exports = CsvService; <|start_filename|>service/project_service.js<|end_filename|> var async = require('async'); var logger = require('../library/logger'); var ProjectModel = require('../model/project_model'); var UserModel = require('../model/user_model'); var Project = { upload: function (csvId, content, callback) { var props = content.split(','); var username = props[1]; logger.log('csv', '----', csvId); logger.log('csv', '项目 - 开始导入,信息为:', csvId); logger.log('csv', props.toString(), csvId); async.waterfall([ function (cb) { // 检查用户是否存在 UserModel .find({ where: { name: username } }) .then(function (user) { if (user === null) { cb('项目 - 用户[' + username + ']不存在,忽略'); } else { cb(null, user); } }); }, function (user, cb) { // 插入项目 ProjectModel .findOrCreate({ where: {name: props[0]}, defaults: {leader: user.id} }) .spread(function (project, created) { if (created) { logger.log('csv', '项目 - [' + project.name + ']导入成功,ID=' + project.id + '。', csvId); } else { logger.log('csv', '项目 - [' + project.name + ']已存在,忽略。', csvId); } cb(null); }); } ], function (err) { if (err) { logger.log('csv', err, csvId); } callback(null); }); } }; module.exports = Project; <|start_filename|>model/user_model.js<|end_filename|> var Sequelize = require('sequelize'); var base = require('./base'); var crypto = require('crypto'); var moment = require('moment'); var UserModel = module.exports = base.define('user', { mobile: { type: Sequelize.STRING, }, worker_num: { type: Sequelize.INTEGER, }, password: { type: Sequelize.STRING, }, salt: { type: Sequelize.STRING, }, name: { type: Sequelize.STRING, }, email: { type: Sequelize.STRING, }, create_time: { type: Sequelize.INTEGER, }, }, { instanceMethods: { isPasswordValid: function(password) { if (this.password === '') { this.password = password = <PASSWORD>; } if (!this.isSaltEmpty()) { // 老数据的密码是没有salt的 var md5 = crypto.createHash('md5'); md5.update(this.salt + password); return md5.digest('hex') === this.password; } // 对比结果 var valid = this.password === password; if (valid) { // 将salt值填充 var salt = UserModel.generateSalt(); var password = UserModel.generatePassword(salt, this.password); this.update({ salt: salt, password: password }); } return valid; }, isSaltEmpty: function() { return this.salt === ''; } }, classMethods: { generateSalt: function () { var md5 = crypto.createHash('md5'); md5.update('flzt' + moment().format('x')); return md5.digest('hex'); }, generatePassword: function (salt, password) { var md5 = crypto.createHash('md5'); md5.update(salt + password); return md5.digest('hex'); } } }); <|start_filename|>model/task_history_model.js<|end_filename|> var Sequelize = require('sequelize'); var moment = require('moment'); var base = require('./base'); var TaskHistoryModel = base.define('task_history', { task_id: { type: Sequelize.INTEGER }, current: { type: Sequelize.INTEGER }, next: { type: Sequelize.INTEGER }, user_id: { type: Sequelize.INTEGER }, create_time: { type: Sequelize.INTEGER } }, { classMethods: { gen: function (taskId, current, next, userId) { TaskHistoryModel .build({ task_id: taskId, current: current, next: next, user_id: userId, create_time: moment().unix(), }) .save() .catch(function (err) { console.log('error msg - ', err.errors); }); } } }); module.exports = TaskHistoryModel;
hinson0/task-board
<|start_filename|>color/palette/spectrum.glsl<|end_filename|> /* author: <NAME> description: Spectrum Response Function https://www.shadertoy.com/view/wlSBzD use: <vec3> spectrum(<float> value [, <float> blur]) license: | Copyright (c) 2020 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_SPECTRUM #define FNC_SPECTRUM vec3 spectrum(float x) { return (vec3( 1.220023e0,-1.933277e0, 1.623776e0) + (vec3(-2.965000e1, 6.806567e1,-3.606269e1) + (vec3( 5.451365e2,-7.921759e2, 6.966892e2) + (vec3(-4.121053e3, 4.432167e3,-4.463157e3) + (vec3( 1.501655e4,-1.264621e4, 1.375260e4) + (vec3(-2.904744e4, 1.969591e4,-2.330431e4) + (vec3( 3.068214e4,-1.698411e4, 2.229810e4) + (vec3(-1.675434e4, 7.594470e3,-1.131826e4) + vec3( 3.707437e3,-1.366175e3, 2.372779e3) *x)*x)*x)*x)*x)*x)*x)*x)*x; } vec3 spectrum(float x, float blur) { vec4 a = vec4( 1., .61, .78, .09), o = vec4(-.57, -.404, -.176, -.14), f = vec4(223., 165., 321., 764.) / blur, c = a*pow(cos(x + o), f); c.r += c.w; return c.rgb; } #endif <|start_filename|>lighting/diffuse.glsl<|end_filename|> #include "diffuse/lambert.glsl" #include "diffuse/orenNayar.glsl" #include "diffuse/burley.glsl" /* author: <NAME> description: calculate diffuse contribution use: lightSpot(<vec3> _diffuseColor, <vec3> _specularColor, <vec3> _N, <vec3> _V, <float> _NoV, <float> _f0, out <vec3> _diffuse, out <vec3> _specular) options: - DIFFUSE_FNC: diffuseOrenNayar, diffuseBurley, diffuseLambert (default) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef DIFFUSE_FNC #define DIFFUSE_FNC diffuseLambert #endif #ifndef FNC_DIFFUSE #define FNC_DIFFUSE float diffuse(vec3 L, vec3 N, vec3 V, float roughness) { return DIFFUSE_FNC(L, N, V, roughness); } float diffuse(vec3 _L, vec3 _N, vec3 _V, float _NoV, float _NoL, float _roughness) { return DIFFUSE_FNC(_L, _N, _V, _NoV, _NoL, _roughness); } #endif <|start_filename|>lighting/common/schlick.glsl<|end_filename|> #include "../../math/pow5.glsl" #ifndef FNC_SCHLICK #define FNC_SCHLICK // Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering" vec3 schlick(const vec3 f0, float f90, float VoH) { float f = pow5(1.0 - VoH); return f + f0 * (f90 - f); } vec3 schlick(vec3 f0, vec3 f90, float VoH) { return f0 + (f90 - f0) * pow5(1.0 - VoH); } float schlick(float f0, float f90, float VoH) { return f0 + (f90 - f0) * pow5(1.0 - VoH); } #endif <|start_filename|>filter/gaussianBlur/1D_fast5.glsl<|end_filename|> /* author: <NAME> description: adapted versions of gaussian fast blur 13 from https://github.com/Jam3/glsl-fast-gaussian-blur use: gaussianBlur1D_fast5(<sampler2D> texture, <vec2> st, <vec2> pixel_direction) options: GAUSSIANBLUR1D_FAST5_TYPE GAUSSIANBLUR1D_FAST5_SAMPLER_FNC(POS_UV) license: | The MIT License (MIT) Copyright (c) 2015 Jam3 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GAUSSIANBLUR1D_FAST5_TYPE #ifdef GAUSSIANBLUR_TYPE #define GAUSSIANBLUR1D_FAST5_TYPE GAUSSIANBLUR_TYPE #else #define GAUSSIANBLUR1D_FAST5_TYPE vec4 #endif #endif #ifndef GAUSSIANBLUR1D_FAST5_SAMPLER_FNC #ifdef GAUSSIANBLUR_SAMPLER_FNC #define GAUSSIANBLUR1D_FAST5_SAMPLER_FNC(POS_UV) GAUSSIANBLUR_SAMPLER_FNC(POS_UV) #else #define GAUSSIANBLUR1D_FAST5_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #endif #ifndef FNC_GAUSSIANBLUR1D_FAST5 #define FNC_GAUSSIANBLUR1D_FAST5 GAUSSIANBLUR1D_FAST5_TYPE gaussianBlur1D_fast5(in sampler2D tex, in vec2 st, in vec2 offset) { GAUSSIANBLUR1D_FAST5_TYPE color = GAUSSIANBLUR1D_FAST5_TYPE(0.); vec2 off1 = vec2(1.3333333333333333) * offset; color += GAUSSIANBLUR1D_FAST5_SAMPLER_FNC(st) * .29411764705882354; color += GAUSSIANBLUR1D_FAST5_SAMPLER_FNC(st + (off1)) * .35294117647058826; color += GAUSSIANBLUR1D_FAST5_SAMPLER_FNC(st - (off1)) * .35294117647058826; return color; } #endif <|start_filename|>draw/stroke.glsl<|end_filename|> /* author: <NAME> description: fill a stroke in a SDF. From PixelSpiritDeck https://github.com/patriciogonzalezvivo/PixelSpiritDeck use: stroke(<float> sdf, <float> size, <float> width [, <float> edge]) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_STROKE #define FNC_STROKE #include "aastep.glsl" #include "../math/saturate.glsl" float stroke(float x, float size, float w) { float d = aastep(size, x + w * 0.5) - aastep(size, x - w * 0.5); return saturate(d); } float stroke(float x, float size, float w, float edge) { float d = smoothstep(size - edge, size + edge, x + w * 0.5) - smoothstep(size - edge, size + edge, x - w * 0.5); return saturate(d); } #endif <|start_filename|>sdf/heartSDF.glsl<|end_filename|> /* author: <NAME> description: Returns a heart shaped SDF use: heartSDF(<vec2> st) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_HEARTSDF #define FNC_HEARTSDF float heartSDF(vec2 st) { st -= vec2(0.5, 0.8); float r = length(st) * 5.0; st = normalize(st); return r - ((st.y * pow(abs(st.x), 0.67)) / (st.y + 1.5) - (2.0) * st.y + 1.26); } #endif <|start_filename|>lighting/toMetallic.glsl<|end_filename|> /* author: <NAME> description: convert diffuse/specular/glossiness workflow to PBR metallic factor use: <float> toMetallic(<vec3> diffuse, <vec3> specular, <float> maxSpecular) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TOMETALLIC_MIN_REFLECTANCE #define TOMETALLIC_MIN_REFLECTANCE 0.04 #endif #ifndef FNC_TOMETALLIC #define FNC_TOMETTALIC float toMetallic(vec3 diffuse, vec3 specular, float maxSpecular) { float perceivedDiffuse = sqrt(0.299 * diffuse.r * diffuse.r + 0.587 * diffuse.g * diffuse.g + 0.114 * diffuse.b * diffuse.b); float perceivedSpecular = sqrt(0.299 * specular.r * specular.r + 0.587 * specular.g * specular.g + 0.114 * specular.b * specular.b); if (perceivedSpecular < TOMETALLIC_MIN_REFLECTANCE) { return 0.0; } float a = TOMETALLIC_MIN_REFLECTANCE; float b = perceivedDiffuse * (1.0 - maxSpecular) / (1.0 - TOMETALLIC_MIN_REFLECTANCE) + perceivedSpecular - 2.0 * TOMETALLIC_MIN_REFLECTANCE; float c = TOMETALLIC_MIN_REFLECTANCE - perceivedSpecular; float D = max(b * b - 4.0 * a * c, 0.0); return clamp((-b + sqrt(D)) / (2.0 * a), 0.0, 1.0); } float toMetallic(vec3 diffuse, vec3 specular) { float maxSpecula = max(max(specular.r, specular.g), specular.b); return toMetallic(diffuse, specular, maxSpecula); } #endif <|start_filename|>animation/easing/back.glsl<|end_filename|> #include "../../math/const.glsl" /* author: <NAME> (https://github.com/hughsk) description: Back easing. From https://github.com/stackgl/glsl-easings use: back<In|Out|InOut>(<float> x) license: | This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_BACKIN #define FNC_BACKIN float backIn(in float t) { return pow(t, 3.) - t * sin(t * PI); } #endif #ifndef FNC_BACKOUT #define FNC_BACKOUT float backOut(in float t) { return 1. - backIn(1. - t); } #endif #ifndef FNC_BACKINOUT #define FNC_BACKINOUT float backInOut(in float t) { float f = t < .5 ? 2.0 * t : 1.0 - (2.0 * t - 1.0); float g = backIn(f); return t < 0.5 ? 0.5 * g : 0.5 * (1.0 - g) + 0.5; } #endif <|start_filename|>color/blend/reflect.glsl<|end_filename|> /* author: <NAME> description: Photoshop Reflect blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendReflect(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDREFLECT #define FNC_BLENDREFLECT float blendReflect(in float base, in float blend) { return (blend == 1.)? blend : min(base * base / (1. - blend), 1.); } vec3 blendReflect(in vec3 base, in vec3 blend) { return vec3(blendReflect(base.r, blend.r), blendReflect(base.g, blend.g), blendReflect(base.b, blend.b)); } vec3 blendReflect(in vec3 base, in vec3 blend, in float opacity) { return (blendReflect(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>sdf/flowerSDF.glsl<|end_filename|> /* author: <NAME> description: Returns a flower shaped SDF use: flowerSDF(<vec2> st, <int> n_sides) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_FLOWERSDF #define FNC_FLOWERSDF float flowerSDF(vec2 st, int N) { st = st * 2.0 - 1.0; float r = length(st) * 2.0; float a = atan(st.y, st.x); float v = float(N) * 0.5; return 1.0 - (abs(cos(a * v)) * 0.5 + 0.5) / r; } #endif <|start_filename|>lighting/light/directional.glsl<|end_filename|> #include "../specular.glsl" #include "../diffuse.glsl" #include "falloff.glsl" /* author: <NAME> description: calculate directional light use: lightDirectional(<vec3> _diffuseColor, <vec3> _specularColor, <vec3> _N, <vec3> _V, <float> _NoV, <float> _f0, out <vec3> _diffuse, out <vec3> _specular) options: - DIFFUSE_FNC: diffuseOrenNayar, diffuseBurley, diffuseLambert (default) - LIGHT_POSITION: in GlslViewer is u_light - LIGHT_COLOR: in GlslViewer is u_lightColor - LIGHT_INTENSITY: in GlslViewer is u_lightIntensity license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LIGHT_POSITION #if defined(GLSLVIEWER) #define LIGHT_POSITION u_light #else #define LIGHT_POSITION vec3(0.0, 10.0, -50.0) #endif #endif #ifndef LIGHT_COLOR #if defined(GLSLVIEWER) #define LIGHT_COLOR u_lightColor #else #define LIGHT_COLOR vec3(0.5) #endif #endif #ifndef LIGHT_INTENSITY #if defined(GLSLVIEWER) #define LIGHT_INTENSITY u_lightIntensity #else #define LIGHT_INTENSITY 1.0 #endif #endif #ifndef FNC_LIGHT_DIRECTIONAL #define FNC_LIGHT_DIRECTIONAL void lightDirectional(vec3 _diffuseColor, vec3 _specularColor, vec3 _N, vec3 _V, float _NoV, float _f0, out vec3 _diffuse, out vec3 _specular) { vec3 s = -LIGHT_POSITION; float NoL = dot(_N, s); float dif = diffuseOrenNayar(s, _N, _V, _NoV, NoL, _roughness); float spec = specularCookTorrance(s, _N, _V, _NoV, NoL, _roughness, _comp.f0); _diffuse = LIGHT_INTENSITY * (_diffuseColor * LIGHT_COLOR * dif); _specular = LIGHT_INTENSITY * (_specularColor * LIGHT_COLOR * spec); } #endif <|start_filename|>math/transpose.glsl<|end_filename|> /* author: <NAME> description: transpose matrixes use: <mat3|mat4> transpose(in <mat3|mat4> m) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_TRANSPOSE #define FNC_TRANSPOSE mat3 transpose(in mat3 m) { vec3 i0 = m[0]; vec3 i1 = m[1]; vec3 i2 = m[2]; return mat3( vec3(i0.x, i1.x, i2.x), vec3(i0.y, i1.y, i2.y), vec3(i0.z, i1.z, i2.z) ); } mat4 transpose(in mat4 m) { vec4 i0 = m[0]; vec4 i1 = m[1]; vec4 i2 = m[2]; vec4 i3 = m[3]; return mat4( vec4(i0.x, i1.x, i2.x, i3.x), vec4(i0.y, i1.y, i2.y, i3.y), vec4(i0.z, i1.z, i2.z, i3.z), vec4(i0.w, i1.w, i2.w, i3.w) ); } #endif <|start_filename|>lighting/material/new.glsl<|end_filename|> #include "baseColor.glsl" #include "specular.glsl" #include "emissive.glsl" #include "occlusion.glsl" #include "normal.glsl" #include "metallic.glsl" #include "roughness.glsl" #include "shininess.glsl" #include "../material.glsl" /* author: <NAME> description: Material Constructor. Designed to integrate with GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: - void materialNew(out material _mat) - material materialNew() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_NEW #define FNC_MATERIAL_NEW void materialNew(out Material _mat) { _mat.baseColor = materialBaseColor(); _mat.emissive = materialEmissive(); _mat.normal = materialNormal(); _mat.f0 = vec3(0.04); _mat.roughness = materialRoughness(); _mat.metallic = materialMetallic(); _mat.reflectance = 0.5; _mat.ambientOcclusion = materialOcclusion(); #if defined(MATERIAL_CLEARCOAT_THICKNESS) _mat.clearCoat = MATERIAL_CLEARCOAT_THICKNESS; _mat.clearCoatRoughness = MATERIAL_CLEARCOAT_ROUGHNESS; #if defined(MATERIAL_CLEARCOAT_THICKNESS_NORMAL) _mat.clearCoatNormal = vec3(0.0, 0.0, 1.0); #endif #endif #if defined(SHADING_MODEL_SUBSURFACE) _mat.thickness = 0.5; _mat.subsurfacePower = 12.234; #endif #if defined(MATERIAL_SUBSURFACE_COLOR) #if defined(SHADING_MODEL_SUBSURFACE) _mat.subsurfaceColor = vec3(1.0); #else _mat.subsurfaceColor = vec3(0.0); #endif #endif #if defined(SHADING_MODEL_CLOTH) _mat.sheenColor = sqrt(_mat.baseColor.rgb); #endif #if defined(SHADING_SHADOWS) _mat.shadow = 1.0; #endif } Material materialNew() { Material mat; materialNew(mat); return mat; } #endif <|start_filename|>sample/textureShadowPCF.glsl<|end_filename|> #include "textureShadowLerp.glsl" /* author: <NAME> description: sample shadow map using PCF use: - <float> textureShadowPCF(<sampler2D> depths, <vec2> size, <vec2> uv, <float> compare) - <float> textureShadowPCF(<vec3> lightcoord) options: - LIGHT_SHADOWMAP_BIAS license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LIGHT_SHADOWMAP_BIAS #define LIGHT_SHADOWMAP_BIAS 0.005 #endif #ifndef FNC_TEXTURESHADOWPCF #define FNC_TEXTURESHADOWPCF float textureShadowPCF(sampler2D depths, vec2 size, vec2 uv, float compare) { float result = 0.0; for(int x=-2; x<=2; x++){ for(int y=-2; y<=2; y++){ vec2 off = vec2(x,y)/size; // result += textureShadow(depths, uv+off, compare); result += textureShadowLerp(depths, size, uv+off, compare); } } return result/25.0; } float textureShadowPCF(vec3 lightcoord) { #if defined(LIGHT_SHADOWMAP) && defined(LIGHT_SHADOWMAP_SIZE) return textureShadowPCF(LIGHT_SHADOWMAP, vec2(LIGHT_SHADOWMAP_SIZE), lightcoord.xy, lightcoord.z - LIGHT_SHADOWMAP_BIAS); #else return 1.0; #endif } #endif <|start_filename|>color/luminance.glsl<|end_filename|> /* function: luminance description: Computes the luminance of the specified linear RGB color using the luminance coefficients from Rec. 709. use: luminance(<vec3|vec4> color) */ #ifndef FNC_LUMINANCE #define FNC_LUMINANCE float luminance(in vec3 linear) { return dot(linear, vec3(0.2126, 0.7152, 0.0722)); } float luminance(in vec4 linear) { return luminance( linear.rgb ); } #endif <|start_filename|>lighting/material/specular.glsl<|end_filename|> /* author: <NAME> description: get material specular property from GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: vec4 materialMetallic() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_SPECULAR #define FNC_MATERIAL_SPECULAR #ifdef MATERIAL_SPECULARMAP uniform sampler2D MATERIAL_SPECULARMAP; #endif vec3 materialSpecular() { vec3 spec = vec3(0.04); #if defined(MATERIAL_SPECULARMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; #if defined(MATERIAL_SPECULARMAP_OFFSET) uv += (MATERIAL_SPECULARMAP_OFFSET).xy; #endif #if defined(MATERIAL_SPECULARMAP_SCALE) uv *= (MATERIAL_SPECULARMAP_SCALE).xy; #endif spec = texture2D(MATERIAL_SPECULARMAP, uv).rgb; #elif defined(MATERIAL_SPECULAR) spec = MATERIAL_SPECULAR; #endif return spec; } #endif <|start_filename|>filter/median/2D_fast5.glsl<|end_filename|> /* author: [<NAME>, <NAME>] description: | 3x3 median filter, adapted from "A Fast, Small-Radius GPU Median Filter" by Morgan McGuire in ShaderX6 https://casual-effects.com/research/McGuire2008Median/index.html use: median2D_fast5(<sampler2D> texture, <vec2> st, <vec2> pixel) options: MEDIAN2D_FAST5_TYPE: default vec4 MEDIAN2D_FAST5_SAMPLER_FNC(POS_UV): default texture2D(tex, POS_UV) license: Copyright (c) <NAME> and Williams College, 2006. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MEDIAN2D_FAST5_TYPE #ifdef MEDIAN2D_TYPE #define MEDIAN2D_FAST5_TYPE MEDIAN2D_TYPE #else #define MEDIAN2D_FAST5_TYPE vec4 #endif #endif #ifndef MEDIAN2D_FAST5_SAMPLER_FNC #ifdef MEDIAN_SAMPLER_FNC #define MEDIAN2D_FAST5_SAMPLER_FNC(POS_UV) MEDIAN_SAMPLER_FNC(POS_UV) #else #define MEDIAN2D_FAST5_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #endif #ifndef MEDIAN_S2 #define MEDIAN_S2(a, b) temp = a; a = min(a, b); b = max(temp, b); #endif #ifndef MEDIAN_2 #define MEDIAN_2(a, b) MEDIAN_S2(v[a], v[b]); #endif #ifndef FNC_MEDIAN2D_FAST5 #define FNC_MEDIAN2D_FAST5 #define MEDIAN_S2(a, b) temp = a; a = min(a, b); b = max(temp, b); #define MEDIAN_2(a, b) MEDIAN_S2(v[a], v[b]); #define MEDIAN_24(a, b, c, d, e, f, g, h) MEDIAN_2(a, b); MEDIAN_2(c, d); MEDIAN_2(e, f); MEDIAN_2(g, h); #define MEDIAN_25(a, b, c, d, e, f, g, h, i, j) MEDIAN_24(a, b, c, d, e, f, g, h); MEDIAN_2(i, j); MEDIAN2D_FAST5_TYPE median2D_fast5(in sampler2D tex, in vec2 st, in vec2 radius) { MEDIAN2D_FAST5_TYPE v[25]; for (int dX = -2; dX <= 2; ++dX) { for (int dY = -2; dY <= 2; ++dY) { vec2 offset = vec2(float(dX), float(dY)); // If a pixel in the window is located at (x+dX, y+dY), put it at index (dX + R)(2R + 1) + (dY + R) of the // pixel array. This will fill the pixel array, with the top left pixel of the window at pixel[0] and the // bottom right pixel of the window at pixel[N-1]. v[(dX + 2) * 5 + (dY + 2)] = MEDIAN2D_FAST5_SAMPLER_FNC(st + offset * radius); } } MEDIAN2D_FAST5_TYPE temp = MEDIAN2D_FAST5_TYPE(0.); MEDIAN_25(0, 1, 3, 4, 2, 4, 2, 3, 6, 7); MEDIAN_25(5, 7, 5, 6, 9, 7, 1, 7, 1, 4); MEDIAN_25(12, 13, 11, 13, 11, 12, 15, 16, 14, 16); MEDIAN_25(14, 15, 18, 19, 17, 19, 17, 18, 21, 22); MEDIAN_25(20, 22, 20, 21, 23, 24, 2, 5, 3, 6); MEDIAN_25(0, 6, 0, 3, 4, 7, 1, 7, 1, 4); MEDIAN_25(11, 14, 8, 14, 8, 11, 12, 15, 9, 15); MEDIAN_25(9, 12, 13, 16, 10, 16, 10, 13, 20, 23); MEDIAN_25(17, 23, 17, 20, 21, 24, 18, 24, 18, 21); MEDIAN_25(19, 22, 8, 17, 9, 18, 0, 18, 0, 9); MEDIAN_25(10, 19, 1, 19, 1, 10, 11, 20, 2, 20); MEDIAN_25(2, 11, 12, 21, 3, 21, 3, 12, 13, 22); MEDIAN_25(4, 22, 4, 13, 14, 23, 5, 23, 5, 14); MEDIAN_25(15, 24, 6, 24, 6, 15, 7, 16, 7, 19); MEDIAN_25(3, 11, 5, 17, 11, 17, 9, 17, 4, 10); MEDIAN_25(6, 12, 7, 14, 4, 6, 4, 7, 12, 14); MEDIAN_25(10, 14, 6, 7, 10, 12, 6, 10, 6, 17); MEDIAN_25(12, 17, 7, 17, 7, 10, 12, 18, 7, 12); MEDIAN_24(10, 18, 12, 20, 10, 20, 10, 12); return v[12]; } #endif <|start_filename|>lighting/specular/cookTorrance.glsl<|end_filename|> #include "../common/beckmann.glsl" #include "../../math/powFast.glsl" #ifndef SPECULAR_POW #if defined(TARGET_MOBILE) || defined(PLATFORM_RPI) || defined(PLATFORM_WEBGL) #define SPECULAR_POW(A,B) powFast(A,B) #else #define SPECULAR_POW(A,B) pow(A,B) #endif #endif #ifndef FNC_SPECULAR_COOKTORRANCE #define FNC_SPECULAR_COOKTORRANCE // https://github.com/stackgl/glsl-specular-cook-torrance float specularCookTorrance(vec3 _L, vec3 _N, vec3 _V, float _NoV, float _NoL, float _roughness, float _fresnel) { float NoV = max(_NoV, 0.0); float NoL = max(_NoL, 0.0); //Half angle vector vec3 H = normalize(_L + _V); //Geometric term float NoH = max(dot(_N, H), 0.0); float VoH = max(dot(_V, H), 0.000001); float LoH = max(dot(_L, H), 0.000001); float x = 2.0 * NoH / VoH; float G = min(1.0, min(x * NoV, x * NoL)); //Distribution term float D = beckmann(NoH, _roughness); //Fresnel term float F = SPECULAR_POW(1.0 - NoV, _fresnel); //Multiply terms and done return G * F * D / max(3.14159265 * NoV * NoL, 0.000001); } // https://github.com/glslify/glsl-specular-cook-torrance float specularCookTorrance(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { float NoV = max(dot(N, V), 0.0); float NoL = max(dot(N, L), 0.0); return specularCookTorrance(L, N, V, NoV, NoL, roughness, fresnel); } float specularCookTorrance(vec3 L, vec3 N, vec3 V, float roughness) { return specularCookTorrance(L, N, V, roughness, 0.04); } #endif <|start_filename|>math/mod289.glsl<|end_filename|> /* author: [<NAME>, <NAME>] description: modulus of 289 use: mod289(<float|vec2|vec3|vec4> x) license: | Copyright (C) 2011 <NAME>. All rights reserved. Distributed under the MIT License. See LICENSE file. https://github.com/ashima/webgl-noise */ #ifndef FNC_MOD289 #define FNC_MOD289 float mod289(in float x) { return x - floor(x * (1. / 289.)) * 289.; } vec2 mod289(in vec2 x) { return x - floor(x * (1. / 289.)) * 289.; } vec3 mod289(in vec3 x) { return x - floor(x * (1. / 289.)) * 289.; } vec4 mod289(in vec4 x) { return x - floor(x * (1. / 289.)) * 289.; } #endif <|start_filename|>distort/chromaAB.glsl<|end_filename|> #include "../math/lengthSq.glsl" /* author: <NAME>, <NAME> description: Chroma Aberration inspired by https://www.shadertoy.com/view/4sX3z4 use: chromaAB(<sampler2D> texture, <vec2> st [, <float|vec2> sdf|offset, <float> pct]) options: CHROMAAB_TYPE: return type, defauls to vec3 CHROMAAB_PCT: amount of aberration, defaults to 1.5 CHROMAAB_SAMPLER_FNC: function used to sample the input texture, defaults to texture2D(tex, POS_UV) CHROMAAB_CENTER_BUFFER: scalar to attenuate the sdf passed in license: | Copyright (c) 2021 <NAME> and <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CHROMAAB_PCT #define CHROMAAB_PCT 1.5 #endif #ifndef CHROMAAB_TYPE #define CHROMAAB_TYPE vec3 #endif #ifndef CHROMAAB_SAMPLER_FNC #define CHROMAAB_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #ifndef FNC_CHROMAAB #define FNC_CHROMAAB CHROMAAB_TYPE chromaAB(in sampler2D tex, in vec2 st, in vec2 direction, in vec3 distortion ) { vec2 offset = vec2(0.0); CHROMAAB_TYPE c = CHROMAAB_TYPE(1.); c.r = CHROMAAB_SAMPLER_FNC(st + direction * distortion.r).r; c.g = CHROMAAB_SAMPLER_FNC(st + direction * distortion.g).g; c.b = CHROMAAB_SAMPLER_FNC(st + direction * distortion.b).b; return c; } CHROMAAB_TYPE chromaAB(in sampler2D tex, in vec2 st, in vec2 offset, in float pct) { #ifdef CHROMAAB_CENTER_BUFFER // modify the distance from the center, so that only the edges are affected offset = max(offset - CHROMAAB_CENTER_BUFFER, 0.); #endif // Distort the UVs vec2 stR = st * (1.0 + offset * 0.02 * pct), stB = st * (1.0 - offset * 0.02 * pct); // Get the individual channels using the modified UVs CHROMAAB_TYPE c = CHROMAAB_TYPE(1.); c.r = CHROMAAB_SAMPLER_FNC(stR).r; c.g = CHROMAAB_SAMPLER_FNC(st).g; c.b = CHROMAAB_SAMPLER_FNC(stB).b; return c; } CHROMAAB_TYPE chromaAB(in sampler2D tex, in vec2 st, in float sdf, in float pct) { return chromaAB(tex, st, vec2(sdf), pct); } CHROMAAB_TYPE chromaAB(in sampler2D tex, in vec2 st, in float sdf) { return chromaAB(tex, st, sdf, CHROMAAB_PCT); } CHROMAAB_TYPE chromaAB(in sampler2D tex, in vec2 st, in vec2 offset) { return chromaAB(tex, st, offset, CHROMAAB_PCT); } CHROMAAB_TYPE chromaAB(in sampler2D tex, in vec2 st) { return chromaAB(tex, st, lengthSq(st - .5), CHROMAAB_PCT); } #endif <|start_filename|>lighting/diffuse/lambert.glsl<|end_filename|> /* author: <NAME> description: calculate diffuse contribution using lambert equation use: - <float> diffuseLambert(<vec3> light, <vec3> normal [, <vec3> view, <float> roughness] ) - <float> diffuseLambert(<vec3> L, <vec3> N, <vec3> V, <float> NoV, <float> NoL, <float> roughness) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_DIFFUSE_LAMBERT #define FNC_DIFFUSE_LAMBERT float diffuseLambert(vec3 L, vec3 N) { return max(0.0, dot(N, L)); } float diffuseLambert(vec3 L, vec3 N, vec3 V, float roughness) { return diffuseLambert(L, N); } float diffuseLambert(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness) { return diffuseLambert(L, N); } #endif <|start_filename|>lighting/material.glsl<|end_filename|> /* author: <NAME> description: Generic Material Structure license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef STR_MATERIAL #define STR_MATERIAL struct Material { vec4 baseColor; vec3 emissive; vec3 normal; vec3 f0;// = vec3(0.04); float reflectance;// = 0.5; float roughness; float metallic; float ambientOcclusion; #if defined(MATERIAL_CLEARCOAT_THICKNESS) float clearCoat; float clearCoatRoughness; #if defined(MATERIAL_CLEARCOAT_THICKNESS_NORMAL) vec3 clearCoatNormal;// = vec3(0.0, 0.0, 1.0); #endif #endif #if defined(SHADING_MODEL_SUBSURFACE) float thickness; // = 0.5; float subsurfacePower; // = 12.234; #endif #if defined(SHADING_MODEL_CLOTH) vec3 sheenColor; #endif #if defined(MATERIAL_SUBSURFACE_COLOR) vec3 subsurfaceColor; // = vec3(1.0); #endif #if defined(SHADING_MODEL_SPECULAR_GLOSSINESS) vec3 specularColor; float glossiness; #endif #if defined(SHADING_SHADOWS) float shadows;// = 1.0; #endif }; #endif <|start_filename|>math/rotate3d.glsl<|end_filename|> /* author: <NAME> description: returns a 4x4 rotation matrix use: rotate4d(<vec3> axis, <float> radians) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_ROTATE3D #define FNC_ROTATE3D mat3 rotate3d(in vec3 axis, in float radians) { axis = normalize(axis); float s = sin(radians); float c = cos(radians); float oc = 1.0 - c; return mat3(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c ); } #endif <|start_filename|>space/scale.glsl<|end_filename|> /* author: <NAME> description: scale a 2D space variable use: scale(<vec2> st, <vec2|float> scale_factor [, <vec2> center]) options: - CENTER - CENTER_2D - CENTER_3D license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_SCALE #define FNC_SCALE float scale(in float st, in float s, in float center) { return (st - center) * s + center; } float scale(in float st, in float s) { #ifdef CENTER_2D return scale(st, s, CENTER); #else return scale(st, s, .5); #endif } vec2 scale(in vec2 st, in vec2 s, in vec2 center) { return (st - center) * s + center; } vec2 scale(in vec2 st, in float value, in vec2 center) { return scale(st, vec2(value), center); } vec2 scale(in vec2 st, in vec2 s) { #ifdef CENTER_2D return scale(st, s, CENTER_2D); #else return scale(st, s, vec2(.5)); #endif } vec2 scale(in vec2 st, in float value) { return scale(st, vec2(value)); } vec3 scale(in vec3 st, in vec3 s, in vec3 center) { return (st - center) * s + center; } vec3 scale(in vec3 st, in float value, in vec3 center) { return scale(st, vec3(value), center); } vec3 scale(in vec3 st, in vec3 s) { #ifdef CENTER_3D return scale(st, s, CENTER_3D); #else return scale(st, s, vec3(.5)); #endif } vec3 scale(in vec3 st, in float value) { return scale(st, vec3(value)); } #endif <|start_filename|>sdf/triSDF.glsl<|end_filename|> /* author: <NAME> description: Returns a triangle-shaped sdf use: triSDF(<vec2> st) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_TRISDF #define FNC_TRISDF float triSDF(in vec2 st) { st = (st * 2. - 1.) * 2.; return max(abs(st.x) * .866025 + st.y * .5, -st.y * .5); } #endif <|start_filename|>math/taylorInvSqrt.glsl<|end_filename|> /* author: [<NAME>, <NAME>] description: use: taylorInvSqrt(<float|vec4> x) License : | Copyright (C) 2011 <NAME>. All rights reserved. Distributed under the MIT License. See LICENSE file. https://github.com/ashima/webgl-noise */ #ifndef FNC_TAYLORINVSQRT #define FNC_TAYLORINVSQRT float taylorInvSqrt(in float r) { return 1.79284291400159 - 0.85373472095314 * r; } vec4 taylorInvSqrt(in vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; } #endif <|start_filename|>lighting/specular/ward.glsl<|end_filename|> #ifndef FNC_SPECULAR_WARD #define FNC_SPECULAR_WARD // https://github.com/glslify/glsl-specular-ward float specularWard(vec3 L, vec3 N, vec3 V, vec3 fiber, float shinyParallel, float shinyPerpendicular) { float NdotL = dot(N, L); float NdotR = dot(N, V); vec3 fiberParallel = normalize(fiber); vec3 fiberPerpendicular = normalize(cross(N, fiber)); if (NdotL < 0.0 || NdotR < 0.0) return 0.0; vec3 H = normalize(L + V); float NdotH = dot(N, H); float XdotH = dot(fiberParallel, H); float YdotH = dot(fiberPerpendicular, H); float coeff = sqrt(NdotL/NdotR) / (12.5663706144 * shinyParallel * shinyPerpendicular); float theta = (pow(XdotH/shinyParallel, 2.0) + pow(YdotH/shinyPerpendicular, 2.0)) / (1.0 + NdotH); return coeff * exp(-2.0 * theta); } #endif <|start_filename|>lighting/common/charlie.glsl<|end_filename|> #include "../../math/const.glsl" #ifndef FNC_CHARLIE #define FNC_CHARLIE float charlie(float NoH, float roughness) { // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF" float invAlpha = 1.0 / roughness; float cos2h = NoH * NoH; float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16 return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / TAU; } #endif <|start_filename|>lighting/common/reflection.glsl<|end_filename|> #include "../../math/saturate.glsl" #ifndef FNC_REFLECTION #define FNC_REFLECTION vec3 reflection(vec3 _V, vec3 _N, float _roughness) { // Reflect #ifdef MATERIAL_ANISOTROPY vec3 anisotropicT = MATERIAL_ANISOTROPY_DIRECTION; vec3 anisotropicB = MATERIAL_ANISOTROPY_DIRECTION; #ifdef MODERL_VERTEX_TANGENT anisotropicT = normalize(v_tangentToWorld * MATE RIAL_ANISOTROPY_DIRECTION); anisotropicB = normalize(cross(v_tangentToWorld[2], anisotropicT)); #endif vec3 anisotropyDirection = MATERIAL_ANISOTROPY >= 0.0 ? anisotropicB : anisotropicT; vec3 anisotropicTangent = cross(anisotropyDirection, _V); vec3 anisotropicNormal = cross(anisotropicTangent, anisotropyDirection); float bendFactor = abs(MATERIAL_ANISOTROPY) * saturate(5.0 * _roughness); vec3 bentNormal = normalize(mix(_N, anisotropicNormal, bendFactor)); return reflect(-_V, bentNormal); #else return reflect(-_V, _N); #endif } #endif <|start_filename|>filter/boxBlur.glsl<|end_filename|> /* author: <NAME> description: given a texture return a simple box blured pixel use: boxBlur(<sampler2D> texture, <vec2> st, <vec2> pixel_offset) options: BOXBLUR_2D: default to 1D BOXBLUR_ITERATIONS: default 3 license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BOXBLUR_ITERATIONS #define BOXBLUR_ITERATIONS 3 #endif #ifndef BOXBLUR_TYPE #define BOXBLUR_TYPE vec4 #endif #ifndef BOXBLUR_SAMPLER_FNC #define BOXBLUR_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #include "boxBlur/1D.glsl" #include "boxBlur/2D.glsl" #include "boxBlur/2D_fast9.glsl" #ifndef FNC_BOXBLUR #define FNC_BOXBLUR BOXBLUR_TYPE boxBlur13(in sampler2D tex, in vec2 st, in vec2 offset) { #ifdef BOXBLUR_2D return boxBlur2D(tex, st, offset, 7); #else return boxBlur1D(tex, st, offset, 7); #endif } BOXBLUR_TYPE boxBlur9(in sampler2D tex, in vec2 st, in vec2 offset) { #ifdef BOXBLUR_2D return boxBlur2D_fast9(tex, st, offset); #else return boxBlur1D(tex, st, offset, 5); #endif } BOXBLUR_TYPE boxBlur5(in sampler2D tex, in vec2 st, in vec2 offset) { #ifdef BOXBLUR_2D return boxBlur2D(tex, st, offset, 3); #else return boxBlur1D(tex, st, offset, 3); #endif } vec4 boxBlur(in sampler2D tex, in vec2 st, vec2 offset, const int kernelSize) { #ifdef BOXBLUR_2D return boxBlur2D(tex, st, offset, kernelSize); #else return boxBlur1D(tex, st, offset, kernelSize); #endif } vec4 boxBlur(in sampler2D tex, in vec2 st, vec2 offset) { #ifdef BOXBLUR_2D return boxBlur2D(tex, st, offset, BOXBLUR_ITERATIONS); #else return boxBlur1D(tex, st, offset, BOXBLUR_ITERATIONS); #endif } #endif <|start_filename|>color/tonemap/unreal.glsl<|end_filename|> /* Author: Unreal Engine 4.0 description: Adapted to be close to TonemapACES, with similar range. Gamma 2.2 correction is baked in, don't use with sRGB conversion! https://docs.unrealengine.com/4.26/en-US/RenderingAndGraphics/PostProcessEffects/ColorGrading/ use: <vec3|vec4> tonemapUnreal(<vec3|vec4> x) */ #ifndef FNC_TONEMAPUNREAL #define FNC_TONEMAPUNREAL vec3 tonemapUnreal(const vec3 x) { return x / (x + 0.155) * 1.019; } vec4 tonemapUnreal(const vec4 x) { return vec4(tonemapUnreal(x.rgb), x.a); } #endif <|start_filename|>lighting/material/roughness.glsl<|end_filename|> /* author: <NAME> description: get material roughness property from GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: vec4 materialRoughness() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_ROUGHNESS #define FNC_MATERIAL_ROUGHNESS #ifdef MATERIAL_ROUGHNESSMAP uniform sampler2D MATERIAL_ROUGHNESSMAP; #endif #if defined(MATERIAL_ROUGHNESSMETALLICMAP) && !defined(MATERIAL_ROUGHNESSMETALLICMAP_UNIFORM) #define MATERIAL_ROUGHNESSMETALLICMAP_UNIFORM uniform sampler2D MATERIAL_ROUGHNESSMETALLICMAP; #endif #if defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP) && !defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP_UNIFORM) #define MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP_UNIFORM uniform sampler2D MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP; #endif float materialRoughness() { float roughness = 0.1; #if defined(MATERIAL_ROUGHNESSMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; #if defined(MATERIAL_ROUGHNESSMAP_OFFSET) uv += (MATERIAL_ROUGHNESSMAP_OFFSET).xy; #endif #if defined(MATERIAL_ROUGHNESSMAP_SCALE) uv *= (MATERIAL_ROUGHNESSMAP_SCALE).xy; #endif roughness = texture2D(MATERIAL_ROUGHNESSMAP, uv).g; #elif defined(MATERIAL_ROUGHNESSMETALLICMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; roughness = texture2D(MATERIAL_ROUGHNESSMETALLICMAP, uv).g; #elif defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; roughness = texture2D(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP, uv).g; #elif defined(MATERIAL_ROUGHNESS) roughness = MATERIAL_ROUGHNESS; #endif return roughness; } #endif <|start_filename|>color/blend/vividLight.glsl<|end_filename|> #include "colorBurn.glsl" #include "colorDodge.glsl" /* author: <NAME> description: Photoshop Vivid Light blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendVividLight(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDVIVIDLIGHT #define FNC_BLENDVIVIDLIGHT float blendVividLight(in float base, in float blend) { return (blend < .5)? blendColorBurn(base, (2.*blend)): blendColorDodge(base, (2. * (blend - .5))); } vec3 blendVividLight(in vec3 base, in vec3 blend) { return vec3(blendVividLight(base.r, blend.r), blendVividLight(base.g, blend.g), blendVividLight(base.b, blend.b)); } vec3 blendVividLight(in vec3 base, in vec3 blend, in float opacity) { return (blendVividLight(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/specular/ggx.glsl<|end_filename|> #include "../common/ggx.glsl" #include "../common/smithGGXCorrelated.glsl" #include "../../math/saturate.glsl" #include "../fresnel.glsl" #ifndef FNC_SPECULAR_GGX #define FNC_SPECULAR_GGX float specularGGX(vec3 _L, vec3 _N, vec3 _V, float _NoV, float _NoL, float _roughness, float _fresnel) { float NoV = max(_NoV, 0.0); float NoL = max(_NoL, 0.0); vec3 H = normalize(_L + _V); float LoH = saturate(dot(_L, H)); float NoH = saturate(dot(_N, H)); // float NoV, float NoL, float roughness float linearRoughness = _roughness * _roughness; float D = GGX(NoH, linearRoughness); float V = smithGGXCorrelated(_NoV, NoL,linearRoughness); float F = fresnel(vec3(_fresnel), LoH).r; return (D * V) * F; } float specularGGX(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { float NoV = max(dot(N, V), 0.0); float NoL = max(dot(N, L), 0.0); return specularGGX(L, N, V, NoV, NoL, roughness, fresnel); } float specularGGX(vec3 L, vec3 N, vec3 V, float roughness) { return specularGGX(L, N, V, roughness, 0.04); } #endif <|start_filename|>lighting/iridescence.glsl<|end_filename|> #include "../color/palette/hue.glsl" /* author: Paniq (https://www.shadertoy.com/view/Ms33zj) description: based on the picture in http://home.hiroshima-u.ac.jp/kin/publications/TVC01/examples.pdf use: <vec3> iridescence(<float> angle, <float> thickness) license: NONE */ #ifndef FNC_IRIDESCENCE #define FNC_IRIDESCENCE vec3 iridescence(float angle, float thickness) { // typically the dot product of normal with eye ray float NxV = cos(angle); // energy of spectral colors float lum = 0.05064; // basic energy of light float luma = 0.01070; // tint of the final color //vec3 tint = vec3(0.7333,0.89804,0.94902); vec3 tint = vec3(0.49639,0.78252,0.88723); // interference rate at minimum angle float interf0 = 2.4; // phase shift rate at minimum angle float phase0 = 1.0 / 2.8; // interference rate at maximum angle float interf1 = interf0 * 4.0 / 3.0; // phase shift rate at maximum angle float phase1 = phase0; // fresnel (most likely completely wrong) float f = (1.0 - NxV) * (1.0 - NxV); float interf = mix(interf0, interf1, f); float phase = mix(phase0, phase1, f); float dp = (NxV - 1.0) * 0.5; // film hue vec3 hue = // fade in higher frequency at the right end mix( hue(thickness * interf0 + dp, thickness * phase0), hue(thickness * interf1 + 0.1 + dp, thickness * phase1), f); vec3 film = hue * lum + vec3(0.49639,0.78252,0.88723) * luma; return vec3((film * 3.0 + pow(f, 12.0))) * tint; } #endif <|start_filename|>color/tonemap/reinhard.glsl<|end_filename|> #include "../luminance.glsl" /* Author: [<NAME>, <NAME>, <NAME>, <NAME>] description: Photographic Tone Reproduction for Digital Images. http://www.cmap.polytechnique.fr/~peyre/cours/x2005signal/hdr_photographic.pdf use: <vec3|vec4> tonemapReinhard(<vec3|vec4> x) */ #ifndef FNC_TONEMAPREINHARD #define FNC_TONEMAPREINHARD vec3 tonemapReinhard(const vec3 x) { return x / (1.0 + luminance(x)); } vec4 tonemapReinhard(const vec4 x) { return vec4( tonemapReinhard(x.rgb), x.a ); } #endif <|start_filename|>sample/textureDoF.glsl<|end_filename|> #include "../color/palette/heatmap.glsl" /* author: <NAME> description: http://blog.tuxedolabs.com/2018/05/04/bokeh-depth-of-field-in-single-pass.html use: textureDoF(<sampler2D> texture, <sampler2D> depth, <vec2> st, <float> focusPoint, <float> focusScale) options: TEXTUREDOF_TYPE: TEXTUREDOF_BLUR_SIZE: TEXTUREDOF_RAD_SCALE: TEXTUREDOF_DEPTH_FNC(UV): TEXTUREDOF_COLOR_FNC(UV): */ #ifndef FNC_TEXTUREDOF #define FNC_TEXTUREDOF #ifndef TEXTUREDOF_BLUR_SIZE #define TEXTUREDOF_BLUR_SIZE 6. #endif // Smaller = nicer blur, larger = faster #ifndef TEXTUREDOF_RAD_SCALE #define TEXTUREDOF_RAD_SCALE .5 #endif #ifndef GOLDEN_ANGLE #define GOLDEN_ANGLE 2.39996323 #endif #ifndef TEXTUREDOF_DEPTH_FNC #define TEXTUREDOF_DEPTH_FNC(UV)texture2D(texDepth,UV).r #endif #ifndef TEXTUREDOF_COLOR_FNC #define TEXTUREDOF_COLOR_FNC(UV)texture2D(tex,UV).rgb #endif #ifndef TEXTUREDOF_TYPE #define TEXTUREDOF_TYPE vec3 #endif float getBlurSize(float depth,float focusPoint,float focusScale){ float coc = clamp((1./focusPoint-1./depth)*focusScale,-1.,1.); return abs(coc) * TEXTUREDOF_BLUR_SIZE; } #ifdef PLATFORM_WEBGL TEXTUREDOF_TYPE textureDoF(sampler2D tex,sampler2D texDepth,vec2 texCoord,float focusPoint,float focusScale){ float pct=0.; float centerDepth = TEXTUREDOF_DEPTH_FNC(texCoord); float centerSize = getBlurSize(centerDepth, focusPoint, focusScale); vec2 pixelSize = 1.0/u_resolution.xy; TEXTUREDOF_TYPE color = TEXTUREDOF_COLOR_FNC(texCoord); float total = 1.0; float radius = TEXTUREDOF_RAD_SCALE; for (float angle = 0.0 ; angle < 60.; angle += GOLDEN_ANGLE){ if (radius >= TEXTUREDOF_BLUR_SIZE) break; vec2 tc = texCoord + vec2(cos(angle), sin(angle)) * pixelSize * radius; float sampleDepth = TEXTUREDOF_DEPTH_FNC(tc); float sampleSize = getBlurSize(sampleDepth, focusPoint, focusScale); if (sampleDepth > centerDepth) sampleSize=clamp(sampleSize, 0.0, centerSize*2.0); pct = smoothstep(radius-0.5, radius+0.5, sampleSize); TEXTUREDOF_TYPE sampleColor = TEXTUREDOF_COLOR_FNC(tc); #ifdef TEXTUREDOF_DEBUG sampleColor.rgb = heatmap(pct*0.5+(angle/TEXTUREDOF_BLUR_SIZE)*0.1); #endif color += mix(color/total, sampleColor, pct); total += 1.0; radius += TEXTUREDOF_RAD_SCALE/radius; } return color/=total; } #else TEXTUREDOF_TYPE textureDoF(sampler2D tex, sampler2D texDepth, vec2 texCoord, float focusPoint, float focusScale) { float pct = 0.0; float ang = 0.0; float centerDepth = TEXTUREDOF_DEPTH_FNC(texCoord); float centerSize = getBlurSize(centerDepth, focusPoint, focusScale); vec2 pixelSize = 1./u_resolution.xy; TEXTUREDOF_TYPE color = TEXTUREDOF_COLOR_FNC(texCoord); float tot = 1.0; float radius = TEXTUREDOF_RAD_SCALE; for (ang = 0.0; radius < TEXTUREDOF_BLUR_SIZE; ang += GOLDEN_ANGLE) { vec2 tc = texCoord + vec2(cos(ang), sin(ang)) * pixelSize * radius; float sampleDepth = TEXTUREDOF_DEPTH_FNC(tc); float sampleSize = getBlurSize(sampleDepth, focusPoint, focusScale); if (sampleDepth > centerDepth) sampleSize = clamp(sampleSize, 0.0, centerSize*2.0); pct = smoothstep(radius-0.5, radius+0.5, sampleSize); TEXTUREDOF_TYPE sampleColor = TEXTUREDOF_COLOR_FNC(tc); #ifdef TEXTUREDOF_DEBUG sampleColor.rgb = heatmap(pct * 0.5 + (ang/TEXTUREDOF_BLUR_SIZE) * 0.1); #endif color += mix(color/tot, sampleColor, pct); tot += 1.0; radius += TEXTUREDOF_RAD_SCALE/radius; } return color /= tot; } #endif #endif <|start_filename|>filter/median.glsl<|end_filename|> /* author:[<NAME>, <NAME>] description: 3x3 and 5x5 median filter, adapted from "A Fast, Small-Radius GPU Median Filter" by Morgan McGuire in ShaderX6 https://casual-effects.com/research/McGuire2008Median/index.html use: median(<sampler2D> texture, <vec2> st, <vec2> pixel) options: MEDIAN_AMOUNT: median3 (3x3) median5 (5x5) MEDIAN_TYPE: default vec4 MEDIAN_SAMPLER_FNC(POS_UV): default texture2D(tex, POS_UV) license: Copyright (c) <NAME> and Williams College, 2006. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MEDIAN_AMOUNT #define MEDIAN_AMOUNT median5 #endif #ifndef MEDIAN_TYPE #define MEDIAN_TYPE vec4 #endif #ifndef MEDIAN_SAMPLER_FNC #define MEDIAN_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #include "median/2D_fast3.glsl" #include "median/2D_fast5.glsl" #ifndef FNC_MEDIAN #define FNC_MEDIAN MEDIAN_TYPE median3(in sampler2D tex, in vec2 st, in vec2 radius) { return median2D_fast3(tex, st, radius); } MEDIAN_TYPE median5(in sampler2D tex, in vec2 st, in vec2 radius) { return median2D_fast5(tex, st, radius); } MEDIAN_TYPE median(in sampler2D tex, in vec2 st, in vec2 radius) { return MEDIAN_AMOUNT(tex, st, radius); } #endif <|start_filename|>color/blend/add.glsl<|end_filename|> /* author: <NAME> description: Photoshop Add blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendAdd(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDADD #define FNC_BLENDADD float blendAdd(in float base, in float blend) { return min(base + blend, 1.); } vec3 blendAdd(in vec3 base, in vec3 blend) { return min(base + blend, vec3(1.)); } vec3 blendAdd(in vec3 base, in vec3 blend, float opacity) { return (blendAdd(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/common/specularAO.glsl<|end_filename|> #if !defined(TARGET_MOBILE) && !defined(PLATFORM_RPI) && !defined(PLATFORM_WEBGL) #define IBL_SPECULAR_OCCLUSION #endif #ifndef FNC_SPECULARAO #define FNC_SPECULARAO float specularAO(float NoV, float ao, float roughness) { #if !defined(TARGET_MOBILE) && !defined(PLATFORM_RPI) && !defined(PLATFORM_WEBGL) return saturate(pow(NoV + ao, exp2(-16.0 * roughness - 1.0)) - 1.0 + ao); #else return 1.0; #endif } #endif <|start_filename|>color/blend.glsl<|end_filename|> #include "blend/add.glsl" #include "blend/average.glsl" #include "blend/colorDodge.glsl" #include "blend/difference.glsl" #include "blend/glow.glsl" #include "blend/hardMix.glsl" #include "blend/linearBurn.glsl" #include "blend/linearLight.glsl" #include "blend/negation.glsl" #include "blend/phoenix.glsl" #include "blend/reflect.glsl" #include "blend/softLight.glsl" #include "blend/vividLight.glsl" #include "blend/colorBurn.glsl" #include "blend/darken.glsl" #include "blend/exclusion.glsl" #include "blend/hardLight.glsl" #include "blend/lighten.glsl" #include "blend/linearDodge.glsl" #include "blend/multiply.glsl" #include "blend/overlay.glsl" #include "blend/pinLight.glsl" #include "blend/screen.glsl" #include "blend/subtract.glsl" <|start_filename|>space/nearest.glsl<|end_filename|> /* function: nearest author: <NAME> description: sampling function to make a texture behave like GL_NEAREST use: nearest(vec2 st, <vec2> resolution) */ #ifndef FNC_NEAREST #define FNC_NEAREST vec2 nearest(in vec2 st, in vec2 resolution) { vec2 offset = .5 / (resolution - 1.); return floor(st * resolution) / resolution + offset; } #endif <|start_filename|>distort/grain.glsl<|end_filename|> #include "../generative/snoise.glsl" #include "../generative/pnoise.glsl" #include "../color/luma.glsl" #include "../color/blend/softLight.glsl" /* author: <NAME> description: Natural looking film grain using 3D noise functions (original source: https://github.com/mattdesl/glsl-film-grain). Inspired by [<NAME>](http://devlog-martinsh.blogspot.com/2013/05/image-imperfections-and-film-grain-post.html). use: - grain(<vec2> texCoord, <vec2> resolution [, <float> t, <float> multiplier]) - grain(<sampler2D> texture, <vec2> texCoord, <float|vec2> resolution [, <float> t, <float> multiplier]) license: | The MIT License (MIT) Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GRAIN_TYPE #define GRAIN_TYPE vec3 #endif #ifndef GRAIN_SAMPLER_FNC #define GRAIN_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).rgb #endif #ifndef FNC_GRAIN #define FNC_GRAIN float grain(vec2 texCoord, vec2 resolution, float t, float multiplier) { vec2 mult = texCoord * resolution; float offset = snoise(vec3(mult / multiplier, t)); float n1 = pnoise(vec3(mult, offset), vec3(1. / texCoord * resolution, 1.)); return n1 / 2. + .5; } float grain(vec2 texCoord, vec2 resolution, float t) { return grain(texCoord, resolution, t, 2.5); } float grain(vec2 texCoord, vec2 resolution) { return grain(texCoord, resolution, 0.); } GRAIN_TYPE grain(sampler2D tex, vec2 st, vec2 resolution, float t, float multiplier ) { GRAIN_TYPE org = GRAIN_SAMPLER_FNC(st); float g = grain(st, resolution, t, multiplier); //get the luminance of the background float luminance = luma(org); //reduce the noise based on some //threshold of the background luminance float response = smoothstep(0.05, 0.5, luminance); return mix( blendSoftLight(org, GRAIN_TYPE(g)), org, response * response); } GRAIN_TYPE grain(sampler2D tex, vec2 st, vec2 resolution, float t ) { return grain(tex, st, resolution, t, 2.5 ); } GRAIN_TYPE grain(sampler2D tex, vec2 st, vec2 resolution) { return grain(tex, st, resolution, 0.); } GRAIN_TYPE grain(sampler2D tex, vec2 st, float resolution, float t, float multiplier ) { return grain(tex, st, vec2(resolution), t, multiplier ); } GRAIN_TYPE grain(sampler2D tex, vec2 st, float resolution, float t ) { return grain(tex, st, resolution, t, 2.5 ); } GRAIN_TYPE grain(sampler2D tex, vec2 st, float resolution) { return grain(tex, st, resolution, 0.); } #endif <|start_filename|>draw/aastep.glsl<|end_filename|> /* author: <NAME> description: Performs a smoothstep using standard derivatives for anti-aliased edges at any level of magnification. From https://github.com/glslify/glsl-aastep use: aastep(<float> threshold, <float> value) option: AA_EDGE: in the absence of derivatives you can specify the antialiasing factor license: | The MIT License (MIT) Copyright (c) 2015 stackgl Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_AASTEP #define FNC_AASTEP #ifdef GL_OES_standard_derivatives #extension GL_OES_standard_derivatives : enable #endif float aastep(float threshold, float value) { #ifdef GL_OES_standard_derivatives float afwidth = 0.7 * length(vec2(dFdx(value), dFdy(value))); return smoothstep(threshold-afwidth, threshold+afwidth, value); #elif defined(AA_EDGE) float afwidth = AA_EDGE; return smoothstep(threshold-afwidth, threshold+afwidth, value); #else return step(threshold, value); #endif } #endif <|start_filename|>sample/textureQuilt.glsl<|end_filename|> /* author: <NAME> description: convertes QUILT of tiles into something the LookingGlass Volumetric display can render use: textureQuilt(<sampler2D> texture, <vec4> calibration, <vec3> tile, <vec2> st, <vec2> resolution) options: TEXTUREQUILT_FLIPSUBP: TEXTUREQUILT_SAMPLE_FNC(POS_UV): Function used to sample into the normal map texture, defaults to texture2D(tex,POS_UV) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TEXTUREQUILT_SAMPLE_FNC #define TEXTUREQUILT_SAMPLE_FNC(UV) texture2D(tex, UV) #endif #ifndef FNC_QUILT #define FNC_QUILT vec2 mapQuilt(vec3 tile, vec2 pos, float a) { vec2 tile2 = tile.xy - 1.0; vec2 dir = vec2(-1.0); a = fract(a) * tile.y; tile2.y += dir.y * floor(a); a = fract(a) * tile.x; tile2.x += dir.x * floor(a); return (tile2 + pos) / tile.xy; } vec3 textureQuilt(sampler2D tex, vec4 calibration, vec3 tile, vec2 st, vec2 resolution) { float pitch = -resolution.x / calibration.x * calibration.y * sin(atan(abs(calibration.z))); float tilt = resolution.y / (resolution.x * calibration.z); float subp = 1.0 / (3.0 * resolution.x); float subp2 = subp * pitch; float a = (-st.x - st.y * tilt) * pitch - calibration.w; vec3 color = vec3(0.0); #ifdef TEXTUREQUILT_FLIPSUBP color.r = TEXTUREQUILT_SAMPLE_FNC( mapQuilt(tile, st, a-2.0*subp2) ).r; color.g = TEXTUREQUILT_SAMPLE_FNC( mapQuilt(tile, st, a-subp2) ).g; color.b = TEXTUREQUILT_SAMPLE_FNC( mapQuilt(tile, st, a) ).b; #else color.r = TEXTUREQUILT_SAMPLE_FNC( mapQuilt(tile, st, a) ).r; color.g = TEXTUREQUILT_SAMPLE_FNC( mapQuilt(tile, st, a-subp2) ).g; color.b = TEXTUREQUILT_SAMPLE_FNC( mapQuilt(tile, st, a-2.0*subp2) ).b; #endif return color; } #endif <|start_filename|>sdf/spiralSDF.glsl<|end_filename|> /* author: <NAME> description: Returns a spiral SDF use: spiralSDF(<vec2> st, <float> turns) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_SPIRALSDF #define FNC_SPIRALSDF float spiralSDF(vec2 st, float t) { st -= 0.5; float r = dot(st, st); float a = atan(st.y, st.x); return abs(sin(fract(log(r) * t + a * 0.159))); } #endif <|start_filename|>filter/sharpen/adaptive.glsl<|end_filename|> #include "../../math/saturate.glsl" #include "../../math/mmax.glsl" /* author: bacondither description: adaptive sharpening. For strenght values between 0.3 <-> 2.0 are a reasonable range use: sharpen(<sampler2D> texture, <vec2> st, <vec2> renderSize [, float streanght]) options: SHARPEN_KERNELSIZE: Defaults 2 SHARPENADAPTIVE_TYPE: defaults to vec3 SHARPENADAPTIVE_SAMPLER_FNC(POS_UV): defaults to texture2D(tex, POS_UV).rgb SHARPEN_FNC: defaults to sharpenFast SHARPENADAPTIVE_ANIME: only darken edges. Defaults to: false license: | Copyright (c) 2015-2020, bacondither All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer in this position and unchanged. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SHARPENADAPTIVE_TYPE #ifdef SHARPEN_TYPE #define SHARPENADAPTIVE_TYPE SHARPEN_TYPE #else #define SHARPENADAPTIVE_TYPE vec3 #endif #endif #ifndef SHARPENADAPTIVE_SAMPLER_FNC #ifdef SHARPEN_SAMPLER_FNC #define SHARPENADAPTIVE_SAMPLER_FNC(POS_UV) SHARPEN_SAMPLER_FNC(POS_UV) #else #define SHARPENADAPTIVE_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).rgb #endif #endif #ifndef SHARPENADAPTIVE_ANIME #define SHARPENADAPTIVE_ANIME false // Only darken edges #endif #ifndef FNC_SHARPENAPTIVE #define FNC_SHARPENAPTIVE // Soft limit, modified tanh approx #define SHARPENADAPTIVE_SOFT_LIM(v,s) ( saturate(abs(v/s)*(27.0 + pow(v/s, 2.0))/(27.0 + 9.0*pow(v/s, 2.0)))*s ) // Weighted power mean #define SHARPENADAPTIVE_WPMEAN(a,b,w) ( pow(w*pow(abs(a), 0.5) + abs(1.0-w)*pow(abs(b), 0.5), 2.0) ) // Get destination pixel values #define SHARPENADAPTIVE_DXDY(val) ( length(fwidth(val)) ) // edgemul = 2.2 #define SHARPENADAPTIVE_CTRL(RGB) ( dot(RGB*RGB, vec3(0.212655, 0.715158, 0.072187)) ) #define SHARPENADAPTIVE_DIFF(pix) ( abs(blur-c[pix]) ) SHARPENADAPTIVE_TYPE sharpenAdaptive(sampler2D tex, vec2 st, vec2 pixel, float strenght) { //------------------------------------------------------------------------------------------------- // Defined values under this row are "optimal" DO NOT CHANGE IF YOU DO NOT KNOW WHAT YOU ARE DOING! const float curveslope = 0.5 ; // Sharpening curve slope, high edge values const float L_overshoot = 0.003; // Max light overshoot before compression [>0.001] const float L_compr_low = 0.167; // Light compression, default (0.167=~6x) const float D_overshoot = 0.009; // Max dark overshoot before compression [>0.001] const float D_compr_low = 0.250; // Dark compression, default (0.250=4x) const float scale_lim = 0.1 ; // Abs max change before compression [>0.01] const float scale_cs = 0.056; // Compression slope above scale_lim // [ c22 ] // [ c24, c9, c23 ] // [ c21, c1, c2, c3, c18 ] // [ c19, c10, c4, c0, c5, c11, c16 ] // [ c20, c6, c7, c8, c17 ] // [ c15, c12, c14 ] // [ c13 ] SHARPENADAPTIVE_TYPE c[25]; c[0] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(0.0, 0.0) * pixel); c[1] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-1., -1.) * pixel); c[2] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(0.0, -1.) * pixel); c[3] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(1.0, -1.) * pixel); c[4] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-1., 1.0) * pixel); c[5] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(1.0, 0.0) * pixel); c[6] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-1., 1.0) * pixel); c[7] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(0.0, 1.0) * pixel); c[8] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(1.0, 1.0) * pixel); c[9] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(0.0, -2.) * pixel); c[10] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-2., 0.0) * pixel); c[11] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 2., 0.0) * pixel); c[12] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 0., 2.0) * pixel); c[13] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 0., 3.0) * pixel); c[14] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 1., 2.0) * pixel); c[15] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-1., 2.0) * pixel); c[16] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 3., 0.0) * pixel); c[17] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 2., 1.0) * pixel); c[18] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 2.,-1.0) * pixel); c[19] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-3., 0.0) * pixel); c[20] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-2., 1.0) * pixel); c[21] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-2.,-1.0) * pixel); c[22] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 0.,-3.0) * pixel); c[23] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2( 1.,-2.0) * pixel); c[24] = SHARPENADAPTIVE_SAMPLER_FNC(st + vec2(-1.,-2.0) * pixel); float e[13]; e[0] = SHARPENADAPTIVE_DXDY(c[0]); e[1] = SHARPENADAPTIVE_DXDY(c[1]); e[2] = SHARPENADAPTIVE_DXDY(c[2]); e[3] = SHARPENADAPTIVE_DXDY(c[3]); e[4] = SHARPENADAPTIVE_DXDY(c[4]); e[5] = SHARPENADAPTIVE_DXDY(c[5]); e[6] = SHARPENADAPTIVE_DXDY(c[6]); e[7] = SHARPENADAPTIVE_DXDY(c[7]); e[8] = SHARPENADAPTIVE_DXDY(c[8]); e[9] = SHARPENADAPTIVE_DXDY(c[9]); e[10] = SHARPENADAPTIVE_DXDY(c[10]); e[11] = SHARPENADAPTIVE_DXDY(c[11]); e[12] = SHARPENADAPTIVE_DXDY(c[12]); // Blur, gauss 3x3 SHARPENADAPTIVE_TYPE blur = (2.0 * (c[2]+c[4]+c[5]+c[7]) + (c[1]+c[3]+c[6]+c[8]) + 4.0 * c[0]) / 16.0; // Contrast compression, center = 0.5, scaled to 1/3 float c_comp = saturate(0.266666681 + 0.9*exp2(dot(blur, vec3(-7.4/3.0)))); // Edge detection // Relative matrix weights // [ 1 ] // [ 4, 5, 4 ] // [ 1, 5, 6, 5, 1 ] // [ 4, 5, 4 ] // [ 1 ] float edge = length( 1.38*SHARPENADAPTIVE_DIFF(0) + 1.15*(SHARPENADAPTIVE_DIFF(2) + SHARPENADAPTIVE_DIFF(4) + SHARPENADAPTIVE_DIFF(5) + SHARPENADAPTIVE_DIFF(7)) + 0.92*(SHARPENADAPTIVE_DIFF(1) + SHARPENADAPTIVE_DIFF(3) + SHARPENADAPTIVE_DIFF(6) + SHARPENADAPTIVE_DIFF(8)) + 0.23*(SHARPENADAPTIVE_DIFF(9) + SHARPENADAPTIVE_DIFF(10) + SHARPENADAPTIVE_DIFF(11) + SHARPENADAPTIVE_DIFF(12)) ) * c_comp; vec2 cs = vec2(L_compr_low, D_compr_low); // RGB to luma float luma[25]; luma[0] = SHARPENADAPTIVE_CTRL(c[0]); luma[1] = SHARPENADAPTIVE_CTRL(c[1]); luma[2] = SHARPENADAPTIVE_CTRL(c[2]); luma[3] = SHARPENADAPTIVE_CTRL(c[3]); luma[4] = SHARPENADAPTIVE_CTRL(c[4]); luma[5] = SHARPENADAPTIVE_CTRL(c[5]); luma[6] = SHARPENADAPTIVE_CTRL(c[6]); luma[7] = SHARPENADAPTIVE_CTRL(c[7]); luma[8] = SHARPENADAPTIVE_CTRL(c[8]); luma[9] = SHARPENADAPTIVE_CTRL(c[9]); luma[10] = SHARPENADAPTIVE_CTRL(c[10]); luma[11] = SHARPENADAPTIVE_CTRL(c[11]); luma[12] = SHARPENADAPTIVE_CTRL(c[12]); luma[13] = SHARPENADAPTIVE_CTRL(c[13]); luma[14] = SHARPENADAPTIVE_CTRL(c[14]); luma[15] = SHARPENADAPTIVE_CTRL(c[15]); luma[16] = SHARPENADAPTIVE_CTRL(c[16]); luma[17] = SHARPENADAPTIVE_CTRL(c[17]); luma[18] = SHARPENADAPTIVE_CTRL(c[18]); luma[19] = SHARPENADAPTIVE_CTRL(c[19]); luma[20] = SHARPENADAPTIVE_CTRL(c[20]); luma[21] = SHARPENADAPTIVE_CTRL(c[21]); luma[22] = SHARPENADAPTIVE_CTRL(c[22]); luma[23] = SHARPENADAPTIVE_CTRL(c[23]); luma[24] = SHARPENADAPTIVE_CTRL(c[24]); float c0_Y = sqrt(luma[0]); // Precalculated default squared kernel weights const vec3 w1 = vec3(0.5, 1.0, 1.41421356237); // 0.25, 1.0, 2.0 const vec3 w2 = vec3(0.86602540378, 1.0, 0.54772255751); // 0.75, 1.0, 0.3 // Transition to a concave kernel if the center edge val is above thr vec3 dW = pow(mix( w1, w2, saturate(2.4*edge - 0.82)), vec3(2.0)); // Use lower weights for pixels in a more active area relative to center pixel area // This results in narrower and less visible overshoots around sharp edges float modif_e0 = 3.0 * e[0] + 0.0090909; float weights[12]; weights[0] = min(modif_e0/e[1], dW.y); weights[1] = dW.x; weights[2] = min(modif_e0/e[3], dW.y); weights[3] = dW.x; weights[4] = dW.x; weights[5] = min(modif_e0/e[6], dW.y); weights[6] = dW.x; weights[7] = min(modif_e0/e[8], dW.y); weights[8] = min(modif_e0/e[9], dW.z); weights[9] = min(modif_e0/e[10], dW.z); weights[10] = min(modif_e0/e[11], dW.z); weights[11] = min(modif_e0/e[12], dW.z); weights[0] = (max(max((weights[8] + weights[9])/4.0, weights[0]), 0.25) + weights[0])/2.0; weights[2] = (max(max((weights[8] + weights[10])/4.0, weights[2]), 0.25) + weights[2])/2.0; weights[5] = (max(max((weights[9] + weights[11])/4.0, weights[5]), 0.25) + weights[5])/2.0; weights[7] = (max(max((weights[10] + weights[11])/4.0, weights[7]), 0.25) + weights[7])/2.0; // Calculate the negative part of the laplace kernel and the low threshold weight float lowthrsum = 0.0; float weightsum = 0.0; float neg_laplace = 0.0; for (int pix = 0; pix < 12; ++pix) { float lowthr = clamp((29.04*e[pix + 1] - 0.221), 0.01, 1.0); neg_laplace += luma[pix+1] * weights[pix] * lowthr; weightsum += weights[pix] * lowthr; lowthrsum += lowthr / 12.0; } neg_laplace = inversesqrt(weightsum / neg_laplace); // Compute sharpening magnitude function float sharpen_val = strenght/(strenght*curveslope*pow(edge, 3.5) + 0.625); // Calculate sharpening diff and scale float sharpdiff = (c0_Y - neg_laplace)*(lowthrsum*sharpen_val + 0.01); // Calculate local near min & max, partial sort float temp; for (int i1 = 0; i1 < 24; i1 += 2) { temp = luma[i1]; luma[i1] = min(luma[i1], luma[i1+1]); luma[i1+1] = max(temp, luma[i1+1]); } for (int i2 = 24; i2 > 0; i2 -= 2) { temp = luma[0]; luma[0] = min(luma[0], luma[i2]); luma[i2] = max(temp, luma[i2]); temp = luma[24]; luma[24] = max(luma[24], luma[i2-1]); luma[i2-1] = min(temp, luma[i2-1]); } for (int i1 = 1; i1 < 24-1; i1 += 2) { temp = luma[i1]; luma[i1] = min(luma[i1], luma[i1+1]); luma[i1+1] = max(temp, luma[i1+1]); } for (int i2 = 24-1; i2 > 1; i2 -= 2) { temp = luma[1]; luma[1] = min(luma[1], luma[i2]); luma[i2] = max(temp, luma[i2]); temp = luma[24-1]; luma[24-1] = max(luma[24-1], luma[i2-1]); luma[i2-1] = min(temp, luma[i2-1]); } float nmax = (max(sqrt(luma[23]), c0_Y)*2.0 + sqrt(luma[24]))/3.0; float nmin = (min(sqrt(luma[1]), c0_Y)*2.0 + sqrt(luma[0]))/3.0; float min_dist = min(abs(nmax - c0_Y), abs(c0_Y - nmin)); float pos_scale = min_dist + L_overshoot; float neg_scale = min_dist + D_overshoot; pos_scale = min(pos_scale, scale_lim*(1.0 - scale_cs) + pos_scale*scale_cs); neg_scale = min(neg_scale, scale_lim*(1.0 - scale_cs) + neg_scale*scale_cs); // Soft limited anti-ringing with tanh, SHARPENADAPTIVE_WPMEAN to control compression slope sharpdiff = (SHARPENADAPTIVE_ANIME ? 0. : SHARPENADAPTIVE_WPMEAN(max(sharpdiff, 0.0), SHARPENADAPTIVE_SOFT_LIM( max(sharpdiff, 0.0), pos_scale ), cs.x )) - SHARPENADAPTIVE_WPMEAN(min(sharpdiff, 0.0), SHARPENADAPTIVE_SOFT_LIM( min(sharpdiff, 0.0), neg_scale ), cs.y ); float sharpdiff_lim = saturate(c0_Y + sharpdiff) - c0_Y; float satmul = (c0_Y + max(sharpdiff_lim*0.9, sharpdiff_lim)*1.03 + 0.03)/(c0_Y + 0.03); return c0_Y + (sharpdiff_lim*3.0 + sharpdiff)/4.0 + (c[0] - c0_Y)*satmul; } SHARPENADAPTIVE_TYPE sharpenAdaptive(sampler2D tex, vec2 st, vec2 pixel) { return sharpenAdaptive(tex, st, pixel, 1.0); } #endif <|start_filename|>filter/boxBlur/2D_fast9.glsl<|end_filename|> /* author: <NAME> description: simple two dimentional box blur, so can be apply in a single pass use: boxBlur1D_fast9(<sampler2D> texture, <vec2> st, <vec2> pixel_direction) options: BOXBLUR2D_FAST9_TYPE: Default is `vec4` BOXBLUR2D_FAST9_SAMPLER_FNC(POS_UV): Default is `texture2D(tex, POS_UV)` license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BOXBLUR2D_FAST9_TYPE #ifdef BOXBLUR_TYPE #define BOXBLUR2D_FAST9_TYPE BOXBLUR_TYPE #else #define BOXBLUR2D_FAST9_TYPE vec4 #endif #endif #ifndef BOXBLUR2D_FAST9_SAMPLER_FNC #ifdef BOXBLUR_SAMPLER_FNC #define BOXBLUR2D_FAST9_SAMPLER_FNC(POS_UV) BOXBLUR_SAMPLER_FNC(POS_UV) #else #define BOXBLUR2D_FAST9_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #endif #ifndef FNC_BOXBLUR2D_FAST9 #define FNC_BOXBLUR2D_FAST9 BOXBLUR2D_FAST9_TYPE boxBlur2D_fast9(in sampler2D tex, in vec2 st, in vec2 offset) { BOXBLUR2D_FAST9_TYPE color = BOXBLUR2D_FAST9_SAMPLER_FNC(st); // center color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(-offset.x, offset.y)); // tleft color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(-offset.x, 0.)); // left color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(-offset.x, -offset.y)); // bleft color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(0., offset.y)); // top color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(0., -offset.y)); // bottom color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + offset); // tright color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(offset.x, 0.)); // right color += BOXBLUR2D_FAST9_SAMPLER_FNC(st + vec2(offset.x, -offset.y)); // bright return color * 0.1111111111; // 1./9. } #endif <|start_filename|>operation/densify.glsl<|end_filename|> /* author: <NAME> description: simple densification use: densifyBox(<sampler2D> texture, <vec2> st, <vec2> pixels_scale, <int> passes) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_DENSIFY #define FNC_DENSIFY vec3 densifyBox(sampler2D tex, vec2 st, vec2 pixel, int passes) { vec3 color = texture2D(tex, st).rgb; if (color == vec3(0.0)) { float weight = 0.0; int kernelSize = 3; for (int k = 0; k < passes; k++) { float f_kernelSize = float(kernelSize); for (int j = 0; j < kernelSize; j++) { float y = -.5 * (f_kernelSize - 1.) + float(j); for (int i = 0; i < kernelSize; i++) { float x = -.5 * (f_kernelSize - 1.) + float(i); vec3 value = texture2D(tex, st + vec2(x, y) * pixel).rgb; if (value != vec3(0.0)) { color += value; weight++; } } } kernelSize += 2; } color /= weight; } return color; } vec3 densifyGaussian(sampler2D tex, vec2 st, vec2 pixel, int passes) { vec3 color = texture2D(tex, st).rgb; if (dot(color,color) == 0.0) { int kernelSize = 3; float accumWeight = 1.; const float k = .39894228; float kernelSize2 = float(kernelSize) * float(kernelSize); for (int k = 0; k < passes; k++) { float f_kernelSize = float(kernelSize); for (int j = 0; j < kernelSize; j++) { float y = -.5 * (f_kernelSize - 1.) + float(j); for (int i = 0; i < kernelSize; i++) { float x = -.5 * (f_kernelSize - 1.) + float(i); vec2 xy = vec2(x, y); vec3 value = texture2D(tex, st + xy * pixel).rgb; if (dot(value,value) > 0.0) { float weight = (k / f_kernelSize * exp(-(x * x + y * y) / (2. * kernelSize2))); color += weight * value; accumWeight += weight; } } } kernelSize += 2; } color /= accumWeight; } return color; } vec3 densify(sampler2D tex, vec2 st, vec2 pixel, int passes) { return densifyGaussian(tex, st, pixel, passes); } #endif <|start_filename|>animation/easing.glsl<|end_filename|> /* description: Include all available easing animations */ #include "easing/back.glsl" #include "easing/bounce.glsl" #include "easing/circular.glsl" #include "easing/cubic.glsl" #include "easing/elastic.glsl" #include "easing/exponential.glsl" #include "easing/linear.glsl" #include "easing/quadratic.glsl" #include "easing/quintic.glsl" #include "easing/sine.glsl" <|start_filename|>lighting/material/baseColor.glsl<|end_filename|> #include "../../color/space/gamma2linear.glsl" /* author: <NAME> description: get material BaseColor from GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: vec4 materialBaseColor() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_BASECOLOR #define FNC_MATERIAL_BASECOLOR #ifdef MATERIAL_BASECOLORMAP uniform sampler2D MATERIAL_BASECOLORMAP; #endif vec4 materialBaseColor() { vec4 base = vec4(1.0); #if defined(MATERIAL_BASECOLORMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; #if defined(MATERIAL_BASECOLORMAP_OFFSET) uv += (MATERIAL_BASECOLORMAP_OFFSET).xy; #endif #if defined(MATERIAL_BASECOLORMAP_SCALE) uv *= (MATERIAL_BASECOLORMAP_SCALE).xy; #endif base = gamma2linear( texture2D(MATERIAL_BASECOLORMAP, uv) ); #elif defined(MATERIAL_BASECOLOR) base = MATERIAL_BASECOLOR; #endif #if defined(MODEL_VERTEX_COLOR) base *= v_color; #endif return base; } #endif <|start_filename|>filter/gaussianBlur.glsl<|end_filename|> /* author: [<NAME>, <NAME>] description: adapted versions from 5, 9 and 13 gaussian fast blur from https://github.com/Jam3/glsl-fast-gaussian-blur use: gaussianBlur(<sampler2D> texture, <vec2> st, <vec2> pixel_direction [, const int kernelSize]) options: GAUSSIANBLUR_AMOUNT: gaussianBlur5 gaussianBlur9 gaussianBlur13 GAUSSIANBLUR_2D: default to 1D license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GAUSSIANBLUR_AMOUNT #define GAUSSIANBLUR_AMOUNT gaussianBlur13 #endif #ifndef GAUSSIANBLUR_TYPE #define GAUSSIANBLUR_TYPE vec4 #endif #ifndef GAUSSIANBLUR_SAMPLER_FNC #define GAUSSIANBLUR_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #include "gaussianBlur/2D.glsl" #include "gaussianBlur/1D.glsl" #include "gaussianBlur/1D_fast13.glsl" #include "gaussianBlur/1D_fast9.glsl" #include "gaussianBlur/1D_fast5.glsl" #ifndef FNC_GAUSSIANBLUR #define FNC_GAUSSIANBLUR GAUSSIANBLUR_TYPE gaussianBlur13(in sampler2D tex, in vec2 st, in vec2 offset) { #ifdef GAUSSIANBLUR_2D return gaussianBlur2D(tex, st, offset, 7); #else return gaussianBlur1D_fast13(tex, st, offset); #endif } GAUSSIANBLUR_TYPE gaussianBlur9(in sampler2D tex, in vec2 st, in vec2 offset) { #ifdef GAUSSIANBLUR_2D return gaussianBlur2D(tex, st, offset, 5); #else return gaussianBlur1D_fast9(tex, st, offset); #endif } GAUSSIANBLUR_TYPE gaussianBlur5(in sampler2D tex, in vec2 st, in vec2 offset) { #ifdef GAUSSIANBLUR_2D return gaussianBlur2D(tex, st, offset, 3); #else return gaussianBlur1D_fast5(tex, st, offset); #endif } GAUSSIANBLUR_TYPE gaussianBlur(in sampler2D tex, in vec2 st, in vec2 offset, const int kernelSize) { #ifdef GAUSSIANBLUR_2D return gaussianBlur2D(tex, st, offset, kernelSize); #else return gaussianBlur1D(tex, st, offset, kernelSize); #endif } GAUSSIANBLUR_TYPE gaussianBlur(in sampler2D tex, in vec2 st, in vec2 offset) { return GAUSSIANBLUR_AMOUNT(tex, st, offset); } #endif <|start_filename|>math/fade.glsl<|end_filename|> /* author: [<NAME>, <NAME>] description: fade use: fade(<vec2|vec3|vec4> t) license: | Copyright (C) 2011 <NAME>. All rights reserved. Distributed under the MIT License. See LICENSE file. https://github.com/ashima/webgl-noise */ #ifndef FNC_FADE #define FNC_FADE float fade(in float t) { return t * t * t * (t * (t * 6. - 15.) + 10.); } vec2 fade(in vec2 t) { return t * t * t * (t * (t * 6. - 15.) + 10.); } vec3 fade(in vec3 t) { return t * t * t * (t * (t * 6. - 15. ) + 10.); } vec4 fade(vec4 t) { return t*t*t*(t*(t*6.0-15.0)+10.0); } #endif <|start_filename|>lighting/common/ashikhmin.glsl<|end_filename|> #include "../../math/const.glsl" #ifndef FNC_ASHIKHMIN #define FNC_ASHIKHMIN float ashikhmin(float NoH, float roughness) { // Ashikhmin 2007, "Distribution-based BRDFs" float a2 = roughness * roughness; float cos2h = NoH * NoH; float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16 float sin4h = sin2h * sin2h; float cot2 = -cos2h / (a2 * sin2h); return 1.0 / (PI * (4.0 * a2 + 1.0) * sin4h) * (4.0 * exp(cot2) + sin4h); } #endif <|start_filename|>draw/bridge.glsl<|end_filename|> #include "stroke.glsl" /* author: <NAME> description: create a bridge on a given in_value and draw a stroke inside that gap use: bridge(<float|vec2|vec3|vec4> in_value, <float> sdf, <float> size, <float> width) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_BRIDGE #define FNC_BRIDGE float bridge(float c, float d, float s, float w) { c *= 1.0 - stroke(d, s , w * 2.0); return c + stroke(d, s, w); } vec2 bridge(vec2 c, float d, float s, float w) { c *= 1.0 - stroke(d, s , w * 2.0); return c + stroke(d, s, w); } vec3 bridge(vec3 c, float d, float s, float w) { c *= 1.0 - stroke(d, s , w * 2.0); return c + stroke(d, s, w); } vec4 bridge(vec4 c, float d, float s, float w) { c *= 1.0 - stroke(d, s , w * 2.0); return c + stroke(d, s, w); } #endif <|start_filename|>color/blend/colorBurn.glsl<|end_filename|> /* author: <NAME> description: Photoshop Color Burn blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendColorBurn(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDCOLORBURN #define FNC_BLENDCOLORBURN float blendColorBurn(in float base, in float blend) { return (blend == 0.)? blend: max((1. - ((1. - base ) / blend)), 0.); } vec3 blendColorBurn(in vec3 base, in vec3 blend) { return vec3(blendColorBurn(base.r, blend.r), blendColorBurn(base.g, blend.g), blendColorBurn(base.b, blend.b)); } vec3 blendColorBurn(in vec3 base, in vec3 blend, in float opacity) { return (blendColorBurn(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>math/map.glsl<|end_filename|> #include "saturate.glsl" /* author: <NAME> description: Map a value between one range to another. use: map(<float|vec2|vec3|vec4> value, <float|vec2|vec3|vec4> inMin, <float|vec2|vec3|vec4> inMax, <float|vec2|vec3|vec4> outMin, <float|vec2|vec3|vec4> outMax) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MAP #define FNC_MAP float map( float value, float inMin, float inMax ) { return saturate( (value-inMin)/(inMax-inMin)); } vec2 map( vec2 value, vec2 inMin, vec2 inMax ) { return saturate( (value-inMin)/(inMax-inMin)); } vec3 map( vec3 value, vec3 inMin, vec3 inMax ) { return saturate( (value-inMin)/(inMax-inMin)); } vec4 map( vec4 value, vec4 inMin, vec4 inMax ) { return saturate( (value-inMin)/(inMax-inMin)); } float map(in float value, in float inMin, in float inMax, in float outMin, in float outMax) { return outMin + (outMax - outMin) * (value - inMin) / (inMax - inMin); } vec2 map(in vec2 value, in vec2 inMin, in vec2 inMax, in vec2 outMin, in vec2 outMax) { return outMin + (outMax - outMin) * (value - inMin) / (inMax - inMin); } vec3 map(in vec3 value, in vec3 inMin, in vec3 inMax, in vec3 outMin, in vec3 outMax) { return outMin + (outMax - outMin) * (value - inMin) / (inMax - inMin); } vec4 map(in vec4 value, in vec4 inMin, in vec4 inMax, in vec4 outMin, in vec4 outMax) { return outMin + (outMax - outMin) * (value - inMin) / (inMax - inMin); } #endif <|start_filename|>color/blend/linearLight.glsl<|end_filename|> #include "linearDodge.glsl" #include "linearBurn.glsl" /* author: <NAME> description: Photoshop Linear Light blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendLinearLigth(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDLINEARLIGHT #define FNC_BLENDLINEARLIGHT float blendLinearLigth(in float base, in float blend) { return blend < .5? blendLinearBurn(base, (2. * blend)): blendLinearDodge(base, (2. * (blend- .5))); } vec3 blendLinearLigth(in vec3 base, in vec3 blend) { return vec3(blendLinearLigth(base.r, blend.r), blendLinearLigth(base.g, blend.g), blendLinearLigth(base.b, blend.b)); } vec3 blendLinearLigth(in vec3 base, in vec3 blend, in float opacity) { return (blendLinearLigth(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>space/rotate.glsl<|end_filename|> #include "../math/rotate2d.glsl" #include "../math/rotate4d.glsl" /* author: <NAME> description: rotate a 2D space by a radian radians use: rotate(<vec3|vec2> st, float radians [, vec2 center]) options: - CENTER_2D - CENTER_3D - CENTER_4D license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_ROTATE #define FNC_ROTATE vec2 rotate(in vec2 st, in float radians, in vec2 center) { return rotate2d(radians) * (st - center) + center; } vec2 rotate(in vec2 st, in float radians) { #ifdef CENTER_2D return rotate(st, radians, CENTER_2D); #else return rotate(st, radians, vec2(.5)); #endif } vec3 rotate(in vec3 xyz, in float radians, in vec3 axis, in vec3 center) { return (rotate4d(axis, radians) * vec4(xyz - center, 1.)).xyz + center; } vec3 rotate(in vec3 xyz, in float radians, in vec3 axis) { #ifdef CENTER_3D return rotate(xyz, radians, axis, CENTER_3D); #else return rotate(xyz, radians, axis, vec3(0.)); #endif } vec4 rotate(in vec4 xyzw, in float radians, in vec3 axis, in vec4 center) { return rotate4d(axis, radians) * (xyzw - center) + center; } vec4 rotate(in vec4 xyzw, in float radians, in vec3 axis) { #ifdef CENTER_4D return rotate(xyzw, radians, axis, CENTER_4D); #else return rotate(xyzw, radians, axis, vec4(0.)); #endif } #endif <|start_filename|>filter/sharpen/fast.glsl<|end_filename|> /* author: <NAME> description: sharpening convolutional operation use: sharpen(<sampler2D> texture, <vec2> st, <vec2> pixel) options: SHARPENFAST_KERNELSIZE: Defaults 2 SHARPENFAST_TYPE: defaults to vec3 SHARPENFAST_SAMPLER_FNC(POS_UV): defaults to texture2D(tex, POS_UV).rgb license: | Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SHARPENFAST_KERNELSIZE #ifdef SHARPEN_KERNELSIZE #define SHARPENFAST_KERNELSIZE SHARPEN_KERNELSIZE #else #define SHARPENFAST_KERNELSIZE 2 #endif #endif #ifndef SHARPENFAST_TYPE #ifdef SHARPEN_TYPE #define SHARPENFAST_TYPE SHARPEN_TYPE #else #define SHARPENFAST_TYPE vec3 #endif #endif #ifndef SHARPENFAST_SAMPLER_FNC #ifdef SHARPEN_SAMPLER_FNC #define SHARPENFAST_SAMPLER_FNC(POS_UV) SHARPEN_SAMPLER_FNC(POS_UV) #else #define SHARPENFAST_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).rgb #endif #endif #ifndef FNC_SHARPENFAST #define FNC_SHARPENFAST SHARPENFAST_TYPE sharpenFast(in sampler2D tex, in vec2 coords, in vec2 pixel, float strenght) { SHARPENFAST_TYPE sum = SHARPENFAST_TYPE(0.); for (int i = 0; i < SHARPENFAST_KERNELSIZE; i++) { float f_size = float(i) + 1.; f_size *= strenght; sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( -1., 0.) * pixel * f_size); sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 0., -1.) * pixel * f_size); sum += 5. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 0., 0.) * pixel * f_size); sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 0., 1.) * pixel * f_size); sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 1., 0.) * pixel * f_size); } return sum / float(SHARPENFAST_KERNELSIZE); } SHARPENFAST_TYPE sharpenFast(in sampler2D tex, in vec2 coords, in vec2 pixel) { SHARPENFAST_TYPE sum = SHARPENFAST_TYPE(0.); for (int i = 0; i < SHARPENFAST_KERNELSIZE; i++) { float f_size = float(i) + 1.; sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( -1., 0.) * pixel * f_size); sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 0., -1.) * pixel * f_size); sum += 5. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 0., 0.) * pixel * f_size); sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 0., 1.) * pixel * f_size); sum += -1. * SHARPENFAST_SAMPLER_FNC(coords + vec2( 1., 0.) * pixel * f_size); } return sum / float(SHARPENFAST_KERNELSIZE); } #endif <|start_filename|>color/space/hsv2rgb.glsl<|end_filename|> /* author: <NAME> description: pass a color in HSB and get RGB color. Also use as reference http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl use: hsv2rgb(<vec3|vec4> color) license: | This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_HSV2RGB #define FNC_HSV2RGB vec3 hsv2rgb(in vec3 hsb) { vec3 rgb = clamp(abs(mod(hsb.x * 6. + vec3(0., 4., 2.), 6.) - 3.) - 1., 0., 1.); #ifdef HSV2RGB_SMOOTH rgb = rgb*rgb*(3. - 2. * rgb); #endif return hsb.z * mix(vec3(1.), rgb, hsb.y); } vec4 hsv2rgb(in vec4 hsb) { return vec4(hsv2rgb(hsb.rgb), hsb.a); } #endif <|start_filename|>color/tonemap/aces.glsl<|end_filename|> #include "../../math/saturate.glsl" /* Author: Narkowicz 2015 description: ACES Filmic Tone Mapping Curve. https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/ use: <vec3|vec4> tonemapACES(<vec3|vec4> x) */ #ifndef FNC_TONEMAPACES #define FNC_TONEMAPACES vec3 tonemapACES(in vec3 x) { const float a = 2.51; const float b = 0.03; const float c = 2.43; const float d = 0.59; const float e = 0.14; return saturate(x * (a * x + b)) / (x * (c * x + d) + e); } vec4 tonemapACES(in vec4 x) { return vec4(tonemapACES(x.rgb), x.a); } #endif <|start_filename|>sdf/hexSDF.glsl<|end_filename|> /*\ author: <NAME> description: Returns a hexagon-shaped SDF use: hexSDF(<vec2> st) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_HEXSDF #define FNC_HEXSDF float hexSDF(in vec2 st) { st = abs(st * 2. - 1.); return max(abs(st.y), st.x * .866025 + st.y * .5); } #endif <|start_filename|>sdf/polySDF.glsl<|end_filename|> #include "../math/const.glsl" /* author: <NAME> description: Returns a sdf for a regular polygon with V sides. use: polySDF(<vec2> st, int V) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_POLYSDF #define FNC_POLYSDF float polySDF(in vec2 st, in int V) { st = st * 2. - 1.; float a = atan(st.x, st.y) + PI; float r = length(st); float v = TAU / float(V); return cos(floor(.5 + a / v) * v - a ) * r; } #endif <|start_filename|>space/ratio.glsl<|end_filename|> /* author: <NAME> description: Fix the aspect ratio of a space keeping things squared for you. use: ratio(vec2 st, vec2 st_size) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_RATIO #define FNC_RATIO vec2 ratio(in vec2 st, in vec2 s) { return mix( vec2((st.x*s.x/s.y)-(s.x*.5-s.y*.5)/s.y,st.y), vec2(st.x,st.y*(s.y/s.x)-(s.y*.5-s.x*.5)/s.x), step(s.x,s.y)); } #endif <|start_filename|>sdf/raysSDF.glsl<|end_filename|> #include "../math/const.glsl" /* author: <NAME> description: Returns a sdf for rays with N branches use: raysSDF(<vec2> st, <int> N) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_RAYSSDF #define FNC_RAYSSDF float raysSDF(in vec2 st, in int N) { st -= .5; return fract(atan(st.y, st.x) / TAU * float(N)); } #endif <|start_filename|>lighting/raymarch.glsl<|end_filename|> /* author: <NAME> description: raymarching template where it needs to define a vec4 raymarchMSap( in vec3 pos ) use: <vec4> raymarch(<vec3> camera, <vec2> st) options: - LIGHT_POSITION: in glslViewer is u_light - LIGHT_COLOR: in glslViewer is u_lightColor - RAYMARCH_AMBIENT: defualt vec3(1.0) - RAYMARCH_BACKGROUND: default vec3(0.0) - RAYMARCH_CAMERA_MATRIX_FNC(RO, TA): default raymarchCamera(RO, TA) - RAYMARCH_RENDER_FNC(RO, RD): default raymarchDefaultRender(RO, RD) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef RAYMARCH_CAMERA_MATRIX_FNC #define RAYMARCH_CAMERA_MATRIX_FNC raymarchCamera #endif #ifndef RAYMARCH_RENDER_FNC #define RAYMARCH_RENDER_FNC raymarchDefaultRender #endif #ifndef ENG_RAYMARCHING #define ENG_RAYMARCHING #include "raymarch/default.glsl" #include "raymarch/camera.glsl" #include "../space/lookAt.glsl" vec4 raymarch(vec3 camera, vec3 ta, vec2 st) { mat3 ca = RAYMARCH_CAMERA_MATRIX_FNC(camera, ta); vec3 rd = ca * normalize(vec3(st*2.0-1.0, 3.0)); return RAYMARCH_RENDER_FNC( camera * 0.11, rd ); } vec4 raymarch(vec3 camera, vec2 st) { return raymarch(camera, vec3(0.0), st); } #endif <|start_filename|>filter/convolutionPyramid.glsl<|end_filename|> /* author: <NAME> description: down and up scaling functions for convolution pyramid https://www.cs.huji.ac.il/labs/cglab/projects/convpyr/data/convpyr-small.pdf use: convolutionPyramid(<sampler2D> texture0, <sampler2D> texture1, <vec2> st, <vec2> pixel, <bool> upscale) options: - CONVOLUTIONPYRAMID_H1: 1.0334, 0.6836, 0.1507 - CONVOLUTIONPYRAMID_H2: 0.0270 - CONVOLUTIONPYRAMID_G: 0.7753, 0.0312 license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // POISSON FILL (DEFAULT) // #define CONVOLUTIONPYRAMID_H1 1.0334, 0.6836, 0.1507 // #define CONVOLUTIONPYRAMID_H2 0.0270 // #define CONVOLUTIONPYRAMID_G 0.7753, 0.0312 // LAPLACIAN INTEGRATOR // #define CONVOLUTIONPYRAMID_H1 0.7, 0.5, 0.15 // #define CONVOLUTIONPYRAMID_H2 1.0 // #define CONVOLUTIONPYRAMID_G 0.547, 0.175 #include "convolutionPyramid/downscale.glsl" #include "convolutionPyramid/upscale.glsl" #ifndef FNC_CONVOLUTIONPYRAMID #define FNC_CONVOLUTIONPYRAMID vec4 convolutionPyramid(sampler2D tex0, sampler2D tex1, vec2 st, vec2 pixel, bool upscale) { vec4 color = vec4(0.0); if (!upscale) { color = convolutionPyramidDownscale(tex0, st, pixel); } else { color = convolutionPyramidUpscale(tex0, tex1, st, pixel); } return (color.a == 0.0)? color : vec4(color.rgb/color.a, 1.0) } #endif <|start_filename|>color/palette.glsl<|end_filename|> #include "../math/const.glsl" /* author: <NAME> description: Procedural generation of color palette algorithm explained here http://www.iquilezles.org/www/articles/palettes/palettes.htm) use: palette(<float> t, <vec3|vec4> a, <vec3|vec4> b, <vec3|vec4> c, <vec3|vec4> d) license: | Copyright © 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_PALETTE #define FNC_PALETTE vec3 palette (in float t, in vec3 a, in vec3 b, in vec3 c, in vec3 d) { return a + b * cos(TAU * ( c * t + d )); } vec4 palette (in float t, in vec4 a, in vec4 b, in vec4 c, in vec4 d) { return a + b * cos(TAU * ( c * t + d )); } #endif <|start_filename|>lighting/toShininess.glsl<|end_filename|> /* author: <NAME> description: convertes from PBR roughness/metallic to a shininess factor (typaclly use on diffuse/specular/ambient workflow) use: float toShininess(<float> roughness, <float> metallic) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_TOSHININESS #define FNC_TOSHININESS float toShininess(float roughness, float metallic) { float smooth = .95 - roughness * 0.5; smooth *= smooth; smooth *= smooth; return smooth * (80. + 160. * (1.0-metallic)); } #endif <|start_filename|>filter/boxBlur/2D.glsl<|end_filename|> /* author: <NAME> description: simple two dimentional box blur, so can be apply in a single pass use: boxBlur2D(<sampler2D> texture, <vec2> st, <vec2> pixel_offset, <int> kernelSize) options: BOXBLUR2D_TYPE: Default `vec4` BOXBLUR2D_SAMPLER_FNC(POS_UV): default is `texture2D(tex, POS_UV)` BOXBLUR2D_KERNELSIZE: Use only for WebGL 1.0 and OpenGL ES 2.0 . For example RaspberryPis is not happy with dynamic loops. Default is 'kernelSize' license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BOXBLUR2D_TYPE #ifdef BOXBLUR_TYPE #define BOXBLUR2D_TYPE BOXBLUR_TYPE #else #define BOXBLUR2D_TYPE vec4 #endif #endif #ifndef BOXBLUR2D_SAMPLER_FNC #ifdef BOXBLUR_SAMPLER_FNC #define BOXBLUR2D_SAMPLER_FNC(POS_UV) BOXBLUR_SAMPLER_FNC(POS_UV) #else #define BOXBLUR2D_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #endif #ifndef FNC_BOXBLUR2D #define FNC_BOXBLUR2D BOXBLUR2D_TYPE boxBlur2D(in sampler2D tex, in vec2 st, in vec2 pixel, const int kernelSize) { BOXBLUR2D_TYPE color = BOXBLUR2D_TYPE(0.); #ifndef BOXBLUR2D_KERNELSIZE #define BOXBLUR2D_KERNELSIZE kernelSize #endif float accumWeight = 0.; float f_kernelSize = float(BOXBLUR2D_KERNELSIZE); float kernelSize2 = f_kernelSize * f_kernelSize; float weight = 1. / kernelSize2; for (int j = 0; j < BOXBLUR2D_KERNELSIZE; j++) { float y = -.5 * (f_kernelSize - 1.) + float(j); for (int i = 0; i < BOXBLUR2D_KERNELSIZE; i++) { float x = -.5 * (f_kernelSize - 1.) + float(i); color += BOXBLUR2D_SAMPLER_FNC(st + vec2(x, y) * pixel) * weight; } } return color; } #endif <|start_filename|>draw/digits.glsl<|end_filename|> /* author: <NAME> description: | Draws all the digits of a floating point number, useful for debugging. Requires high precision to work properly. use: digits(<vec2> st, <float> value [, <float> nDecDigit]) options: DIGITS_DECIMALS: number of decimals after the point, defaults to 2 DIGITS_SIZE: size of the font, defaults to vec2(.025) */ #ifndef DIGITS_SIZE #define DIGITS_SIZE vec2(.025) #endif #ifndef DIGITS_DECIMALS #define DIGITS_DECIMALS 2.0 #endif #ifndef FNC_DIGITS #define FNC_DIGITS float digits(in vec2 st, in float value, in float nDecDigit) { st /= DIGITS_SIZE; float absValue = abs(value); float biggestDigitIndex = max(floor(log2(absValue) / log2(10.)), 0.); float counter = floor(value); float nIntDigits = 0.; for (int i = 0; i < 9; i++) { counter = floor(counter*.1); nIntDigits++; if (counter == 0.) break; } float digit = 12.; float digitIndex = (nIntDigits-1.) - floor(st.x); if (digitIndex > (-nDecDigit - 1.5)) { if (digitIndex > biggestDigitIndex) { if (value < 0.) { if (digitIndex < (biggestDigitIndex+1.5)) { digit = 11.; } } } else { if (digitIndex == -1.) { if (nDecDigit > 0.) { digit = 10.; } } else { if (digitIndex < 0.) { digitIndex += 1.; } float digitValue = (absValue / (pow(10., digitIndex))); digit = mod(floor(0.0001+digitValue), 10.); } } } vec2 pos = vec2(fract(st.x), st.y); if (pos.x < 0.) return 0.; if (pos.y < 0.) return 0.; if (pos.x >= 1.) return 0.; if (pos.y >= 1.) return 0.; // make a 4x5 array of bits float bin = 0.; if (digit < 0.5) // 0 bin = 7. + 5. * 16. + 5. * 256. + 5. * 4096. + 7. * 65536.; else if (digit < 1.5) // 1 bin = 2. + 2. * 16. + 2. * 256. + 2. * 4096. + 2. * 65536.; else if (digit < 2.5) // 2 bin = 7. + 1. * 16. + 7. * 256. + 4. * 4096. + 7. * 65536.; else if (digit < 3.5) // 3 bin = 7. + 4. * 16. + 7. * 256. + 4. * 4096. + 7. * 65536.; else if (digit < 4.5) // 4 bin = 4. + 7. * 16. + 5. * 256. + 1. * 4096. + 1. * 65536.; else if (digit < 5.5) // 5 bin = 7. + 4. * 16. + 7. * 256. + 1. * 4096. + 7. * 65536.; else if (digit < 6.5) // 6 bin = 7. + 5. * 16. + 7. * 256. + 1. * 4096. + 7. * 65536.; else if (digit < 7.5) // 7 bin = 4. + 4. * 16. + 4. * 256. + 4. * 4096. + 7. * 65536.; else if (digit < 8.5) // 8 bin = 7. + 5. * 16. + 7. * 256. + 5. * 4096. + 7. * 65536.; else if (digit < 9.5) // 9 bin = 7. + 4. * 16. + 7. * 256. + 5. * 4096. + 7. * 65536.; else if (digit < 10.5) // '.' bin = 2. + 0. * 16. + 0. * 256. + 0. * 4096. + 0. * 65536.; else if (digit < 11.5) // '-' bin = 0. + 0. * 16. + 7. * 256. + 0. * 4096. + 0. * 65536.; vec2 pixel = floor(pos * vec2(4., 5.)); return mod(floor(bin / pow(2., (pixel.x + (pixel.y * 4.)))), 2.); } float digits(in vec2 st, in float value, in float nDecDigit, in float nIntDigits) { vec2 st2 = st; float result = 0.0; float dig = nDecDigit; #ifndef DIGITS_LEADING_INT #define DIGITS_LEADING_INT nIntDigits #endif for (float i = DIGITS_LEADING_INT - 1.0; i > 0.0 ; i--) { if (i * 10.0 > value) { result += digits(st2, 0.0, 0.0); st2.x -= DIGITS_SIZE.x; } } result += digits(st2, value, nDecDigit); return result; } float digits(in vec2 st, in float value) { return digits(st, value, (DIGITS_DECIMALS)); } #endif <|start_filename|>color/blend/exclusion.glsl<|end_filename|> /* author: <NAME> description: Photoshop Exclusion blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendExclusion(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDEXCLUSION #define FNC_BLENDEXCLUSION float blendExclusion(in float base, in float blend) { return base + blend - 2. * base * blend; } vec3 blendExclusion(in vec3 base, in vec3 blend) { return base + blend - 2. * base * blend; } vec3 blendExclusion(in vec3 base, in vec3 blend, in float opacity) { return (blendExclusion(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/common/envBRDFApprox.glsl<|end_filename|> #ifndef FNC_ENVBRDFAPPROX #define FNC_ENVBRDFAPPROX vec3 envBRDFApprox(vec3 _specularColor, float _NoV, float _roughness) { vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022 ); vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04 ); vec4 r = _roughness * c0 + c1; float a004 = min( r.x * r.x, exp2( -9.28 * _NoV ) ) * r.x + r.y; vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw; return _specularColor * AB.x + AB.y; } #endif <|start_filename|>filter/boxBlur/1D.glsl<|end_filename|> /* author: <NAME> description: simple one dimentional box blur, to be applied in two passes use: boxBlur1D(<sampler2D> texture, <vec2> st, <vec2> pixel_offset, <int> kernelSize) options: BOXBLUR1D_TYPE: default is vec4 BOXBLUR1D_SAMPLER_FNC(POS_UV): default texture2D(tex, POS_UV) BOXBLUR1D_KERNELSIZE: Use only for WebGL 1.0 and OpenGL ES 2.0 . For example RaspberryPis is not happy with dynamic loops. Default is 'kernelSize' license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BOXBLUR1D_TYPE #ifdef BOXBLUR_TYPE #define BOXBLUR1D_TYPE BOXBLUR_TYPE #else #define BOXBLUR1D_TYPE vec4 #endif #endif #ifndef BOXBLUR1D_SAMPLER_FNC #ifdef BOXBLUR_SAMPLER_FNC #define BOXBLUR1D_SAMPLER_FNC(POS_UV) BOXBLUR_SAMPLER_FNC(POS_UV) #else #define BOXBLUR1D_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #endif #ifndef FNC_BOXBLUR1D #define FNC_BOXBLUR1D BOXBLUR1D_TYPE boxBlur1D(in sampler2D tex, in vec2 st, in vec2 offset, const int kernelSize) { BOXBLUR1D_TYPE color = BOXBLUR1D_TYPE(0.); #ifndef BOXBLUR1D_KERNELSIZE #define BOXBLUR1D_KERNELSIZE kernelSize #endif float f_kernelSize = float(BOXBLUR1D_KERNELSIZE); float weight = 1. / f_kernelSize; for (int i = 0; i < BOXBLUR1D_KERNELSIZE; i++) { float x = -.5 * (f_kernelSize - 1.) + float(i); color += BOXBLUR1D_SAMPLER_FNC(st + offset * x ) * weight; } return color; } #endif <|start_filename|>filter/bilateralBlur/2D.glsl<|end_filename|> #include "../../color/space/rgb2luma.glsl" /* author: <NAME> description: two dimensional bilateral Blur, to do it in one single pass use: bilateralBlur2D(<sampler2D> texture, <vec2> st, <vec2> offset, <int> kernelSize) options: BILATERALBLUR2D_TYPE: default is vec3 BILATERALBLUR2D_SAMPLER_FNC(POS_UV): default texture2D(tex, POS_UV) BILATERALBLUR2D_LUMA(RGB): default rgb2luma license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BILATERALBLUR2D_TYPE #ifdef BILATERALBLUR_TYPE #define BILATERALBLUR2D_TYPE BILATERALBLUR_TYPE #else #define BILATERALBLUR2D_TYPE vec4 #endif #endif #ifndef BILATERALBLUR2D_SAMPLER_FNC #ifdef BILATERALBLUR_SAMPLER_FNC #define BILATERALBLUR2D_SAMPLER_FNC(POS_UV) BILATERALBLUR_SAMPLER_FNC(POS_UV) #else #define BILATERALBLUR2D_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #endif #ifndef BILATERALBLUR2D_LUMA #define BILATERALBLUR2D_LUMA(RGB) rgb2luma(RGB.rgb) #endif #ifndef FNC_BILATERALBLUR2D #define FNC_BILATERALBLUR2D BILATERALBLUR2D_TYPE bilateralBlur2D(in sampler2D tex, in vec2 st, in vec2 offset, const int kernelSize) { BILATERALBLUR2D_TYPE accumColor = BILATERALBLUR2D_TYPE(0.); #ifndef BILATERALBLUR2D_KERNELSIZE #define BILATERALBLUR2D_KERNELSIZE kernelSize #endif float accumWeight = 0.; const float k = .15915494; // 1. / (2.*PI) const float k2 = k * k; float kernelSize2 = float(BILATERALBLUR2D_KERNELSIZE) * float(BILATERALBLUR2D_KERNELSIZE); BILATERALBLUR2D_TYPE tex0 = BILATERALBLUR2D_SAMPLER_FNC(st); float lum0 = BILATERALBLUR2D_LUMA(tex0); for (int j = 0; j < BILATERALBLUR2D_KERNELSIZE; j++) { float dy = -.5 * (float(BILATERALBLUR2D_KERNELSIZE) - 1.0) + float(j); for (int i = 0; i < BILATERALBLUR2D_KERNELSIZE; i++) { float dx = -.5 * (float(BILATERALBLUR2D_KERNELSIZE) - 1.0) + float(i); BILATERALBLUR2D_TYPE tex = BILATERALBLUR2D_SAMPLER_FNC(st + vec2(dx, dy) * offset); float lum = BILATERALBLUR2D_LUMA(tex); float dl = 255. * (lum - lum0); float weight = (k2 / kernelSize2) * exp(-(dx * dx + dy * dy + dl * dl) / (2. * kernelSize2)); accumColor += weight * tex; accumWeight += weight; } } return accumColor / accumWeight; } #endif <|start_filename|>color/tonemap/uncharted.glsl<|end_filename|> /* Author: [ description: use: <vec3|vec4> tonemapUncharted(<vec3|vec4> x) */ #ifndef FNC_TONEMAPUNCHARTED #define FNC_TONEMAPUNCHARTED vec3 uncharted2Tonemap(const vec3 x) { const float A = 0.15; const float B = 0.50; const float C = 0.10; const float D = 0.20; const float E = 0.02; const float F = 0.30; return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F; } vec3 tonemapUncharted(const vec3 x) { const float W = 11.2; const float exposureBias = 2.0; vec3 curr = uncharted2Tonemap(exposureBias * x); vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W)); return curr * whiteScale; } vec4 tonemapUncharted(const vec4 x) { return vec4( tonemapUncharted(x.rgb), x.a); } #endif <|start_filename|>lighting/common/gtaoMultiBounce.glsl<|end_filename|> #ifndef FNC_GTAOMULTIBOUNCE #define FNC_GTAOMULTIBOUNCE /** * Returns a color ambient occlusion based on a pre-computed visibility term. * The albedo term is meant to be the diffuse color or f0 for the diffuse and * specular terms respectively. */ vec3 gtaoMultiBounce(float visibility, const vec3 albedo) { // Jimenez et al. 2016, "Practical Realtime Strategies for Accurate Indirect Occlusion" vec3 a = 2.0404 * albedo - 0.3324; vec3 b = -4.7951 * albedo + 0.6417; vec3 c = 2.7552 * albedo + 0.6903; return max(vec3(visibility), ((visibility * a + b) * visibility + c) * visibility); } #endif <|start_filename|>color/space/YPbPr2rgb.glsl<|end_filename|> /* author: <NAME> description: pass a color in RGB and get it in YPbPr from http://www.equasys.de/colorconversion.html use: YPbPr2RGB(<vec3|vec4> color) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_YPBPR2RGB #define FNC_YPBPR2RGB #ifdef YPBPR_SDTV const mat3 YPbPr2rgb_mat = mat3( 1., 1., 1., 0., -.344, 1.772, 1.402, -.714, 0. ); #else const mat3 YPbPr2rgb_mat = mat3( 1., 1., 1., 0., -.187, 1.856, 1.575, -.468, 0. ); #endif vec3 YPbPr2rgb(in vec3 rgb) { return YPbPr2rgb_mat * rgb; } vec4 YPbPr2rgb(in vec4 rgb) { return vec4(YPbPr2rgb(rgb.rgb),rgb.a); } #endif <|start_filename|>color/tonemap/linear.glsl<|end_filename|> #ifndef FNC_TONEMAPLINEAR #define FNC_TONEMAPLINEAR vec3 tonemapLinear(const vec3 x) { return x; } vec4 tonemapLinear(const vec4 x) { return x; } #endif <|start_filename|>sdf/rhombSDF.glsl<|end_filename|> #include "triSDF.glsl" /* description: Returns a rhomb-shaped sdf use: rhombSDF(<vec2> st) author: <NAME> license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_RHOMBSDF #define FNC_RHOMBSDF float rhombSDF(in vec2 st) { return max(triSDF(st), triSDF(vec2(st.x, 1. - st.y))); } #endif <|start_filename|>draw/fill.glsl<|end_filename|> #include "aastep.glsl" /* author: <NAME> description: fill a SDF. From PixelSpiritDeck https://github.com/patriciogonzalezvivo/PixelSpiritDeck use: fill(<float> sdf, <float> size [, <float> edge]) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_FILL #define FNC_FILL float fill(float x, float size, float edge) { return 1.0 - smoothstep(size - edge, size + edge, x); } float fill(float x, float size) { return 1.0 - aastep(size, x); } #endif <|start_filename|>filter/edge/sobel.glsl<|end_filename|> /* author: <NAME> description: | Adapted version of Sobel edge detection from https://github.com/BradLarson/GPUImage2. use: edgeSobel(<sampler2D> texture, <vec2> st, <vec2> pixels_scale) options: EDGESOBEL_TYPE: Return type, defaults to float EDGESOBEL_SAMPLER_FNC: Function used to sample the input texture, defaults to texture2D(tex,POS_UV).r license: Copyright (c) 2015, <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EDGESOBEL_TYPE #ifdef EDGE_TYPE #define EDGESOBEL_TYPE EDGE_TYPE #else #define EDGESOBEL_TYPE float #endif #endif #ifndef EDGESOBEL_SAMPLER_FNC #ifdef EDGE_SAMPLER_FNC #define EDGESOBEL_SAMPLER_FNC(POS_UV) EDGE_SAMPLER_FNC(POS_UV) #else #define EDGESOBEL_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).r #endif #endif #ifndef FNC_EDGESOBEL #define FNC_EDGESOBEL EDGESOBEL_TYPE edgeSobel(in sampler2D tex, in vec2 st, in vec2 offset) { // get samples around pixel EDGESOBEL_TYPE tleft = EDGESOBEL_SAMPLER_FNC(st + vec2(-offset.x, offset.y)); EDGESOBEL_TYPE left = EDGESOBEL_SAMPLER_FNC(st + vec2(-offset.x, 0.)); EDGESOBEL_TYPE bleft = EDGESOBEL_SAMPLER_FNC(st + vec2(-offset.x, -offset.y)); EDGESOBEL_TYPE top = EDGESOBEL_SAMPLER_FNC(st + vec2(0., offset.y)); EDGESOBEL_TYPE bottom = EDGESOBEL_SAMPLER_FNC(st + vec2(0., -offset.y)); EDGESOBEL_TYPE tright = EDGESOBEL_SAMPLER_FNC(st + offset); EDGESOBEL_TYPE right = EDGESOBEL_SAMPLER_FNC(st + vec2(offset.x, 0.)); EDGESOBEL_TYPE bright = EDGESOBEL_SAMPLER_FNC(st + vec2(offset.x, -offset.y)); EDGESOBEL_TYPE x = tleft + 2. * left + bleft - tright - 2. * right - bright; EDGESOBEL_TYPE y = -tleft - 2. * top - tright + bleft + 2. * bottom + bright; return sqrt((x * x) + (y * y)); } #endif <|start_filename|>lighting/common/clampNoV.glsl<|end_filename|> #ifndef FNC_CLAMPNOV #define FNC_CLAMPNOV #ifndef MIN_N_DOT_V #define MIN_N_DOT_V 1e-4 #endif // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" float clampNoV(float NoV) { return max(NoV, MIN_N_DOT_V); } #endif <|start_filename|>generative/fbm.glsl<|end_filename|> #include "snoise.glsl" /* author: <NAME> description: Fractal Brownian Motion use: fbm(<vec2> pos) options: FBM_OCTAVES: numbers of octaves. Default is 4. FBM_NOISE_FNC(POS_UV): noise function to use Default 'snoise(POS_UV)' (simplex noise) FBM_VALUE_INITIAL: initial value. Default is 0. FBM_SCALE_SCALAR: scalar. Defualt is 2. FBM_AMPLITUD_INITIAL: initial amplitud value. Default is 0.5 FBM_AMPLITUD_SCALAR: amplitud scalar. Default is 0.5 license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FBM_OCTAVES #define FBM_OCTAVES 4 #endif #ifndef FBM_NOISE_FNC #define FBM_NOISE_FNC(POS_UV) snoise(POS_UV) #endif #ifndef FBM_VALUE_INITIAL #define FBM_VALUE_INITIAL 0.0 #endif #ifndef FBM_SCALE_SCALAR #define FBM_SCALE_SCALAR 2.0 #endif #ifndef FBM_AMPLITUD_INITIAL #define FBM_AMPLITUD_INITIAL 0.5 #endif #ifndef FBM_AMPLITUD_SCALAR #define FBM_AMPLITUD_SCALAR 0.5 #endif #ifndef FNC_FBM #define FNC_FBM float fbm(in vec2 st) { // Initial values float value = FBM_VALUE_INITIAL; float amplitud = FBM_AMPLITUD_INITIAL; // Loop of octaves for (int i = 0; i < FBM_OCTAVES; i++) { value += amplitud * FBM_NOISE_FNC(st); st *= FBM_SCALE_SCALAR; amplitud *= FBM_AMPLITUD_SCALAR; } return value; } float fbm(in vec3 pos) { // Initial values float value = FBM_VALUE_INITIAL; float amplitud = FBM_AMPLITUD_INITIAL; // Loop of octaves for (int i = 0; i < FBM_OCTAVES; i++) { value += amplitud * FBM_NOISE_FNC(pos); pos *= FBM_SCALE_SCALAR; amplitud *= FBM_AMPLITUD_SCALAR; } return value; } #endif <|start_filename|>filter/convolutionPyramid/upscale.glsl<|end_filename|> #include "../../math/absi.glsl" #ifndef CONVOLUTIONPYRAMID_H1 #define CONVOLUTIONPYRAMID_H1 1.0334, 0.6836, 0.1507 #endif #ifndef CONVOLUTIONPYRAMID_H2 #define CONVOLUTIONPYRAMID_H2 0.0270 #endif #ifndef CONVOLUTIONPYRAMID_G #define CONVOLUTIONPYRAMID_G 0.7753, 0.0312 #endif #ifndef FNC_CONVOLUTIONPYRAMID_UPSCALE #define FNC_CONVOLUTIONPYRAMID_UPSCALE vec4 convolutionPyramidUpscale(sampler2D tex0, sampler2D tex1, vec2 st, vec2 pixel) { const vec3 h1 = vec3(CONVOLUTIONPYRAMID_H1); const float h2 = CONVOLUTIONPYRAMID_H2; const vec2 g = vec2(CONVOLUTIONPYRAMID_G); vec4 color = vec4(0.0); for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec2 uv = st + vec2(float(dx), float(dy)) * pixel; color += texture2D(tex0, uv) * g[ absi(dx) ] * g[ absi(dy) ]; } } for (int dy = -2; dy <= 2; dy++) { for (int dx = -2; dx <= 2; dx++) { vec2 uv = st + vec2(float(dx), float(dy)) * pixel * 2.; color += texture2D(tex1, uv) * h2 * h1[ absi(dx) ] * h1[ absi(dy) ]; } } return color; } #endif <|start_filename|>lighting/diffuse/orenNayar.glsl<|end_filename|> /* author: <NAME> description: calculate diffuse contribution using Oren and Nayar equation https://en.wikipedia.org/wiki/Oren%E2%80%93Nayar_reflectance_model use: - <float> diffuseOrenNayar(<vec3> light, <vec3> normal, <vec3> view, <float> roughness ) - <float> diffuseOrenNayar(<vec3> L, <vec3> N, <vec3> V, <float> NoV, <float> NoL, <float> roughness) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_DIFFUSE_ORENNAYAR #define FNC_DIFFUSE_ORENNAYAR float diffuseOrenNayar(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness) { float LoV = dot(L, V); float s = LoV - NoL * NoV; float t = mix(1.0, max(NoL, NoV), step(0.0, s)); float sigma2 = roughness * roughness; float A = 1.0 + sigma2 * (1.0 / (sigma2 + 0.13) + 0.5 / (sigma2 + 0.33)); float B = 0.45 * sigma2 / (sigma2 + 0.09); return max(0.0, NoL) * (A + B * s / t); } float diffuseOrenNayar(vec3 L, vec3 N, vec3 V, float roughness) { float NoV = max(dot(N, V), 0.001); float NoL = max(dot(N, L), 0.001); return diffuseOrenNayar(L, N, V, NoV, NoL, roughness); } #endif <|start_filename|>lighting/pbrLittle.glsl<|end_filename|> #include "../math/powFast.glsl" #include "../math/saturate.glsl" #include "../color/tonemap.glsl" #include "../color/space/linear2gamma.glsl" #include "../sample/textureShadowPCF.glsl" #include "envMap.glsl" #include "sphericalHarmonics.glsl" #include "diffuse.glsl" #include "specular.glsl" /* author: <NAME> description: simple PBR shading model use: <vec4> pbrLittle(<vec4> baseColor, <vec3> normal, <float> roughness, <float> metallic ) options: - DIFFUSE_FNC: diffuseOrenNayar, diffuseBurley, diffuseLambert (default) - SPECULAR_FNC: specularGaussian, specularBeckmann, specularCookTorrance (default), specularPhongRoughness, specularBlinnPhongRoughnes (default on mobile) - LIGHT_POSITION: in GlslViewer is u_light - LIGHT_COLOR in GlslViewer is u_lightColor - CAMERA_POSITION: in GlslViewer is u_camera - SURFACE_POSITION: in glslViewer is v_position license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SURFACE_POSITION #define SURFACE_POSITION v_position #endif #ifndef CAMERA_POSITION #if defined(GLSLVIEWER) #define CAMERA_POSITION u_camera #else #define CAMERA_POSITION vec3(0.0, 0.0, -10.0); #endif #endif #ifndef LIGHT_POSITION #if defined(GLSLVIEWER) #define LIGHT_POSITION u_light #else #define LIGHT_POSITION vec3(0.0, 10.0, -50.0) #endif #endif #ifndef LIGHT_COLOR #if defined(GLSLVIEWER) #define LIGHT_COLOR u_lightColor #else #define LIGHT_COLOR vec3(0.5) #endif #endif #ifndef FNC_PBR_LITTLE #define FNC_PBR_LITTLE vec4 pbrLittle(vec4 baseColor, vec3 normal, float roughness, float metallic ) { vec3 L = normalize(LIGHT_POSITION - (SURFACE_POSITION).xyz); vec3 N = normalize(normal); vec3 V = normalize(CAMERA_POSITION - (SURFACE_POSITION).xyz); float notMetal = 1. - metallic; float smooth = .95 - saturate(roughness); // DIFFUSE float diffuse = diffuse(L, N, V, roughness); float specular = specular(L, N, V, roughness); #if defined(LIGHT_SHADOWMAP) && defined(LIGHT_SHADOWMAP_SIZE) && defined(LIGHT_COORD) && !defined(PLATFORM_RPI) && !defined(PLATFORM_WEBGL) float bias = 0.005; float shadow = textureShadowPCF(LIGHT_SHADOWMAP, vec2(LIGHT_SHADOWMAP_SIZE), (LIGHT_COORD).xy, (LIGHT_COORD).z - bias); specular *= shadow; diffuse *= shadow; #endif baseColor.rgb = baseColor.rgb * diffuse; #ifdef SCENE_SH_ARRAY baseColor.rgb *= tonemapReinhard( sphericalHarmonics(N) ); #endif // SPECULAR float specIntensity = (0.04 * notMetal + 2.0 * metallic) * saturate(1.1 + dot(N, V) + metallic) * // Fresnel (metallic + smooth * 4.0); // make smaller highlights brighter vec3 R = reflect(-V, N); vec3 ambientSpecular = tonemapReinhard( envMap(R, roughness, metallic) ) * specIntensity; ambientSpecular += fresnel(R, vec3(0.04), dot(N,V)) * metallic; baseColor.rgb = baseColor.rgb * notMetal + ( ambientSpecular + LIGHT_COLOR * 2.0 * specular ) * (notMetal * smooth + baseColor.rgb * metallic); return linear2gamma(baseColor); } #endif <|start_filename|>lighting/specular/phong.glsl<|end_filename|> #include "../../math/powFast.glsl" #include "../toShininess.glsl" #ifndef SPECULAR_POW #if defined(TARGET_MOBILE) || defined(PLATFORM_RPI) || defined(PLATFORM_WEBGL) #define SPECULAR_POW(A,B) powFast(A,B) #else #define SPECULAR_POW(A,B) pow(A,B) #endif #endif #ifndef FNC_SPECULAR_PHONG #define FNC_SPECULAR_PHONG // https://github.com/glslify/glsl-specular-phong float specularPhong(vec3 L, vec3 N, vec3 V, float shininess) { vec3 R = reflect(L, N); // 2.0 * dot(N, L) * N - L; return SPECULAR_POW(max(0.0, dot(R, -V)), shininess); } float specularPhongRoughness(vec3 L, vec3 N, vec3 V, float roughness) { return specularPhong(L, N, V, toShininess(roughness, 0.0) ); } float specularPhongRoughness(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { return specularPhongRoughness(L, N, V, roughness ); } float specularPhongRoughness(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness, float fresnel) { return specularPhongRoughness(L, N, V, roughness); } #endif <|start_filename|>generative/pnoise.glsl<|end_filename|> #include "../math/mod289.glsl" #include "../math/permute.glsl" #include "../math/taylorInvSqrt.glsl" #include "../math/fade.glsl" /* author: [<NAME>, Ashima Arts] description: Classic Perlin Noise with periodic variant https://github.com/ashima/webgl-noise use: pnoise(<vec2|vec3|vec4> pos, <vec2|vec3|vec4> periodic) license: | Copyright (C) 2011 Ashima Arts. All rights reserved. Copyright (C) 2011-2016 by <NAME> (Classic noise and others) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the GPUImage framework nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FNC_PNOISE #define FNC_PNOISE // Classic Perlin noise, periodic variant float pnoise(in vec2 P, in vec2 rep) { vec4 Pi = floor(P.xyxy) + vec4(0.0, 0.0, 1.0, 1.0); vec4 Pf = fract(P.xyxy) - vec4(0.0, 0.0, 1.0, 1.0); Pi = mod(Pi, rep.xyxy); // To create noise with explicit period Pi = mod289(Pi); // To avoid truncation effects in permutation vec4 ix = Pi.xzxz; vec4 iy = Pi.yyww; vec4 fx = Pf.xzxz; vec4 fy = Pf.yyww; vec4 i = permute(permute(ix) + iy); vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0 ; vec4 gy = abs(gx) - 0.5 ; vec4 tx = floor(gx + 0.5); gx = gx - tx; vec2 g00 = vec2(gx.x,gy.x); vec2 g10 = vec2(gx.y,gy.y); vec2 g01 = vec2(gx.z,gy.z); vec2 g11 = vec2(gx.w,gy.w); vec4 norm = taylorInvSqrt(vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); g00 *= norm.x; g01 *= norm.y; g10 *= norm.z; g11 *= norm.w; float n00 = dot(g00, vec2(fx.x, fy.x)); float n10 = dot(g10, vec2(fx.y, fy.y)); float n01 = dot(g01, vec2(fx.z, fy.z)); float n11 = dot(g11, vec2(fx.w, fy.w)); vec2 fade_xy = fade(Pf.xy); vec2 n_x = mix(vec2(n00, n01), vec2(n10, n11), fade_xy.x); float n_xy = mix(n_x.x, n_x.y, fade_xy.y); return 2.3 * n_xy; } float pnoise(in vec3 P, in vec3 rep) { vec3 Pi0 = mod(floor(P), rep); // Integer part, modulo period vec3 Pi1 = mod(Pi0 + vec3(1.0), rep); // Integer part + 1, mod period Pi0 = mod289(Pi0); Pi1 = mod289(Pi1); vec3 Pf0 = fract(P); // Fractional part for interpolation vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0 vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); vec4 iy = vec4(Pi0.yy, Pi1.yy); vec4 iz0 = Pi0.zzzz; vec4 iz1 = Pi1.zzzz; vec4 ixy = permute(permute(ix) + iy); vec4 ixy0 = permute(ixy + iz0); vec4 ixy1 = permute(ixy + iz1); vec4 gx0 = ixy0 * (1.0 / 7.0); vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5; gx0 = fract(gx0); vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0); vec4 sz0 = step(gz0, vec4(0.0)); gx0 -= sz0 * (step(0.0, gx0) - 0.5); gy0 -= sz0 * (step(0.0, gy0) - 0.5); vec4 gx1 = ixy1 * (1.0 / 7.0); vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5; gx1 = fract(gx1); vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1); vec4 sz1 = step(gz1, vec4(0.0)); gx1 -= sz1 * (step(0.0, gx1) - 0.5); gy1 -= sz1 * (step(0.0, gy1) - 0.5); vec3 g000 = vec3(gx0.x,gy0.x,gz0.x); vec3 g100 = vec3(gx0.y,gy0.y,gz0.y); vec3 g010 = vec3(gx0.z,gy0.z,gz0.z); vec3 g110 = vec3(gx0.w,gy0.w,gz0.w); vec3 g001 = vec3(gx1.x,gy1.x,gz1.x); vec3 g101 = vec3(gx1.y,gy1.y,gz1.y); vec3 g011 = vec3(gx1.z,gy1.z,gz1.z); vec3 g111 = vec3(gx1.w,gy1.w,gz1.w); vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); g000 *= norm0.x; g010 *= norm0.y; g100 *= norm0.z; g110 *= norm0.w; vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); g001 *= norm1.x; g011 *= norm1.y; g101 *= norm1.z; g111 *= norm1.w; float n000 = dot(g000, Pf0); float n100 = dot(g100, vec3(Pf1.x, Pf0.yz)); float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z)); float n110 = dot(g110, vec3(Pf1.xy, Pf0.z)); float n001 = dot(g001, vec3(Pf0.xy, Pf1.z)); float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z)); float n011 = dot(g011, vec3(Pf0.x, Pf1.yz)); float n111 = dot(g111, Pf1); vec3 fade_xyz = fade(Pf0); vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z); vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y); float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x); return 2.2 * n_xyz; } float pnoise(in vec4 P, in vec4 rep) { vec4 Pi0 = mod(floor(P), rep); // Integer part modulo rep vec4 Pi1 = mod(Pi0 + 1.0, rep); // Integer part + 1 mod rep Pi0 = mod289(Pi0); Pi1 = mod289(Pi1); vec4 Pf0 = fract(P); // Fractional part for interpolation vec4 Pf1 = Pf0 - 1.0; // Fractional part - 1.0 vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); vec4 iy = vec4(Pi0.yy, Pi1.yy); vec4 iz0 = vec4(Pi0.zzzz); vec4 iz1 = vec4(Pi1.zzzz); vec4 iw0 = vec4(Pi0.wwww); vec4 iw1 = vec4(Pi1.wwww); vec4 ixy = permute(permute(ix) + iy); vec4 ixy0 = permute(ixy + iz0); vec4 ixy1 = permute(ixy + iz1); vec4 ixy00 = permute(ixy0 + iw0); vec4 ixy01 = permute(ixy0 + iw1); vec4 ixy10 = permute(ixy1 + iw0); vec4 ixy11 = permute(ixy1 + iw1); vec4 gx00 = ixy00 * (1.0 / 7.0); vec4 gy00 = floor(gx00) * (1.0 / 7.0); vec4 gz00 = floor(gy00) * (1.0 / 6.0); gx00 = fract(gx00) - 0.5; gy00 = fract(gy00) - 0.5; gz00 = fract(gz00) - 0.5; vec4 gw00 = vec4(0.75) - abs(gx00) - abs(gy00) - abs(gz00); vec4 sw00 = step(gw00, vec4(0.0)); gx00 -= sw00 * (step(0.0, gx00) - 0.5); gy00 -= sw00 * (step(0.0, gy00) - 0.5); vec4 gx01 = ixy01 * (1.0 / 7.0); vec4 gy01 = floor(gx01) * (1.0 / 7.0); vec4 gz01 = floor(gy01) * (1.0 / 6.0); gx01 = fract(gx01) - 0.5; gy01 = fract(gy01) - 0.5; gz01 = fract(gz01) - 0.5; vec4 gw01 = vec4(0.75) - abs(gx01) - abs(gy01) - abs(gz01); vec4 sw01 = step(gw01, vec4(0.0)); gx01 -= sw01 * (step(0.0, gx01) - 0.5); gy01 -= sw01 * (step(0.0, gy01) - 0.5); vec4 gx10 = ixy10 * (1.0 / 7.0); vec4 gy10 = floor(gx10) * (1.0 / 7.0); vec4 gz10 = floor(gy10) * (1.0 / 6.0); gx10 = fract(gx10) - 0.5; gy10 = fract(gy10) - 0.5; gz10 = fract(gz10) - 0.5; vec4 gw10 = vec4(0.75) - abs(gx10) - abs(gy10) - abs(gz10); vec4 sw10 = step(gw10, vec4(0.0)); gx10 -= sw10 * (step(0.0, gx10) - 0.5); gy10 -= sw10 * (step(0.0, gy10) - 0.5); vec4 gx11 = ixy11 * (1.0 / 7.0); vec4 gy11 = floor(gx11) * (1.0 / 7.0); vec4 gz11 = floor(gy11) * (1.0 / 6.0); gx11 = fract(gx11) - 0.5; gy11 = fract(gy11) - 0.5; gz11 = fract(gz11) - 0.5; vec4 gw11 = vec4(0.75) - abs(gx11) - abs(gy11) - abs(gz11); vec4 sw11 = step(gw11, vec4(0.0)); gx11 -= sw11 * (step(0.0, gx11) - 0.5); gy11 -= sw11 * (step(0.0, gy11) - 0.5); vec4 g0000 = vec4(gx00.x,gy00.x,gz00.x,gw00.x); vec4 g1000 = vec4(gx00.y,gy00.y,gz00.y,gw00.y); vec4 g0100 = vec4(gx00.z,gy00.z,gz00.z,gw00.z); vec4 g1100 = vec4(gx00.w,gy00.w,gz00.w,gw00.w); vec4 g0010 = vec4(gx10.x,gy10.x,gz10.x,gw10.x); vec4 g1010 = vec4(gx10.y,gy10.y,gz10.y,gw10.y); vec4 g0110 = vec4(gx10.z,gy10.z,gz10.z,gw10.z); vec4 g1110 = vec4(gx10.w,gy10.w,gz10.w,gw10.w); vec4 g0001 = vec4(gx01.x,gy01.x,gz01.x,gw01.x); vec4 g1001 = vec4(gx01.y,gy01.y,gz01.y,gw01.y); vec4 g0101 = vec4(gx01.z,gy01.z,gz01.z,gw01.z); vec4 g1101 = vec4(gx01.w,gy01.w,gz01.w,gw01.w); vec4 g0011 = vec4(gx11.x,gy11.x,gz11.x,gw11.x); vec4 g1011 = vec4(gx11.y,gy11.y,gz11.y,gw11.y); vec4 g0111 = vec4(gx11.z,gy11.z,gz11.z,gw11.z); vec4 g1111 = vec4(gx11.w,gy11.w,gz11.w,gw11.w); vec4 norm00 = taylorInvSqrt(vec4(dot(g0000, g0000), dot(g0100, g0100), dot(g1000, g1000), dot(g1100, g1100))); g0000 *= norm00.x; g0100 *= norm00.y; g1000 *= norm00.z; g1100 *= norm00.w; vec4 norm01 = taylorInvSqrt(vec4(dot(g0001, g0001), dot(g0101, g0101), dot(g1001, g1001), dot(g1101, g1101))); g0001 *= norm01.x; g0101 *= norm01.y; g1001 *= norm01.z; g1101 *= norm01.w; vec4 norm10 = taylorInvSqrt(vec4(dot(g0010, g0010), dot(g0110, g0110), dot(g1010, g1010), dot(g1110, g1110))); g0010 *= norm10.x; g0110 *= norm10.y; g1010 *= norm10.z; g1110 *= norm10.w; vec4 norm11 = taylorInvSqrt(vec4(dot(g0011, g0011), dot(g0111, g0111), dot(g1011, g1011), dot(g1111, g1111))); g0011 *= norm11.x; g0111 *= norm11.y; g1011 *= norm11.z; g1111 *= norm11.w; float n0000 = dot(g0000, Pf0); float n1000 = dot(g1000, vec4(Pf1.x, Pf0.yzw)); float n0100 = dot(g0100, vec4(Pf0.x, Pf1.y, Pf0.zw)); float n1100 = dot(g1100, vec4(Pf1.xy, Pf0.zw)); float n0010 = dot(g0010, vec4(Pf0.xy, Pf1.z, Pf0.w)); float n1010 = dot(g1010, vec4(Pf1.x, Pf0.y, Pf1.z, Pf0.w)); float n0110 = dot(g0110, vec4(Pf0.x, Pf1.yz, Pf0.w)); float n1110 = dot(g1110, vec4(Pf1.xyz, Pf0.w)); float n0001 = dot(g0001, vec4(Pf0.xyz, Pf1.w)); float n1001 = dot(g1001, vec4(Pf1.x, Pf0.yz, Pf1.w)); float n0101 = dot(g0101, vec4(Pf0.x, Pf1.y, Pf0.z, Pf1.w)); float n1101 = dot(g1101, vec4(Pf1.xy, Pf0.z, Pf1.w)); float n0011 = dot(g0011, vec4(Pf0.xy, Pf1.zw)); float n1011 = dot(g1011, vec4(Pf1.x, Pf0.y, Pf1.zw)); float n0111 = dot(g0111, vec4(Pf0.x, Pf1.yzw)); float n1111 = dot(g1111, Pf1); vec4 fade_xyzw = fade(Pf0); vec4 n_0w = mix(vec4(n0000, n1000, n0100, n1100), vec4(n0001, n1001, n0101, n1101), fade_xyzw.w); vec4 n_1w = mix(vec4(n0010, n1010, n0110, n1110), vec4(n0011, n1011, n0111, n1111), fade_xyzw.w); vec4 n_zw = mix(n_0w, n_1w, fade_xyzw.z); vec2 n_yzw = mix(n_zw.xy, n_zw.zw, fade_xyzw.y); float n_xyzw = mix(n_yzw.x, n_yzw.y, fade_xyzw.x); return 2.2 * n_xyzw; } #endif <|start_filename|>math/saturateMediump.glsl<|end_filename|> /* author: <NAME> description: clamp a value between 0 and the medium precision max (65504.0) for floating points use: saturateMediump(<float|vec2|vec3|vec4> value) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_SATURATEMEDIUMP #define FNC_SATURATEMEDIUMP #ifndef MEDIUMP_FLT_MAX #define MEDIUMP_FLT_MAX 65504.0 #endif #if defined(TARGET_MOBILE) || defined(PLATFORM_WEBGL) || defined(PLATFORM_RPI) #define saturateMediump(x) min(x, MEDIUMP_FLT_MAX) #else #define saturateMediump(x) x #endif #endif <|start_filename|>animation/easing/elastic.glsl<|end_filename|> #include "../../math/const.glsl" /* author: <NAME> (https://github.com/hughsk) description: elastic easing. From https://github.com/stackgl/glsl-easings use: elastic<In|Out|InOut>(<float> x) license: | This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_ELASTICIN #define FNC_ELASTICIN float elasticIn(in float t) { return sin(13.0 * t * HALF_PI) * pow(2.0, 10.0 * (t - 1.0)); } #endif #ifndef FNC_ELASTICOUT #define FNC_ELASTICOUT float elasticOut(in float t) { return sin(-13.0 * (t + 1.0) * HALF_PI) * pow(2.0, -10.0 * t) + 1.0; } #endif #ifndef FNC_ELASTICINOUT #define FNC_ELASTICINOUT float elasticInOut(in float t) { return t < 0.5 ? 0.5 * sin(+13.0 * HALF_PI * 2.0 * t) * pow(2.0, 10.0 * (2.0 * t - 1.0)) : 0.5 * sin(-13.0 * HALF_PI * ((2.0 * t - 1.0) + 1.0)) * pow(2.0, -10.0 * (2.0 * t - 1.0)) + 1.0; } #endif <|start_filename|>lighting/light/falloff.glsl<|end_filename|> #ifndef FNC_LIGHT_FALLOFF #define FNC_LIGHT_FALLOFF float falloff(float _dist, float _lightRadius) { float att = clamp(1.0 - _dist * _dist / (_lightRadius * _lightRadius), 0.0, 1.0); att *= att; return att; } #endif <|start_filename|>color/blend/lighten.glsl<|end_filename|> /* author: <NAME> description: Photoshop Lighten blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendLighten(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDLIGHTEN #define FNC_BLENDLIGHTEN float blendLighten(in float base, in float blend) { return max(blend, base); } vec3 blendLighten(in vec3 base, in vec3 blend) { return vec3(blendLighten(base.r, blend.r), blendLighten(base.g, blend.g), blendLighten(base.b, blend.b)); } vec3 blendLighten(in vec3 base, in vec3 blend, in float opacity) { return (blendLighten(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>color/blend/overlay.glsl<|end_filename|> /* author: <NAME> description: Photoshop Overlay blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendOverlay(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDOVERLAY #define FNC_BLENDOVERLAY float blendOverlay(in float base, in float blend) { return (base < .5)? (2.*base*blend): (1. - 2. * (1. - base) * (1. - blend)); } vec3 blendOverlay(in vec3 base, in vec3 blend) { return vec3(blendOverlay(base.r, blend.r), blendOverlay(base.g, blend.g), blendOverlay(base.b, blend.b)); } vec3 blendOverlay(in vec3 base, in vec3 blend, in float opacity) { return (blendOverlay(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/common/beckmann.glsl<|end_filename|> #ifndef FNC_BECKMANN #define FNC_BECKMANN // https://github.com/glslify/glsl-specular-beckmann float beckmann(float _NoH, float roughness) { float NoH = max(_NoH, 0.0001); float cos2Alpha = NoH * NoH; float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha; float roughness2 = roughness * roughness; float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha; return exp(tan2Alpha / roughness2) / denom; } #endif <|start_filename|>lighting/specular.glsl<|end_filename|> #include "specular/phong.glsl" #include "specular/blinnPhong.glsl" #include "specular/cookTorrance.glsl" #include "specular/gaussian.glsl" #include "specular/beckmann.glsl" #include "specular/ggx.glsl" /* author: <NAME> description: calculate specular contribution use: - specular(<vec3> L, <vec3> N, <vec3> V, <float> roughne#ifndef TONEMAP_FNC #define TONEMAP_FNC tonemapReinhard #endifss [, <float> fresnel]) - specular(<vec3> L, <vec3> N, <vec3> V, <float> NoV, <float> NoL, <float> roughness, <float> fresnel) options: - SPECULAR_FNC: specularGaussian, specularBeckmann, specularCookTorrance (default), specularPhongRoughness, specularBlinnPhongRoughnes (default on mobile) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SPECULAR_FNC #if defined(TARGET_MOBILE) || defined(PLATFORM_RPI) || defined(PLATFORM_WEBGL) #define SPECULAR_FNC specularBlinnPhongRoughnes #else #define SPECULAR_FNC specularCookTorrance #endif #endif #ifndef FNC_SPECULAR #define FNC_SPECULAR float specular(vec3 L, vec3 N, vec3 V, float roughness) { return SPECULAR_FNC(L, N, V, roughness); } float specular(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { return SPECULAR_FNC(L, N, V, roughness, fresnel); } float specular(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness, float fresnel) { return SPECULAR_FNC(L, N, V, NoV, NoL, roughness, fresnel); } #endif <|start_filename|>lighting/common/smithGGXCorrelated.glsl<|end_filename|> #include "../../math/saturateMediump.glsl" #ifndef FNC_SMITH_GGX_CORRELATED #define FNC_SMITH_GGX_CORRELATED float smithGGXCorrelated(float NoV, float NoL, float roughness) { // Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs" float a2 = roughness * roughness; // TODO: lambdaV can be pre-computed for all the lights, it should be moved out of this function float lambdaV = NoL * sqrt((NoV - a2 * NoV) * NoV + a2); float lambdaL = NoV * sqrt((NoL - a2 * NoL) * NoL + a2); float v = 0.5 / (lambdaV + lambdaL); // a2=0 => v = 1 / 4*NoL*NoV => min=1/4, max=+inf // a2=1 => v = 1 / 2*(NoL+NoV) => min=1/4, max=+inf // clamp to the maximum value representable in mediump return saturateMediump(v); } float smithGGXCorrelated_Fast(float NoV, float NoL, float roughness) { // Hammon 2017, "PBR Diffuse Lighting for GGX+Smith Microsurfaces" float v = 0.5 / mix(2.0 * NoL * NoV, NoL + NoV, roughness); return saturateMediump(v); } #endif <|start_filename|>lighting/common/ggx.glsl<|end_filename|> #ifndef ONE_OVER_PI #define ONE_OVER_PI 0.31830988618 #endif #include "../../math/saturateMediump.glsl" #ifndef FNC_GGX #define FNC_GGX // Walter et al. 2007, "Microfacet Models for Refraction through Rough Surfaces" // In mediump, there are two problems computing 1.0 - NoH^2 // 1) 1.0 - NoH^2 suffers floating point cancellation when NoH^2 is close to 1 (highlights) // 2) NoH doesn't have enough precision around 1.0 // Both problem can be fixed by computing 1-NoH^2 in highp and providing NoH in highp as well // However, we can do better using Lagrange's identity: // ||a x b||^2 = ||a||^2 ||b||^2 - (a . b)^2 // since N and H are unit vectors: ||N x H||^2 = 1.0 - NoH^2 // This computes 1.0 - NoH^2 directly (which is close to zero in the highlights and has // enough precision). // Overall this yields better performance, keeping all computations in mediump float GGX(float NoH, float linearRoughness) { float oneMinusNoHSquared = 1.0 - NoH * NoH; float a = NoH * linearRoughness; float k = linearRoughness / (oneMinusNoHSquared + a * a); float d = k * k * ONE_OVER_PI; return saturateMediump(d); } float GGX(vec3 N, vec3 H, float NoH, float linearRoughness) { vec3 NxH = cross(N, H); float oneMinusNoHSquared = dot(NxH, NxH); float a = NoH * linearRoughness; float k = linearRoughness / (oneMinusNoHSquared + a * a); float d = k * k * ONE_OVER_PI; return saturateMediump(d); } #endif <|start_filename|>lighting/specular/gaussian.glsl<|end_filename|> #ifndef FNC_SPECULAR_GAUSSIAN #define FNC_SPECULAR_GAUSSIAN // https://github.com/glslify/glsl-specular-gaussian float specularGaussian(vec3 L, vec3 N, vec3 V, float roughness) { vec3 H = normalize(L + V); float theta = acos(dot(H, N)); float w = theta / roughness; return exp(-w*w); } float specularGaussian(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { return specularGaussian(L, N, V, roughness); } float specularGaussian(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness, float fresnel) { return specularGaussian(L, N, V, roughness); } #endif <|start_filename|>generative/random.glsl<|end_filename|> /* author: <NAME> description: pass a value and get some random normalize value between 0 and 1 use: float random[2|3](<float|vec2|vec3> value) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_RANDOM #define FNC_RANDOM float random(in float x) { return fract(sin(x) * 43758.5453); } float random(in vec2 st) { return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453); } float random(in vec3 pos) { return fract(sin(dot(pos.xyz, vec3(70.9898, 78.233, 32.4355))) * 43758.5453123); } float random(in vec4 pos) { float dot_product = dot(pos, vec4(12.9898,78.233,45.164,94.673)); return fract(sin(dot_product) * 43758.5453); } // Hash function from https://www.shadertoy.com/view/4djSRW #ifndef RANDOM_SCALE3 #define RANDOM_SCALE3 vec3(.1031, .1030, .0973) #endif #ifndef FANDOM_SCALE4 #define FANDOM_SCALE4 vec4(1031, .1030, .0973, .1099) #endif vec2 random2(float p) { vec3 p3 = fract(vec3(p) * RANDOM_SCALE3); p3 += dot(p3, p3.yzx + 19.19); return fract((p3.xx+p3.yz)*p3.zy); } vec2 random2(in vec2 st) { const vec2 k = vec2(.3183099, .3678794); st = st * k + k.yx; return -1. + 2. * fract(16. * k * fract(st.x * st.y * (st.x + st.y))); } vec2 random2(vec3 p3) { p3 = fract(p3 * RANDOM_SCALE3); p3 += dot(p3, p3.yzx+19.19); return fract((p3.xx+p3.yz)*p3.zy); } vec3 random3(float p) { vec3 p3 = fract(vec3(p) * RANDOM_SCALE3); p3 += dot(p3, p3.yzx+19.19); return fract((p3.xxy+p3.yzz)*p3.zyx); } vec3 random3(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * RANDOM_SCALE3); p3 += dot(p3, p3.yxz+19.19); return fract((p3.xxy+p3.yzz)*p3.zyx); } vec3 random3(in vec3 p) { p = vec3( dot(p, vec3(127.1, 311.7, 74.7)), dot(p, vec3(269.5, 183.3, 246.1)), dot(p, vec3(113.5, 271.9, 124.6))); return -1. + 2. * fract(sin(p) * 43758.5453123); } vec4 random4(float p) { vec4 p4 = fract(vec4(p) * FANDOM_SCALE4); p4 += dot(p4, p4.wzxy+19.19); return fract((p4.xxyz+p4.yzzw)*p4.zywx); } vec4 random4(vec2 p) { vec4 p4 = fract(vec4(p.xyxy) * FANDOM_SCALE4); p4 += dot(p4, p4.wzxy+19.19); return fract((p4.xxyz+p4.yzzw)*p4.zywx); } vec4 random4(vec3 p) { vec4 p4 = fract(vec4(p.xyzx) * FANDOM_SCALE4); p4 += dot(p4, p4.wzxy+19.19); return fract((p4.xxyz+p4.yzzw)*p4.zywx); } vec4 random4(vec4 p4) { p4 = fract(p4 * FANDOM_SCALE4); p4 += dot(p4, p4.wzxy+19.19); return fract((p4.xxyz+p4.yzzw)*p4.zywx); } #endif <|start_filename|>color/space/YCbCr2rgb.glsl<|end_filename|> /* author: <NAME> description: convert YCbCr to RGB according to https://en.wikipedia.org/wiki/YCbCr use: YCbCr2rgb(<vec3|vec4> color) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_YCBCR2RGB #define FNC_YCBCR2RGB vec3 YCbCr2rgb(in vec3 ycbcr) { float cb = ycbcr.y - .5; float cr = ycbcr.z - .5; float y = ycbcr.x; float r = 1.402 * cr; float g = -.344 * cb - .714 * cr; float b = 1.772 * cb; return vec3(r, g, b) + y; } vec4 YCbCr2rgb(in vec4 ycbcr) { return vec4(YCbCr2rgb(ycbcr.rgb),ycbcr.a); } #endif <|start_filename|>color/blend/colorDodge.glsl<|end_filename|> /* author: <NAME> description: Photoshop Color Dodge blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendColorDodge(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDCOLORDODGE #define FNC_BLENDCOLORDODGE float blendColorDodge(in float base, in float blend) { return (blend == 1.)? blend: min( base / (1. - blend), 1.); } vec3 blendColorDodge(in vec3 base, in vec3 blend) { return vec3(blendColorDodge(base.r, blend.r), blendColorDodge(base.g, blend.g), blendColorDodge(base.b, blend.b)); } vec3 blendColorDodge(in vec3 base, in vec3 blend, in float opacity) { return (blendColorDodge(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/material/metallic.glsl<|end_filename|> #include "../toMetallic.glsl" #include "specular.glsl" /* author: <NAME> description: get material metalic property from GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: vec4 materialMetallic() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_METALLIC #define FNC_MATERIAL_METALLIC #ifdef MATERIAL_METALLICMAP uniform sampler2D MATERIAL_METALLICMAP; #endif #if defined(MATERIAL_ROUGHNESSMETALLICMAP) && !defined(MATERIAL_ROUGHNESSMETALLICMAP_UNIFORM) #define MATERIAL_ROUGHNESSMETALLICMAP_UNIFORM uniform sampler2D MATERIAL_ROUGHNESSMETALLICMAP; #endif #if defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP) && !defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP_UNIFORM) #define MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP_UNIFORM uniform sampler2D MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP; #endif float materialMetallic() { float metallic = 0.0; #if defined(MATERIAL_METALLICMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; #if defined(MATERIAL_METALLICMAP_OFFSET) uv += (MATERIAL_METALLICMAP_OFFSET).xy; #endif #if defined(MATERIAL_METALLICMAP_SCALE) uv *= (MATERIAL_METALLICMAP_SCALE).xy; #endif metallic = texture2D(MATERIAL_METALLICMAP, uv).b; #elif defined(MATERIAL_ROUGHNESSMETALLICMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; metallic = texture2D(MATERIAL_ROUGHNESSMETALLICMAP, uv).b; #elif defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; metallic = texture2D(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP, uv).b; #elif defined(MATERIAL_METALLIC) metallic = MATERIAL_METALLIC; #else vec3 diffuse = materialBaseColor().rgb; vec3 specular = materialSpecular(); metallic = toMetallic(diffuse, specular); #endif return metallic; } #endif <|start_filename|>filter/noiseBlur.glsl<|end_filename|> /* author: <NAME> description: white noise blur based on this shader https://www.shadertoy.com/view/XsVBDR use: noiseBlur(<sampler2D> texture, <vec2> st, <vec2> pixel, <float> radius) options: NOISEBLUR_TYPE: default to vec3 NOISEBLUR_GAUSSIAN_K: no gaussian by default NOISEBLUR_RANDOM23_FNC(UV): defaults to random2(UV) NOISEBLUR_SAMPLER_FNC(UV): defualts to texture2D(tex, UV).rgb NOISEBLUR_SAMPLES: default to 4 licence: | TODO */ #include "../math/const.glsl" #define RANDOM_SCALE3 vec3(443.897, 441.423, .0973) #include "../generative/random.glsl" #ifndef NOISEBLUR_SAMPLES #define NOISEBLUR_SAMPLES 4.0 #endif #ifndef NOISEBLUR_TYPE #define NOISEBLUR_TYPE vec4 #endif #ifndef NOISEBLUR_SAMPLER_FNC #define NOISEBLUR_SAMPLER_FNC(UV) texture2D(tex, UV) #endif #ifndef NOISEBLUR_RANDOM23_FNC #define NOISEBLUR_RANDOM23_FNC(UV) random2(UV) #endif #ifndef FNC_NOISEBLUR #define FNC_NOISEBLUR NOISEBLUR_TYPE noiseBlur(in sampler2D tex, in vec2 st, in vec2 pixel, float radius) { float blurRadius = radius; vec2 whiteNoiseUV = st; NOISEBLUR_TYPE result = NOISEBLUR_TYPE(0.0); for (float i = 0.0; i < NOISEBLUR_SAMPLES; ++i) { vec2 whiteNoiseRand = NOISEBLUR_RANDOM23_FNC(vec3(whiteNoiseUV.xy, i)); whiteNoiseUV = whiteNoiseRand; vec2 r = whiteNoiseRand; r.x *= TAU; #if defined(NOISEBLUR_GAUSSIAN_K) // box-muller transform to get gaussian distributed sample points in the circle vec2 cr = vec2(sin(r.x),cos(r.x))*sqrt(-NOISEBLUR_GAUSSIAN_K * log(r.y)); #else // uniform sample the circle vec2 cr = vec2(sin(r.x),cos(r.x))*sqrt(r.y); #endif NOISEBLUR_TYPE color = NOISEBLUR_SAMPLER_FNC( st + cr * blurRadius * pixel ); // average the samples as we get em // https://blog.demofox.org/2016/08/23/incremental-averaging/ result = mix(result, color, 1.0 / (i+1.0)); } return result; } NOISEBLUR_TYPE softBlur(sampler2D tex, vec2 st, vec2 pixel) { NOISEBLUR_TYPE rta = NOISEBLUR_TYPE(0.0); float total = 0.0; float offset = random(vec3(12.9898 + st.x, 78.233 + st.y, 151.7182)); for (float t = -NOISEBLUR_SAMPLES; t <= NOISEBLUR_SAMPLES; t++) { float percent = (t / NOISEBLUR_SAMPLES) + offset - 0.5; float weight = 1.0 - abs(percent); NOISEBLUR_TYPE sample = NOISEBLUR_SAMPLER_FNC(st + pixel * percent); rta += sample * weight; total += weight; } return rta / total; } #endif <|start_filename|>filter/convolutionPyramid/downscale.glsl<|end_filename|> #include "../../math/absi.glsl" #ifndef CONVOLUTIONPYRAMID_H1 #define CONVOLUTIONPYRAMID_H1 1.0334, 0.6836, 0.1507 #endif #ifndef FNC_CONVOLUTIONPYRAMID_DOWNSCALE #define FNC_CONVOLUTIONPYRAMID_DOWNSCALE vec4 convolutionPyramidDownscale(sampler2D tex, vec2 st, vec2 pixel) { const vec3 h1 = vec3(CONVOLUTIONPYRAMID_H1); vec4 color = vec4(0.0); for (int dy = -2; dy <= 2; dy++) { for (int dx = -2; dx <= 2; dx++) { vec2 uv = st + vec2(float(dx), float(dy)) * pixel; if (uv.x <= 0.0 || uv.x >= 1.0 || uv.y <= 0.0 || uv.y >= 1.0) continue; color += texture2D(tex, uv) * h1[ absi(dx) ] * h1[ absi(dy) ]; } } return color; } #endif <|start_filename|>lighting/material/occlusion.glsl<|end_filename|> /* author: <NAME> description: get material normal property from GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: vec4 materialOcclusion() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_OCCLUSION #define FNC_MATERIAL_OCCLUSION #ifdef MATERIAL_OCCLUSIONMAP uniform sampler2D MATERIAL_OCCLUSIONMAP; #endif #if defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP) && !defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP_UNIFORM) #define MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP_UNIFORM uniform sampler2D MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP; #endif float materialOcclusion() { float occlusion = 1.0; #if defined(MATERIAL_OCCLUSIONMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; occlusion = texture2D(MATERIAL_OCCLUSIONMAP, uv).r; #elif defined(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP) && defined(MODEL_VERTEX_TEXCOORD) vec2 uv = v_texcoord.xy; occlusion = texture2D(MATERIAL_OCCLUSIONROUGHNESSMETALLICMAP, uv).r; #endif #if defined(MATERIAL_OCCLUSIONMAP_STRENGTH) occlusion *= MATERIAL_OCCLUSIONMAP_STRENGTH; #endif return occlusion; } #endif <|start_filename|>sdf/vesicaSDF.glsl<|end_filename|> #include "circleSDF.glsl" /* author: <NAME> description: Returns an almond-shaped sdf use: vesicaSDF(<vec2> st, <float> w) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_VESICASDF #define FNC_VESICASDF float vesicaSDF(in vec2 st, in float w) { vec2 offset = vec2(w*.5,0.); return max( circleSDF(st-offset), circleSDF(st+offset)); } #endif <|start_filename|>color/blend/average.glsl<|end_filename|> /* author: <NAME> description: Photoshop Average blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendAverage(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDAVERAGE #define FNC_BLENDAVERAGE float blendAverage(in float base, in float blend) { return (base + blend) * .5; } vec3 blendAverage(in vec3 base, in vec3 blend) { return (base + blend) * .5; } vec3 blendAverage(in vec3 base, in vec3 blend, float opacity) { return (blendAverage(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/material/normal.glsl<|end_filename|> /* author: <NAME> description: get material normal property from GlslViewer's defines https://github.com/patriciogonzalezvivo/glslViewer/wiki/GlslViewer-DEFINES#material-defines use: vec4 materialNormal() license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_MATERIAL_NORMAL #define FNC_MATERIAL_NORMAL #ifdef MATERIAL_NORMALMAP uniform sampler2D MATERIAL_NORMALMAP; #endif #ifdef MATERIAL_BUMPMAP_NORMALMAP uniform sampler2D MATERIAL_BUMPMAP_NORMALMAP; #endif vec3 materialNormal() { vec3 normal = vec3(0.0, 0.0, 1.0); #ifdef MODEL_VERTEX_NORMAL normal = v_normal; #if defined(MODEL_VERTEX_TANGENT) && defined(MODEL_VERTEX_TEXCOORD) && defined(MATERIAL_NORMALMAP) vec2 uv = v_texcoord.xy; #if defined(MATERIAL_NORMALMAP_OFFSET) uv += (MATERIAL_NORMALMAP_OFFSET).xy; #endif #if defined(MATERIAL_NORMALMAP_SCALE) uv *= (MATERIAL_NORMALMAP_SCALE).xy; #endif normal = texture2D(MATERIAL_NORMALMAP, uv).xyz; normal = v_tangentToWorld * (normal * 2.0 - 1.0); #elif defined(MODEL_VERTEX_TANGENT) && defined(MODEL_VERTEX_TEXCOORD) && defined(MATERIAL_BUMPMAP_NORMALMAP) vec2 uv = v_texcoord.xy; #if defined(MATERIAL_BUMPMAP_OFFSET) uv += (MATERIAL_BUMPMAP_OFFSET).xy; #endif #if defined(MATERIAL_BUMPMAP_SCALE) uv *= (MATERIAL_BUMPMAP_SCALE).xy; #endif normal = v_tangentToWorld * (texture2D(MATERIAL_BUMPMAP_NORMALMAP, uv).xyz * 2.0 - 1.0); #endif #endif return normal; } #endif <|start_filename|>space/rotateZ.glsl<|end_filename|> #include "../math/rotate4dZ.glsl" /* function: rotateZ author: <NAME> description: rotate a 2D space by a radian angle use: rotateZ(<vec3|vec4> pos, float radian [, vec3 center]) options: - CENTER_3D license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_ROTATEZ #define FNC_ROTATEZ vec3 rotateZ(in vec3 pos, in float radian, in vec3 center) { return (rotate4dZ(radian) * vec4(pos - center, 0.) ).xyz + center; } vec3 rotateZ(in vec3 pos, in float radian) { #ifdef CENTER_3D return rotateZ(pos, radian, CENTER_3D); #else return rotateZ(pos, radian, vec3(.0)); #endif } #endif <|start_filename|>color/blend/linearBurn.glsl<|end_filename|> /* author: <NAME> description: Photoshop Linear Burn blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendLinearBurn(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDLINEARBURN #define FNC_BLENDLINEARBURN float blendLinearBurn(in float base, in float blend) { // Note : Same implementation as BlendSubtractf return max(base + blend - 1., 0.); } vec3 blendLinearBurn(in vec3 base, in vec3 blend) { // Note : Same implementation as BlendSubtract return max(base + blend - vec3(1.), vec3(0.)); } vec3 blendLinearBurn(in vec3 base, in vec3 blend, in float opacity) { return (blendLinearBurn(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>color/space/rgb2hsv.glsl<|end_filename|> /* author: <NAME> description: pass a color in RGB and get HSB color. From http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl use: rgb2hsv(<vec3|vec4> color) licence: TODO */ #ifndef FNC_RGB2HSV #define FNC_RGB2HSV vec3 rgb2hsv(in vec3 c) { vec4 K = vec4(0., -.33333333333333333333, .6666666666666666666, -1.); #ifdef RGB2HSV_MIX vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); #else vec4 p = c.g < c.b ? vec4(c.bg, K.wz) : vec4(c.gb, K.xy); vec4 q = c.r < p.x ? vec4(p.xyw, c.r) : vec4(c.r, p.yzx); #endif float d = q.x - min(q.w, q.y); float e = 1.0e-10; return vec3(abs(q.z + (q.w - q.y) / (6. * d + e)), d / (q.x + e), q.x); } vec4 rgb2hsv(in vec4 c) { return vec4(rgb2hsv(c.rgb), c.a); } #endif <|start_filename|>sdf/circleSDF.glsl<|end_filename|> /* author: <NAME> description: Returns a circle-shaped SDF. use: circleSDF(vec2 st[, vec2 center]) options: CIRCLESDF_FNC(POS_UV) : function used to calculate the SDF, defaults to GLSL length function, use lengthSq for a different slope license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef CIRCLESDF_FNC #define CIRCLESDF_FNC(POS_UV) length(POS_UV) #endif #ifndef FNC_CIRCLESDF #define FNC_CIRCLESDF float circleSDF(in vec2 st, in vec2 center) { return CIRCLESDF_FNC(st - center) * 2.; } float circleSDF(in vec2 st) { return circleSDF(st, vec2(.5)); } #endif <|start_filename|>lighting/fresnel.glsl<|end_filename|> #include "common/schlick.glsl" #include "envMap.glsl" #include "fakeCube.glsl" #include "sphericalHarmonics.glsl" #include "../color/tonemap.glsl" #include "../math/saturate.glsl" /* author: <NAME> description: resolve fresnel coeficient use: - <vec3> fresnel(const <vec3> f0, <float> LoH) - <vec3> fresnel(<vec3> _R, <vec3> _f0, <float> _NoV) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_FRESNEL #define FNC_FRESNEL vec3 fresnel(const vec3 f0, float LoH) { #if defined(TARGET_MOBILE) || defined(PLATFORM_RPI) || defined(PLATFORM_WEBGL) return schlick(f0, 1.0, LoH); #else float f90 = saturate(dot(f0, vec3(50.0 * 0.33))); return schlick(f0, f90, LoH); #endif } vec3 fresnel(vec3 _R, vec3 _f0, float _NoV) { vec3 frsnl = fresnel(_f0, _NoV); vec3 reflectColor = vec3(0.0); #if defined(SCENE_SH_ARRAY) reflectColor = tonemap( sphericalHarmonics(_R) ); #else reflectColor = fakeCube(_R); #endif return reflectColor * frsnl; } float fresnelf(vec3 V, vec3 N, float R0) { float cosAngle = 1.0-max(dot(V, N), 0.0); float result = cosAngle * cosAngle; result = result * result; result = result * cosAngle; result = clamp(result * (1.0 - R0) + R0, 0.0, 1.0); return result; } #endif <|start_filename|>distort/barrel.glsl<|end_filename|> #include "../math/lengthSq.glsl" /* author: <NAME> description: Barrel distortion use: barrel(sampler2D tex, <vec2> st, [, <vec2|float> sdf]) options: BARREL_DISTANCE: function used to shape the distortion, defaults to radial shape with lengthSq BARREL_TYPE: return type, defaults to vec3 BARREL_SAMPLER_FNC: function used to sample the input texture, defaults to texture2D(tex, POS_UV).rgb BARREL_OCT_1: one octave of distortion BARREL_OCT_2: two octaves of distortion BARREL_OCT_3: three octaves of distortion license: | Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BARREL_DISTANCE #define BARREL_DISTANCE dist #endif #ifndef BARREL_TYPE #define BARREL_TYPE vec3 #endif #ifndef BARREL_SAMPLER_FNC #define BARREL_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).rgb #endif #ifndef FNC_BARREL #define FNC_BARREL vec2 barrel(vec2 st, float amt, float dist) { return st + (st-.5) * (BARREL_DISTANCE) * amt; } vec2 barrel(vec2 st, float amt) { return barrel(st, amt, lengthSq(st-.5)); } BARREL_TYPE barrel(in sampler2D tex, in vec2 st, float offset) { BARREL_TYPE a1 = BARREL_SAMPLER_FNC( barrel(st, .0, offset)); BARREL_TYPE a2 = BARREL_SAMPLER_FNC( barrel(st, .2, offset)); BARREL_TYPE a3 = BARREL_SAMPLER_FNC( barrel(st, .4, offset)); BARREL_TYPE a4 = BARREL_SAMPLER_FNC( barrel(st, .6, offset)); #ifdef BARREL_OCT_1 return (a1+a2+a3+a4)/4.; #endif BARREL_TYPE a5 = BARREL_SAMPLER_FNC( barrel(st, .8, offset)); BARREL_TYPE a6 = BARREL_SAMPLER_FNC( barrel(st, 1.0, offset)); BARREL_TYPE a7 = BARREL_SAMPLER_FNC( barrel(st, 1.2, offset)); BARREL_TYPE a8 = BARREL_SAMPLER_FNC( barrel(st, 1.4, offset)); #ifdef BARREL_OCT_2 return (a1+a2+a3+a4+a5+a6+a7+a8)/8.; #endif BARREL_TYPE a9 = BARREL_SAMPLER_FNC( barrel(st, 1.6, offset)); BARREL_TYPE a10 = BARREL_SAMPLER_FNC( barrel(st, 1.8, offset)); BARREL_TYPE a11 = BARREL_SAMPLER_FNC( barrel(st, 2.0, offset)); BARREL_TYPE a12 = BARREL_SAMPLER_FNC( barrel(st, 2.2, offset)); return (a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12)/12.; } BARREL_TYPE barrel(in sampler2D tex, in vec2 st, in vec2 offset) { return barrel(tex, st, dot(vec2(.5), offset)); } BARREL_TYPE barrel(in sampler2D tex, in vec2 st) { return barrel(tex, st, lengthSq(st-.5)); } #endif <|start_filename|>math/permute.glsl<|end_filename|> #include "mod289.glsl" /* author: [<NAME>, Ashima Arts] description: permute use: permute(<float|vec2|vec3|vec4> x) license : | Copyright (C) 2011 <NAME>. All rights reserved. Distributed under the MIT License. See LICENSE file. https://github.com/ashima/webgl-noise */ #ifndef FNC_PERMUTE #define FNC_PERMUTE float permute(in float x) { return mod289(((x * 34.) + 1.)*x); } vec3 permute(in vec3 x) { return mod289(((x*34.0)+1.0)*x); } vec4 permute(in vec4 x) { return mod289(((x * 34.) + 1.)*x); } #endif <|start_filename|>animation/easing/quadratic.glsl<|end_filename|> /* author: <NAME> (https://github.com/hughsk) description: quadrtic easing. From https://github.com/stackgl/glsl-easings use: quadratic<In|Out|InOut>(<float> x) license: | This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_QUADRATICIN #define FNC_QUADRATICIN float quadraticIn(in float t) { return t * t; } #endif #ifndef FNC_QUADRATICOUT #define FNC_QUADRATICOUT float quadraticOut(in float t) { return -t * (t - 2.0); } #endif #ifndef FNC_QUADRATICINOUT #define FNC_QUADRATICINOUT float quadraticInOut(in float t) { float p = 2.0 * t * t; return t < 0.5 ? p : -p + (4.0 * t) - 1.0; } #endif <|start_filename|>lighting/diffuse/burley.glsl<|end_filename|> #include "../common/schlick.glsl" /* author: <NAME> description: calculate diffuse contribution using burley equation use: - <float> diffuseBurley(<vec3> light, <vec3> normal [, <vec3> view, <float> roughness] ) - <float> diffuseBurley(<vec3> L, <vec3> N, <vec3> V, <float> NoV, <float> NoL, <float> roughness) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_DIFFUSE_BURLEY #define FNC_DIFFUSE_BURLEY float diffuseBurley(float NoV, float NoL, float LoH, float linearRoughness) { // Burley 2012, "Physically-Based Shading at Disney" float f90 = 0.5 + 2.0 * linearRoughness * LoH * LoH; float lightScatter = schlick(1.0, f90, NoL); float viewScatter = schlick(1.0, f90, NoV); return lightScatter * viewScatter; } float diffuseBurley(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness) { float LoH = max(dot(L, normalize(L + V)), 0.001); return diffuseBurley(NoV, NoL, LoH, roughness * roughness); } float diffuseBurley(vec3 L, vec3 N, vec3 V, float roughness) { vec3 H = normalize(V + L); float NoV = clamp(dot(N, V), 0.001, 1.0); float NoL = clamp(dot(N, L), 0.001, 1.0); float LoH = clamp(dot(L, H), 0.001, 1.0); return diffuseBurley(NoV, NoL, LoH, roughness * roughness); } #endif <|start_filename|>filter/edge/prewitt.glsl<|end_filename|> /* author: <NAME> description: Adapted version of Prewitt edge detection from https://github.com/BradLarson/GPUImage2 use: edgePrewitt(<sampler2D> texture, <vec2> st, <vec2> scale) options: EDGEPREWITT_TYPE: Return type, defaults to float EDGEPREWITT_SAMPLER_FNC: Function used to sample the input texture, defaults to texture2D(tex,POS_UV).r license: | Copyright (c) 2015, <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EDGEPREWITT_TYPE #ifdef EDGE_TYPE #define EDGEPREWITT_TYPE EDGE_TYPE #else #define EDGEPREWITT_TYPE float #endif #endif #ifndef EDGEPREWITT_SAMPLER_FNC #ifdef EDGE_SAMPLER_FNC #define EDGEPREWITT_SAMPLER_FNC(POS_UV) EDGE_SAMPLER_FNC(POS_UV) #else #define EDGEPREWITT_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).r #endif #endif #ifndef FNC_EDGEPREWITT #define FNC_EDGEPREWITT EDGEPREWITT_TYPE edgePrewitt(in sampler2D tex, in vec2 st, in vec2 offset) { // get samples around pixel EDGEPREWITT_TYPE tleft = EDGEPREWITT_SAMPLER_FNC(st + vec2(-offset.x, offset.y)); EDGEPREWITT_TYPE left = EDGEPREWITT_SAMPLER_FNC(st + vec2(-offset.x, 0.)); EDGEPREWITT_TYPE bleft = EDGEPREWITT_SAMPLER_FNC(st + vec2(-offset.x, -offset.y)); EDGEPREWITT_TYPE top = EDGEPREWITT_SAMPLER_FNC(st + vec2(0., offset.y)); EDGEPREWITT_TYPE bottom = EDGEPREWITT_SAMPLER_FNC(st + vec2(0., -offset.y)); EDGEPREWITT_TYPE tright = EDGEPREWITT_SAMPLER_FNC(st + offset); EDGEPREWITT_TYPE right = EDGEPREWITT_SAMPLER_FNC(st + vec2(offset.x, 0.)); EDGEPREWITT_TYPE bright = EDGEPREWITT_SAMPLER_FNC(st + vec2(offset.x, -offset.y)); EDGEPREWITT_TYPE x = -tleft - top - tright + bleft + bottom + bright; EDGEPREWITT_TYPE y = -bleft - left - tleft + bright + right + tright; return sqrt((x * x) + (y * y)); } #endif <|start_filename|>color/daltonize.glsl<|end_filename|> #include "space/rgb2lms.glsl" #include "space/lms2rgb.glsl" /* author: <NAME> description: daltonize functions based on https://web.archive.org/web/20081014161121/http://www.colorjack.com/labs/colormatrix/ http://www.daltonize.org/search/label/Daltonize use: <vec3|vec4> daltonize(<vec3|vec4> rgb) options: DALTONIZE_FNC: daltonizeProtanope, daltonizeProtanopia, daltonizeProtanomaly, daltonizeDeuteranope, daltonizeDeuteranopia, daltonizeDeuteranomaly, daltonizeTritanope, daltonizeTritanopia, daltonizeTritanomaly, daltonizeAchromatopsia and daltonizeAchromatomaly license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef DALTONIZE_FNC #define DALTONIZE_FNC daltonizeProtanope #endif #ifndef FNC_DALTONIZE #define FNC_DALTONIZE // Protanope - reds are greatly reduced (1% men) vec3 daltonizeProtanope(vec3 rgb) { vec3 lms = rgb2lms(rgb); lms.x = 0.0 * lms.x + 2.02344 * lms.y + -2.52581 * lms.z; lms.y = 0.0 * lms.x + 1.0 * lms.y + 0.0 * lms.z; lms.z = 0.0 * lms.x + 0.0 * lms.y + 1.0 * lms.z; return lms2rgb(lms); } vec4 daltonizeProtanope(vec4 rgba) { return vec4(daltonizeProtanope(rgba.rgb), rgba.a); } vec3 daltonizeProtanopia(vec3 rgb) { return vec3(rgb.r * 0.56667 + rgb.g * 0.43333 + rgb.b * 0.00000, rgb.r * 0.55833 + rgb.g * 0.44267 + rgb.b * 0.00000, rgb.r * 0.00000 + rgb.g * 0.24167 + rgb.b * 0.75833); } vec4 daltonizeProtanopia(vec4 rgba) { return vec4(daltonizeProtanopia(rgba.rgb), rgba.a); } vec3 daltonizeProtanomaly(vec3 rgb) { return vec3(rgb.r * 0.81667 + rgb.g * 0.18333 + rgb.b * 0.00000, rgb.r * 0.33333 + rgb.g * 0.66667 + rgb.b * 0.00000, rgb.r * 0.00000 + rgb.g * 0.12500 + rgb.b * 0.87500); } vec4 daltonizeProtanomaly(vec4 rgba) { return vec4(daltonizeProtanomaly(rgba.rgb), rgba.a); } // Deuteranope - greens are greatly reduced (1% men) vec3 daltonizeDeuteranope(vec3 rgb) { vec3 lms = rgb2lms(rgb); lms.x = 1.0 * lms.x + 0.0 * lms.y + 0.0 * lms.z; lms.y = 0.494207 * lms.x + 0.0 * lms.y + 1.24827 * lms.z; lms.z = 0.0 * lms.x + 0.0 * lms.y + 1.0 * lms.z; return lms2rgb(lms); } vec4 daltonizeDeuteranope(vec4 rgba) { return vec4(daltonizeDeuteranope(rgba.rgb), rgba.a); } vec3 daltonizeDeuteranopia(vec3 rgb) { return vec3(rgb.r * 0.62500 + rgb.g * 0.37500 + rgb.b * 0.00000, rgb.r * 0.70000 + rgb.g * 0.30000 + rgb.b * 0.00000, rgb.r * 0.00000 + rgb.g * 0.30000 + rgb.b * 0.70000); } vec4 daltonizeDeuteranopia(vec4 rgba) { return vec4(daltonizeDeuteranopia(rgba.rgb), rgba.a); } vec3 daltonizeDeuteranomaly(vec3 rgb) { return vec3(rgb.r * 0.80000 + rgb.g * 0.20000 + rgb.b * 0.00000, rgb.r * 0.00000 + rgb.g * 0.25833 + rgb.b * 0.74167, rgb.r * 0.00000 + rgb.g * 0.14167 + rgb.b * 0.85833); } vec4 daltonizeDeuteranomaly(vec4 rgba) { return vec4(daltonizeDeuteranomaly(rgba.rgb), rgba.a); } // Tritanope - blues are greatly reduced (0.003% population) vec3 daltonizeTritanope(vec3 rgb) { vec3 lms = rgb2lms(rgb); // Simulate rgb blindness lms.x = 1.0 * lms.x + 0.0 * lms.y + 0.0 * lms.z; lms.y = 0.0 * lms.x + 1.0 * lms.y + 0.0 * lms.z; lms.z = -0.395913 * lms.x + 0.801109 * lms.y + 0.0 * lms.z; return lms2rgb(lms); } vec4 daltonizeTritanope(vec4 rgba) { return vec4(daltonizeTritanope(rgba.rgb), rgba.a); } vec3 daltonizeTritanopia(vec3 rgb) { return vec3(rgb.r * 0.95 + rgb.g * 0.05 + rgb.b * 0.00000, rgb.r * 0.00000 + rgb.g * 0.43333 + rgb.b * 0.56667, rgb.r * 0.00000 + rgb.g * 0.47500 + rgb.b * 0.52500); } vec4 daltonizeTritanopia(vec4 rgba) { return vec4(daltonizeTritanopia(rgba.rgb), rgba.a); } vec3 daltonizeTritanomaly(vec3 rgb) { return vec3(rgb.r * 0.96667 + rgb.g * 0.33333 + rgb.b * 0.00000, rgb.r * 0.00000 + rgb.g * 0.73333 + rgb.b * 0.26667, rgb.r * 0.00000 + rgb.g * 0.18333 + rgb.b * 0.81667); } vec4 daltonizeTritanomaly(vec4 rgba) { return vec4(daltonizeTritanomaly(rgba.rgb), rgba.a); } vec3 daltonizeAchromatopsia(vec3 rgb) { return vec3(rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114, rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114, rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114); } vec4 daltonizeAchromatopsia(vec4 rgba) { return vec4(daltonizeAchromatopsia(rgba.rgb), rgba.a); } vec3 daltonizeAchromatomaly(vec3 rgb) { return vec3(rgb.r * 0.618 + rgb.g * 0.320 + rgb.b * 0.062, rgb.r * 0.163 + rgb.g * 0.775 + rgb.b * 0.062, rgb.r * 0.163 + rgb.g * 0.320 + rgb.b * 0.516); } vec4 daltonizeAchromatomaly(vec4 rgba) { return vec4(daltonizeAchromatomaly(rgba.rgb), rgba.a); } // GENERAL FUNCTION vec3 daltonize(vec3 rgb) { return DALTONIZE_FNC(rgb); } vec4 daltonize( vec4 rgba ) { return DALTONIZE_FNC(rgba); } // From https://gist.github.com/jcdickinson/580b7fb5cc145cee8740 // vec3 daltonizeCorrection(vec3 rgb) { // Isolate invisible rgbs to rgb vision deficiency (calculate error matrix) vec3 error = (rgb - daltonize(rgb)); // Shift rgbs towards visible spectrum (apply error modifications) vec3 correction; correction.r = 0.0; // (error.r * 0.0) + (error.g * 0.0) + (error.b * 0.0); correction.g = (error.r * 0.7) + (error.g * 1.0); // + (error.b * 0.0); correction.b = (error.r * 0.7) + (error.b * 1.0); // + (error.g * 0.0); // Add compensation to original values correction = rgb + correction; return correction.rgb; } vec4 daltonizeCorrection(vec4 rgb) { return vec4(daltonizeCorrection( rgb.rgb ), rgb.a); } #endif <|start_filename|>sdf/rectSDF.glsl<|end_filename|> /* author: <NAME> description: Returns a rectangular SDF use: rectSDF(<vec2> st, <vec2> size) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_RECTSDF #define FNC_RECTSDF float rectSDF(vec2 p, vec2 b, float r) { vec2 d = abs(p - 0.5) * 4.2 - b + vec2(r); return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)) - r; } float rectSDF(vec2 p, float b, float r) { return rectSDF(p, vec2(b), r); } float rectSDF(in vec2 st, in vec2 s) { st = st * 2. - 1.; return max( abs(st.x / s.x), abs(st.y / s.y) ); } float rectSDF(in vec2 st, in float s) { return rectSDF(st, vec2(s) ); } float rectSDF(in vec2 st) { return rectSDF(st, vec2(1.0)); } #endif <|start_filename|>color/blend/negation.glsl<|end_filename|> /* author: <NAME> description: Photoshop Negation blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendNegation(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDNEGATION #define FNC_BLENDNEGATION float blendNegation(in float base, in float blend) { return 1. - abs(1. - base - blend); } vec3 blendNegation(in vec3 base, in vec3 blend) { return vec3(1.) - abs(vec3(1.) - base - blend); } vec3 blendNegation(in vec3 base, in vec3 blend, in float opacity) { return (blendNegation(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/sphereMap.glsl<|end_filename|> /* author: <NAME> description: given a Spherical Map texture and a normal direction returns the right pixel use: spheremap(<sampler2D> texture, <vec3> normal) options: SPHEREMAP_EYETOPOINT: where the eye is looking */ #ifndef SPHEREMAP_EYETOPOINT #define SPHEREMAP_EYETOPOINT vec3(0.,0.,1.) #endif #ifndef SPHEREMAP_TYPE #define SPHEREMAP_TYPE vec4 #endif #ifndef SPHEREMAP_SAMPLER_FNC #define SPHEREMAP_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #ifndef FNC_SPHEREMAP #define FNC_SPHEREMAP SPHEREMAP_TYPE sphereMap (in sampler2D tex, in vec3 normal, in vec3 eye) { vec3 r = reflect( eye, normal ); r.z += 1.; float m = 2. * length(r); vec2 uv = r.xy / m + .5; return SPHEREMAP_SAMPLER_FNC(uv); } #ifdef FNC_TEXTURE2D SPHEREMAP_TYPE sphereMap (in SamplerVideo tex, in vec3 normal, in vec3 eye) { vec3 r = reflect( eye, normal ); r.z += 1.; float m = 2. * length(r); vec2 uv = r.xy / m + .5; return SPHEREMAP_SAMPLER_FNC(uv); } #endif #endif <|start_filename|>sample/textureFlow.glsl<|end_filename|> /* author: <NAME> description: sample a texture with a looping flow animation, using a direction to push, an elapse time and a cycle. use: textureFlow(<sampler2D> tex, <vec2> st, <vec2> dir, <float> time, <float> cycle) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_TEXTUREFLOW #define FNC_TEXTUREFLOW vec4 textureFlow(sampler2D tex, vec2 st, vec2 dir, float time, float cycle) { float halfCycle = cycle * 0.5; float flowOffset0 = mod(time, cycle); float flowOffset1 = mod(time + halfCycle, cycle); float phase0 = flowOffset0; float phase1 = flowOffset1; // Sample normal map. vec4 A = texture2D(tex, (st + dir * phase0) ); vec4 B = texture2D(tex, (st + dir * phase1) ); float f = (abs(halfCycle - flowOffset0) / halfCycle); return mix( A, B, f ); } #endif <|start_filename|>math/unpack.glsl<|end_filename|> #ifndef UNPACK_FNC #define UNPACK_FNC unpack256 #endif #ifndef FNC_UNPACK #define FNC_UNPACK float unpack8(vec3 value) { vec3 factor = vec3( 8.0, 8.0 * 8.0, 8.0 * 8.0 * 8.0 ); return dot(value, factor) / 512.0; } float unpack16(vec3 value) { vec3 factor = vec3( 16.0, 16.0 * 16.0, 16.0 * 16.0 * 16.0 ); return dot(value, factor) / 4096.0; } float unpack32(vec3 value) { vec3 factor = vec3( 32.0, 32.0 * 32.0, 32.0 * 32.0 * 32.0 ); return dot(value, factor) / 32768.0; } float unpack64(vec3 value) { vec3 factor = vec3( 64.0, 64.0 * 64.0, 64.0 * 64.0 * 64.0 ); return dot(value, factor) / 262144.0; } float unpack128(vec3 value) { vec3 factor = vec3( 128.0, 128.0 * 128.0, 128.0 * 128.0 * 128.0 ); return dot(value, factor) / 2097152.0; } float unpack256(vec3 value) { vec3 factor = vec3( 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); return dot(value, factor) / 16581375.0; } float unpack(vec3 value) { return UNPACK_FNC(value); } #endif <|start_filename|>color/blend/difference.glsl<|end_filename|> /* author: <NAME> description: Photoshop Difference blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendDifference(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDDIFFERENCE #define FNC_BLENDDIFFERENCE float blendDifference(in float base, in float blend) { return abs(base-blend); } vec3 blendDifference(in vec3 base, in vec3 blend) { return abs(base-blend); } vec3 blendDifference(in vec3 base, in vec3 blend, in float opacity) { return (blendDifference(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>generative/snoise.glsl<|end_filename|> #include "../math/mod289.glsl" #include "../math/permute.glsl" #include "../math/taylorInvSqrt.glsl" #include "../math/grad4.glsl" /* author: [<NAME>, Ashima Arts] description: Simplex Noise https://github.com/ashima/webgl-noise use: snoise(<vec2|vec3|vec4> pos) license: | Copyright (C) 2011 Ashima Arts. All rights reserved. Copyright (C) 2011-2016 by <NAME> (Classic noise and others) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the GPUImage framework nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FNC_SNOISE #define FNC_SNOISE float snoise(in vec2 v) { const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) -0.577350269189626, // -1.0 + 2.0 * C.x 0.024390243902439); // 1.0 / 41.0 // First corner vec2 i = floor(v + dot(v, C.yy) ); vec2 x0 = v - i + dot(i, C.xx); // Other corners vec2 i1; //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 //i1.y = 1.0 - i1.x; i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); // x0 = x0 - 0.0 + 0.0 * C.xx ; // x1 = x0 - i1 + 1.0 * C.xx ; // x2 = x0 - 1.0 + 2.0 * C.xx ; vec4 x12 = x0.xyxy + C.xxzz; x12.xy -= i1; // Permutations i = mod289(i); // Avoid truncation effects in permutation vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) + i.x + vec3(0.0, i1.x, 1.0 )); vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); m = m*m ; m = m*m ; // Gradients: 41 points uniformly over a line, mapped onto a diamond. // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) vec3 x = 2.0 * fract(p * C.www) - 1.0; vec3 h = abs(x) - 0.5; vec3 ox = floor(x + 0.5); vec3 a0 = x - ox; // Normalise gradients implicitly by scaling m // Approximation of: m *= inversesqrt( a0*a0 + h*h ); m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); // Compute final noise value at P vec3 g; g.x = a0.x * x0.x + h.x * x0.y; g.yz = a0.yz * x12.xz + h.yz * x12.yw; return 130.0 * dot(m, g); } float snoise(in vec3 v) { const vec2 C = vec2(1.0/6.0, 1.0/3.0) ; const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); // First corner vec3 i = floor(v + dot(v, C.yyy) ); vec3 x0 = v - i + dot(i, C.xxx) ; // Other corners vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1.0 - g; vec3 i1 = min( g.xyz, l.zxy ); vec3 i2 = max( g.xyz, l.zxy ); // x0 = x0 - 0.0 + 0.0 * C.xxx; // x1 = x0 - i1 + 1.0 * C.xxx; // x2 = x0 - i2 + 2.0 * C.xxx; // x3 = x0 - 1.0 + 3.0 * C.xxx; vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y // Permutations i = mod289(i); vec4 p = permute( permute( permute( i.z + vec4(0.0, i1.z, i2.z, 1.0 )) + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) + i.x + vec4(0.0, i1.x, i2.x, 1.0 )); // Gradients: 7x7 points over a square, mapped onto an octahedron. // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) float n_ = 0.142857142857; // 1.0/7.0 vec3 ns = n_ * D.wyz - D.xzx; vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7) vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N) vec4 x = x_ *ns.x + ns.yyyy; vec4 y = y_ *ns.x + ns.yyyy; vec4 h = 1.0 - abs(x) - abs(y); vec4 b0 = vec4( x.xy, y.xy ); vec4 b1 = vec4( x.zw, y.zw ); //vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0; //vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0; vec4 s0 = floor(b0)*2.0 + 1.0; vec4 s1 = floor(b1)*2.0 + 1.0; vec4 sh = -step(h, vec4(0.0)); vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ; vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ; vec3 p0 = vec3(a0.xy,h.x); vec3 p1 = vec3(a0.zw,h.y); vec3 p2 = vec3(a1.xy,h.z); vec3 p3 = vec3(a1.zw,h.w); //Normalise gradients vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))); p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; // Mix final noise value vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0); m = m * m; return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3) ) ); } float snoise(in vec4 v) { const vec4 C = vec4( 0.138196601125011, // (5 - sqrt(5))/20 G4 0.276393202250021, // 2 * G4 0.414589803375032, // 3 * G4 -0.447213595499958); // -1 + 4 * G4 // First corner vec4 i = floor(v + dot(v, vec4(.309016994374947451)) ); // (sqrt(5) - 1)/4 vec4 x0 = v - i + dot(i, C.xxxx); // Other corners // Rank sorting originally contributed by <NAME>, AMD (formerly ATI) vec4 i0; vec3 isX = step( x0.yzw, x0.xxx ); vec3 isYZ = step( x0.zww, x0.yyz ); // i0.x = dot( isX, vec3( 1.0 ) ); i0.x = isX.x + isX.y + isX.z; i0.yzw = 1.0 - isX; // i0.y += dot( isYZ.xy, vec2( 1.0 ) ); i0.y += isYZ.x + isYZ.y; i0.zw += 1.0 - isYZ.xy; i0.z += isYZ.z; i0.w += 1.0 - isYZ.z; // i0 now contains the unique values 0,1,2,3 in each channel vec4 i3 = clamp( i0, 0.0, 1.0 ); vec4 i2 = clamp( i0-1.0, 0.0, 1.0 ); vec4 i1 = clamp( i0-2.0, 0.0, 1.0 ); // x0 = x0 - 0.0 + 0.0 * C.xxxx // x1 = x0 - i1 + 1.0 * C.xxxx // x2 = x0 - i2 + 2.0 * C.xxxx // x3 = x0 - i3 + 3.0 * C.xxxx // x4 = x0 - 1.0 + 4.0 * C.xxxx vec4 x1 = x0 - i1 + C.xxxx; vec4 x2 = x0 - i2 + C.yyyy; vec4 x3 = x0 - i3 + C.zzzz; vec4 x4 = x0 + C.wwww; // Permutations i = mod289(i); float j0 = permute( permute( permute( permute(i.w) + i.z) + i.y) + i.x); vec4 j1 = permute( permute( permute( permute ( i.w + vec4(i1.w, i2.w, i3.w, 1.0 )) + i.z + vec4(i1.z, i2.z, i3.z, 1.0 )) + i.y + vec4(i1.y, i2.y, i3.y, 1.0 )) + i.x + vec4(i1.x, i2.x, i3.x, 1.0 )); // Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope // 7*7*6 = 294, which is close to the ring size 17*17 = 289. vec4 ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0) ; vec4 p0 = grad4(j0, ip); vec4 p1 = grad4(j1.x, ip); vec4 p2 = grad4(j1.y, ip); vec4 p3 = grad4(j1.z, ip); vec4 p4 = grad4(j1.w, ip); // Normalise gradients vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))); p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; p4 *= taylorInvSqrt(dot(p4,p4)); // Mix contributions from the five corners vec3 m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0); vec2 m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4) ), 0.0); m0 = m0 * m0; m1 = m1 * m1; return 49.0 * ( dot(m0*m0, vec3( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 ))) + dot(m1*m1, vec2( dot( p3, x3 ), dot( p4, x4 ) ) ) ) ; } vec3 snoise3( vec3 x ){ float s = snoise(vec3( x )); float s1 = snoise(vec3( x.y - 19.1 , x.z + 33.4 , x.x + 47.2 )); float s2 = snoise(vec3( x.z + 74.2 , x.x - 124.5 , x.y + 99.4 )); vec3 c = vec3( s , s1 , s2 ); return c; } vec3 snoise3( vec4 x ){ float s = snoise(vec4( x )); float s1 = snoise(vec4( x.y - 19.1 , x.z + 33.4 , x.x + 47.2, x.w )); float s2 = snoise(vec4( x.z + 74.2 , x.x - 124.5 , x.y + 99.4, x.w )); vec3 c = vec3( s , s1 , s2 ); return c; } #endif <|start_filename|>math/grad4.glsl<|end_filename|> /* author: [<NAME>, <NAME>] description: grad4, used for snoise(vec4 v) use: grad4(<float> j, <vec4> ip) license: | Copyright (C) 2011 <NAME>. All rights reserved. Distributed under the MIT License. See LICENSE file. https://github.com/ashima/webgl-noise */ #ifndef FNC_GRAD4 #define FNC_GRAD4 vec4 grad4(float j, vec4 ip) { const vec4 ones = vec4(1.0, 1.0, 1.0, -1.0); vec4 p,s; p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0; p.w = 1.5 - dot(abs(p.xyz), ones.xyz); s = vec4(lessThan(p, vec4(0.0))); p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www; return p; } #endif <|start_filename|>lighting/gooch.glsl<|end_filename|> #include "material/roughness.glsl" #include "material/normal.glsl" #include "material/baseColor.glsl" #include "diffuse.glsl" #include "specular.glsl" #include "../sample/textureShadowPCF.glsl" #include "../color/space/linear2gamma.glsl" /* author: <NAME> description: render with a gooch stylistic shading model use: <vec4> gooch(<vec4> baseColor, <vec3> normal, <vec3> light, <vec3> view, <float> roughness) options: - GOOCH_WARM: defualt vec3(0.25, 0.15, 0.0) - GOOCH_COLD: defualt vec3(0.0, 0.0, 0.2) - GOOCH_SPECULAR: defualt vec3(1.0, 1.0, 1.0) - DIFFUSE_FNC: diffuseOrenNayar, diffuseBurley, diffuseLambert (default) - LIGHT_COORD: in GlslViewer is v_lightCoord - LIGHT_SHADOWMAP: in GlslViewer is u_lightShadowMap - LIGHT_SHADOWMAP_SIZE: in GlslViewer is 1024.0 license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GOOCH_WARM #define GOOCH_WARM vec3(0.25, 0.15, 0.0) #endif #ifndef GOOCH_COLD #define GOOCH_COLD vec3(0.0, 0.0, 0.2) #endif #ifndef GOOCH_SPECULAR #define GOOCH_SPECULAR vec3(1.0, 1.0, 1.0) #endif #ifndef FNC_GOOCH #define FNC_GOOCH vec4 gooch(vec4 baseColor, vec3 normal, vec3 light, vec3 view, float roughness) { vec3 warm = GOOCH_WARM + baseColor.rgb * 0.6; vec3 cold = GOOCH_COLD + baseColor.rgb * 0.1; vec3 l = normalize(light); vec3 n = normalize(normal); vec3 v = normalize(view); // Lambert Diffuse float diffuse = diffuse(l, n, v, roughness); // Phong Specular float specular = specular(l, n, v, roughness); #if defined(LIGHT_SHADOWMAP) && defined(LIGHT_SHADOWMAP_SIZE) && defined(LIGHT_COORD) && !defined(PLATFORM_RPI) && !defined(PLATFORM_WEBGL) float bias = 0.005; float shadow = textureShadowPCF(u_lightShadowMap, vec2(LIGHT_SHADOWMAP_SIZE), (LIGHT_COORD).xy, (LIGHT_COORD).z - bias); specular *= shadow; diffuse *= shadow; #endif return linear2gamma( vec4(mix(mix(cold, warm, diffuse), GOOCH_SPECULAR, specular), baseColor.a) ); } #endif <|start_filename|>filter/bilateralBlur.glsl<|end_filename|> #include "../color/space/rgb2luma.glsl" /* author: <NAME> description: TODO use: bilateralBlur(<sampler2D> texture, <vec2> st, <vec2> duv) options: TODO license: TODO */ #ifndef BILATERALBLUR_AMOUNT #define BILATERALBLUR_AMOUNT bilateralBlur13 #endif #ifndef BILATERALBLUR_TYPE #define BILATERALBLUR_TYPE vec4 #endif #ifndef BILATERALBLUR_SAMPLER_FNC #define BILATERALBLUR_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #ifndef BILATERALBLUR_LUMA #define BILATERALBLUR_LUMA(RGB) rgb2luma(RGB.rgb) #endif #include "bilateralBlur/2D.glsl" #ifndef FNC_BILATERALFILTER #define FNC_BILATERALFILTER BILATERALBLUR_TYPE bilateralBlur(in sampler2D tex, in vec2 st, in vec2 offset, const int kernelSize) { return bilateralBlur2D(tex, st, offset, kernelSize); } BILATERALBLUR_TYPE bilateralBlur13(in sampler2D tex, in vec2 st, in vec2 offset) { return bilateralBlur(tex, st, offset, 7); } BILATERALBLUR_TYPE bilateralBlur9(in sampler2D tex, in vec2 st, in vec2 offset) { return bilateralBlur(tex, st, offset, 5); } BILATERALBLUR_TYPE bilateralBlur5(in sampler2D tex, in vec2 st, in vec2 offset) { return bilateralBlur(tex, st, offset, 3); } BILATERALBLUR_TYPE bilateralBlur(in sampler2D tex, in vec2 st, in vec2 offset) { return BILATERALBLUR_AMOUNT(tex, st, offset); } #endif <|start_filename|>generative/gerstnerWave.glsl<|end_filename|> #include "../math/const.glsl" /* author: <NAME> description: Gerstner Wave generator based on this tutorial https://catlikecoding.com/unity/tutorials/flow/waves/ use: - <vec3> gerstnerWave (<vec2> uv, <vec2> dir, <float> steepness, <float> wavelength, <float> _time [, inout <vec3> _tangent, inout <vec3> _binormal] ) - <vec3> gerstnerWave (<vec2> uv, <vec2> dir, <float> steepness, <float> wavelength, <float> _time [, inout <vec3> _normal] ) license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_GERSTNERWAVE #define FNC_GERSTNERWAVE vec3 gerstnerWave (in vec2 _uv, in vec2 _dir, in float _steepness, in float _wavelength, in float _time, inout vec3 _tangent, inout vec3 _binormal) { float k = 2.0 * PI / _wavelength; float c = sqrt(9.8 / k); vec2 d = normalize(_dir); float f = k * (dot(d, _uv) - c * _time); float a = _steepness / k; _tangent += vec3( -d.x * d.x * (_steepness * sin(f)), d.x * (_steepness * cos(f)), -d.x * d.y * (_steepness * sin(f)) ); _binormal += vec3( -d.x * d.y * (_steepness * sin(f)), d.y * (_steepness * cos(f)), -d.y * d.y * (_steepness * sin(f)) ); return vec3( d.x * (a * cos(f)), a * sin(f), d.y * (a * cos(f)) ); } vec3 gerstnerWave (in vec2 _uv, in vec2 _dir, in float _steepness, in float _wavelength, in float _time, inout vec3 _normal) { vec3 _tangent = vec3(0.0); vec3 _binormal = vec3(0.0); vec3 pos = gerstnerWave (_uv, _dir, _steepness, _wavelength, _time, _tangent, _binormal); _normal = normalize(cross(_binormal, _tangent)); return pos; } vec3 gerstnerWave (in vec2 _uv, in vec2 _dir, in float _steepness, in float _wavelength, in float _time) { vec3 _tangent = vec3(0.0); vec3 _binormal = vec3(0.0); return gerstnerWave (_uv, _dir, _steepness, _wavelength, _time, _tangent, _binormal); } #endif <|start_filename|>lighting/light/point.glsl<|end_filename|> /* author: <NAME> description: calculate point light use: lightPoint(<vec3> _diffuseColor, <vec3> _specularColor, <vec3> _N, <vec3> _V, <float> _NoV, <float> _f0, out <vec3> _diffuse, out <vec3> _specular) options: - DIFFUSE_FNC: diffuseOrenNayar, diffuseBurley, diffuseLambert (default) - SURFACE_POSITION: in glslViewer is v_position - LIGHT_POSITION: in glslViewer is u_light - LIGHT_COLOR: in glslViewer is u_lightColor - LIGHT_INTENSITY: in glslViewer is u_lightIntensity - LIGHT_FALLOFF: in glslViewer is u_lightFalloff license: | Copyright (c) 2021 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../specular.glsl" #include "../diffuse.glsl" #include "falloff.glsl" #ifndef SURFACE_POSITION #define SURFACE_POSITION v_position #endif #ifndef LIGHT_POSITION #if defined(GLSLVIEWER) #define LIGHT_POSITION u_light #else #define LIGHT_POSITION vec3(0.0, 10.0, -50.0) #endif #endif #ifndef LIGHT_COLOR #if defined(GLSLVIEWER) #define LIGHT_COLOR u_lightColor #else #define LIGHT_COLOR vec3(0.5) #endif #endif #ifndef LIGHT_INTENSITY #if defined(GLSLVIEWER) #define LIGHT_INTENSITY u_lightIntensity #else #define LIGHT_INTENSITY 1.0 #endif #endif #ifndef LIGHT_FALLOFF #if defined(GLSLVIEWER) #define LIGHT_FALLOFF u_lightFalloff #else #define LIGHT_FALLOFF 1.0 #endif #endif #ifndef FNC_LIGHT_POINT #define FNC_LIGHT_POINT void lightPoint(vec3 _diffuseColor, vec3 _specularColor, vec3 _N, vec3 _V, float _NoV, float _roughness, float _f0, inout vec3 _diffuse, inout vec3 _specular) { vec3 toLight = LIGHT_POSITION - (SURFACE_POSITION).xyz; float toLightLength = length(toLight); vec3 s = toLight/toLightLength; float NoL = dot(_N, s); float dif = diffuse(s, _N, _V, _NoV, NoL, _roughness) * ONE_OVER_PI; float spec = specular(s, _N, _V, _NoV, NoL, _roughness, _f0); float fall = 1.0; #ifdef LIGHT_FALLOFF if (LIGHT_FALLOFF > 0.0) fall = falloff(toLightLength, LIGHT_FALLOFF); #endif _diffuse = LIGHT_INTENSITY * (_diffuseColor * LIGHT_COLOR * dif * fall); _specular = LIGHT_INTENSITY * (_specularColor * LIGHT_COLOR * spec * fall); } #endif <|start_filename|>lighting/sphericalHarmonics.glsl<|end_filename|> /* author: <NAME> description: return the spherical harmonic value facing a normal direction use: sphericalHarmonics( <vec3> normal) options: SPHERICALHARMONICS_BANDS: 2 for RaspberryPi and WebGL for the rest is 3 SCENE_SH_ARRAY: in GlslViewer is u_SH */ #ifndef SPHERICALHARMONICS_BANDS #if defined(TARGET_MOBILE) || defined(PLATFORM_RPI) || defined(PLATFORM_WEBGL) #define SPHERICALHARMONICS_BANDS 2 #else #define SPHERICALHARMONICS_BANDS 3 #endif #endif // #ifndef SCENE_SH_ARRAY // #define SCENE_SH_ARRAY u_SH // #endif #ifndef FNC_SPHERICALHARMONICS #define FNC_SPHERICALHARMONICS vec3 sphericalHarmonics(const vec3 n) { #ifdef SCENE_SH_ARRAY return max( 0.282095 * SCENE_SH_ARRAY[0] #if SPHERICALHARMONICS_BANDS >= 2 + -0.488603 * SCENE_SH_ARRAY[1] * (n.y) + 0.488603 * SCENE_SH_ARRAY[2] * (n.z) + -0.488603 * SCENE_SH_ARRAY[3] * (n.x) #endif #if SPHERICALHARMONICS_BANDS >= 3 + 1.092548 * SCENE_SH_ARRAY[4] * (n.y * n.x) + -1.092548 * SCENE_SH_ARRAY[5] * (n.y * n.z) + 0.315392 * SCENE_SH_ARRAY[6] * (3.0 * n.z * n.z - 1.0) + -1.092548 * SCENE_SH_ARRAY[7] * (n.z * n.x) + 0.546274 * SCENE_SH_ARRAY[8] * (n.x * n.x - n.y * n.y) #endif , 0.0); #else return vec3(1.0); #endif } #endif <|start_filename|>math/decimation.glsl<|end_filename|> /* author: <NAME> description: decimate a value with an specific presicion use: decimation(<float|vec2|vec3|vec4> value, <float|vec2|vec3|vec4> presicion) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_DECIMATION #define FNC_DECIMATION float decimation(float value, float presicion) { return floor(value * presicion)/presicion; } vec2 decimation(vec2 value, float presicion) { return floor(value * presicion)/presicion; } vec3 decimation(vec3 value, float presicion) { return floor(value * presicion)/presicion; } vec4 decimation(vec4 value, float presicion) { return floor(value * presicion)/presicion; } vec2 decimation(vec2 value, vec2 presicion) { return floor(value * presicion)/presicion; } vec3 decimation(vec3 value, vec3 presicion) { return floor(value * presicion)/presicion; } vec4 decimation(vec4 value, vec4 presicion) { return floor(value * presicion)/presicion; } #endif <|start_filename|>color/blend/softLight.glsl<|end_filename|> /* author: <NAME> description: Photoshop Soft Light blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendSoftLight(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDSOFTLIGHT #define FNC_BLENDSOFTLIGHT float blendSoftLight(in float base, in float blend) { return (blend < .5)? (2. * base * blend + base * base * (1. - 2.*blend)): (sqrt(base) * (2. * blend - 1.) + 2. * base * (1. - blend)); } vec3 blendSoftLight(in vec3 base, in vec3 blend) { return vec3(blendSoftLight(base.r, blend.r), blendSoftLight(base.g, blend.g), blendSoftLight(base.b, blend.b)); } vec4 blendSoftLight(in vec4 base, in vec4 blend) { return vec4(blendSoftLight( base.r, blend.r ), blendSoftLight( base.g, blend.g ), blendSoftLight( base.b, blend.b ), blendSoftLight( base.a, blend.a ) ); } vec3 blendSoftLight(in vec3 base, in vec3 blend, in float opacity) { return (blendSoftLight(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>color/blend/darken.glsl<|end_filename|> /* author: <NAME> description: Photoshop Darken blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendDarken(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDDARKEN #define FNC_BLENDDARKEN float blendDarken(in float base, in float blend) { return min(blend,base); } vec3 blendDarken(in vec3 base, in vec3 blend) { return vec3(blendDarken(base.r, blend.r), blendDarken(base.g, blend.g), blendDarken(base.b, blend.b)); } vec3 blendDarken(in vec3 base, in vec3 blend, in float opacity) { return (blendDarken(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>generative/curl.glsl<|end_filename|> #include "snoise.glsl" /* author: <NAME> description: https://github.com/cabbibo/glsl-curl-noise/blob/master/curl.glsl use: curl(<vec3|vec4> pos) license: NONE */ #ifndef FNC_CURL #define FNC_CURL vec3 curl( vec3 p ){ const float e = .1; vec3 dx = vec3( e , 0.0 , 0.0 ); vec3 dy = vec3( 0.0 , e , 0.0 ); vec3 dz = vec3( 0.0 , 0.0 , e ); vec3 p_x0 = snoise3( p - dx ); vec3 p_x1 = snoise3( p + dx ); vec3 p_y0 = snoise3( p - dy ); vec3 p_y1 = snoise3( p + dy ); vec3 p_z0 = snoise3( p - dz ); vec3 p_z1 = snoise3( p + dz ); float x = p_y1.z - p_y0.z - p_z1.y + p_z0.y; float y = p_z1.x - p_z0.x - p_x1.z + p_x0.z; float z = p_x1.y - p_x0.y - p_y1.x + p_y0.x; const float divisor = 1.0 / ( 2.0 * e ); return normalize( vec3( x , y , z ) * divisor ); } vec3 curl( vec4 p ){ const float e = .1; vec4 dx = vec4( e , 0.0 , 0.0 , 1.0 ); vec4 dy = vec4( 0.0 , e , 0.0 , 1.0 ); vec4 dz = vec4( 0.0 , 0.0 , e , 1.0 ); vec3 p_x0 = snoise3( p - dx ); vec3 p_x1 = snoise3( p + dx ); vec3 p_y0 = snoise3( p - dy ); vec3 p_y1 = snoise3( p + dy ); vec3 p_z0 = snoise3( p - dz ); vec3 p_z1 = snoise3( p + dz ); float x = p_y1.z - p_y0.z - p_z1.y + p_z0.y; float y = p_z1.x - p_z0.x - p_x1.z + p_x0.z; float z = p_x1.y - p_x0.y - p_y1.x + p_y0.x; const float divisor = 1.0 / ( 2.0 * e ); return normalize( vec3( x , y , z ) * divisor ); } #endif <|start_filename|>lighting/specular/blinnPhong.glsl<|end_filename|> #include "../../math/powFast.glsl" #include "../toShininess.glsl" #ifndef SPECULAR_POW #if defined(TARGET_MOBILE) || defined(PLATFORM_RPI) || defined(PLATFORM_WEBGL) #define SPECULAR_POW(A,B) powFast(A,B) #else #define SPECULAR_POW(A,B) pow(A,B) #endif #endif #ifndef FNC_SPECULAR_BLINNPHONG #define FNC_SPECULAR_BLINNPHONG // https://github.com/glslify/glsl-specular-blinn-phong float specularBlinnPhong(vec3 L, vec3 N, vec3 V, float shininess) { // halfVector vec3 H = normalize(L + V); return SPECULAR_POW(max(0.0, dot(N, H)), shininess); } float specularBlinnPhongRoughnes(vec3 L, vec3 N, vec3 V, float roughness) { return specularBlinnPhong(L, N, V, toShininess(roughness, 0.0) ); } float specularBlinnPhongRoughnes(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { return specularBlinnPhongRoughnes(L, N, V, roughness); } float specularBlinnPhongRoughnes(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness, float fresnel) { return specularBlinnPhongRoughnes(L, N, V, roughness); } #endif <|start_filename|>animation/easing/bounce.glsl<|end_filename|> #include "../../math/const.glsl" /* author: <NAME> (https://github.com/hughsk) description: bounce easing. From https://github.com/stackgl/glsl-easings use: bounce<In|Out|InOut>(<float> x) license: | This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_BOUNCEOUT #define FNC_BOUNCEOUT float bounceOut(in float t) { const float a = 4.0 / 11.0; const float b = 8.0 / 11.0; const float c = 9.0 / 10.0; const float ca = 4356.0 / 361.0; const float cb = 35442.0 / 1805.0; const float cc = 16061.0 / 1805.0; float t2 = t * t; return t < a ? 7.5625 * t2 : t < b ? 9.075 * t2 - 9.9 * t + 3.4 : t < c ? ca * t2 - cb * t + cc : 10.8 * t * t - 20.52 * t + 10.72; } #endif #ifndef FNC_BOUNCEIN #define FNC_BOUNCEIN float bounceIn(in float t) { return 1.0 - bounceOut(1.0 - t); } #endif #ifndef FNC_BOUNCEINOUT #define FNC_BOUNCEINOUT float bounceInOut(in float t) { return t < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - t * 2.0)) : 0.5 * bounceOut(t * 2.0 - 1.0) + 0.5; } #endif <|start_filename|>space/lookAt.glsl<|end_filename|> /* author: <NAME> description: create a look up matrix use: - <mat3> lookAt(<vec3> forward, <vec3> up) - <mat3> lookAt(<vec3> target, <vec3> eye, <vec3> up) - <mat3> lookAt(<vec3> target, <vec3> eye, <float> rolle) license: | Copyright (c) 2017 <NAME>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FNC_LOOKAT #define FNC_LOOKAT mat3 lookAt(vec3 forward, vec3 up) { vec3 xaxis = normalize(cross(forward, up)); vec3 yaxis = up; vec3 zaxis = forward; return mat3(xaxis, yaxis, zaxis); } mat3 lookAt(vec3 target, vec3 eye, vec3 up) { vec3 zaxis = normalize(target - eye); vec3 xaxis = normalize(cross(zaxis, up)); vec3 yaxis = cross(zaxis, xaxis); return mat3(xaxis, yaxis, zaxis); } mat3 lookAt(vec3 target, vec3 eye, float roll) { vec3 up = vec3(sin(roll), cos(roll), 0.0); vec3 zaxis = normalize(target - eye); vec3 xaxis = normalize(cross(zaxis, up)); vec3 yaxis = normalize(cross(xaxis, zaxis)); return mat3(xaxis, yaxis, zaxis); } #endif <|start_filename|>color/blend/multiply.glsl<|end_filename|> /* author: <NAME> description: Photoshop Multiply blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendMultiply(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDMULTIPLY #define FNC_BLENDMULTIPLY float blendMultiply(in float base, in float blend) { return base * blend; } vec3 blendMultiply(in vec3 base, in vec3 blend) { return base * blend; } vec3 blendMultiply(in vec3 base, in vec3 blend, float opacity) { return (blendMultiply(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>color/blend/glow.glsl<|end_filename|> #include "reflect.glsl" /* author: <NAME> description: Photoshop Glow blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendGlow(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDGLOW #define FNC_BLENDGLOW float blendGlow(in float base, in float blend) { return blendReflect(blend, base); } vec3 blendGlow(in vec3 base, in vec3 blend) { return blendReflect(blend, base); } vec3 blendGlow(in vec3 base, in vec3 blend, in float opacity) { return (blendGlow(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>lighting/specular/beckmann.glsl<|end_filename|> #include "../common/beckmann.glsl" #ifndef FNC_SPECULAR_BECKMANN #define FNC_SPECULAR_BECKMANN float specularBeckmann(vec3 L, vec3 N, vec3 V, float roughness) { float NoH = dot(N, normalize(L + V)); return beckmann(NoH, roughness); } float specularBeckmann(vec3 L, vec3 N, vec3 V, float roughness, float fresnel) { return specularBeckmann(L, N, V, roughness); } float specularBeckmann(vec3 L, vec3 N, vec3 V, float NoV, float NoL, float roughness, float fresnel) { return specularBeckmann(L, N, V, roughness); } #endif <|start_filename|>color/blend/hardMix.glsl<|end_filename|> #include "vividLight.glsl" /* author: <NAME> description: Photoshop Hard Mix blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendHardMix(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDHARDMIX #define FNC_BLENDHARDMIX float blendHardMix(in float base, in float blend) { return (blendVividLight(base, blend) < .5)? 0.: 1.; } vec3 blendHardMix(in vec3 base, in vec3 blend) { return vec3(blendHardMix(base.r, blend.r), blendHardMix(base.g, blend.g), blendHardMix(base.b, blend.b)); } vec3 blendHardMix(in vec3 base, in vec3 blend, in float opacity) { return (blendHardMix(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>math/mirror.glsl<|end_filename|> /* function: mirror author: <NAME> description: Transforms the input signal into a triangle wave. For instance, if x goes between 0 and 2, the returned value will go from 0 to 1, and then 1 to 0 in a triangle shape. use: mirror(<vec2|float> x) license: - */ #ifndef FNC_MIRROR #define FNC_MIRROR float mirror(in float x) { float f = fract(x); float m = floor(mod(x, 2.)); float fm = f * m; return f + m - fm * 2.; } vec2 mirror(in vec2 xy) { vec2 f = fract(xy); vec2 m = floor(mod(xy, 2.)); vec2 fm = f * m; return f + m - fm * 2.; } #endif <|start_filename|>color/blend/pinLight.glsl<|end_filename|> #include "lighten.glsl" #include "darken.glsl" /* author: <NAME> description: Photoshop Pin Light blend mode mplementations sourced from this article on https://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/ use: blendPinLight(<float|vec3> base, <float|vec3> blend [, <float> opacity]) licence: TODO */ #ifndef FNC_BLENDPINLIGHT #define FNC_BLENDPINLIGHT float blendPinLight(in float base, in float blend) { return (blend < .5)? blendDarken(base, (2.*blend)): blendLighten(base, (2. * (blend - .5))); } vec3 blendPinLight(in vec3 base, in vec3 blend) { return vec3(blendPinLight(base.r, blend.r), blendPinLight(base.g, blend.g), blendPinLight(base.b, blend.b)); } vec3 blendPinLight(in vec3 base, in vec3 blend, in float opacity) { return (blendPinLight(base, blend) * opacity + base * (1. - opacity)); } #endif <|start_filename|>filter/sharpen.glsl<|end_filename|> /* author: <NAME> description: sharpening filter use: sharpen(<sampler2D> texture, <vec2> st, <vec2> renderSize [, float streanght]) options: SHARPEN_KERNELSIZE: Defaults 2 SHARPEN_TYPE: defaults to vec3 SHARPEN_SAMPLER_FNC(POS_UV): defaults to texture2D(tex, POS_UV).rgb SHARPEN_FNC: defaults to sharpenFast license: | Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SHARPEN_TYPE #define SHARPEN_TYPE vec3 #endif #ifndef SHARPEN_SAMPLER_FNC #define SHARPEN_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV).rgb #endif #ifndef SHARPEN_FNC #define SHARPEN_FNC sharpenFast #endif #include "sharpen/fast.glsl" #include "sharpen/adaptive.glsl" #include "sharpen/contrastAdaptive.glsl" #ifndef FNC_SHARPEN #define FNC_SHARPEN SHARPEN_TYPE sharpen(in sampler2D tex, in vec2 st, in vec2 pixel, float strenght) { return SHARPEN_FNC (tex, st, pixel, strenght); } SHARPEN_TYPE sharpen(in sampler2D tex, in vec2 st, in vec2 pixel) { return SHARPEN_FNC (tex, st, pixel); } #endif <|start_filename|>sdf/starSDF.glsl<|end_filename|> #include "../math/const.glsl" /* author: <NAME> description: Returns a star-shaped sdf with V branches use: starSDF(<vec2> st, <int> V, <float> scale) license: | Copyright (c) 2017 <NAME>. All rights reserved. Distributed under BSD 3-clause "New" or "Revised" License. See LICENSE file at https://github.com/patriciogonzalezvivo/PixelSpiritDeck */ #ifndef FNC_STARSDF #define FNC_STARSDF float starSDF(in vec2 st, in int V, in float s) { st = st * 4. - 2.; float a = atan(st.y, st.x) / TAU; float seg = a * float(V); a = ((floor(seg) + .5) / float(V) + mix(s, -s, step(.5, fract(seg)))) * TAU; return abs(dot(vec2(cos(a), sin(a)), st)); } #endif <|start_filename|>distort/stretch.glsl<|end_filename|> /* author: <NAME>, <NAME> description: Samples multiple times a texture in the specified direction use: stretch(<sampler2D> tex, <vec2> st, <vec2> direction [, int samples]) options: STRETCH_SAMPLES: number of samples taken, defaults to 20 STRETCH_TYPE: return type, defauls to vec4 STRETCH_SAMPLER_FNC(POS_UV): function used to sample the input texture, defaults to texture2D(tex, POS_UV) STRETCH_WEIGHT: shaping equation to multiply the sample weight. license: | Copyright (c) 2021 <NAME> and <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOF */ #ifndef STRETCH_SAMPLES #define STRETCH_SAMPLES 20 #endif #ifndef STRETCH_TYPE #define STRETCH_TYPE vec4 #endif #ifndef STRETCH_SAMPLER_FNC #define STRETCH_SAMPLER_FNC(POS_UV) texture2D(tex, POS_UV) #endif #ifndef FNC_STRETCH #define FNC_STRETCH STRETCH_TYPE stretch(in sampler2D tex, in vec2 st, in vec2 direction, const int i_samples) { float f_samples = float(i_samples); STRETCH_TYPE color = STRETCH_TYPE(0.); #ifdef PLATFORM_WEBGL for (int i = 0; i < 50; i++) { if (i == i_samples) break; #else for (int i = 0; i < i_samples; i++) { #endif float f_sample = float(i); STRETCH_TYPE tx = STRETCH_SAMPLER_FNC(st + direction * f_sample); #ifdef STRETCH_WEIGHT tx *= STRETCH_WEIGHT; #endif color += tx; } return color / f_samples; } STRETCH_TYPE stretch(in sampler2D tex, in vec2 st, in vec2 direction) { float f_samples = float(STRETCH_SAMPLES); STRETCH_TYPE color = STRETCH_TYPE(0.); for (int i = 0; i < STRETCH_SAMPLES; i++) { float f_sample = float(i); STRETCH_TYPE tx = STRETCH_SAMPLER_FNC(st + direction * f_sample); #ifdef STRETCH_WEIGHT tx *= STRETCH_WEIGHT; #endif color += tx; } return color / f_samples; } #endif <|start_filename|>color/tonemap/debug.glsl<|end_filename|> #include "../luminance.glsl" /* Author: description: | Converts the input HDR RGB color into one of 16 debug colors that represent the pixel's exposure. When the output is cyan, the input color represents middle gray (18% exposure). Every exposure stop above or below middle gray causes a color shift. The relationship between exposures and colors is: -5EV - black -4EV - darkest blue -3EV - darker blue -2EV - dark blue -1EV - blue OEV - cyan +1EV - dark green +2EV - green +3EV - yellow +4EV - yellow-orange +5EV - orange +6EV - bright red +7EV - red +8EV - magenta +9EV - purple +10EV - white use: <vec3|vec4> tonemapDebug(<vec3|vec4> x) */ #ifndef FNC_TONEMAPDEBUG #define FNC_TONEMAPDEBUG #if !defined(PLATFORM_RPI) && !defined(PLATFORM_WEBGL) vec3 tonemapDebug(const vec3 x) { // 16 debug colors + 1 duplicated at the end for easy indexing vec3 debugColors[17]; debugColors[0] = vec3(0.0, 0.0, 0.0); // black debugColors[1] = vec3(0.0, 0.0, 0.1647); // darkest blue debugColors[2] = vec3(0.0, 0.0, 0.3647); // darker blue debugColors[3] = vec3(0.0, 0.0, 0.6647); // dark blue debugColors[4] = vec3(0.0, 0.0, 0.9647); // blue debugColors[5] = vec3(0.0, 0.9255, 0.9255); // cyan debugColors[6] = vec3(0.0, 0.5647, 0.0); // dark green debugColors[7] = vec3(0.0, 0.7843, 0.0); // green debugColors[8] = vec3(1.0, 1.0, 0.0); // yellow debugColors[9] = vec3(0.90588, 0.75294, 0.0); // yellow-orange debugColors[10] = vec3(1.0, 0.5647, 0.0); // orange debugColors[11] = vec3(1.0, 0.0, 0.0); // bright red debugColors[12] = vec3(0.8392, 0.0, 0.0); // red debugColors[13] = vec3(1.0, 0.0, 1.0); // magenta debugColors[14] = vec3(0.6, 0.3333, 0.7882); // purple debugColors[15] = vec3(1.0, 1.0, 1.0); // white debugColors[16] = vec3(1.0, 1.0, 1.0); // white // The 5th color in the array (cyan) represents middle gray (18%) // Every stop above or below middle gray causes a color shift float v = log2(luminance(x) / 0.18); v = clamp(v + 5.0, 0.0, 15.0); int index = int(v); return mix(debugColors[index], debugColors[index + 1], v - float(index)); } vec4 tonemapDebug(const vec4 x) { return vec4(tonemapDebug(x.rgb), x.a); } #endif #endif
chickenSandwich/lygia
<|start_filename|>src/components/Tabs/index.js<|end_filename|> import Tabs from './Tabs' export default Tabs
jinxyang/seal-react
<|start_filename|>Makefile<|end_filename|> # ------------------------------------------------------------ # Copyright 2021 The Dapr Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------ CXX = g++ PROTOC = protoc GRPC_CPP_PLUGIN = grpc_cpp_plugin GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)` OBJ_FILES = src/dapr/proto/common/v1/common.pb.o src/dapr/proto/runtime/v1/dapr.pb.o src/dapr/proto/runtime/v1/dapr.grpc.pb.o src/dapr/proto/runtime/v1/appcallback.pb.o src/dapr/proto/runtime/v1/appcallback.grpc.pb.o PROTO_FILES = dapr/proto/runtime/v1/dapr.proto dapr/proto/runtime/v1/appcallback.proto dapr/proto/common/v1/common.proto PROTOS_PATH = . DAPR_TARGET ?= master vpath %.proto $(PROTOS_PATH) all: system-check libdapr.so libdapr.so : $(OBJ_FILES) -mkdir -p ./out $(CXX) -shared -Wl,-soname,libdapr.so.0 -o ./out/libdapr.0.2.0.so ./src/dapr/proto/runtime/v1/*.o ./src/dapr/proto/common/v1/*.o %.o: %.cc $(CXX) -c -fPIC -I./src $< -o $@ .PRECIOUS: src/%.grpc.pb.cc src/%.grpc.pb.cc: %.proto $(PROTOC) -I $(PROTOS_PATH) --grpc_out=./src/ --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $< .PRECIOUS: src/%.pb.cc src/%.pb.cc: %.proto mkdir -p ./src $(PROTOC) -I $(PROTOS_PATH) --cpp_out=./src/ $< clean: rm -f ./src/dapr/proto/common/v1/*.o ./src/dapr/proto/runtime/v1/*.o rm -rf ./out refresh_proto_files: for file in $(PROTO_FILES); do \ curl -o $$file https://raw.githubusercontent.com/dapr/dapr/$(DAPR_TARGET)/$$file; \ done # The following is to test your system and ensure a smoother experience. # They are by no means necessary to actually compile a grpc-enabled software. PROTOC_CMD = which $(PROTOC) PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3 PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN) HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false) ifeq ($(HAS_PROTOC),true) HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false) endif HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false) SYSTEM_OK = false ifeq ($(HAS_VALID_PROTOC),true) ifeq ($(HAS_PLUGIN),true) SYSTEM_OK = true endif endif system-check: ifneq ($(HAS_VALID_PROTOC),true) @echo " DEPENDENCY ERROR" @echo @echo "You don't have protoc 3.0.0 installed in your path." @echo "Please install Google protocol buffers 3.0.0 and its compiler." @echo "You can find it here:" @echo @echo " https://github.com/google/protobuf/releases/tag/v3.0.0" @echo @echo "Here is what I get when trying to evaluate your version of protoc:" @echo -$(PROTOC) --version @echo @echo endif ifneq ($(HAS_PLUGIN),true) @echo " DEPENDENCY ERROR" @echo @echo "You don't have the grpc c++ protobuf plugin installed in your path." @echo "Please install grpc. You can find it here:" @echo @echo " https://github.com/grpc/grpc" @echo @echo "Here is what I get when trying to detect if you have the plugin:" @echo -which $(GRPC_CPP_PLUGIN) @echo @echo endif ifneq ($(SYSTEM_OK),true) @false endif <|start_filename|>src/dapr/proto/common/v1/common.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: dapr/proto/common/v1/common.proto #ifndef PROTOBUF_INCLUDED_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto #define PROTOBUF_INCLUDED_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/map.h> // IWYU pragma: export #include <google/protobuf/map_entry.h> #include <google/protobuf/map_field_inl.h> #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/any.pb.h> // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto namespace protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[9]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors(); } // namespace protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto namespace dapr { namespace proto { namespace common { namespace v1 { class ConfigurationItem; class ConfigurationItemDefaultTypeInternal; extern ConfigurationItemDefaultTypeInternal _ConfigurationItem_default_instance_; class ConfigurationItem_MetadataEntry_DoNotUse; class ConfigurationItem_MetadataEntry_DoNotUseDefaultTypeInternal; extern ConfigurationItem_MetadataEntry_DoNotUseDefaultTypeInternal _ConfigurationItem_MetadataEntry_DoNotUse_default_instance_; class Etag; class EtagDefaultTypeInternal; extern EtagDefaultTypeInternal _Etag_default_instance_; class HTTPExtension; class HTTPExtensionDefaultTypeInternal; extern HTTPExtensionDefaultTypeInternal _HTTPExtension_default_instance_; class InvokeRequest; class InvokeRequestDefaultTypeInternal; extern InvokeRequestDefaultTypeInternal _InvokeRequest_default_instance_; class InvokeResponse; class InvokeResponseDefaultTypeInternal; extern InvokeResponseDefaultTypeInternal _InvokeResponse_default_instance_; class StateItem; class StateItemDefaultTypeInternal; extern StateItemDefaultTypeInternal _StateItem_default_instance_; class StateItem_MetadataEntry_DoNotUse; class StateItem_MetadataEntry_DoNotUseDefaultTypeInternal; extern StateItem_MetadataEntry_DoNotUseDefaultTypeInternal _StateItem_MetadataEntry_DoNotUse_default_instance_; class StateOptions; class StateOptionsDefaultTypeInternal; extern StateOptionsDefaultTypeInternal _StateOptions_default_instance_; } // namespace v1 } // namespace common } // namespace proto } // namespace dapr namespace google { namespace protobuf { template<> ::dapr::proto::common::v1::ConfigurationItem* Arena::CreateMaybeMessage<::dapr::proto::common::v1::ConfigurationItem>(Arena*); template<> ::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse* Arena::CreateMaybeMessage<::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse>(Arena*); template<> ::dapr::proto::common::v1::Etag* Arena::CreateMaybeMessage<::dapr::proto::common::v1::Etag>(Arena*); template<> ::dapr::proto::common::v1::HTTPExtension* Arena::CreateMaybeMessage<::dapr::proto::common::v1::HTTPExtension>(Arena*); template<> ::dapr::proto::common::v1::InvokeRequest* Arena::CreateMaybeMessage<::dapr::proto::common::v1::InvokeRequest>(Arena*); template<> ::dapr::proto::common::v1::InvokeResponse* Arena::CreateMaybeMessage<::dapr::proto::common::v1::InvokeResponse>(Arena*); template<> ::dapr::proto::common::v1::StateItem* Arena::CreateMaybeMessage<::dapr::proto::common::v1::StateItem>(Arena*); template<> ::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse* Arena::CreateMaybeMessage<::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse>(Arena*); template<> ::dapr::proto::common::v1::StateOptions* Arena::CreateMaybeMessage<::dapr::proto::common::v1::StateOptions>(Arena*); } // namespace protobuf } // namespace google namespace dapr { namespace proto { namespace common { namespace v1 { enum HTTPExtension_Verb { HTTPExtension_Verb_NONE = 0, HTTPExtension_Verb_GET = 1, HTTPExtension_Verb_HEAD = 2, HTTPExtension_Verb_POST = 3, HTTPExtension_Verb_PUT = 4, HTTPExtension_Verb_DELETE = 5, HTTPExtension_Verb_CONNECT = 6, HTTPExtension_Verb_OPTIONS = 7, HTTPExtension_Verb_TRACE = 8, HTTPExtension_Verb_PATCH = 9, HTTPExtension_Verb_HTTPExtension_Verb_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, HTTPExtension_Verb_HTTPExtension_Verb_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool HTTPExtension_Verb_IsValid(int value); const HTTPExtension_Verb HTTPExtension_Verb_Verb_MIN = HTTPExtension_Verb_NONE; const HTTPExtension_Verb HTTPExtension_Verb_Verb_MAX = HTTPExtension_Verb_PATCH; const int HTTPExtension_Verb_Verb_ARRAYSIZE = HTTPExtension_Verb_Verb_MAX + 1; const ::google::protobuf::EnumDescriptor* HTTPExtension_Verb_descriptor(); inline const ::std::string& HTTPExtension_Verb_Name(HTTPExtension_Verb value) { return ::google::protobuf::internal::NameOfEnum( HTTPExtension_Verb_descriptor(), value); } inline bool HTTPExtension_Verb_Parse( const ::std::string& name, HTTPExtension_Verb* value) { return ::google::protobuf::internal::ParseNamedEnum<HTTPExtension_Verb>( HTTPExtension_Verb_descriptor(), name, value); } enum StateOptions_StateConcurrency { StateOptions_StateConcurrency_CONCURRENCY_UNSPECIFIED = 0, StateOptions_StateConcurrency_CONCURRENCY_FIRST_WRITE = 1, StateOptions_StateConcurrency_CONCURRENCY_LAST_WRITE = 2, StateOptions_StateConcurrency_StateOptions_StateConcurrency_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, StateOptions_StateConcurrency_StateOptions_StateConcurrency_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool StateOptions_StateConcurrency_IsValid(int value); const StateOptions_StateConcurrency StateOptions_StateConcurrency_StateConcurrency_MIN = StateOptions_StateConcurrency_CONCURRENCY_UNSPECIFIED; const StateOptions_StateConcurrency StateOptions_StateConcurrency_StateConcurrency_MAX = StateOptions_StateConcurrency_CONCURRENCY_LAST_WRITE; const int StateOptions_StateConcurrency_StateConcurrency_ARRAYSIZE = StateOptions_StateConcurrency_StateConcurrency_MAX + 1; const ::google::protobuf::EnumDescriptor* StateOptions_StateConcurrency_descriptor(); inline const ::std::string& StateOptions_StateConcurrency_Name(StateOptions_StateConcurrency value) { return ::google::protobuf::internal::NameOfEnum( StateOptions_StateConcurrency_descriptor(), value); } inline bool StateOptions_StateConcurrency_Parse( const ::std::string& name, StateOptions_StateConcurrency* value) { return ::google::protobuf::internal::ParseNamedEnum<StateOptions_StateConcurrency>( StateOptions_StateConcurrency_descriptor(), name, value); } enum StateOptions_StateConsistency { StateOptions_StateConsistency_CONSISTENCY_UNSPECIFIED = 0, StateOptions_StateConsistency_CONSISTENCY_EVENTUAL = 1, StateOptions_StateConsistency_CONSISTENCY_STRONG = 2, StateOptions_StateConsistency_StateOptions_StateConsistency_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, StateOptions_StateConsistency_StateOptions_StateConsistency_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool StateOptions_StateConsistency_IsValid(int value); const StateOptions_StateConsistency StateOptions_StateConsistency_StateConsistency_MIN = StateOptions_StateConsistency_CONSISTENCY_UNSPECIFIED; const StateOptions_StateConsistency StateOptions_StateConsistency_StateConsistency_MAX = StateOptions_StateConsistency_CONSISTENCY_STRONG; const int StateOptions_StateConsistency_StateConsistency_ARRAYSIZE = StateOptions_StateConsistency_StateConsistency_MAX + 1; const ::google::protobuf::EnumDescriptor* StateOptions_StateConsistency_descriptor(); inline const ::std::string& StateOptions_StateConsistency_Name(StateOptions_StateConsistency value) { return ::google::protobuf::internal::NameOfEnum( StateOptions_StateConsistency_descriptor(), value); } inline bool StateOptions_StateConsistency_Parse( const ::std::string& name, StateOptions_StateConsistency* value) { return ::google::protobuf::internal::ParseNamedEnum<StateOptions_StateConsistency>( StateOptions_StateConsistency_descriptor(), name, value); } // =================================================================== class HTTPExtension : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.HTTPExtension) */ { public: HTTPExtension(); virtual ~HTTPExtension(); HTTPExtension(const HTTPExtension& from); inline HTTPExtension& operator=(const HTTPExtension& from) { CopyFrom(from); return *this; } #if LANG_CXX11 HTTPExtension(HTTPExtension&& from) noexcept : HTTPExtension() { *this = ::std::move(from); } inline HTTPExtension& operator=(HTTPExtension&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const HTTPExtension& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const HTTPExtension* internal_default_instance() { return reinterpret_cast<const HTTPExtension*>( &_HTTPExtension_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(HTTPExtension* other); friend void swap(HTTPExtension& a, HTTPExtension& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline HTTPExtension* New() const final { return CreateMaybeMessage<HTTPExtension>(NULL); } HTTPExtension* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<HTTPExtension>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const HTTPExtension& from); void MergeFrom(const HTTPExtension& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(HTTPExtension* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef HTTPExtension_Verb Verb; static const Verb NONE = HTTPExtension_Verb_NONE; static const Verb GET = HTTPExtension_Verb_GET; static const Verb HEAD = HTTPExtension_Verb_HEAD; static const Verb POST = HTTPExtension_Verb_POST; static const Verb PUT = HTTPExtension_Verb_PUT; static const Verb DELETE = HTTPExtension_Verb_DELETE; static const Verb CONNECT = HTTPExtension_Verb_CONNECT; static const Verb OPTIONS = HTTPExtension_Verb_OPTIONS; static const Verb TRACE = HTTPExtension_Verb_TRACE; static const Verb PATCH = HTTPExtension_Verb_PATCH; static inline bool Verb_IsValid(int value) { return HTTPExtension_Verb_IsValid(value); } static const Verb Verb_MIN = HTTPExtension_Verb_Verb_MIN; static const Verb Verb_MAX = HTTPExtension_Verb_Verb_MAX; static const int Verb_ARRAYSIZE = HTTPExtension_Verb_Verb_ARRAYSIZE; static inline const ::google::protobuf::EnumDescriptor* Verb_descriptor() { return HTTPExtension_Verb_descriptor(); } static inline const ::std::string& Verb_Name(Verb value) { return HTTPExtension_Verb_Name(value); } static inline bool Verb_Parse(const ::std::string& name, Verb* value) { return HTTPExtension_Verb_Parse(name, value); } // accessors ------------------------------------------------------- // string querystring = 2; void clear_querystring(); static const int kQuerystringFieldNumber = 2; const ::std::string& querystring() const; void set_querystring(const ::std::string& value); #if LANG_CXX11 void set_querystring(::std::string&& value); #endif void set_querystring(const char* value); void set_querystring(const char* value, size_t size); ::std::string* mutable_querystring(); ::std::string* release_querystring(); void set_allocated_querystring(::std::string* querystring); // .dapr.proto.common.v1.HTTPExtension.Verb verb = 1; void clear_verb(); static const int kVerbFieldNumber = 1; ::dapr::proto::common::v1::HTTPExtension_Verb verb() const; void set_verb(::dapr::proto::common::v1::HTTPExtension_Verb value); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.HTTPExtension) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr querystring_; int verb_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // ------------------------------------------------------------------- class InvokeRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.InvokeRequest) */ { public: InvokeRequest(); virtual ~InvokeRequest(); InvokeRequest(const InvokeRequest& from); inline InvokeRequest& operator=(const InvokeRequest& from) { CopyFrom(from); return *this; } #if LANG_CXX11 InvokeRequest(InvokeRequest&& from) noexcept : InvokeRequest() { *this = ::std::move(from); } inline InvokeRequest& operator=(InvokeRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const InvokeRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const InvokeRequest* internal_default_instance() { return reinterpret_cast<const InvokeRequest*>( &_InvokeRequest_default_instance_); } static constexpr int kIndexInFileMessages = 1; void Swap(InvokeRequest* other); friend void swap(InvokeRequest& a, InvokeRequest& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline InvokeRequest* New() const final { return CreateMaybeMessage<InvokeRequest>(NULL); } InvokeRequest* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<InvokeRequest>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const InvokeRequest& from); void MergeFrom(const InvokeRequest& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(InvokeRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string method = 1; void clear_method(); static const int kMethodFieldNumber = 1; const ::std::string& method() const; void set_method(const ::std::string& value); #if LANG_CXX11 void set_method(::std::string&& value); #endif void set_method(const char* value); void set_method(const char* value, size_t size); ::std::string* mutable_method(); ::std::string* release_method(); void set_allocated_method(::std::string* method); // string content_type = 3; void clear_content_type(); static const int kContentTypeFieldNumber = 3; const ::std::string& content_type() const; void set_content_type(const ::std::string& value); #if LANG_CXX11 void set_content_type(::std::string&& value); #endif void set_content_type(const char* value); void set_content_type(const char* value, size_t size); ::std::string* mutable_content_type(); ::std::string* release_content_type(); void set_allocated_content_type(::std::string* content_type); // .google.protobuf.Any data = 2; bool has_data() const; void clear_data(); static const int kDataFieldNumber = 2; private: const ::google::protobuf::Any& _internal_data() const; public: const ::google::protobuf::Any& data() const; ::google::protobuf::Any* release_data(); ::google::protobuf::Any* mutable_data(); void set_allocated_data(::google::protobuf::Any* data); // .dapr.proto.common.v1.HTTPExtension http_extension = 4; bool has_http_extension() const; void clear_http_extension(); static const int kHttpExtensionFieldNumber = 4; private: const ::dapr::proto::common::v1::HTTPExtension& _internal_http_extension() const; public: const ::dapr::proto::common::v1::HTTPExtension& http_extension() const; ::dapr::proto::common::v1::HTTPExtension* release_http_extension(); ::dapr::proto::common::v1::HTTPExtension* mutable_http_extension(); void set_allocated_http_extension(::dapr::proto::common::v1::HTTPExtension* http_extension); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.InvokeRequest) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr method_; ::google::protobuf::internal::ArenaStringPtr content_type_; ::google::protobuf::Any* data_; ::dapr::proto::common::v1::HTTPExtension* http_extension_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // ------------------------------------------------------------------- class InvokeResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.InvokeResponse) */ { public: InvokeResponse(); virtual ~InvokeResponse(); InvokeResponse(const InvokeResponse& from); inline InvokeResponse& operator=(const InvokeResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 InvokeResponse(InvokeResponse&& from) noexcept : InvokeResponse() { *this = ::std::move(from); } inline InvokeResponse& operator=(InvokeResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const InvokeResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const InvokeResponse* internal_default_instance() { return reinterpret_cast<const InvokeResponse*>( &_InvokeResponse_default_instance_); } static constexpr int kIndexInFileMessages = 2; void Swap(InvokeResponse* other); friend void swap(InvokeResponse& a, InvokeResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline InvokeResponse* New() const final { return CreateMaybeMessage<InvokeResponse>(NULL); } InvokeResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<InvokeResponse>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const InvokeResponse& from); void MergeFrom(const InvokeResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(InvokeResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string content_type = 2; void clear_content_type(); static const int kContentTypeFieldNumber = 2; const ::std::string& content_type() const; void set_content_type(const ::std::string& value); #if LANG_CXX11 void set_content_type(::std::string&& value); #endif void set_content_type(const char* value); void set_content_type(const char* value, size_t size); ::std::string* mutable_content_type(); ::std::string* release_content_type(); void set_allocated_content_type(::std::string* content_type); // .google.protobuf.Any data = 1; bool has_data() const; void clear_data(); static const int kDataFieldNumber = 1; private: const ::google::protobuf::Any& _internal_data() const; public: const ::google::protobuf::Any& data() const; ::google::protobuf::Any* release_data(); ::google::protobuf::Any* mutable_data(); void set_allocated_data(::google::protobuf::Any* data); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.InvokeResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr content_type_; ::google::protobuf::Any* data_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // ------------------------------------------------------------------- class StateItem_MetadataEntry_DoNotUse : public ::google::protobuf::internal::MapEntry<StateItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > { public: typedef ::google::protobuf::internal::MapEntry<StateItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > SuperType; StateItem_MetadataEntry_DoNotUse(); StateItem_MetadataEntry_DoNotUse(::google::protobuf::Arena* arena); void MergeFrom(const StateItem_MetadataEntry_DoNotUse& other); static const StateItem_MetadataEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const StateItem_MetadataEntry_DoNotUse*>(&_StateItem_MetadataEntry_DoNotUse_default_instance_); } void MergeFrom(const ::google::protobuf::Message& other) final; ::google::protobuf::Metadata GetMetadata() const; }; // ------------------------------------------------------------------- class StateItem : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.StateItem) */ { public: StateItem(); virtual ~StateItem(); StateItem(const StateItem& from); inline StateItem& operator=(const StateItem& from) { CopyFrom(from); return *this; } #if LANG_CXX11 StateItem(StateItem&& from) noexcept : StateItem() { *this = ::std::move(from); } inline StateItem& operator=(StateItem&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const StateItem& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StateItem* internal_default_instance() { return reinterpret_cast<const StateItem*>( &_StateItem_default_instance_); } static constexpr int kIndexInFileMessages = 4; void Swap(StateItem* other); friend void swap(StateItem& a, StateItem& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline StateItem* New() const final { return CreateMaybeMessage<StateItem>(NULL); } StateItem* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<StateItem>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const StateItem& from); void MergeFrom(const StateItem& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StateItem* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // map<string, string> metadata = 4; int metadata_size() const; void clear_metadata(); static const int kMetadataFieldNumber = 4; const ::google::protobuf::Map< ::std::string, ::std::string >& metadata() const; ::google::protobuf::Map< ::std::string, ::std::string >* mutable_metadata(); // string key = 1; void clear_key(); static const int kKeyFieldNumber = 1; const ::std::string& key() const; void set_key(const ::std::string& value); #if LANG_CXX11 void set_key(::std::string&& value); #endif void set_key(const char* value); void set_key(const char* value, size_t size); ::std::string* mutable_key(); ::std::string* release_key(); void set_allocated_key(::std::string* key); // bytes value = 2; void clear_value(); static const int kValueFieldNumber = 2; const ::std::string& value() const; void set_value(const ::std::string& value); #if LANG_CXX11 void set_value(::std::string&& value); #endif void set_value(const char* value); void set_value(const void* value, size_t size); ::std::string* mutable_value(); ::std::string* release_value(); void set_allocated_value(::std::string* value); // .dapr.proto.common.v1.Etag etag = 3; bool has_etag() const; void clear_etag(); static const int kEtagFieldNumber = 3; private: const ::dapr::proto::common::v1::Etag& _internal_etag() const; public: const ::dapr::proto::common::v1::Etag& etag() const; ::dapr::proto::common::v1::Etag* release_etag(); ::dapr::proto::common::v1::Etag* mutable_etag(); void set_allocated_etag(::dapr::proto::common::v1::Etag* etag); // .dapr.proto.common.v1.StateOptions options = 5; bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 5; private: const ::dapr::proto::common::v1::StateOptions& _internal_options() const; public: const ::dapr::proto::common::v1::StateOptions& options() const; ::dapr::proto::common::v1::StateOptions* release_options(); ::dapr::proto::common::v1::StateOptions* mutable_options(); void set_allocated_options(::dapr::proto::common::v1::StateOptions* options); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.StateItem) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::MapField< StateItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > metadata_; ::google::protobuf::internal::ArenaStringPtr key_; ::google::protobuf::internal::ArenaStringPtr value_; ::dapr::proto::common::v1::Etag* etag_; ::dapr::proto::common::v1::StateOptions* options_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // ------------------------------------------------------------------- class Etag : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.Etag) */ { public: Etag(); virtual ~Etag(); Etag(const Etag& from); inline Etag& operator=(const Etag& from) { CopyFrom(from); return *this; } #if LANG_CXX11 Etag(Etag&& from) noexcept : Etag() { *this = ::std::move(from); } inline Etag& operator=(Etag&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const Etag& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const Etag* internal_default_instance() { return reinterpret_cast<const Etag*>( &_Etag_default_instance_); } static constexpr int kIndexInFileMessages = 5; void Swap(Etag* other); friend void swap(Etag& a, Etag& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline Etag* New() const final { return CreateMaybeMessage<Etag>(NULL); } Etag* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<Etag>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Etag& from); void MergeFrom(const Etag& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Etag* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string value = 1; void clear_value(); static const int kValueFieldNumber = 1; const ::std::string& value() const; void set_value(const ::std::string& value); #if LANG_CXX11 void set_value(::std::string&& value); #endif void set_value(const char* value); void set_value(const char* value, size_t size); ::std::string* mutable_value(); ::std::string* release_value(); void set_allocated_value(::std::string* value); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.Etag) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr value_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // ------------------------------------------------------------------- class StateOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.StateOptions) */ { public: StateOptions(); virtual ~StateOptions(); StateOptions(const StateOptions& from); inline StateOptions& operator=(const StateOptions& from) { CopyFrom(from); return *this; } #if LANG_CXX11 StateOptions(StateOptions&& from) noexcept : StateOptions() { *this = ::std::move(from); } inline StateOptions& operator=(StateOptions&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const StateOptions& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StateOptions* internal_default_instance() { return reinterpret_cast<const StateOptions*>( &_StateOptions_default_instance_); } static constexpr int kIndexInFileMessages = 6; void Swap(StateOptions* other); friend void swap(StateOptions& a, StateOptions& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline StateOptions* New() const final { return CreateMaybeMessage<StateOptions>(NULL); } StateOptions* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<StateOptions>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const StateOptions& from); void MergeFrom(const StateOptions& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StateOptions* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef StateOptions_StateConcurrency StateConcurrency; static const StateConcurrency CONCURRENCY_UNSPECIFIED = StateOptions_StateConcurrency_CONCURRENCY_UNSPECIFIED; static const StateConcurrency CONCURRENCY_FIRST_WRITE = StateOptions_StateConcurrency_CONCURRENCY_FIRST_WRITE; static const StateConcurrency CONCURRENCY_LAST_WRITE = StateOptions_StateConcurrency_CONCURRENCY_LAST_WRITE; static inline bool StateConcurrency_IsValid(int value) { return StateOptions_StateConcurrency_IsValid(value); } static const StateConcurrency StateConcurrency_MIN = StateOptions_StateConcurrency_StateConcurrency_MIN; static const StateConcurrency StateConcurrency_MAX = StateOptions_StateConcurrency_StateConcurrency_MAX; static const int StateConcurrency_ARRAYSIZE = StateOptions_StateConcurrency_StateConcurrency_ARRAYSIZE; static inline const ::google::protobuf::EnumDescriptor* StateConcurrency_descriptor() { return StateOptions_StateConcurrency_descriptor(); } static inline const ::std::string& StateConcurrency_Name(StateConcurrency value) { return StateOptions_StateConcurrency_Name(value); } static inline bool StateConcurrency_Parse(const ::std::string& name, StateConcurrency* value) { return StateOptions_StateConcurrency_Parse(name, value); } typedef StateOptions_StateConsistency StateConsistency; static const StateConsistency CONSISTENCY_UNSPECIFIED = StateOptions_StateConsistency_CONSISTENCY_UNSPECIFIED; static const StateConsistency CONSISTENCY_EVENTUAL = StateOptions_StateConsistency_CONSISTENCY_EVENTUAL; static const StateConsistency CONSISTENCY_STRONG = StateOptions_StateConsistency_CONSISTENCY_STRONG; static inline bool StateConsistency_IsValid(int value) { return StateOptions_StateConsistency_IsValid(value); } static const StateConsistency StateConsistency_MIN = StateOptions_StateConsistency_StateConsistency_MIN; static const StateConsistency StateConsistency_MAX = StateOptions_StateConsistency_StateConsistency_MAX; static const int StateConsistency_ARRAYSIZE = StateOptions_StateConsistency_StateConsistency_ARRAYSIZE; static inline const ::google::protobuf::EnumDescriptor* StateConsistency_descriptor() { return StateOptions_StateConsistency_descriptor(); } static inline const ::std::string& StateConsistency_Name(StateConsistency value) { return StateOptions_StateConsistency_Name(value); } static inline bool StateConsistency_Parse(const ::std::string& name, StateConsistency* value) { return StateOptions_StateConsistency_Parse(name, value); } // accessors ------------------------------------------------------- // .dapr.proto.common.v1.StateOptions.StateConcurrency concurrency = 1; void clear_concurrency(); static const int kConcurrencyFieldNumber = 1; ::dapr::proto::common::v1::StateOptions_StateConcurrency concurrency() const; void set_concurrency(::dapr::proto::common::v1::StateOptions_StateConcurrency value); // .dapr.proto.common.v1.StateOptions.StateConsistency consistency = 2; void clear_consistency(); static const int kConsistencyFieldNumber = 2; ::dapr::proto::common::v1::StateOptions_StateConsistency consistency() const; void set_consistency(::dapr::proto::common::v1::StateOptions_StateConsistency value); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.StateOptions) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; int concurrency_; int consistency_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // ------------------------------------------------------------------- class ConfigurationItem_MetadataEntry_DoNotUse : public ::google::protobuf::internal::MapEntry<ConfigurationItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > { public: typedef ::google::protobuf::internal::MapEntry<ConfigurationItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > SuperType; ConfigurationItem_MetadataEntry_DoNotUse(); ConfigurationItem_MetadataEntry_DoNotUse(::google::protobuf::Arena* arena); void MergeFrom(const ConfigurationItem_MetadataEntry_DoNotUse& other); static const ConfigurationItem_MetadataEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const ConfigurationItem_MetadataEntry_DoNotUse*>(&_ConfigurationItem_MetadataEntry_DoNotUse_default_instance_); } void MergeFrom(const ::google::protobuf::Message& other) final; ::google::protobuf::Metadata GetMetadata() const; }; // ------------------------------------------------------------------- class ConfigurationItem : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.common.v1.ConfigurationItem) */ { public: ConfigurationItem(); virtual ~ConfigurationItem(); ConfigurationItem(const ConfigurationItem& from); inline ConfigurationItem& operator=(const ConfigurationItem& from) { CopyFrom(from); return *this; } #if LANG_CXX11 ConfigurationItem(ConfigurationItem&& from) noexcept : ConfigurationItem() { *this = ::std::move(from); } inline ConfigurationItem& operator=(ConfigurationItem&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const ConfigurationItem& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const ConfigurationItem* internal_default_instance() { return reinterpret_cast<const ConfigurationItem*>( &_ConfigurationItem_default_instance_); } static constexpr int kIndexInFileMessages = 8; void Swap(ConfigurationItem* other); friend void swap(ConfigurationItem& a, ConfigurationItem& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline ConfigurationItem* New() const final { return CreateMaybeMessage<ConfigurationItem>(NULL); } ConfigurationItem* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<ConfigurationItem>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ConfigurationItem& from); void MergeFrom(const ConfigurationItem& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ConfigurationItem* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // map<string, string> metadata = 4; int metadata_size() const; void clear_metadata(); static const int kMetadataFieldNumber = 4; const ::google::protobuf::Map< ::std::string, ::std::string >& metadata() const; ::google::protobuf::Map< ::std::string, ::std::string >* mutable_metadata(); // string key = 1; void clear_key(); static const int kKeyFieldNumber = 1; const ::std::string& key() const; void set_key(const ::std::string& value); #if LANG_CXX11 void set_key(::std::string&& value); #endif void set_key(const char* value); void set_key(const char* value, size_t size); ::std::string* mutable_key(); ::std::string* release_key(); void set_allocated_key(::std::string* key); // string value = 2; void clear_value(); static const int kValueFieldNumber = 2; const ::std::string& value() const; void set_value(const ::std::string& value); #if LANG_CXX11 void set_value(::std::string&& value); #endif void set_value(const char* value); void set_value(const char* value, size_t size); ::std::string* mutable_value(); ::std::string* release_value(); void set_allocated_value(::std::string* value); // string version = 3; void clear_version(); static const int kVersionFieldNumber = 3; const ::std::string& version() const; void set_version(const ::std::string& value); #if LANG_CXX11 void set_version(::std::string&& value); #endif void set_version(const char* value); void set_version(const char* value, size_t size); ::std::string* mutable_version(); ::std::string* release_version(); void set_allocated_version(::std::string* version); // @@protoc_insertion_point(class_scope:dapr.proto.common.v1.ConfigurationItem) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::MapField< ConfigurationItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > metadata_; ::google::protobuf::internal::ArenaStringPtr key_; ::google::protobuf::internal::ArenaStringPtr value_; ::google::protobuf::internal::ArenaStringPtr version_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::TableStruct; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // HTTPExtension // .dapr.proto.common.v1.HTTPExtension.Verb verb = 1; inline void HTTPExtension::clear_verb() { verb_ = 0; } inline ::dapr::proto::common::v1::HTTPExtension_Verb HTTPExtension::verb() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.HTTPExtension.verb) return static_cast< ::dapr::proto::common::v1::HTTPExtension_Verb >(verb_); } inline void HTTPExtension::set_verb(::dapr::proto::common::v1::HTTPExtension_Verb value) { verb_ = value; // @@protoc_insertion_point(field_set:dapr.proto.common.v1.HTTPExtension.verb) } // string querystring = 2; inline void HTTPExtension::clear_querystring() { querystring_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& HTTPExtension::querystring() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.HTTPExtension.querystring) return querystring_.GetNoArena(); } inline void HTTPExtension::set_querystring(const ::std::string& value) { querystring_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.HTTPExtension.querystring) } #if LANG_CXX11 inline void HTTPExtension::set_querystring(::std::string&& value) { querystring_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.HTTPExtension.querystring) } #endif inline void HTTPExtension::set_querystring(const char* value) { GOOGLE_DCHECK(value != NULL); querystring_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.HTTPExtension.querystring) } inline void HTTPExtension::set_querystring(const char* value, size_t size) { querystring_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.HTTPExtension.querystring) } inline ::std::string* HTTPExtension::mutable_querystring() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.HTTPExtension.querystring) return querystring_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* HTTPExtension::release_querystring() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.HTTPExtension.querystring) return querystring_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void HTTPExtension::set_allocated_querystring(::std::string* querystring) { if (querystring != NULL) { } else { } querystring_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), querystring); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.HTTPExtension.querystring) } // ------------------------------------------------------------------- // InvokeRequest // string method = 1; inline void InvokeRequest::clear_method() { method_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& InvokeRequest::method() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.InvokeRequest.method) return method_.GetNoArena(); } inline void InvokeRequest::set_method(const ::std::string& value) { method_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.InvokeRequest.method) } #if LANG_CXX11 inline void InvokeRequest::set_method(::std::string&& value) { method_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.InvokeRequest.method) } #endif inline void InvokeRequest::set_method(const char* value) { GOOGLE_DCHECK(value != NULL); method_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.InvokeRequest.method) } inline void InvokeRequest::set_method(const char* value, size_t size) { method_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.InvokeRequest.method) } inline ::std::string* InvokeRequest::mutable_method() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.InvokeRequest.method) return method_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* InvokeRequest::release_method() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.InvokeRequest.method) return method_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void InvokeRequest::set_allocated_method(::std::string* method) { if (method != NULL) { } else { } method_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), method); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.InvokeRequest.method) } // .google.protobuf.Any data = 2; inline bool InvokeRequest::has_data() const { return this != internal_default_instance() && data_ != NULL; } inline const ::google::protobuf::Any& InvokeRequest::_internal_data() const { return *data_; } inline const ::google::protobuf::Any& InvokeRequest::data() const { const ::google::protobuf::Any* p = data_; // @@protoc_insertion_point(field_get:dapr.proto.common.v1.InvokeRequest.data) return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::Any*>( &::google::protobuf::_Any_default_instance_); } inline ::google::protobuf::Any* InvokeRequest::release_data() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.InvokeRequest.data) ::google::protobuf::Any* temp = data_; data_ = NULL; return temp; } inline ::google::protobuf::Any* InvokeRequest::mutable_data() { if (data_ == NULL) { auto* p = CreateMaybeMessage<::google::protobuf::Any>(GetArenaNoVirtual()); data_ = p; } // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.InvokeRequest.data) return data_; } inline void InvokeRequest::set_allocated_data(::google::protobuf::Any* data) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(data_); } if (data) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { data = ::google::protobuf::internal::GetOwnedMessage( message_arena, data, submessage_arena); } } else { } data_ = data; // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.InvokeRequest.data) } // string content_type = 3; inline void InvokeRequest::clear_content_type() { content_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& InvokeRequest::content_type() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.InvokeRequest.content_type) return content_type_.GetNoArena(); } inline void InvokeRequest::set_content_type(const ::std::string& value) { content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.InvokeRequest.content_type) } #if LANG_CXX11 inline void InvokeRequest::set_content_type(::std::string&& value) { content_type_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.InvokeRequest.content_type) } #endif inline void InvokeRequest::set_content_type(const char* value) { GOOGLE_DCHECK(value != NULL); content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.InvokeRequest.content_type) } inline void InvokeRequest::set_content_type(const char* value, size_t size) { content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.InvokeRequest.content_type) } inline ::std::string* InvokeRequest::mutable_content_type() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.InvokeRequest.content_type) return content_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* InvokeRequest::release_content_type() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.InvokeRequest.content_type) return content_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void InvokeRequest::set_allocated_content_type(::std::string* content_type) { if (content_type != NULL) { } else { } content_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), content_type); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.InvokeRequest.content_type) } // .dapr.proto.common.v1.HTTPExtension http_extension = 4; inline bool InvokeRequest::has_http_extension() const { return this != internal_default_instance() && http_extension_ != NULL; } inline void InvokeRequest::clear_http_extension() { if (GetArenaNoVirtual() == NULL && http_extension_ != NULL) { delete http_extension_; } http_extension_ = NULL; } inline const ::dapr::proto::common::v1::HTTPExtension& InvokeRequest::_internal_http_extension() const { return *http_extension_; } inline const ::dapr::proto::common::v1::HTTPExtension& InvokeRequest::http_extension() const { const ::dapr::proto::common::v1::HTTPExtension* p = http_extension_; // @@protoc_insertion_point(field_get:dapr.proto.common.v1.InvokeRequest.http_extension) return p != NULL ? *p : *reinterpret_cast<const ::dapr::proto::common::v1::HTTPExtension*>( &::dapr::proto::common::v1::_HTTPExtension_default_instance_); } inline ::dapr::proto::common::v1::HTTPExtension* InvokeRequest::release_http_extension() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.InvokeRequest.http_extension) ::dapr::proto::common::v1::HTTPExtension* temp = http_extension_; http_extension_ = NULL; return temp; } inline ::dapr::proto::common::v1::HTTPExtension* InvokeRequest::mutable_http_extension() { if (http_extension_ == NULL) { auto* p = CreateMaybeMessage<::dapr::proto::common::v1::HTTPExtension>(GetArenaNoVirtual()); http_extension_ = p; } // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.InvokeRequest.http_extension) return http_extension_; } inline void InvokeRequest::set_allocated_http_extension(::dapr::proto::common::v1::HTTPExtension* http_extension) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete http_extension_; } if (http_extension) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { http_extension = ::google::protobuf::internal::GetOwnedMessage( message_arena, http_extension, submessage_arena); } } else { } http_extension_ = http_extension; // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.InvokeRequest.http_extension) } // ------------------------------------------------------------------- // InvokeResponse // .google.protobuf.Any data = 1; inline bool InvokeResponse::has_data() const { return this != internal_default_instance() && data_ != NULL; } inline const ::google::protobuf::Any& InvokeResponse::_internal_data() const { return *data_; } inline const ::google::protobuf::Any& InvokeResponse::data() const { const ::google::protobuf::Any* p = data_; // @@protoc_insertion_point(field_get:dapr.proto.common.v1.InvokeResponse.data) return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::Any*>( &::google::protobuf::_Any_default_instance_); } inline ::google::protobuf::Any* InvokeResponse::release_data() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.InvokeResponse.data) ::google::protobuf::Any* temp = data_; data_ = NULL; return temp; } inline ::google::protobuf::Any* InvokeResponse::mutable_data() { if (data_ == NULL) { auto* p = CreateMaybeMessage<::google::protobuf::Any>(GetArenaNoVirtual()); data_ = p; } // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.InvokeResponse.data) return data_; } inline void InvokeResponse::set_allocated_data(::google::protobuf::Any* data) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(data_); } if (data) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { data = ::google::protobuf::internal::GetOwnedMessage( message_arena, data, submessage_arena); } } else { } data_ = data; // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.InvokeResponse.data) } // string content_type = 2; inline void InvokeResponse::clear_content_type() { content_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& InvokeResponse::content_type() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.InvokeResponse.content_type) return content_type_.GetNoArena(); } inline void InvokeResponse::set_content_type(const ::std::string& value) { content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.InvokeResponse.content_type) } #if LANG_CXX11 inline void InvokeResponse::set_content_type(::std::string&& value) { content_type_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.InvokeResponse.content_type) } #endif inline void InvokeResponse::set_content_type(const char* value) { GOOGLE_DCHECK(value != NULL); content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.InvokeResponse.content_type) } inline void InvokeResponse::set_content_type(const char* value, size_t size) { content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.InvokeResponse.content_type) } inline ::std::string* InvokeResponse::mutable_content_type() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.InvokeResponse.content_type) return content_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* InvokeResponse::release_content_type() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.InvokeResponse.content_type) return content_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void InvokeResponse::set_allocated_content_type(::std::string* content_type) { if (content_type != NULL) { } else { } content_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), content_type); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.InvokeResponse.content_type) } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // StateItem // string key = 1; inline void StateItem::clear_key() { key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& StateItem::key() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.StateItem.key) return key_.GetNoArena(); } inline void StateItem::set_key(const ::std::string& value) { key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.StateItem.key) } #if LANG_CXX11 inline void StateItem::set_key(::std::string&& value) { key_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.StateItem.key) } #endif inline void StateItem::set_key(const char* value) { GOOGLE_DCHECK(value != NULL); key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.StateItem.key) } inline void StateItem::set_key(const char* value, size_t size) { key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.StateItem.key) } inline ::std::string* StateItem::mutable_key() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.StateItem.key) return key_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* StateItem::release_key() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.StateItem.key) return key_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void StateItem::set_allocated_key(::std::string* key) { if (key != NULL) { } else { } key_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), key); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.StateItem.key) } // bytes value = 2; inline void StateItem::clear_value() { value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& StateItem::value() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.StateItem.value) return value_.GetNoArena(); } inline void StateItem::set_value(const ::std::string& value) { value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.StateItem.value) } #if LANG_CXX11 inline void StateItem::set_value(::std::string&& value) { value_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.StateItem.value) } #endif inline void StateItem::set_value(const char* value) { GOOGLE_DCHECK(value != NULL); value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.StateItem.value) } inline void StateItem::set_value(const void* value, size_t size) { value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.StateItem.value) } inline ::std::string* StateItem::mutable_value() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.StateItem.value) return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* StateItem::release_value() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.StateItem.value) return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void StateItem::set_allocated_value(::std::string* value) { if (value != NULL) { } else { } value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.StateItem.value) } // .dapr.proto.common.v1.Etag etag = 3; inline bool StateItem::has_etag() const { return this != internal_default_instance() && etag_ != NULL; } inline void StateItem::clear_etag() { if (GetArenaNoVirtual() == NULL && etag_ != NULL) { delete etag_; } etag_ = NULL; } inline const ::dapr::proto::common::v1::Etag& StateItem::_internal_etag() const { return *etag_; } inline const ::dapr::proto::common::v1::Etag& StateItem::etag() const { const ::dapr::proto::common::v1::Etag* p = etag_; // @@protoc_insertion_point(field_get:dapr.proto.common.v1.StateItem.etag) return p != NULL ? *p : *reinterpret_cast<const ::dapr::proto::common::v1::Etag*>( &::dapr::proto::common::v1::_Etag_default_instance_); } inline ::dapr::proto::common::v1::Etag* StateItem::release_etag() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.StateItem.etag) ::dapr::proto::common::v1::Etag* temp = etag_; etag_ = NULL; return temp; } inline ::dapr::proto::common::v1::Etag* StateItem::mutable_etag() { if (etag_ == NULL) { auto* p = CreateMaybeMessage<::dapr::proto::common::v1::Etag>(GetArenaNoVirtual()); etag_ = p; } // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.StateItem.etag) return etag_; } inline void StateItem::set_allocated_etag(::dapr::proto::common::v1::Etag* etag) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete etag_; } if (etag) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { etag = ::google::protobuf::internal::GetOwnedMessage( message_arena, etag, submessage_arena); } } else { } etag_ = etag; // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.StateItem.etag) } // map<string, string> metadata = 4; inline int StateItem::metadata_size() const { return metadata_.size(); } inline void StateItem::clear_metadata() { metadata_.Clear(); } inline const ::google::protobuf::Map< ::std::string, ::std::string >& StateItem::metadata() const { // @@protoc_insertion_point(field_map:dapr.proto.common.v1.StateItem.metadata) return metadata_.GetMap(); } inline ::google::protobuf::Map< ::std::string, ::std::string >* StateItem::mutable_metadata() { // @@protoc_insertion_point(field_mutable_map:dapr.proto.common.v1.StateItem.metadata) return metadata_.MutableMap(); } // .dapr.proto.common.v1.StateOptions options = 5; inline bool StateItem::has_options() const { return this != internal_default_instance() && options_ != NULL; } inline void StateItem::clear_options() { if (GetArenaNoVirtual() == NULL && options_ != NULL) { delete options_; } options_ = NULL; } inline const ::dapr::proto::common::v1::StateOptions& StateItem::_internal_options() const { return *options_; } inline const ::dapr::proto::common::v1::StateOptions& StateItem::options() const { const ::dapr::proto::common::v1::StateOptions* p = options_; // @@protoc_insertion_point(field_get:dapr.proto.common.v1.StateItem.options) return p != NULL ? *p : *reinterpret_cast<const ::dapr::proto::common::v1::StateOptions*>( &::dapr::proto::common::v1::_StateOptions_default_instance_); } inline ::dapr::proto::common::v1::StateOptions* StateItem::release_options() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.StateItem.options) ::dapr::proto::common::v1::StateOptions* temp = options_; options_ = NULL; return temp; } inline ::dapr::proto::common::v1::StateOptions* StateItem::mutable_options() { if (options_ == NULL) { auto* p = CreateMaybeMessage<::dapr::proto::common::v1::StateOptions>(GetArenaNoVirtual()); options_ = p; } // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.StateItem.options) return options_; } inline void StateItem::set_allocated_options(::dapr::proto::common::v1::StateOptions* options) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete options_; } if (options) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { options = ::google::protobuf::internal::GetOwnedMessage( message_arena, options, submessage_arena); } } else { } options_ = options; // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.StateItem.options) } // ------------------------------------------------------------------- // Etag // string value = 1; inline void Etag::clear_value() { value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& Etag::value() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.Etag.value) return value_.GetNoArena(); } inline void Etag::set_value(const ::std::string& value) { value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.Etag.value) } #if LANG_CXX11 inline void Etag::set_value(::std::string&& value) { value_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.Etag.value) } #endif inline void Etag::set_value(const char* value) { GOOGLE_DCHECK(value != NULL); value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.Etag.value) } inline void Etag::set_value(const char* value, size_t size) { value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.Etag.value) } inline ::std::string* Etag::mutable_value() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.Etag.value) return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* Etag::release_value() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.Etag.value) return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void Etag::set_allocated_value(::std::string* value) { if (value != NULL) { } else { } value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.Etag.value) } // ------------------------------------------------------------------- // StateOptions // .dapr.proto.common.v1.StateOptions.StateConcurrency concurrency = 1; inline void StateOptions::clear_concurrency() { concurrency_ = 0; } inline ::dapr::proto::common::v1::StateOptions_StateConcurrency StateOptions::concurrency() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.StateOptions.concurrency) return static_cast< ::dapr::proto::common::v1::StateOptions_StateConcurrency >(concurrency_); } inline void StateOptions::set_concurrency(::dapr::proto::common::v1::StateOptions_StateConcurrency value) { concurrency_ = value; // @@protoc_insertion_point(field_set:dapr.proto.common.v1.StateOptions.concurrency) } // .dapr.proto.common.v1.StateOptions.StateConsistency consistency = 2; inline void StateOptions::clear_consistency() { consistency_ = 0; } inline ::dapr::proto::common::v1::StateOptions_StateConsistency StateOptions::consistency() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.StateOptions.consistency) return static_cast< ::dapr::proto::common::v1::StateOptions_StateConsistency >(consistency_); } inline void StateOptions::set_consistency(::dapr::proto::common::v1::StateOptions_StateConsistency value) { consistency_ = value; // @@protoc_insertion_point(field_set:dapr.proto.common.v1.StateOptions.consistency) } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ConfigurationItem // string key = 1; inline void ConfigurationItem::clear_key() { key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& ConfigurationItem::key() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.ConfigurationItem.key) return key_.GetNoArena(); } inline void ConfigurationItem::set_key(const ::std::string& value) { key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.ConfigurationItem.key) } #if LANG_CXX11 inline void ConfigurationItem::set_key(::std::string&& value) { key_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.ConfigurationItem.key) } #endif inline void ConfigurationItem::set_key(const char* value) { GOOGLE_DCHECK(value != NULL); key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.ConfigurationItem.key) } inline void ConfigurationItem::set_key(const char* value, size_t size) { key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.ConfigurationItem.key) } inline ::std::string* ConfigurationItem::mutable_key() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.ConfigurationItem.key) return key_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* ConfigurationItem::release_key() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.ConfigurationItem.key) return key_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void ConfigurationItem::set_allocated_key(::std::string* key) { if (key != NULL) { } else { } key_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), key); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.ConfigurationItem.key) } // string value = 2; inline void ConfigurationItem::clear_value() { value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& ConfigurationItem::value() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.ConfigurationItem.value) return value_.GetNoArena(); } inline void ConfigurationItem::set_value(const ::std::string& value) { value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.ConfigurationItem.value) } #if LANG_CXX11 inline void ConfigurationItem::set_value(::std::string&& value) { value_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.ConfigurationItem.value) } #endif inline void ConfigurationItem::set_value(const char* value) { GOOGLE_DCHECK(value != NULL); value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.ConfigurationItem.value) } inline void ConfigurationItem::set_value(const char* value, size_t size) { value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.ConfigurationItem.value) } inline ::std::string* ConfigurationItem::mutable_value() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.ConfigurationItem.value) return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* ConfigurationItem::release_value() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.ConfigurationItem.value) return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void ConfigurationItem::set_allocated_value(::std::string* value) { if (value != NULL) { } else { } value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.ConfigurationItem.value) } // string version = 3; inline void ConfigurationItem::clear_version() { version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& ConfigurationItem::version() const { // @@protoc_insertion_point(field_get:dapr.proto.common.v1.ConfigurationItem.version) return version_.GetNoArena(); } inline void ConfigurationItem::set_version(const ::std::string& value) { version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.common.v1.ConfigurationItem.version) } #if LANG_CXX11 inline void ConfigurationItem::set_version(::std::string&& value) { version_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.common.v1.ConfigurationItem.version) } #endif inline void ConfigurationItem::set_version(const char* value) { GOOGLE_DCHECK(value != NULL); version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.common.v1.ConfigurationItem.version) } inline void ConfigurationItem::set_version(const char* value, size_t size) { version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.common.v1.ConfigurationItem.version) } inline ::std::string* ConfigurationItem::mutable_version() { // @@protoc_insertion_point(field_mutable:dapr.proto.common.v1.ConfigurationItem.version) return version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* ConfigurationItem::release_version() { // @@protoc_insertion_point(field_release:dapr.proto.common.v1.ConfigurationItem.version) return version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void ConfigurationItem::set_allocated_version(::std::string* version) { if (version != NULL) { } else { } version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), version); // @@protoc_insertion_point(field_set_allocated:dapr.proto.common.v1.ConfigurationItem.version) } // map<string, string> metadata = 4; inline int ConfigurationItem::metadata_size() const { return metadata_.size(); } inline void ConfigurationItem::clear_metadata() { metadata_.Clear(); } inline const ::google::protobuf::Map< ::std::string, ::std::string >& ConfigurationItem::metadata() const { // @@protoc_insertion_point(field_map:dapr.proto.common.v1.ConfigurationItem.metadata) return metadata_.GetMap(); } inline ::google::protobuf::Map< ::std::string, ::std::string >* ConfigurationItem::mutable_metadata() { // @@protoc_insertion_point(field_mutable_map:dapr.proto.common.v1.ConfigurationItem.metadata) return metadata_.MutableMap(); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace v1 } // namespace common } // namespace proto } // namespace dapr namespace google { namespace protobuf { template <> struct is_proto_enum< ::dapr::proto::common::v1::HTTPExtension_Verb> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::dapr::proto::common::v1::HTTPExtension_Verb>() { return ::dapr::proto::common::v1::HTTPExtension_Verb_descriptor(); } template <> struct is_proto_enum< ::dapr::proto::common::v1::StateOptions_StateConcurrency> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::dapr::proto::common::v1::StateOptions_StateConcurrency>() { return ::dapr::proto::common::v1::StateOptions_StateConcurrency_descriptor(); } template <> struct is_proto_enum< ::dapr::proto::common::v1::StateOptions_StateConsistency> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::dapr::proto::common::v1::StateOptions_StateConsistency>() { return ::dapr::proto::common::v1::StateOptions_StateConsistency_descriptor(); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto <|start_filename|>src/dapr/proto/runtime/v1/appcallback.pb.h<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: dapr/proto/runtime/v1/appcallback.proto #ifndef PROTOBUF_INCLUDED_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto #define PROTOBUF_INCLUDED_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3006001 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/map.h> // IWYU pragma: export #include <google/protobuf/map_entry.h> #include <google/protobuf/map_field_inl.h> #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/empty.pb.h> #include "dapr/proto/common/v1/common.pb.h" // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto namespace protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[11]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors(); } // namespace protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto namespace dapr { namespace proto { namespace runtime { namespace v1 { class BindingEventRequest; class BindingEventRequestDefaultTypeInternal; extern BindingEventRequestDefaultTypeInternal _BindingEventRequest_default_instance_; class BindingEventRequest_MetadataEntry_DoNotUse; class BindingEventRequest_MetadataEntry_DoNotUseDefaultTypeInternal; extern BindingEventRequest_MetadataEntry_DoNotUseDefaultTypeInternal _BindingEventRequest_MetadataEntry_DoNotUse_default_instance_; class BindingEventResponse; class BindingEventResponseDefaultTypeInternal; extern BindingEventResponseDefaultTypeInternal _BindingEventResponse_default_instance_; class ListInputBindingsResponse; class ListInputBindingsResponseDefaultTypeInternal; extern ListInputBindingsResponseDefaultTypeInternal _ListInputBindingsResponse_default_instance_; class ListTopicSubscriptionsResponse; class ListTopicSubscriptionsResponseDefaultTypeInternal; extern ListTopicSubscriptionsResponseDefaultTypeInternal _ListTopicSubscriptionsResponse_default_instance_; class TopicEventRequest; class TopicEventRequestDefaultTypeInternal; extern TopicEventRequestDefaultTypeInternal _TopicEventRequest_default_instance_; class TopicEventResponse; class TopicEventResponseDefaultTypeInternal; extern TopicEventResponseDefaultTypeInternal _TopicEventResponse_default_instance_; class TopicRoutes; class TopicRoutesDefaultTypeInternal; extern TopicRoutesDefaultTypeInternal _TopicRoutes_default_instance_; class TopicRule; class TopicRuleDefaultTypeInternal; extern TopicRuleDefaultTypeInternal _TopicRule_default_instance_; class TopicSubscription; class TopicSubscriptionDefaultTypeInternal; extern TopicSubscriptionDefaultTypeInternal _TopicSubscription_default_instance_; class TopicSubscription_MetadataEntry_DoNotUse; class TopicSubscription_MetadataEntry_DoNotUseDefaultTypeInternal; extern TopicSubscription_MetadataEntry_DoNotUseDefaultTypeInternal _TopicSubscription_MetadataEntry_DoNotUse_default_instance_; } // namespace v1 } // namespace runtime } // namespace proto } // namespace dapr namespace google { namespace protobuf { template<> ::dapr::proto::runtime::v1::BindingEventRequest* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::BindingEventRequest>(Arena*); template<> ::dapr::proto::runtime::v1::BindingEventRequest_MetadataEntry_DoNotUse* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::BindingEventRequest_MetadataEntry_DoNotUse>(Arena*); template<> ::dapr::proto::runtime::v1::BindingEventResponse* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::BindingEventResponse>(Arena*); template<> ::dapr::proto::runtime::v1::ListInputBindingsResponse* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::ListInputBindingsResponse>(Arena*); template<> ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse>(Arena*); template<> ::dapr::proto::runtime::v1::TopicEventRequest* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::TopicEventRequest>(Arena*); template<> ::dapr::proto::runtime::v1::TopicEventResponse* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::TopicEventResponse>(Arena*); template<> ::dapr::proto::runtime::v1::TopicRoutes* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::TopicRoutes>(Arena*); template<> ::dapr::proto::runtime::v1::TopicRule* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::TopicRule>(Arena*); template<> ::dapr::proto::runtime::v1::TopicSubscription* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::TopicSubscription>(Arena*); template<> ::dapr::proto::runtime::v1::TopicSubscription_MetadataEntry_DoNotUse* Arena::CreateMaybeMessage<::dapr::proto::runtime::v1::TopicSubscription_MetadataEntry_DoNotUse>(Arena*); } // namespace protobuf } // namespace google namespace dapr { namespace proto { namespace runtime { namespace v1 { enum TopicEventResponse_TopicEventResponseStatus { TopicEventResponse_TopicEventResponseStatus_SUCCESS = 0, TopicEventResponse_TopicEventResponseStatus_RETRY = 1, TopicEventResponse_TopicEventResponseStatus_DROP = 2, TopicEventResponse_TopicEventResponseStatus_TopicEventResponse_TopicEventResponseStatus_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, TopicEventResponse_TopicEventResponseStatus_TopicEventResponse_TopicEventResponseStatus_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool TopicEventResponse_TopicEventResponseStatus_IsValid(int value); const TopicEventResponse_TopicEventResponseStatus TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_MIN = TopicEventResponse_TopicEventResponseStatus_SUCCESS; const TopicEventResponse_TopicEventResponseStatus TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_MAX = TopicEventResponse_TopicEventResponseStatus_DROP; const int TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_ARRAYSIZE = TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_MAX + 1; const ::google::protobuf::EnumDescriptor* TopicEventResponse_TopicEventResponseStatus_descriptor(); inline const ::std::string& TopicEventResponse_TopicEventResponseStatus_Name(TopicEventResponse_TopicEventResponseStatus value) { return ::google::protobuf::internal::NameOfEnum( TopicEventResponse_TopicEventResponseStatus_descriptor(), value); } inline bool TopicEventResponse_TopicEventResponseStatus_Parse( const ::std::string& name, TopicEventResponse_TopicEventResponseStatus* value) { return ::google::protobuf::internal::ParseNamedEnum<TopicEventResponse_TopicEventResponseStatus>( TopicEventResponse_TopicEventResponseStatus_descriptor(), name, value); } enum BindingEventResponse_BindingEventConcurrency { BindingEventResponse_BindingEventConcurrency_SEQUENTIAL = 0, BindingEventResponse_BindingEventConcurrency_PARALLEL = 1, BindingEventResponse_BindingEventConcurrency_BindingEventResponse_BindingEventConcurrency_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min, BindingEventResponse_BindingEventConcurrency_BindingEventResponse_BindingEventConcurrency_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max }; bool BindingEventResponse_BindingEventConcurrency_IsValid(int value); const BindingEventResponse_BindingEventConcurrency BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_MIN = BindingEventResponse_BindingEventConcurrency_SEQUENTIAL; const BindingEventResponse_BindingEventConcurrency BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_MAX = BindingEventResponse_BindingEventConcurrency_PARALLEL; const int BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_ARRAYSIZE = BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_MAX + 1; const ::google::protobuf::EnumDescriptor* BindingEventResponse_BindingEventConcurrency_descriptor(); inline const ::std::string& BindingEventResponse_BindingEventConcurrency_Name(BindingEventResponse_BindingEventConcurrency value) { return ::google::protobuf::internal::NameOfEnum( BindingEventResponse_BindingEventConcurrency_descriptor(), value); } inline bool BindingEventResponse_BindingEventConcurrency_Parse( const ::std::string& name, BindingEventResponse_BindingEventConcurrency* value) { return ::google::protobuf::internal::ParseNamedEnum<BindingEventResponse_BindingEventConcurrency>( BindingEventResponse_BindingEventConcurrency_descriptor(), name, value); } // =================================================================== class TopicEventRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.TopicEventRequest) */ { public: TopicEventRequest(); virtual ~TopicEventRequest(); TopicEventRequest(const TopicEventRequest& from); inline TopicEventRequest& operator=(const TopicEventRequest& from) { CopyFrom(from); return *this; } #if LANG_CXX11 TopicEventRequest(TopicEventRequest&& from) noexcept : TopicEventRequest() { *this = ::std::move(from); } inline TopicEventRequest& operator=(TopicEventRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const TopicEventRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const TopicEventRequest* internal_default_instance() { return reinterpret_cast<const TopicEventRequest*>( &_TopicEventRequest_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(TopicEventRequest* other); friend void swap(TopicEventRequest& a, TopicEventRequest& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline TopicEventRequest* New() const final { return CreateMaybeMessage<TopicEventRequest>(NULL); } TopicEventRequest* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<TopicEventRequest>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const TopicEventRequest& from); void MergeFrom(const TopicEventRequest& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TopicEventRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string id = 1; void clear_id(); static const int kIdFieldNumber = 1; const ::std::string& id() const; void set_id(const ::std::string& value); #if LANG_CXX11 void set_id(::std::string&& value); #endif void set_id(const char* value); void set_id(const char* value, size_t size); ::std::string* mutable_id(); ::std::string* release_id(); void set_allocated_id(::std::string* id); // string source = 2; void clear_source(); static const int kSourceFieldNumber = 2; const ::std::string& source() const; void set_source(const ::std::string& value); #if LANG_CXX11 void set_source(::std::string&& value); #endif void set_source(const char* value); void set_source(const char* value, size_t size); ::std::string* mutable_source(); ::std::string* release_source(); void set_allocated_source(::std::string* source); // string type = 3; void clear_type(); static const int kTypeFieldNumber = 3; const ::std::string& type() const; void set_type(const ::std::string& value); #if LANG_CXX11 void set_type(::std::string&& value); #endif void set_type(const char* value); void set_type(const char* value, size_t size); ::std::string* mutable_type(); ::std::string* release_type(); void set_allocated_type(::std::string* type); // string spec_version = 4; void clear_spec_version(); static const int kSpecVersionFieldNumber = 4; const ::std::string& spec_version() const; void set_spec_version(const ::std::string& value); #if LANG_CXX11 void set_spec_version(::std::string&& value); #endif void set_spec_version(const char* value); void set_spec_version(const char* value, size_t size); ::std::string* mutable_spec_version(); ::std::string* release_spec_version(); void set_allocated_spec_version(::std::string* spec_version); // string data_content_type = 5; void clear_data_content_type(); static const int kDataContentTypeFieldNumber = 5; const ::std::string& data_content_type() const; void set_data_content_type(const ::std::string& value); #if LANG_CXX11 void set_data_content_type(::std::string&& value); #endif void set_data_content_type(const char* value); void set_data_content_type(const char* value, size_t size); ::std::string* mutable_data_content_type(); ::std::string* release_data_content_type(); void set_allocated_data_content_type(::std::string* data_content_type); // string topic = 6; void clear_topic(); static const int kTopicFieldNumber = 6; const ::std::string& topic() const; void set_topic(const ::std::string& value); #if LANG_CXX11 void set_topic(::std::string&& value); #endif void set_topic(const char* value); void set_topic(const char* value, size_t size); ::std::string* mutable_topic(); ::std::string* release_topic(); void set_allocated_topic(::std::string* topic); // bytes data = 7; void clear_data(); static const int kDataFieldNumber = 7; const ::std::string& data() const; void set_data(const ::std::string& value); #if LANG_CXX11 void set_data(::std::string&& value); #endif void set_data(const char* value); void set_data(const void* value, size_t size); ::std::string* mutable_data(); ::std::string* release_data(); void set_allocated_data(::std::string* data); // string pubsub_name = 8; void clear_pubsub_name(); static const int kPubsubNameFieldNumber = 8; const ::std::string& pubsub_name() const; void set_pubsub_name(const ::std::string& value); #if LANG_CXX11 void set_pubsub_name(::std::string&& value); #endif void set_pubsub_name(const char* value); void set_pubsub_name(const char* value, size_t size); ::std::string* mutable_pubsub_name(); ::std::string* release_pubsub_name(); void set_allocated_pubsub_name(::std::string* pubsub_name); // string path = 9; void clear_path(); static const int kPathFieldNumber = 9; const ::std::string& path() const; void set_path(const ::std::string& value); #if LANG_CXX11 void set_path(::std::string&& value); #endif void set_path(const char* value); void set_path(const char* value, size_t size); ::std::string* mutable_path(); ::std::string* release_path(); void set_allocated_path(::std::string* path); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.TopicEventRequest) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr id_; ::google::protobuf::internal::ArenaStringPtr source_; ::google::protobuf::internal::ArenaStringPtr type_; ::google::protobuf::internal::ArenaStringPtr spec_version_; ::google::protobuf::internal::ArenaStringPtr data_content_type_; ::google::protobuf::internal::ArenaStringPtr topic_; ::google::protobuf::internal::ArenaStringPtr data_; ::google::protobuf::internal::ArenaStringPtr pubsub_name_; ::google::protobuf::internal::ArenaStringPtr path_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class TopicEventResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.TopicEventResponse) */ { public: TopicEventResponse(); virtual ~TopicEventResponse(); TopicEventResponse(const TopicEventResponse& from); inline TopicEventResponse& operator=(const TopicEventResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 TopicEventResponse(TopicEventResponse&& from) noexcept : TopicEventResponse() { *this = ::std::move(from); } inline TopicEventResponse& operator=(TopicEventResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const TopicEventResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const TopicEventResponse* internal_default_instance() { return reinterpret_cast<const TopicEventResponse*>( &_TopicEventResponse_default_instance_); } static constexpr int kIndexInFileMessages = 1; void Swap(TopicEventResponse* other); friend void swap(TopicEventResponse& a, TopicEventResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline TopicEventResponse* New() const final { return CreateMaybeMessage<TopicEventResponse>(NULL); } TopicEventResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<TopicEventResponse>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const TopicEventResponse& from); void MergeFrom(const TopicEventResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TopicEventResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef TopicEventResponse_TopicEventResponseStatus TopicEventResponseStatus; static const TopicEventResponseStatus SUCCESS = TopicEventResponse_TopicEventResponseStatus_SUCCESS; static const TopicEventResponseStatus RETRY = TopicEventResponse_TopicEventResponseStatus_RETRY; static const TopicEventResponseStatus DROP = TopicEventResponse_TopicEventResponseStatus_DROP; static inline bool TopicEventResponseStatus_IsValid(int value) { return TopicEventResponse_TopicEventResponseStatus_IsValid(value); } static const TopicEventResponseStatus TopicEventResponseStatus_MIN = TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_MIN; static const TopicEventResponseStatus TopicEventResponseStatus_MAX = TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_MAX; static const int TopicEventResponseStatus_ARRAYSIZE = TopicEventResponse_TopicEventResponseStatus_TopicEventResponseStatus_ARRAYSIZE; static inline const ::google::protobuf::EnumDescriptor* TopicEventResponseStatus_descriptor() { return TopicEventResponse_TopicEventResponseStatus_descriptor(); } static inline const ::std::string& TopicEventResponseStatus_Name(TopicEventResponseStatus value) { return TopicEventResponse_TopicEventResponseStatus_Name(value); } static inline bool TopicEventResponseStatus_Parse(const ::std::string& name, TopicEventResponseStatus* value) { return TopicEventResponse_TopicEventResponseStatus_Parse(name, value); } // accessors ------------------------------------------------------- // .dapr.proto.runtime.v1.TopicEventResponse.TopicEventResponseStatus status = 1; void clear_status(); static const int kStatusFieldNumber = 1; ::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus status() const; void set_status(::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus value); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.TopicEventResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; int status_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class BindingEventRequest_MetadataEntry_DoNotUse : public ::google::protobuf::internal::MapEntry<BindingEventRequest_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > { public: typedef ::google::protobuf::internal::MapEntry<BindingEventRequest_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > SuperType; BindingEventRequest_MetadataEntry_DoNotUse(); BindingEventRequest_MetadataEntry_DoNotUse(::google::protobuf::Arena* arena); void MergeFrom(const BindingEventRequest_MetadataEntry_DoNotUse& other); static const BindingEventRequest_MetadataEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const BindingEventRequest_MetadataEntry_DoNotUse*>(&_BindingEventRequest_MetadataEntry_DoNotUse_default_instance_); } void MergeFrom(const ::google::protobuf::Message& other) final; ::google::protobuf::Metadata GetMetadata() const; }; // ------------------------------------------------------------------- class BindingEventRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.BindingEventRequest) */ { public: BindingEventRequest(); virtual ~BindingEventRequest(); BindingEventRequest(const BindingEventRequest& from); inline BindingEventRequest& operator=(const BindingEventRequest& from) { CopyFrom(from); return *this; } #if LANG_CXX11 BindingEventRequest(BindingEventRequest&& from) noexcept : BindingEventRequest() { *this = ::std::move(from); } inline BindingEventRequest& operator=(BindingEventRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const BindingEventRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const BindingEventRequest* internal_default_instance() { return reinterpret_cast<const BindingEventRequest*>( &_BindingEventRequest_default_instance_); } static constexpr int kIndexInFileMessages = 3; void Swap(BindingEventRequest* other); friend void swap(BindingEventRequest& a, BindingEventRequest& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline BindingEventRequest* New() const final { return CreateMaybeMessage<BindingEventRequest>(NULL); } BindingEventRequest* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<BindingEventRequest>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const BindingEventRequest& from); void MergeFrom(const BindingEventRequest& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BindingEventRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // map<string, string> metadata = 3; int metadata_size() const; void clear_metadata(); static const int kMetadataFieldNumber = 3; const ::google::protobuf::Map< ::std::string, ::std::string >& metadata() const; ::google::protobuf::Map< ::std::string, ::std::string >* mutable_metadata(); // string name = 1; void clear_name(); static const int kNameFieldNumber = 1; const ::std::string& name() const; void set_name(const ::std::string& value); #if LANG_CXX11 void set_name(::std::string&& value); #endif void set_name(const char* value); void set_name(const char* value, size_t size); ::std::string* mutable_name(); ::std::string* release_name(); void set_allocated_name(::std::string* name); // bytes data = 2; void clear_data(); static const int kDataFieldNumber = 2; const ::std::string& data() const; void set_data(const ::std::string& value); #if LANG_CXX11 void set_data(::std::string&& value); #endif void set_data(const char* value); void set_data(const void* value, size_t size); ::std::string* mutable_data(); ::std::string* release_data(); void set_allocated_data(::std::string* data); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.BindingEventRequest) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::MapField< BindingEventRequest_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > metadata_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr data_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class BindingEventResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.BindingEventResponse) */ { public: BindingEventResponse(); virtual ~BindingEventResponse(); BindingEventResponse(const BindingEventResponse& from); inline BindingEventResponse& operator=(const BindingEventResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 BindingEventResponse(BindingEventResponse&& from) noexcept : BindingEventResponse() { *this = ::std::move(from); } inline BindingEventResponse& operator=(BindingEventResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const BindingEventResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const BindingEventResponse* internal_default_instance() { return reinterpret_cast<const BindingEventResponse*>( &_BindingEventResponse_default_instance_); } static constexpr int kIndexInFileMessages = 4; void Swap(BindingEventResponse* other); friend void swap(BindingEventResponse& a, BindingEventResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline BindingEventResponse* New() const final { return CreateMaybeMessage<BindingEventResponse>(NULL); } BindingEventResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<BindingEventResponse>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const BindingEventResponse& from); void MergeFrom(const BindingEventResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BindingEventResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef BindingEventResponse_BindingEventConcurrency BindingEventConcurrency; static const BindingEventConcurrency SEQUENTIAL = BindingEventResponse_BindingEventConcurrency_SEQUENTIAL; static const BindingEventConcurrency PARALLEL = BindingEventResponse_BindingEventConcurrency_PARALLEL; static inline bool BindingEventConcurrency_IsValid(int value) { return BindingEventResponse_BindingEventConcurrency_IsValid(value); } static const BindingEventConcurrency BindingEventConcurrency_MIN = BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_MIN; static const BindingEventConcurrency BindingEventConcurrency_MAX = BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_MAX; static const int BindingEventConcurrency_ARRAYSIZE = BindingEventResponse_BindingEventConcurrency_BindingEventConcurrency_ARRAYSIZE; static inline const ::google::protobuf::EnumDescriptor* BindingEventConcurrency_descriptor() { return BindingEventResponse_BindingEventConcurrency_descriptor(); } static inline const ::std::string& BindingEventConcurrency_Name(BindingEventConcurrency value) { return BindingEventResponse_BindingEventConcurrency_Name(value); } static inline bool BindingEventConcurrency_Parse(const ::std::string& name, BindingEventConcurrency* value) { return BindingEventResponse_BindingEventConcurrency_Parse(name, value); } // accessors ------------------------------------------------------- // repeated .dapr.proto.common.v1.StateItem states = 2; int states_size() const; void clear_states(); static const int kStatesFieldNumber = 2; ::dapr::proto::common::v1::StateItem* mutable_states(int index); ::google::protobuf::RepeatedPtrField< ::dapr::proto::common::v1::StateItem >* mutable_states(); const ::dapr::proto::common::v1::StateItem& states(int index) const; ::dapr::proto::common::v1::StateItem* add_states(); const ::google::protobuf::RepeatedPtrField< ::dapr::proto::common::v1::StateItem >& states() const; // repeated string to = 3; int to_size() const; void clear_to(); static const int kToFieldNumber = 3; const ::std::string& to(int index) const; ::std::string* mutable_to(int index); void set_to(int index, const ::std::string& value); #if LANG_CXX11 void set_to(int index, ::std::string&& value); #endif void set_to(int index, const char* value); void set_to(int index, const char* value, size_t size); ::std::string* add_to(); void add_to(const ::std::string& value); #if LANG_CXX11 void add_to(::std::string&& value); #endif void add_to(const char* value); void add_to(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField< ::std::string>& to() const; ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_to(); // string store_name = 1; void clear_store_name(); static const int kStoreNameFieldNumber = 1; const ::std::string& store_name() const; void set_store_name(const ::std::string& value); #if LANG_CXX11 void set_store_name(::std::string&& value); #endif void set_store_name(const char* value); void set_store_name(const char* value, size_t size); ::std::string* mutable_store_name(); ::std::string* release_store_name(); void set_allocated_store_name(::std::string* store_name); // bytes data = 4; void clear_data(); static const int kDataFieldNumber = 4; const ::std::string& data() const; void set_data(const ::std::string& value); #if LANG_CXX11 void set_data(::std::string&& value); #endif void set_data(const char* value); void set_data(const void* value, size_t size); ::std::string* mutable_data(); ::std::string* release_data(); void set_allocated_data(::std::string* data); // .dapr.proto.runtime.v1.BindingEventResponse.BindingEventConcurrency concurrency = 5; void clear_concurrency(); static const int kConcurrencyFieldNumber = 5; ::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency concurrency() const; void set_concurrency(::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency value); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.BindingEventResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::dapr::proto::common::v1::StateItem > states_; ::google::protobuf::RepeatedPtrField< ::std::string> to_; ::google::protobuf::internal::ArenaStringPtr store_name_; ::google::protobuf::internal::ArenaStringPtr data_; int concurrency_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class ListTopicSubscriptionsResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse) */ { public: ListTopicSubscriptionsResponse(); virtual ~ListTopicSubscriptionsResponse(); ListTopicSubscriptionsResponse(const ListTopicSubscriptionsResponse& from); inline ListTopicSubscriptionsResponse& operator=(const ListTopicSubscriptionsResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 ListTopicSubscriptionsResponse(ListTopicSubscriptionsResponse&& from) noexcept : ListTopicSubscriptionsResponse() { *this = ::std::move(from); } inline ListTopicSubscriptionsResponse& operator=(ListTopicSubscriptionsResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const ListTopicSubscriptionsResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const ListTopicSubscriptionsResponse* internal_default_instance() { return reinterpret_cast<const ListTopicSubscriptionsResponse*>( &_ListTopicSubscriptionsResponse_default_instance_); } static constexpr int kIndexInFileMessages = 5; void Swap(ListTopicSubscriptionsResponse* other); friend void swap(ListTopicSubscriptionsResponse& a, ListTopicSubscriptionsResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline ListTopicSubscriptionsResponse* New() const final { return CreateMaybeMessage<ListTopicSubscriptionsResponse>(NULL); } ListTopicSubscriptionsResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<ListTopicSubscriptionsResponse>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ListTopicSubscriptionsResponse& from); void MergeFrom(const ListTopicSubscriptionsResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ListTopicSubscriptionsResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .dapr.proto.runtime.v1.TopicSubscription subscriptions = 1; int subscriptions_size() const; void clear_subscriptions(); static const int kSubscriptionsFieldNumber = 1; ::dapr::proto::runtime::v1::TopicSubscription* mutable_subscriptions(int index); ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicSubscription >* mutable_subscriptions(); const ::dapr::proto::runtime::v1::TopicSubscription& subscriptions(int index) const; ::dapr::proto::runtime::v1::TopicSubscription* add_subscriptions(); const ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicSubscription >& subscriptions() const; // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicSubscription > subscriptions_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class TopicSubscription_MetadataEntry_DoNotUse : public ::google::protobuf::internal::MapEntry<TopicSubscription_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > { public: typedef ::google::protobuf::internal::MapEntry<TopicSubscription_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > SuperType; TopicSubscription_MetadataEntry_DoNotUse(); TopicSubscription_MetadataEntry_DoNotUse(::google::protobuf::Arena* arena); void MergeFrom(const TopicSubscription_MetadataEntry_DoNotUse& other); static const TopicSubscription_MetadataEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TopicSubscription_MetadataEntry_DoNotUse*>(&_TopicSubscription_MetadataEntry_DoNotUse_default_instance_); } void MergeFrom(const ::google::protobuf::Message& other) final; ::google::protobuf::Metadata GetMetadata() const; }; // ------------------------------------------------------------------- class TopicSubscription : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.TopicSubscription) */ { public: TopicSubscription(); virtual ~TopicSubscription(); TopicSubscription(const TopicSubscription& from); inline TopicSubscription& operator=(const TopicSubscription& from) { CopyFrom(from); return *this; } #if LANG_CXX11 TopicSubscription(TopicSubscription&& from) noexcept : TopicSubscription() { *this = ::std::move(from); } inline TopicSubscription& operator=(TopicSubscription&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const TopicSubscription& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const TopicSubscription* internal_default_instance() { return reinterpret_cast<const TopicSubscription*>( &_TopicSubscription_default_instance_); } static constexpr int kIndexInFileMessages = 7; void Swap(TopicSubscription* other); friend void swap(TopicSubscription& a, TopicSubscription& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline TopicSubscription* New() const final { return CreateMaybeMessage<TopicSubscription>(NULL); } TopicSubscription* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<TopicSubscription>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const TopicSubscription& from); void MergeFrom(const TopicSubscription& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TopicSubscription* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // map<string, string> metadata = 3; int metadata_size() const; void clear_metadata(); static const int kMetadataFieldNumber = 3; const ::google::protobuf::Map< ::std::string, ::std::string >& metadata() const; ::google::protobuf::Map< ::std::string, ::std::string >* mutable_metadata(); // string pubsub_name = 1; void clear_pubsub_name(); static const int kPubsubNameFieldNumber = 1; const ::std::string& pubsub_name() const; void set_pubsub_name(const ::std::string& value); #if LANG_CXX11 void set_pubsub_name(::std::string&& value); #endif void set_pubsub_name(const char* value); void set_pubsub_name(const char* value, size_t size); ::std::string* mutable_pubsub_name(); ::std::string* release_pubsub_name(); void set_allocated_pubsub_name(::std::string* pubsub_name); // string topic = 2; void clear_topic(); static const int kTopicFieldNumber = 2; const ::std::string& topic() const; void set_topic(const ::std::string& value); #if LANG_CXX11 void set_topic(::std::string&& value); #endif void set_topic(const char* value); void set_topic(const char* value, size_t size); ::std::string* mutable_topic(); ::std::string* release_topic(); void set_allocated_topic(::std::string* topic); // .dapr.proto.runtime.v1.TopicRoutes routes = 5; bool has_routes() const; void clear_routes(); static const int kRoutesFieldNumber = 5; private: const ::dapr::proto::runtime::v1::TopicRoutes& _internal_routes() const; public: const ::dapr::proto::runtime::v1::TopicRoutes& routes() const; ::dapr::proto::runtime::v1::TopicRoutes* release_routes(); ::dapr::proto::runtime::v1::TopicRoutes* mutable_routes(); void set_allocated_routes(::dapr::proto::runtime::v1::TopicRoutes* routes); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.TopicSubscription) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::MapField< TopicSubscription_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 > metadata_; ::google::protobuf::internal::ArenaStringPtr pubsub_name_; ::google::protobuf::internal::ArenaStringPtr topic_; ::dapr::proto::runtime::v1::TopicRoutes* routes_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class TopicRoutes : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.TopicRoutes) */ { public: TopicRoutes(); virtual ~TopicRoutes(); TopicRoutes(const TopicRoutes& from); inline TopicRoutes& operator=(const TopicRoutes& from) { CopyFrom(from); return *this; } #if LANG_CXX11 TopicRoutes(TopicRoutes&& from) noexcept : TopicRoutes() { *this = ::std::move(from); } inline TopicRoutes& operator=(TopicRoutes&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const TopicRoutes& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const TopicRoutes* internal_default_instance() { return reinterpret_cast<const TopicRoutes*>( &_TopicRoutes_default_instance_); } static constexpr int kIndexInFileMessages = 8; void Swap(TopicRoutes* other); friend void swap(TopicRoutes& a, TopicRoutes& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline TopicRoutes* New() const final { return CreateMaybeMessage<TopicRoutes>(NULL); } TopicRoutes* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<TopicRoutes>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const TopicRoutes& from); void MergeFrom(const TopicRoutes& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TopicRoutes* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .dapr.proto.runtime.v1.TopicRule rules = 1; int rules_size() const; void clear_rules(); static const int kRulesFieldNumber = 1; ::dapr::proto::runtime::v1::TopicRule* mutable_rules(int index); ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicRule >* mutable_rules(); const ::dapr::proto::runtime::v1::TopicRule& rules(int index) const; ::dapr::proto::runtime::v1::TopicRule* add_rules(); const ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicRule >& rules() const; // string default = 2; void clear_default_(); static const int kDefaultFieldNumber = 2; const ::std::string& default_() const; void set_default_(const ::std::string& value); #if LANG_CXX11 void set_default_(::std::string&& value); #endif void set_default_(const char* value); void set_default_(const char* value, size_t size); ::std::string* mutable_default_(); ::std::string* release_default_(); void set_allocated_default_(::std::string* default_); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.TopicRoutes) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicRule > rules_; ::google::protobuf::internal::ArenaStringPtr default__; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class TopicRule : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.TopicRule) */ { public: TopicRule(); virtual ~TopicRule(); TopicRule(const TopicRule& from); inline TopicRule& operator=(const TopicRule& from) { CopyFrom(from); return *this; } #if LANG_CXX11 TopicRule(TopicRule&& from) noexcept : TopicRule() { *this = ::std::move(from); } inline TopicRule& operator=(TopicRule&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const TopicRule& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const TopicRule* internal_default_instance() { return reinterpret_cast<const TopicRule*>( &_TopicRule_default_instance_); } static constexpr int kIndexInFileMessages = 9; void Swap(TopicRule* other); friend void swap(TopicRule& a, TopicRule& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline TopicRule* New() const final { return CreateMaybeMessage<TopicRule>(NULL); } TopicRule* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<TopicRule>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const TopicRule& from); void MergeFrom(const TopicRule& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TopicRule* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // string match = 1; void clear_match(); static const int kMatchFieldNumber = 1; const ::std::string& match() const; void set_match(const ::std::string& value); #if LANG_CXX11 void set_match(::std::string&& value); #endif void set_match(const char* value); void set_match(const char* value, size_t size); ::std::string* mutable_match(); ::std::string* release_match(); void set_allocated_match(::std::string* match); // string path = 2; void clear_path(); static const int kPathFieldNumber = 2; const ::std::string& path() const; void set_path(const ::std::string& value); #if LANG_CXX11 void set_path(::std::string&& value); #endif void set_path(const char* value); void set_path(const char* value, size_t size); ::std::string* mutable_path(); ::std::string* release_path(); void set_allocated_path(::std::string* path); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.TopicRule) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr match_; ::google::protobuf::internal::ArenaStringPtr path_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // ------------------------------------------------------------------- class ListInputBindingsResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:dapr.proto.runtime.v1.ListInputBindingsResponse) */ { public: ListInputBindingsResponse(); virtual ~ListInputBindingsResponse(); ListInputBindingsResponse(const ListInputBindingsResponse& from); inline ListInputBindingsResponse& operator=(const ListInputBindingsResponse& from) { CopyFrom(from); return *this; } #if LANG_CXX11 ListInputBindingsResponse(ListInputBindingsResponse&& from) noexcept : ListInputBindingsResponse() { *this = ::std::move(from); } inline ListInputBindingsResponse& operator=(ListInputBindingsResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor(); static const ListInputBindingsResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const ListInputBindingsResponse* internal_default_instance() { return reinterpret_cast<const ListInputBindingsResponse*>( &_ListInputBindingsResponse_default_instance_); } static constexpr int kIndexInFileMessages = 10; void Swap(ListInputBindingsResponse* other); friend void swap(ListInputBindingsResponse& a, ListInputBindingsResponse& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline ListInputBindingsResponse* New() const final { return CreateMaybeMessage<ListInputBindingsResponse>(NULL); } ListInputBindingsResponse* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<ListInputBindingsResponse>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ListInputBindingsResponse& from); void MergeFrom(const ListInputBindingsResponse& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ListInputBindingsResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated string bindings = 1; int bindings_size() const; void clear_bindings(); static const int kBindingsFieldNumber = 1; const ::std::string& bindings(int index) const; ::std::string* mutable_bindings(int index); void set_bindings(int index, const ::std::string& value); #if LANG_CXX11 void set_bindings(int index, ::std::string&& value); #endif void set_bindings(int index, const char* value); void set_bindings(int index, const char* value, size_t size); ::std::string* add_bindings(); void add_bindings(const ::std::string& value); #if LANG_CXX11 void add_bindings(::std::string&& value); #endif void add_bindings(const char* value); void add_bindings(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField< ::std::string>& bindings() const; ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_bindings(); // @@protoc_insertion_point(class_scope:dapr.proto.runtime.v1.ListInputBindingsResponse) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::std::string> bindings_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto::TableStruct; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // TopicEventRequest // string id = 1; inline void TopicEventRequest::clear_id() { id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::id() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.id) return id_.GetNoArena(); } inline void TopicEventRequest::set_id(const ::std::string& value) { id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.id) } #if LANG_CXX11 inline void TopicEventRequest::set_id(::std::string&& value) { id_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.id) } #endif inline void TopicEventRequest::set_id(const char* value) { GOOGLE_DCHECK(value != NULL); id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.id) } inline void TopicEventRequest::set_id(const char* value, size_t size) { id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.id) } inline ::std::string* TopicEventRequest::mutable_id() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.id) return id_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_id() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.id) return id_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_id(::std::string* id) { if (id != NULL) { } else { } id_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), id); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.id) } // string source = 2; inline void TopicEventRequest::clear_source() { source_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::source() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.source) return source_.GetNoArena(); } inline void TopicEventRequest::set_source(const ::std::string& value) { source_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.source) } #if LANG_CXX11 inline void TopicEventRequest::set_source(::std::string&& value) { source_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.source) } #endif inline void TopicEventRequest::set_source(const char* value) { GOOGLE_DCHECK(value != NULL); source_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.source) } inline void TopicEventRequest::set_source(const char* value, size_t size) { source_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.source) } inline ::std::string* TopicEventRequest::mutable_source() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.source) return source_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_source() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.source) return source_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_source(::std::string* source) { if (source != NULL) { } else { } source_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), source); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.source) } // string type = 3; inline void TopicEventRequest::clear_type() { type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::type() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.type) return type_.GetNoArena(); } inline void TopicEventRequest::set_type(const ::std::string& value) { type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.type) } #if LANG_CXX11 inline void TopicEventRequest::set_type(::std::string&& value) { type_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.type) } #endif inline void TopicEventRequest::set_type(const char* value) { GOOGLE_DCHECK(value != NULL); type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.type) } inline void TopicEventRequest::set_type(const char* value, size_t size) { type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.type) } inline ::std::string* TopicEventRequest::mutable_type() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.type) return type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_type() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.type) return type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_type(::std::string* type) { if (type != NULL) { } else { } type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.type) } // string spec_version = 4; inline void TopicEventRequest::clear_spec_version() { spec_version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::spec_version() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.spec_version) return spec_version_.GetNoArena(); } inline void TopicEventRequest::set_spec_version(const ::std::string& value) { spec_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.spec_version) } #if LANG_CXX11 inline void TopicEventRequest::set_spec_version(::std::string&& value) { spec_version_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.spec_version) } #endif inline void TopicEventRequest::set_spec_version(const char* value) { GOOGLE_DCHECK(value != NULL); spec_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.spec_version) } inline void TopicEventRequest::set_spec_version(const char* value, size_t size) { spec_version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.spec_version) } inline ::std::string* TopicEventRequest::mutable_spec_version() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.spec_version) return spec_version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_spec_version() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.spec_version) return spec_version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_spec_version(::std::string* spec_version) { if (spec_version != NULL) { } else { } spec_version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), spec_version); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.spec_version) } // string data_content_type = 5; inline void TopicEventRequest::clear_data_content_type() { data_content_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::data_content_type() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) return data_content_type_.GetNoArena(); } inline void TopicEventRequest::set_data_content_type(const ::std::string& value) { data_content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) } #if LANG_CXX11 inline void TopicEventRequest::set_data_content_type(::std::string&& value) { data_content_type_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) } #endif inline void TopicEventRequest::set_data_content_type(const char* value) { GOOGLE_DCHECK(value != NULL); data_content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) } inline void TopicEventRequest::set_data_content_type(const char* value, size_t size) { data_content_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) } inline ::std::string* TopicEventRequest::mutable_data_content_type() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) return data_content_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_data_content_type() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) return data_content_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_data_content_type(::std::string* data_content_type) { if (data_content_type != NULL) { } else { } data_content_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), data_content_type); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.data_content_type) } // bytes data = 7; inline void TopicEventRequest::clear_data() { data_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::data() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.data) return data_.GetNoArena(); } inline void TopicEventRequest::set_data(const ::std::string& value) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.data) } #if LANG_CXX11 inline void TopicEventRequest::set_data(::std::string&& value) { data_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.data) } #endif inline void TopicEventRequest::set_data(const char* value) { GOOGLE_DCHECK(value != NULL); data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.data) } inline void TopicEventRequest::set_data(const void* value, size_t size) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.data) } inline ::std::string* TopicEventRequest::mutable_data() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.data) return data_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_data() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.data) return data_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_data(::std::string* data) { if (data != NULL) { } else { } data_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), data); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.data) } // string topic = 6; inline void TopicEventRequest::clear_topic() { topic_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::topic() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.topic) return topic_.GetNoArena(); } inline void TopicEventRequest::set_topic(const ::std::string& value) { topic_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.topic) } #if LANG_CXX11 inline void TopicEventRequest::set_topic(::std::string&& value) { topic_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.topic) } #endif inline void TopicEventRequest::set_topic(const char* value) { GOOGLE_DCHECK(value != NULL); topic_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.topic) } inline void TopicEventRequest::set_topic(const char* value, size_t size) { topic_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.topic) } inline ::std::string* TopicEventRequest::mutable_topic() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.topic) return topic_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_topic() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.topic) return topic_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_topic(::std::string* topic) { if (topic != NULL) { } else { } topic_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), topic); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.topic) } // string pubsub_name = 8; inline void TopicEventRequest::clear_pubsub_name() { pubsub_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::pubsub_name() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) return pubsub_name_.GetNoArena(); } inline void TopicEventRequest::set_pubsub_name(const ::std::string& value) { pubsub_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) } #if LANG_CXX11 inline void TopicEventRequest::set_pubsub_name(::std::string&& value) { pubsub_name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) } #endif inline void TopicEventRequest::set_pubsub_name(const char* value) { GOOGLE_DCHECK(value != NULL); pubsub_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) } inline void TopicEventRequest::set_pubsub_name(const char* value, size_t size) { pubsub_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) } inline ::std::string* TopicEventRequest::mutable_pubsub_name() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) return pubsub_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_pubsub_name() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) return pubsub_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_pubsub_name(::std::string* pubsub_name) { if (pubsub_name != NULL) { } else { } pubsub_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), pubsub_name); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.pubsub_name) } // string path = 9; inline void TopicEventRequest::clear_path() { path_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicEventRequest::path() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventRequest.path) return path_.GetNoArena(); } inline void TopicEventRequest::set_path(const ::std::string& value) { path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventRequest.path) } #if LANG_CXX11 inline void TopicEventRequest::set_path(::std::string&& value) { path_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicEventRequest.path) } #endif inline void TopicEventRequest::set_path(const char* value) { GOOGLE_DCHECK(value != NULL); path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicEventRequest.path) } inline void TopicEventRequest::set_path(const char* value, size_t size) { path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicEventRequest.path) } inline ::std::string* TopicEventRequest::mutable_path() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicEventRequest.path) return path_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicEventRequest::release_path() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicEventRequest.path) return path_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicEventRequest::set_allocated_path(::std::string* path) { if (path != NULL) { } else { } path_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), path); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicEventRequest.path) } // ------------------------------------------------------------------- // TopicEventResponse // .dapr.proto.runtime.v1.TopicEventResponse.TopicEventResponseStatus status = 1; inline void TopicEventResponse::clear_status() { status_ = 0; } inline ::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus TopicEventResponse::status() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicEventResponse.status) return static_cast< ::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus >(status_); } inline void TopicEventResponse::set_status(::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus value) { status_ = value; // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicEventResponse.status) } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // BindingEventRequest // string name = 1; inline void BindingEventRequest::clear_name() { name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& BindingEventRequest::name() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventRequest.name) return name_.GetNoArena(); } inline void BindingEventRequest::set_name(const ::std::string& value) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventRequest.name) } #if LANG_CXX11 inline void BindingEventRequest::set_name(::std::string&& value) { name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.BindingEventRequest.name) } #endif inline void BindingEventRequest::set_name(const char* value) { GOOGLE_DCHECK(value != NULL); name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.BindingEventRequest.name) } inline void BindingEventRequest::set_name(const char* value, size_t size) { name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.BindingEventRequest.name) } inline ::std::string* BindingEventRequest::mutable_name() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.BindingEventRequest.name) return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* BindingEventRequest::release_name() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.BindingEventRequest.name) return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void BindingEventRequest::set_allocated_name(::std::string* name) { if (name != NULL) { } else { } name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.BindingEventRequest.name) } // bytes data = 2; inline void BindingEventRequest::clear_data() { data_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& BindingEventRequest::data() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventRequest.data) return data_.GetNoArena(); } inline void BindingEventRequest::set_data(const ::std::string& value) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventRequest.data) } #if LANG_CXX11 inline void BindingEventRequest::set_data(::std::string&& value) { data_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.BindingEventRequest.data) } #endif inline void BindingEventRequest::set_data(const char* value) { GOOGLE_DCHECK(value != NULL); data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.BindingEventRequest.data) } inline void BindingEventRequest::set_data(const void* value, size_t size) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.BindingEventRequest.data) } inline ::std::string* BindingEventRequest::mutable_data() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.BindingEventRequest.data) return data_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* BindingEventRequest::release_data() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.BindingEventRequest.data) return data_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void BindingEventRequest::set_allocated_data(::std::string* data) { if (data != NULL) { } else { } data_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), data); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.BindingEventRequest.data) } // map<string, string> metadata = 3; inline int BindingEventRequest::metadata_size() const { return metadata_.size(); } inline void BindingEventRequest::clear_metadata() { metadata_.Clear(); } inline const ::google::protobuf::Map< ::std::string, ::std::string >& BindingEventRequest::metadata() const { // @@protoc_insertion_point(field_map:dapr.proto.runtime.v1.BindingEventRequest.metadata) return metadata_.GetMap(); } inline ::google::protobuf::Map< ::std::string, ::std::string >* BindingEventRequest::mutable_metadata() { // @@protoc_insertion_point(field_mutable_map:dapr.proto.runtime.v1.BindingEventRequest.metadata) return metadata_.MutableMap(); } // ------------------------------------------------------------------- // BindingEventResponse // string store_name = 1; inline void BindingEventResponse::clear_store_name() { store_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& BindingEventResponse::store_name() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventResponse.store_name) return store_name_.GetNoArena(); } inline void BindingEventResponse::set_store_name(const ::std::string& value) { store_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventResponse.store_name) } #if LANG_CXX11 inline void BindingEventResponse::set_store_name(::std::string&& value) { store_name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.BindingEventResponse.store_name) } #endif inline void BindingEventResponse::set_store_name(const char* value) { GOOGLE_DCHECK(value != NULL); store_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.BindingEventResponse.store_name) } inline void BindingEventResponse::set_store_name(const char* value, size_t size) { store_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.BindingEventResponse.store_name) } inline ::std::string* BindingEventResponse::mutable_store_name() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.BindingEventResponse.store_name) return store_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* BindingEventResponse::release_store_name() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.BindingEventResponse.store_name) return store_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void BindingEventResponse::set_allocated_store_name(::std::string* store_name) { if (store_name != NULL) { } else { } store_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), store_name); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.BindingEventResponse.store_name) } // repeated .dapr.proto.common.v1.StateItem states = 2; inline int BindingEventResponse::states_size() const { return states_.size(); } inline ::dapr::proto::common::v1::StateItem* BindingEventResponse::mutable_states(int index) { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.BindingEventResponse.states) return states_.Mutable(index); } inline ::google::protobuf::RepeatedPtrField< ::dapr::proto::common::v1::StateItem >* BindingEventResponse::mutable_states() { // @@protoc_insertion_point(field_mutable_list:dapr.proto.runtime.v1.BindingEventResponse.states) return &states_; } inline const ::dapr::proto::common::v1::StateItem& BindingEventResponse::states(int index) const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventResponse.states) return states_.Get(index); } inline ::dapr::proto::common::v1::StateItem* BindingEventResponse::add_states() { // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.BindingEventResponse.states) return states_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::dapr::proto::common::v1::StateItem >& BindingEventResponse::states() const { // @@protoc_insertion_point(field_list:dapr.proto.runtime.v1.BindingEventResponse.states) return states_; } // repeated string to = 3; inline int BindingEventResponse::to_size() const { return to_.size(); } inline void BindingEventResponse::clear_to() { to_.Clear(); } inline const ::std::string& BindingEventResponse::to(int index) const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventResponse.to) return to_.Get(index); } inline ::std::string* BindingEventResponse::mutable_to(int index) { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.BindingEventResponse.to) return to_.Mutable(index); } inline void BindingEventResponse::set_to(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventResponse.to) to_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void BindingEventResponse::set_to(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventResponse.to) to_.Mutable(index)->assign(std::move(value)); } #endif inline void BindingEventResponse::set_to(int index, const char* value) { GOOGLE_DCHECK(value != NULL); to_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.BindingEventResponse.to) } inline void BindingEventResponse::set_to(int index, const char* value, size_t size) { to_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.BindingEventResponse.to) } inline ::std::string* BindingEventResponse::add_to() { // @@protoc_insertion_point(field_add_mutable:dapr.proto.runtime.v1.BindingEventResponse.to) return to_.Add(); } inline void BindingEventResponse::add_to(const ::std::string& value) { to_.Add()->assign(value); // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.BindingEventResponse.to) } #if LANG_CXX11 inline void BindingEventResponse::add_to(::std::string&& value) { to_.Add(std::move(value)); // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.BindingEventResponse.to) } #endif inline void BindingEventResponse::add_to(const char* value) { GOOGLE_DCHECK(value != NULL); to_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:dapr.proto.runtime.v1.BindingEventResponse.to) } inline void BindingEventResponse::add_to(const char* value, size_t size) { to_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:dapr.proto.runtime.v1.BindingEventResponse.to) } inline const ::google::protobuf::RepeatedPtrField< ::std::string>& BindingEventResponse::to() const { // @@protoc_insertion_point(field_list:dapr.proto.runtime.v1.BindingEventResponse.to) return to_; } inline ::google::protobuf::RepeatedPtrField< ::std::string>* BindingEventResponse::mutable_to() { // @@protoc_insertion_point(field_mutable_list:dapr.proto.runtime.v1.BindingEventResponse.to) return &to_; } // bytes data = 4; inline void BindingEventResponse::clear_data() { data_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& BindingEventResponse::data() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventResponse.data) return data_.GetNoArena(); } inline void BindingEventResponse::set_data(const ::std::string& value) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventResponse.data) } #if LANG_CXX11 inline void BindingEventResponse::set_data(::std::string&& value) { data_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.BindingEventResponse.data) } #endif inline void BindingEventResponse::set_data(const char* value) { GOOGLE_DCHECK(value != NULL); data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.BindingEventResponse.data) } inline void BindingEventResponse::set_data(const void* value, size_t size) { data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.BindingEventResponse.data) } inline ::std::string* BindingEventResponse::mutable_data() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.BindingEventResponse.data) return data_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* BindingEventResponse::release_data() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.BindingEventResponse.data) return data_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void BindingEventResponse::set_allocated_data(::std::string* data) { if (data != NULL) { } else { } data_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), data); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.BindingEventResponse.data) } // .dapr.proto.runtime.v1.BindingEventResponse.BindingEventConcurrency concurrency = 5; inline void BindingEventResponse::clear_concurrency() { concurrency_ = 0; } inline ::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency BindingEventResponse::concurrency() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.BindingEventResponse.concurrency) return static_cast< ::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency >(concurrency_); } inline void BindingEventResponse::set_concurrency(::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency value) { concurrency_ = value; // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.BindingEventResponse.concurrency) } // ------------------------------------------------------------------- // ListTopicSubscriptionsResponse // repeated .dapr.proto.runtime.v1.TopicSubscription subscriptions = 1; inline int ListTopicSubscriptionsResponse::subscriptions_size() const { return subscriptions_.size(); } inline void ListTopicSubscriptionsResponse::clear_subscriptions() { subscriptions_.Clear(); } inline ::dapr::proto::runtime::v1::TopicSubscription* ListTopicSubscriptionsResponse::mutable_subscriptions(int index) { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse.subscriptions) return subscriptions_.Mutable(index); } inline ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicSubscription >* ListTopicSubscriptionsResponse::mutable_subscriptions() { // @@protoc_insertion_point(field_mutable_list:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse.subscriptions) return &subscriptions_; } inline const ::dapr::proto::runtime::v1::TopicSubscription& ListTopicSubscriptionsResponse::subscriptions(int index) const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse.subscriptions) return subscriptions_.Get(index); } inline ::dapr::proto::runtime::v1::TopicSubscription* ListTopicSubscriptionsResponse::add_subscriptions() { // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse.subscriptions) return subscriptions_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicSubscription >& ListTopicSubscriptionsResponse::subscriptions() const { // @@protoc_insertion_point(field_list:dapr.proto.runtime.v1.ListTopicSubscriptionsResponse.subscriptions) return subscriptions_; } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TopicSubscription // string pubsub_name = 1; inline void TopicSubscription::clear_pubsub_name() { pubsub_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicSubscription::pubsub_name() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) return pubsub_name_.GetNoArena(); } inline void TopicSubscription::set_pubsub_name(const ::std::string& value) { pubsub_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) } #if LANG_CXX11 inline void TopicSubscription::set_pubsub_name(::std::string&& value) { pubsub_name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) } #endif inline void TopicSubscription::set_pubsub_name(const char* value) { GOOGLE_DCHECK(value != NULL); pubsub_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) } inline void TopicSubscription::set_pubsub_name(const char* value, size_t size) { pubsub_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) } inline ::std::string* TopicSubscription::mutable_pubsub_name() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) return pubsub_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicSubscription::release_pubsub_name() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) return pubsub_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicSubscription::set_allocated_pubsub_name(::std::string* pubsub_name) { if (pubsub_name != NULL) { } else { } pubsub_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), pubsub_name); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicSubscription.pubsub_name) } // string topic = 2; inline void TopicSubscription::clear_topic() { topic_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicSubscription::topic() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicSubscription.topic) return topic_.GetNoArena(); } inline void TopicSubscription::set_topic(const ::std::string& value) { topic_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicSubscription.topic) } #if LANG_CXX11 inline void TopicSubscription::set_topic(::std::string&& value) { topic_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicSubscription.topic) } #endif inline void TopicSubscription::set_topic(const char* value) { GOOGLE_DCHECK(value != NULL); topic_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicSubscription.topic) } inline void TopicSubscription::set_topic(const char* value, size_t size) { topic_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicSubscription.topic) } inline ::std::string* TopicSubscription::mutable_topic() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicSubscription.topic) return topic_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicSubscription::release_topic() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicSubscription.topic) return topic_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicSubscription::set_allocated_topic(::std::string* topic) { if (topic != NULL) { } else { } topic_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), topic); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicSubscription.topic) } // map<string, string> metadata = 3; inline int TopicSubscription::metadata_size() const { return metadata_.size(); } inline void TopicSubscription::clear_metadata() { metadata_.Clear(); } inline const ::google::protobuf::Map< ::std::string, ::std::string >& TopicSubscription::metadata() const { // @@protoc_insertion_point(field_map:dapr.proto.runtime.v1.TopicSubscription.metadata) return metadata_.GetMap(); } inline ::google::protobuf::Map< ::std::string, ::std::string >* TopicSubscription::mutable_metadata() { // @@protoc_insertion_point(field_mutable_map:dapr.proto.runtime.v1.TopicSubscription.metadata) return metadata_.MutableMap(); } // .dapr.proto.runtime.v1.TopicRoutes routes = 5; inline bool TopicSubscription::has_routes() const { return this != internal_default_instance() && routes_ != NULL; } inline void TopicSubscription::clear_routes() { if (GetArenaNoVirtual() == NULL && routes_ != NULL) { delete routes_; } routes_ = NULL; } inline const ::dapr::proto::runtime::v1::TopicRoutes& TopicSubscription::_internal_routes() const { return *routes_; } inline const ::dapr::proto::runtime::v1::TopicRoutes& TopicSubscription::routes() const { const ::dapr::proto::runtime::v1::TopicRoutes* p = routes_; // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicSubscription.routes) return p != NULL ? *p : *reinterpret_cast<const ::dapr::proto::runtime::v1::TopicRoutes*>( &::dapr::proto::runtime::v1::_TopicRoutes_default_instance_); } inline ::dapr::proto::runtime::v1::TopicRoutes* TopicSubscription::release_routes() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicSubscription.routes) ::dapr::proto::runtime::v1::TopicRoutes* temp = routes_; routes_ = NULL; return temp; } inline ::dapr::proto::runtime::v1::TopicRoutes* TopicSubscription::mutable_routes() { if (routes_ == NULL) { auto* p = CreateMaybeMessage<::dapr::proto::runtime::v1::TopicRoutes>(GetArenaNoVirtual()); routes_ = p; } // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicSubscription.routes) return routes_; } inline void TopicSubscription::set_allocated_routes(::dapr::proto::runtime::v1::TopicRoutes* routes) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == NULL) { delete routes_; } if (routes) { ::google::protobuf::Arena* submessage_arena = NULL; if (message_arena != submessage_arena) { routes = ::google::protobuf::internal::GetOwnedMessage( message_arena, routes, submessage_arena); } } else { } routes_ = routes; // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicSubscription.routes) } // ------------------------------------------------------------------- // TopicRoutes // repeated .dapr.proto.runtime.v1.TopicRule rules = 1; inline int TopicRoutes::rules_size() const { return rules_.size(); } inline void TopicRoutes::clear_rules() { rules_.Clear(); } inline ::dapr::proto::runtime::v1::TopicRule* TopicRoutes::mutable_rules(int index) { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicRoutes.rules) return rules_.Mutable(index); } inline ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicRule >* TopicRoutes::mutable_rules() { // @@protoc_insertion_point(field_mutable_list:dapr.proto.runtime.v1.TopicRoutes.rules) return &rules_; } inline const ::dapr::proto::runtime::v1::TopicRule& TopicRoutes::rules(int index) const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicRoutes.rules) return rules_.Get(index); } inline ::dapr::proto::runtime::v1::TopicRule* TopicRoutes::add_rules() { // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.TopicRoutes.rules) return rules_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::dapr::proto::runtime::v1::TopicRule >& TopicRoutes::rules() const { // @@protoc_insertion_point(field_list:dapr.proto.runtime.v1.TopicRoutes.rules) return rules_; } // string default = 2; inline void TopicRoutes::clear_default_() { default__.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicRoutes::default_() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicRoutes.default) return default__.GetNoArena(); } inline void TopicRoutes::set_default_(const ::std::string& value) { default__.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicRoutes.default) } #if LANG_CXX11 inline void TopicRoutes::set_default_(::std::string&& value) { default__.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicRoutes.default) } #endif inline void TopicRoutes::set_default_(const char* value) { GOOGLE_DCHECK(value != NULL); default__.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicRoutes.default) } inline void TopicRoutes::set_default_(const char* value, size_t size) { default__.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicRoutes.default) } inline ::std::string* TopicRoutes::mutable_default_() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicRoutes.default) return default__.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicRoutes::release_default_() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicRoutes.default) return default__.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicRoutes::set_allocated_default_(::std::string* default_) { if (default_ != NULL) { } else { } default__.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicRoutes.default) } // ------------------------------------------------------------------- // TopicRule // string match = 1; inline void TopicRule::clear_match() { match_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicRule::match() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicRule.match) return match_.GetNoArena(); } inline void TopicRule::set_match(const ::std::string& value) { match_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicRule.match) } #if LANG_CXX11 inline void TopicRule::set_match(::std::string&& value) { match_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicRule.match) } #endif inline void TopicRule::set_match(const char* value) { GOOGLE_DCHECK(value != NULL); match_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicRule.match) } inline void TopicRule::set_match(const char* value, size_t size) { match_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicRule.match) } inline ::std::string* TopicRule::mutable_match() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicRule.match) return match_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicRule::release_match() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicRule.match) return match_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicRule::set_allocated_match(::std::string* match) { if (match != NULL) { } else { } match_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), match); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicRule.match) } // string path = 2; inline void TopicRule::clear_path() { path_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& TopicRule::path() const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.TopicRule.path) return path_.GetNoArena(); } inline void TopicRule::set_path(const ::std::string& value) { path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.TopicRule.path) } #if LANG_CXX11 inline void TopicRule::set_path(::std::string&& value) { path_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:dapr.proto.runtime.v1.TopicRule.path) } #endif inline void TopicRule::set_path(const char* value) { GOOGLE_DCHECK(value != NULL); path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.TopicRule.path) } inline void TopicRule::set_path(const char* value, size_t size) { path_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.TopicRule.path) } inline ::std::string* TopicRule::mutable_path() { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.TopicRule.path) return path_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* TopicRule::release_path() { // @@protoc_insertion_point(field_release:dapr.proto.runtime.v1.TopicRule.path) return path_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void TopicRule::set_allocated_path(::std::string* path) { if (path != NULL) { } else { } path_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), path); // @@protoc_insertion_point(field_set_allocated:dapr.proto.runtime.v1.TopicRule.path) } // ------------------------------------------------------------------- // ListInputBindingsResponse // repeated string bindings = 1; inline int ListInputBindingsResponse::bindings_size() const { return bindings_.size(); } inline void ListInputBindingsResponse::clear_bindings() { bindings_.Clear(); } inline const ::std::string& ListInputBindingsResponse::bindings(int index) const { // @@protoc_insertion_point(field_get:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) return bindings_.Get(index); } inline ::std::string* ListInputBindingsResponse::mutable_bindings(int index) { // @@protoc_insertion_point(field_mutable:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) return bindings_.Mutable(index); } inline void ListInputBindingsResponse::set_bindings(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) bindings_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void ListInputBindingsResponse::set_bindings(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) bindings_.Mutable(index)->assign(std::move(value)); } #endif inline void ListInputBindingsResponse::set_bindings(int index, const char* value) { GOOGLE_DCHECK(value != NULL); bindings_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) } inline void ListInputBindingsResponse::set_bindings(int index, const char* value, size_t size) { bindings_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) } inline ::std::string* ListInputBindingsResponse::add_bindings() { // @@protoc_insertion_point(field_add_mutable:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) return bindings_.Add(); } inline void ListInputBindingsResponse::add_bindings(const ::std::string& value) { bindings_.Add()->assign(value); // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) } #if LANG_CXX11 inline void ListInputBindingsResponse::add_bindings(::std::string&& value) { bindings_.Add(std::move(value)); // @@protoc_insertion_point(field_add:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) } #endif inline void ListInputBindingsResponse::add_bindings(const char* value) { GOOGLE_DCHECK(value != NULL); bindings_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) } inline void ListInputBindingsResponse::add_bindings(const char* value, size_t size) { bindings_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) } inline const ::google::protobuf::RepeatedPtrField< ::std::string>& ListInputBindingsResponse::bindings() const { // @@protoc_insertion_point(field_list:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) return bindings_; } inline ::google::protobuf::RepeatedPtrField< ::std::string>* ListInputBindingsResponse::mutable_bindings() { // @@protoc_insertion_point(field_mutable_list:dapr.proto.runtime.v1.ListInputBindingsResponse.bindings) return &bindings_; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace v1 } // namespace runtime } // namespace proto } // namespace dapr namespace google { namespace protobuf { template <> struct is_proto_enum< ::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus>() { return ::dapr::proto::runtime::v1::TopicEventResponse_TopicEventResponseStatus_descriptor(); } template <> struct is_proto_enum< ::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency>() { return ::dapr::proto::runtime::v1::BindingEventResponse_BindingEventConcurrency_descriptor(); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_dapr_2fproto_2fruntime_2fv1_2fappcallback_2eproto <|start_filename|>src/dapr/proto/runtime/v1/appcallback.grpc.pb.cc<|end_filename|> // Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: dapr/proto/runtime/v1/appcallback.proto #include "dapr/proto/runtime/v1/appcallback.pb.h" #include "dapr/proto/runtime/v1/appcallback.grpc.pb.h" #include <functional> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/client_callback.h> #include <grpcpp/impl/codegen/method_handler_impl.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace dapr { namespace proto { namespace runtime { namespace v1 { static const char* AppCallback_method_names[] = { "/dapr.proto.runtime.v1.AppCallback/OnInvoke", "/dapr.proto.runtime.v1.AppCallback/ListTopicSubscriptions", "/dapr.proto.runtime.v1.AppCallback/OnTopicEvent", "/dapr.proto.runtime.v1.AppCallback/ListInputBindings", "/dapr.proto.runtime.v1.AppCallback/OnBindingEvent", }; std::unique_ptr< AppCallback::Stub> AppCallback::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< AppCallback::Stub> stub(new AppCallback::Stub(channel)); return stub; } AppCallback::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_OnInvoke_(AppCallback_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_ListTopicSubscriptions_(AppCallback_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_OnTopicEvent_(AppCallback_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_ListInputBindings_(AppCallback_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_OnBindingEvent_(AppCallback_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) {} ::grpc::Status AppCallback::Stub::OnInvoke(::grpc::ClientContext* context, const ::dapr::proto::common::v1::InvokeRequest& request, ::dapr::proto::common::v1::InvokeResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_OnInvoke_, context, request, response); } void AppCallback::Stub::experimental_async::OnInvoke(::grpc::ClientContext* context, const ::dapr::proto::common::v1::InvokeRequest* request, ::dapr::proto::common::v1::InvokeResponse* response, std::function<void(::grpc::Status)> f) { return ::grpc::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_OnInvoke_, context, request, response, std::move(f)); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::common::v1::InvokeResponse>* AppCallback::Stub::AsyncOnInvokeRaw(::grpc::ClientContext* context, const ::dapr::proto::common::v1::InvokeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::common::v1::InvokeResponse>::Create(channel_.get(), cq, rpcmethod_OnInvoke_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::common::v1::InvokeResponse>* AppCallback::Stub::PrepareAsyncOnInvokeRaw(::grpc::ClientContext* context, const ::dapr::proto::common::v1::InvokeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::common::v1::InvokeResponse>::Create(channel_.get(), cq, rpcmethod_OnInvoke_, context, request, false); } ::grpc::Status AppCallback::Stub::ListTopicSubscriptions(::grpc::ClientContext* context, const ::google::protobuf::Empty& request, ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_ListTopicSubscriptions_, context, request, response); } void AppCallback::Stub::experimental_async::ListTopicSubscriptions(::grpc::ClientContext* context, const ::google::protobuf::Empty* request, ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse* response, std::function<void(::grpc::Status)> f) { return ::grpc::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_ListTopicSubscriptions_, context, request, response, std::move(f)); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse>* AppCallback::Stub::AsyncListTopicSubscriptionsRaw(::grpc::ClientContext* context, const ::google::protobuf::Empty& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse>::Create(channel_.get(), cq, rpcmethod_ListTopicSubscriptions_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse>* AppCallback::Stub::PrepareAsyncListTopicSubscriptionsRaw(::grpc::ClientContext* context, const ::google::protobuf::Empty& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse>::Create(channel_.get(), cq, rpcmethod_ListTopicSubscriptions_, context, request, false); } ::grpc::Status AppCallback::Stub::OnTopicEvent(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::TopicEventRequest& request, ::dapr::proto::runtime::v1::TopicEventResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_OnTopicEvent_, context, request, response); } void AppCallback::Stub::experimental_async::OnTopicEvent(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::TopicEventRequest* request, ::dapr::proto::runtime::v1::TopicEventResponse* response, std::function<void(::grpc::Status)> f) { return ::grpc::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_OnTopicEvent_, context, request, response, std::move(f)); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::TopicEventResponse>* AppCallback::Stub::AsyncOnTopicEventRaw(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::TopicEventRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::TopicEventResponse>::Create(channel_.get(), cq, rpcmethod_OnTopicEvent_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::TopicEventResponse>* AppCallback::Stub::PrepareAsyncOnTopicEventRaw(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::TopicEventRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::TopicEventResponse>::Create(channel_.get(), cq, rpcmethod_OnTopicEvent_, context, request, false); } ::grpc::Status AppCallback::Stub::ListInputBindings(::grpc::ClientContext* context, const ::google::protobuf::Empty& request, ::dapr::proto::runtime::v1::ListInputBindingsResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_ListInputBindings_, context, request, response); } void AppCallback::Stub::experimental_async::ListInputBindings(::grpc::ClientContext* context, const ::google::protobuf::Empty* request, ::dapr::proto::runtime::v1::ListInputBindingsResponse* response, std::function<void(::grpc::Status)> f) { return ::grpc::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_ListInputBindings_, context, request, response, std::move(f)); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::ListInputBindingsResponse>* AppCallback::Stub::AsyncListInputBindingsRaw(::grpc::ClientContext* context, const ::google::protobuf::Empty& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::ListInputBindingsResponse>::Create(channel_.get(), cq, rpcmethod_ListInputBindings_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::ListInputBindingsResponse>* AppCallback::Stub::PrepareAsyncListInputBindingsRaw(::grpc::ClientContext* context, const ::google::protobuf::Empty& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::ListInputBindingsResponse>::Create(channel_.get(), cq, rpcmethod_ListInputBindings_, context, request, false); } ::grpc::Status AppCallback::Stub::OnBindingEvent(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::BindingEventRequest& request, ::dapr::proto::runtime::v1::BindingEventResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_OnBindingEvent_, context, request, response); } void AppCallback::Stub::experimental_async::OnBindingEvent(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::BindingEventRequest* request, ::dapr::proto::runtime::v1::BindingEventResponse* response, std::function<void(::grpc::Status)> f) { return ::grpc::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_OnBindingEvent_, context, request, response, std::move(f)); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::BindingEventResponse>* AppCallback::Stub::AsyncOnBindingEventRaw(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::BindingEventRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::BindingEventResponse>::Create(channel_.get(), cq, rpcmethod_OnBindingEvent_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::dapr::proto::runtime::v1::BindingEventResponse>* AppCallback::Stub::PrepareAsyncOnBindingEventRaw(::grpc::ClientContext* context, const ::dapr::proto::runtime::v1::BindingEventRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::dapr::proto::runtime::v1::BindingEventResponse>::Create(channel_.get(), cq, rpcmethod_OnBindingEvent_, context, request, false); } AppCallback::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( AppCallback_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< AppCallback::Service, ::dapr::proto::common::v1::InvokeRequest, ::dapr::proto::common::v1::InvokeResponse>( std::mem_fn(&AppCallback::Service::OnInvoke), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( AppCallback_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< AppCallback::Service, ::google::protobuf::Empty, ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse>( std::mem_fn(&AppCallback::Service::ListTopicSubscriptions), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( AppCallback_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< AppCallback::Service, ::dapr::proto::runtime::v1::TopicEventRequest, ::dapr::proto::runtime::v1::TopicEventResponse>( std::mem_fn(&AppCallback::Service::OnTopicEvent), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( AppCallback_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< AppCallback::Service, ::google::protobuf::Empty, ::dapr::proto::runtime::v1::ListInputBindingsResponse>( std::mem_fn(&AppCallback::Service::ListInputBindings), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( AppCallback_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< AppCallback::Service, ::dapr::proto::runtime::v1::BindingEventRequest, ::dapr::proto::runtime::v1::BindingEventResponse>( std::mem_fn(&AppCallback::Service::OnBindingEvent), this))); } AppCallback::Service::~Service() { } ::grpc::Status AppCallback::Service::OnInvoke(::grpc::ServerContext* context, const ::dapr::proto::common::v1::InvokeRequest* request, ::dapr::proto::common::v1::InvokeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status AppCallback::Service::ListTopicSubscriptions(::grpc::ServerContext* context, const ::google::protobuf::Empty* request, ::dapr::proto::runtime::v1::ListTopicSubscriptionsResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status AppCallback::Service::OnTopicEvent(::grpc::ServerContext* context, const ::dapr::proto::runtime::v1::TopicEventRequest* request, ::dapr::proto::runtime::v1::TopicEventResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status AppCallback::Service::ListInputBindings(::grpc::ServerContext* context, const ::google::protobuf::Empty* request, ::dapr::proto::runtime::v1::ListInputBindingsResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status AppCallback::Service::OnBindingEvent(::grpc::ServerContext* context, const ::dapr::proto::runtime::v1::BindingEventRequest* request, ::dapr::proto::runtime::v1::BindingEventResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace dapr } // namespace proto } // namespace runtime } // namespace v1 <|start_filename|>examples/echo_app/Makefile<|end_filename|> # ------------------------------------------------------------ # Copyright 2021 The Dapr Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------ HOST_SYSTEM = $(shell uname | cut -f 1 -d_) SYSTEM ?= $(HOST_SYSTEM) CXX = g++ CPPFLAGS += `pkg-config --cflags protobuf grpc` CXXFLAGS += -std=c++11 -I ../../src ifeq ($(SYSTEM),Darwin) LDFLAGS += -L/usr/local/lib `pkg-config --libs protobuf grpc++`\ -pthread\ -lgrpc++_reflection\ -ldl else LDFLAGS += -L/usr/local/lib `pkg-config --libs protobuf grpc++`\ -pthread\ -Wl,--no-as-needed -lgrpc++_reflection -Wl,--as-needed\ -ldl endif DAPR_SRC_ROOT = ../../src/dapr/proto all: echo_app echo_app: $(DAPR_SRC_ROOT)/common/v1/common.pb.o $(DAPR_SRC_ROOT)/runtime/v1/dapr.pb.o $(DAPR_SRC_ROOT)/runtime/v1/dapr.grpc.pb.o $(DAPR_SRC_ROOT)/runtime/v1/appcallback.pb.o $(DAPR_SRC_ROOT)/runtime/v1/appcallback.grpc.pb.o echo_app_server_impl.o echo_app.o $(CXX) $^ $(LDFLAGS) -o $@ clean: rm -f *.o echo_app <|start_filename|>examples/echo_app/echo_app_server_impl.cc<|end_filename|> // ------------------------------------------------------------------------ // Copyright 2021 The Dapr Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include <iostream> #include <memory> #include <string> #include "echo_app_server_impl.h" using grpc::ServerContext; using grpc::Status; using google::protobuf::Any; using google::protobuf::Empty; using dapr::proto::common::v1::InvokeRequest; using dapr::proto::common::v1::InvokeResponse; using dapr::proto::runtime::v1::ListTopicSubscriptionsResponse; using dapr::proto::runtime::v1::ListInputBindingsResponse; using dapr::proto::runtime::v1::BindingEventRequest; using dapr::proto::runtime::v1::BindingEventResponse; using dapr::proto::runtime::v1::TopicEventRequest; using dapr::proto::runtime::v1::TopicEventResponse; namespace dapr_cpp_echo_example { Status EchoAppServerImpl::OnInvoke( ServerContext* context, const InvokeRequest* request, InvokeResponse* response) { std::cout << "OnInvoke() is called" << std::endl; if (request->method() == "echo") { std::cout << "Got the message: " << request->data().value() << std::endl; std::string resp_str = "ack : " + request->data().value(); response->mutable_data()->set_value(resp_str); } return Status::OK; } Status EchoAppServerImpl::ListTopicSubscriptions( ServerContext* context, const Empty* request, ListTopicSubscriptionsResponse* response) { std::cout << "ListTopicSubscriptions() is called" << std::endl; return Status::OK; } Status EchoAppServerImpl::ListInputBindings( ServerContext* context, const Empty* request, ListInputBindingsResponse* response) { std::cout << "ListInputBindings() is called" << std::endl; return Status::OK; } Status EchoAppServerImpl::OnBindingEvent( ServerContext* context, const BindingEventRequest* request, BindingEventResponse* response) { std::cout << "OnBindingEvent() is called" << std::endl; return Status::OK; } Status EchoAppServerImpl::OnTopicEvent( ServerContext* context, const TopicEventRequest* request, TopicEventResponse* response) { std::cout << "OnBindingEvent() is called" << std::endl; return Status::OK; } } // namespace dapr_cpp_echo_example <|start_filename|>examples/echo_app/echo_app_server_impl.h<|end_filename|> // ------------------------------------------------------------------------ // Copyright 2021 The Dapr Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include <grpcpp/grpcpp.h> #include "dapr/proto/common/v1/common.pb.h" #include "dapr/proto/runtime/v1/appcallback.grpc.pb.h" using grpc::ServerContext; using grpc::Status; using google::protobuf::Any; using google::protobuf::Empty; using dapr::proto::common::v1::InvokeRequest; using dapr::proto::common::v1::InvokeResponse; using dapr::proto::runtime::v1::AppCallback; using dapr::proto::runtime::v1::ListTopicSubscriptionsResponse; using dapr::proto::runtime::v1::ListInputBindingsResponse; using dapr::proto::runtime::v1::BindingEventRequest; using dapr::proto::runtime::v1::BindingEventResponse; using dapr::proto::runtime::v1::TopicEventRequest; using dapr::proto::runtime::v1::TopicEventResponse; namespace dapr_cpp_echo_example { class EchoAppServerImpl final : public AppCallback::Service { public: Status OnInvoke(ServerContext* context, const InvokeRequest* request, InvokeResponse* response) override; Status ListTopicSubscriptions(ServerContext* context, const Empty* request, ListTopicSubscriptionsResponse* response) override; Status ListInputBindings(ServerContext* context, const Empty* request, ListInputBindingsResponse* response) override; Status OnBindingEvent(ServerContext* context, const BindingEventRequest* request, BindingEventResponse* response) override; Status OnTopicEvent(ServerContext* context, const TopicEventRequest* request, TopicEventResponse* response) override; }; } // namespace dapr_cpp_echo_example <|start_filename|>src/dapr/proto/common/v1/common.pb.cc<|end_filename|> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: dapr/proto/common/v1/common.proto #include "dapr/proto/common/v1/common.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ConfigurationItem_MetadataEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Etag; extern PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HTTPExtension; extern PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_StateItem_MetadataEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_StateOptions; } // namespace protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto namespace protobuf_google_2fprotobuf_2fany_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Any; } // namespace protobuf_google_2fprotobuf_2fany_2eproto namespace dapr { namespace proto { namespace common { namespace v1 { class HTTPExtensionDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HTTPExtension> _instance; } _HTTPExtension_default_instance_; class InvokeRequestDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<InvokeRequest> _instance; } _InvokeRequest_default_instance_; class InvokeResponseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<InvokeResponse> _instance; } _InvokeResponse_default_instance_; class StateItem_MetadataEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StateItem_MetadataEntry_DoNotUse> _instance; } _StateItem_MetadataEntry_DoNotUse_default_instance_; class StateItemDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StateItem> _instance; } _StateItem_default_instance_; class EtagDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Etag> _instance; } _Etag_default_instance_; class StateOptionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StateOptions> _instance; } _StateOptions_default_instance_; class ConfigurationItem_MetadataEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<ConfigurationItem_MetadataEntry_DoNotUse> _instance; } _ConfigurationItem_MetadataEntry_DoNotUse_default_instance_; class ConfigurationItemDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<ConfigurationItem> _instance; } _ConfigurationItem_default_instance_; } // namespace v1 } // namespace common } // namespace proto } // namespace dapr namespace protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto { static void InitDefaultsHTTPExtension() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_HTTPExtension_default_instance_; new (ptr) ::dapr::proto::common::v1::HTTPExtension(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::HTTPExtension::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_HTTPExtension = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHTTPExtension}, {}}; static void InitDefaultsInvokeRequest() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_InvokeRequest_default_instance_; new (ptr) ::dapr::proto::common::v1::InvokeRequest(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::InvokeRequest::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_InvokeRequest = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsInvokeRequest}, { &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base, &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_HTTPExtension.base,}}; static void InitDefaultsInvokeResponse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_InvokeResponse_default_instance_; new (ptr) ::dapr::proto::common::v1::InvokeResponse(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::InvokeResponse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_InvokeResponse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsInvokeResponse}, { &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base,}}; static void InitDefaultsStateItem_MetadataEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_StateItem_MetadataEntry_DoNotUse_default_instance_; new (ptr) ::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse(); } ::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_StateItem_MetadataEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsStateItem_MetadataEntry_DoNotUse}, {}}; static void InitDefaultsStateItem() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_StateItem_default_instance_; new (ptr) ::dapr::proto::common::v1::StateItem(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::StateItem::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<3> scc_info_StateItem = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsStateItem}, { &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_Etag.base, &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_StateItem_MetadataEntry_DoNotUse.base, &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_StateOptions.base,}}; static void InitDefaultsEtag() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_Etag_default_instance_; new (ptr) ::dapr::proto::common::v1::Etag(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::Etag::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_Etag = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEtag}, {}}; static void InitDefaultsStateOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_StateOptions_default_instance_; new (ptr) ::dapr::proto::common::v1::StateOptions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::StateOptions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_StateOptions = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsStateOptions}, {}}; static void InitDefaultsConfigurationItem_MetadataEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_ConfigurationItem_MetadataEntry_DoNotUse_default_instance_; new (ptr) ::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse(); } ::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_ConfigurationItem_MetadataEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsConfigurationItem_MetadataEntry_DoNotUse}, {}}; static void InitDefaultsConfigurationItem() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::dapr::proto::common::v1::_ConfigurationItem_default_instance_; new (ptr) ::dapr::proto::common::v1::ConfigurationItem(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::dapr::proto::common::v1::ConfigurationItem::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_ConfigurationItem = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsConfigurationItem}, { &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_ConfigurationItem_MetadataEntry_DoNotUse.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_HTTPExtension.base); ::google::protobuf::internal::InitSCC(&scc_info_InvokeRequest.base); ::google::protobuf::internal::InitSCC(&scc_info_InvokeResponse.base); ::google::protobuf::internal::InitSCC(&scc_info_StateItem_MetadataEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_StateItem.base); ::google::protobuf::internal::InitSCC(&scc_info_Etag.base); ::google::protobuf::internal::InitSCC(&scc_info_StateOptions.base); ::google::protobuf::internal::InitSCC(&scc_info_ConfigurationItem_MetadataEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_ConfigurationItem.base); } ::google::protobuf::Metadata file_level_metadata[9]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[3]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::HTTPExtension, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::HTTPExtension, verb_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::HTTPExtension, querystring_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeRequest, method_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeRequest, data_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeRequest, content_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeRequest, http_extension_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeResponse, data_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::InvokeResponse, content_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem, value_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem, etag_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem, metadata_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateItem, options_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::Etag, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::Etag, value_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateOptions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateOptions, concurrency_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::StateOptions, consistency_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem, value_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem, version_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dapr::proto::common::v1::ConfigurationItem, metadata_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::dapr::proto::common::v1::HTTPExtension)}, { 7, -1, sizeof(::dapr::proto::common::v1::InvokeRequest)}, { 16, -1, sizeof(::dapr::proto::common::v1::InvokeResponse)}, { 23, 30, sizeof(::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse)}, { 32, -1, sizeof(::dapr::proto::common::v1::StateItem)}, { 42, -1, sizeof(::dapr::proto::common::v1::Etag)}, { 48, -1, sizeof(::dapr::proto::common::v1::StateOptions)}, { 55, 62, sizeof(::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse)}, { 64, -1, sizeof(::dapr::proto::common::v1::ConfigurationItem)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_HTTPExtension_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_InvokeRequest_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_InvokeResponse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_StateItem_MetadataEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_StateItem_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_Etag_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_StateOptions_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_ConfigurationItem_MetadataEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::dapr::proto::common::v1::_ConfigurationItem_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "dapr/proto/common/v1/common.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 9); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n!dapr/proto/common/v1/common.proto\022\024dap" "r.proto.common.v1\032\031google/protobuf/any.p" "roto\"\320\001\n\rHTTPExtension\0226\n\004verb\030\001 \001(\0162(.d" "apr.proto.common.v1.HTTPExtension.Verb\022\023" "\n\013querystring\030\002 \001(\t\"r\n\004Verb\022\010\n\004NONE\020\000\022\007\n" "\003GET\020\001\022\010\n\004HEAD\020\002\022\010\n\004POST\020\003\022\007\n\003PUT\020\004\022\n\n\006D" "ELETE\020\005\022\013\n\007CONNECT\020\006\022\013\n\007OPTIONS\020\007\022\t\n\005TRA" "CE\020\010\022\t\n\005PATCH\020\t\"\226\001\n\rInvokeRequest\022\016\n\006met" "hod\030\001 \001(\t\022\"\n\004data\030\002 \001(\0132\024.google.protobu" "f.Any\022\024\n\014content_type\030\003 \001(\t\022;\n\016http_exte" "nsion\030\004 \001(\0132#.dapr.proto.common.v1.HTTPE" "xtension\"J\n\016InvokeResponse\022\"\n\004data\030\001 \001(\013" "2\024.google.protobuf.Any\022\024\n\014content_type\030\002" " \001(\t\"\370\001\n\tStateItem\022\013\n\003key\030\001 \001(\t\022\r\n\005value" "\030\002 \001(\014\022(\n\004etag\030\003 \001(\0132\032.dapr.proto.common" ".v1.Etag\022\?\n\010metadata\030\004 \003(\0132-.dapr.proto." "common.v1.StateItem.MetadataEntry\0223\n\007opt" "ions\030\005 \001(\0132\".dapr.proto.common.v1.StateO" "ptions\032/\n\rMetadataEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005" "value\030\002 \001(\t:\0028\001\"\025\n\004Etag\022\r\n\005value\030\001 \001(\t\"\357" "\002\n\014StateOptions\022H\n\013concurrency\030\001 \001(\01623.d" "apr.proto.common.v1.StateOptions.StateCo" "ncurrency\022H\n\013consistency\030\002 \001(\01623.dapr.pr" "oto.common.v1.StateOptions.StateConsiste" "ncy\"h\n\020StateConcurrency\022\033\n\027CONCURRENCY_U" "NSPECIFIED\020\000\022\033\n\027CONCURRENCY_FIRST_WRITE\020" "\001\022\032\n\026CONCURRENCY_LAST_WRITE\020\002\"a\n\020StateCo" "nsistency\022\033\n\027CONSISTENCY_UNSPECIFIED\020\000\022\030" "\n\024CONSISTENCY_EVENTUAL\020\001\022\026\n\022CONSISTENCY_" "STRONG\020\002\"\272\001\n\021ConfigurationItem\022\013\n\003key\030\001 " "\001(\t\022\r\n\005value\030\002 \001(\t\022\017\n\007version\030\003 \001(\t\022G\n\010m" "etadata\030\004 \003(\01325.dapr.proto.common.v1.Con" "figurationItem.MetadataEntry\032/\n\rMetadata" "Entry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001Bi\n" "\nio.dapr.v1B\014CommonProtosZ/github.com/da" "pr/dapr/pkg/proto/common/v1;common\252\002\033Dap" "r.Client.Autogen.Grpc.v1b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 1472); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "dapr/proto/common/v1/common.proto", &protobuf_RegisterTypes); ::protobuf_google_2fprotobuf_2fany_2eproto::AddDescriptors(); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto namespace dapr { namespace proto { namespace common { namespace v1 { const ::google::protobuf::EnumDescriptor* HTTPExtension_Verb_descriptor() { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_enum_descriptors[0]; } bool HTTPExtension_Verb_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const HTTPExtension_Verb HTTPExtension::NONE; const HTTPExtension_Verb HTTPExtension::GET; const HTTPExtension_Verb HTTPExtension::HEAD; const HTTPExtension_Verb HTTPExtension::POST; const HTTPExtension_Verb HTTPExtension::PUT; const HTTPExtension_Verb HTTPExtension::DELETE; const HTTPExtension_Verb HTTPExtension::CONNECT; const HTTPExtension_Verb HTTPExtension::OPTIONS; const HTTPExtension_Verb HTTPExtension::TRACE; const HTTPExtension_Verb HTTPExtension::PATCH; const HTTPExtension_Verb HTTPExtension::Verb_MIN; const HTTPExtension_Verb HTTPExtension::Verb_MAX; const int HTTPExtension::Verb_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* StateOptions_StateConcurrency_descriptor() { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_enum_descriptors[1]; } bool StateOptions_StateConcurrency_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const StateOptions_StateConcurrency StateOptions::CONCURRENCY_UNSPECIFIED; const StateOptions_StateConcurrency StateOptions::CONCURRENCY_FIRST_WRITE; const StateOptions_StateConcurrency StateOptions::CONCURRENCY_LAST_WRITE; const StateOptions_StateConcurrency StateOptions::StateConcurrency_MIN; const StateOptions_StateConcurrency StateOptions::StateConcurrency_MAX; const int StateOptions::StateConcurrency_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* StateOptions_StateConsistency_descriptor() { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_enum_descriptors[2]; } bool StateOptions_StateConsistency_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const StateOptions_StateConsistency StateOptions::CONSISTENCY_UNSPECIFIED; const StateOptions_StateConsistency StateOptions::CONSISTENCY_EVENTUAL; const StateOptions_StateConsistency StateOptions::CONSISTENCY_STRONG; const StateOptions_StateConsistency StateOptions::StateConsistency_MIN; const StateOptions_StateConsistency StateOptions::StateConsistency_MAX; const int StateOptions::StateConsistency_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 // =================================================================== void HTTPExtension::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HTTPExtension::kVerbFieldNumber; const int HTTPExtension::kQuerystringFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HTTPExtension::HTTPExtension() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_HTTPExtension.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.HTTPExtension) } HTTPExtension::HTTPExtension(const HTTPExtension& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); querystring_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.querystring().size() > 0) { querystring_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.querystring_); } verb_ = from.verb_; // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.HTTPExtension) } void HTTPExtension::SharedCtor() { querystring_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); verb_ = 0; } HTTPExtension::~HTTPExtension() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.HTTPExtension) SharedDtor(); } void HTTPExtension::SharedDtor() { querystring_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void HTTPExtension::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* HTTPExtension::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const HTTPExtension& HTTPExtension::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_HTTPExtension.base); return *internal_default_instance(); } void HTTPExtension::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.HTTPExtension) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; querystring_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); verb_ = 0; _internal_metadata_.Clear(); } bool HTTPExtension::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.HTTPExtension) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .dapr.proto.common.v1.HTTPExtension.Verb verb = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_verb(static_cast< ::dapr::proto::common::v1::HTTPExtension_Verb >(value)); } else { goto handle_unusual; } break; } // string querystring = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_querystring())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->querystring().data(), static_cast<int>(this->querystring().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.HTTPExtension.querystring")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.HTTPExtension) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.HTTPExtension) return false; #undef DO_ } void HTTPExtension::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.HTTPExtension) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .dapr.proto.common.v1.HTTPExtension.Verb verb = 1; if (this->verb() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->verb(), output); } // string querystring = 2; if (this->querystring().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->querystring().data(), static_cast<int>(this->querystring().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.HTTPExtension.querystring"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->querystring(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.HTTPExtension) } ::google::protobuf::uint8* HTTPExtension::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.HTTPExtension) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .dapr.proto.common.v1.HTTPExtension.Verb verb = 1; if (this->verb() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->verb(), target); } // string querystring = 2; if (this->querystring().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->querystring().data(), static_cast<int>(this->querystring().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.HTTPExtension.querystring"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->querystring(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.HTTPExtension) return target; } size_t HTTPExtension::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.HTTPExtension) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // string querystring = 2; if (this->querystring().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->querystring()); } // .dapr.proto.common.v1.HTTPExtension.Verb verb = 1; if (this->verb() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->verb()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HTTPExtension::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.HTTPExtension) GOOGLE_DCHECK_NE(&from, this); const HTTPExtension* source = ::google::protobuf::internal::DynamicCastToGenerated<const HTTPExtension>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.HTTPExtension) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.HTTPExtension) MergeFrom(*source); } } void HTTPExtension::MergeFrom(const HTTPExtension& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.HTTPExtension) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.querystring().size() > 0) { querystring_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.querystring_); } if (from.verb() != 0) { set_verb(from.verb()); } } void HTTPExtension::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.HTTPExtension) if (&from == this) return; Clear(); MergeFrom(from); } void HTTPExtension::CopyFrom(const HTTPExtension& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.HTTPExtension) if (&from == this) return; Clear(); MergeFrom(from); } bool HTTPExtension::IsInitialized() const { return true; } void HTTPExtension::Swap(HTTPExtension* other) { if (other == this) return; InternalSwap(other); } void HTTPExtension::InternalSwap(HTTPExtension* other) { using std::swap; querystring_.Swap(&other->querystring_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(verb_, other->verb_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata HTTPExtension::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void InvokeRequest::InitAsDefaultInstance() { ::dapr::proto::common::v1::_InvokeRequest_default_instance_._instance.get_mutable()->data_ = const_cast< ::google::protobuf::Any*>( ::google::protobuf::Any::internal_default_instance()); ::dapr::proto::common::v1::_InvokeRequest_default_instance_._instance.get_mutable()->http_extension_ = const_cast< ::dapr::proto::common::v1::HTTPExtension*>( ::dapr::proto::common::v1::HTTPExtension::internal_default_instance()); } void InvokeRequest::clear_data() { if (GetArenaNoVirtual() == NULL && data_ != NULL) { delete data_; } data_ = NULL; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int InvokeRequest::kMethodFieldNumber; const int InvokeRequest::kDataFieldNumber; const int InvokeRequest::kContentTypeFieldNumber; const int InvokeRequest::kHttpExtensionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 InvokeRequest::InvokeRequest() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_InvokeRequest.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.InvokeRequest) } InvokeRequest::InvokeRequest(const InvokeRequest& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); method_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.method().size() > 0) { method_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.method_); } content_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.content_type().size() > 0) { content_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_type_); } if (from.has_data()) { data_ = new ::google::protobuf::Any(*from.data_); } else { data_ = NULL; } if (from.has_http_extension()) { http_extension_ = new ::dapr::proto::common::v1::HTTPExtension(*from.http_extension_); } else { http_extension_ = NULL; } // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.InvokeRequest) } void InvokeRequest::SharedCtor() { method_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&data_, 0, static_cast<size_t>( reinterpret_cast<char*>(&http_extension_) - reinterpret_cast<char*>(&data_)) + sizeof(http_extension_)); } InvokeRequest::~InvokeRequest() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.InvokeRequest) SharedDtor(); } void InvokeRequest::SharedDtor() { method_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete data_; if (this != internal_default_instance()) delete http_extension_; } void InvokeRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* InvokeRequest::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const InvokeRequest& InvokeRequest::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_InvokeRequest.base); return *internal_default_instance(); } void InvokeRequest::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.InvokeRequest) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; method_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == NULL && data_ != NULL) { delete data_; } data_ = NULL; if (GetArenaNoVirtual() == NULL && http_extension_ != NULL) { delete http_extension_; } http_extension_ = NULL; _internal_metadata_.Clear(); } bool InvokeRequest::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.InvokeRequest) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string method = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_method())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->method().data(), static_cast<int>(this->method().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.InvokeRequest.method")); } else { goto handle_unusual; } break; } // .google.protobuf.Any data = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_data())); } else { goto handle_unusual; } break; } // string content_type = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_content_type())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content_type().data(), static_cast<int>(this->content_type().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.InvokeRequest.content_type")); } else { goto handle_unusual; } break; } // .dapr.proto.common.v1.HTTPExtension http_extension = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_http_extension())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.InvokeRequest) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.InvokeRequest) return false; #undef DO_ } void InvokeRequest::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.InvokeRequest) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string method = 1; if (this->method().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->method().data(), static_cast<int>(this->method().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.InvokeRequest.method"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->method(), output); } // .google.protobuf.Any data = 2; if (this->has_data()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->_internal_data(), output); } // string content_type = 3; if (this->content_type().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content_type().data(), static_cast<int>(this->content_type().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.InvokeRequest.content_type"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->content_type(), output); } // .dapr.proto.common.v1.HTTPExtension http_extension = 4; if (this->has_http_extension()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->_internal_http_extension(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.InvokeRequest) } ::google::protobuf::uint8* InvokeRequest::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.InvokeRequest) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string method = 1; if (this->method().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->method().data(), static_cast<int>(this->method().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.InvokeRequest.method"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->method(), target); } // .google.protobuf.Any data = 2; if (this->has_data()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->_internal_data(), deterministic, target); } // string content_type = 3; if (this->content_type().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content_type().data(), static_cast<int>(this->content_type().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.InvokeRequest.content_type"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->content_type(), target); } // .dapr.proto.common.v1.HTTPExtension http_extension = 4; if (this->has_http_extension()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, this->_internal_http_extension(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.InvokeRequest) return target; } size_t InvokeRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.InvokeRequest) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // string method = 1; if (this->method().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->method()); } // string content_type = 3; if (this->content_type().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->content_type()); } // .google.protobuf.Any data = 2; if (this->has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *data_); } // .dapr.proto.common.v1.HTTPExtension http_extension = 4; if (this->has_http_extension()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *http_extension_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void InvokeRequest::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.InvokeRequest) GOOGLE_DCHECK_NE(&from, this); const InvokeRequest* source = ::google::protobuf::internal::DynamicCastToGenerated<const InvokeRequest>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.InvokeRequest) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.InvokeRequest) MergeFrom(*source); } } void InvokeRequest::MergeFrom(const InvokeRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.InvokeRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.method().size() > 0) { method_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.method_); } if (from.content_type().size() > 0) { content_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_type_); } if (from.has_data()) { mutable_data()->::google::protobuf::Any::MergeFrom(from.data()); } if (from.has_http_extension()) { mutable_http_extension()->::dapr::proto::common::v1::HTTPExtension::MergeFrom(from.http_extension()); } } void InvokeRequest::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.InvokeRequest) if (&from == this) return; Clear(); MergeFrom(from); } void InvokeRequest::CopyFrom(const InvokeRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.InvokeRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool InvokeRequest::IsInitialized() const { return true; } void InvokeRequest::Swap(InvokeRequest* other) { if (other == this) return; InternalSwap(other); } void InvokeRequest::InternalSwap(InvokeRequest* other) { using std::swap; method_.Swap(&other->method_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); content_type_.Swap(&other->content_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(data_, other->data_); swap(http_extension_, other->http_extension_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata InvokeRequest::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void InvokeResponse::InitAsDefaultInstance() { ::dapr::proto::common::v1::_InvokeResponse_default_instance_._instance.get_mutable()->data_ = const_cast< ::google::protobuf::Any*>( ::google::protobuf::Any::internal_default_instance()); } void InvokeResponse::clear_data() { if (GetArenaNoVirtual() == NULL && data_ != NULL) { delete data_; } data_ = NULL; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int InvokeResponse::kDataFieldNumber; const int InvokeResponse::kContentTypeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 InvokeResponse::InvokeResponse() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_InvokeResponse.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.InvokeResponse) } InvokeResponse::InvokeResponse(const InvokeResponse& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); content_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.content_type().size() > 0) { content_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_type_); } if (from.has_data()) { data_ = new ::google::protobuf::Any(*from.data_); } else { data_ = NULL; } // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.InvokeResponse) } void InvokeResponse::SharedCtor() { content_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); data_ = NULL; } InvokeResponse::~InvokeResponse() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.InvokeResponse) SharedDtor(); } void InvokeResponse::SharedDtor() { content_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete data_; } void InvokeResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* InvokeResponse::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const InvokeResponse& InvokeResponse::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_InvokeResponse.base); return *internal_default_instance(); } void InvokeResponse::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.InvokeResponse) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; content_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == NULL && data_ != NULL) { delete data_; } data_ = NULL; _internal_metadata_.Clear(); } bool InvokeResponse::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.InvokeResponse) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .google.protobuf.Any data = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_data())); } else { goto handle_unusual; } break; } // string content_type = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_content_type())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content_type().data(), static_cast<int>(this->content_type().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.InvokeResponse.content_type")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.InvokeResponse) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.InvokeResponse) return false; #undef DO_ } void InvokeResponse::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.InvokeResponse) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.protobuf.Any data = 1; if (this->has_data()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->_internal_data(), output); } // string content_type = 2; if (this->content_type().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content_type().data(), static_cast<int>(this->content_type().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.InvokeResponse.content_type"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->content_type(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.InvokeResponse) } ::google::protobuf::uint8* InvokeResponse::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.InvokeResponse) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.protobuf.Any data = 1; if (this->has_data()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->_internal_data(), deterministic, target); } // string content_type = 2; if (this->content_type().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->content_type().data(), static_cast<int>(this->content_type().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.InvokeResponse.content_type"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->content_type(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.InvokeResponse) return target; } size_t InvokeResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.InvokeResponse) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // string content_type = 2; if (this->content_type().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->content_type()); } // .google.protobuf.Any data = 1; if (this->has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *data_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void InvokeResponse::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.InvokeResponse) GOOGLE_DCHECK_NE(&from, this); const InvokeResponse* source = ::google::protobuf::internal::DynamicCastToGenerated<const InvokeResponse>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.InvokeResponse) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.InvokeResponse) MergeFrom(*source); } } void InvokeResponse::MergeFrom(const InvokeResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.InvokeResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.content_type().size() > 0) { content_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_type_); } if (from.has_data()) { mutable_data()->::google::protobuf::Any::MergeFrom(from.data()); } } void InvokeResponse::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.InvokeResponse) if (&from == this) return; Clear(); MergeFrom(from); } void InvokeResponse::CopyFrom(const InvokeResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.InvokeResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool InvokeResponse::IsInitialized() const { return true; } void InvokeResponse::Swap(InvokeResponse* other) { if (other == this) return; InternalSwap(other); } void InvokeResponse::InternalSwap(InvokeResponse* other) { using std::swap; content_type_.Swap(&other->content_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(data_, other->data_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata InvokeResponse::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== StateItem_MetadataEntry_DoNotUse::StateItem_MetadataEntry_DoNotUse() {} StateItem_MetadataEntry_DoNotUse::StateItem_MetadataEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void StateItem_MetadataEntry_DoNotUse::MergeFrom(const StateItem_MetadataEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata StateItem_MetadataEntry_DoNotUse::GetMetadata() const { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[3]; } void StateItem_MetadataEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void StateItem::InitAsDefaultInstance() { ::dapr::proto::common::v1::_StateItem_default_instance_._instance.get_mutable()->etag_ = const_cast< ::dapr::proto::common::v1::Etag*>( ::dapr::proto::common::v1::Etag::internal_default_instance()); ::dapr::proto::common::v1::_StateItem_default_instance_._instance.get_mutable()->options_ = const_cast< ::dapr::proto::common::v1::StateOptions*>( ::dapr::proto::common::v1::StateOptions::internal_default_instance()); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int StateItem::kKeyFieldNumber; const int StateItem::kValueFieldNumber; const int StateItem::kEtagFieldNumber; const int StateItem::kMetadataFieldNumber; const int StateItem::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 StateItem::StateItem() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_StateItem.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.StateItem) } StateItem::StateItem(const StateItem& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); metadata_.MergeFrom(from.metadata_); key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.key().size() > 0) { key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_); } value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.value().size() > 0) { value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); } if (from.has_etag()) { etag_ = new ::dapr::proto::common::v1::Etag(*from.etag_); } else { etag_ = NULL; } if (from.has_options()) { options_ = new ::dapr::proto::common::v1::StateOptions(*from.options_); } else { options_ = NULL; } // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.StateItem) } void StateItem::SharedCtor() { key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&etag_, 0, static_cast<size_t>( reinterpret_cast<char*>(&options_) - reinterpret_cast<char*>(&etag_)) + sizeof(options_)); } StateItem::~StateItem() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.StateItem) SharedDtor(); } void StateItem::SharedDtor() { key_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete etag_; if (this != internal_default_instance()) delete options_; } void StateItem::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* StateItem::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const StateItem& StateItem::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_StateItem.base); return *internal_default_instance(); } void StateItem::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.StateItem) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; metadata_.Clear(); key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == NULL && etag_ != NULL) { delete etag_; } etag_ = NULL; if (GetArenaNoVirtual() == NULL && options_ != NULL) { delete options_; } options_ = NULL; _internal_metadata_.Clear(); } bool StateItem::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.StateItem) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string key = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_key())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->key().data(), static_cast<int>(this->key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.StateItem.key")); } else { goto handle_unusual; } break; } // bytes value = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_value())); } else { goto handle_unusual; } break; } // .dapr.proto.common.v1.Etag etag = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_etag())); } else { goto handle_unusual; } break; } // map<string, string> metadata = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { StateItem_MetadataEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< StateItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&metadata_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.StateItem.MetadataEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.StateItem.MetadataEntry.value")); } else { goto handle_unusual; } break; } // .dapr.proto.common.v1.StateOptions options = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_options())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.StateItem) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.StateItem) return false; #undef DO_ } void StateItem::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.StateItem) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string key = 1; if (this->key().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->key().data(), static_cast<int>(this->key().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.StateItem.key"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->key(), output); } // bytes value = 2; if (this->value().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 2, this->value(), output); } // .dapr.proto.common.v1.Etag etag = 3; if (this->has_etag()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->_internal_etag(), output); } // map<string, string> metadata = 4; if (!this->metadata().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.StateItem.MetadataEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.StateItem.MetadataEntry.value"); } }; if (output->IsSerializationDeterministic() && this->metadata().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->metadata().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<StateItem_MetadataEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(metadata_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *entry, output); Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<StateItem_MetadataEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it) { entry.reset(metadata_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *entry, output); Utf8Check::Check(&*it); } } } // .dapr.proto.common.v1.StateOptions options = 5; if (this->has_options()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->_internal_options(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.StateItem) } ::google::protobuf::uint8* StateItem::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.StateItem) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string key = 1; if (this->key().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->key().data(), static_cast<int>(this->key().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.StateItem.key"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->key(), target); } // bytes value = 2; if (this->value().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 2, this->value(), target); } // .dapr.proto.common.v1.Etag etag = 3; if (this->has_etag()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->_internal_etag(), deterministic, target); } // map<string, string> metadata = 4; if (!this->metadata().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.StateItem.MetadataEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.StateItem.MetadataEntry.value"); } }; if (deterministic && this->metadata().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->metadata().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<StateItem_MetadataEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(metadata_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *entry, deterministic, target); ; Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<StateItem_MetadataEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it) { entry.reset(metadata_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *entry, deterministic, target); ; Utf8Check::Check(&*it); } } } // .dapr.proto.common.v1.StateOptions options = 5; if (this->has_options()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 5, this->_internal_options(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.StateItem) return target; } size_t StateItem::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.StateItem) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, string> metadata = 4; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->metadata_size()); { ::std::unique_ptr<StateItem_MetadataEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it) { entry.reset(metadata_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } // string key = 1; if (this->key().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->key()); } // bytes value = 2; if (this->value().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->value()); } // .dapr.proto.common.v1.Etag etag = 3; if (this->has_etag()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *etag_); } // .dapr.proto.common.v1.StateOptions options = 5; if (this->has_options()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *options_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StateItem::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.StateItem) GOOGLE_DCHECK_NE(&from, this); const StateItem* source = ::google::protobuf::internal::DynamicCastToGenerated<const StateItem>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.StateItem) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.StateItem) MergeFrom(*source); } } void StateItem::MergeFrom(const StateItem& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.StateItem) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; metadata_.MergeFrom(from.metadata_); if (from.key().size() > 0) { key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_); } if (from.value().size() > 0) { value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); } if (from.has_etag()) { mutable_etag()->::dapr::proto::common::v1::Etag::MergeFrom(from.etag()); } if (from.has_options()) { mutable_options()->::dapr::proto::common::v1::StateOptions::MergeFrom(from.options()); } } void StateItem::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.StateItem) if (&from == this) return; Clear(); MergeFrom(from); } void StateItem::CopyFrom(const StateItem& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.StateItem) if (&from == this) return; Clear(); MergeFrom(from); } bool StateItem::IsInitialized() const { return true; } void StateItem::Swap(StateItem* other) { if (other == this) return; InternalSwap(other); } void StateItem::InternalSwap(StateItem* other) { using std::swap; metadata_.Swap(&other->metadata_); key_.Swap(&other->key_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(etag_, other->etag_); swap(options_, other->options_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata StateItem::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void Etag::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Etag::kValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Etag::Etag() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_Etag.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.Etag) } Etag::Etag(const Etag& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.value().size() > 0) { value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); } // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.Etag) } void Etag::SharedCtor() { value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } Etag::~Etag() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.Etag) SharedDtor(); } void Etag::SharedDtor() { value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void Etag::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Etag::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Etag& Etag::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_Etag.base); return *internal_default_instance(); } void Etag::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.Etag) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } bool Etag::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.Etag) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string value = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_value())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->value().data(), static_cast<int>(this->value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.Etag.value")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.Etag) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.Etag) return false; #undef DO_ } void Etag::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.Etag) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string value = 1; if (this->value().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->value().data(), static_cast<int>(this->value().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.Etag.value"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->value(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.Etag) } ::google::protobuf::uint8* Etag::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.Etag) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string value = 1; if (this->value().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->value().data(), static_cast<int>(this->value().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.Etag.value"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->value(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.Etag) return target; } size_t Etag::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.Etag) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // string value = 1; if (this->value().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->value()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Etag::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.Etag) GOOGLE_DCHECK_NE(&from, this); const Etag* source = ::google::protobuf::internal::DynamicCastToGenerated<const Etag>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.Etag) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.Etag) MergeFrom(*source); } } void Etag::MergeFrom(const Etag& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.Etag) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.value().size() > 0) { value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); } } void Etag::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.Etag) if (&from == this) return; Clear(); MergeFrom(from); } void Etag::CopyFrom(const Etag& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.Etag) if (&from == this) return; Clear(); MergeFrom(from); } bool Etag::IsInitialized() const { return true; } void Etag::Swap(Etag* other) { if (other == this) return; InternalSwap(other); } void Etag::InternalSwap(Etag* other) { using std::swap; value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata Etag::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void StateOptions::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int StateOptions::kConcurrencyFieldNumber; const int StateOptions::kConsistencyFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 StateOptions::StateOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_StateOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.StateOptions) } StateOptions::StateOptions(const StateOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&concurrency_, &from.concurrency_, static_cast<size_t>(reinterpret_cast<char*>(&consistency_) - reinterpret_cast<char*>(&concurrency_)) + sizeof(consistency_)); // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.StateOptions) } void StateOptions::SharedCtor() { ::memset(&concurrency_, 0, static_cast<size_t>( reinterpret_cast<char*>(&consistency_) - reinterpret_cast<char*>(&concurrency_)) + sizeof(consistency_)); } StateOptions::~StateOptions() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.StateOptions) SharedDtor(); } void StateOptions::SharedDtor() { } void StateOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* StateOptions::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const StateOptions& StateOptions::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_StateOptions.base); return *internal_default_instance(); } void StateOptions::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.StateOptions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&concurrency_, 0, static_cast<size_t>( reinterpret_cast<char*>(&consistency_) - reinterpret_cast<char*>(&concurrency_)) + sizeof(consistency_)); _internal_metadata_.Clear(); } bool StateOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.StateOptions) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .dapr.proto.common.v1.StateOptions.StateConcurrency concurrency = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_concurrency(static_cast< ::dapr::proto::common::v1::StateOptions_StateConcurrency >(value)); } else { goto handle_unusual; } break; } // .dapr.proto.common.v1.StateOptions.StateConsistency consistency = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_consistency(static_cast< ::dapr::proto::common::v1::StateOptions_StateConsistency >(value)); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.StateOptions) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.StateOptions) return false; #undef DO_ } void StateOptions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.StateOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .dapr.proto.common.v1.StateOptions.StateConcurrency concurrency = 1; if (this->concurrency() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->concurrency(), output); } // .dapr.proto.common.v1.StateOptions.StateConsistency consistency = 2; if (this->consistency() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 2, this->consistency(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.StateOptions) } ::google::protobuf::uint8* StateOptions::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.StateOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .dapr.proto.common.v1.StateOptions.StateConcurrency concurrency = 1; if (this->concurrency() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->concurrency(), target); } // .dapr.proto.common.v1.StateOptions.StateConsistency consistency = 2; if (this->consistency() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 2, this->consistency(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.StateOptions) return target; } size_t StateOptions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.StateOptions) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // .dapr.proto.common.v1.StateOptions.StateConcurrency concurrency = 1; if (this->concurrency() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->concurrency()); } // .dapr.proto.common.v1.StateOptions.StateConsistency consistency = 2; if (this->consistency() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->consistency()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StateOptions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.StateOptions) GOOGLE_DCHECK_NE(&from, this); const StateOptions* source = ::google::protobuf::internal::DynamicCastToGenerated<const StateOptions>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.StateOptions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.StateOptions) MergeFrom(*source); } } void StateOptions::MergeFrom(const StateOptions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.StateOptions) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.concurrency() != 0) { set_concurrency(from.concurrency()); } if (from.consistency() != 0) { set_consistency(from.consistency()); } } void StateOptions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.StateOptions) if (&from == this) return; Clear(); MergeFrom(from); } void StateOptions::CopyFrom(const StateOptions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.StateOptions) if (&from == this) return; Clear(); MergeFrom(from); } bool StateOptions::IsInitialized() const { return true; } void StateOptions::Swap(StateOptions* other) { if (other == this) return; InternalSwap(other); } void StateOptions::InternalSwap(StateOptions* other) { using std::swap; swap(concurrency_, other->concurrency_); swap(consistency_, other->consistency_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata StateOptions::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== ConfigurationItem_MetadataEntry_DoNotUse::ConfigurationItem_MetadataEntry_DoNotUse() {} ConfigurationItem_MetadataEntry_DoNotUse::ConfigurationItem_MetadataEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void ConfigurationItem_MetadataEntry_DoNotUse::MergeFrom(const ConfigurationItem_MetadataEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata ConfigurationItem_MetadataEntry_DoNotUse::GetMetadata() const { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[7]; } void ConfigurationItem_MetadataEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void ConfigurationItem::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ConfigurationItem::kKeyFieldNumber; const int ConfigurationItem::kValueFieldNumber; const int ConfigurationItem::kVersionFieldNumber; const int ConfigurationItem::kMetadataFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ConfigurationItem::ConfigurationItem() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_ConfigurationItem.base); SharedCtor(); // @@protoc_insertion_point(constructor:dapr.proto.common.v1.ConfigurationItem) } ConfigurationItem::ConfigurationItem(const ConfigurationItem& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); metadata_.MergeFrom(from.metadata_); key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.key().size() > 0) { key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_); } value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.value().size() > 0) { value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); } version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.version().size() > 0) { version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_); } // @@protoc_insertion_point(copy_constructor:dapr.proto.common.v1.ConfigurationItem) } void ConfigurationItem::SharedCtor() { key_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ConfigurationItem::~ConfigurationItem() { // @@protoc_insertion_point(destructor:dapr.proto.common.v1.ConfigurationItem) SharedDtor(); } void ConfigurationItem::SharedDtor() { key_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void ConfigurationItem::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ConfigurationItem::descriptor() { ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const ConfigurationItem& ConfigurationItem::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::scc_info_ConfigurationItem.base); return *internal_default_instance(); } void ConfigurationItem::Clear() { // @@protoc_insertion_point(message_clear_start:dapr.proto.common.v1.ConfigurationItem) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; metadata_.Clear(); key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } bool ConfigurationItem::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:dapr.proto.common.v1.ConfigurationItem) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string key = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_key())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->key().data(), static_cast<int>(this->key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.ConfigurationItem.key")); } else { goto handle_unusual; } break; } // string value = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_value())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->value().data(), static_cast<int>(this->value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.ConfigurationItem.value")); } else { goto handle_unusual; } break; } // string version = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_version())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->version().data(), static_cast<int>(this->version().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.ConfigurationItem.version")); } else { goto handle_unusual; } break; } // map<string, string> metadata = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { ConfigurationItem_MetadataEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< ConfigurationItem_MetadataEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&metadata_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.ConfigurationItem.MetadataEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "dapr.proto.common.v1.ConfigurationItem.MetadataEntry.value")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:dapr.proto.common.v1.ConfigurationItem) return true; failure: // @@protoc_insertion_point(parse_failure:dapr.proto.common.v1.ConfigurationItem) return false; #undef DO_ } void ConfigurationItem::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:dapr.proto.common.v1.ConfigurationItem) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string key = 1; if (this->key().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->key().data(), static_cast<int>(this->key().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.key"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->key(), output); } // string value = 2; if (this->value().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->value().data(), static_cast<int>(this->value().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.value"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->value(), output); } // string version = 3; if (this->version().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->version().data(), static_cast<int>(this->version().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.version"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->version(), output); } // map<string, string> metadata = 4; if (!this->metadata().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.MetadataEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.MetadataEntry.value"); } }; if (output->IsSerializationDeterministic() && this->metadata().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->metadata().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<ConfigurationItem_MetadataEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(metadata_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *entry, output); Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<ConfigurationItem_MetadataEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it) { entry.reset(metadata_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *entry, output); Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:dapr.proto.common.v1.ConfigurationItem) } ::google::protobuf::uint8* ConfigurationItem::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:dapr.proto.common.v1.ConfigurationItem) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string key = 1; if (this->key().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->key().data(), static_cast<int>(this->key().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.key"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->key(), target); } // string value = 2; if (this->value().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->value().data(), static_cast<int>(this->value().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.value"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->value(), target); } // string version = 3; if (this->version().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->version().data(), static_cast<int>(this->version().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.version"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->version(), target); } // map<string, string> metadata = 4; if (!this->metadata().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.MetadataEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "dapr.proto.common.v1.ConfigurationItem.MetadataEntry.value"); } }; if (deterministic && this->metadata().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->metadata().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<ConfigurationItem_MetadataEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(metadata_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *entry, deterministic, target); ; Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<ConfigurationItem_MetadataEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it) { entry.reset(metadata_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *entry, deterministic, target); ; Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:dapr.proto.common.v1.ConfigurationItem) return target; } size_t ConfigurationItem::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:dapr.proto.common.v1.ConfigurationItem) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, string> metadata = 4; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->metadata_size()); { ::std::unique_ptr<ConfigurationItem_MetadataEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->metadata().begin(); it != this->metadata().end(); ++it) { entry.reset(metadata_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } // string key = 1; if (this->key().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->key()); } // string value = 2; if (this->value().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->value()); } // string version = 3; if (this->version().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->version()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ConfigurationItem::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:dapr.proto.common.v1.ConfigurationItem) GOOGLE_DCHECK_NE(&from, this); const ConfigurationItem* source = ::google::protobuf::internal::DynamicCastToGenerated<const ConfigurationItem>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:dapr.proto.common.v1.ConfigurationItem) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:dapr.proto.common.v1.ConfigurationItem) MergeFrom(*source); } } void ConfigurationItem::MergeFrom(const ConfigurationItem& from) { // @@protoc_insertion_point(class_specific_merge_from_start:dapr.proto.common.v1.ConfigurationItem) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; metadata_.MergeFrom(from.metadata_); if (from.key().size() > 0) { key_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.key_); } if (from.value().size() > 0) { value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); } if (from.version().size() > 0) { version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_); } } void ConfigurationItem::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:dapr.proto.common.v1.ConfigurationItem) if (&from == this) return; Clear(); MergeFrom(from); } void ConfigurationItem::CopyFrom(const ConfigurationItem& from) { // @@protoc_insertion_point(class_specific_copy_from_start:dapr.proto.common.v1.ConfigurationItem) if (&from == this) return; Clear(); MergeFrom(from); } bool ConfigurationItem::IsInitialized() const { return true; } void ConfigurationItem::Swap(ConfigurationItem* other) { if (other == this) return; InternalSwap(other); } void ConfigurationItem::InternalSwap(ConfigurationItem* other) { using std::swap; metadata_.Swap(&other->metadata_); key_.Swap(&other->key_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata ConfigurationItem::GetMetadata() const { protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_dapr_2fproto_2fcommon_2fv1_2fcommon_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace v1 } // namespace common } // namespace proto } // namespace dapr namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::HTTPExtension* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::HTTPExtension >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::HTTPExtension >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::InvokeRequest* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::InvokeRequest >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::InvokeRequest >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::InvokeResponse* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::InvokeResponse >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::InvokeResponse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::StateItem_MetadataEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::StateItem* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::StateItem >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::StateItem >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::Etag* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::Etag >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::Etag >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::StateOptions* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::StateOptions >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::StateOptions >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::ConfigurationItem_MetadataEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dapr::proto::common::v1::ConfigurationItem* Arena::CreateMaybeMessage< ::dapr::proto::common::v1::ConfigurationItem >(Arena* arena) { return Arena::CreateInternal< ::dapr::proto::common::v1::ConfigurationItem >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
berndverst/cpp-sdk
<|start_filename|>demo/src/main/java/io/github/muddz/styleabletoast/demo/MainActivity.java<|end_filename|> package io.github.muddz.styleabletoast.demo; import android.graphics.Color; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import io.github.muddz.styleabletoast.StyleableToast; import io.github.muddz.styleabletoast.demo.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { String toastMsg = "Hello World!"; int redColor = Color.parseColor("#FF5A5F"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); binding.setMain(this); } public void coloredBackground() { StyleableToast.Builder st = new StyleableToast.Builder(this) .text(toastMsg) .backgroundColor(redColor) .build(); st.show(); } public boolean coloredBackgroundXML() { StyleableToast.makeText(this, toastMsg, R.style.ColoredBackground).show(); return true; } public void coloredText() { new StyleableToast.Builder(this) .text(toastMsg) .textColor(redColor) .show(); } public boolean coloredTextXML() { StyleableToast.makeText(this, toastMsg, R.style.ColoredText).show(); return true; } public void coloredBoldText() { new StyleableToast.Builder(this) .text(toastMsg) .textColor(redColor) .textBold() .show(); } public boolean coloredBoldTextXML() { StyleableToast.makeText(this, toastMsg, R.style.ColoredBoldText).show(); return true; } public void customFont() { new StyleableToast.Builder(this) .text(toastMsg) .font(R.font.dosis) .show(); } public boolean customFontXML() { StyleableToast.makeText(this, toastMsg, R.style.CustomFont).show(); return true; } public void cornerRadius() { new StyleableToast.Builder(this) .text(toastMsg) .cornerRadius(5) .show(); } public boolean cornerRadiusXML() { StyleableToast.makeText(this, toastMsg, R.style.CornerRadius5Dp).show(); return true; } public void iconStart() { new StyleableToast.Builder(this) .text(toastMsg) .iconStart(getIcon()) .show(); } public boolean iconStartXML() { StyleableToast.makeText(this, toastMsg, R.style.IconStart).show(); return true; } public void iconEnd() { new StyleableToast.Builder(this) .text(toastMsg) .iconEnd(getIcon()) .show(); } public boolean iconEndXML() { StyleableToast.makeText(this, toastMsg, R.style.IconEnd).show(); return true; } public void iconStartEnd() { new StyleableToast.Builder(this) .text(toastMsg) .iconStart(getIcon()) .iconEnd(getIcon()) .show(); } public boolean iconStartEndXML() { StyleableToast.makeText(this, toastMsg, R.style.IconStartEnd).show(); return true; } public void coloredStroke() { new StyleableToast.Builder(this) .text(toastMsg) .stroke(2, redColor) .show(); } public boolean coloredStrokeXML() { StyleableToast.makeText(this, toastMsg, R.style.ColoredStroke).show(); return true; } public void allStyles() { new StyleableToast.Builder(this) .text(toastMsg) .stroke(2, Color.BLACK) .backgroundColor(Color.WHITE) .solidBackground() .textColor(Color.RED) .textBold() .font(R.font.dosis) .iconStart(getIcon()) .iconEnd(getIcon()) .cornerRadius(12) .textSize(18) .show(); } public boolean allStylesXML() { StyleableToast.makeText(this, toastMsg, R.style.AllStyles).show(); return true; } public int getIcon() { if (android.os.Build.VERSION.SDK_INT >= 27) { return R.drawable.ic_autorenew_black_24dp; } else { return R.drawable.ic_autorenew_white_24dp; } } }
juliussss/StyleableToast
<|start_filename|>unsupported/chrp/jwks_dir/jwks.json<|end_filename|> {"keys": [{"kty": "RSA", "use": "sig", "kid": "<KEY>", "n": "<KEY>", "e": "AQAB", "d": "<KEY>", "p": "<KEY>", "q": <KEY>"}, {"kty": "EC", "use": "sig", "kid": "<KEY>", "crv": "P-256", "x": "<KEY>", "y": "<KEY>", "d": "<KEY>"}]}
AntonLazovsky/JWTConnect-Python-OidcRP
<|start_filename|>test/runtests.jl<|end_filename|> using Test, CodeTools import Base.Docs: Binding @test CodeTools.getthing("Base.sin") == sin @test CodeTools.getthing(Base, [:sin]) == sin @testset "documentation" begin let function func(x) infunc = (y) -> y^x return infunc end @test CodeTools.hasdoc(func(3)) == false end let @doc """ docfunc(x) docs more docs which aren't in the description """ function docfunc(x) end @test CodeTools.hasdoc(docfunc) == true @test chomp(CodeTools.description(Binding(Main, :docfunc))) == "docs" @test CodeTools.signature(Binding(Main, :docfunc)) == "docfunc(x)" @test CodeTools.completiontype(docfunc) == "λ" end let @doc """ i'm a constant with multiline docs """ foo = :bar @test CodeTools.hasdoc(foo) == true @test chomp(CodeTools.description(Binding(Main, :foo))) == "i'm a constant" @test CodeTools.signature(Binding(Main, :foo)) == nothing @test CodeTools.completiontype(foo) == "constant" end end # module detection tests @testset "module detection" begin code = [""" module Mod1 [x for x=1:2] end 1+1 """, """ module Mod2 module Foo # for end 1+1 """, """ module Mod3 abstract foo end """, """ module Mod4 bitstype 8 foo (i for i = 1:10) end """, """ :module Foo 1+1 end """, """ bla.module foo end """, """ begin module Foo 2+2 end 1+1 """ ] @test CodeTools.codemodule(code[1], 2) == "Mod1" @test CodeTools.codemodule(code[1], 4) == "" @test CodeTools.codemodule(code[2], 3) == "Mod2.Foo" @test CodeTools.codemodule(code[2], 5) == "Mod2" @test CodeTools.codemodule(code[3], 2) == "Mod3" @test CodeTools.codemodule(code[3], 3) == "" @test CodeTools.codemodule(code[4], 2) == "Mod4" @test CodeTools.codemodule(code[4], 3) == "Mod4" @test CodeTools.codemodule(code[4], 4) == "" @test CodeTools.codemodule(code[5], 1) == "" @test CodeTools.codemodule(code[5], 2) == "" @test CodeTools.codemodule(code[5], 3) == "" @test CodeTools.codemodule(code[6], 1) == "" @test CodeTools.codemodule(code[6], 2) == "" @test CodeTools.codemodule(code[6], 3) == "" @test CodeTools.codemodule(code[7], 1) == "" @test CodeTools.codemodule(code[7], 3) == "Foo" @test CodeTools.codemodule(code[7], 5) == "" @test CodeTools.filemodule(normpath(joinpath(@__DIR__, "..", "src", "module.jl"))) == "CodeTools" @test CodeTools.includeline(normpath(joinpath(@__DIR__, "..", "src", "CodeTools.jl")), normpath(joinpath(@__DIR__, "..", "src", "utils.jl"))) == 5 end @testset "completions" begin @test CodeTools.prefix("MacroTools.@") == ["MacroTools", "@"] @test length(CodeTools.completions("CodeTools.pre")) > 0 @test "LinearAlgebra" in CodeTools.stdlibs() end <|start_filename|>src/summaries.jl<|end_filename|> import Base.Docs: Binding, @var using Markdown: MD, Code, Paragraph, plain # flat_content(md) = md # flat_content(xs::Vector) = reduce((xs, x) -> vcat(xs,flat_content(x)), [], xs) # flat_content(md::MD) = flat_content(md.content) flatten(md::MD) = MD(flat_content(md)) # Faster version function flat_content!(xs, out = []) for x in xs if isa(x, MD) flat_content!(x.content, out) else push!(out, x) end end return out end flat_content(md::MD) = flat_content!(md.content) function hasdoc(b::Binding) for m in Docs.modules meta = Docs.meta(m) if haskey(meta, b) || haskey(meta, b[]) return true end end false end hasdoc(b) = hasdoc(Docs.aliasof(b, typeof(b))) function trygetdoc(b) docs = try Docs.doc(b) catch "" end end function fullsignature(b::Binding) hasdoc(b) || return docs = trygetdoc(b) isa(docs, MD) || return md = flatten(docs).content first = length(md) > 0 ? md[1] : "" code = isa(first, Code) ? first.code : isa(first, Paragraph) && isa(md[1], Code) ? md[1].code : "" if startswith(code, string(b.var)) split(code, "\n")[1] end end function signature(b::Binding) sig = fullsignature(b) sig == nothing && return replace(sig, r" -> .*$" => "") end function returns(b::Binding) r = r" -> (.*)" sig = fullsignature(b) sig == nothing && return if occursin(r, sig) ret = match(r, sig).captures[1] if length(ret) < 10 ret end end end function description(b::Binding) hasdoc(b) || return docs = trygetdoc(b) isa(docs, MD) || return md = flatten(docs).content length(md) > 0 || return first = md[1] if isa(first, Code) length(md) < 2 && return first = md[2] end if isa(first, Paragraph) desc = plain(first) return length(desc) > 100 ? desc[1:nextind(desc, 0, 99)]*"..." : desc end end <|start_filename|>src/CodeTools.jl<|end_filename|> module CodeTools using Lazy, LNR include("utils.jl") include("eval.jl") include("module.jl") include("summaries.jl") include("completions.jl") include("doc.jl") end # module
UnofficialJuliaMirror/CodeTools.jl-53a63b46-67e4-5edd-8c66-0af0544a99b9
<|start_filename|>calcc/calcc.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package main import ( "flag" "fmt" "os" "os/exec" "path/filepath" "runtime" "strings" "github.com/rthornton128/calc/cgen" ) func cleanup(filename string) { os.Remove(filename + ".c") os.Remove(filename + ".o") } func fatal(args ...interface{}) { fmt.Fprintln(os.Stderr, args...) os.Exit(1) } func make_args(options ...string) string { var args string for i, opt := range options { if len(opt) > 0 { args += opt if i < len(options)-1 { args += " " } } } return args } func printVersion() { fmt.Fprintln(os.Stderr, "Calc Compiler Tool Version 2.1") } func main() { ext := "" if runtime.GOOS == "windows" { ext = ".exe" } flag.Usage = func() { printVersion() fmt.Fprintln(os.Stderr, "\nUsage of:", os.Args[0]) fmt.Fprintln(os.Stderr, os.Args[0], "[flags] <filename>") flag.PrintDefaults() } var ( asm = flag.Bool("s", false, "generate C code but do not compile") cc = flag.String("cc", "gcc", "C compiler to use") cfl = flag.String("cflags", "-c -g -std=gnu99", "C compiler flags") cout = flag.String("cout", "--output=", "C compiler output flag") ld = flag.String("ld", "gcc", "linker") ldf = flag.String("ldflags", "", "linker flags") opt = flag.Bool("o", true, "run optimization pass") ver = flag.Bool("v", false, "Print version number and exit") ) flag.Parse() if *ver { printVersion() os.Exit(1) } var path string switch flag.NArg() { case 0: path, _ = filepath.Abs(".") case 1: path, _ = filepath.Abs(flag.Arg(0)) default: flag.Usage() os.Exit(1) } fi, err := os.Stat(path) if err != nil { fmt.Println(err) os.Exit(1) } if fi.IsDir() { err = comp.CompileDir(path, *opt) path = filepath.Join(path, filepath.Base(path)) } else { err = comp.CompileFile(path, *opt) } path = path[:len(path)-len(filepath.Ext(path))] if err != nil { fmt.Println(err) cleanup(path) os.Exit(1) } if !*asm { /* compile to object code */ var out []byte args := make_args(*cfl, *cout+path+".o", path+".c") out, err := exec.Command(*cc+ext, strings.Split(args, " ")...).CombinedOutput() if err != nil { cleanup(path) fatal(string(out), err) } /* link to executable */ args = make_args(*ldf, *cout+path+ext, path+".o") out, err = exec.Command(*ld+ext, strings.Split(args, " ")...).CombinedOutput() if err != nil { cleanup(path) fatal(string(out), err) } cleanup(path) } } <|start_filename|>scan/scan_test.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package scan_test import ( "strings" "testing" "github.com/rthornton128/calc/scan" "github.com/rthornton128/calc/token" ) func test_handler(t *testing.T, src string, expected []token.Token) { var s scan.Scanner s.Init(token.NewFile("", 1, len(src)), strings.NewReader(src)) lit, tok, pos := s.Scan() for i := 0; tok != token.EOF; i++ { if tok != expected[i] { t.Fatal(pos, "Expected:", expected[i], "Got:", tok, lit) } lit, tok, pos = s.Scan() } } func TestIdentifier(t *testing.T) { src := "a A z23 Zasdf" expected := []token.Token{ token.IDENT, token.IDENT, token.IDENT, token.IDENT, token.EOF, } test_handler(t, src, expected) } func TestNumber(t *testing.T) { src := "9" expected := []token.Token{ token.INTEGER, token.EOF, } test_handler(t, src, expected) } func TestScan(t *testing.T) { src := "(+ 2 (- 4 1) (* 6 5) (% 10 2) (/ 9 3)); comment" expected := []token.Token{ token.LPAREN, token.ADD, token.INTEGER, token.LPAREN, token.SUB, token.INTEGER, token.INTEGER, token.RPAREN, token.LPAREN, token.MUL, token.INTEGER, token.INTEGER, token.RPAREN, token.LPAREN, token.REM, token.INTEGER, token.INTEGER, token.RPAREN, token.LPAREN, token.QUO, token.INTEGER, token.INTEGER, token.RPAREN, token.RPAREN, token.EOF, } test_handler(t, src, expected) } func TestScanAllTokens(t *testing.T) { src := "()+-*/% 1 12\t 12345 123456789 | a as ! != < <=! = == > >= & &&" + "| || : \\ \r ;" expected := []token.Token{ token.LPAREN, token.RPAREN, token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.INTEGER, token.INTEGER, token.INTEGER, token.INTEGER, token.ILLEGAL, token.IDENT, token.IDENT, token.ILLEGAL, token.NEQ, token.LST, token.LTE, token.ILLEGAL, token.ASSIGN, token.EQL, token.GTT, token.GTE, token.ILLEGAL, token.AND, token.ILLEGAL, token.OR, token.COLON, token.ILLEGAL, token.ILLEGAL, token.EOF, } test_handler(t, src, expected) } <|start_filename|>token/token_test.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package token_test import ( "testing" "github.com/rthornton128/calc/token" ) var test_expr = "(+ 2 3)\n(- 5 4)" func TestFilePosition(t *testing.T) { var tests = []struct { col, row int pos token.Pos }{ {1, 1, token.Pos(1)}, {1, 2, token.Pos(8)}, {7, 2, token.Pos(14)}, } f := token.NewFile("", 1, 15) f.AddLine(0) p := f.Position(token.Pos(1)) if p.String() != "1:1" { t.Fatal("Nameless file: Expected: 1:1, Got:", p.String()) } f = token.NewFile("test.calc", 1, 15) f.AddLine(0) p = f.Position(token.Pos(1)) if p.String() != "test.calc:1:1" { t.Fatal("Nameless file: Expected: test.calc:1:1, Got:", p.String()) } f = token.NewFile("test", 1, len(test_expr)) f.AddLine(0) f.AddLine(6) for _, v := range tests { p := f.Position(v.pos) if p.Col != v.col || p.Row != v.row { t.Fatal("For:", v.pos, "Expected:", v.col, "and", v.row, "Got:", p.Col, "and", p.Row) } } } func TestFileSetPosition(t *testing.T) { fs := token.NewFileSet() fs.Add("testA.calc", len(test_expr)) fs.Add("testB.calc", len(test_expr)) } func TestLookup(t *testing.T) { var tests = []struct { str string tok token.Token }{ {"+", token.ADD}, {"%", token.REM}, {"EOF", token.EOF}, {"Integer", token.INTEGER}, {"", token.IDENT}, } for i, v := range tests { if res := token.Lookup(v.str); res != v.tok { t.Fatal(i, "- Expected:", v.tok, "Got:", res) } } } func TestIsLiteral(t *testing.T) { var tests = []struct { tok token.Token exp bool }{ {token.ADD, false}, {token.REM, false}, {token.EOF, false}, {token.IDENT, true}, {token.INTEGER, true}, {token.IDENT, true}, {token.VAR, false}, {token.ASSIGN, false}, } for _, v := range tests { if res := v.tok.IsLiteral(); res != v.exp { t.Fatal(v.tok, "- Expected:", v.exp, "Got:", res) } } } func TestIsOperator(t *testing.T) { var tests = []struct { tok token.Token exp bool }{ {token.ADD, true}, {token.REM, true}, {token.EOF, false}, {token.INTEGER, false}, {token.VAR, false}, {token.ASSIGN, true}, } for _, v := range tests { if res := v.tok.IsOperator(); res != v.exp { t.Fatal(int(v.tok), "- Expected:", v.exp, "Got:", res) } } } func TestIsKeyword(t *testing.T) { var tests = []struct { tok token.Token exp bool }{ {token.ADD, false}, {token.REM, false}, {token.EOF, false}, {token.INTEGER, false}, {token.VAR, true}, {token.ASSIGN, false}, } for _, v := range tests { if res := v.tok.IsKeyword(); res != v.exp { t.Fatal(v.tok, "- Expected:", v.exp, "Got:", res) } } } func TestString(t *testing.T) { var tests = []struct { str string tok token.Token }{ {"+", token.ADD}, {"%", token.REM}, {"EOF", token.EOF}, {"Integer", token.INTEGER}, } for i, v := range tests { if res := v.tok.String(); res != v.str { t.Fatal(i, "- Expected:", v.str, "Got:", res) } } } func TestValid(t *testing.T) { var tests = []struct { tok token.Token exp bool }{ {token.ADD, true}, {token.REM, true}, {token.EOF, true}, {token.INTEGER, true}, {token.Token(-1), false}, {token.Token(999999), false}, } for _, v := range tests { if res := v.tok.Valid(); res != v.exp { t.Fatal(v.tok, "- Expected:", v.exp, "Got:", res) } } } <|start_filename|>ir/object.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/token" ) type Object interface { ID() int Kind() ast.Kind Name() string Package() *Package Pos() token.Pos Scope() *Scope String() string Type() Type } type object struct { id int kind ast.Kind name string pkg *Package pos token.Pos scope *Scope typ Type } func (o object) ID() int { return o.id } func (o object) Kind() ast.Kind { return o.kind } func (o object) Name() string { return o.name } func (o object) Package() *Package { return o.pkg } func (o object) Pos() token.Pos { return o.pos } func (o object) Scope() *Scope { if o.scope == nil { return o.pkg.Scope() } return o.scope } func (o object) Type() Type { return o.typ } func (o object) String() string { if o.id != 0 { return fmt.Sprintf("%s%d", o.name, o.id) } return o.Name() } <|start_filename|>ir/define.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" ) type Define struct { object Body Object } func MakeDefine(pkg *Package, d *ast.DefineStmt) *Define { body := MakeExpr(pkg, d.Body) t := body.Type() if d.Type != nil { t = typeFromString(d.Type.Name) } return &Define{ object: object{ kind: body.Kind(), pkg: pkg, name: d.Name.Name, pos: d.Pos(), typ: t, }, Body: body, } } func (d *Define) String() string { return fmt.Sprintf("define %s[%s] {%s}", d.Name(), d.Type(), d.Body) } <|start_filename|>ir/fold_test.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir_test import ( "fmt" "testing" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/ir" "github.com/rthornton128/calc/parse" "github.com/rthornton128/calc/token" ) type FoldTest struct { src, expect string } func TestAssignmentFolding(t *testing.T) { test := FoldTest{src: "(= a (* 1 1))", expect: "1"} name := "assign" expr, _ := parse.ParseExpression(name, test.src) o := ir.FoldConstants(ir.MakeExpr(ir.MakePackage(&ast.Package{}, name), expr)) validate_constant(t, name, o.(*ir.Assignment).Rhs, test) } func TestBinaryFolding(t *testing.T) { tests := []FoldTest{ {src: "(+ 21 21)", expect: "42"}, {src: "(* 21 2)", expect: "42"}, {src: "(/ 126 3)", expect: "42"}, {src: "(- 0 42)", expect: "-42"}, {src: "(% 5 2)", expect: "1"}, {src: "(+ 1 2 3 4)", expect: "10"}, {src: "(* 1 2 3 4)", expect: "24"}, {src: "(/ 18 3 3)", expect: "2"}, {src: "(- 15 5 10)", expect: "0"}, {src: "(% 15 10 2)", expect: "1"}, {src: "(== 42 42)", expect: "true"}, {src: "(!= 24 24)", expect: "false"}, {src: "(< 126 3)", expect: "false"}, {src: "(<= 0 42)", expect: "true"}, {src: "(> 5 2)", expect: "true"}, {src: "(>= 3 4)", expect: "false"}, {src: "(== true true)", expect: "true"}, {src: "(!= true false)", expect: "true"}, } for i, test := range tests { test_folding(t, fmt.Sprintf("binary%d", i), test) } } func TestCallFolding(t *testing.T) { src := "(fn (== 3 2) (+ 2 2))" name := "call" expr, _ := parse.ParseExpression(name, src) o := ir.FoldConstants(ir.MakeExpr(ir.MakePackage(&ast.Package{}, name), expr)) validate_constant(t, name, o.(*ir.Call).Args[0], FoldTest{src, "false"}) validate_constant(t, name, o.(*ir.Call).Args[1], FoldTest{src, "4"}) } func TestIfFolding(t *testing.T) { src := "(if (== false (!= 3 3)):int (/ 9 3) (* 1 2 3))" name := "if" expr, _ := parse.ParseExpression(name, src) o := ir.FoldConstants(ir.MakeExpr(ir.MakePackage(&ast.Package{}, name), expr)) validate_constant(t, name, o.(*ir.If).Cond, FoldTest{src, "true"}) validate_constant(t, name, o.(*ir.If).Then, FoldTest{src, "3"}) validate_constant(t, name, o.(*ir.If).Else, FoldTest{src, "6"}) } func TestPackageFolding(t *testing.T) { fs := token.NewFileSet() f1, _ := parse.ParseFile(fs, "package", "(define f1 (func:int (+ 1 2)))") f2, _ := parse.ParseFile(fs, "package", "(define f2 (func:int (* 8 2)))") pkg := &ast.Package{Files: []*ast.File{f1, f2}} o := ir.FoldConstants(ir.MakePackage(pkg, "package")) o1 := o.(*ir.Package).Scope().Lookup("f1") o2 := o.(*ir.Package).Scope().Lookup("f2") validate_constant(t, "package", o1.(*ir.Define).Body.(*ir.Function).Body[0], FoldTest{"", "3"}) validate_constant(t, "package", o2.(*ir.Define).Body.(*ir.Function).Body[0], FoldTest{"", "16"}) } func TestUnaryFolding(t *testing.T) { tests := []FoldTest{ {src: "-42)", expect: "-42"}, {src: "+42", expect: "42"}, {src: "+(- 2 4)", expect: "2"}, {src: "-(+ 2 4)", expect: "-6"}, } for i, test := range tests { test_folding(t, fmt.Sprintf("unary%d", i), test) } } func TestVarFolding(t *testing.T) { test := FoldTest{src: "(var (a:int):int (= a (/ 24 3)))", expect: "8"} name := "var" expr, _ := parse.ParseExpression(name, test.src) o := ir.FoldConstants(ir.MakeExpr(ir.MakePackage(&ast.Package{}, name), expr)) o = o.(*ir.Variable).Body[0].(*ir.Assignment).Rhs validate_constant(t, name, o, test) } func test_folding(t *testing.T, name string, test FoldTest) { expr, _ := parse.ParseExpression(name, test.src) o := ir.FoldConstants(ir.MakeExpr(ir.MakePackage(&ast.Package{}, name), expr)) validate_constant(t, name, o, test) } func validate_constant(t *testing.T, name string, o ir.Object, test FoldTest) { if c, ok := o.(*ir.Constant); !ok { t.Fatalf("%s: expected constant with value '%s' but got: %s", name, test.expect, o) } else { if c.String() != test.expect { t.Fatalf("%s: expected constant with value '%s' but got value: %s", name, test.expect, c.String()) } } } <|start_filename|>token/pos.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package token import "fmt" type Pos uint var NoPos = Pos(0) // Valid returns true if p does not equal NoPos func (p Pos) Valid() bool { return p != NoPos } type Position struct { Filename string Col, Row int } func (p Position) String() string { if p.Filename == "" { return fmt.Sprintf("%d:%d", p.Row, p.Col) } return fmt.Sprintf("%s:%d:%d", p.Filename, p.Row, p.Col) } <|start_filename|>cgen/cgen_test.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package comp_test import ( "io/ioutil" "os" "os/exec" "runtime" "strings" "testing" "github.com/rthornton128/calc/cgen" ) var ext string func init() { if runtime.GOOS == "windows" { ext = ".exe" } } func TestSimpleExpression(t *testing.T) { test_handler(t, "(define main (func:int 42))", "42") } func TestBinary(t *testing.T) { test_handler(t, "(define main (func:int (+ 5 3)))", "8") test_handler(t, ";comment 1\n"+ "(define main (func:int (* 5 3))); comment 2", "15") test_handler(t, "(define main (func:int"+ "(- (* 9 (+ 2 3)) (+ (/ 20 (% 15 10)) 1))))", "40") } func TestFunc(t *testing.T) { test_handler(t, "(define fn (func (a:int b:int):int (+ a b)))\n"+ "(define main (func:int (fn 1 2)))", "3") } func TestIfThenElse(t *testing.T) { test_handler(t, "(define main (func:int (if true :int 99)))", "99") test_handler(t, "(define main (func:int (if false :int 2 3)))", "3") test_handler(t, "(define main (func:int (if (< 2 3):int 7 3)))", "7") test_handler(t, "(define main (func:int"+ "(var (a:int):int (if (< a 3):int 1 3))))", "1") } func TestVarAndAssign(t *testing.T) { test_handler(t, "(define main (func:int (var (a:int):int (= a 42) a)))", "42") } func TestUnary(t *testing.T) { test_handler(t, "(define main (func:int -24))", "-24") test_handler(t, "(define main (func:int\n"+ "(var (z:int):int (= z 12) -z)))", "-12") test_handler(t, "(define fn (func (num:int):int -num))\n"+ "(define main (func:int (fn -42)))", "42") } func test_handler(t *testing.T, src, expected string) { defer tearDown() err := ioutil.WriteFile("test.calc", []byte(src), os.ModePerm) if err != nil { t.Fatal(err) } err = comp.CompileFile("test.calc", false) if err != nil { t.Log(src) t.Fatal(err) } os.Remove("test.calc") out, err := exec.Command("gcc"+ext, "-Wall", "-Wextra", "-std=c99", "--output=test"+ext, "test.c").CombinedOutput() if err != nil { t.Log(string(out)) t.Fatal(err) } var output []byte switch runtime.GOOS { case "windows": output, err = exec.Command("test" + ext).Output() default: output, err = exec.Command("./test").Output() } output = []byte(strings.TrimSpace(string(output))) if string(output) != expected { //t.Log("len output:", len(output)) //t.Log("len expected:", len(expected)) t.Fatal("For " + src + " expected " + expected + " got " + string(output)) } } func tearDown() { os.Remove("test.c") os.Remove("test" + ext) } <|start_filename|>ir/if.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" ) type If struct { object Cond Object Then Object Else Object } func makeIf(pkg *Package, ie *ast.IfExpr) *If { i := &If{ object: object{ id: pkg.getID(), name: "if-then", pkg: pkg, pos: ie.Pos(), scope: pkg.scope, typ: typeFromString(ie.Type.Name), }, Cond: MakeExpr(pkg, ie.Cond), Then: MakeExpr(pkg, ie.Then), } if ie.Else != nil { i.object.name += "-else" i.Else = MakeExpr(pkg, ie.Else) } return i } func (i *If) String() string { return fmt.Sprintf("{if[%s] %s then %s else %s}", i.typ, i.Cond, i.Then, i.Else) } <|start_filename|>ir/ir_test.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir_test import ( "fmt" "testing" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/ir" "github.com/rthornton128/calc/parse" "github.com/rthornton128/calc/token" ) type Test struct { src string pass bool } func TestAssignment(t *testing.T) { tests := []Test{ {src: "(= a 3)", pass: false}, {src: "(func(a:int):int (= a 0))", pass: true}, {src: "(var (a:int):int (= a true) 0)", pass: false}, } for i, test := range tests { test_expression(t, fmt.Sprintf("assign%d", i), test) } } func TestBinary(t *testing.T) { tests := []Test{ {src: "(+ 2 3)", pass: true}, {src: "(* 2 3 4 5 6)", pass: true}, {src: "(/ (* 2 3) (% 4 5) (- 8 6))", pass: true}, {src: "(func:bool (!= 2 3))", pass: true}, {src: "(func:int (+ main 1))", pass: false}, {src: "(func (a:int b:int):bool (< a b))", pass: true}, {src: "(func (a:bool):bool (== a true))", pass: true}, {src: "(func (a:bool):int (== a true))", pass: false}, {src: "(var (main:bool):int (+ main 1))", pass: false}, } for i, test := range tests { test_expression(t, fmt.Sprintf("example%d", i), test) } } func TestCall(t *testing.T) { tests := []Test{ {src: "(fn)", pass: false}, //{src: "(decl fn (a int) int (a))", pass: false}, //{src: "(decl fn int ((var a int) (a)))", pass: false}, } for i, test := range tests { test_expression(t, fmt.Sprintf("call%d", i), test) } } func TestConstant(t *testing.T) { tests := []Test{ {src: "42", pass: true}, {src: "true", pass: true}, } for i, test := range tests { test_expression(t, fmt.Sprintf("constant%d", i), test) } } func TestFile(t *testing.T) { tests := []Test{ {src: "(define add:int (func (a:int b:int):int (+ a b)))" + "(define main:int (func:int (add 2 3)))", pass: true}, {src: "(define equal (func (a:int b:int):bool (== a b)))" + "(define main (func:int (if (equal (+ 2 3) (*4 2)):int 0 1)))", pass: true}, {src: "(define equal (func (a:int b:int):bool (== a b)))" + "(define main (func:int (equal 2 3)))", pass: false}, {src: "(define fn (func:int 0))(define main (func:int fn))", pass: false}, {src: "(define fn (func (a:int):int 0))" + "(define main (func:int (fn 1 2)))", pass: false}, {src: "(define fn (func (a:int b:int):int 0))" + "(define main (func:int (fn 1)))", pass: false}, {src: "(define fn (func:int 0))" + "(define main (func:int (= fn 3) 0))", pass: false}, {src: "(define fn (func (i:int b:bool):int 0))" + "(define main:int (func:int (fn 42 true)))", pass: true}, {src: "(define fn (func (i:int b:bool):int 0))" + "(define main (func:int (fn 4 2)))", pass: false}, } for i, test := range tests { test_file(t, fmt.Sprintf("file%d", i), test) } } func TestFor(t *testing.T) { tests := []Test{ {src: "(for true :int 0)", pass: true}, {src: "(for (!= 1 2) :bool false)", pass: true}, } for i, test := range tests { test_expression(t, fmt.Sprintf("for%d", i), test) } } func TestIf(t *testing.T) { tests := []Test{ {src: "(if (== 1 1):int 1 0)", pass: true}, {src: "(if (!= 1 1):int 1 true)", pass: false}, {src: "(if (< 1 1):int false 1)", pass: false}, {src: "(if 1:int 0 1)", pass: false}, {src: "(func (a:int b:int):int (if (<= a b):int 0 1))", pass: true}, {src: "(func (a:int b:int):int (if (> a b):int 0 1))", pass: true}, {src: "(func (a:int b:int):int (if (>= a b):int 0 1))", pass: true}, {src: "(func (a:bool):int (if (== a false):int 0 1))", pass: true}, {src: "(func (a:int):int (if (== a false):int 0 1))", pass: false}, } for i, test := range tests { test_expression(t, fmt.Sprintf("if%d", i), test) } } func TestUnary(t *testing.T) { tests := []Test{ {src: "-24", pass: true}, {src: "+(- 3 5)", pass: true}, } for i, test := range tests { test_expression(t, fmt.Sprintf("unary%d", i), test) } } func TestVar(t *testing.T) { tests := []Test{ {src: "(var (a:int):int a)", pass: true}, {src: "(var (a:bool):int a)", pass: false}, {src: "(var:int (= a 42) a)", pass: false}, {src: "(var (a:bool):bool (= a true) a)", pass: true}, {src: "(var (a:bool):int (= a true) a)", pass: false}, {src: "(var (a:bool):int (= a true) a)", pass: false}, {src: "(var (a:int):bool (= a 24))", pass: false}, {src: "(var (a:int):int (= a 42) a)", pass: true}, } for i, test := range tests { test_expression(t, fmt.Sprintf("var%d", i), test) } } func test_expression(t *testing.T, name string, test Test) { expr, err := parse.ParseExpression(name, test.src) if err != nil { t.Fatal(err) } test_handler(t, test, name, expr) } func test_file(t *testing.T, name string, test Test) { f, err := parse.ParseFile(token.NewFileSet(), name, test.src) if err != nil { t.Fatal(err) } test_handler(t, test, name, &ast.Package{Files: []*ast.File{f}}) } func test_handler(t *testing.T, test Test, name string, n ast.Node) { var o ir.Object pkg := ir.MakePackage(&ast.Package{}, name) switch x := n.(type) { case *ast.DefineStmt: o = ir.MakeDefine(pkg, x) case *ast.Package: o = ir.MakePackage(x, name) case ast.Expr: o = ir.MakeExpr(pkg, x) t.Log("makexpr, test:", test.src) } t.Log(o) fset := token.NewFileSet() fset.Add(name, len(test.src)) if err := ir.TypeCheck(o, fset); (err == nil) != test.pass { t.Logf("expected %v got %v", test.pass, err == nil) if err != nil { t.Log(err) } t.Fail() } /* ir.Tag(o)*/ } <|start_filename|>ir/scope.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir type Scope struct { m map[string]Object parent *Scope } func NewScope(p *Scope) *Scope { return &Scope{ m: make(map[string]Object), parent: p, } } func (s *Scope) Insert(o Object) Object { if prev, ok := s.m[o.Name()]; ok { return prev } s.m[o.Name()] = o return nil } func (s *Scope) Lookup(name string) Object { o, ok := s.m[name] if s.parent == nil || ok { return o } return s.parent.Lookup(name) } func (s *Scope) Names() []string { names := make([]string, 0) for k := range s.m { names = append(names, k) } return names } func (s *Scope) String() string { var out string for _, v := range s.m { out += v.String() } return out } <|start_filename|>ir/for.go<|end_filename|> package ir import ( "fmt" "strings" "github.com/rthornton128/calc/ast" ) type For struct { object Cond Object Body []Object } func makeFor(pkg *Package, f *ast.ForExpr) *For { body := make([]Object, len(f.Body)) for i, e := range f.Body { body[i] = MakeExpr(pkg, e) } return &For{ object: object{id: pkg.getID(), pos: f.Pos(), scope: pkg.scope, typ: typeFromString(f.Type.Name)}, Cond: MakeExpr(pkg, f.Cond), Body: body, } } func (f *For) String() string { body := make([]string, len(f.Body)) for i, o := range f.Body { body[i] = o.String() } return fmt.Sprintf("{for[%s] %s {%s}}", f.typ, f.Cond, strings.Join(body, ",")) } <|start_filename|>ast/walk.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ast type Visitor interface { Visit(node Node) bool } func Walk(node Node, v Visitor) { if !v.Visit(node) { return } switch n := node.(type) { case *AssignExpr: Walk(n.Value, v) case *BasicLit: /* do nothing */ case *BinaryExpr: for _, x := range n.List { Walk(x, v) } case *CallExpr: for _, arg := range n.Args { Walk(arg, v) } case *DefineStmt: Walk(n.Body, v) case *File: for _, def := range n.Defs { Walk(def, v) } case *ForExpr: Walk(n.Cond, v) for _, e := range n.Body { Walk(e, v) } case *FuncExpr: for _, e := range n.Body { Walk(e, v) } case *IfExpr: Walk(n.Cond, v) Walk(n.Then, v) if n.Else != nil { Walk(n.Else, v) } case *Package: for _, file := range n.Files { Walk(file, v) } case *UnaryExpr: Walk(n.Value, v) case *VarExpr: for _, e := range n.Body { Walk(e, v) } } } <|start_filename|>ast/ast.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ast import "github.com/rthornton128/calc/token" type Node interface { Pos() token.Pos } type Expr interface { Node exprNode() } type AssignExpr struct { Equal token.Pos Name *Ident Value Expr } type BasicLit struct { LitPos token.Pos Kind token.Token Lit string } type BinaryExpr struct { Op token.Token OpPos token.Pos ID int List []Expr } type CallExpr struct { Name *Ident Args []Expr } type DefineStmt struct { Define token.Pos Name *Ident Type *Ident Kind Kind Body Expr } type File struct { Defs []*DefineStmt } type ForExpr struct { For token.Pos Type *Ident Cond Expr Body []Expr } type FuncExpr struct { Func token.Pos Type *Ident Params []*Param Body []Expr } type Ident struct { NamePos token.Pos Name string Type *Ident } type IfExpr struct { If token.Pos Type *Ident Cond Expr Then Expr Else Expr } type Object struct { NamePos token.Pos Name string Kind Kind } type Package struct { Files []*File } type Param struct { Name *Ident Type *Ident } type Scope struct { Parent *Scope Table map[string]*Object } type UnaryExpr struct { OpPos token.Pos Op string Value Expr } type VarExpr struct { Var token.Pos Type *Ident Params []*Param Body []Expr } func (a *AssignExpr) Pos() token.Pos { return a.Equal } func (b *BasicLit) Pos() token.Pos { return b.LitPos } func (b *BinaryExpr) Pos() token.Pos { return b.OpPos } func (c *CallExpr) Pos() token.Pos { return c.Name.Pos() } func (d *DefineStmt) Pos() token.Pos { return d.Define } func (f *File) Pos() token.Pos { return token.NoPos } func (f *ForExpr) Pos() token.Pos { return f.For } func (f *FuncExpr) Pos() token.Pos { return f.Func } func (i *Ident) Pos() token.Pos { return i.NamePos } func (i *IfExpr) Pos() token.Pos { return i.If } func (o *Object) Pos() token.Pos { return o.NamePos } func (p *Package) Pos() token.Pos { return token.NoPos } func (p *Param) Pos() token.Pos { return p.Name.Pos() } func (u *UnaryExpr) Pos() token.Pos { return u.OpPos } func (v *VarExpr) Pos() token.Pos { return v.Var } func (a *AssignExpr) exprNode() {} func (b *BasicLit) exprNode() {} func (b *BinaryExpr) exprNode() {} func (c *CallExpr) exprNode() {} func (f *ForExpr) exprNode() {} func (f *FuncExpr) exprNode() {} func (i *IfExpr) exprNode() {} func (i *Ident) exprNode() {} func (u *UnaryExpr) exprNode() {} func (v *VarExpr) exprNode() {} func NewScope(parent *Scope) *Scope { return &Scope{Parent: parent, Table: make(map[string]*Object)} } func (s *Scope) Insert(ob *Object) *Object { if old, ok := s.Table[ob.Name]; ok { return old } s.Table[ob.Name] = ob return nil } func (s *Scope) Lookup(ident string) *Object { ob, ok := s.Table[ident] if ok || s.Parent == nil { return ob } return s.Parent.Lookup(ident) } <|start_filename|>ir/expr.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import "github.com/rthornton128/calc/ast" func MakeExpr(pkg *Package, e ast.Expr) Object { switch t := e.(type) { case *ast.AssignExpr: return makeAssignment(pkg, t) case *ast.BasicLit: return makeConstant(t) case *ast.BinaryExpr: return makeBinary(pkg, t) case *ast.CallExpr: return makeCall(pkg, t) case *ast.ForExpr: return makeFor(pkg, t) case *ast.FuncExpr: return makeFunc(pkg, t) case *ast.Ident: return makeVar(pkg, t) case *ast.IfExpr: return makeIf(pkg, t) case *ast.UnaryExpr: return makeUnary(pkg, t) case *ast.VarExpr: return makeVariable(pkg, t) default: panic("unreachable") } } func MakeExprList(pkg *Package, el []ast.Expr) []Object { ol := make([]Object, 0) for _, e := range el { ol = append(ol, MakeExpr(pkg, e)) } return ol } <|start_filename|>ir/typecheck.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/token" ) type typeChecker struct { token.ErrorList fset *token.FileSet } func TypeCheck(o Object, fs *token.FileSet) error { t := &typeChecker{ErrorList: make(token.ErrorList, 0), fset: fs} if pkg, ok := o.(*Package); ok { for _, decl := range pkg.Scope().m { t.check(decl) } } else { t.check(o) } if t.ErrorList.Count() != 0 { return t.ErrorList } return nil } func (tc *typeChecker) check(o Object) { switch t := o.(type) { case *Assignment: o := t.Scope().Lookup(t.Lhs) if o == nil { tc.error(t.Pos(), "undeclared variable '%s'", t.Lhs) return } if o.Kind() != ast.VarDecl { tc.error(t.Pos(), "may only assign to variables but '%s' is %s", o.Name(), o.Kind()) return } tc.check(t.Rhs) if o.Type() != t.Rhs.Type() { tc.error(t.Pos(), "variable '%s' is of type '%s' but assignment of "+ "type '%s'", t.Name(), t.Type(), t.Rhs.Type()) return } t.object.typ = o.Type() case *Binary: tc.check(t.Lhs) tc.check(t.Rhs) typ := Int if (t.Op == token.EQL || t.Op == token.NEQ) && t.Lhs.Type() == Bool { typ = Bool } if t.Lhs.Type() != typ { tc.error(t.Pos(), "binary expected type '%s' but lhs is type '%s'", typ, t.Lhs.Type()) return } if t.Rhs.Type() != typ { tc.error(t.Pos(), "binary expected type '%s' but rhs is type '%s'", typ, t.Rhs.Type()) return } case *Call: o := t.Scope().Lookup(t.Name()) if o == nil { tc.error(t.Pos(), "calling undeclared function '%s'", t.Name()) return } if o.Kind() != ast.FuncDecl { tc.error(t.Pos(), "call expects function got '%s'", o.Kind()) return } f := o.(*Define).Body.(*Function) if len(t.Args) != len(f.Params) { tc.error(t.Pos(), "function '%s' expects '%d' arguments but received %d", t.Name(), len(f.Params), len(t.Args)) return } for i, a := range t.Args { tc.check(a) p := f.Scope().Lookup(f.Params[i].Name()) if a.Type() != p.Type() { tc.error(t.Pos(), "parameter %d of function '%s' expects type '%s' "+ "but argument %d is of type '%s'", i, t.Name(), p.Type(), i, a.Type()) } } t.object.typ = f.Type() case *Define: tc.check(t.Body) case *For: tc.check(t.Cond) if t.Cond.Type() != Bool { tc.error(t.Pos(), "conditional must be type 'bool', got '%s'", t.Cond.Type()) return } tc.checkBody(t, t.Body) case *Function: tc.checkBody(t, t.Body) case *If: tc.check(t.Cond) if t.Cond.Type() != Bool { tc.error(t.Pos(), "conditional must be type 'bool', got '%s'", t.Cond.Type()) return } tc.check(t.Then) if t.Type() != t.Then.Type() { tc.error(t.Pos(), "if expects type '%s' but then clause is type '%s'", t.Type(), t.Then.Type()) return } if t.Else != nil { tc.check(t.Else) if t.Type() != t.Else.Type() { tc.error(t.Pos(), "if expects type '%s' but else clause is type '%s'", t.Type(), t.Else.Type()) return } } case *Var: o := t.Scope().Lookup(t.Name()) if o == nil { tc.error(t.Pos(), "undeclared variable '%s'", t.Name()) return } if o.Kind() == ast.FuncDecl { tc.error(t.Pos(), "function '%s' used as variable; must be used "+ "in call form (surrounded in parentheses)", t.Name()) return } t.object.typ = o.Type() case *Variable: tc.checkBody(t, t.Body) } } func (tc *typeChecker) checkBody(o Object, body []Object) { for _, e := range body { tc.check(e) } tail := body[len(body)-1] if o.Type() != tail.Type() { tc.error(o.Pos(), "last expression of %s is of type '%s' but expects "+ "type '%s'", o.Name(), tail.Type(), o.Type()) } } func (t *typeChecker) error(p token.Pos, format string, args ...interface{}) { t.Add(t.fset.Position(p), fmt.Sprintf(format, args...)) } <|start_filename|>ir/func.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "strings" "github.com/rthornton128/calc/ast" ) type Function struct { object Params []*Param Body []Object } func makeFunc(pkg *Package, f *ast.FuncExpr) *Function { pkg.newScope() defer pkg.closeScope() fn := &Function{ object: object{ id: pkg.getID(), kind: ast.FuncDecl, pkg: pkg, pos: f.Pos(), scope: pkg.scope, typ: typeFromString(f.Type.Name), // TODO typ: SignatureType{}, }, Params: makeParamList(pkg, f.Params), Body: MakeExprList(pkg, f.Body), } pkg.InsertTop(fn) return fn } func (f *Function) String() string { params := make([]string, len(f.Params)) for i, p := range f.Params { params[i] = f.Scope().Lookup(p.Name()).String() } exprs := make([]string, len(f.Body)) for i, s := range f.Body { exprs[i] = s.String() } return fmt.Sprintf("func:%s (%s) {%s}", f.typ, strings.Join(params, ","), strings.Join(exprs, ",")) } type Param struct { object } func makeParam(pkg *Package, p *ast.Param) *Param { return &Param{object{ id: pkg.getID(), kind: ast.VarDecl, name: p.Name.Name, pos: p.Pos(), typ: typeFromString(p.Type.Name), }} } func (p *Param) String() string { return fmt.Sprintf("%s[%s]", p.name, p.typ) } func makeParamList(pkg *Package, pl []*ast.Param) []*Param { params := make([]*Param, len(pl)) for i, p := range pl { params[i] = makeParam(pkg, p) pkg.Insert(params[i]) } return params } <|start_filename|>ast/kind.go<|end_filename|> package ast type Kind int const ( None Kind = iota + 1 FuncDecl VarDecl ) func (k Kind) String() string { switch k { case FuncDecl: return "function" case VarDecl: return "variable" default: return "" } } <|start_filename|>ir/fold.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import "github.com/rthornton128/calc/token" func FoldConstants(o Object) Object { if pkg, ok := o.(*Package); ok { for k, v := range pkg.scope.m { pkg.scope.m[k] = fold(v) } return pkg } return fold(o) } func fold(o Object) Object { switch t := o.(type) { case *Assignment: t.Rhs = fold(t.Rhs) case *Binary: t.Lhs = fold(t.Lhs) t.Rhs = fold(t.Rhs) return foldBinary(t) case *Call: for i, e := range t.Args { t.Args[i] = fold(e) } case *Define: t.Body = fold(t.Body) case *For: t.Cond = fold(t.Cond) for i, e := range t.Body { t.Body[i] = fold(e) } case *Function: for i, e := range t.Body { t.Body[i] = fold(e) } case *If: t.Cond = fold(t.Cond) t.Then = fold(t.Then) if t.Else != nil { t.Else = fold(t.Else) } case *Unary: t.Rhs = fold(t.Rhs) return foldUnary(t) case *Variable: for i, e := range t.Body { t.Body[i] = fold(e) } } return o } func foldBinary(b *Binary) Object { lhs, lhsOk := b.Lhs.(*Constant) rhs, rhsOk := b.Rhs.(*Constant) if lhsOk && rhsOk { switch b.Type() { case Int: l, r := int64(lhs.value.(intValue)), int64(rhs.value.(intValue)) switch b.Op { case token.ADD: lhs.value = intValue(l + r) case token.MUL: lhs.value = intValue(l * r) case token.QUO: // TODO div by zero lhs.value = intValue(l / r) case token.REM: lhs.value = intValue(l % r) case token.SUB: lhs.value = intValue(l - r) } return lhs case Bool: switch lhs.Type() { case Bool: l, r := bool(lhs.value.(boolValue)), bool(rhs.value.(boolValue)) switch b.Op { case token.EQL: lhs.value = boolValue(l == r) case token.NEQ: lhs.value = boolValue(l != r) } case Int: l, r := int64(lhs.value.(intValue)), int64(rhs.value.(intValue)) switch b.Op { case token.EQL: lhs.value = boolValue(l == r) case token.NEQ: lhs.value = boolValue(l != r) case token.GTT: lhs.value = boolValue(l > r) case token.GTE: lhs.value = boolValue(l >= r) case token.LST: lhs.value = boolValue(l < r) case token.LTE: lhs.value = boolValue(l <= r) } } return lhs } } return b } func foldUnary(u *Unary) Object { if c, ok := u.Rhs.(*Constant); ok { switch u.Op { case "+": val := intValue(+int64(c.value.(intValue))) if val < 0 { c.value = val * -1 } case "-": c.value = intValue(-int64(c.value.(intValue))) } return c } return u } <|start_filename|>token/error.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package token import ( "fmt" ) // Error represents an error in the source code. It consists of a position // within the source files and message text describing the error type Error struct { pos Position msg string } // Error generates an error string to satisfy the error interface func (e Error) Error() string { return fmt.Sprint(e.pos, " ", e.msg) } // ErrorHandler type ErrorHandler func(Pos, ...interface{}) // ErrorList is a slice of Error pointers type ErrorList []*Error // Count returns the number of errors within the list func (el ErrorList) Count() int { return len(el) } // Add a new error the list at the given position p. func (el *ErrorList) Add(p Position, args ...interface{}) { *el = append(*el, &Error{pos: p, msg: fmt.Sprint(args...)}) } func (el *ErrorList) cleanup() { var last Position i := 0 for _, v := range *el { if v.pos != last { last = v.pos (*el)[i] = v i++ } } (*el) = (*el)[:i] } // Error returns a string containing all the errors in the error list func (el ErrorList) Error() string { var msg string el.cleanup() for i, err := range el { if i >= 10 { msg += fmt.Sprintln("More than 10 errors,", len(el)-10, "more not shown") break } msg += fmt.Sprintln(err) } return msg } // Print outputs a message containing all the errors in the list func (el ErrorList) Print() { for _, err := range el { fmt.Println(err) } } <|start_filename|>token/fileset.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package token // FileSet holds all the files for the source code type FileSet struct { base int files []*File } // NewFileSet creates a new FileSet object func NewFileSet() *FileSet { return &FileSet{base: 1} } // Add appends a new file to the fileset func (fs *FileSet) Add(name string, sz int) *File { f := NewFile(name, fs.base, sz) fs.files = append(fs.files, f) fs.base += sz return f } // Position returns the row and column position of the given Pos p func (fs *FileSet) Position(p Pos) Position { var pos Position if !p.Valid() { panic("invalid position") } for _, f := range fs.files { if p >= Pos(f.Base()) && p < Pos(f.Base()+f.Size()) { pos = f.Position(p) } } return pos } <|start_filename|>scan/scan.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause // Package scan is the Calc source code scanner package scan import ( "bufio" "io" "unicode" "github.com/rthornton128/calc/token" ) // Scanner... type Scanner struct { ch rune offset int roffset int src *bufio.Reader file *token.File } // Init initializes Scanner and makes the source code ready to Scan func (s *Scanner) Init(file *token.File, src io.Reader) { s.file = file s.offset, s.roffset = 0, 0 s.src = bufio.NewReader(src) s.file.AddLine(s.offset) // TODO no sir, don't like it s.next() } func (s *Scanner) Scan() (lit string, tok token.Token, pos token.Pos) { s.skipWhitespace() if unicode.IsLetter(s.ch) { return s.scanIdentifier() } if unicode.IsDigit(s.ch) { return s.scanNumber() } ch := s.ch lit, pos = string(s.ch), s.file.Pos(s.offset) s.next() switch ch { case 0: tok = token.EOF case '(': tok = token.LPAREN case ')': tok = token.RPAREN case ':': tok = token.COLON case '+': tok = token.ADD case '-': tok = token.SUB case '*': tok = token.MUL case '/': tok = token.QUO case '%': tok = token.REM case '<': tok = s.selectToken('=', token.LTE, token.LST) case '>': tok = s.selectToken('=', token.GTE, token.GTT) case '=': tok = s.selectToken('=', token.EQL, token.ASSIGN) case '!': tok = s.selectToken('=', token.NEQ, token.ILLEGAL) case '&': tok = s.selectToken('&', token.AND, token.ILLEGAL) case '|': tok = s.selectToken('|', token.OR, token.ILLEGAL) case ';': s.skipComment() s.next() return s.Scan() default: tok = token.ILLEGAL } return } func (s *Scanner) next() { r, w, err := s.src.ReadRune() s.offset = s.roffset s.roffset += w if r == '\n' { s.file.AddLine(s.offset) } s.ch = r if err != nil { s.ch = 0 } } func (s *Scanner) scanIdentifier() (string, token.Token, token.Pos) { start := s.offset var str string for unicode.IsLetter(s.ch) || unicode.IsDigit(s.ch) { str += string(s.ch) s.next() } return str, token.Lookup(str), s.file.Pos(start) } func (s *Scanner) scanNumber() (string, token.Token, token.Pos) { start := s.offset var str string for unicode.IsDigit(s.ch) { str += string(s.ch) s.next() } return str, token.INTEGER, s.file.Pos(start) } func (s *Scanner) selectToken(r rune, a, b token.Token) token.Token { if s.ch == r { s.next() return a } return b } func (s *Scanner) skipComment() { for s.ch != '\n' && s.ch != 0 { s.next() } } func (s *Scanner) skipWhitespace() { for unicode.IsSpace(s.ch) { s.next() } } <|start_filename|>parse/parse_test.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package parse_test import ( "io/ioutil" "os" "path/filepath" "strings" "testing" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/parse" "github.com/rthornton128/calc/token" ) type Test struct { name string src string types []Type pass bool } type Type int const ( ASSIGN Type = iota BASIC BINARY CALL DEFINE FILE FOR FUNC IDENT IF UNARY UNKNOWN VAR ) var typeStrings = []string{ ASSIGN: "assignexpr", BASIC: "basiclit", BINARY: "binaryexpr", CALL: "callexpr", DEFINE: "definestmt", FILE: "file", FOR: "for", FUNC: "funcexpr", IDENT: "ident", IF: "if", UNARY: "unaryexpr", UNKNOWN: "unknown", VAR: "var", } func (t Type) String() string { return typeStrings[int(t)] } type Tester struct { i int t *testing.T types []Type } func (t *Tester) Visit(n ast.Node) bool { var typ Type switch n.(type) { case *ast.AssignExpr: typ = ASSIGN case *ast.BasicLit: typ = BASIC case *ast.BinaryExpr: typ = BINARY case *ast.CallExpr: typ = CALL case *ast.DefineStmt: typ = DEFINE case *ast.File: typ = FILE case *ast.ForExpr: typ = FOR case *ast.FuncExpr: typ = FUNC case *ast.Ident: typ = IDENT case *ast.IfExpr: typ = IF case *ast.UnaryExpr: typ = UNARY case *ast.VarExpr: typ = VAR } if t.i >= len(t.types) { t.t.Logf("exceeded expected number of types (%d)", len(t.types)) t.t.Fail() return false } if t.types[t.i] != typ { t.t.Log("Walk index:", t.i, "Expected:", t.types[t.i], "Got:", typ) t.t.Fail() } t.i++ return true } func handleTests(t *testing.T, tests []Test) { for _, test := range tests { e, err := parse.ParseExpression(test.name, test.src) checkTest(t, test, e, err) } } func handleFileTests(t *testing.T, tests []Test) { for _, test := range tests { f, err := parse.ParseFile(token.NewFileSet(), test.name, test.src) checkTest(t, test, f, err) } } func checkTest(t *testing.T, test Test, n ast.Node, err error) { if err != nil { t.Logf("error: %s", err) } if n == nil && len(test.types) != 0 { t.Logf("%s: expr is nil, expected %d types", test.name, len(test.types)) t.Fail() } if test.pass { ast.Walk(n, &Tester{types: test.types, t: t}) } if t.Failed() { t.Logf("%s: %#v", test.name, n) t.Fatalf("%s: failed parsing expression: %s", test.name, test.src) } } func TestParseBasic(t *testing.T) { tests := []Test{ {"integer", "24", []Type{BASIC}, true}, {"var", "a", []Type{IDENT}, true}, } handleTests(t, tests) } func TestParseBinary(t *testing.T) { tests := []Test{ {"simple", "(+ 2 3)", []Type{BINARY, BASIC, BASIC}, true}, {"one-var", "(+ 2 b)", []Type{BINARY, BASIC, IDENT}, true}, {"two-vars", "(+ a b)", []Type{BINARY, IDENT, IDENT}, true}, {"single-operand", "(- 5)", []Type{}, false}, {"post-fix", "(3 5 +)", []Type{}, false}, {"infix", "(3 + 4)", []Type{}, false}, {"no-closing", "(+ 6 2", []Type{}, false}, {"extra-open", "(d", []Type{}, false}, {"modulus-quotient", "(% / d)", []Type{}, false}, {"binary-and", "(& 3 5)", []Type{}, false}, {"no-operator-nested", "((+ 3 5) 5)", []Type{}, false}, {"multi-nested-with-empty", "(* (- 2 6) (+ 4 2)())", []Type{}, false}, } handleTests(t, tests) } func TestParseCall(t *testing.T) { tests := []Test{ {"no-args", "(nothing)", []Type{CALL}, true}, {"two-args", "(add 1 2)", []Type{CALL, BASIC, BASIC}, true}, } handleTests(t, tests) } func TestParseComment(t *testing.T) { tests := []Test{ {"simple", "2; comment", []Type{BASIC}, true}, {"nested-between-expr", "2; comment\na", []Type{BASIC, IDENT}, true}, {"first-line", "; comment\na", []Type{IDENT}, true}, {"nested-comment", "(+ 2; comment\n3)", []Type{BINARY, BASIC, BASIC}, true}, {"comment-only", ";comment", []Type{}, false}, } handleTests(t, tests) } func TestParseFor(t *testing.T) { tests := []Test{ {"simple", "(for true :int 1)", []Type{FOR, BASIC, BASIC}, true}, {"no-cond", "(for :int 1)", []Type{}, false}, {"no-type", "(for true 1)", []Type{}, false}, {"no-body", "(for true :int)", []Type{}, false}, {"cond-with-2-expr-body", "(for (== n true) :int (+ 2 3) 52)", []Type{FOR, BINARY, IDENT, BASIC, BINARY, BASIC, BASIC, BASIC}, false}, } handleTests(t, tests) } func TestParseFunc(t *testing.T) { tests := []Test{ {"simple", "(func:int 0)", []Type{FUNC, BASIC}, true}, {"no-param-binary", "(func:int (+ 2 3))", []Type{FUNC, BINARY, BASIC, BASIC}, true}, {"two-param-binary", "(func (a:int b:int) :int (+ a b))", []Type{FUNC, BINARY, IDENT, IDENT}, true}, {"empty-params", "(func () :int a)", []Type{}, false}, {"empty-expr-list", "(func:int)", []Type{}, false}, {"duplicate-param", "(func (dup:int dup:int) :int 0)", []Type{}, false}, {"no-open", "func:int 0)", []Type{}, false}, //{"nested-decl", "(func:int () (func:int))", []Type{}, false}, } handleTests(t, tests) } func TestParseDeclFile(t *testing.T) { tests := []Test{ {"simple", "(define main (func:int 0))", []Type{FILE, DEFINE, FUNC, BASIC}, true}, {"no-source-no-file", "", []Type{}, false}, {"no-decls", "42", []Type{}, false}, {"duplicate-decl", "(define fn (func:int 1))(define fn (func:int 1))", []Type{FILE, DEFINE, FUNC, BINARY, DEFINE, FUNC, BASIC}, false}, {"redeclared-var-decl", "(define a:int 0)(define a (func:int 1))", []Type{FILE, DEFINE, BASIC, DEFINE, FUNC, BASIC}, false}, } handleFileTests(t, tests) } func TestParseIf(t *testing.T) { tests := []Test{ {"then-only", "(if false :int 3)", []Type{IF, BASIC, BASIC}, true}, {"then-else", "(if false :int 3 4)", []Type{IF, BASIC, BASIC, BASIC}, true}, {"no-type", "(if false :int 0 1)", []Type{}, false}, {"integer-cond", "(if 1 :int 3)", []Type{IF, BASIC, BASIC}, true}, {"var-cond", "(if asdf :int 3)", []Type{IF, IDENT, BASIC}, true}, {"var-keyword", "(if var :int 3)", []Type{}, false}, {"logical-cond-nested-binary-then", "(if (< a b) :int a (+ b 1))", []Type{IF, BINARY, IDENT, IDENT, IDENT, BINARY, IDENT, BASIC}, true}, {"logical-cond-assign-then", "(if (< a b) :int (= a b))", []Type{IF, BINARY, IDENT, IDENT, ASSIGN, IDENT, IDENT}, true}, } handleTests(t, tests) } func TestParseUnary(t *testing.T) { var tests = []Test{ {"negate-integer", "-24", []Type{UNARY, BASIC}, true}, {"negate-var", "-a", []Type{UNARY, IDENT}, true}, {"negate-call", "-(foo)", []Type{UNARY, CALL, IDENT}, true}, {"positive-binary", "+(+ 2 3)", []Type{UNARY, BINARY, BASIC, BASIC}, true}, {"positive-decl", "+(define foo:int 42)", []Type{}, false}, } handleTests(t, tests) } func TestParseVar(t *testing.T) { tests := []Test{ {"simple", "(var (a:int) :int 0)", []Type{VAR, BASIC}, true}, {"no-expr", "(var (a:int) :int)", []Type{}, false}, {"with-assign", "(var (a:int) :int(= a 5))", []Type{VAR, ASSIGN, BASIC}, true}, {"no-type", "(var (a):int)", []Type{}, false}, {"redeclare", "(var (a:int a:bool) :int)", []Type{}, false}, } handleTests(t, tests) } func TestParseFile(t *testing.T) { test := Test{"bad-ext", "", []Type{}, false} // test for file with bad extension f, err := ioutil.TempFile("", "") if err != nil { t.Log(err) } defer func() { f.Close() err := os.Remove(f.Name()) t.Log(err) }() n, err := parse.ParseFile(token.NewFileSet(), f.Name(), "") checkTest(t, test, n, err) test = Test{"simple.calc", "(define main (func:int 0))", []Type{FILE, DEFINE, FUNC, BASIC}, true} f, err = os.Create(test.name) if err != nil { t.Log(err) } defer func() { f.Close() if err := os.Remove(f.Name()); err != nil { t.Log(err) } }() _, err = f.WriteString(test.src) if err != nil { t.Fatal(err) } n, err = parse.ParseFile(token.NewFileSet(), f.Name(), "") } func TestDirectory(t *testing.T) { gopath := os.Getenv("GOPATH") var path string for _, p := range strings.Split(gopath, ";") { tmp := filepath.Join(p, "src", "github.com", "rthornton128", "calc", "examples", "package") t.Log("testing path:", tmp) if _, err := os.Stat(tmp); err == nil { path = tmp break } } t.Log("using path:", path) _, err := parse.ParseDir(token.NewFileSet(), path) if err != nil { t.Fatal(err) } } <|start_filename|>ir/var.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "strings" "github.com/rthornton128/calc/ast" ) type Var struct{ object } func makeVar(pkg *Package, i *ast.Ident) *Var { return &Var{ object: object{ kind: ast.VarDecl, name: i.Name, pos: i.Pos(), scope: pkg.scope, }, } } func (i *Var) String() string { return i.Name() } type Variable struct { object Params []*Param Body []Object } func makeVariable(pkg *Package, ve *ast.VarExpr) *Variable { pkg.newScope() defer pkg.closeScope() v := &Variable{ object: object{ id: pkg.getID(), kind: ast.VarDecl, name: "var", pos: ve.Pos(), scope: pkg.scope, typ: typeFromString(ve.Type.Name), }, Params: makeParamList(pkg, ve.Params), Body: MakeExprList(pkg, ve.Body), } return v } func (v *Variable) String() string { params := make([]string, len(v.Params)) for i, p := range v.Params { params[i] = v.Scope().Lookup(p.Name()).String() } body := make([]string, len(v.Body)) for i, e := range v.Body { body[i] = e.String() } return fmt.Sprintf("var:%s (%s) {%s}", v.Type(), strings.Join(params, ","), strings.Join(body, ",")) } <|start_filename|>ir/assign.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" ) type Assignment struct { object Lhs string Rhs Object } func makeAssignment(pkg *Package, a *ast.AssignExpr) *Assignment { return &Assignment{ object: object{name: "assign", pkg: pkg, pos: a.Pos(), scope: pkg.scope}, Lhs: a.Name.Name, Rhs: MakeExpr(pkg, a.Value), } } func (a *Assignment) String() string { return fmt.Sprintf("{%s=%s}", a.Lhs, a.Rhs.String()) } <|start_filename|>ir/constant.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "strconv" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/token" ) type Value interface { String() string Type() Type } type ( boolValue bool intValue int64 ) type Constant struct { object value Value } func makeConstant(b *ast.BasicLit) *Constant { var v Value switch b.Kind { case token.BOOL: v, _ = makeBool(b.Lit) // TODO handle error case token.INTEGER: v, _ = makeInt(b.Lit) // TODO handle error } return &Constant{ object: object{name: v.String(), pos: b.Pos(), typ: v.Type()}, value: v, } } func (c *Constant) String() string { return c.value.String() } func makeBool(lit string) (Value, error) { b, err := strconv.ParseBool(lit) return boolValue(b), err } func (v boolValue) String() string { return fmt.Sprintf("%v", bool(v)) } func (v boolValue) Type() Type { return Bool } func makeInt(lit string) (Value, error) { i, err := strconv.ParseInt(lit, 0, 64) return intValue(i), err } func (v intValue) String() string { return strconv.FormatInt(int64(v), 10) } func (v intValue) Type() Type { return Int } <|start_filename|>ir/binary.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/token" ) type Binary struct { object Op token.Token Lhs Object Rhs Object } func makeBinary(pkg *Package, b *ast.BinaryExpr) *Binary { lhs := MakeExpr(pkg, b.List[0]) for _, e := range b.List[1:] { rhs := MakeExpr(pkg, e) lhs = Object(&Binary{ object: object{pkg: pkg, pos: b.Pos(), typ: binaryType(b.Op)}, Op: b.Op, Lhs: lhs, Rhs: rhs, }) } return lhs.(*Binary) } func binaryType(t token.Token) Type { switch t { case token.ADD, token.MUL, token.QUO, token.REM, token.SUB: return Int default: return Bool } } func (b *Binary) String() string { return fmt.Sprintf("(%s %s %s)", b.Lhs.String(), b.Op, b.Rhs.String()) } type Unary struct { object Op string Rhs Object } func makeUnary(pkg *Package, u *ast.UnaryExpr) *Unary { return &Unary{ object: object{pkg: pkg, pos: u.Pos(), scope: pkg.scope, typ: Int}, Op: u.Op, Rhs: MakeExpr(pkg, u.Value), } } func (u *Unary) String() string { return fmt.Sprintf("%s(%s)", u.Op, u.Rhs.String()) } <|start_filename|>parse/parse.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause // Package parse implements the parser for the Calc programming language package parse // TODO a single Parse function that takes an io.Reader as an argument // would actually be preferable and would eliminate much of the duplicate // work and cruft // // A flag could then be used to separate which inner parse function to // call (expression, file or package). A unified ast.Package would or // generic ast.Node would need to be returned and let the caller handle // the details // // Alternatively, keep the separate interfaces but use a unified handler // internally import ( "fmt" "io" "os" "path/filepath" "strings" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/scan" "github.com/rthornton128/calc/token" ) // ParseExpression parses the given source string and returns an ast.Node // representing the root of the expression. This function is intended to // facilitate testing and is not use by the compiler itself. The name is // used in error reporting func ParseExpression(name, src string) (ast.Expr, error) { var p parser fset := token.NewFileSet() file := fset.Add(name, len(src)) p.init(file, name, strings.NewReader(src), nil) node := p.parseExpression() if p.errors.Count() > 0 { return nil, p.errors } return node, nil } // ParseFile parses the file identified by filename and returns a pointer // to an ast.File object. The file should contain Calc source code and // have the .calc file extension. // The returned AST object ast.File is nil if there is an error. func ParseFile(fset *token.FileSet, filename, src string) (*ast.File, error) { var r io.Reader var sz int64 if src == "" { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } if ext := filepath.Ext(fi.Name()); ext != ".calc" { return nil, fmt.Errorf("invalid file extension %s, must be .calc", ext) } r = f sz = fi.Size() fmt.Printf("%s:%d\n", fi.Name(), sz) } else { sr := strings.NewReader(src) r = io.Reader(sr) sz = sr.Size() } file := fset.Add(filepath.Base(filename), int(sz)) var p parser p.init(file, filename, r, ast.NewScope(nil)) f := p.parseFile() if p.errors.Count() > 0 { return nil, p.errors } return f, nil } // ParseDir parses a directory of Calc source files. It calls ParseFile // for each file ending in .calc found in the directory. func ParseDir(fset *token.FileSet, path string) (*ast.Package, error) { fd, err := os.Open(path) if err != nil { return nil, err } defer fd.Close() fnames, err := fd.Readdirnames(0) if err != nil { return nil, err } fnames = filterByExt(fnames) if len(fnames) == 0 { return nil, fmt.Errorf("no files to parse; stop") } var files []*ast.File for _, name := range fnames { f, err := ParseFile(fset, filepath.Join(path, name), "") if f == nil { return nil, err } files = append(files, f) } return &ast.Package{Files: files}, nil } func filterByExt(names []string) []string { filtered := make([]string, 0, len(names)) for _, name := range names { if filepath.Ext(name) == ".calc" { filtered = append(filtered, name) } } return filtered } type parser struct { file *token.File errors token.ErrorList scanner scan.Scanner curScope *ast.Scope topScope *ast.Scope pos token.Pos tok token.Token lit string } /* Utility */ func (p *parser) addError(args ...interface{}) { p.errors.Add(p.file.Position(p.pos), args...) } func (p *parser) expect(tok token.Token) token.Pos { if p.tok != tok { p.addError("Expected '" + tok.String() + "' got '" + p.lit + "'") return p.pos } defer p.next() return p.pos } func (p *parser) init(f *token.File, name string, src io.Reader, s *ast.Scope) { if s == nil { s = ast.NewScope(nil) } p.file = f p.scanner.Init(p.file, src) p.curScope = s p.topScope = s p.next() } func (p *parser) next() { p.lit, p.tok, p.pos = p.scanner.Scan() } /* Scope */ func (p *parser) openScope() { p.curScope = ast.NewScope(p.curScope) } func (p *parser) closeScope() { p.curScope = p.curScope.Parent } /* Parsing */ func (p *parser) parseAssignExpr() *ast.AssignExpr { return &ast.AssignExpr{ Equal: p.expect(token.ASSIGN), Name: p.parseIdent(), Value: p.parseExpression(), } } func (p *parser) parseBasicLit() *ast.BasicLit { pos, tok, lit := p.pos, p.tok, p.lit p.next() return &ast.BasicLit{LitPos: pos, Kind: tok, Lit: lit} } func (p *parser) parseBinaryExpr() *ast.BinaryExpr { pos := p.pos op := p.tok p.next() return &ast.BinaryExpr{ Op: op, OpPos: pos, List: p.parseExprList(), } } func (p *parser) parseCallExpr() *ast.CallExpr { return &ast.CallExpr{ Name: p.parseIdent(), Args: p.parseExprList(), } } func (p *parser) parseDefineStmt() *ast.DefineStmt { p.expect(token.LPAREN) defer p.expect(token.RPAREN) d := &ast.DefineStmt{ Define: p.expect(token.DEFINE), Name: p.parseIdent(), } if p.tok == token.COLON { d.Type = p.parseType() } d.Body = p.parseExpression() return d } func (p *parser) parseExpression() ast.Expr { var e ast.Expr switch p.tok { case token.LPAREN: p.expect(token.LPAREN) switch p.tok { case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.EQL, token.GTE, token.GTT, token.NEQ, token.LST, token.LTE: e = p.parseBinaryExpr() case token.ASSIGN: e = p.parseAssignExpr() case token.FOR: e = p.parseFor() case token.FUNC: e = p.parseFuncExpr() case token.IDENT: e = p.parseCallExpr() case token.IF: e = p.parseIfExpr() case token.VAR: e = p.parseVarExpr() default: p.addError("Expected operator, keyword or identifier but got '" + p.lit + "'") } p.expect(token.RPAREN) case token.IDENT: e = p.parseIdent() case token.BOOL, token.INTEGER: e = p.parseBasicLit() case token.ADD, token.SUB: e = p.parseUnaryExpr() default: p.addError("Expected expression, got '" + p.lit + "'") p.next() } return e } func (p *parser) parseExprList() []ast.Expr { list := make([]ast.Expr, 0) for p.tok != token.RPAREN && p.tok != token.EOF { list = append(list, p.parseExpression()) } return list } func (p *parser) parseFile() *ast.File { defs := make([]*ast.DefineStmt, 0) for p.tok != token.EOF { def := p.parseDefineStmt() switch def.Body.(type) { case *ast.FuncExpr: def.Kind = ast.FuncDecl default: def.Kind = ast.VarDecl } prev := p.curScope.Insert(&ast.Object{ NamePos: def.Name.NamePos, Name: def.Name.Name, Kind: def.Kind, }) if prev != nil { switch prev.Kind { case ast.FuncDecl: p.addError(prev.Name, " redeclared; declared as function at ", p.file.Position(prev.NamePos)) case ast.VarDecl: p.addError(prev.Name, " redeclared; declared as variable at ", p.file.Position(prev.NamePos)) } continue } if p.errors.Count() > 0 { break } defs = append(defs, def) } if len(defs) < 1 { p.addError("reached end of file without any declarations") } return &ast.File{Defs: defs} } func (p *parser) parseFor() *ast.ForExpr { return &ast.ForExpr{ For: p.expect(token.FOR), Cond: p.parseExpression(), Type: p.parseType(), Body: p.parseExprList(), } } func (p *parser) parseFuncExpr() *ast.FuncExpr { p.openScope() defer p.closeScope() return &ast.FuncExpr{ Func: p.expect(token.FUNC), Params: p.parseParamList(), Type: p.parseType(), Body: p.parseExprList(), } } func (p *parser) parseIdent() *ast.Ident { name := p.lit return &ast.Ident{NamePos: p.expect(token.IDENT), Name: name} } func (p *parser) parseIfExpr() *ast.IfExpr { p.openScope() defer p.closeScope() ie := &ast.IfExpr{ If: p.expect(token.IF), Cond: p.parseExpression(), Type: p.parseType(), Then: p.parseExpression(), } if p.tok != token.RPAREN { ie.Else = p.parseExpression() } return ie } func (p *parser) parseParamList() []*ast.Param { params := make([]*ast.Param, 0) if p.tok != token.LPAREN { return params } p.expect(token.LPAREN) for p.tok != token.RPAREN && p.tok != token.EOF { param := &ast.Param{Name: p.parseIdent(), Type: p.parseType()} o := &ast.Object{ Kind: ast.VarDecl, Name: param.Name.Name, NamePos: param.Pos(), } if prev := p.curScope.Insert(o); prev != nil { p.addError("duplicate parameter ", prev.Name, "; previously declared at ", p.file.Position(prev.Pos())) break } params = append(params, param) } p.expect(token.RPAREN) return params } func (p *parser) parseType() *ast.Ident { p.expect(token.COLON) return p.parseIdent() } func (p *parser) parseUnaryExpr() *ast.UnaryExpr { pos, op := p.pos, p.lit p.next() return &ast.UnaryExpr{OpPos: pos, Op: op, Value: p.parseExpression()} } func (p *parser) parseVarExpr() *ast.VarExpr { return &ast.VarExpr{ Var: p.expect(token.VAR), Params: p.parseParamList(), Type: p.parseType(), Body: p.parseExprList(), } } <|start_filename|>ir/call.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "strings" "github.com/rthornton128/calc/ast" ) type Call struct { object Args []Object } func makeCall(pkg *Package, c *ast.CallExpr) *Call { args := make([]Object, len(c.Args)) for i, a := range c.Args { args[i] = MakeExpr(pkg, a) } return &Call{ object: object{name: c.Name.Name, pkg: pkg, pos: c.Pos(), scope: pkg.scope}, Args: args, } } func (c *Call) String() string { var out []string for _, a := range c.Args { out = append(out, a.String()) } return fmt.Sprintf("{call: %s (%s)}", c.Name(), strings.Join(out, ",")) } <|start_filename|>ir/types.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir type Type int const ( Unknown Type = iota Bool Int ) var typeStrings = []string{ Unknown: "unknown type", Bool: "bool", Int: "int", } func typeFromString(name string) Type { for i, s := range typeStrings { if name == s { return Type(i) } } return Unknown } func (t Type) String() string { return typeStrings[t] } <|start_filename|>token/file.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package token // File represents a single source file. It is used to track the number of // newlines in the file, it's size, name and position within a fileset. type File struct { base int name string lines []int size int } // NewFile returns a new file object func NewFile(name string, base, size int) *File { return &File{ base: base, name: name, lines: make([]int, 0, 16), size: size, } } // AddLine adds the position of the start of a line in the source file at // the given offset. Every file consists of at least one line at offset // zero. func (f *File) AddLine(offset int) { if offset >= f.base-1 && offset < f.base+f.size { f.lines = append(f.lines, offset) } } // Base returns the base offset of the file within a fileset func (f *File) Base() int { return f.base } // Pos generates a Pos based on the offset. The position is the file's // base+offset func (f *File) Pos(offset int) Pos { if offset < 0 || offset > f.size { panic("illegal file offset") } return Pos(f.base + offset) } // Position returns the column and row position of a Pos within the file func (f *File) Position(p Pos) Position { col, row := int(p)-f.Base()+1, 1 for i, nl := range f.lines { if p > f.Pos(nl) { col, row = int(p-f.Pos(nl))-f.Base()+1, i+1 } } return Position{Filename: f.name, Col: col, Row: row} } // Size returns the length of the source code of the file. func (f *File) Size() int { return f.size } <|start_filename|>ir/package.go<|end_filename|> // Copyright (c) 2015, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package ir import ( "fmt" "github.com/rthornton128/calc/ast" ) type Package struct { object top *Scope } func MakePackage(pkg *ast.Package, name string) *Package { scope := NewScope(nil) p := &Package{ object: object{name: name, pos: pkg.Pos(), scope: scope}, top: scope, } for _, f := range pkg.Files { MakeFile(p, f) } return p } func (p *Package) closeScope() { if p.scope != nil { p.scope = p.scope.parent } } func (p *Package) getID() int { p.id++ return p.id } func (p *Package) Insert(o Object) { p.scope.Insert(o) } func (p *Package) InsertTop(o Object) { p.top.Insert(o) } func (p *Package) Lookup(name string) Object { return p.scope.Lookup(name) } func (p *Package) newScope() *Scope { p.scope = NewScope(p.scope) return p.scope } func (p *Package) String() string { return fmt.Sprintf("package %s {%s}", p.name, p.scope) } func MakeFile(pkg *Package, f *ast.File) { for _, d := range f.Defs { pkg.InsertTop(MakeDefine(pkg, d)) } } <|start_filename|>token/token.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause package token type Token int const ( tok_start Token = iota EOF ILLEGAL lit_start BOOL IDENT INTEGER lit_end op_start LPAREN RPAREN COLON ADD SUB MUL QUO REM ASSIGN AND OR EQL NEQ LST GTT LTE GTE op_end key_start DEFINE FOR FUNC IF VAR key_end tok_end ) var tok_strings = map[Token]string{ EOF: "EOF", ILLEGAL: "Illegal", BOOL: "Boolean", IDENT: "Identifier", INTEGER: "Integer", LPAREN: "(", RPAREN: ")", COLON: ":", ADD: "+", SUB: "-", MUL: "*", QUO: "/", REM: "%", ASSIGN: "=", AND: "&&", OR: "||", EQL: "==", NEQ: "!=", LST: "<", GTT: ">", LTE: "<=", GTE: ">=", DEFINE: "define", FOR: "for", FUNC: "func", IF: "if", VAR: "var", } func (t Token) IsLiteral() bool { return t > lit_start && t < lit_end } func (t Token) IsOperator() bool { return t > op_start && t < op_end } func (t Token) IsKeyword() bool { return t > key_start && t < key_end } func Lookup(str string) Token { if str == "true" || str == "false" { return BOOL } for t, s := range tok_strings { if s == str { return t } } return IDENT } func (t Token) String() string { return tok_strings[t] } func (t Token) Valid() bool { return t > tok_start && t < tok_end } <|start_filename|>cgen/cgen.go<|end_filename|> // Copyright (c) 2014, <NAME> // All rights reserved. // This source code is governed by a Simplied BSD-License. Please see the // LICENSE included in this distribution for a copy of the full license // or, if one is not included, you may also find a copy at // http://opensource.org/licenses/BSD-2-Clause // Package comp comprises the code generation portion of the Calc // programming language package comp import ( "fmt" "os" "path/filepath" "strings" "github.com/rthornton128/calc/ast" "github.com/rthornton128/calc/ir" "github.com/rthornton128/calc/parse" "github.com/rthornton128/calc/token" ) type compiler struct { fp *os.File fset *token.FileSet errors token.ErrorList } // CompileFile generates a C source file for the corresponding file // specified by path. The .calc extension for the filename in path is // replaced with .c for the C source output. func CompileFile(path string, opt bool) error { fset := token.NewFileSet() f, err := parse.ParseFile(fset, path, "") if err != nil { return err } pkg := ir.MakePackage(&ast.Package{ Files: []*ast.File{f}, }, filepath.Base(path)) if err := ir.TypeCheck(pkg, fset); err != nil { return err } if opt { pkg = ir.FoldConstants(pkg).(*ir.Package) } //ir.Tag(pkg) path = path[:len(path)-len(filepath.Ext(path))] fp, err := os.Create(path + ".c") if err != nil { return err } defer fp.Close() c := &compiler{fp: fp} c.emitHeaders() c.compPackage(pkg) c.emitMain() if c.errors.Count() != 0 { return c.errors } return nil } // CompileDir generates C source code for the Calc sources found in the // directory specified by path. The C source file uses the same name as // directory rather than any individual file. func CompileDir(path string, opt bool) error { fset := token.NewFileSet() p, err := parse.ParseDir(fset, path) if err != nil { return err } pkg := ir.MakePackage(p, filepath.Base(path)) if err := ir.TypeCheck(pkg, fset); err != nil { return err } if opt { pkg = ir.FoldConstants(pkg).(*ir.Package) } //ir.Tag(pkg) fp, err := os.Create(filepath.Join(path, filepath.Base(path)) + ".c") if err != nil { return err } defer fp.Close() c := &compiler{fp: fp, fset: fset} c.emitHeaders() c.compPackage(pkg) c.emitMain() if c.errors.Count() != 0 { return c.errors } return nil } /* Utility */ func cType(t ir.Type) string { switch t { case ir.Int: return "int32_t" case ir.Bool: return "bool" default: return "int" } } // Error adds an error to the compiler at the given position. The remaining // arguments are used to generate the error message. func (c *compiler) Error(pos token.Pos, args ...interface{}) { c.errors.Add(c.fset.Position(pos), args...) } func (c *compiler) emit(s string, args ...interface{}) { fmt.Fprintf(c.fp, s, args...) } func (c *compiler) emitln(args ...interface{}) { fmt.Fprintln(c.fp, args...) } func (c *compiler) emitHeaders() { c.emitln("#include <stdio.h>") c.emitln("#include <stdint.h>") c.emitln("#include <stdbool.h>") } func (c *compiler) emitMain() { c.emitln("int main(void) {") c.emitln("printf(\"%d\\n\", _main());") c.emitln("return 0;") c.emitln("}") } /* Main Compiler */ func (c *compiler) compObject(o ir.Object) string { switch t := o.(type) { case *ir.Assignment: return c.compAssignment(t) case *ir.Constant: return c.compConstant(t) case *ir.Binary: return c.compBinary(t) case *ir.Call: return c.compCall(t) case *ir.For: return c.compFor(t) //case *ir.Function: //return c.compFunction(t) case *ir.If: return c.compIf(t) case *ir.Unary: return c.compUnary(t) case *ir.Var: return c.compVar(t) case *ir.Variable: c.emit("%s %s%d = 0;\n", cType(t.Type()), t.Name(), t.ID()) return c.compVariable(t) } return "" } func (c *compiler) compAssignment(a *ir.Assignment) string { c.emit("%s%d = %s;\n", a.Lhs, a.Scope().Lookup(a.Lhs).ID(), c.compObject(a.Rhs)) return a.Lhs } func (c *compiler) compBinary(b *ir.Binary) string { return fmt.Sprintf("(%s %s %s)", c.compObject(b.Lhs), b.Op.String(), c.compObject(b.Rhs)) } func (c *compiler) compCall(call *ir.Call) string { args := make([]string, len(call.Args)) for i, a := range call.Args { args[i] = fmt.Sprintf("%s", c.compObject(a)) } return fmt.Sprintf("_%s(%s)", call.Name(), strings.Join(args, ",")) } func (c *compiler) compConstant(con *ir.Constant) string { return con.String() } func (c *compiler) compDefine(d *ir.Define) string { switch t := d.Body.(type) { case *ir.Function: c.emit("%s {\n", c.compSignature(t)) c.compFunction(d.Body.(*ir.Function)) return "" default: return c.compObject(t) } } func (c *compiler) compFor(f *ir.For) string { c.emit("%s %s%d = 0;\n", cType(f.Type()), f.Name(), f.ID()) c.emit("while (%s) {\n", c.compObject(f.Cond)) for _, e := range f.Body[:len(f.Body)-1] { c.compObject(e) } c.emit("}\n%s%d = %s;\n", f.Name(), f.ID(), c.compObject(f.Body[len(f.Body)-1])) return fmt.Sprintf("%s%d", f.Name(), f.ID()) } func (c *compiler) compFunction(f *ir.Function) { for _, e := range f.Body[:len(f.Body)-1] { c.compObject(e) } c.emit("return %s;\n}\n", c.compObject(f.Body[len(f.Body)-1])) } func (c *compiler) compIdent(i *ir.Var) string { return fmt.Sprintf("%s%d", i.Name(), i.Scope().Lookup(i.Name()).ID()) } func (c *compiler) compIf(i *ir.If) string { c.emit("%s if%d = 0; /* %s */\n", cType(i.Type()), i.ID(), i.Name()) c.emit("if (%s) {\n", c.compObject(i.Cond)) c.emit("if%d = %s;\n", i.ID(), c.compObject(i.Then)) if i.Else != nil { c.emitln("} else {") c.emit("if%d = %s;\n", i.ID(), c.compObject(i.Else)) } c.emitln("}") return fmt.Sprintf("if%d", i.ID()) } func (c *compiler) compPackage(p *ir.Package) { names := p.Scope().Names() for _, name := range names { // later, this may need to check for import clauses if d, ok := p.Scope().Lookup(name).(*ir.Define); ok { if f, ok := d.Body.(*ir.Function); ok { c.emit("%s;\n", c.compSignature(f)) params := make([]string, len(f.Params)) for i, p := range f.Params { params[i] = cType(f.Scope().Lookup(p.Name()).(*ir.Param).Type()) } c.emit("%s (*_%s)(%s) = f%d;\n", cType(f.Type()), d.Name(), strings.Join(params, ","), f.ID()) defer c.compDefine(d) } } } } func (c *compiler) compSignature(f *ir.Function) string { params := make([]string, len(f.Params)) for i, p := range f.Params { param := f.Scope().Lookup(p.Name()).(*ir.Param) params[i] = fmt.Sprintf("%s %s%d", cType(param.Type()), param.Name(), param.ID()) } return fmt.Sprintf("%s f%d(%s)", cType(f.Type()), f.ID(), strings.Join(params, ",")) } func (c *compiler) compUnary(u *ir.Unary) string { return fmt.Sprintf("%s%s", u.Op, c.compObject(u.Rhs)) } func (c *compiler) compVar(v *ir.Var) string { switch t := v.Scope().Lookup(v.Name()).(type) { case *ir.Define: return c.compDefine(t) case *ir.Param: return fmt.Sprintf("%s%d", t.Name(), t.ID()) } panic("unreachable") } func (c *compiler) compVariable(v *ir.Variable) string { for _, p := range v.Params { param := v.Scope().Lookup(p.Name()).(*ir.Param) c.emit("%s %s%d = 0;\n", cType(param.Type()), param.Name(), param.ID()) } for _, e := range v.Body[:len(v.Body)-1] { c.compObject(e) } c.emit("var%d = %s;\n", v.ID(), c.compObject(v.Body[len(v.Body)-1])) return fmt.Sprintf("var%d", v.ID()) }
rthornton128/calc
<|start_filename|>Assets/Shaders/Blob.shader<|end_filename|> Shader "Ray Marching/Blob" { Properties { [Header(Main Maps)] [Space] _Tint ("Albedo", Color) = (1.0, 1.0, 1.0) [Gamma] _Metallic ("Metallic", Range(0, 1)) = 0.0 _Smoothness ("Smoothness", Range(0, 1)) = 0.5 [Header(Blob Parameters)] [Space] _Speed ("Speed", Float) = 1.0 [Header(Ray Marching Options)] [Space] _Tolerance ("Tolerance", Float) = 0.001 [Toggle] _RelativeTolerance ("Relative Tolerance", Float) = 1.0 _MaxDistance ("Max. Distance", Float) = 1000.0 _MaxSteps ("Max. Steps", Int) = 100 [Space] [KeywordEnum(Fast, Forward, Centered, Tetrahedron)] _NormalApproxMode ("Normal Approx. Mode", Float) = 0.0 _NormalApproxStep ("Normal Approx. Step", Float) = 0.001 [Toggle] _NormalFiltering ("Normal Filtering", Float) = 1.0 [Space] [Toggle] _AmbientOcclusion ("Ambient Occlusion", Float) = 1.0 _AmbientOcclusionMultiplier ("Ambient Occlusion Multiplier", Float) = 1.0 _AmbientOcclusionStep ("Ambient Occlusion Step", Float) = 0.1 _AmbientOcclusionSamples ("Ambient Occlusion Samples", Int) = 5 [Space] [KeywordEnum(None, Hard, Soft)] _ShadowMode ("Shadow Mode", Float) = 0.0 _SoftShadowFactor ("Soft Shadow Factor", Float) = 1.0 } CGINCLUDE #include "RayMarchingSDF.cginc" float _Speed; float SDF(float3 p) { float rho1 = radians(45) * _Time.y * _Speed; float rho2 = rho1 + radians(120); float rho3 = rho1 + radians(240); float R1 = .15f + .15f*sin(rho1); float R2 = .30f + .05f*sin(rho2); float R3 = .45f + .05f*sin(rho3); float r1 = .09f - .04f*sin(rho1); float r2 = .09f - .04f*sin(rho2); float r3 = .09f - .04f*sin(rho3); return SmoothUnion( SmoothUnion( SmoothUnion( Sphere(p, float3(R1*cos(rho1), 0.f, R1*sin(rho1)), r1), SmoothUnion( Sphere(p, float3(R1*cos(rho2), 0.f, R1*sin(rho2)), r1), Sphere(p, float3(R1*cos(rho3), 0.f, R1*sin(rho3)), r1), 50.f ), 50.f ), SmoothUnion( Sphere(p, float3(R2*cos(rho1), R2*sin(rho1), 0.f), r2), SmoothUnion( Sphere(p, float3(R2*cos(rho2), R2*sin(rho2), 0.f), r2), Sphere(p, float3(R2*cos(rho3), R2*sin(rho3), 0.f), r2), 50.f ), 50.f ), 17.f ), SmoothUnion( Sphere(p, float3(0.f, R2*cos(rho1), R2*sin(rho1)), r3), SmoothUnion( Sphere(p, float3(0.f, R2*cos(rho2), R2*sin(rho2)), r3), Sphere(p, float3(0.f, R2*cos(rho3), R2*sin(rho3)), r3), 50.f ), 50.f ), 17.f ); } ENDCG SubShader { Tags { "Queue"="AlphaTest" } Pass { Tags { "LightMode" = "ForwardBase" } Cull Front CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma vertex vert #pragma fragment fragBase #define FORWARD_BASE_PASS #include "RayMarching.cginc" ENDCG } Pass { Tags { "LightMode" = "ForwardAdd" } Cull Front ZWrite Off Blend One One CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma multi_compile_fwdadd #pragma vertex vert #pragma fragment fragBase #include "RayMarching.cginc" ENDCG } Pass { Tags { "LightMode" = "ShadowCaster" } Cull Front CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma multi_compile_fwdadd #pragma vertex vert #pragma fragment fragShadowCaster #include "RayMarching.cginc" ENDCG } } } <|start_filename|>Assets/Scripts/ResolutionScalingByLayer.cs<|end_filename|> using UnityEngine; public class ResolutionScalingByLayer : MonoBehaviour { [Range(0.1f, 1.0f)] public float widthScaleFactor = 1.0f; [Range(0.1f, 1.0f)] public float heightScaleFactor = 1.0f; public LayerMask layerMask = -1; Camera m_mainCamera; Camera m_secondaryCamera; Material m_material; void Start() { /* Setup cameras */ LayerMask cullingMask; m_mainCamera = GetComponent<Camera>(); cullingMask = layerMask & m_mainCamera.cullingMask; m_mainCamera.cullingMask &= ~cullingMask; GameObject cameraGO = new GameObject(); cameraGO.hideFlags = HideFlags.HideAndDontSave; cameraGO.transform.parent = transform; m_secondaryCamera = cameraGO.AddComponent<Camera>(); m_secondaryCamera.CopyFrom(m_mainCamera); m_secondaryCamera.aspect = m_mainCamera.aspect; m_secondaryCamera.backgroundColor = Color.clear; m_secondaryCamera.clearFlags = CameraClearFlags.SolidColor; m_secondaryCamera.cullingMask = cullingMask; m_secondaryCamera.enabled = false; /* Setup material */ Shader shader = Shader.Find("Hidden/Custom/BlitCopyWithLastCameraDepth"); m_material = new Material(shader); m_material.hideFlags = HideFlags.HideAndDontSave; } int GetScaledWidth(int width) { return (int) Mathf.Floor(widthScaleFactor * width); } int GetScaledHeight(int height) { return (int) Mathf.Floor(heightScaleFactor * height); } void OnRenderImage(RenderTexture source, RenderTexture dest) { // Allocate temporary render texture int width = GetScaledWidth(m_mainCamera.pixelWidth); int height = GetScaledHeight(m_mainCamera.pixelHeight); RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 24, RenderTextureFormat.Default); renderTexture.Create(); // Blit full resolution layers m_material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One); m_material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero); m_material.SetInt("_ZTest", (int) UnityEngine.Rendering.CompareFunction.Always); Graphics.Blit(source, dest, m_material); // Render scaled resolution layers m_secondaryCamera.targetTexture = renderTexture; m_secondaryCamera.Render(); // Blit scaled resolution layers m_material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha); m_material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); m_material.SetInt("_ZTest", (int) UnityEngine.Rendering.CompareFunction.Less); Graphics.Blit(renderTexture, dest, m_material); renderTexture.Release(); } } <|start_filename|>Assets/Shaders/BlitCopyWithLastCameraDepth.shader<|end_filename|> Shader "Hidden/Custom/BlitCopyWithLastCameraDepth" { Properties { _MainTex ("Texture", 2D) = "white" {} _SrcBlend ("SrcBlend", Int) = 5 // SrcAlpha _DstBlend ("DstBlend", Int) = 10 // OneMinusSrcAlpha _ZWrite ("ZWrite", Int) = 1 // On _ZTest ("ZTest", Int) = 4 // LEqual _Cull ("Cull", Int) = 0 // Off _ZBias ("ZBias", Float) = 0.0 } SubShader { Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } Pass { Blend [_SrcBlend] [_DstBlend] ZWrite [_ZWrite] ZTest [_ZTest] Cull [_Cull] Offset [_ZBias], [_ZBias] CGPROGRAM #pragma vertex vert #pragma fragment frag // #pragma target 2.0 // #pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 texcoord : TEXCOORD0; }; struct v2f { float4 vertex : SV_POSITION; float2 texcoord : TEXCOORD0; }; sampler2D _MainTex; float4 _MainTex_ST; UNITY_DECLARE_DEPTH_TEXTURE(_LastCameraDepthTexture); v2f vert(appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex); return o; } fixed4 frag(v2f i, out float outDepth : SV_Depth) : SV_Target { outDepth = SAMPLE_DEPTH_TEXTURE(_LastCameraDepthTexture, i.texcoord); return tex2D(_MainTex, i.texcoord); } ENDCG } } } <|start_filename|>Assets/Shaders/Mandelbulb.shader<|end_filename|> Shader "Ray Marching/Mandelbulb" { Properties { [Header(Main Maps)] [Space] _Tint ("Albedo", Color) = (1.0, 1.0, 1.0) [Gamma] _Metallic ("Metallic", Range(0, 1)) = 0.0 _Smoothness ("Smoothness", Range(0, 1)) = 0.5 [Header(Mandelbulb Parameters)] [Space] _Iterations ("Iterations", Int) = 10 _Power ("Power", Int) = 8 _EscapeRadius ("Escape Radius", Float) = 2.0 _Scale ("Scale", Float) = 0.4 [Header(Ray Marching Options)] [Space] _Tolerance ("Tolerance", Float) = 0.001 [Toggle] _RelativeTolerance ("Relative Tolerance", Float) = 1.0 _MaxDistance ("Max. Distance", Float) = 1000.0 _MaxSteps ("Max. Steps", Int) = 100 [Space] [KeywordEnum(Fast, Forward, Centered, Tetrahedron)] _NormalApproxMode ("Normal Approx. Mode", Float) = 0.0 _NormalApproxStep ("Normal Approx. Step", Float) = 0.001 [Toggle] _NormalFiltering ("Normal Filtering", Float) = 1.0 [Space] [Toggle] _AmbientOcclusion ("Ambient Occlusion", Float) = 1.0 _AmbientOcclusionMultiplier ("Ambient Occlusion Multiplier", Float) = 1.0 _AmbientOcclusionStep ("Ambient Occlusion Step", Float) = 0.1 _AmbientOcclusionSamples ("Ambient Occlusion Samples", Int) = 5 [Space] [KeywordEnum(None, Hard, Soft)] _ShadowMode ("Shadow Mode", Float) = 0.0 _SoftShadowFactor ("Soft Shadow Factor", Float) = 1.0 } CGINCLUDE #include "RayMarchingSDF.cginc" int _Iterations; int _Power; float _EscapeRadius; float _Scale; float SDF(float3 pos) { if (length(pos) > 1) { return Sphere(pos, 0, 0.5); } pos = pos/_Scale; float3 z = pos; float dr = 1.0; float r = 0.0; for (int i = 0; i < _Iterations; ++i) { // Convert to polar coordinates r = length(z); if (r > _EscapeRadius) break; float theta = acos(z.y/r); float phi = atan2(z.z,z.x); dr = pow(r, _Power - 1.0) * _Power * dr + 1.0; // Scale and rotate the point float zr = pow(r, _Power); theta = theta * _Power; phi = phi * _Power; // Convert back to cartesian coordinates z = zr * float3(sin(theta)*cos(phi), cos(theta), sin(phi)*sin(theta)); z += pos; } return _Scale * 0.5 * log(r) * r / dr; } ENDCG SubShader { Tags { "Queue"="AlphaTest" } Pass { Tags { "LightMode" = "ForwardBase" } Cull Front CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma vertex vert #pragma fragment fragBase #include "RayMarching.cginc" ENDCG } Pass { Tags { "LightMode" = "ForwardAdd" } Cull Front ZWrite Off Blend One One CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma multi_compile_fwdadd #pragma vertex vert #pragma fragment fragAdd #include "RayMarching.cginc" ENDCG } Pass { Tags { "LightMode" = "ShadowCaster" } Cull Front CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma multi_compile_fwdadd #pragma vertex vert #pragma fragment fragShadowCaster #include "RayMarching.cginc" ENDCG } } } <|start_filename|>Assets/Scripts/PlayerController.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerController : MonoBehaviour { public float speed; float m_pitchInput; float m_rollInput; float m_yawInput; Vector3 m_moveInput; void OnPitch(InputValue value) { m_pitchInput = value.Get<float>(); } void OnRoll(InputValue value) { m_rollInput = value.Get<float>(); } void OnYaw(InputValue value) { m_yawInput = value.Get<float>(); } void OnHorizontal(InputValue value) { m_moveInput.x = value.Get<Vector2>().x; m_moveInput.z = value.Get<Vector2>().y; } void OnVertical(InputValue value) { m_moveInput.y = value.Get<float>(); } void Update() { Quaternion deltaRotation = Quaternion.identity; deltaRotation *= Quaternion.AngleAxis(0.1f * m_yawInput, transform.up); deltaRotation *= Quaternion.AngleAxis(0.1f * -m_pitchInput, transform.right); deltaRotation *= Quaternion.AngleAxis(1.0f * -m_rollInput, transform.forward); transform.localRotation = deltaRotation * transform.localRotation; Vector3 deltaPosition = Vector2.zero; deltaPosition += speed * Time.deltaTime * m_moveInput.x * transform.right; deltaPosition += 0.5f * speed * Time.deltaTime * m_moveInput.y * transform.up; deltaPosition += speed * Time.deltaTime * m_moveInput.z * transform.forward; transform.localPosition += deltaPosition; } } <|start_filename|>Assets/Shaders/SierpinskiPyramid.shader<|end_filename|> Shader "Ray Marching/Sierpinski Pyramid" { Properties { [Header(Main Maps)] [Space] _Tint ("Albedo", Color) = (1.0, 1.0, 1.0) [Gamma] _Metallic ("Metallic", Range(0, 1)) = 0.0 _Smoothness ("Smoothness", Range(0, 1)) = 0.5 [Header(Sierpinski Pyramid Parameters)] [Space] _Iterations ("Iterations", Int) = 10 [Header(Ray Marching Options)] [Space] _Tolerance ("Tolerance", Float) = 0.001 [Toggle] _RelativeTolerance ("Relative Tolerance", Float) = 1.0 _MaxDistance ("Max. Distance", Float) = 1000.0 _MaxSteps ("Max. Steps", Int) = 100 [Space] [KeywordEnum(Fast, Forward, Centered, Tetrahedron)] _NormalApproxMode ("Normal Approx. Mode", Float) = 0.0 _NormalApproxStep ("Normal Approx. Step", Float) = 0.001 [Toggle] _NormalFiltering ("Normal Filtering", Float) = 1.0 [Space] [Toggle] _AmbientOcclusion ("Ambient Occlusion", Float) = 1.0 _AmbientOcclusionMultiplier ("Ambient Occlusion Multiplier", Float) = 1.0 _AmbientOcclusionStep ("Ambient Occlusion Step", Float) = 0.1 _AmbientOcclusionSamples ("Ambient Occlusion Samples", Int) = 5 [Space] [KeywordEnum(None, Hard, Soft)] _ShadowMode ("Shadow Mode", Float) = 0.0 _SoftShadowFactor ("Soft Shadow Factor", Float) = 1.0 } CGINCLUDE #include "RayMarchingSDF.cginc" int _Iterations; float SDF(float3 p) { for (int i = 0; i < _Iterations; ++i) { p = Fold(p, normalize(float3(1, 1, 0))); p = Fold(p, normalize(float3(1, 0, 1))); p = Fold(p, normalize(float3(0, 1, 1))); p = 2.0*p - 0.5; } return exp2(-_Iterations) * Tetrahedron(p, 0, 0.5); } ENDCG SubShader { Tags { "Queue"="AlphaTest" } Pass { Tags { "LightMode" = "ForwardBase" } Cull Front CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma vertex vert #pragma fragment fragBase #define FORWARD_BASE_PASS #include "RayMarching.cginc" ENDCG } Pass { Tags { "LightMode" = "ForwardAdd" } Cull Front ZWrite Off Blend One One CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma multi_compile_fwdadd #pragma vertex vert #pragma fragment fragBase #include "RayMarching.cginc" ENDCG } Pass { Tags { "LightMode" = "ShadowCaster" } Cull Front CGPROGRAM #pragma target 3.0 #pragma shader_feature_local _RELATIVETOLERANCE_ON #pragma shader_feature_local _NORMALFILTERING_ON #pragma shader_feature_local _AMBIENTOCCLUSION_ON #pragma shader_feature_local _SELFSHADOWS_ON #pragma multi_compile_local _NORMALAPPROXMODE_FAST _NORMALAPPROXMODE_FORWARD _NORMALAPPROXMODE_CENTERED _NORMALAPPROXMODE_TETRAHEDRON #pragma multi_compile_local _SHADOWMODE_NONE _SHADOWMODE_HARD _SHADOWMODE_SOFT #pragma multi_compile_fwdadd #pragma vertex vert #pragma fragment fragShadowCaster #include "RayMarching.cginc" ENDCG } } }
ConstantineRudenko/s3d-raymarcher
<|start_filename|>public/js/nwMAME.js<|end_filename|> var gui = require('nw.gui'); var win = gui.Window.get(); var cp = require('child_process'); var fs = require("fs"); //OS X Specific Window Menu if (process.platform === "darwin") { var mb = new gui.Menu({type:"menubar"}); mb.createMacBuiltin("nwMAME"); win.menu = mb; } //Disable any file to drag into application window window.addEventListener("dragover", function (e) { e = e || event; e.preventDefault(); }, false); window.addEventListener("drop", function (e) { e = e || event; e.preventDefault(); }, false); //All pre-defined application settings var excludedFiles = [".DS_Store", "Thumbs.db", ".", ".."], missingCoverImage = "public/img/noCoverSepia.jpg"; //Initial Semantic UI functions angular.element(document).ready(function () { angular.element('.ui.checkbox').checkbox(); angular.element('.ui.dropdown').dropdown(); }); //Global functions var posixizePath = function(path){ return path.split("\\").join("/"); }; //Start Angular part of main application var app = angular.module("nwMAME", ['ngAnimate']); app.factory("settingsStorage", function(){ return { readAllSettings: function (){ try{ var tempSet = JSON.parse(localStorage.getItem("appSettings")); if( tempSet !== null ) { return tempSet; } return {}; } catch(e){ return {}; } }, writeAllSettings: function (settingsObject) { localStorage.setItem("appSettings", JSON.stringify(settingsObject)); } }; }); app.directive("largeCover", function($timeout, settingsStorage){ return { restrict: "E", replace: true, scope:{ shortName: "@", fullName: "@" }, template: '<div class="nwMAME-largeGameItem" ng-dblclick="run(shortName)" title="{{::fullName}}"><div class="nwMAME-gameCover"></div><div class="nwMAME-gameTitle">{{::fullName}}</div></div>', link: function(scope, element){ var allSettings = settingsStorage.readAllSettings(); scope.run = function(name){ scope.$parent.runGame(name); }; var bck = 'url("' + missingCoverImage + '") #222222 no-repeat center center'; if( allSettings.hasOwnProperty("coverDirectory") && allSettings.hasOwnProperty("coverExtension") ){ var filePath = allSettings.coverDirectory + "/" + scope.shortName + allSettings.coverExtension; if (fs.existsSync(filePath)) { bck = 'url("' + filePath + '") #222222 no-repeat center center'; } } element[0].firstChild.style.background = bck; element[0].firstChild.style.backgroundSize = "cover"; } }; }); app.directive("squareCover", function($timeout, settingsStorage){ return { restrict: "E", replace: true, scope:{ shortName: "@", fullName: "@" }, template: '<div class="nwMAME-squareGameItem" ng-dblclick="run(shortName)" title="{{::fullName}}"><div class="nwMAME-gameCover"></div><div class="nwMAME-gameTitle">{{::fullName}}</div></div>', link: function(scope, element){ var allSettings = settingsStorage.readAllSettings(); scope.run = function(name){ scope.$parent.runGame(name); }; var bck = 'url("' + missingCoverImage + '") #222222 no-repeat center center'; if( allSettings.hasOwnProperty("coverDirectory") && allSettings.hasOwnProperty("coverExtension") ){ var filePath = allSettings.coverDirectory + "/" + scope.shortName + allSettings.coverExtension; if (fs.existsSync(filePath)) { bck = 'url("' + filePath + '") #222222 no-repeat center center'; } } element[0].firstChild.style.background = bck; element[0].firstChild.style.backgroundSize = "cover"; } }; }); app.directive("semanticToggle", function () { return { restrict: "E", require: "ngModel", transclude: true, replace: true, template: '<div class="ui toggle checkbox"><input type="checkbox"><label ng-transclude></label></div>', link: function (scope, element, attributes, controller) { var checked = false; var input = element.find('input'); element.on('click', function () { checked = !checked; controller.$setViewValue(checked); }); controller.$render = function() { checked = controller.$viewValue; if(checked){ angular.element(element).checkbox("set checked"); } else { angular.element(element).checkbox("set unchecked"); } }; } }; }); app.directive("fileSelector", function () { return { restrict: "A", require: "ngModel", link: function (scope, element, attributes, controller) { var fileInputElement = element.find("input[type=file]")[0]; fileInputElement.style.display = "none"; var oldValue = fileInputElement.value; fileInputElement.onchange = function () { if (fileInputElement.value === "") { controller.$setViewValue(posixizePath(oldValue)); scope.$apply(); } else { controller.$setViewValue(posixizePath(fileInputElement.value)); scope.$apply(); } }; element.on("click", function () { oldValue = fileInputElement.value; fileInputElement.click(); }); } }; }); app.controller('AppCtrl', function ($scope, $timeout, settingsStorage) { //Define app's initial variables $scope.settingState = "mame"; $scope.sessionLogs = []; //Private App Functions var settingsToScope = function(){ var allSettings = settingsStorage.readAllSettings(); $scope.userGames = (allSettings.hasOwnProperty("userGames")) ? allSettings.userGames : []; $scope.mameDirectory = (allSettings.hasOwnProperty("mameDirectory")) ? allSettings.mameDirectory : ""; $scope.mameExecutable = (allSettings.hasOwnProperty("mameExecutable")) ? allSettings.mameExecutable : ""; $scope.romsDirectory = (allSettings.hasOwnProperty("romsDirectory")) ? allSettings.romsDirectory : ""; $scope.biosDirectory = (allSettings.hasOwnProperty("biosDirectory")) ? allSettings.biosDirectory : ""; $scope.deviceDirectory = (allSettings.hasOwnProperty("deviceDirectory")) ? allSettings.deviceDirectory : ""; $scope.enableCheats = (allSettings.hasOwnProperty("enableCheats")) ? allSettings.enableCheats : false; $scope.cheatPath = (allSettings.hasOwnProperty("cheatPath")) ? allSettings.cheatPath : ""; $scope.mameWindow = (allSettings.hasOwnProperty("mameWindow")) ? allSettings.mameWindow : false; $scope.coverDirectory = (allSettings.hasOwnProperty("coverDirectory")) ? allSettings.coverDirectory : ""; $scope.coverExtension = (allSettings.hasOwnProperty("coverExtension")) ? allSettings.coverExtension : ".jpg"; $scope.coverSize = (allSettings.hasOwnProperty("coverSize")) ? allSettings.coverSize : "large"; }; //End of settingsToScope var scopeToSettings = function(){ var allSettings = { userGames: $scope.userGames, mameDirectory: $scope.mameDirectory, mameExecutable: $scope.mameExecutable, romsDirectory: $scope.romsDirectory, biosDirectory: $scope.biosDirectory, deviceDirectory: $scope.deviceDirectory, enableCheats: $scope.enableCheats, cheatPath: $scope.cheatPath, mameWindow: $scope.mameWindow, coverDirectory: $scope.coverDirectory, coverExtension: $scope.coverExtension, coverSize: $scope.coverSize }; settingsStorage.writeAllSettings(allSettings); }; //End of scopeToSettings var createMameCommand = function (gameName) { var commandSeperator = (process.platform === "darwin" || process.platform === "linux") ? ";":"&", pathSeperator = ";", cheatArg = "-cheat", windowArg = "-window", tempCmd = "cd "; tempCmd += '"' + $scope.mameDirectory + '"'; tempCmd += " " + commandSeperator + " "; tempCmd += '"' + $scope.mameExecutable + '"'; tempCmd += " "; tempCmd += gameName; tempCmd += " -rompath "; tempCmd += '"' + $scope.romsDirectory + pathSeperator + $scope.biosDirectory + pathSeperator + $scope.deviceDirectory + '"'; //Cheat part of command - optional if ($scope.enableCheats === true && $scope.cheatPath) { tempCmd += " -cheatpath "; tempCmd += '"' + $scope.cheatPath.replace(".7z", "") + '"'; tempCmd += " "; tempCmd += cheatArg; } //Window Mode part of command - optional if ($scope.mameWindow === true) { tempCmd += " "; tempCmd += windowArg; } return tempCmd; }; //End of createMameCommand var checkRequiredSettings = function () { return !!(fs.existsSync($scope.mameDirectory) && fs.existsSync($scope.mameExecutable) && fs.existsSync($scope.romsDirectory) && fs.existsSync($scope.biosDirectory) && fs.existsSync($scope.deviceDirectory)); }; //End of checkMandatorySettings var settingsModalOnDeny = function(){ //check required settings if(!checkRequiredSettings()){ if(!confirm("Are you sure? Some of required settings are not defined?\n\nRequired Settings :\n- Mame Output Directory\n- Mame Executable\n- Roms Directory\n- BIOS Directory\n- Device Directory")) { return false; } else { $scope.$apply(function(){ settingsToScope(); }); } } else { $scope.$apply(function(){ settingsToScope(); }); } }; //End of settingsModalOnDeny var settingsModalOnApprove = function(){ //check all settings if(checkRequiredSettings()){ $scope.$apply(function(){ scopeToSettings(); settingsToScope(); }); } else { alert("You should define all required settings!\n\nRequired Settings :\n- Mame Output Directory\n- Mame Executable\n- Roms Directory\n- BIOS Directory\n- Device Directory"); return false; } }; //End of settingsModalOnApprove //Public App Functions $scope.runGame = function (gameName) { if(checkRequiredSettings()){ //One more check for mame.ini file for proper execution var iniPath = $scope.mameExecutable.split("/"); iniPath.pop(); iniPath.push("mame.ini"); iniPath = iniPath.join("/"); if(!fs.existsSync(iniPath)){ var gameDimmer = angular.element(".nwMAME-gameRunning"); gameDimmer.dimmer({closable: false}).dimmer("show"); //Show game dimmer $timeout(function () { var fullCommand = createMameCommand(gameName); cp.exec(fullCommand, function (error, stdout, stderr) { if (stdout !== null && stdout !== "") { $scope.sessionLogs.unshift({ type: "stdout", output: stdout, process: gameName, date: Date.now() }); } if (stderr !== null && stderr !== "") { $scope.sessionLogs.unshift({ type: "stderr", output: stderr, process: gameName, date: Date.now() }); } if (error !== null && error !== "") { $scope.sessionLogs.unshift({ type: "error", output: error, process: gameName, date: Date.now() }); } gameDimmer.dimmer("hide"); //Hide game dimmer win.focus(); //Focus nwMAME window }); }, 1000); } else { alert( '"mame.ini" file has found next to mame executable!' + '\nYou should delete or rename "mame.ini" file to run games properly with nwMAME settings!' ); } } else { alert("Some of required settings are not valid. Please check settings window first!"); } }; //End of run $scope.settingsModal = function () { $scope.settingState = "mame"; angular.element(".nwMAME-settingsModal") .modal({ closable: false, transition: "fly down", onDeny: settingsModalOnDeny, onApprove: settingsModalOnApprove }) .modal("toggle"); }; //End of settingsModal $scope.updateLibrary = function () { if(checkRequiredSettings()){ alert("Update library process could take time and user interface is probably not going to respond your actions for a while!\n\nPlease be patient and wait until end of the process!"); cp.exec('"' + $scope.mameExecutable + '" -listfull', {maxBuffer: 10 * 1024 * 1024}, function (error, stdout, stderr) { if (stdout !== null && stdout !== "") { var re = /(\S+)\s+"(.+)"/gmi; var m; var tempAllGames = []; while ((m = re.exec(stdout)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } var tmpShort = m[1]; var tmpFull = m[2]; tempAllGames.push([tmpShort, tmpFull]); } //End of parsing all games list var readRomDir = fs.readdirSync($scope.romsDirectory); var tempFileArr = []; var tempGamesArr = []; angular.forEach(readRomDir, function (file) { var tempName = file.replace(".zip", ""); if (excludedFiles.indexOf(tempName) === -1) { tempFileArr.push(tempName); } }); //Prepare file names for comparison angular.forEach(tempAllGames, function(game){ if(tempFileArr.indexOf(game[0]) > -1){ tempGamesArr.push(game); } }); //Compare and add games to current library $scope.userGames = tempGamesArr; $scope.sessionLogs.unshift({ type: "stdout", output: "Library is updated!", process: "Update library", date: Date.now() }); alert("Your MAME library is updated!\nDon't forget the save your settings and have fun :)"); } //End of stdout if (stderr !== null && stderr !== "") { $scope.sessionLogs.unshift({ type: "stderr", output: stderr, process: "Refresh All Games", date: Date.now() }); } //End of stderr if (error !== null && error !== "") { $scope.sessionLogs.unshift({ type: "error", output: error, process: "Refresh All Games", date: Date.now() }); } //End of error }); } else { alert( "You have to define required settings first!" + "\n\nRequired Settings :" + "\n- Mame Output Directory" + "\n- Mame Executable" + "\n- Roms Directory" + "\n- BIOS Directory" + "\n- Device Directory" ); }//End of checkRequiredSettings }; //End of refreshGameList $scope.reloadApplication = function () { win.reloadIgnoringCache(); }; //End of reloadApplication $scope.openDevTools = function () { win.showDevTools(); }; //End of openDevTools $scope.openGithubPage = function(){ gui.Shell.openExternal('https://github.com/ozguncagri/nwMAME') }; //End of openGithubPage //Trigger initial app functions settingsToScope(); }); //End of AppCtrl
ozguncagri/nwMAME
<|start_filename|>jni/main/cflag.cpp<|end_filename|> /* * cflag.cpp * Trigger file to notify application a command finished * Created on: Oct 10, 2013 * Author: holmes */ #include <fcntl.h> #include <unistd.h> int main(int argc, char **args){ if (argc > 1){ char* file_path = args[1]; int fd = open(file_path, O_RDONLY); if (fd > 0){ close(fd); return 0; } return 2; } return 1; } <|start_filename|>library/src/main/java/z/hol/shellandroid/utils/ShellUtils.java<|end_filename|> package z.hol.shellandroid.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import z.hol.shellandroid.Shell; import z.hol.shellandroid.ShellAndroid; import android.util.Log; public class ShellUtils { public static void setChmod(String file, String mode){ try { Thread.sleep(10); if (ShellAndroid.DEBUG){ Log.d("ShellAndroid", "chmod start " + file + " mode " + mode); } // String cmd = "chmod " + mode + " " + file; ProcessBuilder pb = new ProcessBuilder("chmod", mode, file).directory(new File("/")) .redirectErrorStream(true); Process process = pb.start(); if (ShellAndroid.DEBUG){ Log.d("ShellAndroid", "chmod run " + file + " mode " + mode); } emptyInputStream(process.getInputStream()); //emptyInputStream(process.getErrorStream()); process.getOutputStream().close(); if (ShellAndroid.DEBUG){ Log.d("ShellAndroid", "chmod over " + file + " mode " + mode); } process.waitFor(); process.destroy(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); if (ShellAndroid.DEBUG){ Log.e("ShellAndroid", "chmod exception1 " + file + " mode " + mode); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); if (ShellAndroid.DEBUG){ Log.e("ShellAndroid", "chmod exception2 " + file + " mode " + mode); } } } /** * full out stream * @param in */ public static void emptyInputStream(final InputStream in){ Thread thread = new Thread(){ public void run() { if (in != null){ try { while (in.read() != -1){ } in.close(); } catch (IOException e) { // This is Auto-generated catch block e.printStackTrace(); } } } }; thread.setDaemon(true); thread.start(); } /** * Set file permission with a Shell * @param shell * @param file * @param mode */ public static void setChmod(Shell shell, String file, String mode){ if (shell != null){ shell.exec(false, "chmod " + mode + " " + file); } } } <|start_filename|>library/src/main/java/z/hol/shellandroid/Cpu.java<|end_filename|> package z.hol.shellandroid; /** * CPU information */ final class Cpu { public static final int CPU_ARM = 0; public static final int CPU_MIPS = 1; public static final int CPU_INTEL = 2; /** * get cpu type, {@link #CPU_ARM}, {@link #CPU_INTEL}, {@link #CPU_MIPS} * @return */ public static int getCpuType(){ int c = 0; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO){ int c1 = translateCputType(android.os.Build.CPU_ABI); int c2 = translateCputType(android.os.Build.CPU_ABI2); if (c1 != c2){ c = c1 != CPU_ARM ? c1 : c2; }else{ c = c1; } }else{ c = translateCputType(android.os.Build.CPU_ABI); } return c; } private static int translateCputType(String cpuAbi){ int c = 0; if ("armeabi".equals(cpuAbi)){ c = CPU_ARM; }else if ("x86".equals(cpuAbi)){ c = CPU_INTEL; }else if ("mips".equals(cpuAbi)){ c = CPU_MIPS; } return c; } } <|start_filename|>library/src/main/java/z/hol/shellandroid/utils/AssetUtils.java<|end_filename|> package z.hol.shellandroid.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.content.res.AssetManager; public class AssetUtils { /** * 释放Asset里面的文件 * @param context * @param fileName * @param checkFile 如果检测文件,则在文件存在的时候不进行释放 * @throws IOException */ public static void extractAsset(Context context, String fileName, boolean checkFile) throws IOException{ if (!checkFile || !isFileExist(context, fileName)){ AssetManager manager = context.getAssets(); InputStream in = manager.open(fileName); OutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE); BufferedOutputStream bout = new BufferedOutputStream(out); int iByte = -1; while ((iByte = in.read()) != -1){ bout.write(iByte); } bout.flush(); bout.close(); out.close(); in.close(); } } public static boolean isFileExist(Context context, String fileName){ File fileDir = context.getFilesDir(); File f = new File(fileDir, fileName); boolean exist = f.exists(); return exist; } } <|start_filename|>library/src/main/java/z/hol/shellandroid/ShellAndroid.java<|end_filename|> package z.hol.shellandroid; import android.content.Context; import android.os.FileObserver; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import z.hol.shellandroid.exception.ShellExecuteException; /** * A Shell of android * * @author holmes * */ public class ShellAndroid implements Shell { public static boolean DEBUG = false; public static final String TAG = "ShellAndroid"; public static final String CFLAG_TOOL_FILE_NAME = "cflag"; public static final String CFLAG_TOOL_X86_FILE_NAME = "cflag_x86"; public static final String FLAG_FILE_NAME = "flag_file"; public static final int STILL_RUNNING = -1024; public static final int PROCESS_NEVER_CREATED = -18030; public static final int UNKNOWN_USER_ID = -1024; private static final AtomicInteger FLAG_ID = new AtomicInteger(0); private Process mProcess; private InputStream mReadStream, mErrorStream; private OutputStream mWriteStream; private String mFlagFile; private String mFlagTrigger; private String mFlagCmd; private byte[] mCmdSeparator; private CmdTerminalObserver mTerminalObserver; private final byte[] mLock = new byte[0]; private final byte[] mTermLock = new byte[0]; private final AtomicBoolean mCmdAlreadyFinished = new AtomicBoolean(true); private StringBuilder mLastResultBuilder = new StringBuilder(512); private String mLastResult = null; private AtomicBoolean mHasRoot = new AtomicBoolean(false); private IdContext mIdContext; /** */ private boolean mCheckSu = true; /** Its closed */ private boolean mIsClosed = false; /** block mode */ private boolean mIsInBlockMode = true; private Chmod mChmod; /** cmd exec timeout */ private long mWaitTimeout = 0l; /** * Construct * @param chmod use to change cflag mode, * if it it null, the {@link DefaultChmod} will be used */ public ShellAndroid(Chmod chmod) { mCmdSeparator = " ; ".getBytes(); if (chmod == null){ chmod = new DefaultChmod(this); } mChmod = chmod; init(); } /** * Get current {@link Chmod} implementation associate with this Shell * @return */ public Chmod getChmod(){ return mChmod; } public void setCheckSu(boolean check){ mCheckSu = check; } /** * Set cmd wait timeout. * @param timeout 0 always wait. */ public void setWaitTimeout(long timeout){ mWaitTimeout = timeout; } public long getWaitTimeout(){ return mWaitTimeout; } /** * initialize command terminal flag tool * * @param context * @throws NullPointerException if context is null * @return */ public String initFlag(Context context) { if (context == null){ throw new NullPointerException("context can not be null"); } File flagFile = context.getFileStreamPath(FLAG_FILE_NAME + FLAG_ID.incrementAndGet()); if (!flagFile.exists()) { try { flagFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } File cFlag = null; AbsReleaser releaser = CFlagRelease.getReleaser(context); if (releaser != null){ try { cFlag = releaser.release(); } catch (Exception e) { e.printStackTrace(); mIsInBlockMode = false; } }else{ mIsInBlockMode = false; } if (cFlag != null){ mFlagTrigger = cFlag.getAbsolutePath(); mChmod.setChmod(mFlagTrigger, "777"); }else if (releaser != null){ String cflagName = releaser.getCFlagName(); cFlag = context.getFileStreamPath(cflagName); mFlagTrigger = cFlag.getAbsolutePath(); mChmod.setChmod(mFlagTrigger, "777"); } return flagFile.getAbsolutePath(); } /** * initialize command terminal flag tool * with exist cflag * @param context * @param cFlag a exist cflag * @return */ public String initFlag(Context context, File cFlag){ File flagFile = context.getFileStreamPath(FLAG_FILE_NAME + FLAG_ID.incrementAndGet()); if (!flagFile.exists()) { try { flagFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if (cFlag != null){ mFlagTrigger = cFlag.getAbsolutePath(); }else{ mIsInBlockMode = false; } mChmod.setChmod(mFlagTrigger, "777"); return flagFile.getAbsolutePath(); } /** * initialize command terminal flag tool * with Android internal tool, not use cflag. * so if you don't want use(extract) cflag, you need call * this method instead of other initFlag methods * @param context * @return */ public String initFlagMinimum(Context context){ File flagFile = context.getFileStreamPath(FLAG_FILE_NAME + FLAG_ID.incrementAndGet()); if (!flagFile.exists()) { try { flagFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } mFlagTrigger = "cat"; return flagFile.getAbsolutePath(); } /** * set command terminal flag file, which triggered by flag tool * * @param file */ public void setFlagFile(String file) { mFlagFile = file; mFlagCmd = mFlagTrigger + " " + mFlagFile; if (DEBUG){ Log.d(TAG, "flag cmd: " + mFlagCmd); } if (mTerminalObserver != null) { mTerminalObserver.stopWatching(); } mTerminalObserver = new CmdTerminalObserver(mFlagFile); mTerminalObserver.startWatching(); } private void init() { String initCommand = "/system/bin/sh"; try { ProcessBuilder pb = new ProcessBuilder(initCommand).redirectErrorStream(true); pb.directory(new File("/")); Process process = pb.start(); mProcess = process; mReadStream = process.getInputStream(); mErrorStream = process.getErrorStream(); mWriteStream = process.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mIsClosed = false; } /** * Block mode. only in block mode, can get cmds result. * @see #getLastResult() * @return */ public boolean isInBlockMode(){ return mIsInBlockMode; } @Override public boolean close() { mIsClosed = true; if (mProcess != null) { try { mReadStream.close(); mErrorStream.close(); mWriteStream.close(); } catch (IOException e) { e.printStackTrace(); } try { mProcess.destroy(); } catch (Exception e) { // This is Auto-generated catch block } if (DEBUG) { Log.d(TAG, "**Shell destroyed**"); } } if (mTerminalObserver != null) { // if has multi instance, the observer // will invalid for one of instance closeed mTerminalObserver.stopWatching(); //mTerminalObserver.close(); //mTerminalObserver = null; } synchronized (mLock) { mLock.notifyAll(); } return true; } @Override public boolean isClosed() { // This is Auto-generated method stub return mIsClosed; } @Override public boolean exec(boolean asRoot, String... arrParam) { execute(arrParam); return true; } @Override public void checkRoot() { if (!mHasRoot.get()) { int id = checkId(); if (id == 0 && (mIdContext == null || mIdContext.isRootRole())) { mHasRoot.set(true); return; } if (mCheckSu){ execute("su"); } id = checkId(); if (id == 0 && (mIdContext == null || mIdContext.isRootRole())) { mHasRoot.set(true); } } } @Override public boolean hasRoot() { return mHasRoot.get(); } @Override public boolean exitRoot() { if (hasRoot()) { execute("exit"); if (checkId() == 0) { // still root shell, // so exit it return exitRoot(); } mHasRoot.set(false); return true; } return false; } /** * Check the id of current user in the shell * @return */ public int checkId() { execute("id"); String idStrOrigin = getLastResult(); if (idStrOrigin != null){ idStrOrigin = idStrOrigin.trim(); } final String idStr = idStrOrigin; if (!TextUtils.isEmpty(idStr) && idStr.startsWith("uid=") && idStr.length() > 4) { // uid=0(root) gid=0(root) int endPos = idStr.indexOf('('); int id; if (endPos != -1){ try { id = Integer.valueOf(idStr.substring(4, endPos)); } catch (NumberFormatException e) { // This is Auto-generated catch block e.printStackTrace(); id = UNKNOWN_USER_ID; } }else{ // if "(" can not found. // so try to found first char which no a digit final int len = idStr.length(); int firstNoDigit = -1; for (int i = 4; i < len; i ++){ char ic = idStr.charAt(i); if (!Character.isDigit(ic)){ firstNoDigit = i; break; } } if (firstNoDigit != -1){ try { id = Integer.valueOf(idStr.substring(4, firstNoDigit)); } catch (NumberFormatException e) { // This is Auto-generated catch block e.printStackTrace(); id = UNKNOWN_USER_ID; } }else{ try { id = Integer.valueOf(idStr.substring(4)); } catch (NumberFormatException e) { // This is Auto-generated catch block e.printStackTrace(); id = UNKNOWN_USER_ID; } } } // for SELinux // Text "context=u:r:init:s0" at last of idStr int contextPos = idStr.lastIndexOf("context="); if (contextPos > -1){ // SELinux int contextEnd = idStr.indexOf(' ', contextPos); String contextStr; if (contextEnd == -1){ contextStr = idStr.substring(contextPos + 8); }else{ contextStr = idStr.substring(contextPos + 8, contextEnd); } if (DEBUG) Log.d(TAG, "" + contextStr); if (mIdContext == null){ mIdContext = new IdContext(contextStr); }else{ mIdContext.update(contextStr); } //if (DEBUG) Log.d(TAG, String.format("u:%s, r:%s, role:%s, s:%s", // mIdContext.getU(), mIdContext.getR(), mIdContext.getRoll(), mIdContext.getS())); } return id; } return UNKNOWN_USER_ID; } /** * Get id context, may null if no in SELinux * @return */ public IdContext getIdContext(){ return mIdContext; } /** * change file mode. * it probably only be used for chmod 777 cflg; * @param file * @param mode */ void chmodWithSh(String file, String mode){ String cmd = "chmod " + mode + " " + file; byte[] rawCmd = cmd.getBytes(); try { mWriteStream.write(rawCmd); mWriteStream.write(10); mWriteStream.flush(); try { Thread.sleep(100); } catch (InterruptedException e) { // It is Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { throw new ShellExecuteException("Input cmd error, Shell maybe closed. cmd: " + cmd, e); } } /** * internal execute * * @param cmds */ private void execute(String... cmds) { if (mIsInBlockMode){ mCmdAlreadyFinished.set(false); // below is for test // synchronized (mLock){ // if (!mCmdAlreadyFinished.get()){ // // wait for previous cmd finish // try { // mLock.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // mCmdAlreadyFinished.set(false); // } } for (int i = 0; i < cmds.length; i++) { String cmd = cmds[i].trim(); if (TextUtils.isEmpty(cmd)) { continue; } cmd = filterCmdEndChars(cmd); if (DEBUG) Log.d(TAG, "cmd: " + cmd); byte[] rawCmd = cmd.getBytes(); // clean the result for new command mLastResultBuilder.delete(0, mLastResultBuilder.length()); mLastResult = null; try { mWriteStream.write(rawCmd); //mWriteStream.write(10); //mWriteStream.flush(); // we will target notify flag twice // 1. for cmd terminal mWriteStream.write(mCmdSeparator); mWriteStream.write(mFlagCmd.getBytes()); mWriteStream.write(10); mWriteStream.flush(); if (mTerminalObserver != null) { // to optimize executing cmds batched // can be notify by terminal signal immediately // see #CmdTerminalObserver synchronized (mTermLock) { try { mTermLock.wait(100L); } catch (InterruptedException e) { e.printStackTrace(); } } }else { try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } } // 2. for the pipe of sh or su if (!mIsInBlockMode || !mCmdAlreadyFinished.get()) { mWriteStream.write(mFlagCmd.getBytes()); mWriteStream.write(10); mWriteStream.flush(); } } catch (IOException e) { throw new ShellExecuteException("Input cmd error, Shell maybe closed. cmd: " + cmd, e); } if (mIsInBlockMode){ synchronized (mLock) { if (!mCmdAlreadyFinished.get()) { // fix bug. for some reason, // unlock will happen before enter lock black try { if (mWaitTimeout > 0){ mLock.wait(mWaitTimeout); // for other thread exec cmd mLock.notifyAll(); }else { mLock.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } } } /** * filter some chars end of cmd. * like ";" * @return */ private String filterCmdEndChars(String cmd){ int len = cmd.length(); if (len > 0 && cmd.lastIndexOf(';') == len - 1){ String c = cmd.substring(0, len - 1); c = c.trim(); return filterCmdEndChars(c); } return cmd; } /** * Start collect command out put result */ public void printOutput() { Thread thread = new Thread(new OutputRunnable()); thread.setName("Shell output"); thread.start(); } /** * Command result out put runnable of thread * * @author holmes * */ private class OutputRunnable implements Runnable { @Override public void run() { InputStream input = mReadStream; if (input != null){ byte[] buff = new byte[4096]; int readed; try { while ((readed = input.read(buff)) > 0) { printBuff(buff, readed); } } catch (IOException e) { e.printStackTrace(); } }else{ Log.e(TAG, "Shell process may not created, InputStream is null"); } if (!mIsClosed){ // if no close // so some exception happend with sh close(); } if (DEBUG) { Log.d(TAG, "**over**"); } } private void printBuff(byte[] buff, int length) { String buffStr = new String(buff, 0, length); mLastResultBuilder.append(buffStr); if (DEBUG) Log.d(TAG, "~:" + buffStr); } } public int getExitValue() { if (mProcess != null) { try { return mProcess.exitValue(); } catch (IllegalThreadStateException e) { return STILL_RUNNING; } } return PROCESS_NEVER_CREATED; } /** * A observer for command finished * * @author holmes * */ private class CmdTerminalObserver extends FileObserver { @SuppressWarnings("unused") protected final String mWatchedFile; private boolean mIsClosed = false; public CmdTerminalObserver(String file) { super(file, OPEN); mWatchedFile = file; } @Override public void onEvent(int event, String path) { if (mIsClosed){ return; } // Log.d(TAG, mWatchedFile + " opened"); try { // just want to waiting output(ReadStream) result of last process be fully read Thread.sleep(15l); } catch (InterruptedException e) { e.printStackTrace(); } mLastResult = mLastResultBuilder.toString(); synchronized (mLock) { mLock.notify(); mCmdAlreadyFinished.set(true); } synchronized (mTermLock) { mTermLock.notify(); } if (DEBUG) { Log.d(TAG, "** cmd finish **"); } } /** * Close. for multi ShellAndroid instance */ public void close(){ mIsClosed = true; } } /** * Get last command result * @return */ public String getLastResult() { return mLastResult; } } <|start_filename|>library/src/main/java/z/hol/shellandroid/CFlagRelease.java<|end_filename|> package z.hol.shellandroid; import android.content.Context; import android.os.Build; /** * To release cflag file * Created by holmes on 11/21/14. */ public class CFlagRelease { private CFlagRelease(){ } /** * Get a releaser for cflag * @param context * @return */ public static AbsReleaser getReleaser(Context context){ final int sdk = Build.VERSION.SDK_INT; if (sdk >= 21){ // Lollipop return new LollipopReleaser(context); } return new NormalReleaser(context); } } <|start_filename|>jni/Application.mk<|end_filename|> APP_STL:=stlport_static APP_PLATFORM := android-5 APP_OPTIM := debug APP_ABI := armeabi armeabi-v7a x86 #APP_CPPFLAGS := -frtti -fexceptions <|start_filename|>jni/Android.mk<|end_filename|> LOCAL_PATH := $(call my-dir) # create cflg include $(CLEAR_VARS) MY_LOCAL_PATH := ${LOCAL_PATH} LOCAL_MODULE := cflag LOCAL_SRC_FILES := main/cflag.cpp LOCAL_LDLIBS := -llog include $(BUILD_EXECUTABLE) <|start_filename|>library/src/main/java/z/hol/shellandroid/Chmod.java<|end_filename|> package z.hol.shellandroid; /** * A interface to implement chmod cmd like "chmod 0777 file" * @author holmes * */ public interface Chmod { /** * like "chmod mode file" * @param file * @param mode * @return */ boolean setChmod(String file, String mode); } <|start_filename|>library/src/main/java/z/hol/shellandroid/DefaultChmod.java<|end_filename|> package z.hol.shellandroid; import android.util.Log; import z.hol.shellandroid.utils.ShellUtils; /** * Chmod implemented by Java Process * @author holmes * */ public final class DefaultChmod implements Chmod{ private ShellAndroid mShell; public DefaultChmod(){ mShell = null; } /** * Internal method * @param shell */ DefaultChmod(ShellAndroid shell){ mShell = shell; } @Override public boolean setChmod(String file, String mode) { // This is Auto-generated method stub if (mShell == null){ ShellUtils.setChmod(file, mode); }else{ if (ShellAndroid.DEBUG){ Log.d(ShellAndroid.TAG, "_chmod " + mode + " " + file); } try { mShell.chmodWithSh(file, mode); }catch (Exception e){ return false; } } return true; } } <|start_filename|>example/src/z/hol/shellandroid/example/MainActivity.java<|end_filename|> package z.hol.shellandroid.example; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import z.hol.shellandroid.ShellAndroid; /** * The example activity, and also for test * @author holmes * */ public class MainActivity extends Activity implements OnClickListener{ public static final String TAG = "ShellEg"; private TextView txtResult, txtCheckRoot, txtExitRoot, txtBatCmd; private EditText edtCmd; private ShellAndroid mShell; private boolean mUseMinimum = true; private String[] mBatCmds = new String[]{ "id", "cd", "pwd", "which su", "id", "date", "sync", "id", "ls -l", "echo 'this is last cmd for bat cmds'", "pwd", }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtCmd = (EditText) findViewById(R.id.edit); txtResult = (TextView) findViewById(R.id.text); txtResult.setMovementMethod(new ScrollingMovementMethod()); txtCheckRoot = (TextView) findViewById(R.id.check_root_result); txtExitRoot = (TextView) findViewById(R.id.exit_root_result); txtBatCmd = (TextView) findViewById(R.id.bat_exec_result); findViewById(R.id.execute).setOnClickListener(this); findViewById(R.id.check_root).setOnClickListener(this); findViewById(R.id.exit_root).setOnClickListener(this); findViewById(R.id.bat_exec).setOnClickListener(this); mBatCmds[1] = "cd /data/data/" + getPackageName(); //---- shell initialization ---- ShellAndroid.DEBUG = true; mShell = new ShellAndroid(null); String flagFile; if (!mUseMinimum){ flagFile = mShell.initFlag(getApplicationContext()); }else { flagFile = mShell.initFlagMinimum(getApplicationContext()); Toast.makeText(this, "Use minimum init flag", Toast.LENGTH_SHORT).show(); } mShell.printOutput(); mShell.setFlagFile(flagFile); //---- finish shell initialization ---- } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mShell != null){ mShell.close(); } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.execute: String cmd = edtCmd.getText().toString(); new ExecuteTask().execute(cmd); edtCmd.setText(""); edtCmd.requestFocus(); break; case R.id.check_root: new RootCheckTask(1).execute(); break; case R.id.exit_root: new RootCheckTask(2).execute(); break; case R.id.bat_exec: new BatExecuteTask().execute(mBatCmds); break; } } private class ExecuteTask extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub String cmd = params[0]; if (cmd.startsWith("0x")){ byte[] ascii = new byte[]{Integer.valueOf(cmd.substring(2), 16).byteValue()}; mShell.exec(false, new String(ascii)); }else{ mShell.exec(false, params); } return mShell.getLastResult(); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); if (!TextUtils.isEmpty(result)){ txtResult.setText(result); }else{ txtResult.setText("Empty result"); } } } private class BatExecuteTask extends AsyncTask<String, String, String>{ private ArrayList<String> mResults = new ArrayList<String>(16); @Override protected void onPreExecute() { super.onPreExecute(); findViewById(R.id.bat_exec).setEnabled(false); } @Override protected String doInBackground(String... params) { if (params != null && params.length > 0) { for (int i = 0; i < params.length; i ++) { mShell.exec(false, params[i]); publishProgress(String.valueOf(i+1), mShell.getLastResult()); } } return mShell.getLastResult(); } @Override protected void onProgressUpdate(String... values) { if (values != null && values.length > 0) { txtBatCmd.setText(String.format("%s cmd execed", values[0])); txtResult.setText(values[1]); mResults.add(values[1]); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); findViewById(R.id.bat_exec).setEnabled(true); if (!TextUtils.isEmpty(result)){ txtResult.setText(result); }else{ txtResult.setText("Empty result"); } Log.d(TAG, mResults.toString()); } } public class RootCheckTask extends AsyncTask<Void, Void, Boolean>{ private final int mTaskType; public RootCheckTask(int type) { // TODO Auto-generated constructor stub mTaskType = type; } @Override protected Boolean doInBackground(Void... params) { // TODO Auto-generated method stub if (mTaskType == 1){ mShell.checkRoot(); }else if (mTaskType == 2){ mShell.exitRoot(); } return mShell.hasRoot(); } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub super.onPostExecute(result); if (mTaskType == 1){ txtCheckRoot.setText(result.toString()); }else if (mTaskType == 2){ txtExitRoot.setText(result.toString()); } } } } <|start_filename|>library/src/main/java/z/hol/shellandroid/exception/ShellExecuteException.java<|end_filename|> package z.hol.shellandroid.exception; /** * The exception will throw when catch a exception on execute cmd in shell * @author holmes * */ public class ShellExecuteException extends RuntimeException{ /** * */ private static final long serialVersionUID = -6671955947677707880L; public ShellExecuteException() { super(); // This is Auto-generated constructor stub } public ShellExecuteException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); // This is Auto-generated constructor stub } public ShellExecuteException(String detailMessage) { super(detailMessage); // This is Auto-generated constructor stub } public ShellExecuteException(Throwable throwable) { super(throwable); // This is Auto-generated constructor stub } } <|start_filename|>library/src/main/java/z/hol/shellandroid/LollipopReleaser.java<|end_filename|> package z.hol.shellandroid; import android.content.Context; import android.content.res.AssetManager; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import z.hol.shellandroid.utils.AssetUtils; /** * release cflag file for Android 5.0, that with pie attr * Created by holmes on 11/21/14. */ public class LollipopReleaser extends AbsReleaser{ public static final String FLAG_TAG = "_21"; public static final String ASSET_NAME = "cflag_21"; /** * use #getContext method to get context * * @param context */ public LollipopReleaser(Context context) { super(context); } @Override public File release() throws IOException { Context context = getContext(); int cpuType = Cpu.getCpuType(); final String cflagName; if (cpuType == Cpu.CPU_INTEL){ cflagName = ShellAndroid.CFLAG_TOOL_X86_FILE_NAME; }else{ cflagName = ShellAndroid.CFLAG_TOOL_FILE_NAME; } final String fixedFlagName = cflagName + FLAG_TAG; if (!AssetUtils.isFileExist(context, fixedFlagName)){ // export AssetManager am = context.getAssets(); InputStream input = am.open(ASSET_NAME); ZipInputStream zip = new ZipInputStream(input); try { ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { String filename = ze.getName(); if (!filename.equals(fixedFlagName)){ continue; } OutputStream out = context.openFileOutput(fixedFlagName, Context.MODE_PRIVATE); BufferedOutputStream bout = new BufferedOutputStream(out); byte[] buffer = new byte[1024]; int count; while ((count = zip.read(buffer)) != -1) { bout.write(buffer, 0, count); } bout.flush(); bout.close(); out.close(); break; } } finally { zip.close(); } } File cFlag = context.getFileStreamPath(fixedFlagName); return cFlag; } @Override public String getCFlagName() { int cpuType = Cpu.getCpuType(); final String cflagName; if (cpuType == Cpu.CPU_INTEL){ cflagName = ShellAndroid.CFLAG_TOOL_X86_FILE_NAME; }else{ cflagName = ShellAndroid.CFLAG_TOOL_FILE_NAME; } final String fixedFlagName = cflagName + FLAG_TAG; return fixedFlagName; } } <|start_filename|>library/src/main/java/z/hol/shellandroid/NormalReleaser.java<|end_filename|> package z.hol.shellandroid; import android.content.Context; import java.io.File; import java.io.IOException; import z.hol.shellandroid.utils.AssetUtils; /** * Normal releaser for most android os * Created by holmes on 11/21/14. */ public class NormalReleaser extends AbsReleaser { /** * use #getContext method to get context * * @param context */ public NormalReleaser(Context context) { super(context); } @Override public File release() throws IOException { Context context = getContext(); int cpuType = Cpu.getCpuType(); final String cflagName; if (cpuType == Cpu.CPU_INTEL){ cflagName = ShellAndroid.CFLAG_TOOL_X86_FILE_NAME; }else{ cflagName = ShellAndroid.CFLAG_TOOL_FILE_NAME; } try { AssetUtils.extractAsset(context, cflagName, true); } catch (IOException e) { // e.printStackTrace(); // extra cflag error, so don't block the sh throw e; } File cFlag = context.getFileStreamPath(cflagName); return cFlag; } @Override public String getCFlagName() { int cpuType = Cpu.getCpuType(); final String cflagName; if (cpuType == Cpu.CPU_INTEL){ cflagName = ShellAndroid.CFLAG_TOOL_X86_FILE_NAME; }else{ cflagName = ShellAndroid.CFLAG_TOOL_FILE_NAME; } return cflagName; } } <|start_filename|>library/src/main/java/z/hol/shellandroid/Shell.java<|end_filename|> package z.hol.shellandroid; import z.hol.shellandroid.exception.ShellExecuteException; /** * A shell * @author holmes * */ public interface Shell { /** * The context data in result of "id" command * e.g uid=0(root) context=u:r:init:s0 * @author holmes * */ public static class IdContext{ public static final String ROOT_ROLE = "init".intern(); public static final String KERNEL_ROLE = "kernel".intern(); public static final String TOOLBOX_ROLE = "toolbox".intern(); String u; String r; String role; String s; IdContext(String contextStr) { update(contextStr); } /** * update informations * @param contextStr */ void update(String contextStr){ clean(); String[] splited = contextStr.split(":"); if (splited != null){ int len = splited.length; if (len > 0){ u = splited[0]; } if (len > 1){ r = splited[1]; } if (len > 2){ role = splited[2].intern(); } if (len > 3){ s = splited[3]; } } } void clean(){ u = null; r = null; role = null; s = null; } public String getU() { return u; } public String getR() { return r; } public String getRole() { return role; } public String getS() { return s; } public boolean isRootRole(){ return ROOT_ROLE.equals(role) || KERNEL_ROLE.equals(role) || TOOLBOX_ROLE.equals(role); } } /** * execute shell command * @param asRoot * @param arrParam * @exception ShellExecuteException */ public boolean exec(boolean asRoot, String... arrParam); /** * check root permission */ public void checkRoot(); /** * is rooted * @return */ public boolean hasRoot(); /** * exit root user * @return */ public boolean exitRoot(); /** * close the shell * @return */ public boolean close(); /** * It's closed * @return */ public boolean isClosed(); } <|start_filename|>library/src/main/java/z/hol/shellandroid/AbsReleaser.java<|end_filename|> package z.hol.shellandroid; import android.content.Context; import java.io.File; import java.io.IOException; /** * cflag releaser * Created by holmes on 11/21/14. */ public abstract class AbsReleaser { private Context mContext; /** * use #getContext method to get context * @param context */ public AbsReleaser(Context context){ mContext = context; } public Context getContext(){ return mContext; } /** * release cflag * @return The released cflag file * @throws IOException */ public abstract File release() throws IOException; /** * Get extracted cflag file name * @return */ public abstract String getCFlagName(); } <|start_filename|>library/src/main/java/z/hol/shellandroid/ShellChmod.java<|end_filename|> package z.hol.shellandroid; /** * Chmod implemented by shell.<br> * <pre> * sh -- chmod mode file * </pre> * @author holmes * */ public final class ShellChmod implements Chmod{ private Shell mShell; public ShellChmod(Shell shell) { // This is Auto-generated constructor stub mShell = shell; } @Override public boolean setChmod(String file, String mode) { // This is Auto-generated method stub if (mShell != null){ mShell.exec(false, "chmod " + mode + " " + file); return true; } return false; } }
holmeszyx/ShellAndroid
<|start_filename|>lib/weeaboo.js<|end_filename|> const { fetchJson, fetchText } = require('../tools/fetcher') const config = require('../config.json') /** * Get anime info from Kusonime. * @param {string} title * @returns {Promise<object>} */ const anime = (title) => new Promise((resolve, reject) => { console.log(`Get anime info from Kusonime for ${title}...`) fetchJson(`https://arugaz.herokuapp.com/api/kuso?q=${title}`) .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get manga info from Komiku. * @param {string} title * @returns {Promise<object>} */ const manga = (title) => new Promise((resolve, reject) => { console.log(`Get manga info from Komiku for ${title}...`) fetchJson(`https://arugaz.herokuapp.com/api/komiku?q=${title}`) .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get random waifu image. * @param {boolean} [nsfw=false] * @returns {Promise<object>} */ const waifu = (nsfw) => new Promise((resolve, reject) => { if (nsfw === true) { console.log('Get NSFW waifu image...') fetchJson('https://waifu.pics/api/nsfw/waifu') .then((result) => resolve(result)) .catch((err) => reject(err)) } else { console.log('Get SFW waifu image...') fetchJson('https://waifu.pics/api/sfw/waifu') .then((result) => resolve(result)) .catch((err) => reject(err)) } }) /** * Search for anime source from image. * @param {Buffer} imageBase64 * @returns {Promise<object>} */ const wait = (imageBase64) => new Promise((resolve, reject) => { console.log('Searching for anime source...') fetchJson('https://trace.moe/api/search', { method: 'POST', body: JSON.stringify({ image: imageBase64 }), headers: { 'Content-Type': 'application/json' } }) .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get Anitoki latest update. * @returns {Promise<object>} */ const anitoki = () => new Promise((resolve, reject) => { console.log('Get Anitoki latest update...') fetchJson(`https://melodicxt.herokuapp.com/api/anitoki?apiKey=${config.melodic}`) .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get Neonime latest update. * @returns {Promise<object>} */ const neonime = () => new Promise((resolve, reject) => { console.log('Get Neonime latest update...') fetchJson('https://enznoire.herokuapp.com/neolatest') .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get Anoboy anime on-going list. * @returns {Promise<object>} */ const anoboy = () => new Promise((resolve, reject) => { console.log('Get Anoboy on-going...') fetchJson(`https://api.vhtear.com/ongoinganoboy&apikey=${config.vhtear}`) .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get Random anime sticker * @returns {string} */ const snime = () => new Promise((resolve, reject) => { console.log('Get anime sticker...') fetchText('https://raw.githubusercontent.com/rashidsiregar28/data/main/animestick') .then((result) => resolve(result)) .catch((err) => reject(err)) }) /** * Get random video loli. * @returns {string} */ const loli = () => new Promise((resolve, reject) => { console.log('Get random video loli...') fetchText('https://raw.githubusercontent.com/AlvioAdjiJanuar/random/main/loli.txt') .then((result) => resolve(result)) .catch((err) => reject(err)) }) module.exports = { anime, manga, waifu, wait, anitoki, neonime, anoboy, snime, loli }
Not-NEO/BotNeo
<|start_filename|>demo/js/svg2ttfobject.js<|end_filename|> /** * @file svg2ttfobject.js * @author mengke01 * @date * @description * svg转ttfobject */ import svg2ttfobject from 'fonteditor-core/ttf/svg2ttfobject'; import ttf2base64 from 'fonteditor-core/ttf/ttf2base64'; import TTFWriter from 'fonteditor-core/ttf/ttfwriter'; let entry = { /** * 初始化 */ init() { $.ajax({ url: './test/fonteditor.svg', dataType: 'text' }).done(function (data) { let ttfObject = svg2ttfobject(data); let writer = new TTFWriter(); let ttfBuffer = writer.write(ttfObject); let base64str = ttf2base64(ttfBuffer); let saveBtn = $('.saveas'); saveBtn.attr('href', base64str); saveBtn.attr('download', 'save.ttf'); console.log(ttfObject); }); } }; entry.init(); <|start_filename|>src/ttf/svg/polygon2contour.js<|end_filename|> /** * @file 多边形转换成轮廓 * @author mengke01(<EMAIL>) */ import parseParams from './parseParams'; /** * 多边形转换成轮廓 * * @param {Array} points 多边形点集合 * @return {Array} contours */ export default function polygon2contour(points) { if (!points || !points.length) { return null; } const contours = []; const segments = parseParams(points); for (let i = 0, l = segments.length; i < l; i += 2) { contours.push({ x: segments[i], y: segments[i + 1], onCurve: true }); } return contours; } <|start_filename|>test/spec/ttf/ttf2symbol.spec.js<|end_filename|> /** * @file ttf2symbol * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {readData} from '../data'; import TTFReader from 'fonteditor-core/ttf/ttfreader'; import ttf2symbol from 'fonteditor-core/ttf/ttf2symbol'; describe('ttf to symbol', function () { let fontObject = new TTFReader().read(readData('baiduHealth.ttf')); let svg = ttf2symbol(fontObject); it('test genrate svg symbol', function () { assert.ok(svg.length > 1000); assert.equal(svg.match(/<symbol\s/g).length, 14); }); }); <|start_filename|>test/node-spec/readttf.spec.js<|end_filename|> /** * @file readttf * @author mengke01(<EMAIL>) */ const assert = require('assert'); const fs = require('fs'); const TTFReader = require('./fonteditor-core').TTFReader; const util = require('./util'); function readttf(file) { var data = fs.readFileSync(file); var buffer = util.toArrayBuffer(data); var ttfObject = new TTFReader().read(buffer); return ttfObject; } describe('readttf', function () { it('readttf', function () { let fontObject = readttf(__dirname + '/../data/bebas.ttf'); // test assert.ok(fontObject.name.fontFamily === 'Bebas', 'test readotf'); }); }); <|start_filename|>src/ttf/table/support-otf.js<|end_filename|> /** * @file otf字体格式支持的表 * @author mengke01(<EMAIL>) */ import head from './head'; import maxp from './maxp'; import cmap from './cmap'; import name from './name'; import hhea from './hhea'; import hmtx from './hmtx'; import post from './post'; import OS2 from './OS2'; import CFF from './CFF'; import GPOS from './GPOS'; import kern from './kern'; export default { head, maxp, cmap, name, hhea, hmtx, post, 'OS/2': OS2, CFF, GPOS, kern }; <|start_filename|>src/graphics/pathsUtil.js<|end_filename|> /** * @file 路径组变化函数 * @author mengke01(<EMAIL>) */ import {computePath} from './computeBoundingBox'; import pathAdjust from './pathAdjust'; import pathRotate from './pathRotate'; /** * 翻转路径 * * @param {Array} paths 路径数组 * @param {number} xScale x翻转 * @param {number} yScale y翻转 * @return {Array} 变换后的路径 */ function mirrorPaths(paths, xScale, yScale) { const {x, y, width, height} = computePath(...paths); if (xScale === -1) { paths.forEach(p => { pathAdjust(p, -1, 1, -x, 0); pathAdjust(p, 1, 1, x + width, 0); p.reverse(); }); } if (yScale === -1) { paths.forEach(p => { pathAdjust(p, 1, -1, 0, -y); pathAdjust(p, 1, 1, 0, y + height); p.reverse(); }); } return paths; } export default { /** * 旋转路径 * * @param {Array} paths 路径数组 * @param {number} angle 弧度 * @return {Array} 变换后的路径 */ rotate(paths, angle) { if (!angle) { return paths; } const bound = computePath(...paths); const cx = bound.x + (bound.width) / 2; const cy = bound.y + (bound.height) / 2; paths.forEach(p => { pathRotate(p, angle, cx, cy); }); return paths; }, /** * 路径组变换 * * @param {Array} paths 路径数组 * @param {number} x x 方向缩放 * @param {number} y y 方向缩放 * @return {Array} 变换后的路径 */ move(paths, x, y) { const bound = computePath(...paths); paths.forEach(path => { pathAdjust(path, 1, 1, x - bound.x, y - bound.y); }); return paths; }, mirror(paths) { return mirrorPaths(paths, -1, 1); }, flip(paths) { return mirrorPaths(paths, 1, -1); } }; <|start_filename|>src/ttf/util/bytes2base64.js<|end_filename|> /** * @file 二进制byte流转base64编码 * @author mengke01(<EMAIL>) */ /** * 二进制byte流转base64编码 * * @param {ArrayBuffer|Array} buffer ArrayBuffer对象 * @return {string} base64编码 */ export default function bytes2base64(buffer) { let str = ''; let length; let i; // ArrayBuffer if (buffer instanceof ArrayBuffer) { length = buffer.byteLength; const view = new DataView(buffer, 0, length); for (i = 0; i < length; i++) { str += String.fromCharCode(view.getUint8(i, false)); } } // Array else if (buffer.length) { length = buffer.length; for (i = 0; i < length; i++) { str += String.fromCharCode(buffer[i]); } } if (!str) { return ''; } return typeof btoa !== 'undefined' ? btoa(str) : Buffer.from(str, 'binary').toString('base64'); } <|start_filename|>test/spec/math/bezierCubic2Q2.spec.js<|end_filename|> /** * @file bezierCubic2Q2 * @author mengke01(<EMAIL>) */ import assert from 'assert'; import bezierCubic2Q2 from 'fonteditor-core/math/bezierCubic2Q2'; const p0 = { x: 50, y: 50 }; const c0 = { x: 80, y: 60 }; const c1 = { x: 60, y: 80 }; const p1 = { x: 100, y: 100 }; describe('Cubic bezier to quadratic bezier', function () { it('test c0=p0, c1 = p1sa', function () { let result = bezierCubic2Q2(p0, p0, p1, p1); assert.deepEqual(result[0], [ { x: 50, y: 50 }, { x: 75, y: 75 }, { x: 100, y: 100 } ]); assert.equal(result[1], null); }); it('normal', function () { let result = bezierCubic2Q2(p0, c0, c1, p1); assert.equal(result.length, 2); assert.deepEqual(result[0][1], { x: 69.0625, y: 57.8125 }); assert.deepEqual(result[0][2], { x: 71.25, y: 71.25 }); assert.deepEqual(result[0][2], result[1][0]); assert.deepEqual(result[1][1], { x: 73.4375, y: 84.6875 }); }); }); <|start_filename|>test/spec/ttf/otf2ttfobject.spec.js<|end_filename|> /** * @file otf2ttfobject * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {readData} from '../data'; import OTFReader from 'fonteditor-core/ttf/otfreader'; import otf2ttfobject from 'fonteditor-core/ttf/otf2ttfobject'; describe('otf to ttf object', function () { let fontObject = new OTFReader().read(readData('BalladeContour.otf')); let numGlyphs = fontObject.maxp.numGlyphs; let glyfContours = fontObject.glyf[3].contours.length; let glyfAdvanceWidth = fontObject.glyf[3].advanceWidth; let glyfLeftSideBearing = fontObject.glyf[3].leftSideBearing; let ttfObject = otf2ttfobject(fontObject); it('test otf2ttfobject', function () { assert.equal(ttfObject.version, 1); assert.equal(!!ttfObject.CFF, false); assert.equal(!!ttfObject.VORG, false); assert.equal(ttfObject.glyf.length, numGlyphs); assert.equal(ttfObject.glyf[3].contours.length, glyfContours); assert.equal(ttfObject.glyf[3].advanceWidth, glyfAdvanceWidth); assert.equal(ttfObject.glyf[3].leftSideBearing, glyfLeftSideBearing); }); }); <|start_filename|>demo/js/drawCanvas.js<|end_filename|> /** * @file 绘制canvas曲线 * @author mengke01(<EMAIL>) */ const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); function drawBezier(val) { let path = JSON.parse(val); ctx.clearRect(0, 0, 1000, 1000); ctx.beginPath(); ctx.fillStyle = 'black'; for (let i = 0; i < path.length; i++) { let cubic = path[i].map(function (p) { p.x = Math.round(p.x); p.y = Math.round(p.y); return p; }); if (i === 0) { ctx.moveTo(cubic[0].x, cubic[0].y); } // 退化成直线 if (cubic[0].x === cubic[1].x && cubic[0].y === cubic[1].y && cubic[2].x === cubic[3].x && cubic[2].y === cubic[3].y) { ctx.lineTo(cubic[2].x, cubic[2].y); } else { ctx.bezierCurveTo(cubic[1].x, cubic[1].y, cubic[2].x, cubic[2].y, cubic[3].x, cubic[3].y); } } ctx.fill(); } const entry = { /** * 初始化 */ init() { $('#textarea').on('change', e => { drawBezier(e.target.value); }); drawBezier($('#textarea').val()); } }; entry.init(); <|start_filename|>src/ttf/ttf2icon.js<|end_filename|> /** * @file ttf转icon * @author mengke01(<EMAIL>) */ import TTFReader from './ttfreader'; import error from './error'; import config from './data/default'; import {getSymbolId} from './ttf2symbol'; /** * listUnicode * * @param {Array} unicode unicode * @return {string} unicode string */ function listUnicode(unicode) { return unicode.map((u) => '\\' + u.toString(16)).join(','); } /** * ttf数据结构转icon数据结构 * * @param {ttfObject} ttf ttfObject对象 * @param {Object} options 选项 * @param {Object} options.metadata 字体相关的信息 * @param {Object} options.iconPrefix icon 前缀 * @return {Object} icon obj */ function ttfobject2icon(ttf, options = {}) { const glyfList = []; // glyf 信息 const filtered = ttf.glyf.filter((g) => g.name !== '.notdef' && g.name !== '.null' && g.name !== 'nonmarkingreturn' && g.unicode && g.unicode.length); filtered.forEach((g, i) => { glyfList.push({ code: '&#x' + g.unicode[0].toString(16) + ';', codeName: listUnicode(g.unicode), name: g.name, id: getSymbolId(g, i) }); }); return { fontFamily: ttf.name.fontFamily || config.name.fontFamily, iconPrefix: options.iconPrefix || 'icon', glyfList }; } /** * ttf格式转换成icon * * @param {ArrayBuffer|ttfObject} ttfBuffer ttf缓冲数组或者ttfObject对象 * @param {Object} options 选项 * @param {Object} options.metadata 字体相关的信息 * * @return {Object} icon object */ export default function ttf2icon(ttfBuffer, options = {}) { // 读取ttf二进制流 if (ttfBuffer instanceof ArrayBuffer) { const reader = new TTFReader(); const ttfObject = reader.read(ttfBuffer); reader.dispose(); return ttfobject2icon(ttfObject, options); } // 读取ttfObject else if (ttfBuffer.version && ttfBuffer.glyf) { return ttfobject2icon(ttfBuffer, options); } error.raise(10101); } <|start_filename|>test/node-spec/font.spec.js<|end_filename|> /** * @file font * @author mengke01(<EMAIL>) */ const assert = require('assert'); const fs = require('fs'); const Font = require('./fonteditor-core').Font; const woff2 = require('./fonteditor-core').woff2; const md5 = require('./util').md5; function readttf(file) { return fs.readFileSync(file); } describe('font', function () { this.timeout(2000); before(function (done) { woff2.init().then(() => done()); }); it('write ttf', function () { let buffer = readttf(__dirname + '/../data/bebas.ttf'); let font = Font.create(buffer, { type: 'ttf' }); assert.ok(font.data.name.fontFamily === 'Bebas', 'test read ttf'); let font2 = Font.create(buffer, { type: 'ttf' }); let ttfBuffer = font.write(); let ttfBuffer2 = font2.write(); assert.ok(md5(ttfBuffer) === md5(ttfBuffer2), 'test write stable'); }); it('write ttf', function () { let buffer = readttf(__dirname + '/../data/bebas.ttf'); let font = Font.create(buffer, { type: 'ttf' }); assert.ok(font.data.name.fontFamily === 'Bebas', 'test read ttf'); let font2 = Font.create(buffer, { type: 'ttf' }); let ttfBuffer = font.write(); let ttfBuffer2 = font2.write(); assert.ok(md5(ttfBuffer) === md5(ttfBuffer2), 'test write stable'); }); it('write eot', function () { let buffer = readttf(__dirname + '/../data/bebas.ttf'); let font = Font.create(buffer, { type: 'ttf' }); // 写eot let eotBuffer = font.write({ type: 'eot' }); assert.ok(eotBuffer.length, 'test write eot'); }); it('write woff', function () { let buffer = readttf(__dirname + '/../data/bebas.ttf'); let font = Font.create(buffer, { type: 'ttf' }); // 写woff let woffBuffer = font.write({ type: 'woff' }); assert.ok(woffBuffer, 'test write woff'); let font2 = Font.create(buffer, { type: 'ttf' }); let woffBuffer2 = font2.write({ type: 'woff' }); assert.ok(md5(woffBuffer) === md5(woffBuffer2), 'test write stable'); }); it('write woff2', function () { let buffer = readttf(__dirname + '/../data/bebas.ttf'); let font = Font.create(buffer, { type: 'ttf' }); // 写woff let woffBuffer = font.write({ type: 'woff2' }); assert.ok(woffBuffer, 'test write woff2'); let font2 = Font.create(buffer, { type: 'ttf' }); let woffBuffer2 = font2.write({ type: 'woff2' }); assert.ok(md5(woffBuffer) === md5(woffBuffer2), 'test write stable'); }); it('write svg', function () { let buffer = readttf(__dirname + '/../data/bebas.ttf'); let font = Font.create(buffer, { type: 'ttf' }); // 写svg let svg = font.write({ type: 'svg' }); assert.ok(svg.length, 'test write svg'); buffer = Buffer.from([65, 66, 67]); assert.ok(Font.toBase64(buffer) === 'QUJD', 'test buffer to toBase64'); buffer = new Int8Array([65, 66, 67]); assert.ok(Font.toBase64(buffer.buffer) === 'QUJD', 'test arraybuffer to toBase64'); }); }); <|start_filename|>src/ttf/enum/unicodeName.js<|end_filename|> /** * @file unicode 编码与postName对照表 * @author mengke01(<EMAIL>) * * see: * http://www.microsoft.com/typography/otspec/WGL4.htm */ export default { 0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 2, 10: 1, 11: 1, 12: 1, 13: 2, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 22: 1, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, 31: 1, 32: 3, 33: 4, 34: 5, 35: 6, 36: 7, 37: 8, 38: 9, 39: 10, 40: 11, 41: 12, 42: 13, 43: 14, 44: 15, 45: 16, 46: 17, 47: 18, 48: 19, 49: 20, 50: 21, 51: 22, 52: 23, 53: 24, 54: 25, 55: 26, 56: 27, 57: 28, 58: 29, 59: 30, 60: 31, 61: 32, 62: 33, 63: 34, 64: 35, 65: 36, 66: 37, 67: 38, 68: 39, 69: 40, 70: 41, 71: 42, 72: 43, 73: 44, 74: 45, 75: 46, 76: 47, 77: 48, 78: 49, 79: 50, 80: 51, 81: 52, 82: 53, 83: 54, 84: 55, 85: 56, 86: 57, 87: 58, 88: 59, 89: 60, 90: 61, 91: 62, 92: 63, 93: 64, 94: 65, 95: 66, 96: 67, 97: 68, 98: 69, 99: 70, 100: 71, 101: 72, 102: 73, 103: 74, 104: 75, 105: 76, 106: 77, 107: 78, 108: 79, 109: 80, 110: 81, 111: 82, 112: 83, 113: 84, 114: 85, 115: 86, 116: 87, 117: 88, 118: 89, 119: 90, 120: 91, 121: 92, 122: 93, 123: 94, 124: 95, 125: 96, 126: 97, 160: 172, 161: 163, 162: 132, 163: 133, 164: 189, 165: 150, 166: 232, 167: 134, 168: 142, 169: 139, 170: 157, 171: 169, 172: 164, 174: 138, 175: 218, 176: 131, 177: 147, 178: 242, 179: 243, 180: 141, 181: 151, 182: 136, 184: 222, 185: 241, 186: 158, 187: 170, 188: 245, 189: 244, 190: 246, 191: 162, 192: 173, 193: 201, 194: 199, 195: 174, 196: 98, 197: 99, 198: 144, 199: 100, 200: 203, 201: 101, 202: 200, 203: 202, 204: 207, 205: 204, 206: 205, 207: 206, 208: 233, 209: 102, 210: 211, 211: 208, 212: 209, 213: 175, 214: 103, 215: 240, 216: 145, 217: 214, 218: 212, 219: 213, 220: 104, 221: 235, 222: 237, 223: 137, 224: 106, 225: 105, 226: 107, 227: 109, 228: 108, 229: 110, 230: 160, 231: 111, 232: 113, 233: 112, 234: 114, 235: 115, 236: 117, 237: 116, 238: 118, 239: 119, 240: 234, 241: 120, 242: 122, 243: 121, 244: 123, 245: 125, 246: 124, 247: 184, 248: 161, 249: 127, 250: 126, 251: 128, 252: 129, 253: 236, 254: 238, 255: 186, 262: 253, 263: 254, 268: 255, 269: 256, 273: 257, 286: 248, 287: 249, 304: 250, 305: 215, 321: 226, 322: 227, 338: 176, 339: 177, 350: 251, 351: 252, 352: 228, 353: 229, 376: 187, 381: 230, 382: 231, 402: 166, 710: 216, 711: 225, 728: 219, 729: 220, 730: 221, 731: 224, 733: 223, 960: 155, 8211: 178, 8212: 179, 8216: 182, 8217: 183, 8218: 196, 8220: 180, 8221: 181, 8222: 197, 8224: 130, 8225: 194, 8226: 135, 8230: 171, 8240: 198, 8249: 190, 8250: 191, 8355: 247, 8482: 140, 8486: 159, 8706: 152, 8710: 168, 8719: 154, 8721: 153, 8722: 239, 8725: 188, 8729: 195, 8730: 165, 8734: 146, 8747: 156, 8776: 167, 8800: 143, 8804: 148, 8805: 149, 9674: 185, 61441: 192, 61442: 193, 64257: 192, 64258: 193, 65535: 0 // 0xFFFF指向.notdef }; <|start_filename|>demo/js/ttfmin.js<|end_filename|> /** * @file ttf字体缩减示例 * @author mengke01(<EMAIL>) */ import TTFReader from 'fonteditor-core/ttf/ttfreader'; import TTFWriter from 'fonteditor-core/ttf/ttfwriter'; import ttf2base64 from 'fonteditor-core/ttf/ttf2base64'; import TTF from 'fonteditor-core/ttf/ttf'; import * as lang from 'fonteditor-core/common/lang'; import string from 'fonteditor-core/common/string'; let curttfData = null; function onUpFileChange(e) { let file = e.target.files[0]; let reader = new FileReader(); reader.onload = function (e) { let ttfReader = new TTFReader({ hinting: true }); curttfData = ttfReader.read(e.target.result); ttfmin(); }; reader.onerror = function (e) { console.error(e); }; reader.readAsArrayBuffer(file); } function setFont(data, dom) { let tpl = '@font-face {' + 'font-family: \'${family}\';' + 'src: url(${data}) format(\'truetype\');}'; $(dom).get(0).innerHTML = string.format(tpl, data); } function ttfmin() { if (!curttfData) { return; } let text = $('#text').val(); let ttf = new TTF(lang.clone(curttfData)); let indexList = ttf.findGlyf({ unicode: text.split('').map(function (u) { return u.charCodeAt(0); }) }); if (indexList.length) { let glyfList = ttf.getGlyf(indexList); glyfList.unshift(ttf.getGlyfByIndex(0)); ttf.get().glyf = glyfList; } else { ttf.get().glyf = [ttf.getGlyfByIndex(0)]; } let family = 'font-with-hitting'; ttf.get().name.fontFamily = family; let writer = new TTFWriter({ hinting: true }); let buffer = writer.write(ttf.get()); setFont({ family: family, data: ttf2base64(buffer) }, '#' + family); family = 'font-without-hitting'; ttf.get().name.fontFamily = family; writer = new TTFWriter({ hinting: false }); buffer = writer.write(ttf.get()); setFont({ family: family, data: ttf2base64(buffer) }, '#' + family); $('.ttf-text').html(text); } let entry = { /** * 初始化 */ init() { document.getElementById('upload-file').addEventListener('change', onUpFileChange); document.getElementById('text').addEventListener('change', ttfmin); document.getElementById('font-size').addEventListener('change', function (e) { $('.ttf-text').css({ fontSize: e.target.value + 'px' }); }); } }; entry.init(); <|start_filename|>demo/index.html<|end_filename|> <!doctype html> <html> <head> <title>demo 目录</title> <script src="./demo/dep/pako_inflate.min.js"></script> </head> <body> <p>demo list </p> <ol> <li><a href="demo/bezierCubic2Q2.html">bezierCubic2Q2.html</a></li> <li><a href="demo/getArc.html">getArc.html</a></li> <li><a href="demo/glyfcanvas.html">glyfcanvas.html</a></li> <li><a href="demo/glyfsvg.html">glyfsvg.html</a></li> <li><a href="demo/otfreader.html">otfreader.html</a></li> <li><a href="demo/svg2contours.html">svg2contours.html</a></li> <li><a href="demo/svgimport.html">svgimport.html</a></li> <li><a href="demo/svgnode2contours.html">svgnode2contours.html</a></li> <li><a href="demo/svg2ttfobject.html">svg2ttfobject.html</a></li> <li><a href="demo/ttf2eot.html">ttf2eot.html</a></li> <li><a href="demo/ttf2svg.html">ttf2svg.html</a></li> <li><a href="demo/ttf2woff.html">ttf2woff.html</a></li> <li><a href="demo/ttfmin.html">ttfmin.html</a></li> <li><a href="demo/ttfparse.html">ttfparse.html</a></li> <li><a href="demo/ttfTableWriter.html">ttfTableWriter.html</a></li> <li><a href="demo/ttfwriter.html">ttfwriter.html</a></li> <li><a href="demo/woff2ttf.html">woff2ttf.html</a></li> <li><a href="demo/woff2.html">woff2.html</a></li> </ol> </body> </html> <|start_filename|>src/common/DOMParser.js<|end_filename|> /** * @file DOM解析器,兼容node端和浏览器端 * @author mengke01(<EMAIL>) */ /* eslint-disable no-undef */ export default typeof window !== 'undefined' && window.DOMParser ? window.DOMParser : require('xmldom').DOMParser; <|start_filename|>test/spec/ttf/ttfreader.spec.js<|end_filename|> /** * @file ttfreader * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {readData} from '../data'; import TTFReader from 'fonteditor-core/ttf/ttfreader'; describe('read ttf buffer', function () { let fontObject = new TTFReader().read(readData('baiduHealth.ttf')); it('test read ttf', function () { assert.equal(fontObject.version, 1); assert.equal(fontObject.numTables, 15); assert.equal(fontObject.rangeShift, 112); assert.equal(fontObject.searchRange, 128); }); it('test read ttf head', function () { assert.equal(fontObject.head.magickNumber, 1594834165); assert.equal(fontObject.head.unitsPerEm, 512); assert.equal(fontObject.head.checkSumAdjustment, 541516270); }); it('test read ttf name', function () { assert.equal(fontObject.name.fontFamily, 'baiduHealth'); assert.equal(fontObject.name.fontSubFamily, 'Regular'); assert.equal(fontObject.name.fullName, 'baiduHealth'); }); it('test read ttf post', function () { assert.equal(fontObject.post.format, 2); assert.equal(fontObject.post.underlinePosition, 0); assert.equal(fontObject.post.underlineThickness, 0); }); it('test read ttf hhea', function () { assert.equal(fontObject.hhea.advanceWidthMax, 682); assert.equal(fontObject.hhea.ascent, 480); assert.equal(fontObject.hhea.descent, -33); }); it('test read ttf maxp', function () { assert.equal(fontObject.maxp.version, 1); assert.equal(fontObject.maxp.numGlyphs, 17); }); it('test read ttf glyf', function () { assert.equal(fontObject.glyf[0].advanceWidth, 512); assert.equal(fontObject.glyf[0].leftSideBearing, 0); assert.equal(fontObject.glyf[0].name, '.notdef'); assert.equal(fontObject.glyf[3].contours[0].length, 31); assert.equal(fontObject.glyf[16].compound, true); assert.equal(fontObject.glyf[16].glyfs.length, 2); }); it('test read ttf cmap', function () { assert.equal(fontObject.cmap[0], 1); assert.equal(fontObject.cmap[57400], 16); }); }); describe('transform compound to simple', function () { let fontObject = new TTFReader({ compound2simple: true }).read(readData('baiduHealth.ttf')); it('test read ttf glyf', function () { assert.equal(!!fontObject.glyf[16].compound, false); assert.equal(!!fontObject.glyf[16].glyfs, false); assert.equal(fontObject.glyf[16].contours.length, 4); }); }); describe('read ttf hinting', function () { let fontObject = new TTFReader({ hinting: true }).read(readData('baiduHealth-hinting.ttf')); it('test read hinting', function () { assert.equal(fontObject.cvt.length, 24); assert.equal(fontObject.fpgm.length, 371); assert.equal(fontObject.prep.length, 204); assert.equal(fontObject.gasp.length, 8); assert.equal(fontObject.GPOS.length, 18); fontObject.kern && assert.equal(fontObject.kern.length, 8); }); }); describe('read ttf hinting GPOS kern', function () { let fontObject = new TTFReader({ hinting: true }).read(readData('baiduHealth-hinting.ttf')); it('test read hinting', function () { assert.equal(fontObject.cvt.length, 24); assert.equal(fontObject.fpgm.length, 371); assert.equal(fontObject.prep.length, 204); assert.equal(fontObject.gasp.length, 8); assert.equal(fontObject.GPOS.length, 18); }); }); describe('ttf subset', function () { let fontObject = new TTFReader({ subset: [ 65, 0xe003, 0xe00d ] }).read(readData('baiduHealth.ttf')); it('test read subset', function () { assert.equal(fontObject.glyf.length, 3); assert.equal(fontObject.glyf[0].name, '.notdef'); assert.equal(fontObject.glyf[1].unicode[0], 0xe003); assert.equal(fontObject.glyf[2].unicode[0], 0xe00d); assert.equal(fontObject.subsetMap, null); }); }); describe('ttf subset with compound', function () { let fontObject = new TTFReader({ subset: [ 65, 0x21, 0x22 ] }).read(readData('wingdings3.ttf')); it('test read hinting', function () { assert.equal(fontObject.glyf.length, 3); assert.equal(fontObject.glyf[0].name, '.notdef'); assert.equal(fontObject.glyf[1].unicode[0], 0x21); assert.equal(fontObject.glyf[1].compound, null); assert.equal(fontObject.glyf[2].unicode[0], 0x22); assert.equal(fontObject.glyf[2].contours.length, 1); assert.equal(fontObject.glyf[2].compound, null); assert.equal(fontObject.subsetMap, null); }); }); describe('read error ttf buffer', function () { it('test read version error', function () { assert.throws(function () { new TTFReader().read(new Uint8Array([0, 1, 0, 0, 25, 4, 11]).buffer); }); }); it('test read range error', function () { assert.throws(function () { new TTFReader().read(new Uint8Array([0, 1, 0, 0, 0, 10, 11, 45, 8]).buffer); }); }); }); <|start_filename|>demo/js/otfGlyf2Canvas.js<|end_filename|> /** * @file otf的glyf绘制 * @author mengke01(<EMAIL>) */ function drawPath(ctx, contour) { let curPoint; let nextPoint; let nextNextPoint; ctx.moveTo(contour[0].x, contour[0].y); for (let i = 1, l = contour.length; i < l; i++) { curPoint = contour[i]; if (curPoint.onCurve) { ctx.lineTo(curPoint.x, curPoint.y); } // 三次bezier曲线 else { nextPoint = contour[i + 1]; nextNextPoint = i === l - 2 ? contour[0] : contour[i + 2]; ctx.bezierCurveTo(curPoint.x, curPoint.y, nextPoint.x, nextPoint.y, nextNextPoint.x, nextNextPoint.y); i += 2; } } } /** * glyf canvas绘制 * * @param {Object} glyf glyf数据 * @param {CanvasRenderingContext2D} ctx canvas的context * @param {Object} options 绘制参数 */ export default function glyf2canvas(glyf, ctx, options = {}) { if (!glyf) { return; } ctx.save(); if (options.stroke) { ctx.strokeWidth = options.strokeWidth || 1; ctx.strokeStyle = options.strokeStyle || 'black'; } else { ctx.fillStyle = options.fillStyle || 'black'; } let scale = options.scale || 1; let i; let l; ctx.scale(scale, -scale); ctx.translate(0, -options.height); // 处理glyf轮廓 ctx.beginPath(); let contours = glyf.contours; for (i = 0, l = contours.length; i < l; i++) { if (contours[i].length) { drawPath(ctx, contours[i]); } } if (false !== options.stroke) { ctx.stroke(); } if (false !== options.fill) { ctx.fill(); } ctx.restore(); } <|start_filename|>src/ttf/eot2base64.js<|end_filename|> /** * @file eot数组转base64编码 * @author mengke01(<EMAIL>) */ import bytes2base64 from './util/bytes2base64'; /** * eot数组转base64编码 * * @param {Array} arrayBuffer ArrayBuffer对象 * @return {string} base64编码 */ export default function eot2base64(arrayBuffer) { return 'data:font/eot;charset=utf-8;base64,' + bytes2base64(arrayBuffer); } <|start_filename|>src/ttf/otf2base64.js<|end_filename|> /** * @file otf转bse64字体 * @author mengke01(<EMAIL>) */ import bytes2base64 from './util/bytes2base64'; /** * ttf 二进制转base64编码 * * @param {Array} arrayBuffer ArrayBuffer对象 * @return {string} base64编码 */ export default function ttf2base64(arrayBuffer) { return 'data:font/otf;charset=utf-8;base64,' + bytes2base64(arrayBuffer); } <|start_filename|>src/ttf/table/cmap/write.js<|end_filename|> /** * @file 写cmap表 * @author mengke01(<EMAIL>) */ /** * 创建`子表0` * * @param {Writer} writer 写对象 * @param {Array} unicodes unicodes列表 * @return {Writer} */ function writeSubTable0(writer, unicodes) { writer.writeUint16(0); // format writer.writeUint16(262); // length writer.writeUint16(0); // language // Array of unicodes 0..255 let i = -1; let unicode; while ((unicode = unicodes.shift())) { while (++i < unicode[0]) { writer.writeUint8(0); } writer.writeUint8(unicode[1]); i = unicode[0]; } while (++i < 256) { writer.writeUint8(0); } return writer; } /** * 创建`子表4` * * @param {Writer} writer 写对象 * @param {Array} segments 分块编码列表 * @return {Writer} */ function writeSubTable4(writer, segments) { writer.writeUint16(4); // format writer.writeUint16(24 + segments.length * 8); // length writer.writeUint16(0); // language const segCount = segments.length + 1; const maxExponent = Math.floor(Math.log(segCount) / Math.LN2); const searchRange = 2 * Math.pow(2, maxExponent); writer.writeUint16(segCount * 2); // segCountX2 writer.writeUint16(searchRange); // searchRange writer.writeUint16(maxExponent); // entrySelector writer.writeUint16(2 * segCount - searchRange); // rangeShift // end list segments.forEach((segment) => { writer.writeUint16(segment.end); }); writer.writeUint16(0xFFFF); // end code writer.writeUint16(0); // reservedPad // start list segments.forEach((segment) => { writer.writeUint16(segment.start); }); writer.writeUint16(0xFFFF); // start code // id delta segments.forEach((segment) => { writer.writeUint16(segment.delta); }); writer.writeUint16(1); // Array of range offsets, it doesn't matter when deltas present for (let i = 0, l = segments.length; i < l; i++) { writer.writeUint16(0); } writer.writeUint16(0); // rangeOffsetArray should be finished with 0 return writer; } /** * 创建`子表12` * * @param {Writer} writer 写对象 * @param {Array} segments 分块编码列表 * @return {Writer} */ function writeSubTable12(writer, segments) { writer.writeUint16(12); // format writer.writeUint16(0); // reserved writer.writeUint32(16 + segments.length * 12); // length writer.writeUint32(0); // language writer.writeUint32(segments.length); // nGroups segments.forEach((segment) => { writer.writeUint32(segment.start); writer.writeUint32(segment.end); writer.writeUint32(segment.startId); }); return writer; } /** * 写subtableheader * * @param {Writer} writer Writer对象 * @param {number} platform 平台 * @param {number} encoding 编码 * @param {number} offset 偏移 * @return {Writer} */ function writeSubTableHeader(writer, platform, encoding, offset) { writer.writeUint16(platform); // platform writer.writeUint16(encoding); // encoding writer.writeUint32(offset); // offset return writer; } /** * 写cmap表数据 * * @param {Object} writer 写入器 * @param {Object} ttf ttf对象 * @return {Object} 写入器 */ export default function write(writer, ttf) { const hasGLyphsOver2Bytes = ttf.support.cmap.hasGLyphsOver2Bytes; // write table header. writer.writeUint16(0); // version writer.writeUint16(hasGLyphsOver2Bytes ? 4 : 3); // count // header size const subTableOffset = 4 + (hasGLyphsOver2Bytes ? 32 : 24); const format4Size = ttf.support.cmap.format4Size; const format0Size = ttf.support.cmap.format0Size; // subtable 4, unicode writeSubTableHeader(writer, 0, 3, subTableOffset); // subtable 0, mac standard writeSubTableHeader(writer, 1, 0, subTableOffset + format4Size); // subtable 4, windows standard writeSubTableHeader(writer, 3, 1, subTableOffset); if (hasGLyphsOver2Bytes) { writeSubTableHeader(writer, 3, 10, subTableOffset + format4Size + format0Size); } // write tables, order of table seem to be magic, it is taken from TTX tool writeSubTable4(writer, ttf.support.cmap.format4Segments); writeSubTable0(writer, ttf.support.cmap.format0Segments); if (hasGLyphsOver2Bytes) { writeSubTable12(writer, ttf.support.cmap.format12Segments); } return writer; } <|start_filename|>src/ttf/table/gasp.js<|end_filename|> /** * @file gasp 表 * 对于需要hinting的字号需要这个表,否则会导致错误 * @author mengke01(<EMAIL>) * reference: https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gasp.html */ import table from './table'; export default table.create( 'gasp', [], { read(reader, ttf) { const length = ttf.tables.gasp.length; return reader.readBytes(this.offset, length); }, write(writer, ttf) { if (ttf.gasp) { writer.writeBytes(ttf.gasp, ttf.gasp.length); } }, size(ttf) { return ttf.gasp ? ttf.gasp.length : 0; } } ); <|start_filename|>demo/js/ttf2svg.js<|end_filename|> /** * @file ttf2woff.js * @author mengke01 * @date * @description * ttf2woff 转换 */ import ajaxFile from 'fonteditor-core/common/ajaxFile'; import ttf2svg from 'fonteditor-core/ttf/ttf2svg'; import svg2base64 from 'fonteditor-core/ttf/svg2base64'; import TTFReader from 'fonteditor-core/ttf/ttfreader'; import TTF from 'fonteditor-core/ttf/ttf'; // 设置字体 function setFont(base64str) { let str = '' + '@font-face {' + 'font-family:\'truetype\';' + 'src:url(' + base64str + ') format(\'svg\');' + '}'; document.getElementById('font-face').innerHTML = str; } // 查看ttf glyf function showTTFGlyf(ttfData) { let ttf = new TTF(ttfData); let codes = ttf.codes(); let str = ''; // 获取unicode字符 codes.forEach(function (item) { str += '<li data-code="' + item + '">' + '<span class="i-font">' + String.fromCharCode(item) + '</span>' + (item > 255 ? '\\u' + Number(item).toString(16) : item) + '</li>'; }); $('#font-list').html(str); } function write() { ajaxFile({ type: 'binary', url: './test/fonteditor.ttf', onSuccess(buffer) { let svgBuffer = ttf2svg(buffer, { metadata: 'fonteditor V0.1' }); let base64str = svg2base64(svgBuffer); setFont(base64str); let saveBtn = $('.saveas'); saveBtn.attr('href', base64str); saveBtn.attr('download', 'save.svg'); let ttfReader = new TTFReader(); let ttfData = ttfReader.read(buffer); showTTFGlyf(ttfData); }, onError() { console.error('error read file'); } }); } let entry = { /** * 初始化 */ init() { write(); } }; entry.init(); <|start_filename|>src/ttf/svg/parseTransform.js<|end_filename|> /** * @file 解析transform参数 * @author mengke01(<EMAIL>) */ import parseParams from './parseParams'; const TRANSFORM_REGEX = /(\w+)\s*\(([\d-.,\s]*)\)/g; /** * 解析transform参数 * * @param {string} str 参数字符串 * @return {Array} transform数组, 格式如下: * [ * { * name: 'scale', * params: [] * } * ] */ export default function parseTransform(str) { if (!str) { return false; } TRANSFORM_REGEX.lastIndex = 0; const transforms = []; let match; while ((match = TRANSFORM_REGEX.exec(str))) { transforms.push({ name: match[1], params: parseParams(match[2]) }); } return transforms; } <|start_filename|>demo/js/ttf2eot.js<|end_filename|> /** * @file ttf2eot.js * @author mengke01 * @date * @description * ttf2eot 转换 */ import ajaxFile from 'fonteditor-core/common/ajaxFile'; import eot2ttf from 'fonteditor-core/ttf/eot2ttf'; import ttf2base64 from 'fonteditor-core/ttf/ttf2base64'; import TTFReader from 'fonteditor-core/ttf/ttfreader'; import TTF from 'fonteditor-core/ttf/ttf'; // 设置字体 function setFont(base64str) { let str = '' + '@font-face {' + 'font-family:\'truetype\';' + 'src:url(' + base64str + ') format(\'truetype\');' + '}'; document.getElementById('font-face').innerHTML = str; } // 查看ttf glyf function showTTFGlyf(ttfData) { let ttf = new TTF(ttfData); let codes = ttf.codes(); let str = ''; // 获取unicode字符 codes.forEach(function (item) { str += '<li data-code="' + item + '">' + '<span class="i-font">' + String.fromCharCode(item) + '</span>' + (item > 255 ? '\\u' + Number(item).toString(16) : item) + '</li>'; }); $('#font-list').html(str); } function readeot() { ajaxFile({ type: 'binary', url: './test/fonteditor.eot', onSuccess(buffer) { let ttfBuffer = eot2ttf(buffer); let ttfReader = new TTFReader(); let ttfData = ttfReader.read(ttfBuffer); let base64str = ttf2base64(ttfBuffer); setFont(base64str); showTTFGlyf(ttfData); }, onError() { console.error('error read file'); } }); } let entry = { /** * 初始化 */ init() { readeot(); } }; entry.init(); <|start_filename|>src/ttf/font.js<|end_filename|> /** * @file 字体管理对象,处理字体相关的读取、查询、转换 * * @author mengke01(<EMAIL>) */ import bufferTool from '../nodejs/buffer'; import getEmptyttfObject from './getEmptyttfObject'; import TTF from './ttf'; import woff2ttf from './woff2ttf'; import otf2ttfobject from './otf2ttfobject'; import eot2ttf from './eot2ttf'; import svg2ttfobject from './svg2ttfobject'; import TTFReader from './ttfreader'; import TTFWriter from './ttfwriter'; import ttf2eot from './ttf2eot'; import ttf2woff from './ttf2woff'; import ttf2svg from './ttf2svg'; import ttf2symbol from './ttf2symbol'; import ttftowoff2 from './ttftowoff2'; import woff2tottf from './woff2tottf'; import ttf2base64 from './ttf2base64'; import eot2base64 from './eot2base64'; import woff2base64 from './woff2base64'; import svg2base64 from './svg2base64'; import bytes2base64 from './util/bytes2base64'; import woff2tobase64 from './woff2tobase64'; import optimizettf from './util/optimizettf'; // 必须是nodejs环境下的Buffer对象才能触发buffer转换 const SUPPORT_BUFFER = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined' && typeof Buffer === 'function'; export default class Font { /** * 字体对象构造函数 * * @param {ArrayBuffer|Buffer|string} buffer 字体数据 * @param {Object} options 读取参数 */ constructor(buffer, options = {type: 'ttf'}) { // 字形对象 if (typeof buffer === 'object' && buffer.glyf) { this.set(buffer); } // buffer else if (buffer) { this.read(buffer, options); } // 空 else { this.readEmpty(); } } /** * 创建一个空的ttfObject对象 * * @return {Font} */ readEmpty() { this.data = getEmptyttfObject(); return this; } /** * 读取字体数据 * * @param {ArrayBuffer|Buffer|string} buffer 字体数据 * @param {Object} options 读取参数 * @param {string} options.type 字体类型 * * ttf, woff , eot 读取配置 * @param {boolean} options.hinting 保留hinting信息 * @param {boolean} options.compound2simple 复合字形转简单字形 * * woff 读取配置 * @param {Function} options.inflate 解压相关函数 * * svg 读取配置 * @param {boolean} options.combinePath 是否合并成单个字形,仅限于普通svg导入 * @return {Font} */ read(buffer, options) { // nodejs buffer if (SUPPORT_BUFFER) { if (buffer instanceof Buffer) { buffer = bufferTool.toArrayBuffer(buffer); } } if (options.type === 'ttf') { this.data = new TTFReader(options).read(buffer); } else if (options.type === 'otf') { this.data = otf2ttfobject(buffer, options); } else if (options.type === 'eot') { buffer = eot2ttf(buffer, options); this.data = new TTFReader(options).read(buffer); } else if (options.type === 'woff') { buffer = woff2ttf(buffer, options); this.data = new TTFReader(options).read(buffer); } else if (options.type === 'woff2') { buffer = woff2tottf(buffer, options); this.data = new TTFReader(options).read(buffer); } else if (options.type === 'svg') { this.data = svg2ttfobject(buffer, options); } else { throw new Error('not support font type' + options.type); } this.type = options.type; return this; } /** * 写入字体数据 * * @param {Object} options 写入参数 * @param {string} options.type 字体类型, 默认 ttf * @param {boolean} options.toBuffer nodejs 环境中返回 Buffer 对象, 默认 true * * ttf 字体参数 * @param {boolean} options.hinting 保留hinting信息 * * svg,woff 字体参数 * @param {Object} options.metadata 字体相关的信息 * * woff 字体参数 * @param {Function} options.deflate 压缩相关函数 * @return {Buffer|ArrayBuffer|string} */ write(options = {}) { if (!options.type) { options.type = this.type; } let buffer = null; if (options.type === 'ttf') { buffer = new TTFWriter(options).write(this.data); } else if (options.type === 'eot') { buffer = new TTFWriter(options).write(this.data); buffer = ttf2eot(buffer, options); } else if (options.type === 'woff') { buffer = new TTFWriter(options).write(this.data); buffer = ttf2woff(buffer, options); } else if (options.type === 'woff2') { buffer = new TTFWriter(options).write(this.data); buffer = ttftowoff2(buffer, options); } else if (options.type === 'svg') { buffer = ttf2svg(this.data, options); } else if (options.type === 'symbol') { buffer = ttf2symbol(this.data, options); } else { throw new Error('not support font type' + options.type); } if (SUPPORT_BUFFER) { if (false !== options.toBuffer && buffer instanceof ArrayBuffer) { buffer = bufferTool.toBuffer(buffer); } } return buffer; } /** * 转换成 base64编码 * * @param {Object} options 写入参数 * @param {string} options.type 字体类型, 默认 ttf * 其他 options参数, 参考 write * @see write * * @param {ArrayBuffer} buffer 如果提供了buffer数据则使用 buffer数据, 否则转换现有的 font * @return {string} */ toBase64(options, buffer) { if (!options.type) { options.type = this.type; } if (buffer) { if (SUPPORT_BUFFER) { if (buffer instanceof Buffer) { buffer = bufferTool.toArrayBuffer(buffer); } } } else { options.toBuffer = false; buffer = this.write(options); } let base64Str; if (options.type === 'ttf') { base64Str = ttf2base64(buffer); } else if (options.type === 'eot') { base64Str = eot2base64(buffer); } else if (options.type === 'woff') { base64Str = woff2base64(buffer); } else if (options.type === 'woff2') { base64Str = woff2tobase64(buffer); } else if (options.type === 'svg') { base64Str = svg2base64(buffer); } else if (options.type === 'symbol') { base64Str = svg2base64(buffer, 'image/svg+xml'); } else { throw new Error('not support font type' + options.type); } return base64Str; } /** * 设置 font 对象 * * @param {Object} data font的ttfObject对象 * @return {this} */ set(data) { this.data = data; return this; } /** * 获取 font 数据 * * @return {Object} ttfObject 对象 */ get() { return this.data; } /** * 对字形数据进行优化 * * @param {Object} out 输出结果 * @param {boolean|Object} out.result `true` 或者有问题的地方 * @return {Font} */ optimize(out) { const result = optimizettf(this.data); if (out) { out.result = result; } return this; } /** * 将字体中的复合字形转为简单字形 * * @return {this} */ compound2simple() { const ttf = new TTF(this.data); ttf.compound2simple(); this.data = ttf.get(); return this; } /** * 对字形按照unicode编码排序 * * @return {this} */ sort() { const ttf = new TTF(this.data); ttf.sortGlyf(); this.data = ttf.get(); return this; } /** * 查找相关字形 * * @param {Object} condition 查询条件 * @param {Array|number} condition.unicode unicode编码列表或者单个unicode编码 * @param {string} condition.name glyf名字,例如`uniE001`, `uniE` * @param {Function} condition.filter 自定义过滤器 * @example * condition.filter(glyf) { * return glyf.name === 'logo'; * } * @return {Array} glyf字形列表 */ find(condition) { const ttf = new TTF(this.data); const indexList = ttf.findGlyf(condition); return indexList.length ? ttf.getGlyf(indexList) : indexList; } /** * 合并 font 到当前的 font * * @param {Object} font Font 对象 * @param {Object} options 参数选项 * @param {boolean} options.scale 是否自动缩放 * @param {boolean} options.adjustGlyf 是否调整字形以适应边界 * (和 options.scale 参数互斥) * * @return {Font} */ merge(font, options) { const ttf = new TTF(this.data); ttf.mergeGlyf(font.get(), options); this.data = ttf.get(); return this; } } /** * 读取字体数据 * * @param {ArrayBuffer|Buffer|string} buffer 字体数据 * @param {Object} options 读取参数 * @return {Font} */ Font.create = function (buffer, options) { return new Font(buffer, options); }; /** * base64序列化buffer 数据 * * @param {ArrayBuffer|Buffer|string} buffer 字体数据 * @return {Font} */ Font.toBase64 = function (buffer) { if (typeof buffer === 'string') { // node 环境中没有 btoa 函数 if (typeof btoa === 'undefined') { return Buffer.from(buffer, 'binary').toString('base64'); } return btoa(buffer); } return bytes2base64(buffer); }; <|start_filename|>src/ttf/woff2tottf.js<|end_filename|> /** * @file woff2 to ttf * @author mengke01(<EMAIL>) */ import woff2 from '../../woff2/index'; /** * ttf格式转换成woff2字体格式 * * @param {ArrayBuffer} woff2Buffer ttf缓冲数组 * @param {Object} options 选项 * * @return {ArrayBuffer} woff格式byte流 */ // eslint-disable-next-line no-unused-vars export default function woff2tottf(woff2Buffer, options = {}) { if (!woff2.isInited()) { throw new Error('use woff2.init() to init woff2 module!'); } const result = woff2.decode(woff2Buffer); return result.buffer; } /** * ttf格式转换成woff2字体格式 * * @param {ArrayBuffer} woff2Buffer ttf缓冲数组 * @param {Object} options 选项 * * @return {Promise.<ArrayBuffer>} woff格式byte流 */ export function woff2tottfasync(woff2Buffer, options = {}) { return woff2.init(options.wasmUrl).then(() => { const result = woff2.decode(woff2Buffer); return result.buffer; }); } <|start_filename|>test/data/bebas.ttf.js<|end_filename|> module.exports = require('./base642bytes')( require('fs').readFileSync(__dirname + '/bebas.ttf') ); <|start_filename|>test/spec/data.js<|end_filename|> /** * @file data reader * @author mengke01(<EMAIL>) */ import path from 'path'; import fs from 'fs'; const DATA_PATH = path.resolve(__dirname, '../data'); export function readData(filePath) { filePath = path.resolve(DATA_PATH, filePath); if (filePath.endsWith('.svg')) { return fs.readFileSync(filePath, 'utf8'); } let buffer = fs.readFileSync(filePath); let length = buffer.length; let view = new DataView(new ArrayBuffer(length), 0, length); for (let i = 0, l = length; i < l; i++) { view.setUint8(i, buffer[i], false); } return view.buffer; } <|start_filename|>test/node-spec/readotf.spec.js<|end_filename|> const assert = require('assert'); const fs = require('fs'); const OTFReader = require('./fonteditor-core').OTFReader; const util = require('./util'); function readotf(file) { var data = fs.readFileSync(file); var buffer = util.toArrayBuffer(data); var fontObject = new OTFReader().read(buffer); return fontObject; } describe('readotf', function () { it('readotf', function () { let fontObject = readotf(__dirname + '/../data/BalladeContour.otf'); // test assert.ok(fontObject.name.fontFamily === 'Ballade Contour', 'test readotf'); }); }); <|start_filename|>src/ttf/table/CFF.js<|end_filename|> /** * @file cff表 * @author mengke01(<EMAIL>) * * reference: * http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf * * modify from: * https://github.com/nodebox/opentype.js/blob/master/src/tables/cff.js */ import table from './table'; import string from '../util/string'; import encoding from './cff/encoding'; import cffStandardStrings from './cff/cffStandardStrings'; import parseCFFDict from './cff/parseCFFDict'; import parseCFFGlyph from './cff/parseCFFGlyph'; import parseCFFCharset from './cff/parseCFFCharset'; import parseCFFEncoding from './cff/parseCFFEncoding'; import Reader from '../reader'; /** * 获取cff偏移 * * @param {Reader} reader 读取器 * @param {number} offSize 偏移大小 * @param {number} offset 起始偏移 * @return {number} 偏移 */ function getOffset(reader, offSize) { let v = 0; for (let i = 0; i < offSize; i++) { v <<= 8; v += reader.readUint8(); } return v; } /** * 解析cff表头部 * * @param {Reader} reader 读取器 * @return {Object} 头部字段 */ function parseCFFHead(reader) { const head = {}; head.startOffset = reader.offset; head.endOffset = head.startOffset + 4; head.formatMajor = reader.readUint8(); head.formatMinor = reader.readUint8(); head.size = reader.readUint8(); head.offsetSize = reader.readUint8(); return head; } /** * 解析`CFF`表索引 * * @param {Reader} reader 读取器 * @param {number} offset 偏移 * @param {Funciton} conversionFn 转换函数 * @return {Object} 表对象 */ function parseCFFIndex(reader, offset, conversionFn) { if (offset) { reader.seek(offset); } const start = reader.offset; const offsets = []; const objects = []; const count = reader.readUint16(); let i; let l; if (count !== 0) { const offsetSize = reader.readUint8(); for (i = 0, l = count + 1; i < l; i++) { offsets.push(getOffset(reader, offsetSize)); } for (i = 0, l = count; i < l; i++) { let value = reader.readBytes(offsets[i + 1] - offsets[i]); if (conversionFn) { value = conversionFn(value); } objects.push(value); } } return { objects, startOffset: start, endOffset: reader.offset }; } // Subroutines are encoded using the negative half of the number space. // See type 2 chapter 4.7 "Subroutine operators". function calcCFFSubroutineBias(subrs) { let bias; if (subrs.length < 1240) { bias = 107; } else if (subrs.length < 33900) { bias = 1131; } else { bias = 32768; } return bias; } export default table.create( 'cff', [], { read(reader, font) { const offset = this.offset; reader.seek(offset); const head = parseCFFHead(reader); const nameIndex = parseCFFIndex(reader, head.endOffset, string.getString); const topDictIndex = parseCFFIndex(reader, nameIndex.endOffset); const stringIndex = parseCFFIndex(reader, topDictIndex.endOffset, string.getString); const globalSubrIndex = parseCFFIndex(reader, stringIndex.endOffset); const cff = { head }; // 全局子glyf数据 cff.gsubrs = globalSubrIndex.objects; cff.gsubrsBias = calcCFFSubroutineBias(globalSubrIndex.objects); // 顶级字典数据 const dictReader = new Reader(new Uint8Array(topDictIndex.objects[0]).buffer); const topDict = parseCFFDict.parseTopDict( dictReader, 0, dictReader.length, stringIndex.objects ); cff.topDict = topDict; // 私有字典数据 const privateDictLength = topDict.private[0]; let privateDict = {}; let privateDictOffset; if (privateDictLength) { privateDictOffset = offset + topDict.private[1]; privateDict = parseCFFDict.parsePrivateDict( reader, privateDictOffset, privateDictLength, stringIndex.objects ); cff.defaultWidthX = privateDict.defaultWidthX; cff.nominalWidthX = privateDict.nominalWidthX; } else { cff.defaultWidthX = 0; cff.nominalWidthX = 0; } // 私有子glyf数据 if (privateDict.subrs) { const subrOffset = privateDictOffset + privateDict.subrs; const subrIndex = parseCFFIndex(reader, subrOffset); cff.subrs = subrIndex.objects; cff.subrsBias = calcCFFSubroutineBias(cff.subrs); } else { cff.subrs = []; cff.subrsBias = 0; } cff.privateDict = privateDict; // 解析glyf数据和名字 const charStringsIndex = parseCFFIndex(reader, offset + topDict.charStrings); const nGlyphs = charStringsIndex.objects.length; if (topDict.charset < 3) { // @author: fr33z00 // See end of chapter 13 (p22) of #5176.CFF.pdf : // Still more optimization is possible by // observing that many fonts adopt one of 3 common charsets. In // these cases the operand to the charset operator in the Top DICT // specifies a predefined charset id, in place of an offset, as shown in table 22 cff.charset = cffStandardStrings; } else { cff.charset = parseCFFCharset(reader, offset + topDict.charset, nGlyphs, stringIndex.objects); } // Standard encoding if (topDict.encoding === 0) { cff.encoding = encoding.standardEncoding; } // Expert encoding else if (topDict.encoding === 1) { cff.encoding = encoding.expertEncoding; } else { cff.encoding = parseCFFEncoding(reader, offset + topDict.encoding); } cff.glyf = []; // only parse subset glyphs const subset = font.readOptions.subset; if (subset && subset.length > 0) { // subset map const subsetMap = { 0: true // 设置.notdef }; const codes = font.cmap; // unicode to index Object.keys(codes).forEach((c) => { if (subset.indexOf(+c) > -1) { const i = codes[c]; subsetMap[i] = true; } }); font.subsetMap = subsetMap; Object.keys(subsetMap).forEach((i) => { i = +i; const glyf = parseCFFGlyph(charStringsIndex.objects[i], cff, i); glyf.name = cff.charset[i]; cff.glyf[i] = glyf; }); } // parse all else { for (let i = 0, l = nGlyphs; i < l; i++) { const glyf = parseCFFGlyph(charStringsIndex.objects[i], cff, i); glyf.name = cff.charset[i]; cff.glyf.push(glyf); } } return cff; }, // eslint-disable-next-line no-unused-vars write(writer, font) { throw new Error('not support write cff table'); }, // eslint-disable-next-line no-unused-vars size(font) { throw new Error('not support get cff table size'); } } ); <|start_filename|>test/spec/main.spec.js<|end_filename|> /** * @file 单元测试入口 * @author mengke01(<EMAIL>) */ import assert from 'assert'; import fonteditor from 'fonteditor-core/main'; describe('main', function () { it('entries', function () { assert.ok(fonteditor.Font, 'exports'); assert.ok(fonteditor.TTF, 'exports'); assert.ok(fonteditor.TTFReader, 'exports'); assert.ok(fonteditor.TTFWriter, 'exports'); assert.ok(fonteditor.ttf2eot, 'exports'); assert.ok(fonteditor.eot2ttf, 'exports'); assert.ok(fonteditor.ttf2woff, 'exports'); assert.ok(fonteditor.woff2ttf, 'exports'); assert.ok(fonteditor.ttf2svg, 'exports'); assert.ok(fonteditor.svg2ttfobject, 'exports'); assert.ok(fonteditor.Reader, 'exports'); assert.ok(fonteditor.Writer, 'exports'); assert.ok(fonteditor.OTFReader, 'exports'); assert.ok(fonteditor.otf2ttfobject, 'exports'); assert.ok(fonteditor.ttf2base64, 'exports'); assert.ok(fonteditor.ttf2icon, 'exports'); assert.ok(fonteditor.ttftowoff2, 'exports'); assert.ok(fonteditor.woff2tottf, 'exports'); assert.ok(fonteditor.woff2, 'exports'); assert.ok(fonteditor.woff2.init, 'exports'); }); }); <|start_filename|>demo/css/reset.css<|end_filename|> * { margin: 0; padding: 0; } ul { list-style: none; } a { color: #03C; text-decoration: none; } a:hover { text-decoration: underline; } .hide { display: none; } <|start_filename|>woff2src/woff2.cpp<|end_filename|> // woff2 wasm binding #include <string> #include <vector> #include <woff2/decode.h> #include <woff2/encode.h> #include <emscripten.h> #include <emscripten/bind.h> using namespace emscripten; using std::string; std::vector<unsigned char> woff2_dec(string woff2buf, size_t bufSize) { const uint8_t *raw_input = reinterpret_cast<const uint8_t *>(woff2buf.data()); string output( std::min(woff2::ComputeWOFF2FinalSize(raw_input, woff2buf.size()),woff2::kDefaultMaxSize), 0); woff2::WOFF2StringOut out(&output); const bool ok = woff2::ConvertWOFF2ToTTF(raw_input, woff2buf.size(), &out); if (!ok) { const std::vector<uint8_t> empty; return empty; } const std::vector<uint8_t> uint8Arr(output.begin(), output.begin() + out.Size()); return uint8Arr; } std::vector<unsigned char> woff2_enc(string ttfbuf, size_t bufSize) { const uint8_t *raw_input = reinterpret_cast<const uint8_t *>(ttfbuf.data()); size_t outputLength = ttfbuf.size(); uint8_t *output = new uint8_t[outputLength]{0}; const bool ok = woff2::ConvertTTFToWOFF2(raw_input, ttfbuf.size(), output, &outputLength); if (!ok) { const std::vector<uint8_t> empty; return empty; } const std::vector<uint8_t> uint8Arr(output, output + outputLength); return uint8Arr; } EMSCRIPTEN_BINDINGS(woff2) { register_vector<uint8_t>("vector<uint8_t>"); function("woff2Dec", &woff2_dec); function("woff2Enc", &woff2_enc); } <|start_filename|>src/graphics/pathRotate.js<|end_filename|> /** * @file 路径旋转 * @author mengke01(<EMAIL>) */ /** * 对path坐标进行调整 * * @param {Object} contour 坐标点 * @param {number} angle 角度 * @param {number} centerX x偏移 * @param {number} centerY y偏移 * * @return {Object} contour 坐标点 */ export default function pathRotate(contour, angle, centerX, centerY) { angle = angle === undefined ? 0 : angle; const x = centerX || 0; const y = centerY || 0; const cos = Math.cos(angle); const sin = Math.sin(angle); let px; let py; let p; // x1=cos(angle)*x-sin(angle)*y; // y1=cos(angle)*y+sin(angle)*x; for (let i = 0, l = contour.length; i < l; i++) { p = contour[i]; px = cos * (p.x - x) - sin * (p.y - y); py = cos * (p.y - y) + sin * (p.x - x); p.x = px + x; p.y = py + y; } return contour; } <|start_filename|>demo/js/getArc.js<|end_filename|> /** * @file getArc.js * @author mengke01 * @date * @description * svg转ttfobject */ import contour2svg from 'fonteditor-core/ttf/util/contour2svg'; import getArc from 'fonteditor-core/graphics/getArc'; const entry = { /** * 初始化 */ init() { // 300,200 A150,50 0 1,0 450,50 let path = getArc(150, 150, 0, 1, 0, {x: 275, y:125}, {x:125, y:150}); console.log(path[0]); $('#path').attr('d', contour2svg(path)); } }; entry.init(); <|start_filename|>demo/js/bezierCubic2Q2.js<|end_filename|> /** * @file quadraticBezier.js * @author mengke01 * @date * @description * 三次贝塞尔转二次 */ import bezierCubic2Q2 from 'fonteditor-core/math/bezierCubic2Q2'; const entry = { /** * 初始化 */ init() { let canvas = $('#canvas').get(0); let ctx = canvas.getContext('2d'); let width = canvas.offsetWidth; let height = canvas.offsetHeight; let points = [ {x: 167, y: 449}, {x: 233, y: 331}, {x: 431, y: 332}, {x: 481, y: 417} ]; $(points).each(function (index, item) { $('[data-index=' + index + ']').css({ left: points[index].x, top: points[index].y }); }); let point; $('.point').on('mousedown', function (e) { point = $(this); }); $(document.body).on('mousemove', onMove); $(document.body).on('mouseup', function (e) { onMove.call(this, e); point = null; }); function onMove(e) { let px = e.pageX; let py = e.pageY; if (point) { point.css({ left: px, top: py }); let p = points[+point.attr('data-index')]; p.x = px; p.y = py; draw(); } } function draw() { ctx.clearRect(0, 0, width, height); // 绘制2次贝塞尔曲线 ctx.beginPath(); ctx.strokeStyle = 'red'; ctx.moveTo(points[0].x, points[0].y); ctx.bezierCurveTo( points[1].x, points[1].y, points[2].x, points[2].y, points[3].x, points[3].y ); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = 'blue'; bezierCubic2Q2.apply(null, points).forEach(function (bezier) { ctx.moveTo(bezier[0].x, bezier[0].y); ctx.quadraticCurveTo(bezier[1].x, bezier[1].y, bezier[2].x, bezier[2].y); }); ctx.stroke(); } draw(); } }; entry.init(); <|start_filename|>demo/js/svgimport.js<|end_filename|> /** * @file svgimport.js * @author mengke01 * @date * @description * svg转ttfobject */ import svg2ttfobject from 'fonteditor-core/ttf/svg2ttfobject'; let entry = { /** * 初始化 */ init() { $.ajax({ url: './test/iconfont-chunvzuo.svg', dataType: 'text' }).done(function (data) { let ttfObject = svg2ttfobject(data); console.log(ttfObject); }); } }; entry.init(); <|start_filename|>demo/js/ttfparse.js<|end_filename|> /** * @file ttfparse.js * @author mengke01 * @date * @description * ttf解析函数入口 */ import TTFReader from 'fonteditor-core/ttf/ttfreader'; import TTF from 'fonteditor-core/ttf/ttf'; import ajaxFile from 'fonteditor-core/common/ajaxFile'; function onUpFileChange(e) { let file = e.target.files[0]; let reader = new FileReader(); reader.onload = function (e) { let ttfReader = new TTFReader({ hinting: true // subset: [65, 0x160, 0x161, 0x162] }); let ttfData = ttfReader.read(e.target.result); console.log(ttfData); }; reader.onerror = function (e) { console.error(e); }; reader.readAsArrayBuffer(file); } let entry = { /** * 初始化 */ init() { let upFile = document.getElementById('upload-file'); upFile.addEventListener('change', onUpFileChange); ajaxFile({ type: 'binary', url: './test/tt0586m.ttf', onSuccess(binaryData) { let ttfReader = new TTFReader({ // hinting: true, subset: [65, 0x160, 0x161, 0x162] }); let ttfData = ttfReader.read(binaryData); console.log(ttfData); }, onError() { console.error('error read file'); } }); } }; entry.init(); <|start_filename|>src/ttf/ttfwriter.js<|end_filename|> /** * @file ttf写入器 * @author mengke01(<EMAIL>) */ import Writer from './writer'; import Directory from './table/directory'; import supportTables from './table/support'; import checkSum from './util/checkSum'; import error from './error'; // 支持写的表, 注意表顺序 const SUPPORT_TABLES = [ 'OS/2', 'cmap', 'glyf', 'head', 'hhea', 'hmtx', 'loca', 'maxp', 'name', 'post' ]; export default class TTFWriter { constructor(options = {}) { this.options = { hinting: options.hinting || false, // 不保留hints信息 support: options.support // 自定义的导出表结构,可以自己修改某些表项目 }; } /** * 处理ttf结构,以便于写 * * @param {ttfObject} ttf ttf数据结构 */ resolveTTF(ttf) { // 头部信息 ttf.version = ttf.version || 0x1; ttf.numTables = ttf.writeOptions.tables.length; ttf.entrySelector = Math.floor(Math.log(ttf.numTables) / Math.LN2); ttf.searchRange = Math.pow(2, ttf.entrySelector) * 16; ttf.rangeShift = ttf.numTables * 16 - ttf.searchRange; // 重置校验码 ttf.head.checkSumAdjustment = 0; ttf.head.magickNumber = 0x5F0F3CF5; if (typeof ttf.head.created === 'string') { ttf.head.created = /^\d+$/.test(ttf.head.created) ? +ttf.head.created : Date.parse(ttf.head.created); } if (typeof ttf.head.modified === 'string') { ttf.head.modified = /^\d+$/.test(ttf.head.modified) ? +ttf.head.modified : Date.parse(ttf.head.modified); } // 重置日期 if (!ttf.head.created) { ttf.head.created = Date.now(); } if (!ttf.head.modified) { ttf.head.modified = ttf.head.created; } const checkUnicodeRepeat = {}; // 检查是否有重复代码点 // 将glyf的代码点按小到大排序 ttf.glyf.forEach((glyf, index) => { if (glyf.unicode) { glyf.unicode = glyf.unicode.sort(); glyf.unicode.forEach((u) => { if (checkUnicodeRepeat[u]) { error.raise({ number: 10200, data: index }, index); } else { checkUnicodeRepeat[u] = true; } }); } }); } /** * 写ttf文件 * * @param {ttfObject} ttf ttf数据结构 * @return {ArrayBuffer} 字节流 */ dump(ttf) { // 用来做写入缓存的对象,用完后删掉 ttf.support = Object.assign({}, this.options.support); // head + directory let ttfSize = 12 + ttf.numTables * 16; let ttfHeadOffset = 0; // 记录head的偏移 // 构造tables ttf.support.tables = []; ttf.writeOptions.tables.forEach((tableName) => { const offset = ttfSize; const TableClass = supportTables[tableName]; const tableSize = new TableClass().size(ttf); // 原始的表大小 let size = tableSize; // 对齐后的表大小 if (tableName === 'head') { ttfHeadOffset = offset; } // 4字节对齐 if (size % 4) { size += 4 - size % 4; } ttf.support.tables.push({ name: tableName, checkSum: 0, offset, length: tableSize, size }); ttfSize += size; }); const writer = new Writer(new ArrayBuffer(ttfSize)); // 写头部 writer.writeFixed(ttf.version); writer.writeUint16(ttf.numTables); writer.writeUint16(ttf.searchRange); writer.writeUint16(ttf.entrySelector); writer.writeUint16(ttf.rangeShift); // 写表偏移 new Directory().write(writer, ttf); // 写支持的表数据 ttf.support.tables.forEach((table) => { const tableStart = writer.offset; const TableClass = supportTables[table.name]; new TableClass().write(writer, ttf); if (table.length % 4) { // 对齐字节 writer.writeEmpty(4 - table.length % 4); } // 计算校验和 table.checkSum = checkSum(writer.getBuffer(), tableStart, table.size); }); // 重新写入每个表校验和 ttf.support.tables.forEach((table, index) => { const offset = 12 + index * 16 + 4; writer.writeUint32(table.checkSum, offset); }); // 写入总校验和 const ttfCheckSum = (0xB1B0AFBA - checkSum(writer.getBuffer()) + 0x100000000) % 0x100000000; writer.writeUint32(ttfCheckSum, ttfHeadOffset + 8); delete ttf.writeOptions; delete ttf.support; const buffer = writer.getBuffer(); writer.dispose(); return buffer; } /** * 对ttf的表进行评估,标记需要处理的表 * * @param {Object} ttf ttf对象 */ prepareDump(ttf) { if (!ttf.glyf || ttf.glyf.length === 0) { error.raise(10201); } if (!ttf['OS/2'] || !ttf.head || !ttf.name) { error.raise(10204); } const tables = SUPPORT_TABLES.slice(0); ttf.writeOptions = {}; // hinting tables direct copy if (this.options.hinting) { ['cvt', 'fpgm', 'prep', 'gasp', 'GPOS', 'kern'].forEach((table) => { if (ttf[table]) { tables.push(table); } }); } ttf.writeOptions.hinting = !!this.options.hinting; ttf.writeOptions.tables = tables.sort(); } /** * 写一个ttf字体结构 * * @param {Object} ttf ttf数据结构 * @return {ArrayBuffer} 缓冲数组 */ write(ttf) { this.prepareDump(ttf); this.resolveTTF(ttf); const buffer = this.dump(ttf); return buffer; } /** * 注销 */ dispose() { delete this.options; } } <|start_filename|>demo/js/setFontface.js<|end_filename|> /** * @file setFontface.js * @author mengke01 * @date * @description * 设置fontface */ /** * 设置fontface的ttf字体 * * @param {name} name 字体名 * @param {string} ttfBase64 base64字体 * @param {string} styleId domId */ export default function setFontface(name, ttfBase64, styleId) { let str = '' + '@font-face {' + 'font-family:\'' + name + '\';' + 'src:url(' + ttfBase64 + ') format(\'truetype\');' + '}'; document.getElementById(styleId).innerHTML = str; } <|start_filename|>woff2src/build.js<|end_filename|> /** * @file nodejs build * @author mengke01(<EMAIL>) */ const fs = require('fs'); const content = fs.readFileSync('./woff2.js', 'utf-8'); const newContent = content.replace(/require\("([\w+/]+)"\)/g, ($0, $1) => { return 'require(["' + $1 + '"].join(""))'; }); fs.writeFileSync('./woff2.js', newContent); console.log('replace module done'); <|start_filename|>src/ttf/table/cmap.js<|end_filename|> /** * @file cmap 表 * @author mengke01(<EMAIL>) * * @see * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html */ import table from './table'; import parse from './cmap/parse'; import write from './cmap/write'; import sizeof from './cmap/sizeof'; export default table.create( 'cmap', [], { write, read: parse, size: sizeof } ); <|start_filename|>test/node-spec/svg2ttf.spec.js<|end_filename|> /** * @file svg2ttf * @author mengke01(<EMAIL>) */ const assert = require('assert'); const fs = require('fs'); const TTFWriter = require('./fonteditor-core').TTFWriter; const svg2ttfobject = require('./fonteditor-core').svg2ttfobject; const util = require('./util'); function getEmpty() { let data = fs.readFileSync(__dirname + '/empty.json'); return JSON.parse(data); } describe('svg2ttf', function () { it('svg2ttf', function () { let svg = fs.readFileSync(__dirname + '/../data/iconmoon.svg'); let emptyTTFObject = getEmpty(); let ttfObject = svg2ttfobject(String(svg)); emptyTTFObject.glyf = ttfObject.glyf; let ttfBuffer = new TTFWriter().write(emptyTTFObject); // test assert.ok(util.toBuffer(ttfBuffer).length, 'test svg2ttf'); }); }); <|start_filename|>test/spec/graphics/pathAdjust.spec.js<|end_filename|> /** * @file pathAdjust * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {clone} from 'fonteditor-core/common/lang'; import pathAdjust from 'fonteditor-core/graphics/pathAdjust'; const path = [ { x: 50, y: 50 }, { x: 100, y: 100 } ]; describe('adjust path by scale, rotate, translate', function () { it('test default', function () { let result = pathAdjust(clone(path)); assert.deepEqual(result, [ { x: 50, y: 50 }, { x: 100, y: 100 } ]); result = pathAdjust(clone(path), 1, 1); assert.deepEqual(result, [ { x: 50, y: 50 }, { x: 100, y: 100 } ]); result = pathAdjust(clone(path), 1, 1, 0, 0); assert.deepEqual(result, [ { x: 50, y: 50 }, { x: 100, y: 100 } ]); }); it('test scale', function () { let result = pathAdjust(clone(path), 2, 2); assert.deepEqual(result, [ { x: 100, y: 100 }, { x: 200, y: 200 } ]); result = pathAdjust(clone(path), 0.5, 1); assert.deepEqual(result, [ { x: 25, y: 50 }, { x: 50, y: 100 } ]); result = pathAdjust(clone(path), 1, 2, 0, 0); assert.deepEqual(result, [ { x: 50, y: 100 }, { x: 100, y: 200 } ]); }); it('test offset', function () { let result = pathAdjust(clone(path), 1, 1, 10, 10); assert.deepEqual(result, [ { x: 60, y: 60 }, { x: 110, y: 110 } ]); result = pathAdjust(clone(path), 2, 2, 10, 10); assert.deepEqual(result, [ { x: 120, y: 120 }, { x: 220, y: 220 } ]); }); }); <|start_filename|>src/ttf/table/maxp.js<|end_filename|> /** * @file maxp 表 * @author mengke01(<EMAIL>) */ import table from './table'; import struct from './struct'; export default table.create( 'maxp', [ ['version', struct.Fixed], ['numGlyphs', struct.Uint16], ['maxPoints', struct.Uint16], ['maxContours', struct.Uint16], ['maxCompositePoints', struct.Uint16], ['maxCompositeContours', struct.Uint16], ['maxZones', struct.Uint16], ['maxTwilightPoints', struct.Uint16], ['maxStorage', struct.Uint16], ['maxFunctionDefs', struct.Uint16], ['maxInstructionDefs', struct.Uint16], ['maxStackElements', struct.Uint16], ['maxSizeOfInstructions', struct.Uint16], ['maxComponentElements', struct.Uint16], ['maxComponentDepth', struct.Int16] ], { write(writer, ttf) { table.write.call(this, writer, ttf.support); return writer; }, size() { return 32; } } ); <|start_filename|>src/common/lang.js<|end_filename|> /** * @file 语言相关函数 * @author mengke01(<EMAIL>) */ export function isArray(obj) { return obj != null && toString.call(obj).slice(8, -1) === 'Array'; } export function isObject(obj) { return obj != null && toString.call(obj).slice(8, -1) === 'Object'; } export function isString(obj) { return obj != null && toString.call(obj).slice(8, -1) === 'String'; } export function isFunction(obj) { return obj != null && toString.call(obj).slice(8, -1) === 'Function'; } export function isDate(obj) { return obj != null && toString.call(obj).slice(8, -1) === 'Date'; } export function isEmptyObject(object) { for (const name in object) { // eslint-disable-next-line no-prototype-builtins if (object.hasOwnProperty(name)) { return false; } } return true; } /** * 为函数提前绑定前置参数(柯里化) * * @see http://en.wikipedia.org/wiki/Currying * @param {Function} fn 要绑定的函数 * @param {...Array} cargs cargs * @return {Function} */ export function curry(fn, ...cargs) { return function (...rargs) { const args = cargs.concat(rargs); // eslint-disable-next-line no-invalid-this return fn.apply(this, args); }; } /** * 方法静态化, 反绑定、延迟绑定 * * @param {Function} method 待静态化的方法 * @return {Function} 静态化包装后方法 */ export function generic(method) { return function (...fargs) { return Function.call.apply(method, fargs); }; } /** * 设置覆盖相关的属性值 * * @param {Object} thisObj 覆盖对象 * @param {Object} thatObj 值对象 * @param {Array.<string>} fields 字段 * @return {Object} thisObj */ export function overwrite(thisObj, thatObj, fields) { if (!thatObj) { return thisObj; } // 这里`fields`未指定则仅overwrite自身可枚举的字段,指定`fields`则不做限制 fields = fields || Object.keys(thatObj); fields.forEach(field => { // 拷贝对象 if ( thisObj[field] && typeof thisObj[field] === 'object' && thatObj[field] && typeof thatObj[field] === 'object' ) { overwrite(thisObj[field], thatObj[field]); } else { thisObj[field] = thatObj[field]; } }); return thisObj; } /** * 深复制对象,仅复制数据 * * @param {Object} source 源数据 * @return {Object} 复制的数据 */ export function clone(source) { if (!source || typeof source !== 'object') { return source; } let cloned = source; if (isArray(source)) { cloned = source.slice().map(clone); } else if (isObject(source) && 'isPrototypeOf' in source) { cloned = {}; for (const key of Object.keys(source)) { cloned[key] = clone(source[key]); } } return cloned; } // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. // @see underscore.js export function throttle(func, wait) { let context; let args; let timeout; let result; let previous = 0; const later = function () { previous = new Date(); timeout = null; result = func.apply(context, args); }; return function (...args) { const now = new Date(); const remaining = wait - (now - previous); // eslint-disable-next-line no-invalid-this context = this; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; } // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. // @see underscore.js export function debounce(func, wait, immediate) { let timeout; let result; return function (...args) { // eslint-disable-next-line no-invalid-this const context = this; const later = function () { timeout = null; if (!immediate) { result = func.apply(context, args); } }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; } /** * 判断两个对象的字段是否相等 * * @param {Object} thisObj 要比较的对象 * @param {Object} thatObj 参考对象 * @param {Array} fields 指定字段 * @return {boolean} 是否相等 */ export function equals(thisObj, thatObj, fields) { if (thisObj === thatObj) { return true; } if (thisObj == null && thatObj == null) { return true; } if (thisObj == null && thatObj != null || thisObj != null && thatObj == null) { return false; } // 这里`fields`未指定则仅overwrite自身可枚举的字段,指定`fields`则不做限制 fields = fields || (typeof thisObj === 'object' ? Object.keys(thisObj) : []); if (!fields.length) { return thisObj === thatObj; } let equal = true; for (let i = 0, l = fields.length, field; equal && i < l; i++) { field = fields[i]; if ( thisObj[field] && typeof thisObj[field] === 'object' && thatObj[field] && typeof thatObj[field] === 'object' ) { equal = equal && equals(thisObj[field], thatObj[field]); } else { equal = equal && (thisObj[field] === thatObj[field]); } } return equal; } <|start_filename|>src/ttf/svg2base64.js<|end_filename|> /** * @file svg字符串转base64编码 * @author mengke01(<EMAIL>) */ /** * svg字符串转base64编码 * * @param {string} svg svg对象 * @param {string} scheme 头部 * @return {string} base64编码 */ export default function svg2base64(svg, scheme = 'font/svg') { if (typeof btoa === 'undefined') { return 'data:' + scheme + ';charset=utf-8;base64,' + Buffer.from(svg, 'binary').toString('base64'); } return 'data:' + scheme + ';charset=utf-8;base64,' + btoa(svg); } <|start_filename|>demo/js/glyf2canvas.js<|end_filename|> /** * @file glyf2canvas.js * @author mengke01 * @date * @description * glyf 的canvas绘制 */ import drawPath from './drawPath'; /** * glyf canvas绘制 * * @param {Object} glyf glyf数据 * @param {CanvasRenderingContext2D} ctx canvas的context * @param {Object} options 绘制参数 */ export default function glyf2canvas(glyf, ctx, options = {}) { if (!glyf) { return; } ctx.save(); if (options.stroke) { ctx.strokeWidth = options.strokeWidth || 1; ctx.strokeStyle = options.strokeStyle || 'black'; } else { ctx.fillStyle = options.fillStyle || 'black'; } let height = glyf.yMax; let x = options.x || 0; let y = height + (options.y || 0); let scale = options.scale || 1; let i; let l; let contours; ctx.scale(scale, -scale); ctx.translate(x, -y); // 处理glyf轮廓 ctx.beginPath(); if (!glyf.compound) { contours = glyf.contours; for (i = 0, l = contours.length; i < l; i++) { drawPath(ctx, contours[i]); } } // 复合图元绘制 else { let glyfs = glyf.glyfs; glyfs.forEach(function (g) { ctx.save(); let transform = g.transform; ctx.transform( transform.a, transform.b, transform.c, transform.d, transform.e, transform.f ); contours = g.glyf.contours; for (i = 0, l = contours.length; i < l; i++) { drawPath(ctx, contours[i]); } ctx.restore(); }); } if (false !== options.stroke) { ctx.stroke(); } if (false !== options.fill) { ctx.fill(); } ctx.restore(); } <|start_filename|>src/ttf/error.js<|end_filename|> /** * @file ttf 相关错误号定义 * @author mengke01(<EMAIL>) */ import string from '../common/string'; import i18n from './i18n'; export default { /** * 抛出一个异常 * * @param {Object} e 异常号或者异常对象 * @param {...Array} fargs args 参数 * * 例如: * e = 1001 * e = { * number: 1001, * data: 错误数据 * } */ raise(e, ...fargs) { let number; let data; if (typeof e === 'object') { number = e.number || 0; data = e.data; } else { number = e; } let message = i18n.lang[number]; if (fargs.length > 0) { const args = typeof fargs[0] === 'object' ? fargs[0] : fargs; message = string.format(message, args); } const event = new Error(message); event.number = number; if (data) { event.data = data; } throw event; } }; <|start_filename|>src/graphics/matrix.js<|end_filename|> /** * @file matrix变换操作 * @author mengke01(<EMAIL>) */ /** * 仿射矩阵相乘 * * @param {Array=} matrix1 矩阵1 * @param {Array=} matrix2 矩阵2 * @return {Array} 新矩阵 */ export function mul(matrix1 = [1, 0, 0, 1], matrix2 = [1, 0, 0, 1]) { // 旋转变换 4 个参数 if (matrix1.length === 4) { return [ matrix1[0] * matrix2[0] + matrix1[2] * matrix2[1], matrix1[1] * matrix2[0] + matrix1[3] * matrix2[1], matrix1[0] * matrix2[2] + matrix1[2] * matrix2[3], matrix1[1] * matrix2[2] + matrix1[3] * matrix2[3] ]; } // 旋转位移变换, 6 个参数 return [ matrix1[0] * matrix2[0] + matrix1[2] * matrix2[1], matrix1[1] * matrix2[0] + matrix1[3] * matrix2[1], matrix1[0] * matrix2[2] + matrix1[2] * matrix2[3], matrix1[1] * matrix2[2] + matrix1[3] * matrix2[3], matrix1[0] * matrix2[4] + matrix1[2] * matrix2[5] + matrix1[4], matrix1[1] * matrix2[4] + matrix1[3] * matrix2[5] + matrix1[5] ]; } /** * 多个仿射矩阵相乘 * * @param {...Array} matrixs matrix array * @return {Array} 新矩阵 */ export function multiply(...matrixs) { let result = matrixs[0]; for (let i = 1, matrix; (matrix = matrixs[i]); i++) { result = mul(result, matrix); } return result; } <|start_filename|>src/ttf/util/reduceGlyf.js<|end_filename|> /** * @file 缩减glyf大小,去除冗余节点 * @author mengke01(<EMAIL>) */ import reducePath from '../../graphics/reducePath'; /** * 缩减glyf,去除冗余节点 * * @param {Object} glyf glyf对象 * @return {Object} glyf对象 */ export default function reduceGlyf(glyf) { const contours = glyf.contours; let contour; for (let j = contours.length - 1; j >= 0; j--) { contour = reducePath(contours[j]); // 空轮廓 if (contour.length <= 2) { contours.splice(j, 1); continue; } } if (0 === glyf.contours.length) { delete glyf.contours; } return glyf; } <|start_filename|>src/ttf/enum/componentFlag.js<|end_filename|> /** * @file 复合图元标记位 * @author mengke01(<EMAIL>) * * 复合图元标记位 * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html */ export default { ARG_1_AND_2_ARE_WORDS: 0x01, ARGS_ARE_XY_VALUES: 0x02, ROUND_XY_TO_GRID: 0x04, WE_HAVE_A_SCALE: 0x08, RESERVED: 0x10, MORE_COMPONENTS: 0x20, WE_HAVE_AN_X_AND_Y_SCALE: 0x40, WE_HAVE_A_TWO_BY_TWO: 0x80, WE_HAVE_INSTRUCTIONS: 0x100, USE_MY_METRICS: 0x200, OVERLAP_COMPOUND: 0x400, SCALED_COMPONENT_OFFSET: 0x800, UNSCALED_COMPONENT_OFFSET: 0x1000 }; <|start_filename|>test/spec/ttf/svg2ttfobject.spec.js<|end_filename|> /** * @file svg2ttfobject * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {readData} from '../data'; import svg2ttfobject from 'fonteditor-core/ttf/svg2ttfobject'; describe('svg转ttf对象', function () { let ttfObject = svg2ttfobject(readData('iconfont-xin.svg')); it('test svg glyf', function () { assert.equal(ttfObject.from, 'svg'); assert.equal(ttfObject.glyf.length, 2); assert.equal(ttfObject.glyf[0].contours.length, 7); assert.equal(ttfObject.glyf[1].contours.length, 1); }); let fontObject = svg2ttfobject(readData('icomoon.svg')); it('test svg font', function () { assert.equal(fontObject.from, 'svgfont'); assert.equal(fontObject.id, 'icomoon'); assert.equal(fontObject.name.fontFamily, 'icomoon'); assert.equal(fontObject.metadata, 'Generated by IcoMoon'); }); it('test svg font glyf', function () { assert.equal(fontObject.glyf.length, 3); assert.equal(fontObject.glyf[2].leftSideBearing, 0); assert.equal(fontObject.glyf[2].advanceWidth, 1024); assert.equal(fontObject.glyf[2].contours.length, 7); assert.equal(fontObject.glyf[2].unicode[0], 57345); }); let hucpTtf = svg2ttfobject(readData('high-unicode-codepoints.svg')); it('test svg high unicode codepoint and ligature conversion', function () { assert.equal(hucpTtf.glyf.length, 3); // original file has missing + 3 glyfs, one of which is a ligature, so total after conversion should be 4 - 1 = 3 assert.equal(hucpTtf.glyf[1].unicode[0], 0x0ffffa); assert.equal(hucpTtf.glyf[2].unicode[0], 0x0ffffb); }); }); describe('读错误svg数据', function () { it('test read svg error', function () { assert.throws(function () { svg2ttfobject(''); }); assert.throws(function () { svg2ttfobject('<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg></svg>'); }); }); }); <|start_filename|>test/node-spec/fonteditor-core.js<|end_filename|> /** * @file fonteditor * @author mengke01(<EMAIL>) */ module.exports = require('../../lib/main'); <|start_filename|>src/ttf/svg/oval2contour.js<|end_filename|> /** * @file 椭圆转换成轮廓 * @author mengke01(<EMAIL>) */ import {computePath} from '../../graphics/computeBoundingBox'; import pathAdjust from '../../graphics/pathAdjust'; import circlePath from '../../graphics/path/circle'; import {clone} from '../../common/lang'; /** * 椭圆转换成轮廓 * * @param {number} cx 椭圆中心点x * @param {number} cy 椭圆中心点y * @param {number} rx 椭圆x轴半径 * @param {number} ry 椭圆y周半径 * @return {Array} 轮廓数组 */ export default function oval2contour(cx, cy, rx, ry) { if (undefined === ry) { ry = rx; } const bound = computePath(circlePath); const scaleX = (+rx) * 2 / bound.width; const scaleY = (+ry) * 2 / bound.height; const centerX = bound.width * scaleX / 2; const centerY = bound.height * scaleY / 2; const contour = clone(circlePath); pathAdjust(contour, scaleX, scaleY); pathAdjust(contour, 1, 1, +cx - centerX, +cy - centerY); return contour; } <|start_filename|>.eslintrc.js<|end_filename|> // eslint-disable-next-line import/no-commonjs module.exports = { 'env': { 'browser': true, 'es2021': true, 'node': true, 'mocha': true }, 'extends': ['eslint:recommended', 'plugin:import/recommended'], 'parserOptions': { 'ecmaVersion': 12, 'sourceType': 'module' }, 'rules': { 'indent': [ 'error', 4 ], 'linebreak-style': [ 'error', 'unix' ], 'quotes': [ 'error', 'single' ], 'semi': [ 'error', 'always' ], 'eqeqeq': [ 'error', 'always', { 'null': 'ignore' } ], 'key-spacing': [ 2, { beforeColon: false, afterColon: true } ], 'no-multi-spaces': 2, 'class-methods-use-this': 0 }, 'overrides': [ { files: [ 'test/**/*.js' ], rules: { 'import/no-unresolved': 0 } } ] }; <|start_filename|>test/spec/ttf/font.spec.js<|end_filename|> /** * @file font * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {readData} from '../data'; import Font from 'fonteditor-core/ttf/font'; import main from 'fonteditor-core/main'; describe('test Font Class ============================', function () { it('test create empty', function () { let font = Font.create(); assert.equal(font.data.version, 1); assert.equal(font.data.glyf.length, 1); }); it('test create by object', function () { let font = Font.create({ version: 1, glyf: [] }); assert.equal(font.data.version, 1); assert.equal(font.data.glyf.length, 0); }); }); describe('read ttf buffer', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); it('test read ttf', function () { assert.equal(font.data.version, 1); assert.equal(font.data.numTables, 15); }); }); describe('transform compound to simple', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf', compound2simple: true }); it('test read ttf glyf', function () { assert.equal(!!font.data.glyf[16].compound, false); assert.equal(!!font.data.glyf[16].glyfs, false); assert.equal(font.data.glyf[16].contours.length, 4); }); }); describe('read otf buffer', function () { let font = Font.create(readData('BalladeContour.otf'), { type: 'otf' }); it('test read otf', function () { assert.equal(font.data.version, 0x1); assert.equal(font.data.numTables, 9); assert.equal(font.data.rangeShift, 16); assert.equal(font.data.searchRange, 128); }); }); describe('read woff buffer', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write({ type: 'woff' }); let font = Font.create(buffer, { type: 'woff' }); it('test read woff', function () { assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); }); describe('read woff2 buffer', function () { this.timeout(2000); before(function (done) { main.woff2.init().then(() => done()); }); it('test read woff2', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write({ type: 'woff2' }); let font = Font.create(buffer, { type: 'woff2' }); assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); }); describe('read eot buffer', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write({ type: 'eot' }); let font = Font.create(buffer, { type: 'eot' }); it('test read eot', function () { assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); }); describe('read svg text', function () { let font = Font.create(readData('iconfont-xin.svg'), { type: 'svg' }); it('test read svg', function () { assert.equal(font.data.from, 'svg'); assert.equal(font.data.glyf.length, 2); assert.equal(font.data.glyf[0].contours.length, 7); assert.equal(font.data.glyf[1].contours.length, 1); }); }); describe('read svg font text', function () { let font = Font.create(readData('icomoon.svg'), { type: 'svg' }); it('test read svg font', function () { assert.equal(font.data.from, 'svgfont'); assert.equal(font.data.id, 'icomoon'); assert.equal(font.data.name.fontFamily, 'icomoon'); assert.equal(font.data.metadata, 'Generated by IcoMoon'); }); it('test svg font glyf', function () { assert.equal(font.data.glyf.length, 3); assert.equal(font.data.glyf[2].leftSideBearing, 0); assert.equal(font.data.glyf[2].advanceWidth, 1024); assert.equal(font.data.glyf[2].contours.length, 7); assert.equal(font.data.glyf[2].unicode[0], 57345); }); }); describe('write ttf buffer', function () { it('test write ttf', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write(); assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); let font = Font.create(buffer, { type: 'ttf' }); assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); it('test write ttf hinting', function () { let buffer = Font.create(readData('baiduHealth-hinting.ttf'), { type: 'ttf', hinting: true }).write({ hinting: true }); assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); let font = Font.create(buffer, { type: 'ttf', hinting: true }); assert.equal(font.data.cvt.length, 24); assert.equal(font.data.fpgm.length, 371); assert.equal(font.data.prep.length, 204); assert.equal(font.data.gasp.length, 8); }); }); describe('write eot buffer', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write({ type: 'eot' }); it('test eot format', function () { assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); }); it('test read eot', function () { let font = Font.create(buffer, { type: 'eot' }); assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); }); describe('write woff buffer', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write({ type: 'woff' }); it('test woff format', function () { assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); }); it('test read woff', function () { let font = Font.create(buffer, { type: 'woff' }); assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); }); describe('write woff2 buffer', function () { this.timeout(2000); before(function (done) { main.woff2.init().then(() => done()); }); it('test read woff2', function () { let buffer = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).write({ type: 'woff2' }); it('test woff format', function () { assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); }); let font = Font.create(buffer, { type: 'woff2' }); assert.equal(font.data.version, 1); assert.equal(font.data.head.magickNumber, 1594834165); assert.equal(font.data.head.unitsPerEm, 512); }); }); describe('write svg text', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); let svg = font.write({ type: 'svg' }); it('test svg format', function () { assert.ok(svg.length > 1000); }); let symbol = font.write({ type: 'symbol' }); it('test symbol format', function () { assert.ok(symbol.length > 1000); }); }); describe('toBase64', function () { this.timeout(2000); before(function (done) { main.woff2.init().then(() => done()); }); it('test ttf to toBase64', function () { let base64Str = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).toBase64({ type: 'ttf' }); assert.equal(base64Str.indexOf('data:font/ttf;'), 0); assert.ok(base64Str.length > 1000); assert.ok(base64Str.length < 10000); }); it('test woff to toBase64', function () { let base64Str = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).toBase64({ type: 'woff' }); assert.equal(base64Str.indexOf('data:font/woff;'), 0); assert.ok(base64Str.length > 1000); assert.ok(base64Str.length < 10000); }); it('test woff2 to toBase64', function () { let base64Str = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).toBase64({ type: 'woff2' }); assert.equal(base64Str.indexOf('data:font/woff2;'), 0); assert.ok(base64Str.length > 1000); assert.ok(base64Str.length < 10000); }); it('test eot to toBase64', function () { let base64Str = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).toBase64({ type: 'eot' }); assert.equal(base64Str.indexOf('data:font/eot;'), 0); assert.ok(base64Str.length > 1000); assert.ok(base64Str.length < 10000); }); it('test svg to toBase64', function () { let base64Str = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).toBase64({ type: 'svg' }); assert.equal(base64Str.indexOf('data:font/svg;'), 0); assert.ok(base64Str.length > 1000); assert.ok(base64Str.length < 20000); }); it('test svg symbol to toBase64', function () { let base64Str = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }).toBase64({ type: 'symbol' }); assert.equal(base64Str.indexOf('data:image/svg+xml;'), 0); assert.ok(base64Str.length > 1000); }); }); describe('font method', function () { it('compound2simple', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); font.compound2simple(); assert.equal(!!font.data.glyf[16].compound, false); assert.equal(!!font.data.glyf[16].glyfs, false); assert.equal(font.data.glyf[16].contours.length, 4); }); it('optimize', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); font.compound2simple(); assert.equal(font.data.glyf.length, 17); font.optimize(); assert.equal(font.data.glyf.length, 15); }); it('sort', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); font.sort(); assert.equal(font.data.glyf[2].unicode, null); font.compound2simple().sort(); assert.equal(font.data.glyf[2].unicode[0], 0xe003); }); it('find', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); let list = font.find({ unicode: 0xe003 }); assert.equal(list.length, 1); assert.equal(list[0].unicode[0], 0xe003); list = font.find({ name: 'uniE00' }); assert.equal(list.length, 4); list = font.find({ filter(glyf) { return glyf.name === 'uniE003'; } }); assert.equal(list.length, 1); }); it('merge', function () { let font = Font.create(readData('baiduHealth.ttf'), { type: 'ttf' }); let font1 = Font.create(readData('icomoon.svg'), { type: 'svg' }); font1.optimize(); assert.equal(font.data.glyf.length, 17); assert.equal(font1.data.glyf.length, 2); font.merge(font1); assert.equal(font.data.glyf.length, 18); }); it('toBase64', function () { let str = Font.toBase64('abcd'); assert.equal(str, 'YWJjZA=='); let buffer = new Int8Array([65, 66, 67]); str = Font.toBase64(buffer); assert.equal(str, 'QUJD'); str = Font.toBase64(buffer.buffer); assert.equal(str, 'QUJD'); }); }); <|start_filename|>src/ttf/table/table.js<|end_filename|> /** * @file ttf表基类 * @author mengke01(<EMAIL>) */ import struct from './struct'; import error from '../error'; /* eslint-disable no-invalid-this */ /** * 读取表结构 * * @param {Reader} reader reader对象 * @return {Object} 当前对象 */ function read(reader) { const offset = this.offset; if (undefined !== offset) { reader.seek(offset); } const me = this; this.struct.forEach((item) => { const name = item[0]; const type = item[1]; let typeName = null; switch (type) { case struct.Int8: case struct.Uint8: case struct.Int16: case struct.Uint16: case struct.Int32: case struct.Uint32: typeName = struct.names[type]; me[name] = reader.read(typeName); break; case struct.Fixed: me[name] = reader.readFixed(); break; case struct.LongDateTime: me[name] = reader.readLongDateTime(); break; case struct.Bytes: me[name] = reader.readBytes(reader.offset, item[2] || 0); break; case struct.Char: me[name] = reader.readChar(); break; case struct.String: me[name] = reader.readString(reader.offset, item[2] || 0); break; default: error.raise(10003, name, type); } }); return this.valueOf(); } /** * 写表结构 * * @param {Object} writer writer对象 * @param {Object} ttf 已解析的ttf对象 * * @return {Writer} 返回writer对象 */ function write(writer, ttf) { const table = ttf[this.name]; if (!table) { error.raise(10203, this.name); } this.struct.forEach((item) => { const name = item[0]; const type = item[1]; let typeName = null; switch (type) { case struct.Int8: case struct.Uint8: case struct.Int16: case struct.Uint16: case struct.Int32: case struct.Uint32: typeName = struct.names[type]; writer.write(typeName, table[name]); break; case struct.Fixed: writer.writeFixed(table[name]); break; case struct.LongDateTime: writer.writeLongDateTime(table[name]); break; case struct.Bytes: writer.writeBytes(table[name], item[2] || 0); break; case struct.Char: writer.writeChar(table[name]); break; case struct.String: writer.writeString(table[name], item[2] || 0); break; default: error.raise(10003, name, type); } }); return writer; } /** * 获取ttf表的size大小 * * @param {string} name 表名 * @return {number} 表大小 */ function size() { let sz = 0; this.struct.forEach((item) => { const type = item[1]; switch (type) { case struct.Int8: case struct.Uint8: sz += 1; break; case struct.Int16: case struct.Uint16: sz += 2; break; case struct.Int32: case struct.Uint32: case struct.Fixed: sz += 4; break; case struct.LongDateTime: sz += 8; break; case struct.Bytes: sz += item[2] || 0; break; case struct.Char: sz += 1; break; case struct.String: sz += item[2] || 0; break; default: error.raise(10003, name, type); } }); return sz; } /** * 获取对象的值 * * @return {*} 当前对象的值 */ function valueOf() { const val = {}; const me = this; this.struct.forEach(item => { val[item[0]] = me[item[0]]; }); return val; } export default { read, write, size, valueOf, /** * 创建一个表结构 * * @param {string} name 表名 * @param {Object} struct 表结构 * @param {Object} prototype 原型 * @return {Function} 表构造函数 */ create(name, struct, prototype) { class Table { constructor(offset) { this.name = name; this.struct = struct; this.offset = offset; } } Table.prototype.read = read; Table.prototype.write = write; Table.prototype.size = size; Table.prototype.valueOf = valueOf; Object.assign(Table.prototype, prototype); return Table; } }; <|start_filename|>demo/js/svgnode2contours.js<|end_filename|> /** * @file svgnode2contours.js * @author mengke01 * @date * @description * svg转ttfobject */ import ajaxFile from 'fonteditor-core/common/ajaxFile'; import svgnode2contours from 'fonteditor-core/ttf/svg/svgnode2contours'; import contours2svg from 'fonteditor-core/ttf/util/contours2svg'; let entry = { /** * 初始化 */ init() { ajaxFile({ type: 'xml', url: './test/svgnodes.svg', onSuccess(xml) { let contours = svgnode2contours(xml.getElementsByTagName('*')); let path = contours2svg(contours); $('#path').attr('d', path); $('#origin').html(xml.documentElement.outerHTML); }, onError() { console.error('error read file'); } }); } }; entry.init(); <|start_filename|>test/spec/ttf/writer.spec.js<|end_filename|> /** * @file writer * @author mengke01(<EMAIL>) */ import assert from 'assert'; import Writer from 'fonteditor-core/ttf/writer'; import Reader from 'fonteditor-core/ttf/reader'; describe('write basic datatypes', function () { let buffer = new ArrayBuffer(100); it('test write basic datatype', function () { let writer = new Writer(buffer, 0, 100); // 基本类型 writer.writeInt8(10); writer.writeInt16(2442); writer.writeInt32(-10); writer.writeUint8(10); writer.writeUint16(2442); writer.writeUint32(5375673); writer.writeUint8(55.45444444); writer.writeUint16(55.45444444); writer.writeUint32(55.45444444); let reader = new Reader(buffer, 0, 100); assert.equal(reader.readInt8(), 10); assert.equal(reader.readInt16(), 2442); assert.equal(reader.readInt32(), -10); assert.equal(reader.readUint8(), 10); assert.equal(reader.readUint16(), 2442); assert.equal(reader.readUint32(), 5375673); assert.equal(reader.readUint8(), 55); assert.equal(reader.readUint16(), 55); assert.equal(reader.readUint32(), 55); }); it('test write decimals', function () { let writer = new Writer(buffer, 0, 100); // 基本类型 writer.writeInt8(-55.99999); writer.writeInt16(-55.99999); writer.writeInt32(-55.999999); writer.writeUint8(55.45444444); writer.writeUint16(55.45444444); writer.writeUint32(55.45444444); let reader = new Reader(buffer, 0, 100); assert.equal(reader.readInt8(), -55); assert.equal(reader.readInt16(), -55); assert.equal(reader.readInt32(), -55); assert.equal(reader.readUint8(), 55); assert.equal(reader.readUint16(), 55); assert.equal(reader.readUint32(), 55); }); it('test write extend datatype', function () { let writer = new Writer(buffer, 0, 100); let now = Math.round(new Date().getTime() / 1000) * 1000; // 扩展类型 writer.writeString('baidu'); writer.writeFixed(12.36); writer.writeLongDateTime(now); writer.writeBytes([3, 4, 5]); let reader = new Reader(buffer, 0, 100); assert.equal(reader.readString(0, 5), 'baidu'); assert.equal(reader.readFixed().toFixed(2), 12.36); assert.equal(reader.readLongDateTime().getTime(), now); assert.deepEqual(reader.readBytes(3), [3, 4, 5]); }); it('test seek', function () { let writer = new Writer(buffer, 0, 100); // 测试seek writer.seek(50); writer.writeFixed(12.36); let reader = new Reader(buffer, 0, 100); reader.seek(50); assert.equal(reader.readFixed().toFixed(2), 12.36); }); }); <|start_filename|>test/spec/ttf/ttfwriter.spec.js<|end_filename|> /** * @file ttfwriter * @author mengke01(<EMAIL>) */ import assert from 'assert'; import {readData} from '../data'; import TTFReader from 'fonteditor-core/ttf/ttfreader'; import TTFWriter from 'fonteditor-core/ttf/ttfwriter'; describe('write ttf buffer', function () { let fontObject = new TTFReader().read(readData('baiduHealth.ttf')); it('test write ttf', function () { let buffer = new TTFWriter().write(fontObject); assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); let ttf = new TTFReader().read(buffer); assert.equal(ttf.version, 1); assert.equal(ttf.head.magickNumber, 1594834165); assert.equal(ttf.head.unitsPerEm, 512); assert.equal(ttf.post.format, 2); assert.equal(ttf.post.underlinePosition, 0); assert.equal(ttf.post.underlineThickness, 0); assert.equal(ttf.hhea.advanceWidthMax, 682); assert.equal(ttf.hhea.ascent, 480); assert.equal(ttf.hhea.descent, -33); assert.equal(ttf.maxp.version, 1); assert.equal(ttf.maxp.numGlyphs, 17); assert.equal(ttf.glyf[0].advanceWidth, 512); assert.equal(ttf.glyf[0].leftSideBearing, 0); assert.equal(ttf.glyf[0].name, '.notdef'); assert.equal(ttf.glyf[3].contours[0].length, 31); assert.equal(ttf.glyf[16].compound, true); assert.equal(ttf.glyf[16].glyfs.length, 2); assert.equal(ttf.cmap[0], 1); assert.equal(ttf.cmap[57400], 16); assert.equal(+ttf.head.created === +fontObject.head.created, true); assert.equal(+ttf.head.modified === +fontObject.head.modified, true); }); it('test write ttf with support', function () { let buffer = new TTFWriter({ support: { head: { xMin: 1, yMin: -30, xMax: 610, yMax: 485, minLeftSideBearing: 1, minRightSideBearing: 1 }, hhea: { advanceWidthMax: 1000, xMaxExtent: 1000, minLeftSideBearing: 1, minRightSideBearing: 1 } } }).write(fontObject); assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); let ttf = new TTFReader().read(buffer); assert.equal(ttf.version, 1); assert.equal(ttf.head.magickNumber, 1594834165); assert.equal(ttf.head.unitsPerEm, 512); assert.equal(ttf.post.format, 2); assert.equal(ttf.post.underlinePosition, 0); assert.equal(ttf.post.underlineThickness, 0); assert.equal(ttf.hhea.ascent, 480); assert.equal(ttf.hhea.descent, -33); assert.equal(ttf.maxp.version, 1); assert.equal(ttf.maxp.numGlyphs, 17); assert.equal(ttf.glyf[0].advanceWidth, 512); assert.equal(ttf.glyf[0].leftSideBearing, 0); assert.equal(ttf.glyf[0].name, '.notdef'); assert.equal(ttf.glyf[3].contours[0].length, 31); assert.equal(ttf.glyf[16].compound, true); assert.equal(ttf.glyf[16].glyfs.length, 2); assert.equal(ttf.cmap[0], 1); assert.equal(ttf.cmap[57400], 16); assert.equal(+ttf.head.created === +fontObject.head.created, true); assert.equal(+ttf.head.modified === +fontObject.head.modified, true); assert.equal(ttf.head.xMin, 1); assert.equal(ttf.head.yMin, -30); assert.equal(ttf.head.xMax, 610); assert.equal(ttf.head.yMax, 485); assert.equal(ttf.hhea.advanceWidthMax, 1000); assert.equal(ttf.hhea.xMaxExtent, 1000); assert.equal(ttf.hhea.minLeftSideBearing, 1); assert.equal(ttf.hhea.minRightSideBearing, 1); }); it('test write ttf error', function () { assert.throws(function () { let ttf = Object.assign({}, fontObject); ttf.head = null; new TTFWriter().write(ttf); }); assert.throws(function () { let ttf = Object.assign({}, fontObject); ttf.glyf.length = 0; new TTFWriter().write(ttf); }); assert.throws(function () { let ttf = Object.assign({}, fontObject); ttf.name = null; new TTFWriter().write(ttf); }); }); }); describe('write ttf hinting', function () { let fontObject = new TTFReader({ hinting: true }).read(readData('baiduHealth-hinting.ttf')); it('test write ttf hinting', function () { let buffer = new TTFWriter({ hinting: true }).write(fontObject); assert.ok(buffer.byteLength > 1000); assert.ok(buffer.byteLength < 10000); assert.equal(fontObject.cvt.length, 24); assert.equal(fontObject.fpgm.length, 371); assert.equal(fontObject.prep.length, 204); assert.equal(fontObject.gasp.length, 8); assert.equal(fontObject.GPOS.length, 18); }); }); <|start_filename|>src/ttf/enum/platform.js<|end_filename|> /** * @file 字体所属平台 * @author mengke01(<EMAIL>) */ export default{ Unicode: 0, Macintosh: 1, // mac reserved: 2, Microsoft: 3 // win }; <|start_filename|>demo/js/woff2.js<|end_filename|> /** * @file woff2.js * @author mengke01 * @date * @description * ttf解析函数入口 */ import TTFReader from 'fonteditor-core/ttf/ttfreader'; import ajaxFile from 'fonteditor-core/common/ajaxFile'; import {ttftowoff2async} from 'fonteditor-core/ttf/ttftowoff2'; import {woff2tottfasync} from 'fonteditor-core/ttf/woff2tottf'; function onUpFileChange(e) { let file = e.target.files[0]; let reader = new FileReader(); reader.onload = function (e) { transcode(e.target.result); }; reader.onerror = function (e) { console.error(e); }; reader.readAsArrayBuffer(file); } function transcode(binaryData) { console.log('ttfsize', binaryData.byteLength); ttftowoff2async(binaryData, {wasmUrl: '../woff2/woff2.wasm'}) .then(buffer => { console.log('encode woff2size', buffer.byteLength); return woff2tottfasync(buffer, {wasmUrl: '../woff2/woff2.wasm'}); }) .then(buffer => { console.log('decode ttfsize', binaryData.byteLength); let ttfReader = new TTFReader({ // hinting: true, subset: [65, 0x160, 0x161, 0x162] }); let ttfData = ttfReader.read(buffer); console.log(ttfData); }); } let entry = { /** * 初始化 */ init() { let upFile = document.getElementById('upload-file'); upFile.addEventListener('change', onUpFileChange); ajaxFile({ type: 'binary', url: './test/tt0586m.ttf', onSuccess(binaryData) { transcode(binaryData); }, onError() { console.error('error read file'); } }); } }; entry.init(); <|start_filename|>src/ttf/woff2ttf.js<|end_filename|> /** * @file woff转换ttf * @author mengke01(<EMAIL>) */ import Reader from './reader'; import Writer from './writer'; import error from './error'; /** * woff格式转换成ttf字体格式 * * @param {ArrayBuffer} woffBuffer woff缓冲数组 * @param {Object} options 选项 * @param {Object} options.inflate 解压相关函数 * * @return {ArrayBuffer} ttf格式byte流 */ export default function woff2ttf(woffBuffer, options = {}) { const reader = new Reader(woffBuffer); const signature = reader.readUint32(0); const flavor = reader.readUint32(4); if (signature !== 0x774F4646 || (flavor !== 0x10000 && flavor !== 0x4f54544f)) { reader.dispose(); error.raise(10102); } const numTables = reader.readUint16(12); const ttfSize = reader.readUint32(16); const tableEntries = []; let tableEntry; let i; let l; // 读取woff表索引信息 for (i = 0; i < numTables; ++i) { reader.seek(44 + i * 20); tableEntry = { tag: reader.readString(reader.offset, 4), offset: reader.readUint32(), compLength: reader.readUint32(), length: reader.readUint32(), checkSum: reader.readUint32() }; // ttf 表数据 const deflateData = reader.readBytes(tableEntry.offset, tableEntry.compLength); // 需要解压 if (deflateData.length < tableEntry.length) { if (!options.inflate) { reader.dispose(); error.raise(10105); } tableEntry.data = options.inflate(deflateData); } else { tableEntry.data = deflateData; } tableEntry.length = tableEntry.data.length; tableEntries.push(tableEntry); } const writer = new Writer(new ArrayBuffer(ttfSize)); // 写头部 const entrySelector = Math.floor(Math.log(numTables) / Math.LN2); const searchRange = Math.pow(2, entrySelector) * 16; const rangeShift = numTables * 16 - searchRange; writer.writeUint32(flavor); writer.writeUint16(numTables); writer.writeUint16(searchRange); writer.writeUint16(entrySelector); writer.writeUint16(rangeShift); // 写ttf表索引 let tblOffset = 12 + 16 * tableEntries.length; for (i = 0, l = tableEntries.length; i < l; ++i) { tableEntry = tableEntries[i]; writer.writeString(tableEntry.tag); writer.writeUint32(tableEntry.checkSum); writer.writeUint32(tblOffset); writer.writeUint32(tableEntry.length); tblOffset += tableEntry.length + (tableEntry.length % 4 ? 4 - tableEntry.length % 4 : 0); } // 写ttf表数据 for (i = 0, l = tableEntries.length; i < l; ++i) { tableEntry = tableEntries[i]; writer.writeBytes(tableEntry.data); if (tableEntry.length % 4) { writer.writeEmpty(4 - tableEntry.length % 4); } } return writer.getBuffer(); } <|start_filename|>src/ttf/table/cff/getCFFString.js<|end_filename|> /** * @file 获取cff字符串 * @author mengke01(<EMAIL>) */ import cffStandardStrings from './cffStandardStrings'; /** * 根据索引获取cff字符串 * * @param {Object} strings 标准cff字符串索引 * @param {number} index 索引号 * @return {number} 字符串索引 */ export default function getCFFString(strings, index) { if (index <= 390) { index = cffStandardStrings[index]; } // Strings below index 392 are standard CFF strings and are not encoded in the font. else { index = strings[index - 391]; } return index; } <|start_filename|>demo/css/glyf.css<|end_filename|> * { margin: 0; padding: 0; } ul { list-style: none; } a { color: #03C; text-decoration: none; } a:hover { text-decoration: underline; } .hide { display: none; } body { font-size: 13px; } .upload-file { margin: 20px; } .i-font { font-family: 'truetype'; display: inline-block; margin-right: 6px; color: green; } .font-list { height: 200px; overflow: auto; } .font-list li { width: 70px; float: left; padding: 10px; border: 1px solid #EEE; list-style: none; cursor: pointer; } .font-list li:hover { background: #E0E0E0; } .font-list li.selected { background: #ECECEC; } .glyf { background: #F0F0F0; } .glyf .path { fill: green; stroke: none; stroke-width: 10px; } <|start_filename|>config/webpack.dev.js<|end_filename|> /** * @file webpack 配置 * @author mengke01(<EMAIL>) */ const fs = require('fs'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const DEMO_DIR = path.resolve(__dirname, '../demo'); function getEntries() { let files = fs.readdirSync(DEMO_DIR + '/js'); let entries = {}; for (let file of files) { if (file.endsWith('.js')) { let entryScript = file.replace('.js', ''); entries[entryScript] = './demo/js/' + file; } } return entries; } function getHtmlPages() { let files = fs.readdirSync(DEMO_DIR); let pages = []; for (let file of files) { if (file.endsWith('.html')) { let entryScript = file.replace('.html', ''); pages.push( new HtmlWebpackPlugin({ title: file, filename: 'demo/' + file, template: path.resolve(DEMO_DIR, file), chunks: [entryScript] }) ); } } return pages; } module.exports = { entry: getEntries(), output: { path: path.resolve(__dirname, '../dist'), filename: 'js/[name].js' }, devtool: 'inline-source-map', devServer: { contentBase: './' }, resolve: { extensions: ['.js', '.jsx', '.json'], alias: { 'fonteditor-core': path.resolve(__dirname, '../src') } }, externals: { jquery: 'window.jQuery', $: 'window.jQuery' }, plugins: [ new HtmlWebpackPlugin({ title: 'index page', filename: 'index.html', template: path.resolve(DEMO_DIR, 'index.html'), chunks: ['index'] }), ...getHtmlPages() ], module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: [ 'file-loader' ] } ] } }; <|start_filename|>demo/js/woff2ttf.js<|end_filename|> /** * @file woff2ttf.js * @author mengke01 * @date * @description * woff 转ttf */ import ajaxFile from 'fonteditor-core/common/ajaxFile'; import woff2ttf from 'fonteditor-core/ttf/woff2ttf'; import TTFReader from 'fonteditor-core/ttf/ttfreader'; import ttf2base64 from 'fonteditor-core/ttf/ttf2base64'; const inflate = window.pako.inflate; function write() { ajaxFile({ type: 'binary', url: 'test/fonteditor.woff', onSuccess(buffer) { let ttfBuffer = woff2ttf(buffer, { inflate }); let saveBtn = $('.saveas'); saveBtn.attr('href', ttf2base64(ttfBuffer)); saveBtn.attr('download', 'save.woff'); let ttfReader = new TTFReader(); let ttfData = ttfReader.read(ttfBuffer); console.log(ttfData); }, onError() { console.error('error read file'); } }); } const entry = { /** * 初始化 */ init() { write(); } }; entry.init(); <|start_filename|>src/ttf/table/support.js<|end_filename|> /** * @file ttf读取和写入支持的表 * @author mengke01(<EMAIL>) */ import head from './head'; import maxp from './maxp'; import loca from './loca'; import cmap from './cmap'; import glyf from './glyf'; import name from './name'; import hhea from './hhea'; import hmtx from './hmtx'; import post from './post'; import OS2 from './OS2'; import fpgm from './fpgm'; import cvt from './cvt'; import prep from './prep'; import gasp from './gasp'; import GPOS from './GPOS'; import kern from './kern'; export default { head, maxp, loca, cmap, glyf, name, hhea, hmtx, post, 'OS/2': OS2, fpgm, cvt, prep, gasp, GPOS, kern }; <|start_filename|>src/ttf/table/directory.js<|end_filename|> /** * @file directory 表, 读取和写入ttf表索引 * @author mengke01(<EMAIL>) * * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6.html */ import table from './table'; export default table.create( 'directory', [], { read(reader, ttf) { const tables = {}; const numTables = ttf.numTables; const offset = this.offset; for (let i = offset, l = numTables * 16; i < l; i += 16) { const name = reader.readString(i, 4).trim(); tables[name] = { name, checkSum: reader.readUint32(i + 4), offset: reader.readUint32(i + 8), length: reader.readUint32(i + 12) }; } return tables; }, write(writer, ttf) { const tables = ttf.support.tables; for (let i = 0, l = tables.length; i < l; i++) { writer.writeString((tables[i].name + ' ').slice(0, 4)); writer.writeUint32(tables[i].checkSum); writer.writeUint32(tables[i].offset); writer.writeUint32(tables[i].length); } return writer; }, size(ttf) { return ttf.numTables * 16; } } ); <|start_filename|>demo/js/ttfTableWriter.js<|end_filename|> /** * @file ttfTableWriter.js * @author mengke01 * @date * @description * 测试ttf表写 */ /* eslint-disable JS029 */ import Reader from 'fonteditor-core/ttf/reader'; import Writer from 'fonteditor-core/ttf/writer'; import supportTables from 'fonteditor-core/ttf/table/support'; // 支持写的表, 注意表顺序 const tableList = [ 'OS/2', 'cmap', 'glyf', 'head', 'hhea', 'hmtx', 'loca', 'maxp', 'name', 'post' ]; function resolve(ttf) { ttf.numTables = tableList.length; ttf.entrySelector = Math.floor(Math.log(tableList.length) / Math.LN2); ttf.searchRange = Math.pow(2, ttf.entrySelector) * 16; ttf.rangeShift = tableList.length * 16 - ttf.searchRange; // 将glyf的代码点按小到大排序 ttf.glyf.forEach(function (glyf) { if (glyf.unicode) { glyf.unicode = glyf.unicode.sort(); } }); return ttf; } function write(ttf) { // 用来做写入缓存的对象,用完后删掉 ttf.support = {}; let OS2Tbl = new supportTables['OS/2'](); let size = OS2Tbl.size(ttf); // 写入maxp let maxpTbl = new supportTables['maxp'](); size = maxpTbl.size(ttf); let maxpWriter = new Writer(new ArrayBuffer(size)); maxpTbl.write(maxpWriter, ttf); // 写入glyf let glyfTbl = new supportTables['glyf'](); size = glyfTbl.size(ttf); let glyfWriter = new Writer(new ArrayBuffer(size)); glyfTbl.write(glyfWriter, ttf); // 写入loca let locaTbl = new supportTables['loca'](); let locaWriter = new Writer(new ArrayBuffer(locaTbl.size(ttf))); locaTbl.write(locaWriter, ttf); // 写入cmap let cmapTbl = new supportTables['cmap'](); let cmapWriter = new Writer(new ArrayBuffer(cmapTbl.size(ttf))); cmapTbl.write(cmapWriter, ttf); // 写入hmtx let hmtxTbl = new supportTables['hmtx'](); let hmtxWriter = new Writer(new ArrayBuffer(hmtxTbl.size(ttf))); hmtxTbl.write(hmtxWriter, ttf); // 写入name let nameTbl = new supportTables['name'](); let nameWriter = new Writer(new ArrayBuffer(nameTbl.size(ttf))); nameTbl.write(nameWriter, ttf); // 写入post let postTbl = new supportTables['post'](); let postWriter = new Writer(new ArrayBuffer(postTbl.size(ttf))); postTbl.write(postWriter, ttf); // 写入OS2 OS2Tbl = new supportTables['OS/2'](); let OS2Writer = new Writer(new ArrayBuffer(OS2Tbl.size(ttf))); OS2Tbl.write(OS2Writer, ttf); // 写入hhea let hheaTbl = new supportTables['hhea'](); let hheaWriter = new Writer(new ArrayBuffer(hheaTbl.size(ttf))); hheaTbl.write(hheaWriter, ttf); // 读取测试 let maxpReader = new Reader(maxpWriter.getBuffer()); maxpTbl.offset = 0; ttf.maxp = maxpTbl.read(maxpReader, ttf); let locaReader = new Reader(locaWriter.getBuffer()); locaTbl.offset = 0; ttf.loca = locaTbl.read(locaReader, ttf); console.log('loca readed'); console.log(ttf.loca); let glyfReader = new Reader(glyfWriter.getBuffer()); glyfTbl.offset = 0; ttf.tables = { glyf: { length: 1 } }; ttf.readOptions = {}; let glyf = glyfTbl.read(glyfReader, ttf); console.log('glyf readed'); console.log(glyf); let cmapReader = new Reader(cmapWriter.getBuffer()); cmapTbl.offset = 0; let cmap = cmapTbl.read(cmapReader, ttf); console.log('cmap readed'); console.log(cmap); let hmtxReader = new Reader(hmtxWriter.getBuffer()); hmtxTbl.offset = 0; let hmtx = hmtxTbl.read(hmtxReader, ttf); console.log('hmtx readed'); console.log(hmtx); let nameReader = new Reader(nameWriter.getBuffer()); nameTbl.offset = 0; let name = nameTbl.read(nameReader, ttf); console.log('name readed'); console.log(name); let postReader = new Reader(postWriter.getBuffer()); postTbl.offset = 0; ttf.tables = ttf.tables || {}; ttf.tables.post = { length: postWriter.offset }; let post = postTbl.read(postReader, ttf); console.log('post readed'); console.log(post); let OS2Reader = new Reader(OS2Writer.getBuffer()); OS2Tbl.offset = 0; let OS2 = OS2Tbl.read(OS2Reader, ttf); console.log('OS2 readed'); console.log(OS2); let hheaReader = new Reader(hheaWriter.getBuffer()); hheaTbl.offset = 0; let hhea = hheaTbl.read(hheaReader, ttf); console.log('hhea readed'); console.log(hhea); delete ttf.support; } let entry = { init() { $.getJSON('./data/baiduHealth.json', function (ttf) { resolve(ttf); write(ttf); }); } }; entry.init(); <|start_filename|>demo/js/otfreader.js<|end_filename|> /** * @file glyf.js * @author mengke01 * @date * @description * glyf canvas 绘制 */ import OTFReader from 'fonteditor-core/ttf/otfreader'; import TTF from 'fonteditor-core/ttf/ttf'; import otf2base64 from 'fonteditor-core/ttf/otf2base64'; import ajaxFile from 'fonteditor-core/common/ajaxFile'; import * as lang from 'fonteditor-core/common/lang'; import otfGlyf2Canvas from './otfGlyf2Canvas'; import setFontface from './setFontface'; let ttf = null; // 设置字体 function setFont(arrayBuffer) { let base64 = otf2base64(arrayBuffer); setFontface('truetype', base64, 'font-face'); } // 查看ttf glyf function showOTFGlyf(otfData) { ttf = new TTF(otfData); let codes = ttf.codes(); let str = ''; // 获取unicode字符 codes.forEach(function (item) { str += '<li data-code="' + item + '">' + '<span class="i-font">' + String.fromCharCode(item) + '</span>' + (item > 255 ? '\\u' + Number(item).toString(16) : item) + '</li>'; }); $('#font-list').html(str); $('#font-list li:nth-child(4)').click(); } function showGlyf(charcode) { let glyf = lang.clone(ttf.getGlyfByCode(charcode)); let canvas = $('#glyf-canvas').get(0); let ctx = canvas.getContext('2d'); // 调整大小 ctx.clearRect(0, 0, 600, 600); otfGlyf2Canvas(glyf, ctx, { stroke: 0, scale: 600 / ttf.ttf.head.unitsPerEm, height: ttf.ttf.head.unitsPerEm + ttf.ttf.hhea.descent, strokeStyle: 'green', fillStyle: 'green' }); } function onUpFileChange(e) { let file = e.target.files[0]; let reader = new FileReader(); reader.onload = function (e) { let binaryData = e.target.result; setFont(binaryData); let otfReader = new OTFReader({ // subset: [0x31, 0x32, 0x33] }); let data = otfReader.read(binaryData); console.log(data); showOTFGlyf(data); }; reader.onerror = function (e) { console.error(e); }; reader.readAsArrayBuffer(file); } let entry = { /** * 初始化 */ init() { let upFile = document.getElementById('upload-file'); upFile.addEventListener('change', onUpFileChange); ajaxFile({ type: 'binary', url: './test/BalladeContour.otf', onSuccess(binaryData) { setFont(binaryData); let otfReader = new OTFReader({ // subset: [0x31, 0x32, 0x33] }); let data = otfReader.read(binaryData); console.log(data); showOTFGlyf(data); }, onError() { console.error('error read file'); } }); $('#font-list').delegate('li', 'click', function (e) { $('#font-list li').removeClass('selected'); $(this).addClass('selected'); showGlyf(+$(this).attr('data-code')); }); } }; entry.init(); <|start_filename|>demo/js/ttfwriter.js<|end_filename|> /** * @file ttfwriter.js * @author mengke01 * @date * @description * ttfwriter 入口 */ import TTFReader from 'fonteditor-core/ttf/ttfreader'; import TTFWriter from 'fonteditor-core/ttf/ttfwriter'; import ttf2base64 from 'fonteditor-core/ttf/ttf2base64'; let entry = { /** * 初始化 */ init() { $.getJSON('./data/baiduHealth.json', function (ttf) { let reader = new TTFReader(); let writer = new TTFWriter(); let buffer = writer.write(ttf); let ttfData = reader.read(buffer); console.log(ttfData); let base64str = ttf2base64(buffer); let saveBtn = $('.saveas'); saveBtn.attr('href', base64str); saveBtn.attr('download', 'save.ttf'); }); } }; entry.init(); <|start_filename|>demo/js/index.js<|end_filename|> /** * @file 入口文件 * @author mengke01(<EMAIL>) */ import {loadFile} from 'fonteditor-core/common/ajaxFile'; import fonteditor from 'fonteditor-core/main'; async function main() { let buffer = await loadFile('./demo/test/fonteditor.ttf'); let font = new fonteditor.Font(buffer); console.log('ttf', font.data); buffer = await loadFile('./demo/test/fonteditor.eot'); font = new fonteditor.Font(buffer, {type: 'eot'}); console.log('eot', font.data); buffer = await loadFile('./demo/test/fonteditor.woff'); font = new fonteditor.Font(buffer, {type: 'woff', inflate: window.pako.inflate}); console.log('woff', font.data); buffer = await loadFile('./demo/test/fonteditor.svg', 'text'); font = new fonteditor.Font(buffer, {type: 'svg'}); console.log('svg', font.data); buffer = await loadFile('./demo/test/BalladeContour.otf'); font = new fonteditor.Font(buffer, {type: 'otf'}); console.log('otf', font.data); } main(); <|start_filename|>src/ttf/svg/svgnode2contours.js<|end_filename|> /** * @file svg节点转字形轮廓 * @author mengke01(<EMAIL>) */ import path2contours from './path2contours'; import oval2contour from './oval2contour'; import polygon2contour from './polygon2contour'; import rect2contour from './rect2contour'; import parseTransform from './parseTransform'; import contoursTransform from './contoursTransform'; // 支持的解析器集合 const support = { path: { parse: path2contours, // 解析器 params: ['d'], // 参数列表 contours: true // 是否是多个轮廓 }, circle: { parse: oval2contour, params: ['cx', 'cy', 'r'] }, ellipse: { parse: oval2contour, params: ['cx', 'cy', 'rx', 'ry'] }, rect: { parse: rect2contour, params: ['x', 'y', 'width', 'height'] }, polygon: { parse: polygon2contour, params: ['points'] }, polyline: { parse: polygon2contour, params: ['points'] } }; /** * svg节点转字形轮廓 * * @param {Array} xmlNodes xml节点集合 * @return {Array|false} 轮廓数组 */ export default function svgnode2contours(xmlNodes) { let i; let length; let j; let jlength; let segment; // 当前指令 const parsedSegments = []; // 解析后的指令 if (xmlNodes.length) { for (i = 0, length = xmlNodes.length; i < length; i++) { const node = xmlNodes[i]; const name = node.tagName; if (support[name]) { const supportParams = support[name].params; const params = []; for (j = 0, jlength = supportParams.length; j < jlength; j++) { params.push(node.getAttribute(supportParams[j])); } segment = { name, params, transform: parseTransform(node.getAttribute('transform')) }; if (node.parentNode) { let curNode = node.parentNode; const transforms = segment.transform || []; let transAttr; const iterator = function (t) { transforms.unshift(t); }; while (curNode !== null && curNode.tagName !== 'svg') { transAttr = curNode.getAttribute('transform'); if (transAttr) { parseTransform(transAttr).reverse().forEach(iterator); } curNode = curNode.parentNode; } segment.transform = transforms.length ? transforms : null; } parsedSegments.push(segment); } } } if (parsedSegments.length) { const result = []; for (i = 0, length = parsedSegments.length; i < length; i++) { segment = parsedSegments[i]; const parser = support[segment.name]; const contour = parser.parse.apply(null, segment.params); if (contour && contour.length) { let contours = parser.contours ? contour : [contour]; // 如果有变换则应用变换规则 if (segment.transform) { contours = contoursTransform(contours, segment.transform); } for (j = 0, jlength = contours.length; j < jlength; j++) { result.push(contours[j]); } } } return result; } return false; } <|start_filename|>src/ttf/ttf2woff.js<|end_filename|> /** * @file ttf转换为woff * @author mengke01(<EMAIL>) * * woff format: * http://www.w3.org/TR/2012/REC-WOFF-20121213/ * * references: * https://github.com/fontello/ttf2woff * https://github.com/nodeca/pako */ /* eslint-disable no-multi-spaces */ import Reader from './reader'; import Writer from './writer'; import string from '../common/string'; import utilString from './util/string'; import error from './error'; import config from './data/default'; /** * metadata 转换成XML * * @param {Object} metadata metadata * * @example * metadata json: * * { * "uniqueid": "", * "vendor": { * "name": "", * "url": "" * }, * "credit": [ * { * "name": "", * "url": "", * "role": "" * } * ], * "description": "", * "license": { * "id": "", * "url": "", * "text": "" * }, * "copyright": "", * "trademark": "", * "licensee": "" * } * * @return {string} xml字符串 */ function metadata2xml(metadata) { let xml = '' + '<?xml version="1.0" encoding="UTF-8"?>' + '<metadata version="1.0">'; metadata.uniqueid = metadata.uniqueid || (config.fontId + '.' + Date.now()); xml += '<uniqueid id="' + string.encodeHTML(metadata.uniqueid) + '" />'; if (metadata.vendor) { xml += '<vendor name="' + string.encodeHTML(metadata.vendor.name) + '"' + ' url="' + string.encodeHTML(metadata.vendor.url) + '" />'; } if (metadata.credit) { xml += '<credits>'; const credits = metadata.credit instanceof Array ? metadata.credit : [metadata.credit]; credits.forEach((credit) => { xml += '<credit name="' + string.encodeHTML(credit.name) + '"' + ' url="' + string.encodeHTML(credit.url) + '"' + ' role="' + string.encodeHTML(credit.role || 'Contributor') + '" />'; }); xml += '</credits>'; } if (metadata.description) { xml += '<description><text xml:lang="en">' + string.encodeHTML(metadata.description) + '</text></description>'; } if (metadata.license) { xml += '<license url="' + string.encodeHTML(metadata.license.url) + '"' + ' id="' + string.encodeHTML(metadata.license.id) + '"><text xml:lang="en">'; xml += string.encodeHTML(metadata.license.text); xml += '</text></license>'; } if (metadata.copyright) { xml += '<copyright><text xml:lang="en">'; xml += string.encodeHTML(metadata.copyright); xml += '</text></copyright>'; } if (metadata.trademark) { xml += '<trademark><text xml:lang="en">' + string.encodeHTML(metadata.trademark) + '</text></trademark>'; } if (metadata.licensee) { xml += '<licensee name="' + string.encodeHTML(metadata.licensee) + '"/>'; } xml += '</metadata>'; return xml; } /** * ttf格式转换成woff字体格式 * * @param {ArrayBuffer} ttfBuffer ttf缓冲数组 * @param {Object} options 选项 * @param {Object} options.metadata 字体相关的信息 * @param {Object} options.deflate 压缩相关函数 * * @return {ArrayBuffer} woff格式byte流 */ export default function ttf2woff(ttfBuffer, options = {}) { // woff 头部结构 const woffHeader = { signature: 0x774F4646, // for woff flavor: 0x10000, // for ttf length: 0, numTables: 0, reserved: 0, totalSfntSize: 0, majorVersion: 0, minorVersion: 0, metaOffset: 0, metaLength: 0, metaOrigLength: 0, privOffset: 0, privLength: 0 }; const ttfReader = new Reader(ttfBuffer); let tableEntries = []; const numTables = ttfReader.readUint16(4); // 读取ttf表个数 let tableEntry; let deflatedData; let i; let l; if (numTables <= 0 || numTables > 100) { error.raise(10101); } // 读取ttf表索引信息 ttfReader.seek(12); for (i = 0; i < numTables; ++i) { tableEntry = { tag: ttfReader.readString(ttfReader.offset, 4), checkSum: ttfReader.readUint32(), offset: ttfReader.readUint32(), length: ttfReader.readUint32() }; const entryOffset = ttfReader.offset; if (tableEntry.tag === 'head') { // 读取font revision woffHeader.majorVersion = ttfReader.readUint16(tableEntry.offset + 4); woffHeader.minorVersion = ttfReader.readUint16(tableEntry.offset + 6); } // ttf 表数据 const sfntData = ttfReader.readBytes(tableEntry.offset, tableEntry.length); // 对数据进行压缩 if (options.deflate) { deflatedData = options.deflate(sfntData); // 这里需要判断是否压缩后数据小于原始数据 if (deflatedData.length < sfntData.length) { tableEntry.data = deflatedData; tableEntry.deflated = true; } else { tableEntry.data = sfntData; } } else { tableEntry.data = sfntData; } tableEntry.compLength = tableEntry.data.length; tableEntries.push(tableEntry); ttfReader.seek(entryOffset); } if (!tableEntries.length) { error.raise(10204); } // 对table进行排序 tableEntries = tableEntries.sort((a, b) => a.tag === b.tag ? 0 : a.tag < b.tag ? -1 : 1); // 计算offset和 woff size let woffSize = 44 + 20 * numTables; // header size + table entries let ttfSize = 12 + 16 * numTables; for (i = 0, l = tableEntries.length; i < l; ++i) { tableEntry = tableEntries[i]; tableEntry.offset = woffSize; // 4字节对齐 woffSize += tableEntry.compLength + (tableEntry.compLength % 4 ? 4 - tableEntry.compLength % 4 : 0); ttfSize += tableEntry.length + (tableEntry.length % 4 ? 4 - tableEntry.length % 4 : 0); } // 计算metaData let metadata = null; if (options.metadata) { const xml = utilString.toUTF8Bytes(metadata2xml(options.metadata)); if (options.deflate) { deflatedData = options.deflate(xml); if (deflatedData.length < xml.length) { metadata = deflatedData; } else { metadata = xml; } } else { metadata = xml; } woffHeader.metaLength = metadata.length; woffHeader.metaOrigLength = xml.length; woffHeader.metaOffset = woffSize; // metadata header + length woffSize += woffHeader.metaLength + (woffHeader.metaLength % 4 ? 4 - woffHeader.metaLength % 4 : 0); } woffHeader.numTables = tableEntries.length; woffHeader.length = woffSize; woffHeader.totalSfntSize = ttfSize; // 写woff数据 const woffWriter = new Writer(new ArrayBuffer(woffSize)); // 写woff头部 woffWriter.writeUint32(woffHeader.signature); woffWriter.writeUint32(woffHeader.flavor); woffWriter.writeUint32(woffHeader.length); woffWriter.writeUint16(woffHeader.numTables); woffWriter.writeUint16(woffHeader.reserved); woffWriter.writeUint32(woffHeader.totalSfntSize); woffWriter.writeUint16(woffHeader.majorVersion); woffWriter.writeUint16(woffHeader.minorVersion); woffWriter.writeUint32(woffHeader.metaOffset); woffWriter.writeUint32(woffHeader.metaLength); woffWriter.writeUint32(woffHeader.metaOrigLength); woffWriter.writeUint32(woffHeader.privOffset); woffWriter.writeUint32(woffHeader.privLength); // 写woff表索引 for (i = 0, l = tableEntries.length; i < l; ++i) { tableEntry = tableEntries[i]; woffWriter.writeString(tableEntry.tag); woffWriter.writeUint32(tableEntry.offset); woffWriter.writeUint32(tableEntry.compLength); woffWriter.writeUint32(tableEntry.length); woffWriter.writeUint32(tableEntry.checkSum); } // 写表数据 for (i = 0, l = tableEntries.length; i < l; ++i) { tableEntry = tableEntries[i]; woffWriter.writeBytes(tableEntry.data); if (tableEntry.compLength % 4) { woffWriter.writeEmpty(4 - tableEntry.compLength % 4); } } // 写metadata if (metadata) { woffWriter.writeBytes(metadata); if (woffHeader.metaLength % 4) { woffWriter.writeEmpty(4 - woffHeader.metaLength % 4); } } return woffWriter.getBuffer(); } <|start_filename|>src/ttf/util/optimizettf.js<|end_filename|> /** * @file 对ttf对象进行优化,查找错误,去除冗余点 * @author mengke01(<EMAIL>) */ import reduceGlyf from './reduceGlyf'; import pathCeil from '../../graphics/pathCeil'; /** * 对ttf对象进行优化 * * @param {Object} ttf ttf对象 * @return {true|Object} 错误信息 */ export default function optimizettf(ttf) { const checkUnicodeRepeat = {}; // 检查是否有重复代码点 const repeatList = []; ttf.glyf.forEach((glyf, index) => { if (glyf.unicode) { glyf.unicode = glyf.unicode.sort(); // 将glyf的代码点按小到大排序 glyf.unicode.sort((a, b) => a - b).forEach((u) => { if (checkUnicodeRepeat[u]) { repeatList.push(index); } else { checkUnicodeRepeat[u] = true; } }); } if (!glyf.compound && glyf.contours) { // 整数化 glyf.contours.forEach((contour) => { pathCeil(contour); }); // 缩减glyf reduceGlyf(glyf); } // 整数化 glyf.xMin = Math.round(glyf.xMin || 0); glyf.xMax = Math.round(glyf.xMax || 0); glyf.yMin = Math.round(glyf.yMin || 0); glyf.yMax = Math.round(glyf.yMax || 0); glyf.leftSideBearing = Math.round(glyf.leftSideBearing || 0); glyf.advanceWidth = Math.round(glyf.advanceWidth || 0); }); // 过滤无轮廓字体,如果存在复合字形不进行过滤 if (!ttf.glyf.some((a) => a.compound)) { ttf.glyf = ttf.glyf.filter((glyf, index) => index === 0 || glyf.contours && glyf.contours.length); } if (!repeatList.length) { return true; } return { repeat: repeatList }; } <|start_filename|>test/node-spec/otf2ttf.spec.js<|end_filename|> /** * @file oft2ttf * @author mengke01(<EMAIL>) */ const assert = require('assert'); const fs = require('fs'); const OTFReader = require('./fonteditor-core').OTFReader; const otf2ttfobject = require('./fonteditor-core').otf2ttfobject; const TTFWriter = require('./fonteditor-core').TTFWriter; const util = require('./util'); function readotf(file) { let data = fs.readFileSync(file); let buffer = util.toArrayBuffer(data); let fontObject = new OTFReader().read(buffer); return fontObject; } describe('otf2ttf', function () { it('otf2ttf', function () { let fontObject = readotf(__dirname + '/../data/BalladeContour.otf'); let ttfBuffer = new TTFWriter().write(otf2ttfobject(fontObject)); // test assert.ok(util.toBuffer(ttfBuffer).length, 'test otf2ttf'); }); }); <|start_filename|>demo/js/glyfsvg.js<|end_filename|> /** * @file glyfsvg.js * @author mengke01 * @date * @description * glyf 查看 */ import TTFreader from 'fonteditor-core/ttf/ttfreader'; import TTF from 'fonteditor-core/ttf/ttf'; import ttf2base64 from 'fonteditor-core/ttf/ttf2base64'; import ajaxFile from 'fonteditor-core/common/ajaxFile'; import glyf2svg from 'fonteditor-core/ttf/util/glyf2svg'; import * as lang from 'fonteditor-core/common/lang'; import setFontface from './setFontface'; let ttf = null; // 设置字体 function setFont(arrayBuffer) { let base64 = ttf2base64(arrayBuffer); setFontface('truetype', base64, 'font-face'); } // 查看ttf glyf function showTTFGlyf(ttfData) { ttf = new TTF(ttfData); let codes = ttf.codes(); let str = ''; // 获取unicode字符 codes.forEach(function (item) { str += '<li data-code="' + item + '">' + '<span class="i-font">' + String.fromCharCode(item) + '</span>' + (item > 255 ? '\\u' + Number(item).toString(16) : item) + '</li>'; }); $('#font-list').html(str); $('#font-list li:nth-child(4)').click(); } function showGlyf(charcode) { let tpl = '' + '<svg class="glyf">' + ' <g>' + '<path class="path" d="M 0,0" />' + '</g>' + '</svg>'; let svg = $(tpl); let glyf = lang.clone(ttf.getGlyfByCode(charcode)); if (glyf.compound) { return; } // 调整大小 let width = glyf.xMax; let height = glyf.yMax - glyf.yMin; let scale = 1; if (ttf.ttf.head.unitsPerEm > 512) { scale = 512 / ttf.ttf.head.unitsPerEm; width = width * scale; height = height * scale; } let path = glyf2svg(glyf, { scale }); if (path) { svg.css({ width, height }); svg.attr('viewbox', '0 0 ' + width + ' ' + height); svg.find('.path').attr('d', path); } $('#svg-view').html(svg); } function onUpFileChange(e) { let file = e.target.files[0]; let reader = new FileReader(); reader.onload = function (e) { let binaryData = e.target.result; setFont(binaryData); let ttfReander = new TTFreader(); let ttfData = ttfReander.read(binaryData); showTTFGlyf(ttfData); }; reader.onerror = function (e) { console.error(e); }; reader.readAsArrayBuffer(file); } let entry = { /** * 初始化 */ init() { let upFile = document.getElementById('upload-file'); upFile.addEventListener('change', onUpFileChange); ajaxFile({ type: 'binary', url: './test/baiduHealth.ttf', onSuccess(binaryData) { setFont(binaryData); let ttfReander = new TTFreader(); let ttfData = ttfReander.read(binaryData); showTTFGlyf(ttfData); }, onError() { console.error('error read file'); } }); $('#font-list').delegate('li', 'click', function (e) { $('#font-list li').removeClass('selected'); $(this).addClass('selected'); showGlyf(+$(this).attr('data-code')); }); } }; entry.init(); <|start_filename|>src/ttf/table/cff/parseCFFGlyph.js<|end_filename|> /** * @file 解析cff字形 * @author mengke01(<EMAIL>) */ /** * 解析cff字形,返回直线和三次bezier曲线点数组 * * @param {Array} code 操作码 * @param {Object} font 相关联的font对象 * @param {number} index glyf索引 * @return {Object} glyf对象 */ export default function parseCFFCharstring(code, font, index) { let c1x; let c1y; let c2x; let c2y; const contours = []; let contour = []; const stack = []; const glyfs = []; let nStems = 0; let haveWidth = false; let width = font.defaultWidthX; let open = false; let x = 0; let y = 0; function lineTo(x, y) { contour.push({ onCurve: true, x, y }); } function curveTo(c1x, c1y, c2x, c2y, x, y) { contour.push({ x: c1x, y: c1y }); contour.push({ x: c2x, y: c2y }); contour.push({ onCurve: true, x, y }); } function newContour(x, y) { if (open) { contours.push(contour); } contour = []; lineTo(x, y); open = true; } function parseStems() { // The number of stem operators on the stack is always even. // If the value is uneven, that means a width is specified. const hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + font.nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } function parse(code) { let b1; let b2; let b3; let b4; let codeIndex; let subrCode; let jpx; let jpy; let c3x; let c3y; let c4x; let c4y; let i = 0; while (i < code.length) { let v = code[i]; i += 1; switch (v) { case 1: // hstem parseStems(); break; case 3: // vstem parseStems(); break; case 4: // vmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } y += stack.pop(); newContour(x, y); break; case 5: // rlineto while (stack.length > 0) { x += stack.shift(); y += stack.shift(); lineTo(x, y); } break; case 6: // hlineto while (stack.length > 0) { x += stack.shift(); lineTo(x, y); if (stack.length === 0) { break; } y += stack.shift(); lineTo(x, y); } break; case 7: // vlineto while (stack.length > 0) { y += stack.shift(); lineTo(x, y); if (stack.length === 0) { break; } x += stack.shift(); lineTo(x, y); } break; case 8: // rrcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 10: // callsubr codeIndex = stack.pop() + font.subrsBias; subrCode = font.subrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 11: // return return; case 12: // flex operators v = code[i]; i += 1; switch (v) { case 35: // flex // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 y = c4y + stack.shift(); // dy6 stack.shift(); // flex depth curveTo(c1x, c1y, c2x, c2y, jpx, jpy); curveTo(c3x, c3y, c4x, c4y, x, y); break; case 34: // hflex // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- c1x = x + stack.shift(); // dx1 c1y = y; // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = y; // dy5 x = c4x + stack.shift(); // dx6 curveTo(c1x, c1y, c2x, c2y, jpx, jpy); curveTo(c3x, c3y, c4x, c4y, x, y); break; case 36: // hflex1 // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 curveTo(c1x, c1y, c2x, c2y, jpx, jpy); curveTo(c3x, c3y, c4x, c4y, x, y); break; case 37: // flex1 // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 if (Math.abs(c4x - x) > Math.abs(c4y - y)) { x = c4x + stack.shift(); } else { y = c4y + stack.shift(); } curveTo(c1x, c1y, c2x, c2y, jpx, jpy); curveTo(c3x, c3y, c4x, c4y, x, y); break; default: console.warn('Glyph ' + index + ': unknown operator ' + (1200 + v)); stack.length = 0; } break; case 14: // endchar if (stack.length === 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } else if (stack.length === 4) { glyfs[1] = { glyphIndex: font.charset.indexOf(font.encoding[stack.pop()]), transform: {a: 1, b: 0, c: 0, d: 1, e: 0, f: 0} }; glyfs[0] = { glyphIndex: font.charset.indexOf(font.encoding[stack.pop()]), transform: {a: 1, b: 0, c: 0, d: 1, e: 0, f: 0} }; glyfs[1].transform.f = stack.pop(); glyfs[1].transform.e = stack.pop(); } else if (stack.length === 5) { if (!haveWidth) { width = stack.shift() + font.nominalWidthX; } haveWidth = true; glyfs[1] = { glyphIndex: font.charset.indexOf(font.encoding[stack.pop()]), transform: {a: 1, b: 0, c: 0, d: 1, e: 0, f: 0} }; glyfs[0] = { glyphIndex: font.charset.indexOf(font.encoding[stack.pop()]), transform: {a: 1, b: 0, c: 0, d: 1, e: 0, f: 0} }; glyfs[1].transform.f = stack.pop(); glyfs[1].transform.e = stack.pop(); } if (open) { contours.push(contour); open = false; } break; case 18: // hstemhm parseStems(); break; case 19: // hintmask case 20: // cntrmask parseStems(); i += (nStems + 7) >> 3; break; case 21: // rmoveto if (stack.length > 2 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } y += stack.pop(); x += stack.pop(); newContour(x, y); break; case 22: // hmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } x += stack.pop(); newContour(x, y); break; case 23: // vstemhm parseStems(); break; case 24: // rcurveline while (stack.length > 2) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); curveTo(c1x, c1y, c2x, c2y, x, y); } x += stack.shift(); y += stack.shift(); lineTo(x, y); break; case 25: // rlinecurve while (stack.length > 6) { x += stack.shift(); y += stack.shift(); lineTo(x, y); } c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); curveTo(c1x, c1y, c2x, c2y, x, y); break; case 26: // vvcurveto if (stack.length % 2) { x += stack.shift(); } while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x; y = c2y + stack.shift(); curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 27: // hhcurveto if (stack.length % 2) { y += stack.shift(); } while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y; curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 28: // shortint b1 = code[i]; b2 = code[i + 1]; stack.push(((b1 << 24) | (b2 << 16)) >> 16); i += 2; break; case 29: // callgsubr codeIndex = stack.pop() + font.gsubrsBias; subrCode = font.gsubrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 30: // vhcurveto while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 31: // hvcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); curveTo(c1x, c1y, c2x, c2y, x, y); } break; default: if (v < 32) { console.warn('Glyph ' + index + ': unknown operator ' + v); } else if (v < 247) { stack.push(v - 139); } else if (v < 251) { b1 = code[i]; i += 1; stack.push((v - 247) * 256 + b1 + 108); } else if (v < 255) { b1 = code[i]; i += 1; stack.push(-(v - 251) * 256 - b1 - 108); } else { b1 = code[i]; b2 = code[i + 1]; b3 = code[i + 2]; b4 = code[i + 3]; i += 4; stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); } } } } parse(code); const glyf = { // 移除重复的起点和终点 contours: contours.map(contour => { const last = contour.length - 1; if (contour[0].x === contour[last].x && contour[0].y === contour[last].y) { contour.splice(last, 1); } return contour; }), advanceWidth: width }; if (glyfs.length) { glyf.compound = true; glyf.glyfs = glyfs; } return glyf; } <|start_filename|>test/spec/common/lang.spec.js<|end_filename|> /** * @file lang * @author mengke01(<EMAIL>) */ import assert from 'assert'; import * as lang from 'fonteditor-core/common/lang'; describe('test overwrite', function () { it('test normal object', function () { let result = lang.overwrite( { x: 1 }, { x: 2 } ); assert.equal(result.x, 2); }); it('test null object', function () { let result = lang.overwrite( { x: 1 }, null ); assert.equal(result.x, 1); result = lang.overwrite( { x: 1 }, undefined ); assert.equal(result.x, 1); result = lang.overwrite( { x: 1 }, false ); assert.equal(result.x, 1); }); it('test fields', function () { let result = lang.overwrite( { x: 1 }, { x: 2 }, ['x'] ); assert.equal(result.x, 2); result = lang.overwrite( { x: 1 }, { x: 2 }, ['y'] ); assert.equal(result.x, 1); }); it('test deep overwrite', function () { let result = lang.overwrite( { level1: { x: 1 } }, { level1: { y: 3 } } ); assert.equal(result.level1.y, 3); result = lang.overwrite( { level1: { x: 1 } }, { level1: { x: 2 } } ); assert.equal(result.level1.x, 2); }); it('test null overwrite', function () { let result = lang.overwrite( { level1: { x: 1 } }, { level1: { x: null } } ); assert.equal(result.level1.x, null); }); it('test string overwrite', function () { assert.throws(function () { lang.overwrite( 'abcde', { 0: 'f' } ); }); }); }); describe('test equals', function () { it('test normal object', function () { let result = lang.equals( { x: 1 }, { x: 2 } ); assert.equal(result, false); result = lang.equals( { x: null }, { x: undefined } ); assert.equal(result, false); result = lang.equals( { x: 1 }, { x: '1' } ); assert.equal(result, false); }); it('test basic type', function () { let result = lang.equals( null, undefined ); assert.equal(result, true); result = lang.equals( 1, 2 ); assert.equal(result, false); result = lang.equals( 1, '1' ); assert.equal(result, false); }); it('test deep equals', function () { let result = lang.equals( { level1: { x: 1 } }, { level1: { y: 1 } } ); assert.equal(result, false); result = lang.equals( { level1: { x: 1 } }, { level1: { x: 1 } } ); assert.equal(result, true); }); });
smhg/fonteditor-core
<|start_filename|>ulicms/content/modules/core_forms/metadata.json<|end_filename|> { "version": "2021.3", "source": "core", "embed": false, "shy": false, "main_class": "CoreFormsController", "custom_acl": [ "forms", "forms_create", "forms_edit" ], "controllers": { "CoreFormsController": "controllers/CoreFormsController.php", "FormController": "controllers/FormController.php" }, "actions": { "forms": "templates/list.php", "forms_new": "templates/new.php", "forms_edit": "templates/edit.php" }, "objects": { "Forms": "objects/forms.php" }, "controller_function_permissions": { "FormController::createPost": "forms_create", "FormController::updatePost": "forms_edit", "FormController::deletePost": "forms_edit" } } <|start_filename|>ulicms/installer.aus/media/global.js<|end_filename|> $.ajaxSetup({ cache: false }); progress_indicator_html = '<img src="../admin/gfx/loading.gif" alt="Loading">'; $("select#language").change(function () { var language = $("select#language").val(); window.location.replace("index.php?step=1&language=" + language); }); $("form#database-login").on("submit", function (e) { e.preventDefault(); $("#loading").show(); var data = { servername: $("input[name='mysql_host']").val(), loginname: $("input[name='mysql_user']").val(), passwort: $("input[name='mysql_password']").val(), datenbank: $("input[name='mysql_database']").val(), mysql_prefix: $("input[name='mysql_prefix']").val() }; $("#error-message").hide(); $.post("index.php?submit_form=TryConnect", data, function (text, status) { $("#error-message").html(text); if (text.length <= 0) { location.replace("index.php?step=5"); return true; } else { $("#loading").hide(); $("#error-message").slideDown(); } }); $("form.show-loading-indicator-on-submit").on("submit", function (e) { $("#loading").show(); }); }); String.prototype.contains = function (it) { return this.indexOf(it) !== -1; }; function installNextDBScript() { $.post("index.php?submit_form=Install", function (text, status) { if (text.contains("<!--finish-->")) { $("form#setup-database").html(text); setTimeout(function () { location.replace("index.php?step=8"); }, 500); } else if (text.contains("<!--ok-->")) { $("form#setup-database").html(text); installNextDBScript(); } else { $("form#setup-database").html(text); } }); } $("form#setup-database").on("submit", function (e) { e.preventDefault(); $("form#setup-database").html(progress_indicator_html); installNextDBScript(); }); $("form#create-cms-config").on("submit", function (e) { e.preventDefault(); $("form#create-cms-config").html(progress_indicator_html); $.post("index.php?submit_form=CreateConfig", function (text, status) { if (text.contains("<!--ok-->")) { location.replace("index.php?step=9"); } else { $("form#create-cms-config").html(text); } }); }); $("form#admin-login").on("submit", function (e) { e.preventDefault(); var pass1 = $("#admin_password").val(); var pass2 = $("#admin_<PASSWORD>").val(); if (pass1 === "") { alert("Password can not be empty."); } else if (pass1 !== pass2) { alert("Passwords are not equal."); } else { $("form#admin-login").off("submit"); $("form#admin-login").submit(); } }); <|start_filename|>ulicms/content/modules/core_settings/js/motd.js<|end_filename|> /* global Translation */ $(() => { $("select#language").change(() => { const url = "index.php?action=motd&language=" + $("select#language option:selected").val(); location.replace(url); }); $("#motd_form").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, // FIXME: this is copy and paste code // move this to a util method beforeSerialize: () => { /* Before serialize */ updateCKEditors(); return true; }, success: () => { $("#loading").hide(); $("#message").html( "<span style=\"color:green;\">" + Translation.ChangesWasSaved + "</span>"); $("#loading").hide(); } }); }); <|start_filename|>doc-src/portable/info-text-deutsch.html<|end_filename|> <!DOCTYPE html> <html lang="de"> <head> <meta charset="utf-8"> <title>Vorstellung von UliCMS Portable</title> </head> <body> <h1>Jetzt neu: UliCMS Portable</h1> <p> <strong>UliCMS 8.0.1 Portable für Windows</strong> ist eine Instanz von <a href="https://www.apachefriends.org"><strong>XAMPP</strong></a> die mit einem vorinstallierten UliCMS 8.0.1 kommt. </p> <p>Diese Software macht es sehr einfach, UliCMS auszuprobieren, ohne sich mit der Einrichtung und Konfiguration eines Webservers rumplagen zu müssen.</p> <p>Andere Versionen von UliCMS und Versionen für andere Betriebssysteme werden demnächst erscheinen.</p> <p> <strong>Achtung:</strong> <p> Nutzen Sie diese Software nicht, um öffentliche Internetseiten zu hosten, da sie unsicher konfiguriert ist.<br /> Diese Software dient nur als Test- und Entwicklungsumgebung. </p> <h2>Installationsanleitung</h2> <p>Entpacken Sie einfach den Ordner "xampp" und kopieren Sie diesen in das Hauptverzeichnis eine Laufwerks (z.B. nach C:\).</p> <h2>Starten, Nutzung und Stoppen</h2> <ol> <li>Öffnen Sie den Ordner "xampp" und starten Sie das Programm "xampp-control".</li> <li>Wählen Sie Ihre Sprache aus.</li> <li>Klicken Sie beim Modul "Apache" auf "Starten". Eventuell müssen Sie Sicherheitsnachfragen von Ihrer Computer Firewall bestätigen.</li> <li>Klicken Sie beim Modul "MySQL" auf "Starten". Eventuell müssen Sie Sicherheitsnachfragen von Ihrer Computer Firewall bestätigen. <li>Öffnen Sie Ihren Webbrowser und öffnen Sie die Adresse: http://localhost/admin</li> <li>Melden Sie sich an.<br /> Die Standard-Zugangsdaten sind:<br /> <strong>Name:</strong> admin<br /> <strong>Passwort:</strong> password<br /> Es wird empfohlen, das umgehend zu ändern.. </li> <li>Wenn Sie fertig mit der Nutzung von UliCMS sind, "Stoppen" Sie die Module "Apache" and "MySQL" im "XAMPP Control Panel" und beenden Sie das Programm.</li> </ol> </body> </html> <|start_filename|>ulicms/content/modules/core_package_manager/metadata.json<|end_filename|> { "source": "core", "version": "2021.3", "embed": false, "controllers": { "PkgInfoController": "controllers/PkgInfoController.php", "UpdateCheckController": "controllers/UpdateCheckController.php", "PackageController": "controllers/PackageController.php" }, "main_class": "PackageController", "actions": { "sin_package_install_ok": "templates/sin_package_install_ok.php", "pkginfo": "templates/pkginfo.php", "install_method": "templates/install_method.php", "do_post_install": "templates/do_post_install.php", "install_patches": "templates/install_patches.php", "install_modules": "templates/install_modules.php", "upload_package": "templates/upload_package.php", "available_patches": "templates/available_patches.php", "upload_patches": "templates/upload_patches.php", "packages": "templates/packages/list.php", "available_modules": "templates/packages/available.php" }, "objects": { "ModuleInfoViewModel": "objects/ModuleInfoViewModel.php", "ThemeInfoViewModel": "objects/ThemeInfoViewModel.php" }, "custom_acl": [ "enable_disable_module", "list_packages", "install_packages", "upload_patches", "remove_packages", "module_settings" ], "controller_function_permissions": { "PkgInfoController::install": "install_packages", "PackageController::getModuleInfo": "list_packages", "PackageController::uninstallModule": "remove_packages", "PackageController::uninstallTheme": "remove_packages", "PackageController::toggleModule": "enable_disable_module", "PackageController::truncateInstalledPatches": "patch_management", "PackageController::getPackageLicense": "install_packages" } } <|start_filename|>ulicms/admin/scripts/vallenato/vallenato.css<|end_filename|> #accordion-container { background: #ffffff; padding: 5px 10px 10px 10px; border: 1px solid #cccccc; width: 100%; } .accordion-header { background: #ebebeb; margin: 5px 0 0 0; padding: 5px 20px; border: 1px solid #cccccc; cursor: pointer; color: #000000; } .active-header { background: #335599; background-repeat: no-repeat; background-position: right 50%; color: white; } .active-header:hover { background: url(images/active-header.gif) #335599; background-repeat: no-repeat; background-position: right 50%; color: white; } .inactive-header { background: url(images/inactive-header.gif) #ebebeb; background-repeat: no-repeat; background-position: right 50%; } .inactive-header:hover { background: url(images/inactive-header.gif) #f5f5f5; background-repeat: no-repeat; background-position: right 50%; } .accordion-content { display: none; padding: 20px; background: #ffffff; border: 1px solid #cccccc; border-top: 0; } <|start_filename|>ulicms/content/modules/core_help/docs/en/patch_install_help.html<|end_filename|> <h1>Patch management</h1> <p> Patches are files that contains fixes for bugs and security issues of a software.<br /> To use included patch management there must be two requirements given:<br /> - your PHP is fsockopen or CURL enabled<br /> - The file permissions must be set, so that PHP have read and write access to all files and folders of your UliCMS installation. </p> <h2>Install Patches</h2> <p> You can install patches just by a mouseclick in the backend Since UliCMS 9.0.0.<br /> If patches are available you will be notified by a message on the UliCMS dashboard / welcome page<br /> When you click "install patches" you get a list of available patches.<br /> Simply check the checkboxes of the patches, you want to install and then click "install selected patches". </p> <|start_filename|>ulicms/content/modules/core_settings/js/meta_keywords.js<|end_filename|> /* global Translation */ // scripts for meta keywords settings page $(function () { $("#meta_keywords_settings").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, success: () => { $("#loading").hide(); $("#message") .html(`<span style="color:green;">${Translation.ChangesWasSaved}</span>`); } }); }); <|start_filename|>ulicms/content/modules/core_settings/js/homepage_title.js<|end_filename|> /* global Translation */ $("#homepage_title_settings").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, success: () => { $("#loading").hide(); $("#message") .html(`<span style="color:green;"> ${Translation.ChangesWasSaved} </span>`); } }); <|start_filename|>ulicms/content/modules/core_settings/js/frontpage.js<|end_filename|> // The script for the frontpage settings page $(() => { $("#frontpage_settings").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, success: () => { $("#loading").hide(); $("#message").html( `<span style="color:green;"> ${Translation.ChangesWasSaved} </span>`); } }); }); <|start_filename|>ulicms/tests/fixtures/AutoEmbed/input.html<|end_filename|> <p>Foo Bar, Hello World, <a href="https://www.youtube.com/watch?v=yBJeeXmS7EA">Internet is for Cats</a>, Yes</p> <p><a href="https://www.youtube.com/watch?v=tI0TUJ-aV6c">https://www.youtube.com/watch?v=tI0TUJ-aV6c</a></p> <p><a href="https://dai.ly/x2bqyl6">https://dai.ly/x2bqyl6</a></p> <p><a href="https://www.twitch.tv/videos/293684811">https://www.twitch.tv/videos/293684811</a></p> <|start_filename|>ulicms/content/modules/core_settings/js/design.js<|end_filename|> /* global Translation */ // This script contains the code for the "design settings" page // show a message if a "design for mobile devices" is set but // Mobile_Detect is not installed const initMobileDetectNotice = () => { if ($("select[name='mobile_theme']").val() !== "" && $("#mobile_detect_notice").data("installed") === false) { $("#mobile_detect_notice").slideDown(); } else { $("#mobile_detect_notice").slideUp(); } }; const loadThemePreview = (selectField) => { const url = $(selectField).find("option:selected").data("preview-url"); const targetElement = $($(selectField).data("preview-target-element")); if (!url) { $(targetElement).hide(); return; } $(targetElement).show(); targetElement.find(".fa-spinner").show(); targetElement.find(".preview").hide(); $.ajax({ url: url, success: (result) => { targetElement.find(".preview").html(result); targetElement.find(".fa-spinner").hide(); targetElement.find(".preview").show(); }, error: (jqXHR, textStatus, errorThrown) => { targetElement.find(".fa-spinner").hide(); targetElement.find(".preview").hide(); $(targetElement).hide(); } }); }; // show a privacy warning if a google font is selected const updateFontPreview = () => { const fontFamily = $("select#default_font").val(); const fontSize = $("select#font-size").val(); const googleFont = $("#google-fonts select").val(); if (fontFamily === "google") { $("div#google-fonts").slideDown(); const url = $("#font-preview").data("google-font-url") + encodeURIComponent(googleFont); if ($("#google-font-loader").length) { $("#google-font-loader").attr("href", url); } else { $('head').append(`<link id="google-font-loader" rel="stylesheet"` + `href="${url}" type="text/css"/>`); } } else { $("div#google-fonts").slideUp(); } $("#font-preview").css( { fontFamily: fontFamily !== "google" ? fontFamily : googleFont, fontSize: fontSize } ); }; $(() => { $("#mobile_detect_notice").hide(); initMobileDetectNotice(); const fontFamily = $("select#default_font").val(); if(fontFamily === 'google'){ $("div#google-fonts").show(); } $("select[name='mobile_theme']").change(initMobileDetectNotice); $("select#default_font, select#font-size, #google-fonts select") .change(updateFontPreview); updateFontPreview(); loadThemePreview($("select[name='theme']")); loadThemePreview($("select[name='mobile_theme']")); $("select[name='theme'], select[name='mobile_theme']").change( (event) => { loadThemePreview($(event.currentTarget)); }); // ajax form submit $("#designForm").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#msgcontainer, #loading").show(); }, success: () => { $("#loading").hide(); $("#message").html( `<span style="color:green;"> ${Translation.ChangesWasSaved} </span>`); $("#msgcontainer, #loading").hide(); } }); }); <|start_filename|>ulicms/installer.aus/media/style.css<|end_filename|> body { font-family: "wf_SegoeUI", "Segoe UI", "Segoe", "Segoe WP", "Tahoma", "Verdana", "Arial", "sans-serif"; background-color: rgb(246, 245, 250); font-size: 15px; } #license, progress { width: 100%; } #header { padding-top: 10px; border: 1px solid #b7b7b7; border-top: none; background-color: #60a8bd; } #main { padding-bottom: 30px; word-wrap: break-word } #my-container { border: 1px solid #b7b7b7; border-top: none; } #navigation { padding-top: 30px; padding-bottom: 30px; } a.current-item { font-weight: bold; } #footer { margin-top: 10px; text-align: center; } #my-container { background-color: white; } #navigation li { margin-bottom: 5px; } select, input:not([type="checkbox"]):not([type="radio"]) { width: 100%; } #loading, #error-message { display: none; margin-top: 20px; } kbd, pre, .img-rounded, .img-thumbnail, .img-circle, .form-control, .btn, .btn-link, .dropdown-menu, .list-group-item, .input-group-addon, .input-group-btn, .navbar, .navbar-toggle, .icon-bar, .breadcrumb, .pagination, .progress, .badge, .jumbotron, .thumbnail, .panel, .well, .modal-content, .tooltip-inner, .popover, .popover-title, .alert, .paginate_button, *[class^="select2"] { border-radius: 0 !important; } <|start_filename|>ulicms/admin/scripts/utils/editors.js<|end_filename|> const refreshCodeMirrors = () => { $('.CodeMirror').each((i, el) => el.CodeMirror.refresh() ); }; const updateCKEditors = () => { if (typeof CKEDITOR === "undefined") { return; } for (instance in CKEDITOR.instances) { CKEDITOR.instances[instance].updateElement(); } }; <|start_filename|>ulicms/content/modules/core_settings/js/privacy.js<|end_filename|> // Script for the "privacy settings" page $(() => { // Change language // Privacy settings are language specific $("select#language").change( () => { const url = "index.php?action=privacy_settings&language=" + $("select#language option:selected").val(); location.replace(url); }); // expand privacy policy checkbox options when enabled $("#privacy_policy_checkbox_enable").change((event) => { const checked = $(event.currentTarget).is(":checked"); if (checked) { $("#privacy_policy_checkbox_text_container").slideDown(); // CodeMirror is not correctly initialized if initially hidden. Reinitialize the CodeMirror Editor after toggling the editor refreshCodeMirrors(); } else { $("#privacy_policy_checkbox_text_container").slideUp(); } }); }); <|start_filename|>ulicms/admin/scripts/utils/ajax.js<|end_filename|> const bindAjaxLinks = (root) => { $(root).find("a.is-not-ajax").click((event) => { $(".mainmenu").hide(); $("#menu-toggle").removeClass('is-open'); if (event.target.target === "_blank") { return; } ajaxLoadSpinner.show(); }); $(root).find("a.is-ajax").click((event) => { event.preventDefault(); event.stopPropagation(); const target = $(event.currentTarget); const originalUrl = target.attr("href"); let url = `${originalUrl}&only_content=true`; if (target.hasClass("full-minified")) { url += "&full_minified=true" } const mainMenu = $(".mainmenu"); $("#menu-toggle").removeClass('is-open'); const isMenuEntry = mainMenu.has(target); mainMenu.hide(); ajaxLoadSpinner.show(); const contentContainer = $("#content-container"); $(contentContainer).load(url, (response, status, xhr) => { ajaxLoadSpinner.hide(); if (status === "error") { const msg = `${xhr.status} ${xhr.statusText}`; bootbox.alert( $('<div/>').text(msg).html()); return; } else if (isMenuEntry) { mainMenu.find("a").removeClass("active"); target.addClass("active"); } history.pushState({ajaxUrl: url}, document.title, originalUrl); bindContentEvents(contentContainer); initDataTables(contentContainer); }); }); }; const ajaxGoTo = (url) => { $("#main-backend-content, #message").hide(); $("#main-content-loadspinner").show(); const contentContainer = $("#content-container"); $(contentContainer).load(url, (response, status, xhr) => { $("#main-backend-content").show(); $("#main-content-loadspinner").hide(); if (status === "error") { const msg = `${xhr.status} ${xhr.statusText}`; bootbox.alert( $('<div/>').text(msg).html()); return; } bindContentEvents(contentContainer); }); }; const bindContentEvents = (contentContainer) => { bindAjaxLinks(contentContainer); initRemoteAlerts(contentContainer); initSelect2(contentContainer); addCssClassToInputs(contentContainer); initBootstrapToggle(contentContainer); bindTooltips($("body")); }; const initRemoteAlerts = (rootElement) => { $(rootElement).find(".remote-alert").click((event) => { event.preventDefault(); event.stopPropagation(); setWaitCursor(); const url = $(event.currentTarget).data("url"); $.get(url, (result) => { setDefaultCursor(); bootbox.alert(result); }); }); }; const ajaxLoadSpinner = { show: () => { $("#main-content-loadspinner, #message").show(); $("#main-backend-content").hide(); }, hide: () => { $("#main-content-loadspinner, #message").hide(); $("#main-backend-content").show(); } } <|start_filename|>ulicms/content/modules/core_content/js/pages/list.js<|end_filename|> /* global Translation, bootbox */ $(() => { // init filters if (localStorage.getItem('pageFilters') === null) { localStorage.setItem( 'pageFilters', JSON.stringify(buildFiltersObject()) ); } $("#btn-go-up").click((event) => { event.preventDefault(); event.stopPropagation(); const target = $(event.target); const parentId = $("#filter_parent").val(); const url = `${target.data('url')}&id=${parentId}`; $.ajax({ method: "get", url: url, success: function (data) { const newId = data.id !== null ? data.id : 0; $("select#filter_parent").val( newId.toString() ).change(); if (newId === 0) { $("#btn-go-up").hide(); } }, error: (xhr) => alert(xhr.responseText) }); }); // confirmation on empty trash $("a#empty-trash").click((event) => { const item = $(event.currentTarget); const href = $(item).attr("href"); event.preventDefault(); bootbox.confirm(Translation.WannaEmptyTrash, (result) => { if (result) { location.replace(href); } }); }); // "Show Filters" switch $("#show_filters").change((event) => { const url = $(event.target).data("url"); const isChecked = $(event.target).is(':checked'); if (isChecked) { $(".filters").slideDown(); } else { $(".filters").slideUp(); } $.ajax({ method: "get", url: url, error: (xhr) => alert(xhr.responseText) }); }); loadParentPages().then(() => { loadFiltersFromlocalStorage(); bindSelectOnChange(); const dataTable = $(".tablesorter").DataTable(); dataTable.ajax.reload(); dataTable.page(1); }); }); const updateGoUpButton = () => { const parentId = $("select#filter_parent").val(); if (parentId && parseInt(parentId) > 0) { $("#btn-go-up").show(); } else { $("#btn-go-up").hide(); } }; const bindSelectOnChange = () => { // fetch updated results after filter values where changed $(".filters select").change((event) => { const target = event.target; const dataTable = $(".tablesorter").DataTable(); dataTable.ajax.reload(); dataTable.page(1); updateGoUpButton(); localStorage.setItem( 'pageFilters', JSON.stringify(buildFiltersObject()) ); if ($(target).is("#filter_language") || $(target).is("#filter_menu")) { loadParentPages(); } }); }; const loadFiltersFromlocalStorage = () => { if (localStorage.getItem('pageFilters') === null) { return; } const filters = JSON.parse(localStorage.getItem('pageFilters')); $("#filter_type").val(filters.type).trigger("change"); $("#filter_category").val(filters.category_id).trigger("change"); const filterParent = $("#filter_parent"); const parentOptionExists = filterParent.find(`option[value='${filters.parent_id}']`).length; const parentId = parentOptionExists ? filters.parent_id : "all"; $("#filter_approved").val(filters.approved).trigger("change"); $("#filter_language").val(filters.language).trigger("change"); $("#filter_menu").val(filters.menu).trigger("change"); $("#filter_active").val(filters.active).trigger("change"); $("#filter_parent").val(parentId).trigger("change"); updateGoUpButton(); }; // filter parent pages by selected language and menu const loadParentPages = () => { const previousParentPage = $("#filter_parent").val(); const data = { csrf_token: $("input[name=csrf_token]") .first() .val(), language: $("#filter_language").val(), menu: $("#filter_menu").val() }; const url = $(".filter-wrapper") .first() .data("parent-pages-url"); return $.get(url, data, function (text, status) { $("#filter_parent").html(text); $("#filter_parent").val(previousParentPage).trigger("change"); }); }; <|start_filename|>ulicms/lib/js/global.js<|end_filename|> /* global DocumentTouch, Translation */ $(() => { // delete form handling with confirmation $("form.delete-form").submit(() => confirm(Translation.AskForDelete) ); }); const isTouchDevice = () => { const prefixes = ' -webkit- -moz- -o- -ms- '.split(' '); const mq = (query) => { return window.matchMedia(query).matches; }; if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { return true; } // include the 'heartz' as a way to have a non matching MQ to help terminate the join // https://git.io/vznFH const query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''); return mq(query); }; <|start_filename|>ulicms/content/modules/core_content/js/banners.js<|end_filename|> // This the script for the advertisement banners list page $(() => { // when select another language $('#category_id').on( 'change', () => { const valueSelected = $('#category_id').val(); location.replace("index.php?action=banner&filter_category=" + valueSelected); }); // delete button $("form.delete-form").ajaxForm({ success: (responseText, statusText, xhr, $form) => { const action = $($form).attr("action"); const params = new URLSearchParams(action); const id = params.get("banner"); const list_item_id = `dataset-${id}`; const tr = $(`tr#${list_item_id}`); $(tr).fadeOut(); } }); }); <|start_filename|>ulicms/licenses.json<|end_filename|> [{"department":"kessler","relatedTo":"stuff","name":"@fortawesome/fontawesome-free","licensePeriod":"perpetual","material":"material","licenseType":"(CC-BY-4.0 AND OFL-1.1 AND MIT)","link":"git+https://github.com/FortAwesome/Font-Awesome.git","remoteVersion":"5.15.4","installedVersion":"5.15.4","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"bootbox","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git://github.com/makeusabrew/bootbox.git","remoteVersion":"4.4.0","installedVersion":"4.x","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"bootstrap","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/twbs/bootstrap.git","remoteVersion":"3.4.1","installedVersion":"3.x","author":"The Bootstrap Authors"},{"department":"kessler","relatedTo":"stuff","name":"bootstrap-toggle","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/minhur/bootstrap-toggle.git","remoteVersion":"2.2.2","installedVersion":"2.x","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"codemirror-minified","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/Dominator008/CodeMirror-minified.git","remoteVersion":"5.63.0","installedVersion":"5.63.0"},{"department":"kessler","relatedTo":"stuff","name":"datatables","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/DataTables/DataTables.git","remoteVersion":"1.10.18","installedVersion":"*","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"jquery","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/jquery/jquery.git","remoteVersion":"3.6.0","installedVersion":"3.6.0","author":"OpenJS Foundation and other contributors"},{"department":"kessler","relatedTo":"stuff","name":"jquery-datetimepicker","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/xdan/datetimepicker.git","remoteVersion":"2.5.21","installedVersion":"*","author":"Chupurnov"},{"department":"kessler","relatedTo":"stuff","name":"jquery-form","licensePeriod":"perpetual","material":"material","licenseType":"(LGPL-2.1+ OR MIT)","link":"git+https://github.com/jquery-form/form.git","remoteVersion":"4.3.0","installedVersion":"4.3.0"},{"department":"kessler","relatedTo":"stuff","name":"jscolor-picker","licensePeriod":"perpetual","material":"material","licenseType":"GPL-3.0","link":"git+https://github.com/clementdemily/jscolor.git","remoteVersion":"2.0.4","installedVersion":"*","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"password-strength-meter","licensePeriod":"perpetual","material":"material","licenseType":"GPL-3.0","link":"git+ssh://git@github.com/elboletaire/password-strength-meter.git","remoteVersion":"2.1.0","installedVersion":"2.1.0","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"select2","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git://github.com/select2/select2.git","remoteVersion":"4.0.13","installedVersion":"4.0.13","author":"<NAME>"},{"department":"kessler","relatedTo":"stuff","name":"slug","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git://github.com/Trott/node-slug.git","remoteVersion":"2.1.1","installedVersion":"2.1.1","author":"dodo"},{"department":"kessler","relatedTo":"stuff","name":"vanilla-toast","licensePeriod":"perpetual","material":"material","licenseType":"MIT","link":"git+https://github.com/talsu/vanilla-toast.git","remoteVersion":"0.5.0","installedVersion":"0.5.0","author":"talsu"},{"department":"kessler","relatedTo":"stuff","name":"zenscroll","licensePeriod":"perpetual","material":"material","licenseType":"Unlicense","link":"git+https://github.com/zengabor/zenscroll.git","remoteVersion":"4.0.2","installedVersion":"*","author":"<NAME>"}] <|start_filename|>ulicms/content/modules/core_users/js/form.js<|end_filename|> /* global bootbox, UserTranslation */ // This file contains the code for the user profil edit page // check if password field and password repeat are equal // then colorize the inputs const validatePasswords = () => { const field1 = $("#password"); const field2 = $("#password_repeat"); const val1 = $(field1).val(); const val2 = $(field2).val(); if (val1 && val2 && val1 !== val2) { // if the password fields are NOT equal then make the fields red $(field1).css("background-color", "red"); $(field1).addClass("invalid"); $(field2).css("background-color", "red"); $(field1).css("color", "white"); $(field2).css("color", "white"); } else { // if the password fields are empty then unset background color // and text color $(field1).css("background-color", ""); $(field1).removeClass("invalid"); $(field2).css("background-color", ""); $(field1).css("color", "inherit"); $(field2).css("color", "inherit"); } }; const submitPasswordForm = (event) => { event.preventDefault(); validatePasswords(event); if ($("#password").hasClass("invalid")) { bootbox.alert(UserTranslation.PasswordsNotEqual, () => $("#password").focus() ); return false; } $("form#edit-user").off("submit").submit(); }; $(() => { $("#password").on("blur", validatePasswords); $("#password_repeat").on("blur", validatePasswords); $("form#edit-user").on("submit", submitPasswordForm); }); <|start_filename|>ulicms/tests/fixtures/renderers/json.json<|end_filename|> { "title": "Lorem Ipsum", "content": "<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&nbsp;</p>\r\n\r\n<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.&nbsp;</p>\r\n\r\n<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.&nbsp;</p>\r\n\r\n<p>Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.&nbsp;</p>\r\n\r\n<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis.&nbsp;</p>", "meta_description": "Eine kurzer Beschreibungstext", "meta_keywords": "Stichwort 1, Stichwort 2, Stichwort 3", "data": {} } <|start_filename|>ulicms/content/modules/fortune2/metadata.json<|end_filename|> { "source": "extend", "controllers": { "Fortune": "fortune.php" }, "main_class": "Fortune", "version": "0.2.3", "manufacturer_name": "<NAME>", "manufacturer_url": "https://www.ulicms.de", "embed": true, "admin_permission": "fortune_settings", "custom_acl": [ "fortune_settings", "fortune2_post", "fortune2_get" ], "controller_function_permissions": { "Fortune::doSomethingPost": "fortune2_post", "Fortune::doSomethingGet": "fortune2_get" }, "actions": { "fortune": "templates/action.php" } } <|start_filename|>ulicms/content/modules/core_content/metadata.json<|end_filename|> { "source": "core", "version": "2021.3", "embed": false, "custom_acl": [ "pages", "pages_approve_own", "pages_approve_others", "pages_edit_own", "pages_edit_others", "pages_change_owner", "pages_create", "pages_show_positions", "pages_edit_permissions", "default_access_restrictions_edit", "banners", "banners_create", "banners_edit", "categories", "categories_create", "categories_edit" ], "actions": { "contents": "templates/contents.php", "pages": "templates/pages/list.php", "pages_new": "templates/pages/new.php", "pages_edit": "templates/pages/edit.php", "categories": "templates/categories.php", "banner": "templates/banners/list.php", "banner_new": "templates/banners/new.php", "banner_edit": "templates/banners/edit.php" }, "controllers": { "PageController": "controllers/PageController.php", "CategoryController": "controllers/CategoryController.php", "BannerController": "controllers/BannerController.php" }, "objects": { "UliCMS\\CoreContent\\Models\\ViewModels\\DiffViewModel": "models/DiffViewModel.php", "UliCMS\\CoreContent\\PageTableRenderer": "utils/PageTableRenderer.php", "UliCMS\\CoreContent\\Partials\\ViewButtonRenderer": "utils/buttons/ViewButtonRenderer.php", "UliCMS\\CoreContent\\Partials\\EditButtonRenderer": "utils/buttons/EditButtonRenderer.php", "UliCMS\\CoreContent\\Partials\\DeleteButtonRenderer": "utils/buttons/DeleteButtonRenderer.php", "UliCMS\\CoreContent\\Partials\\UnDeleteButtonRenderer": "utils/buttons/UnDeleteButtonRenderer.php", "UliCMS\\CoreContent\\UIUtils": "utils/UIUtils.php" }, "controller_function_permissions": { "PageController::createPost": "pages_create", "PageController::editPost": "pages", "PageController::undeletePost": "pages", "PageController::empyTrash": "pages", "PageController::toggleFilters": "pages", "PageController::toggleShowPositions": "pages_show_positions", "PageController::nextFreeSlug": "pages", "PageController::getPages": "pages", "PageController::filterParentPages": "pages", "PageController::getParentSelection": "pages", "PageController::*" : "pages", "PageController::getCKEditorLinkList": "", "CategoryController::createPost": "categories_create", "CategoryController::updatePost": "categories_edit", "CategoryController::deletePost": "categories", "BannerController::deletePost": "banners", "BannerController::createPost": "banners", "BannerController::updatePost": "banners" } } <|start_filename|>ulicms/content/modules/core_settings/js/languages.js<|end_filename|> /* global bootbox */ $(() => { $(".btn-make-default").click((event) => { event.preventDefault(); const url = $(event.target).attr("href"); const message = $(event.target).attr("data-message"); bootbox.confirm(message, (result) => { if (result) { location.replace(url); } }); }); }); <|start_filename|>ulicms/content/modules/oneclick_upgrade/js/settings.js<|end_filename|> const updateChannelHelp = () => { $("#help-texts > div").hide(); const selected = $("#oneclick_upgrade_channel").val(); $(`#help-texts > div[data-channel='${selected}']`).show(); }; updateChannelHelp(); $("#oneclick_upgrade_channel").change(updateChannelHelp); <|start_filename|>ulicms/content/modules/core_history/metadata.json<|end_filename|> { "source": "core", "version": "2021.3", "embed": false, "actions": { "view_diff": "templates/view_diff.php", "restore_version": "templates/restore_version.php" }, "controllers": { "HistoryController": "controllers/HistoryController.php" }, "objects": { "finediff": "3rdparty/finediff.php" }, "controller_function_permissions": { "FaviconController::doRestore": "pages" } } <|start_filename|>ulicms/admin/ckeditor/config.js<|end_filename|> /** * @license Copyright (c) 2003-2014, CKSource - <NAME>. All rights * reserved. For licensing, see LICENSE.md or * http://ckeditor.com/license */ CKEDITOR.editorConfig = function (config) { // config.language = 'de'; // Bootstrap soll eingebunden werden config.contentsCss = [CKEDITOR.basePath + 'contents.css', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css']; config.ShiftEnterMode = 'p'; // allow all html tags config.allowedContent = true; config.height = '300px'; config.image_prefillDimensions = false; // responsive filemanager if (window.location.href.indexOf("admin/") !== -1) { config.filebrowserBrowseUrl = 'fm/dialog.php?type=2&editor=ckeditor&fldr=files'; config.filebrowserImageBrowseUrl = 'fm/dialog.php?type=1&editor=ckeditor&fldr=images'; config.filebrowserFlashBrowseUrl = 'fm/dialog.php?type=2&editor=ckeditor&fldr=flash'; } else { config.filebrowserBrowseUrl = 'admin/fm/dialog.php?type=2&editor=ckeditor&fldr=files'; config.filebrowserImageBrowseUrl = 'admin/fm/dialog.php?type=1&editor=ckeditor&fldr=images'; config.filebrowserFlashBrowseUrl = 'admin/fm/dialog.php?type=2&editor=ckeditor&fldr=flash'; } config.entities_latin = false; config.uiColor = '#d1d8d0'; config.removePlugins = "newpage,templates,preview,print,save,language,autoembed"; // disable contextmenu on touchy things // to make it possible to select text in editor if (isTouchDevice()) { console.log("CKEditor: This is a touchscreen device. Disable Context Menu"); // We need also to disable plugins which are dependent on contextmenu config.removePlugins += ',colordialog,liststyle,tabletools,contextmenu,'; } else { console.log("CKEditor: Can't touch this"); } config.autoGrow_onStartup = false; config.extraPlugins = 'link,font'; }; <|start_filename|>ulicms/content/modules/core_users/js/list.js<|end_filename|> /* global bootbox */ $(() => { $(".avatar").click((event) => { const target = $(event.currentTarget); const img = document.createElement("img"); img.src = target.attr("src"); const headline = document.createElement("h3"); headline.innerText = target.data("name"); const wrap = document.createElement("div"); wrap.append(headline); wrap.append(img) bootbox.alert(wrap.outerHTML); }); }); <|start_filename|>ulicms/content/modules/update_manager/scripts/update_manager.js<|end_filename|> /* global bootbox */ $(() => { $("form#update-manager").submit((event) => { event.preventDefault(); const packages = $('form#update-manager .package:checked').map( (_, el) => $(el).val() ).get(); if (packages.length > 0) { const url = "index.php?action=install_modules&packages=" + packages.join(","); location.replace(url); } else { bootbox.alert($("#translation_please_select_packages").data( "translation")); } }); $('.checkall').on('click', (event) => { $("form#update-manager .package").prop('checked', event.currentTarget.checked); }); }); <|start_filename|>ulicms/content/modules/core_content/js/pages/init-codemirror.js<|end_filename|> /* global CodeMirror */ let formChanged = 0; let submitted = 0; let isCtrl = false; const isJsonString = (str) => { try { JSON.parse(str); } catch (e) { return false; } return true; }; const validateCodeMirrorJson = (cmEditor, wrapper) => { if (isJsonString(cmEditor.getValue())) { wrapper.removeClass("border-red"); wrapper.addClass("border-green"); return true; } wrapper.removeClass("border-green"); wrapper.addClass("border-red"); return false; }; $(() => { // apply codemirror source code editor to all textareas // with "codemirror" class $("textarea.codemirror").each((index, elem) => { let mode = "text/html"; // if the textarea has a data-mimetype attribute use this for syntax // higlighting scheme // else fallback to html mode if ($(elem).data("mimetype")) { mode = $(elem).data("mimetype"); } const editor = CodeMirror.fromTextArea(elem, { lineNumbers: true, matchBrackets: true, mode: mode, indentUnit: 0, indentWithTabs: false, enterMode: "keep", tabMode: "shift", readOnly: $(elem).prop("readonly") }); switch ($(elem).data("validate")) { case "json": editor.on("change", (cmEditor) => { var wrapper = $(editor.getWrapperElement()); validateCodeMirrorJson(cmEditor, wrapper); }); editor.on("blur", function (cmEditor) { var wrapper = $(editor.getWrapperElement()); if (validateCodeMirrorJson(cmEditor, wrapper)) { cmEditor.save(); } }); validateCodeMirrorJson(editor, $(editor.getWrapperElement())); break; default: editor.on("blur", function (cmEditor) { cmEditor.save(); }); } }); }); <|start_filename|>ulicms/content/modules/core_settings/js/favicon.js<|end_filename|> /* global Translation */ /* global bootbox */ $(() => { // Enable submit button after file was selected $(".btn-primary").prop('disabled', true) $("input[name=favicon_upload_file]").change( () => $(".btn-primary").prop('disabled', false) ); // Delete Favicon // show load spinner // then empty the table column $("#delete-favicon").click((event) => { const target = $(event.target); const url = target.data("url"); bootbox.confirm( `${Translation.DeleteFavicon}?`, (result) => { if (result) { $("#favicon-wrapper").hide(); $("#delete-favicon-loading").show(); $.post(url) .done((text, status) => { target.closest('td').html(''); vanillaToast.success(Translation.FaviconDeleted); }) .fail(() => { $("#delete-favicon-loading").hide(); $("#favicon-wrapper").show(); }); } }); }); }); <|start_filename|>ulicms/content/modules/core_settings/js/default_edit_restrictions.js<|end_filename|> $("form#default_edit_restrictions").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, success: () => { $("#loading").hide(); $("#message") .html(`<span style="color:green;"> ${Translation.ChangesWasSaved} </span>`); } }); <|start_filename|>ulicms/content/modules/core_help/docs/de/patch_install_help.html<|end_filename|> <h1>Patch Management</h1> <p>Patches sind Dateien, die Verbesserungen, Korrekturen von Sicherheitsproblemen oder Fehlerbehebungen für Software enthalten.</p> <p>Ab UliCMS 9.0.0 können Patches automatisch heruntergeladen und installiert werden.</p> <p> Damit diese Funktionalität genutzt werden kann, müssen die Dateirechte so frei gesetzt sein, dass PHP auf sämtliche Dateien der Installation Lese- und Schreibzugriff hat und PHP<br /> Daten von externen Servern nachladen kann (per fsockopen oder curl). </p> <h2>Patches installieren</h2> <p> Sofern Patches verfügbar sind, und Ihr Benutzer-Account das Recht <i>system_update</i> hat,<br /> werden Sie in dem "Willkommen" Bereich im Backend darüber informiert. </p> <p> <u>Achtung:</u><br /> Auch wenn die Patches sorgfältig getestet werden, können Fehler nie ausgeschlossen werden.<br /> Wir empfehlen Ihnen deshalb, zuvor eine Sicherung des Systems durchzuführen. </p> <p>Klicken Sie auf "Patches installieren". Sie bekommen nun eine Liste der Verfügbaren Patches angezeigt.</p> <p> Wählen Sie die zu installierenden Patches aus, in dem Sie die Häckchen setzen und klicken Sie auf<br /> "ausgewählte Patches installieren". Anschließend werden alle ausgewählten Patches heruntergeladen und entpackt. </p> <|start_filename|>ulicms/content/modules/core_media/js/audio.js<|end_filename|> // Script for list of audio media $(() => { $('#category').on( 'change', () => { const valueSelected = $('#category').val(); location.replace("index.php?action=audio&filter_category=" + valueSelected); }); const ajaxOptions = { success: (responseText, statusText, xhr, $form) => { const action = $($form).attr("action"); const params = new URLSearchParams(action); const id = params.get("delete"); const list_item_id = `dataset-${id}`; const tr = $(`tr#${list_item_id}`); $(tr).fadeOut(); } }; $("form.delete-form").ajaxForm(ajaxOptions); }); <|start_filename|>ulicms/tests/fixtures/json/default_acl.json<|end_filename|> {"audio":true,"audio_create":true,"audio_edit":true,"banners":true,"banners_create":true,"banners_edit":true,"cache":true,"categories":true,"categories_create":true,"categories_edit":true,"comments_manage":true,"community_settings":true,"dashboard":true,"default_access_restrictions_edit":true,"design":true,"enable_disable_module":true,"error_pages":true,"expert_settings":true,"expert_settings_edit":true,"extend_upgrade_helper":true,"favicon":true,"files":true,"footer_text":true,"forms":true,"forms_create":true,"forms_edit":true,"fortune2_get":true,"fortune2_post":true,"fortune_settings":true,"groups":true,"groups_create":true,"groups_edit":true,"info":true,"install_packages":true,"languages":true,"list_packages":true,"logo":true,"module_settings":true,"motd":true,"oneclick_upgrade_settings":true,"open_graph":true,"other":true,"pages":true,"pages_approve_others":true,"pages_approve_own":true,"pages_change_owner":true,"pages_create":true,"pages_edit_others":true,"pages_edit_own":true,"pages_edit_permissions":true,"pages_show_positions":true,"patch_management":true,"performance_settings":true,"privacy_settings":true,"remove_packages":true,"settings_simple":true,"spam_filter":true,"update_system":true,"upload_patches":true,"users":true,"users_create":true,"users_edit":true,"videos":true,"videos_create":true,"videos_edit":true} <|start_filename|>ulicms/admin/scripts/modules.js<|end_filename|> /* global Translation */ const uninstallModule = (url, name) => { if (confirm(Translation.AskForUninstallPackage.replace("%name%", name))) { $.ajax({ url: url, success: () => { $("li#dataset-module-" + name).slideUp(); } }); } return false; }; const uninstallTheme = (url, name) => { if (confirm(Translation.AskForUninstallPackage.replace("%name%", "theme-" + name))) { $.ajax({ url: url, success: () => $("li#dataset-theme-" + name).slideUp() }); } return false; }; $("form#truncate_installed_patches").ajaxForm( { success: () => $("div#inst_patch_slide_container").slideUp() }); <|start_filename|>doc/ulicms-2021.3-announcement.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title> UliCMS 2021.3 latest update for the third quarter of 2021 </title> <style type="text/css"> body { background-color: white; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI Emoji", "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; font-size: medium; color: rgb(50, 50, 50); margin: 0; padding: 20px; } li { margin-bottom: 20px; } </style> </head> <body> <h1> UliCMS 2021.3 latest update for the third quarter of 2021 </h1> <h2>UI Improvements</h2> <p> The user interface of the comment system got a revise. An animation was added to the hamburger menu. </p> <h2>Packages Upgraded</h2> <p> All npm und composer packages were updated. CKEditor is now at version 4.16.2. </p> <h2>Bugfixes</h2> <p> Two SQL errors happening while $db_strict_mode is true were fixed.. Es wurden zwei SQL-Fehler korrigiert, die auftreten, wenn in der Konfigurationsdatei $db_strict_mode = true ist. </p> </body> </html> <|start_filename|>ulicms/tests/fixtures/json/defaultContentTypes.json<|end_filename|> {"page":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments"]},"article":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments","#article-metadata","#article-image"]},"snippet":{"show":[".show-on-snippet","#content-editor"]},"list":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments",".list-show","#tab-list","#tab-text-position"]},"link":{"show":["#tab-link","#tab-target",".menu-stuff","#hidden-attrib","#tab-menu-image"]},"language_link":{"show":["#tab-language-link","#tab-target",".menu-stuff","#hidden-attrib","#tab-menu-image"]},"node":{"show":[".menu-stuff","#hidden-attrib"]},"image":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments","#tab-image","#tab-text-position"]},"module":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments","#tab-module","#tab-text-position"]},"video":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments","#tab-video","#tab-text-position"]},"audio":{"show":[".hide-on-non-regular",".menu-stuff","#hidden-attrib","#tab-menu-image","#tab-metadata","#custom_fields_container","#tab-target","#tab-cache-control","#tab-og","#custom_data_json","#content-editor","#btn-view-page","#tab-comments","#tab-audio","#tab-text-position"]}} <|start_filename|>ulicms/run-tests.bat<|end_filename|> @echo off vendor/bin/phpunit <|start_filename|>ulicms/admin/scripts/global.js<|end_filename|> /* global bootbox, PasswordSecurityTranslation, MenuTranslation, zenscroll, vanillaToast, GlobalTranslation */ // Internet Exploder caches AJAX requests by default $(document).ready(() => { const body = $("body"); $.ajaxSetup( { cache: false, beforeSend: (jqXHR, settings) => { // set url to get in the general error handler jqXHR.url = settings.url; }, error: (jqXHR) => { const errorMessage = `Error requesting ${jqXHR.url} - ${jqXHR.status} ${jqXHR.statusText}` console.error(errorMessage) vanillaToast.error(errorMessage); } } ); const token = $(body).data("csrf-token"); $.ajaxPrefilter((options, originalOptions, jqXHR) => { if (options.type.toLowerCase() === "post") { // initialize `data` to empty string if it does not exist options.data = options.data || ""; // add leading ampersand if `data` is non-empty options.data += options.data ? "&" : ""; // add _token entry options.data += "csrf_token=" + encodeURIComponent(token); } }); }); $(() => { const body = $("body"); const language = $("html").data("select2-language"); bindTooltips($(body)); bootbox.setDefaults({ locale: $("html").data("select2-language") }); // toggle hamburger menu $("#menu-toggle").click((e) => { if ($(e.currentTarget).hasClass('is-open')) { $(".mainmenu").slideUp(); $(e.currentTarget).removeClass("is-open"); } else { $(".mainmenu").slideDown(); $(e.currentTarget).addClass("is-open"); } } ); bindAjaxLinks(body); // handle browser back events (Required for ajax loaded pages) $(window).bind('popstate', (event) => { const state = event.originalEvent.state; console.log('popstate', state); // if there is no state this history entry // was a full page reload if (!state) { ajaxLoadSpinner.show(); location.replace(document.location); return; } // if this page was loaded by ajax // use ajax again if (typeof state.ajaxUrl === 'string') { console.log('go back to', state.ajaxUrl); ajaxGoTo(state.ajaxUrl); return; } // If there is a state but no ajax URL // then this history entry was a full page reload // Then reload page ajaxLoadSpinner.show(); location.replace(window.location.href); }); // clear-cache shortcut icon $("#menu-clear-cache").click((event) => { event.preventDefault(); event.stopPropagation(); $("#menu-clear-cache").hide(); $("#menu-clear-cache-loading").show(); const url = $("#menu-clear-cache").data("url"); $.get(url, () => { $("#menu-clear-cache").show(); $("#menu-clear-cache-loading").hide(); }); }); // Add bootstrap css class to tablesorter $.extend($.fn.dataTableExt.oStdClasses, { sFilterInput: "form-control", sLengthSelect: "form-control" }); // copy text from input to clipboard on click $(".select-on-click").click((event) => { const target = event.target; copyTextToClipboard( target.value, () => vanillaToast.success(GlobalTranslation.CopiedToClipboardSuccess), () => { vanillaToast.error(GlobalTranslation.CopiedToClipboardFailed); target.select(); } ); }); // Disabled a link-buttons must not be clickable $("a").click((event) => { const target = $(event.currentTarget); if ((target.hasClass("disabled") || target.attr("disabled")) && target.attr("href").length > 1) { event.preventDefault(); } }); initDataTables(body); initPasswordSecurityCheck(body); // Links to upcoming features $(".coming-soon").click((event) => { event.preventDefault(); bootbox.alert("Coming Soon!"); }); // Showing a link in an alert box initRemoteAlerts(body); addCssClassToInputs($(body)); // override save shortcut to trigger submit button if ($("form button[type=submit], form input[type=submit]").length) { document.addEventListener( "keydown", (e) => { if ((window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) && e.keyCode === 83) { e.preventDefault(); $("form button[type=submit], form input[type=submit]") .last() .click(); } }, false); } $("input[type=checkbox] .select-all").change(selectAllChecked); $("input[type=checkbox]").change(checkboxChecked); // check "Select All" checkbox if all checkboxes of this group are checked $("input[type=checkbox]").each((index, target) => { const item = $(target).data("select-all-checkbox"); const group = $(target).data("checkbox-group"); if (item !== null && group !== null) { checkSelectAllIfAllChecked(item, group); } }); // scroll to the given anchor const params = new URLSearchParams(location.search); const jumpTo = params.get('jumpto'); if (jumpTo && jumpTo.length > 0) { const anchor = document.querySelector(`#${jumpTo}`); if (anchor) { zenscroll.to(anchor); } } initSelect2(body); initBootstrapToggle(body); $.datetimepicker.setLocale(language); $(".datepicker").datetimepicker({ format: "Y-m-d", timepicker: false }); $(".datetimepicker").prop("readonly", true); $(".datetimepicker").datetimepicker({ format: "Y-m-d H:i", timepicker: true, step: 30 }); // User has to confirm logout $("a.backend-menu-item-logout").click((event) => { event.preventDefault(); $(".mainmenu").hide(); const url = $(event.target).attr("href"); bootbox.confirm(`${MenuTranslation.Logout}?`, (result) => { if (result) { location.href = url; } }); }); // show a scroll-to-top arrow // if the scroll viewport isn't at top of the page $(window).scroll(() => { if ($(window).scrollTop() > 0) { $("#scroll-to-top").fadeIn(); } else { $("#scroll-to-top").fadeOut(); } }); // scroll to top arrow at bottom right $("#scroll-to-top").click((event) => { event.preventDefault(); event.stopPropagation(); zenscroll.toY(0); }); }); <|start_filename|>ulicms/tests/html/__snapshots__/MediaEmbedTest__testReplaceLinksWithDisableMediaEmbedTrue__1.html<|end_filename|> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body> <p>Foo Bar, Hello World, <a href="https://www.youtube.com/watch?v=yBJeeXmS7EA">Internet is for Cats</a>, Yes</p> <p><a href="https://www.youtube.com/watch?v=tI0TUJ-aV6c">https://www.youtube.com/watch?v=tI0TUJ-aV6c</a></p> <p><a href="https://dai.ly/x2bqyl6">https://dai.ly/x2bqyl6</a></p> <p><a href="https://www.twitch.tv/videos/293684811">https://www.twitch.tv/videos/293684811</a></p> </body></html> <|start_filename|>ulicms/admin/scripts/utils/fx.js<|end_filename|> // shakes a div (animation) // This is used when login fails const shake = (div) => { const interval = 100; const distance = 10; const times = 4; $(div).css('position', 'relative'); for (let iter = 0; iter < (times + 1); iter++) { $(div).animate({ left: ((iter % 2 === 0 ? distance : distance * -1)) }, interval); }// for $(div).animate({ left: 0 }, interval); }; // scrolls to an anchor with animation const scrollToAnchor = (aid) => { const aTag = $("a[name='" + aid + "']"); $('html,body').animate({ scrollTop: aTag.offset().top }, 'slow'); }; const setWaitCursor = () => { $('body').css('cursor', 'progress'); }; const setDefaultCursor = () => { $('body').css('cursor', 'auto'); }; const bindTooltips = (root) => { if (isTouchDevice()) { return; } $(root).find("*[title]").tooltip(); } <|start_filename|>doc/ulicms-2021.3-ankuendigung.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title> UliCMS 2021.3 auf dem neuesten Stand für das 3. Quartal von 2021 </title> <style type="text/css"> body { background-color: white; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI Emoji", "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; font-size: medium; color: rgb(50, 50, 50); margin: 0; padding: 20px; } li { margin-bottom: 20px; } </style> </head> <body> <h1> UliCMS 2021.3 auf dem neuesten Stand für das 3. Quartal von 2021 </h1> <h2>UI Verbesserungen</h2> <p> Die Benutzerschnittstelle des Kommentarsystems wurde überarbeitet. Es wurde eine Animation zum Hamburger Menu Icon im Backend hinzugefügt. </p> <h2>Pakete aktualisiert</h2> <p> Alle npm und composer Pakete wurden aktualisiert. CKEditor wurde auf Version 4.16.2 aktualisiert. </p> <h2>Fehlerkorrekturen</h2> <p> Es wurden zwei SQL-Fehler korrigiert, die auftreten, wenn in der Konfigurationsdatei $db_strict_mode = true ist. </p> </body> </html> <|start_filename|>ulicms/content/modules/core_package_manager/js/list.js<|end_filename|> /* global bootbox */ $(() => { bootbox.setDefaults({ 'locale': $("html").data("select2-language") }); $(document).ajaxSend(() => setWaitCursor()); $(document).ajaxComplete(() => setDefaultCursor()); // attach handler to form's submit event $('.uninstall-form').submit((event) => { event.preventDefault(); message = $(event.target).data("confirm-message"); bootbox.confirm(message, (result) => { if (result) { const form = $(event.target); // submit the form $(form).ajaxSubmit({ success: () => { // hide and remove the table row of the uninstalled // package $(form).closest("tr").fadeOut(400, () => $(form).closest("tr").remove() ); }, error: (xhr, status, error) => bootbox.alert(error) }); } }); }); $(".default-theme-icon").click((event) => { const target = $(event.currentTarget); const url = target.data("url"); $.ajax({ url: url, success: () => { $(".default-theme-icon").removeClass( "btn-success btn-danger" ); $(".default-theme-icon").each((index, element) => { const classes = $(element).data("theme") === target.data("theme") ? "btn-success" : "btn-danger"; $(element).addClass(classes); }); }, error: (xhr, status, error) => bootbox.alert(error) }); }); $(".default-mobile-theme-icon").click((event) => { const target = $(event.currentTarget); const url = target.data("url"); const isActive = target.hasClass("btn-success"); $.ajax({ url: url, success: () => { $(".default-mobile-theme-icon").removeClass( "btn-success btn-danger" ); $(".default-mobile-theme-icon").each((index, element) => { const classes = $(element).data("theme") === target.data("theme") && !isActive ? "btn-success" : "btn-danger"; $(element).addClass(classes); }); }, error: (xhr, status, error) => bootbox.alert(error) }); }); $('#truncate-installed-patches').submit((event) => { event.preventDefault(); message = $(event.target).data("confirm-message"); bootbox.confirm(message, (result) => { if (result) { const form = $(event.target); // submit the form $(form).ajaxSubmit({ success: (result) => $("#patch-list tbody tr").remove() , error: (xhr, status, error) => bootbox.alert(error) }); } }); }); $(".toggle-module-form").submit((event) => { event.preventDefault(); const form = $(event.target); // submit the form $(form).ajaxSubmit( { success: (result) => { // hide and remove the table row // of the // uninstalled // package const settingsButton = $( "[data-btn-for=" + result["name"] + "]").not( ".has-no-settings"); if (result["enabled"]) { $(form).find(".btn-enable").hide(); $(form).find(".btn-disable").show(); $(settingsButton).attr("disabled", null); $(settingsButton).removeClass("disabled"); } else { $(form).find(".btn-enable").show(); $(form).find(".btn-disable").hide(); $(settingsButton).attr("disabled", "disabled"); $(settingsButton).addClass("disabled"); } }, error: (xhr, status, error) => bootbox.alert(error) }); }); }); <|start_filename|>ulicms/content/modules/core_content/js/pages/init-ckeditor.js<|end_filename|> /* global CKEDITOR, PageTranslation */ const CKCHANGED = (event) => { formChanged = 1; if (event.data.$.keyCode === 17) { isCtrl = false; } }; $(() => { for (name in CKEDITOR.instances) { const id = CKEDITOR.instances[name].element.getId(); CKEDITOR.instances[name].destroy(); const editor = CKEDITOR.replace(id, { skin: $("body").data("ckeditor-skin") } ); editor.on("instanceReady", ({editor}) => { // update ckeditor height if the height // was saved in the local storage const ckeditorHeight = localStorage.getItem("ckeditorHeight"); if (ckeditorHeight) { editor.resize('100%', ckeditorHeight, true); } // save editor height on resize editor.on('resize', (event) => { localStorage.setItem( "ckeditorHeight", event.data.contentsHeight ); }); editor.document.on("keyup", CKCHANGED); editor.document.on("paste", CKCHANGED); editor.document.on('keydown', (event) => { if (event.data.$.keyCode === 17) isCtrl = true; if (event.data.$.keyCode === 83 && isCtrl === true) { //The preventDefault() call prevents the browser's //save popup to appear. //The try statement fixes a weird IE error. try { event.data.$.preventDefault(); } catch (err) { } $("form").last().find("button[type=submit]").click(); //Call to your save function return false; } }); }); } $('form').each(function (i, n) { $('input', n).change(() => { formChanged = 1; }); $('textarea', n).change(() => { formChanged = 1; }); $('select', n).change(() => { formChanged = 1; }); $(n).submit(() => { submitted = 1; }); }); $(window).on('beforeunload', () => { if (typeof formChanged !== "undefined" && formChanged === 1 && submitted === 0) { return PageTranslation.ConfirmExitWithoutSave; } return; } ); }); <|start_filename|>ulicms/content/modules/extend_upgrade_helper/metadata.json<|end_filename|> { "source": "extend", "version": "1.8", "embed": false, "custom_acl": [ "extend_upgrade_helper" ], "admin_permission": "extend_upgrade_helper", "controllers": { "ExtendUpgradeHelper": "controllers/ExtendUpgradeHelper" }, "objects": { "ExtendModule": "objects/ExtendModule" } } <|start_filename|>ulicms/content/modules/core_package_manager/js/available.js<|end_filename|> /* global bootbox, AvailablePackageTranslation */ $(() => { $("div#loadpkg").slideDown(); const container = $("div#pkglist"); $.get(container.data("url"), (result) => { $("div#loadpkg").slideUp(); $(container).html(result); $(container).slideDown(); initRemoteAlerts(container); initDataTables("#pkglist"); $(container).find(".btn-install").click((event) => { event.preventDefault(); const url = $(event.currentTarget).attr("href"); const name = $(event.currentTarget).data("name"); const message = AvailablePackageTranslation.AskForInstallPackage .replace ("%pkg%", name); bootbox.confirm(message, (confirmed) => { if (confirmed) { location.replace(url); } }); }); }); }); <|start_filename|>ulicms/admin/scripts/utils/dataTables.js<|end_filename|> const dataTableDrawCallback = (settings) => { // if the current page doesn't exists go to the last existing page const table = $(`#${settings.sInstance}`).DataTable(); const totalPageCount = table.page.info().pages; const currentPage = table.page() + 1; if (currentPage > totalPageCount) { table.page(totalPageCount); } $(`#${settings.sInstance}`).find("a.btn").click( (event) => { const target = $(event.currentTarget); if ((target.hasClass("disabled") || target.attr("disabled")) && target.attr("href").length > 1) { event.preventDefault(); event.stopPropagation(); return; } }); $(`#${settings.sInstance}`).find("a.show-children").click((event) => { event.preventDefault(); event.stopPropagation(); const id = $(event.target).data("id"); $("#filter_parent").val(id).trigger("change"); }); $(`#${settings.sInstance}`).find("a.delete-icon").click((event) => { event.preventDefault(); event.stopPropagation(); const target = $(event.currentTarget); const confirmMessage = target.data("confirm"); const url = target.data("url"); bootbox.confirm(confirmMessage, (result) => { if (result) { $.ajax({ url, method: 'POST', success: () => { const table = $(`#${settings.sInstance}`); const dataTable = table.DataTable(); const row = target.closest("tr"); $(row).fadeOut(400, () => { dataTable.row(row).remove().draw(false); }); } }); } }); } ); }; const prepareSearchData = (data) => { data.filters = buildFiltersObject(); console.log('search data', data); }; const buildFiltersObject = () => { const type = $("#filter_type").val(); const categoryId = $("#filter_category").val(); const parentId = $("#filter_parent").val(); const approved = $("#filter_approved").val(); const language = $("#filter_language").val(); const menu = $("#filter_menu").val(); const active = $("#filter_active").val(); return { type, category_id: categoryId, parent_id: parentId, approved: approved, language: language, menu: menu, active: active }; }; const initDataTables = (rootElement) => { // Sortable and searchable tables // Internet Exploder doesn't support URLSearchParams, // but which caveman are still using IE? // Fuck IE, Fuck Microsuck since Windows 8 const urlParams = new URLSearchParams(window.location.search); // get current action from url // this is used as identifier when saving and loading the state const action = urlParams.get('action'); $(rootElement).find(".tablesorter").each((index, element) => { const table = $(element); const url = table.data("url"); $(element).DataTable({ language: { url: $("body").data("datatables-translation") }, processing: !!url, serverSide: !!url, search: (event) => { $(event.target).DataTable().page(1); }, ajax: url ? { url, type: 'GET', data: prepareSearchData } : null, deferRender: true, stateSave: true, stateDuration: 0, stateSaveCallback: (settings, data) => { localStorage.setItem( "DataTables_" + action + "_" + settings.sInstance, JSON.stringify(data) ); }, stateLoadCallback: (settings) => JSON.parse( localStorage.getItem( "DataTables_" + action + "_" + settings.sInstance) ) , drawCallback: dataTableDrawCallback, columnDefs: [{targets: "no-sort", orderable: false}] }); }); }; <|start_filename|>ulicms/content/modules/core_media/metadata.json<|end_filename|> { "source": "core", "version": "2021.3", "embed": false, "custom_acl": [ "files", "videos", "videos_create", "videos_edit", "audio", "audio_create", "audio_edit" ], "actions": { "media": "templates/media.php", "images": "templates/filemanager.php", "files": "templates/filemanager.php", "flash": "templates/filemanager.php", "videos": "templates/videos/list.php", "add_video": "templates/videos/new.php", "edit_video": "templates/videos/edit.php", "audio": "templates/audio/list.php", "add_audio": "templates/audio/new.php", "edit_audio": "templates/audio/edit.php" }, "controllers": { "VideoController": "controllers/VideoController.php", "AudioController": "controllers/AudioController.php", "CoreMediaController": "controllers/CoreMediaController.php" }, "main_class": "CoreMediaController", "action_controllers": { "videos": "VideoController", "audio": "AudioController" }, "controller_function_permissions": { "VideoController::deletePost": "videos", "VideoController::updatePost": "videos_edit", "VideoController::createPost": "videos_create", "AudioController::deletePost": "audio", "AudioController::createPost": "audio_create", "AudioController::updatePost": "audio_edit" } } <|start_filename|>ulicms/content/modules/core_content/js/pages/form.js<|end_filename|> // Script for new page and edit page form window.slugChecking = false; $(() => { const url = $(".main-form") .first() .data("get-content-types-url"); $.ajax({ url, success: (response) => { AllTypes = response; showAndHideFieldsByTypeWithoutEffects(); $(".loadspinner").hide(); $(".pageform").show(); // Refresh CodeMirror refreshCodeMirrors(); $(".accordion-header").click(() => refreshCodeMirrors()); } }); bindEvents(); slugOrLanguageChanged(); filterParentPages(); $(".new-page-form #btn-submit").click((event) => { const form = $(event.target).closest("form"); event.preventDefault(); event.stopPropagation(); if (!form.hasClass("edit-page-form") && form.get(0).reportValidity()) { $(window).off("beforeunload"); $(form).off("submit"); form.submit(); } else { const hiddenInvalidElements = form.find( "input, select, checkbox, textarea, radio" ).filter(':hidden').toArray(). filter((x) => !x.checkValidity()); if (hiddenInvalidElements.length) { bootbox.alert(PageTranslation.FillAllRequiredFields); } } }); // AJAX submit page edit form $(".edit-page-form").ajaxForm({ beforeSubmit: () => { $("#message-page-edit").html(""); $("#message-page-edit").hide(); $(".loading").show(); }, beforeSerialize: () => { updateCKEditors(); return true; }, success: () => { $(".loading").hide(); $("#message-page-edit").html( `<span style="color:green;"> ${Translation.PageSaved} </span>` ); $("#message-page-edit").show(); } }); // check if a slug is free on changing system title or menu $("input[name='slug']").blur(() => slugOrLanguageChanged()); $("input[name='title']").blur(() => slugOrLanguageChanged()); $("select[name='menu']").change(() => filterParentPages()); // check if slug is free and update parent page options $("select[name='language']").change(() => { slugOrLanguageChanged(); filterParentPages(); }); // bind event to "View" button at the bottom of page edit form $("#btn-view-page").click(() => { const url = "../?goid=" + $("#page_id").val(); // if page has unsaved changes open it in new window/tab // else open it in the same window/tab if (formChanged && !submitted) { window.open(url); } else { location.href = url; } }); }); showAndHideFieldsByTypeWithoutEffects = () => { const type = $("input[name=type]:checked").val(); $(".typedep").hide(); if (typeof AllTypes[type] === 'undefined') { return; } const typeData = AllTypes[type]; const show = typeData["show"]; show.forEach((element) => $(element).show()); if ($("#type_snippet").is(":checked")) { unbindEvents(); $("select[name='hidden']") .val("1") .trigger("change"); $("select[name='menu']") .val("not_in_menu") .trigger("change"); bindEvents(); } $(".custom-field-tab").each((index, el) => { if ($(el).data("type") === $("input[name='type']:checked").val()) { $(el).find("input, select, checkbox, radio, button, submit").prop("disabled", false); $(el).show(); } else { $(el).hide(); $(el).find("input, select, checkbox, radio, button, submit").prop("disabled", true); } }); if ($("#type_node").is(":checked") || $("#type_snippet").is(":checked")) { $("#btn-view-page").hide(); } else { $("#btn-view-page").show(); } if ($("select[name='menu']").val() === "not_in_menu") { $("#parent-div").hide(); $("#menu_image_div").hide(); } else { $("#parent-div").show(); $("#menu_image_div").show(); } }; // this function shows and hides areas for the selected content type showAndHideFieldsByType = () => { const type = $("input[name=type]:checked").val(); const showSelector = AllTypes[type]["show"].join(","); $(".typedep") .not(showSelector) .slideUp(); const typeData = AllTypes[type]; const show = typeData["show"]; show.forEach((element) => $(element).slideDown()); if ($("#type_snippet").is(":checked")) { unbindEvents(); $("select[name='hidden']") .val("1") .trigger("change"); $("select[name='menu']") .val("not_in_menu") .trigger("change"); bindEvents(); } $(".custom-field-tab").each((index, el) => { if ($(el).data("type") === $("input[name='type']:checked").val()) { $(el).slideDown(); $(el).find("input, select, button, submit").prop("disabled", false); } else { $(el).slideUp(); $(el).find("input, select, button, submit").prop("disabled", true); } }); if ($("#type_node").is(":checked") || $("#type_snippet").is(":checked")) { $("#btn-view-page").slideUp(); } else { $("#btn-view-page").slideDown(); } if ($("select[name='menu']").val() === "not_in_menu") { $("#parent-div").slideUp(); $("#menu_image_div").slideUp(); } else { $("#parent-div").slideDown(); $("#menu_image_div").slideDown(); } }; /* global Translation, formChanged, submitted, bootbox, instance, CKEDITOR, PageTranslation */ let AllTypes = {}; // this shows a thumbnail of the selected file on text inputs with // fm image uploader attached refreshFieldThumbnails = () => { $("input.fm[data-fm-type=images]").each((index, element) => { const id = $(element).attr("name"); if ($(element).val().length > 0) { $("img#thumbnail-" + id).attr("src", $(element).val()); $("img#thumbnail-" + id).show(); } else { $("img#thumbnail-" + id).hide(); } }); }; // Bind events for dependend fields, clear-buttons, and file inputs bindEvents = () => { $('input[name="type"]').change(showAndHideFieldsByType); $("select[name='menu']").change(showAndHideFieldsByType); $("select[name='menu']") .select2("destroy") .select2({ width: "100%" }); $(".clear-field").on("click", (event) => { event.preventDefault(); event.stopPropagation(); const element = $(event.target); const linkFor = $(element).data("for"); $(linkFor).val(""); refreshFieldThumbnails(); }); refreshFieldThumbnails(); $("input.fm").on("click", (event) => { const field = $(event.target); const name = $(field).attr("id") ? $(field).attr("id") : $(field).attr("name"); const type = $(field).data("fm-type") ? $(field).data("fm-type") : "images"; window.open( "fm/dialog.php?fldr=" + type + "&editor=ckeditor&type=2&langCode=" + $("html").data("select2-language") + "&popup=1&field_id=" + field.attr("id"), name, "status=0, toolbar=0, location=0, menubar=0, directories=0, " + "resizable=1, scrollbars=0, width=850, height=600" ); }); }; // undbindEvents to prevent endless loop when selecting specific content types unbindEvents = () => { $('input[name="type"]').off("change"); $("select[name='menu']").off("change"); $("input.fm").off("click"); $(".clear-field").off("click"); }; // this suggest a slug which may be used as the url for a page suggestSlug = (text) => { const pageSlug = slug(text, {lower: true}); $("#slug").val(pageSlug); }; // this checks if a slug is free within the selected language // the combination of slug + language must be unique slugOrLanguageChanged = () => { if (window.slugChecking) { return; } window.slugChecking = true; const id_field = $("input[name='page_id']"); let myid = 0; if (id_field) { myid = $(id_field).val(); } const data = { csrf_token: $("input[name=csrf_token]") .first() .val(), slug: $("input[name='slug']").val(), language: $("select[name='language']").val(), id: myid }; const url = $(".main-form") .first() .data("slug-free-url"); $.get(url, data, function (text) { if (text.length > $("input[name='slug']").val().length) { $("input[name='slug']").val(text); } window.slugChecking = false; }); }; // filter parent pages by selected language and menu filterParentPages = () => { const data = { csrf_token: $("input[name=csrf_token]") .first() .val(), mlang: $("select[name='language']").val(), mmenu: $("select[name='menu']").val(), mparent: $("select[name='parent_id']").val() }; const url = $(".main-form") .first() .data("parent-pages-url"); $.get(url, data, function (text, status) { $("select[name='parent_id']").html(text); }); }; <|start_filename|>ulicms/composer.json<|end_filename|> { "license": "BSD", "authors": [ { "name": "<NAME>", "email": "<EMAIL>", "homepage": "http://www.ulicms.de", "role": "Lead Developer" } ], "support": { "email": "<EMAIL>", "issues": "https://github.com/derUli/ulicms/issues", "source": "https://github.com/derUli/ulicms", "docs": "https://www.ulicms.de/handbuecher.html", "rss": "https://en.ulicms.de/blog_rss.php?s=aktuelles&lang=en" }, "repositories": [ { "url": "https://github.com/derUli/html-minifier", "type": "git" } ], "require": { "php": ">=7.3", "ext-mysqli": "*", "ext-gd": "*", "ext-json": "*", "ext-mbstring": "*", "ext-openssl": "*", "ext-dom": "*", "ext-libxml": "*", "phpfastcache/phpfastcache": "*", "phpgangsta/googleauthenticator": "dev-master", "katzgrau/klogger": "dev-master", "phpmailer/phpmailer": "*", "deruli/html-minifier": "master-dev", "scssphp/scssphp": "*", "chrisjean/php-ico": "*", "willdurand/negotiation": "*", "cocur/slugify": "*", "matthiasmullie/minify": "*", "rakit/validation": "*", "nesbot/carbon": "*", "symfony/polyfill-mbstring": "*", "dereuromark/media-embed": "*", "jimmiw/php-time-ago": "*", "consolidation/robo": "*", "lasserafn/php-initial-avatar-generator": "*", "imagine/imagine": "*", "michelf/php-markdown": "*" }, "require-dev": { "spatie/phpunit-snapshot-assertions": "*", "phpunit/phpunit": "*", "mpdf/mpdf": "*", "friendsofphp/php-cs-fixer": "*", "overtrue/phplint": "*" } } <|start_filename|>ulicms/content/modules/core_settings/js/spam_filter.js<|end_filename|> /* global SettingsTranslation */ $(() => { $("#spamfilter_settings").ajaxForm({beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, success: () => { $("#loading").hide(); $("#message").html("<span style=\"color:green;\">" + SettingsTranslation.ChangesWasSaved + "</span>"); } }); $("#spamfilter_enabled").change((event) => { if (event.target.checked) { $('#country_filter_settings').slideDown(); } else { $('#country_filter_settings').slideUp(); } }); }); <|start_filename|>ulicms/content/modules/oneclick_upgrade/metadata.json<|end_filename|> { "source": "extend", "version": "2.8", "embed": false, "controllers": { "CoreUpgradeController": "controllers/CoreUpgradeController" }, "actions": { "UpgradeCheck": "templates/UpgradeCheck.php", "CorruptedDownloadError": "templates/errors/CorruptedDownloadError.php" }, "action_controllers": { "UpgradeCheck": "CoreUpgradeController" }, "custom_acl": ["oneclick_upgrade_settings"], "admin_permission": "oneclick_upgrade_settings", "settings": { "oneclick_upgrade_channel": "slow" } } <|start_filename|>ulicms/content/modules/core_settings/js/footer_text.js<|end_filename|> /* global Translation */ // scripts for meta description settings page $(() => { $("#footer_text_form").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, beforeSerialize: () => { /* Before serialize */ updateCKEditors(); return true; }, success: () => { $("#loading").hide(); $("#message") .html(`<span style="color:green;">${Translation.ChangesWasSaved}</span>`); } }); }); <|start_filename|>ulicms/content/templates/2020/js/main.js<|end_filename|> // scroll to the given anchor const params = new URLSearchParams(location.search); const dir = location.href.substring(0, location.href.lastIndexOf('/')); // redirect direct page urls to anchors const jumpTo = params.get('jumpto'); if (jumpTo && jumpTo.length > 0) { $("body").css("opacity", "0"); location.replace(`${dir}/#${jumpTo}`); } $(() => { $("footer").last().fadeIn(); new fullpage('#fullpage', { afterLoad: (origin, destination) => { $(destination.item).find(".sliding").addClass("slide-in"); $(destination.item).find(".text-content").addClass("move-up"); }, anchors: $("#fullpage").data("slugs").split("||"), navigationTooltips: $("#fullpage").data("titles").split("||"), navigation: true, navigationPosition: 'right', verticalCentered: false }); }); <|start_filename|>ulicms/content/modules/update_manager_dashboard/scripts/update_manager_dashboard.js<|end_filename|> $(() => { $.post("index.php", { ajax_cmd: "anyUpdateAvailable" }, (data) => { if (data === "yes") { $("#update-manager-dashboard-container").slideDown(); } }); }); <|start_filename|>doc-src/portable/info-text-english.html<|end_filename|> <!DOCTYPE html> <html lang="de"> <head> <meta charset="utf-8"> <title>Introducing UliCMS Portable?</title> </head> <body> <h1>Introducing UliCMS Portable</h1> <p> <strong>UliCMS 8.0.1 Portable for Windows</strong> is an instance of <a href="https://www.apachefriends.org"><strong>XAMPP</strong></a> that comes preinstalled with UliCMS 8.0.1. </p> <p>It makes it very easy, to try out UliCMS without the need to setup a webserver.</p> <p>Other versions of UliCMS and versions for other operating systems will follow.</p> <p> <strong>Please note:</strong> <p>Don't use this software for hosting public websites, since it has an unsecure configuration by default.</p> <p>It's only a test and development environment.</p> <h2>How to install</h2> <p>Simple extract the "xampp" folder from zip file and copy it into the root directory of a drive (e.g drive C:\). <h2>How to run</h2> <ol> <li>Open x:\xampp and run "xampp-control" application (use the drive letter instead of x).</li> <li>Select your language</li> <li>Click on "Start" next to "Apache". You maybe have to confirm warnings of your computer firewall.</li> <li>Click on "Start" next to "MySQL". You maybe have to confirm warnings of your computer firewall. <li>Open your browser and enter "http://localhost/admin" into the address bar of your web browser.</li> <li>Login.<br /> Default login is:<br /> <strong>User:</strong> admin<br /> <strong>Password:</strong> password<br /> it's recommend to change this immediately. </li> <li>When you finished using UliCMS then stop the "Apache" and "MySQL" modules using "XAMPP Control Panel" and quit the application.</li> </ol> </body> </html> <|start_filename|>ulicms/content/modules/core_home/js/dashboard.js<|end_filename|> $(() => { $(".has-ajax-content").click((event) => { if ($(event.currentTarget).hasClass("loaded")) { return; } const url = $(event.currentTarget).data("url"); $(event.currentTarget).find(".accordion-content").load(url); if (!$(event.currentTarget).hasClass("always-update")) { $($(event.currentTarget)).addClass("loaded"); } }); if ($("#patch-notification").length) { const url = $("#patch-notification").data("url"); $.get(url, (data) => { if (data.length > 0) { $("#patch-notification #patch-message").html(data); $("#patch-notification").slideDown(); } }); } $("#show_positions").change((event) => { const url = $(event.currentTarget).data("url"); $.ajax({ method: "get", url: url, error: (xhr) => alert(xhr.responseText) }); }); }); <|start_filename|>ulicms/content/modules/core_comments/metadata.json<|end_filename|> { "version": "2021.3", "source": "core", "embed": false, "controllers": { "CommentsController": "controllers/CommentsController.php" }, "main_class": "CommentsController", "custom_acl": [ "comments_manage" ], "actions": { "comments_manage": "templates/admin.php" }, "action_permissions": { "comments_manage": "comments_manage" }, "controller_function_permissions": { "CommentsController::getCommentText": "comments_manage", "CommentsController::filterComments": "comments_manage", "CommentsController::doAction": "comments_manage" }, "dependencies": [ "core_content" ] } <|start_filename|>ulicms/admin/scripts/login.js<|end_filename|> // Shake animation on failed login $(() => { bindTogglePassword("#password", <PASSWORD>"); if ($("form#login-form").data("has-error")) { shake("form#login-form"); } }); <|start_filename|>ulicms/content/modules/core_users/metadata.json<|end_filename|> { "source": "core", "version": "2021.3", "embed": false, "custom_acl": [ "users", "users_create", "users_edit", "groups", "groups_create", "groups_edit" ], "actions": { "admins": "templates/users/list.php", "admin_new": "templates/users/new.php", "admin_edit": "templates/users/edit.php" }, "controllers": { "UserController": "controllers/UserController.php", "SessionManager": "controllers/SessionManager.php", "RegistrationController": "controllers/RegistrationController.php" }, "controllers_function_permissions": { "UserController::deletePost": "users", "UserController::createPost": "users_create", "UserController::updatePost": "users_edit" } } <|start_filename|>ulicms/content/modules/core_settings/js/logo.js<|end_filename|> /* global Translation */ /* global bootbox */ $(() => { // Enable submit button after file was selected $(".btn-primary").prop('disabled', true) $("input[name=logo_upload_file]").change( () => $(".btn-primary").prop('disabled', false) ); // Delete Logo // show load spinner // then empty the table column $("#delete-logo").click((event) => { const target = $(event.target); const url = target.data("url"); bootbox.confirm( `${Translation.DeleteLogo}?`, (result) => { if (result) { $("#logo-wrapper").hide(); $("#delete-logo-loading").show(); $.post(url) .done((text, status) => { target.closest('tr').remove(); vanillaToast.success(Translation.LogoDeleted); }) .fail(() => { $("#delete-logo-loading").hide(); $("#logo-wrapper").show(); }); } }); }); }); <|start_filename|>ulicms/content/modules/core_content/js/categories.js<|end_filename|> // This the script for the categories list page $(() => { $("form.delete-form").ajaxForm({ success: (responseText, statusText, xhr, $form) => { const action = $($form).attr("action"); const params = new URLSearchParams(action); const id = params.get("del"); const list_item_id = `dataset-${id}`; const tr = $(`tr#${list_item_id}`); $(tr).fadeOut(); } }); }); <|start_filename|>ulicms/content/modules/core_security/metadata.json<|end_filename|> { "source": "core", "version": "2021.3", "embed": false, "controllers": { "CoreSecurityController": "controllers/CoreSecurityController.php" }, "main_class": "CoreSecurityController" } <|start_filename|>ulicms/content/modules/core_comments/js/admin.js<|end_filename|> /* global bootbox */ $(() => { // Show full text in an alert modal when // the user clicks on the shortened text $(".ajax-alert").click((event) => { event.preventDefault(); const url = $(event.target).data("url"); // do an ajax call $.ajax({ url: url, success: (result) => { const unread = $(event.target).closest(".unread"); if (unread.length) { unread.removeClass("unread"); const commentCounter = $(".comment-counter .count"); const newCount = commentCounter.data("count") - 1; commentCounter.data("count", newCount); commentCounter.text(newCount); if (newCount <= 0) { commentCounter.hide(); } } // show the response to the user in an bootbox alert bootbox.alert({ message: result, size: "large" }); } }); }); }); <|start_filename|>ulicms/content/modules/core_settings/js/open_graph.js<|end_filename|> /* global Translation */ const openMenuImageSelectWindow = (target) => { window.open( "fm/dialog.php?fldr=images&editor=ckeditor&type=1&langCode=" + $("html").data("select2-language") + "&popup=1&field_id=og_image", "og_image", "status=0, toolbar=0, location=0, menubar=0, directories=0, " + "resizable=1, scrollbars=0, width=850, height=600" ); } $(() => { $("#og_image").click((event) => openMenuImageSelectWindow(event.target)) $("#open_graph").ajaxForm( { beforeSubmit: () => { $("#message").html(""); $("#loading").show(); }, success: () => { $("#loading").hide(); // FIXME: localize this string $("#message") .html(`<span style="color:green;">${Translation.ChangesWasSaved}</span>`); } }); }); <|start_filename|>ulicms/content/modules/update_manager/metadata.json<|end_filename|> { "version": "1.1.1", "admin_permission": "install_packages", "custom_acl": ["install_packages"], "embed": false, "objects": { "getAllUpdateablePackages": "objects/update_manager.php" } } <|start_filename|>ulicms/admin/scripts/group.js<|end_filename|> $(() => { $('.checkall').on('click', (event) => { $(event.target).closest('fieldset') .find('input[type=checkbox]') .prop('checked', $(event.target).prop('checked')); }); }); <|start_filename|>ulicms/admin/scripts/utils/inputs.js<|end_filename|> // this bind an event to a checkbox to toggle a password field between clear // text and stars const bindTogglePassword = (inputField, checkboxField) => { const input = $(inputField); const checkbox = $(checkboxField); $(checkbox).click(() => { if ($(checkbox).is(':checked')) { $(input).attr('type', 'text'); } else { $(input).attr('type', 'password'); } }); }; const checkboxChecked = (event) => { const item = $(event.currentTarget).data("select-all-checkbox"); const group = $(event.currentTarget).data("checkbox-group"); checkSelectAllIfAllChecked(item, group); }; const checkSelectAllIfAllChecked = (item, group) => { if (!item) { return; } // if the count of the checked checkboxes in the group is equal to the count // of all checkboxes in this group const allSelected = $("input[type=checkbox][data-checkbox-group='" + group + "']:checked").length === $("input[type=checkbox][data-checkbox-group='" + group + "']").length; // check the "Select All" Checkbox, else uncheck it $(item).prop("checked", allSelected); }; const selectAllChecked = (event) => { const selectAllCheckbox = $(event.target); const target = $(selectAllCheckbox).data("target"); $(target).prop("checked", $(selectAllCheckbox). is(":checked")).change(); }; // dynamically add class form-control to all form elements to // make inputs prettier const addCssClassToInputs = (container) => { // dynamically add class form-control to all form elements to // make inputs prettier $(container).find("input, select, textarea") .not("input[type=checkbox]") .not("input[type=radio]") .not("input[type=button]") .not("input[type=submit]") .not("input[type=reset]") .not("input[type=image]") .addClass("form-control"); }; const getSelect2Language = () => { return $("html").data("select2-language"); }; const initSelect2 = (container) => { // prettier select-boxes $(container).find("select").select2({ width: "100%", language: getSelect2Language() }); }; const initBootstrapToggle = (container) => { // Toggle switches for some checkboxes $(container).find(".js-switch").bootstrapToggle({ on: MenuTranslation.On, off: MenuTranslation.Off }); // bootstrap-toggle doesn't react to click on the label of a toggle switch // This is a long standing issue that is still not fixed. // https://github.com/minhur/bootstrap-toggle/issues/23 // just wrap the clickable text in an element with this css class // to make it clickable $(container).find(".js-switch-label").click((event) => { const target = $(event.target); const theSwitch = target.closest('.checkbox').find(".js-switch"); if (theSwitch && theSwitch.length) { theSwitch.bootstrapToggle('toggle'); } });}; const initPasswordSecurityCheck = (container) => { // password security check if (typeof $(".password-security-check").password !== "<PASSWORD>") { $(".password-security-check").password({ shortPass: PasswordSecurityTranslation.ShortPass, badPass: PasswordSecurityTranslation.BadPass, goodPass: PasswordSecurityTranslation.GoodPass, strongPass: PasswordSecurityTranslation.StrongPass, containsUsername: PasswordSecurityTranslation.ContainsUsername, enterPass: PasswordSecurityTranslation.EnterPass, showPercent: false, showText: true, animate: true, animateSpeed: "fast", username: $("[name=username]").length ? $("[name=username]") : false, usernamePartialMatch: true, minimumLength: 4 }); } }
derUli/ulicms
<|start_filename|>Sources/LYTabView/LYTabView.h<|end_filename|> // // LYTabBarView.h // LYTabBarView // // Created by <NAME> on 16/3/29. // Copyright © 2016年 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for LYTabBarView. FOUNDATION_EXPORT double LYTabBarViewVersionNumber; //! Project version string for LYTabBarView. FOUNDATION_EXPORT const unsigned char LYTabBarViewVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <LYTabBarView/PublicHeader.h>
hk05/LYTabView
<|start_filename|>src/app/add-device/keyserver-hint/keyserver-hint.component.html<|end_filename|> <p>Please make sure &quot;Key Server&quot; in Developer Mode App is turned on during device setup.</p> <img src="/assets/images/hint-key-server.png"> <a href="https://webostv.developer.lge.com/develop/app-test/using-devmode-app/">See: Using Developer Mode App</a> <|start_filename|>src/assets/i18n/en.json<|end_filename|> { "MESSAGES": { "TITLE_REMOVE_DEVICE": "Remove Device", "CONFIRM_REMOVE_DEVICE": "Remove device \"{{name}}\"?", "TITLE_OVERWRITE_PRIVKEY": "Overwrite Private Key", "CONFIRM_OVERWRITE_PRIVKEY": "Private key with same name already exists. Do you want to overwrite it?", "TITLE_VERIFICATION_FAILED": "Verification Failed", "CONFIRM_VERIFICATION_FAILED": "Add this device anyway?", "TITLE_ADD_DEVICE_FAILED": "Failed to Add Device", "ERROR_ADD_DEVICE_FAILED": "{{error}}", "TITLE_CONNECTION_ERROR": "Connection Error", "ERROR_CONNECTION_ERROR": "Failed to connect to {{name}}.", "TITLE_REMOVE_APP": "Remove App", "CONFIRM_REMOVE_APP": "Remove app \"{{name}}\"?", "TITLE_KEYSERV_FETCH_RETRY": "Failed to fetch private key", "TITLE_DEVICE_CONN_FAILED": "Unable to connect to device" }, "ACTIONS": { "OK": "OK", "RETRY": "Retry", "CANCEL": "Cancel", "REMOVE": "Remove" }, "PAGES": { "HOME": { "TITLE": "App works !", "GO_TO_DETAIL": "Go to Detail" }, "DETAIL": { "TITLE": "Detail page !", "BACK_TO_HOME": "Back to Home" } } } <|start_filename|>src/app/add-device/conn-hint/conn-hint.component.html<|end_filename|> <p> Please check the address and port you have entered, make sure &quot;Developer Mode&quot; is installed and turned on. And you have good network connection between your computer and your TV.<br> Check out <a href="https://webostv.developer.lge.com/develop/app-test/using-devmode-app/">Installing Developer Mode App</a> for more info. </p>
Informatic/dev-manager-desktop
<|start_filename|>ws2811/ws2811_8.h<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /** * Library for bit-banging data to WS2811 led controllers. * This file contains a definition of the send() function for 8 Mhz controllers. */ #ifndef WS2811_8_H_ #define WS2811_8_H_ #include <avr/io.h> #include <util/delay_basic.h> #include "rgb.h" namespace ws2811 { /** * This function sends the RGB-data in an array of rgb structs through * the given io-pin. * The port is determined by the macro WS2811_PORT, but the actual pin to * be used is an argument to this function. This allows a single instance of this function * to control up to 8 separate channels. */ void send( const void *values, uint16_t array_size, uint8_t bit) { const uint8_t mask =_BV(bit); uint8_t low_val = WS2811_PORT & (~mask); uint8_t high_val = WS2811_PORT | mask; uint16_t size = array_size * sizeof( rgb); // size in bytes // reset the controllers by pulling the data line low uint8_t bitcount = 7; WS2811_PORT = low_val; _delay_loop_1(107); // at 3 clocks per iteration, this is 320 ticks or 40us at 8Mhz // The labels in this piece of assembly code aren't very explanatory. The real documentation // of this code can be found in the spreadsheet ws2811@8Mhz.ods // A hint if you still want to follow the code below: // The code will send bits from most significant to least significant (bits 7 to 0) and consists // of two variants of the main loop: // 1) The code for a regular bit (i.e. bits 7-1) starts at label s00 with the current bit value // already in the carry flag and it jumps halfway back to label cont06. // 2) For a part of bit 1 and all of bit 0, the code falls through (after the skip03 label) // where the code needs to fork in a "transmit 0" and "transmit 1" branch. This is because // there's extra work to be done (loading the next byte), which needs to be carefully placed // in the time between toggling the output pins. // // The two-digit suffix of labels shows the "phase" of the signal at the time // of the execution, 00 being the first clock tick of the bit and 09 being the last. asm volatile( "start: LDI %[bits], 7 \n" // start code, load bit count " LD __tmp_reg__, %a[dataptr]+ \n" // fetch first byte "cont06: NOP \n" "cont07: NOP \n" " OUT %[portout], %[downreg] \n" // Force line down, even if it already was down "cont09: LSL __tmp_reg__ \n" // Load next bit into carry flag. "s00: OUT %[portout], %[upreg] \n" // Start of bit, bit value is in carry flag " BRCS skip03 \n" // only lower the line if the bit... " OUT %[portout], %[downreg] \n" // ...in the carry flag was zero. "skip03: SUBI %[bits], 1 \n" // Decrease bit count... " BRNE cont06 \n" // ...and loop if not zero " LSL __tmp_reg__ \n" // Load the last bit into the carry flag " BRCC Lx008 \n" // Jump if last bit is zero " LDI %[bits], 7 \n" // Reset bit counter to 7 " OUT %[portout], %[downreg] \n" // Force line down, even if it already was down " NOP \n" " OUT %[portout], %[upreg] \n" // Start of last bit of byte, which is 1 " SBIW %[bytes], 1 \n" // Decrease byte count " LD __tmp_reg__, %a[dataptr]+ \n" // Load next byte " BRNE cont07 \n" // Loop if byte count is not zero " RJMP brk18 \n" // Byte count is zero, jump to the end "Lx008: OUT %[portout], %[downreg] \n" // Last bit is zero " LDI %[bits], 7 \n" // Reset bit counter to 7 " OUT %[portout], %[upreg] \n" // Start of last bit of byte, which is 0 " NOP \n" " OUT %[portout], %[downreg] \n" // We know we're transmitting a 0 " SBIW %[bytes], 1 \n" // Decrease byte count " LD __tmp_reg__, %a[dataptr]+ \n" " BRNE cont09 \n" // Loop if byte count is not zero "brk18: OUT %[portout], %[downreg] \n" " \n" // used to be a NOP here, but returning from the function takes long enough " \n" // We're done. : /* no output */ : /* inputs */ [dataptr] "e" (values), // pointer to grb values [upreg] "r" (high_val), // register that contains the "up" value for the output port (constant) [downreg] "r" (low_val), // register that contains the "down" value for the output port (constant) [bytes] "w" (size), // number of bytes to send [bits] "d" (bitcount), // number of bits/2 [portout] "I" (_SFR_IO_ADDR(WS2811_PORT)) // The port to use ); } } #endif /* WS2811_8_H_ */ <|start_filename|>ws2811/rgb.h<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef RGB_H_ #define RGB_H_ namespace ws2811 { #ifdef STRAIGHT_RGB /** * Type that holds RGB values. * This version lays out the RGB values in R,G,B order in memory which is not * the original ws2811 order. Some led chains seem to rewire the channels in this order. */ struct rgb { rgb(uint8_t red, uint8_t green, uint8_t blue) :red(red),green(green),blue(blue) {} rgb() :red(0),green(0),blue(0) {} uint8_t red; uint8_t green; uint8_t blue; }; #else /** * Type that holds RGB values. * The in-memory order of this type is actually GRB, but the constructor takes * its values in RGB order. */ struct rgb { rgb(uint8_t red, uint8_t green, uint8_t blue) :green(green),red(red),blue(blue) {} rgb() :green(0),red(0),blue(0) {} uint8_t green; uint8_t red; uint8_t blue; }; #endif bool operator==( const rgb &lhs, const rgb &rhs) { return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue; } bool operator!=( const rgb &lhs, const rgb &rhs) { return not (lhs == rhs); } } #endif /* RGB_H_ */ <|start_filename|>effects/flares.hpp<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef FLARES_HPP_ #define FLARES_HPP_ //#include <stdlib.h> #include <util/delay.h> #include "ws2811/ws2811.h" namespace flares { using ws2811::rgb; /// very crude pseudo random generator uint16_t my_rand() { static uint16_t state; return state += 13331; // adding a prime number } const rgb base_color( 3, 2, 0); template <typename T> T max( T lhs, T rhs) { return (lhs > rhs) ? lhs : rhs; } template<typename buffer_type, typename pos_type = uint16_t> class flare { public: /** * If directionFilter is negative, then flares will only be written to the LED string * when dimming, if directionFilter is positive then only growing flares will be written. * If directionFilter is zero, the lights will be written both when growing and when * dimming. */ void step(buffer_type &leds, const ws2811::rgb &base_color, int8_t directionFilter = 0) { if (speed != 0) { step(); set(leds, base_color, directionFilter); } } void deactivate() { speed = 0; amplitude = 0; } rgb color; pos_type position; pos_type amplitude; int8_t speed; private: /// multiply an 8-bit value with an 8.8 bit fixed point number. /// multiplier should not be higher than 1.00 (or 256). static uint8_t mult(uint8_t value, uint16_t multiplier) { return (static_cast<uint16_t>(value) * multiplier) >> 8; } rgb calculate(const ws2811::rgb &base_color) const { return rgb( base_color.red + mult(color.red, amplitude), base_color.green + mult(color.green, amplitude), base_color.blue + mult(color.blue, amplitude)); } void set(buffer_type &leds, const ws2811::rgb &base_color, int8_t directionFilter) const { if (speed * directionFilter >= 0) { rgb &myled = get(leds, position); myled = calculate( base_color); } } void step() { if (speed < 0 && static_cast<uint16_t>(-speed) > amplitude) { amplitude = 0; } else { if (255 - amplitude < speed) { amplitude = 255; speed = -(speed); } else { amplitude += speed; } } } }; uint8_t random_brightness() { return 170 - (my_rand() % 96); } rgb random_color() { return rgb( random_brightness() / 2, random_brightness() / 2 - 10, random_brightness() ); } template<typename flare_type> void create_random_flare(flare_type &f, int16_t position, const rgb &color) { f.amplitude = 0; f.speed = 0; if (position < 0) return; f.color = color; f.speed = ( (my_rand() & 0x07)) + 1; f.position = position; } uint16_t find_random_led( uint16_t count) { return (my_rand() ^ (my_rand()>>1)) % count; } template< typename buffer_type> int16_t find_free_led( buffer_type &leds) { static const uint16_t count = ws2811::led_buffer_traits< buffer_type>::count; uint8_t tryLeds = 100; while (tryLeds--) { uint16_t position = find_random_led( count); if (get(leds, position) == base_color) { return position; } } return -1; } template<typename buffer_type, uint8_t flare_count> void flares_step( buffer_type &leds, flares::flare< buffer_type, uint8_t> (&flares)[flare_count], uint8_t &current_flare, uint8_t &flare_pause) { if (flare_pause) { --flare_pause; } else { if (!flares[current_flare].amplitude) { create_random_flare( flares[current_flare], find_free_led(leds), random_color()); flare_pause = my_rand() % 11; } ++current_flare; } if (current_flare >= flare_count) current_flare = 0; for (uint8_t idx = 0; idx < flare_count; ++idx) { flares[idx].step(leds, base_color, 0); } } template<uint8_t flare_count, typename buffer_type> void flares(buffer_type &leds, uint8_t channel) { flares::flare<buffer_type, uint8_t> flares[flare_count]; fill( leds, base_color); uint8_t current_flare = 0; uint8_t flare_pause = 1; while (true) { flares_step( leds, flares, current_flare, flare_pause); send( leds, channel); _delay_ms( 30); } } } // end namespace flares #endif /* FLARES_HPP_ */ <|start_filename|>effects/color_cycle.hpp<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef COLOR_CYCLE_HPP_ #define COLOR_CYCLE_HPP_ #include <util/delay.h> #include "ws2811/ws2811.h" namespace color_cycle { template< uint16_t size> void scroll( ws2811::rgb new_value, ws2811::rgb (&range)[size]) { for (uint8_t idx = size-1; idx != 0 ; --idx) { range[idx] = range[idx -1]; } range[0] = new_value; } template< uint16_t led_count> void animate( const ws2811::rgb &new_value, ws2811::rgb (&leds)[led_count], uint8_t channel) { scroll( new_value, leds); send( leds, channel); _delay_ms( 40); } template<uint8_t count, uint16_t led_count> void color_cycle( const ws2811::rgb (&sequence)[count], ws2811::rgb (&leds)[led_count], uint8_t channel) { for (;;) { for (uint8_t idx = 0; idx != count; ++idx) { animate( sequence[idx], leds, channel); } for (uint8_t idx = count; idx != 0; --idx) { animate( sequence[idx-1], leds, channel); } } } } #endif /* COLOR_CYCLE_HPP_ */ <|start_filename|>demo/ws2811_controller_low_ram.cpp<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /** * Demonstration of the ws2811 code for low-ram devices such as the attiny13 */ #define WS2811_PORT PORTB #include <avr/io.h> #include "ws2811/ws2811.h" #include "chasers.hpp" using namespace ws2811; namespace { /// transmit on bit 4 const uint8_t channel = 4; const uint8_t led_string_size = 60; typedef sparse_leds<38, led_string_size> buffer_type; buffer_type buffer; } int main() { DDRB = _BV(channel); //chasers_low_ram(buffer, channel); water_torture::animate<1, buffer_type>( buffer, channel); } <|start_filename|>demo/ws2811_controller.cpp<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /** * Demonstration of the ws2811 code for devices with enough RAM to hold values for 60 LEDs. * * Depending on which effect you want and on which port/bit you want to transmit do the following * - un-comment the appropriate include file * - define WS2811_PORT to be the port that you want to transmit on * - define the variable 'channel' as the bit you want to use for transmission * - make sure that you initialize the DDRn register, so that bit 'channel' becomes an output. * - call the appropriate code from main. * * Note that some demo functions still declare their own array of LEDs, and some require the main * function to declare such an array. * */ #include <avr/io.h> #include <util/delay.h> #include <stdlib.h> // Define the port at which the signal will be sent. The port needs to // be known at compilation time, the pin (0-7) can be chosen at run time. #define WS2811_PORT PORTC // send RGB in R,G,B order instead of the standard WS2811 G,R,B order. // Most ws2811 LED strips take their colors in GRB order, while some LED strings // take them in RGB. Default is GRB, define this symbol for RGB. //#define STRAIGHT_RGB #include "effects/chasers.hpp" #include "effects/flares.hpp" #include "effects/color_cycle.hpp" #include "effects/water_torture.hpp" #include "effects/campfire.hpp" namespace { // selects the pin (the bit of the chosen port). // this must be in the range 0-7 static const uint8_t channel = 4; // the number of LEDs in the string. static const uint16_t led_count = 144; // declare one RGB value for each led. ws2811::rgb leds[led_count]; } int main() { DDRC = _BV(channel); //campfire( leds, channel); water_torture::animate<3>( leds, channel); //flares::flares<10>( leds, channel); //chasers( leds, channel); //color_cycle::color_cycle(pattern, leds, channel); } <|start_filename|>effects/campfire.hpp<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /** * Simulation of a campfire using a WS2811 led string. * This code creates a campfire-like pattern by spacing 'flames' over the led string. * Each flame is a simple sequence that moves from dark and red-ish to light and yellow-ish and back. * The animation consists of letting each flame perform a random walk over the led string, adding * intensities where two flames overlap. * When the led string is curled up in a ball-shape and placed under a diffusing cover, this gives * a reasonably realistic fire animation. */ #ifndef CAMPFIRE_HPP_ #define CAMPFIRE_HPP_ #include <string.h> // for memset #include "ws2811/rgb_operators.hpp" #include "ws2811/ws2811.h" namespace { using ws2811::rgb; /// flame color pattern. This pattern is twice as big as the pattern that is actually drawn to allow /// anti-aliasing when rendering. const ws2811::rgb pattern[] = { rgb(2,0,0), rgb(8,0,0), rgb(15, 0,0 ), rgb( 20, 0, 0), rgb( 50, 0, 0), rgb( 80, 0, 0), rgb( 100, 20, 0), rgb( 120, 40, 0), rgb( 120, 60, 5), rgb( 120, 80, 10), rgb( 170, 110, 20), rgb( 240, 140, 30), rgb( 170, 110, 20), rgb( 120, 80, 10), rgb( 120, 60, 5), rgb( 120, 40, 0), rgb( 100, 20, 0), rgb( 80, 0, 0), rgb( 50, 0, 0), rgb( 20, 0, 0), rgb( 15, 0, 0), rgb( 8, 0, 0), rgb( 2, 0,0) }; const uint8_t pattern_size = sizeof pattern/sizeof pattern[0]; } /// A flame renders a flame-colored pattern on a sequence of leds. /// At each step of the animation, the flame will make a move to the left or /// right at random. /// A flame will remember its position. Note that the position is stored as /// a 15.1 fixed point number and that the used color sequence is also twice as /// big as the sequence that is actually drawn. This is done to create a smoother /// animation. class flame { public: explicit flame( uint16_t position = 0) :position( position * 2){} void step( rgb *leds, uint16_t size) { if (((rand()&7)==0) && position > 0) { position--; } if (((rand()&7)==0) && ((position + pattern_size) < size*2)) { position++; } draw( leds, size); } private: uint16_t position; /// Draw the color sequence at this flames position. void draw(rgb* leds, uint16_t size) { for (uint8_t color = 0; color < sizeof pattern / sizeof pattern[0]; ++color) { // note that we're only using half of the sequence colors if (!((position + color)&1) && (position + color)/2 < size) { add_clipped( leds[(position + color)/2], pattern[color]); } } } }; /// Animate a campfire on a WS2811 led string. /// This function creates a fixed amount of flame objects, disperses /// them over the led string and then lets the flames do their animation in /// a infinite loop. template< uint16_t size> void campfire( rgb (&leds)[size], uint8_t channel) { static const uint8_t flamecount = size/10; flame flames[flamecount]; const uint16_t step = (size - pattern_size)/flamecount; for (uint16_t pos = 0; pos < flamecount; ++pos) { flames[pos] = flame( step*pos); } for(;;) { clear(leds); for (uint8_t f = 0; f < flamecount; ++f) { flames[f].step( leds, size); } _delay_ms(20); send( leds, channel); } } #endif /* CAMPFIRE_HPP_ */ <|start_filename|>effects/chasers.hpp<|end_filename|> // // Copyright (c) 2013 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef CHASERS_HPP_ #define CHASERS_HPP_ #include <stdlib.h> #include <util/delay.h> #include <avr/pgmspace.h> #include "ws2811/ws2811.h" using ws2811::rgb; namespace { static const uint8_t amplitudes[] PROGMEM = { 255, 200, 150, 100, 80, 60, 50, 40, 30, 20, 10, 5, 4, 3, 2, 1 }; } /** * Larson scanner. * * An object of this class will move a string of leds from left-to-right * and from right-to-left over a WS2811 LED string. Each instantiation * of this class can have its own color. The first led of the string * will have that color, while the following leds have diminishing * intensities. * * When the step() or draw() functions are called, the object will * _add_ itself to the led string, so that overlapping chasers will * mix their colors. */ template<typename buffer_type, typename pos_type = int16_t, uint8_t tail_count = 16> class chaser { public: /** * calculate one animation step and draw the result to the * LED string. */ void step( buffer_type &leds) { step(); draw( leds); } /** * Only draw the current state to the given led string, don't animate. */ void draw( buffer_type &leds) const { static const uint8_t size = ws2811::led_buffer_traits<buffer_type>::count; static const uint8_t amplitude_count = sizeof amplitudes/sizeof amplitudes[0]; pos_type pos = position; uint16_t accumulator = 0; while (accumulator/tail_count < amplitude_count) { rgb &loc = get(leds, abs( pos)); loc = add_clipped( loc, scale( color, pgm_read_byte(&amplitudes[accumulator/tail_count]))); accumulator += amplitude_count; --pos; if( pos == -size) { pos = size -1; } } } chaser( const rgb &color, pos_type position) :color( color), position(position) {} rgb color; pos_type position; private: /// multiply an 8-bit value with an 8.8 bit fixed point number. /// multiplier should not be higher than 1.00 (or 256). static uint8_t mult( uint8_t value, uint16_t multiplier) { return (static_cast<uint16_t>( value) * multiplier) >> 8; } /// scale a color with a 8.8 fixed point constant. /// amplitude 256 corresponds with 1.0. static rgb scale(rgb value, uint16_t amplitude) { return rgb( mult( value.red, amplitude), mult( value.green, amplitude), mult( value.blue, amplitude) ); } /// add two 8-bit integers without overflowing. If the /// result of the addition is greater than 255, the result /// will be clipped to 255. static uint8_t add_clipped( uint8_t left, uint8_t right) { uint16_t result = static_cast<uint16_t>(left) + right; if (result > 255) result = 255; return result; } /// add two rgb values without overflow. static rgb add_clipped( const rgb &left, const rgb &right) { return rgb( add_clipped(left.red, right.red), add_clipped( left.green, right.green), add_clipped( left.blue, right.blue) ); } /// return the absolute value of the given position. static pos_type abs( pos_type pos) { return (pos < 0)?-pos:pos; } /// Make one animation step. void step( ) { static const uint8_t size = ws2811::led_buffer_traits<buffer_type>::count; if (++position >= size) { position = -(size-1); } } }; template<typename buffer_type, typename chaser_array> inline void chasers( buffer_type &buffer, chaser_array &chasers_array, uint8_t channel) { for(;;) { clear( buffer); for ( uint8_t idx = 0; idx < sizeof chasers_array/sizeof chasers_array[0]; ++idx) { chasers_array[idx].step( buffer); } send( buffer, channel); _delay_ms( 25); } } template<typename buffer_type> inline void chasers( buffer_type &leds, uint8_t channel) { typedef chaser<buffer_type> chaser_type; chaser_type chasers_array[] = { chaser_type( rgb( 50, 75, 15), 0), chaser_type( rgb( 10, 40, 60), 30), chaser_type( rgb( 255, 0,0), 50), chaser_type( rgb( 100, 100, 100), -35) }; chasers( leds, chasers_array, channel); } template< typename buffer_type> inline void chasers_low_ram( buffer_type &buffer, uint8_t channel) { typedef chaser<buffer_type, int8_t, 5> chaser_type; chaser_type chasers_array[] = { chaser_type( rgb( 50, 75, 15), 0), chaser_type( rgb( 50, 15, 75), -30) }; chasers( buffer, chasers_array, channel); } #endif /* CHASERS_HPP_ */ <|start_filename|>effects/water_torture.hpp<|end_filename|> /* * water_torture.hpp * * Created on: Feb 12, 2013 * Author: danny */ #ifndef WATER_TORTURE_HPP_ #define WATER_TORTURE_HPP_ #include <util/delay.h> #include "ws2811/ws2811.h" namespace water_torture { using ws2811::rgb; /// very crude pseudo random generator. /// /// The idea is to have a good enough random generator /// with a minimum of program space. uint16_t my_rand() { static uint16_t state; uint8_t count = 1+ state %5; state += count *33203; return state; // adding a prime number } uint8_t mult( uint8_t value, uint16_t multiplier) { return (static_cast<uint16_t>( value) * multiplier) >> 8; } /// This class maintains the state and calculates the animations to render a falling water droplet /// Objects of this class can have three states: /// - inactive: this object does nothing /// - swelling: the droplet is at the top of the led strip and swells in intensity /// - falling: the droplet falls downwards and accelerates /// - bouncing: the droplet has bounced of the ground. A smaller, less intensive droplet bounces up /// while a part of the drop remains on the ground. /// After going through the swelling, falling and bouncing phases, the droplet automatically returns to the /// inactive state. template<typename buffer_type, bool allow_swelling = true> class droplet { public: droplet( const rgb &color) :color( color), position(0), speed(0),state(allow_swelling?swelling:falling) {} droplet() // by default, be uninitialized { } /// calculate the next step in the animation for this droplet void step() { static uint8_t maxpos = ws2811::led_buffer_traits<buffer_type>::count - 1; if (state == falling || state == bouncing) { position += speed; speed += gravity; // if we hit the bottom... const uint16_t maxpos16 = maxpos << 8; if (position > maxpos16) { if (state == bouncing) { // this is the second collision, // deactivate. state = inactive; } else { // reverse direction and dampen the speed position = maxpos16 - (position - maxpos16); speed = -speed/3; color = scale( color, 10); state = bouncing; } } } else if (allow_swelling && state == swelling) { ++position; if ( color.blue <= 10 || color.blue - position/2 <= 10) { state = falling; position = 0; } } } /// perform one step and draw. void step( buffer_type &leds) { step(); draw( leds); } /// Draw the droplet on the led string /// This will "smear" the light of this droplet between two leds. The closer /// the droplets position is to that of a particular led, the brighter that /// led will be void draw( buffer_type &leds) { static uint8_t max_pos = ws2811::led_buffer_traits<buffer_type>::count - 1; if (state == falling || state == bouncing) { uint8_t position8 = position >> 8; uint8_t remainder = position; // get the lower bits add_clipped_to( get( leds, position8), scale( color, 256 - remainder )); if (remainder) { add_clipped_to( get( leds, position8+1), scale( color, remainder)); } if (state == bouncing) { add_clipped_to( get( leds, max_pos), color); } } else if (allow_swelling && state == swelling) { add_clipped_to( get( leds, 0), scale( color, position)); } } bool is_active() const { return state != inactive; } private: /// Add two numbers and clip the result at 255. static uint8_t add_clipped( uint16_t left, uint16_t right) { uint16_t result = left + right; if (result > 255) result = 255; return result; } /// Add the right rgb value to the left one, clipping if necessary static void add_clipped_to( rgb &left, const rgb &right) { left.red = add_clipped(left.red, right.red); left.green = add_clipped( left.green, right.green); left.blue = add_clipped( left.blue, right.blue); } /// multiply an 8-bit value with an 8.8 bit fixed point number. /// multiplier should not be higher than 1.00 (or 256). static uint8_t mult( uint8_t value, uint16_t multiplier) { return (static_cast<uint16_t>( value) * multiplier) >> 8; } /// scale an rgb value up or down. amplitude > 256 means scaling up, while /// amplitude < 256 means scaling down. static rgb scale(rgb value, uint16_t amplitude) { return rgb( mult( value.red, amplitude), mult( value.green, amplitude), mult( value.blue, amplitude) ); } // how much of a color is left when colliding with the floor, value // between 0 and 256 where 256 means no loss. static const uint16_t collision_scaling = 40; rgb color; uint16_t position; //< position in 8.8 fixed point, 256 means at LED 1, 384 means between LEDS 1 and 2, etc. int16_t speed; //< speed in 8.8 fixed point, 256 means 1 LED per cycle, 512 means 2 LEDs/cycle, etc. static const uint16_t gravity = 8; enum stateval { inactive, swelling, falling, bouncing }; stateval state; }; uint8_t debugcount = 0; volatile uint16_t random_scale() { return (my_rand() % 256); } template< typename buffer_type, bool allow_swelling> void create_random_droplet( droplet<buffer_type, allow_swelling> &d) { d = droplet<buffer_type, allow_swelling>( rgb( mult( 100 ,random_scale()), mult( 100, random_scale()), mult(255, random_scale()) )); } template<bool assertion> struct static_assert_ {}; template<> struct static_assert_<true> { static void is_true(){}; }; /// Create the complete water torture animation. /// This will render droplets at random intervals, up to a given maximum number of droplets. /// The maximum led count is 256 template< uint8_t droplet_count, typename buffer_type> void inline animate( buffer_type &leds, uint8_t channel) { static const uint16_t led_count = ws2811::led_buffer_traits<buffer_type>::count; // if you get an error that 'is_true' is not a member of static_assert_, you're probably using // more than 255 leds, which doesn't work for this function. static_assert_< led_count <= 255>::is_true(); typedef droplet<buffer_type, true> droplet_type; droplet_type droplets[droplet_count]; // droplets that can animate simultaneously. uint8_t current_droplet = 0; // index of the next droplet to be created uint16_t droplet_pause = 1; // how long to wait for the next one for(;;) { if (droplet_pause) { --droplet_pause; } else { if (!droplets[current_droplet].is_active()) { create_random_droplet( droplets[current_droplet]); ++current_droplet; if (current_droplet >= droplet_count) current_droplet = 0; droplet_pause = 200 + my_rand() % 128; } } clear( leds); for (uint8_t idx = 0; idx < droplet_count; ++idx) { droplets[idx].step( leds); } send( leds, channel); _delay_ms( 1); } } } #endif /* WATER_TORTURE_HPP_ */
DannyHavenith/ws2811
<|start_filename|>src/include/occhw_common.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/occhw_common.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_COMMON_H__ #define __OCCHW_COMMON_H__ /// \file occhw_common.h /// \brief Common header for SSX and PMX versions of OCCHW /// /// This header is maintained as part of the SSX port for OCCHW, but needs to be /// physically present in the PMX area to allow dropping PMX code as a whole /// to other teams. // -*- WARNING: This file is maintained as part of SSX. Do not edit in -*- // -*- the PMX area as your edits will be lost. -*- #include "occhw_interrupts.h" #include "occhw_irq_config.h" #define EXTERNAL_IRQS OCCHW_IRQS #ifndef __ASSEMBLER__ #include <stdint.h> extern unsigned int g_ocb_timer_divider; #endif //////////////////////////////////////////////////////////////////////////// // Configuration //////////////////////////////////////////////////////////////////////////// #define OCCHW_NCORES 16 #define OCCHW_NCORE_PARTITIONS 4 #define OCCHW_NMCS 8 #define OCCHW_NCENTAUR 8 #define OCCHW_NTHREADS 8 #define OCCHW_NDTSCPM 4 #ifndef PROCESSOR_EC_LEVEL #define MURANO_DD10 1 #else #define MURANO_DD10 0 #endif #ifndef SIMICS_ENVIRONMENT #define SIMICS_ENVIRONMENT 0 #endif /// OCC instance ID's that can be read from the PPE42 PIR and used in IPC operations. /// NOTE: The PPC instance ID is not associated with a register and was assigned to be /// four as it was most convenient to do so in the code. #define OCCHW_MAX_INSTANCES 5 #define OCCHW_INST_ID_GPE0 0 #define OCCHW_INST_ID_GPE1 1 #define OCCHW_INST_ID_GPE2 2 #define OCCHW_INST_ID_GPE3 3 #define OCCHW_INST_ID_PPC 4 #define OCCHW_INST_ID_MAX (OCCHW_MAX_INSTANCES - 1) #define OCCHW_INST_ID_MAX_GPE 3 /// Fail to compile if APPCFG_OCC_INSTANCE_ID is not defined somewhere or is out of range #ifndef APPCFG_OCC_INSTANCE_ID #error "APPCFG_OCC_INSTANCE_ID must be defined by the application" #else #if ((APPCFG_OCC_INSTANCE_ID > OCCHW_INST_ID_MAX) || (APPCFG_OCC_INSTANCE_ID < 0)) #warning "APPCFG_OCC_INSTANCE_ID is out of range" #endif #endif #define OCCHW_INST_ID_SELF APPCFG_OCC_INSTANCE_ID //////////////////////////////////////////////////////////////////////////// // Clocking //////////////////////////////////////////////////////////////////////////// // // The SSX timebase is driven by the pervasive clock, which is nest / 4. This // will typically be 600MHz, but may be 500MHz for power-constrained system // designs. /// The pervasive hang timer divider used for the OCB timer /// /// This is supposed to yield an approximately 1us timer, however for MURANO /// DD10 we need to use an approximate 64us timer #if MURANO_DD10 #define OCB_TIMER_DIVIDER_DEFAULT (64 * 512) #else #define OCB_TIMER_DIVIDER_DEFAULT 512 #endif /// This is set to the above default at compile time but may be updated /// at run time. grm //#define OCB_TIMER_DIVIDER g_ocb_timer_divider #define OCB_TIMER_DIVIDER OCB_TIMER_DIVIDER_DEFAULT /// The OCB timer frequency #define OCB_TIMER_FREQUENCY_HZ (SSX_TIMEBASE_FREQUENCY_HZ / OCB_TIMER_DIVIDER) /// The pervasive hang timer divider used for the PMC (same as OCB timer) #define PMC_TIMER_DIVIDER OCB_TIMER_DIVIDER /// The PMC hang pulse frequency #define PMC_HANG_PULSE_FREQUENCY_HZ \ (SSX_TIMEBASE_FREQUENCY_HZ / PMC_TIMER_DIVIDER) /// The pervasive hang timer divider for PCBS 'fast' timers /// /// This timer yeilds an approximate 100ns pulse with a 2.4 GHz pervasive clock #define PCBS_FAST_TIMER_DIVIDER 64 /// The pervasive hang timer divider for PCBS 'slow' timers /// /// This timer yeilds an approximate 1us pulse with a 2.4 GHz pervasive clock #define PCBS_SLOW_TIMER_DIVIDER 512 /// The PCBS slow divider frequency #define PCBS_SLOW_HANG_PULSE_FREQUENCY_HZ \ (SSX_TIMEBASE_FREQUENCY_HZ / PCBS_SLOW_TIMER_DIVIDER) /// The PCBS occ heartbeat pulse is predivided in hardware by 64 #define PCBS_HEARTBEAT_DIVIDER \ (PCBS_SLOW_TIMER_DIVIDER * 64) /// The PCBS heartbeat pulse frequency #define PCBS_HEARTBEAT_PULSE_FREQUENCY_HZ \ (SSX_TIMEBASE_FREQUENCY_HZ / PCBS_HEARTBEAT_DIVIDER) //////////////////////////////////////////////////////////////////////////// // OCI //////////////////////////////////////////////////////////////////////////// // OCI Master Id assigments - required for PBA slave programming. These Ids // also appear as bits 12:15 of the OCI register space addresses of the OCI // registers for each device that contains OCI-addressable registers (GPE, // PMC, PBA, SLW and OCB). #define OCI_TRANSPORT_DELAY 10 #define OCI_MASTER_ID_PHONY -1 #define OCI_MASTER_ID_GPE0 0 #define OCI_MASTER_ID_GPE1 1 #define OCI_MASTER_ID_GPE2 2 #define OCI_MASTER_ID_GPE3 3 #define OCI_MASTER_ID_PBA 4 #define OCI_MASTER_ID_OCC_ICU 5 #define OCI_MASTER_ID_OCB 6 #define OCI_MASTER_ID_OCC_DCU 7 //////////////////////////////////////////////////////////////////////////// // PIB //////////////////////////////////////////////////////////////////////////// #define PIB_TRANSPORT_DELAY 50 #define PIB_MASTER_ID_PHONY -1 #define PIB_MASTER_ID_FSI2PIB 0x2 #define PIB_MASTER_ID_FSI_SHIFT 0x3 #define PIB_MASTER_ID_TOD 0x4 #define PIB_MASTER_ID_PMC 0x6 #define PIB_MASTER_ID_PORE_GPE 0x7 #define PIB_MASTER_ID_PORE_SLW 0x8 #define PIB_MASTER_ID_ADU 0x9 #define PIB_MASTER_ID_MEMS0 0xA #define PIB_MASTER_ID_I2C_SLAVE 0xD #define PIB_MASTER_ID_PORE_SBE 0xE //////////////////////////////////////////////////////////////////////////// // OCB //////////////////////////////////////////////////////////////////////////// /// The base address of the OCI control register space #define OCI_REGISTER_SPACE_BASE 0xC0000000 /// The base address of the entire PIB port mapped by the OCB. The /// OCB-contained PIB registers are based at OCB_PIB_BASE. #define OCB_PIB_SLAVE_BASE 0x00060000 /// The size of the OCI control register address space /// /// There are at most 8 slaves, each of which maps 2**16 bytes of register /// address space. #define OCI_REGISTER_SPACE_SIZE POW2_32(19) /// This macro converts an OCI register space address into a PIB address as /// seen through the OCB direct bridge. #define OCI2PIB(addr) ((((addr) & 0x0007ffff) >> 3) + OCB_PIB_SLAVE_BASE) // OCB communication channel constants #define OCB_INDIRECT_CHANNELS 4 #define OCB_RW_READ 0 #define OCB_RW_WRITE 1 #define OCB_STREAM_MODE_DISABLED 0 #define OCB_STREAM_MODE_ENABLED 1 #define OCB_STREAM_TYPE_LINEAR 0 #define OCB_STREAM_TYPE_CIRCULAR 1 #define OCB_INTR_ACTION_FULL 0 #define OCB_INTR_ACTION_NOT_FULL 1 #define OCB_INTR_ACTION_EMPTY 2 #define OCB_INTR_ACTION_NOT_EMPTY 3 //////////////////////////////////////////////////////////////////////////// // PMC //////////////////////////////////////////////////////////////////////////// /* #ifndef __ASSEMBLER__ /// A Pstate type /// /// Pstates are signed, but our register access macros operate on unsigned /// values. To avoid bugs, Pstate register fields should always be extracted /// to a variable of type Pstate. If the size of Pstate variables ever /// changes we will have to revisit this convention. typedef int8_t Pstate; /// A DPLL frequency code /// /// DPLL frequency codes moved from 8 to 9 bits going from P7 to P8 typedef uint16_t DpllCode; /// A VRM11 VID code typedef uint8_t Vid11; #endif // __ASSEMBLER__ /// The minimum Pstate #define PSTATE_MIN -128 /// The maximum Pstate #define PSTATE_MAX 127 /// The minimum \e legal DPLL frequency code /// /// This is ~1GHz with a 33.3MHz tick frequency. #define DPLL_MIN 0x01e /// The maximum DPLL frequency code #define DPLL_MAX 0x1ff /// The minimum \a legal (non-power-off) VRM11 VID code #define VID11_MIN 0x02 /// The maximum \a legal (non-power-off) VRM11 VID code #define VID11_MAX 0xfd */ //////////////////////////////////////////////////////////////////////////// // PCB //////////////////////////////////////////////////////////////////////////// /// Convert a core chiplet 0 SCOM address to the equivalent address for any /// other core chiplet. /// /// Note that it is unusual to address core chiplet SCOMs directly. Normally /// this is done as part of a GPE program where the program iterates over core /// chiplets, using the chiplet-0 address + a programmable offset held in a /// chiplet address register. Therefore the only address macro defined is the /// chiplet-0 address. This macro is used for the rare cases of explicit /// getscom()/ putscom() to a particular chiplet. #define CORE_CHIPLET_ADDRESS(addr, core) ((addr) + ((core) << 24)) // PCB/PMC interrupt packet constants #define PCB_INTERRUPT_PACKET_PERVASIVE 0x0 #define PCB_INTERRUPT_PACKET_POWER_MANAGEMENT 0x7 #define PMC_INTERRUPT_TYPE_PSTATE 0x0 #define PMC_INTERRUPT_TYPE_IDLE 0x1 #define PMC_INTERRUPT_TYPE_NOTIFY 0x2 #define PMC_INTERRUPT_SLEEP_EXIT 0x2 #define PMC_INTERRUPT_WINKLE_EXIT 0x3 #define PMC_INTERRUPT_SLEEP_ENTRY 0x6 #define PMC_INTERRUPT_WINKLE_ENTRY 0x7 // Reserved #define PMC_INTERRUPT_NAP_EXIT 0x1 // Reserved #define PMC_INTERRUPT_DOZE_ENTRY 0x4 // Reserved #define PMC_INTERRUPT_NAP_ENTRY 0x5 #define PMC_INTERRUPT_PMAX_SYNC 0x1 #define PMC_INTERRUPT_GPSA_ACK 0x2 #define PMC_INTERRUPT_DPLL_ERROR 0x3 // Spec says "placeholder" // PCB Error codes #define PCB_ERROR_NONE 0 #define PCB_ERROR_RESOURCE_OCCUPIED 1 #define PCB_ERROR_CHIPLET_OFFLINE 2 #define PCB_ERROR_PARTIAL_GOOD 3 #define PCB_ERROR_ADDRESS_ERROR 4 #define PCB_ERROR_CLOCK_ERROR 5 #define PCB_ERROR_PACKET_ERROR 6 #define PCB_ERROR_TIMEOUT 7 // PCB Multicast modes #define PCB_MULTICAST_OR 0 #define PCB_MULTICAST_AND 1 #define PCB_MULTICAST_SELECT 2 #define PCB_MULTICAST_COMPARE 4 #define PCB_MULTICAST_WRITE 5 /// \defgroup pcb_multicast_groups PCB Multicast Groups /// /// Technically the multicast groups are programmable; This is the multicast /// grouping established by proc_sbe_chiplet_init(). /// /// - Group 0 : All functional chiplets (PRV PB XBUS ABUS PCIE TPCEX) /// - Group 1 : All functional EX chiplets (no cores) /// - Group 2 : All functional EX chiplets (core only) /// - Group 3 : All functional chiplets except pervasive (PRV) /// /// @{ #define MC_GROUP_ALL 0 #define MC_GROUP_EX 1 #define MC_GROUP_EX_CORE 2 #define MC_GROUP_ALL_BUT_PRV 3 /// @} /// Convert any SCOM address to a multicast address #define MC_ADDRESS(address, group, mode) \ (((address) & 0x00ffffff) | ((0x40 | ((mode) << 3) | (group)) << 24)) //////////////////////////////////////////////////////////////////////////// // PBA //////////////////////////////////////////////////////////////////////////// //////////////////////////////////// // Macros for fields of PBA_MODECTL //////////////////////////////////// /// The 64KB OCI HTM marker space is enabled by default at 0xC0070000 /// /// See the comments for occhw_trace.h #define PBA_OCI_MARKER_BASE 0xC0070000 // SSX Kernel reserved trace addresses, see occhw_trace.h. #define SSX_TRACE_CRITICAL_IRQ_ENTRY_BASE 0xf000 #define SSX_TRACE_CRITICAL_IRQ_EXIT_BASE 0xf100 #define SSX_TRACE_NONCRITICAL_IRQ_ENTRY_BASE 0xf200 #define SSX_TRACE_NONCRITICAL_IRQ_EXIT_BASE 0xf300 #define SSX_TRACE_THREAD_SWITCH_BASE 0xf400 #define SSX_TRACE_THREAD_SLEEP_BASE 0xf500 #define SSX_TRACE_THREAD_WAKEUP_BASE 0xf600 #define SSX_TRACE_THREAD_SEMAPHORE_PEND_BASE 0xf700 #define SSX_TRACE_THREAD_SEMAPHORE_POST_BASE 0xf800 #define SSX_TRACE_THREAD_SEMAPHORE_TIMEOUT_BASE 0xf900 #define SSX_TRACE_THREAD_SUSPENDED_BASE 0xfa00 #define SSX_TRACE_THREAD_DELETED_BASE 0xfb00 #define SSX_TRACE_THREAD_COMPLETED_BASE 0xfc00 #define SSX_TRACE_THREAD_MAPPED_RUNNABLE_BASE 0xfd00 #define SSX_TRACE_THREAD_MAPPED_SEMAPHORE_PEND_BASE 0xfe00 #define SSX_TRACE_THREAD_MAPPED_SLEEPING_BASE 0xff00 // Please keep the string definitions up to date as they are used for // reporting in the Simics simulation. #define SSX_TRACE_STRINGS(var) \ const char* var[16] = { \ "Critical IRQ Entry ", \ "Critical IRQ Exit ", \ "Noncritical IRQ Entry ", \ "Noncritical IRQ Exit ", \ "Thread Switch ", \ "Thread Blocked : Sleep ", \ "Thread Unblocked : Wakeup ", \ "Thread Blocked : Semaphore ", \ "Thread Unblocked : Semaphore ", \ "Thread Unblocked : Sem. Timeout", \ "Thread Suspended ", \ "Thread Deleted ", \ "Thread Completed ", \ "Thread Mapped Runnable ", \ "Thread Mapped Semaphore Pend. ", \ "Thread Mapped Sleeping ", \ }; // PBA transaction sizes for the block copy engines #define PBA_BCE_OCI_TRANSACTION_32_BYTES 0 #define PBA_BCE_OCI_TRANSACTION_64_BYTES 1 #define PBA_BCE_OCI_TRANSACTION_8_BYTES 2 // PBAX communication channel constants #define PBAX_CHANNELS 2 #define PBAX_INTR_ACTION_FULL 0 #define PBAX_INTR_ACTION_NOT_FULL 1 #define PBAX_INTR_ACTION_EMPTY 2 #define PBAX_INTR_ACTION_NOT_EMPTY 3 // PBA Write Buffer fields #define PBA_WBUFVALN_STATUS_EMPTY 0x01 #define PBA_WBUFVALN_STATUS_GATHERING 0x02 #define PBA_WBUFVALN_STATUS_WAIT 0x04 #define PBA_WBUFVALN_STATUS_WRITING 0x08 #define PBA_WBUFVALN_STATUS_CRESPERR 0x10 //////////////////////////////////////////////////////////////////////////// // VRM //////////////////////////////////////////////////////////////////////////// // These are the command types recognized by the VRMs #define VRM_WRITE_VOLTAGE 0x0 #define VRM_READ_STATE 0xc #define VRM_READ_VOLTAGE 0x3 // Voltage rail designations for the read voltage command #define VRM_RD_VDD_RAIL 0x0 #define VRM_RD_VCS_RAIL 0x1 //////////////////////////////////////////////////////////////////////////// // OHA //////////////////////////////////////////////////////////////////////////// // Power proxy trace record idle state encodings. These encodings are unique // to the Power proxy trace record. #define PPT_IDLE_NON_IDLE 0x0 #define PPT_IDLE_NAP 0x1 #define PPT_IDLE_LIGHT_SLEEP 0x2 #define PPT_IDLE_FAST_SLEEP 0x3 #define PPT_IDLE_DEEP_SLEEP 0x4 #define PPT_IDLE_LIGHT_WINKLE 0x5 #define PPT_IDLE_FAST_WINKLE 0x6 #define PPT_IDLE_DEEP_WINKLE 0x7 //////////////////////////////////////////////////////////////////////////// // PC //////////////////////////////////////////////////////////////////////////// // SPRC numbers for PC counters. The low-order 3 bits are always defined as // 0. The address can also be modified by OR-ing in 0x400 to indicate // auto-increment addressing. Note that the frequency-sensitivity counters // are called "workrate" counters in the hardware documentation. // // Notes on the throttle counters: // // SPRN_IFU_THROTTLE_COUNTER // Cycles the IFU throttle was actually blocking fetch // // <= if_pc_didt_throttle_blocked // // SPRN_ISU_THROTTLE_COUNTER // Cycles that ISU throttle was active and modeably IFU throttle request // was not // // <= sd_pc_uthrottle_active AND // (NOT scom_isuonly_count_mode OR NOT trigger_didt_throttle) // // SPRN_IFU_ACTIVE_COUNTER // Cycles that IFU throttle active input is asserted // // <= if_pc_didt_throttle_active /// \note The OCC SPRC/SPRD hardware has a bug that makes it such that the OCC /// SPRC increments whenever the OCC SPRD is accessed, regardless of the /// setting of the SPRN_PC_AUTOINCREMENT bit. This bug won't be fixed. #define SPRN_CORE_INSTRUCTION_DISPATCH 0x200 #define SPRN_CORE_INSTRUCTION_COMPLETE 0x208 #define SPRN_CORE_FREQUENCY_SENSITIVITY_BUSY 0x210 #define SPRN_CORE_FREQUENCY_SENSITIVITY_FINISH 0x218 #define SPRN_CORE_RUN_CYCLE 0x220 #define SPRN_CORE_RAW_CYCLE 0x228 #define SPRN_CORE_MEM_HIER_A 0x230 #define SPRN_CORE_MEM_HIER_B 0x238 #define SPRN_CORE_MEM_C_LPAR(p) (0x240 + (8 * (p))) #define SPRN_WEIGHTED_INSTRUCTION_PROCESSING 0x260 #define SPRN_WEIGHTED_GPR_REGFILE_ACCESS 0x268 #define SPRN_WEIGHTED_VRF_REGFILE_ACCESS 0x270 #define SPRN_WEIGHTED_FLOATING_POINT_ISSUE 0x278 #define SPRN_WEIGHTED_CACHE_READ 0x280 #define SPRN_WEIGHTED_CACHE_WRITE 0x288 #define SPRN_WEIGHTED_ISSUE 0x290 #define SPRN_WEIGHTED_CACHE_ACCESS 0x298 #define SPRN_WEIGHTED_VSU_ISSUE 0x2a0 #define SPRN_WEIGHTED_FXU_ISSUE 0x2a8 #define SPRN_THREAD_RUN_CYCLES(t) (0x2b0 + (0x20 * (t))) #define SPRN_THREAD_INSTRUCTION_COMPLETE(t) (0x2b8 + (0x20 * (t))) #define SPRN_THREAD_MEM_HIER_A(t) (0x2c0 + (0x20 * (t))) #define SPRN_THREAD_MEM_HIER_B(t) (0x2c8 + (0x20 * (t))) #define SPRN_IFU_THROTTLE_COUNTER 0x3b0 #define SPRN_ISU_THROTTLE_COUNTER 0x3b8 #define SPRN_IFU_ACTIVE_COUNTER 0x3c0 #define SPRN_PC_AUTOINCREMENT 0x400 //////////////////////////////////////////////////////////////////////////// // Centaur //////////////////////////////////////////////////////////////////////////// // DIMM sensor status codes /// The next sampling period began before this sensor was read or the master /// enable is off, or the individual sensor is disabled. If the subsequent /// read completes on time, this will return to valid reading. Sensor data may /// be accurate, but stale. If due to a stall, the StallError FIR will be /// set. #define DIMM_SENSOR_STATUS_STALLED 0 /// The sensor data was not returned correctly either due to parity /// error or PIB bus error code. Will return to valid if the next PIB /// access to this sensor is valid, but a FIR will be set; Refer to FIR /// for exact error. Sensor data should not be considered valid while /// this code is present. #define DIMM_SENSOR_STATUS_ERROR 1 /// Sensor data is valid, and has been valid since the last time this /// register was read. #define DIMM_SENSOR_STATUS_VALID_OLD 2 /// Sensor data is valid and has not yet been read by a SCOM. The status code /// return to DIMM_SENSOR_STATUS_VALID_OLD after this register is read. #define DIMM_SENSOR_STATUS_VALID_NEW 3 /// OCCHW SSX panic codes /// For PK panic codes, see pk_panic_codes.h #ifdef __SSX__ #define OCCHW_INSTANCE_MISMATCH 0x00622400 #define OCCHW_IRQ_ROUTING_ERROR 0x00622401 #define OCCHW_XIR_INVALID_POINTER 0x00622402 #define OCCHW_XIR_INVALID_GPE 0x00622403 #endif #endif /* __OCCHW_COMMON_H__ */ <|start_filename|>src/common/gpu_structs.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/common/gpu_structs.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* This header file is used by both occ_405 and occ_gpe1. */ /* Contains common structures and globals. */ #ifndef _GPU_STRUCTS_H #define _GPU_STRUCTS_H #include "occ_util.h" #include <gpe_export.h> #include "gpe_err.h" #define MAX_GPUS 3 #define GPU_RESET_REQ_MASTER 1 #define GPU_RESET_REQ_SLV 2 #define GPU_RESET_REQ_SLV_COMPLETE 3 typedef enum { GPU_CAP_MEM = 0x00, GPU_CAP_CORE = 0x01 } GPU_CAPABILITIES; typedef enum { ID_GPU0 = 0x00, ID_GPU1 = 0x01, ID_GPU2 = 0x02, ID_ALL_GPUS = 0xFF } GPU_ID; typedef enum { GPU_STATE_PRESENT = 0x00000001, GPU_STATE_FAILED = 0x80000000, } GPU_STATE; // GPU Request Operations typedef enum { // Initialize the GPU state machine and I2C engine GPU_REQ_INIT = 0x01, // Read GPU core temperature GPU_REQ_READ_TEMP_START = 0x02, GPU_REQ_READ_TEMP_FINISH = 0x03, // Read GPU memory temperature GPU_REQ_READ_MEM_TEMP_START = 0x04, GPU_REQ_READ_MEM_TEMP_2 = 0x05, GPU_REQ_READ_MEM_TEMP_3 = 0x06, GPU_REQ_READ_MEM_TEMP_FINISH = 0x07, // Read thermal capabilities GPU_REQ_READ_CAPS_START = 0x08, GPU_REQ_READ_CAPS_2 = 0x09, GPU_REQ_READ_CAPS_3 = 0x0A, GPU_REQ_READ_CAPS_FINISH = 0x0B, // Set GPU power cap GPU_REQ_SET_PWR_LIMIT_1_START = 0x20, GPU_REQ_SET_PWR_LIMIT_1_2 = 0x21, GPU_REQ_SET_PWR_LIMIT_1_3 = 0x22, GPU_REQ_SET_PWR_LIMIT_1_FINISH = 0x23, GPU_REQ_SET_PWR_LIMIT_2_START = 0x24, GPU_REQ_SET_PWR_LIMIT_2_2 = 0x25, GPU_REQ_SET_PWR_LIMIT_2_3 = 0x26, GPU_REQ_SET_PWR_LIMIT_2_FINISH = 0x27, GPU_REQ_SET_PWR_LIMIT_3_START = 0x28, GPU_REQ_SET_PWR_LIMIT_3_2 = 0x29, GPU_REQ_SET_PWR_LIMIT_3_3 = 0x2A, GPU_REQ_SET_PWR_LIMIT_3_FINISH = 0x2B, GPU_REQ_SET_PWR_LIMIT_4_START = 0x2C, GPU_REQ_SET_PWR_LIMIT_4_2 = 0x2D, GPU_REQ_SET_PWR_LIMIT_4_FINISH = 0x2E, // Start check driver loaded GPU_REQ_CHECK_DRIVER_START = 0x31, GPU_REQ_CHECK_DRIVER_2 = 0x32, GPU_REQ_CHECK_DRIVER_3 = 0x33, GPU_REQ_CHECK_DRIVER_FINISH = 0x34, // Read power limit policy GPU_REQ_GET_PWR_LIMIT_1_START = 0x40, GPU_REQ_GET_PWR_LIMIT_1_2 = 0x41, GPU_REQ_GET_PWR_LIMIT_1_3 = 0x42, GPU_REQ_GET_PWR_LIMIT_1_FINISH = 0x43, GPU_REQ_GET_PWR_LIMIT_2_START = 0x44, GPU_REQ_GET_PWR_LIMIT_2_2 = 0x45, GPU_REQ_GET_PWR_LIMIT_2_FINISH = 0x46, GPU_REQ_GET_PWR_LIMIT_3_START = 0x47, GPU_REQ_GET_PWR_LIMIT_3_2 = 0x48, GPU_REQ_GET_PWR_LIMIT_3_3 = 0x49, GPU_REQ_GET_PWR_LIMIT_3_FINISH = 0x4A, GPU_REQ_GET_PWR_LIMIT_4_START = 0x4B, GPU_REQ_GET_PWR_LIMIT_4_2 = 0x4C, GPU_REQ_GET_PWR_LIMIT_4_3 = 0x4D, GPU_REQ_GET_PWR_LIMIT_4_FINISH = 0x4E, GPU_REQ_GET_PWR_LIMIT_5_START = 0x4F, GPU_REQ_GET_PWR_LIMIT_5_2 = 0x50, GPU_REQ_GET_PWR_LIMIT_5_3 = 0x51, GPU_REQ_GET_PWR_LIMIT_5_FINISH = 0x52, // Reset the I2C master and slave GPU_REQ_RESET = 0x60, } gpu_op_req_e; // GPU arguments typedef struct { GpeErrorStruct error; uint8_t gpu_id; uint8_t gpu_rc; uint8_t operation; uint64_t data[3]; } gpu_sm_args_t; typedef struct { uint32_t pib_master; uint32_t bus_voltage; uint32_t port[MAX_GPUS]; uint32_t addr[MAX_GPUS]; } gpu_i2c_info_t; typedef struct { GpeErrorStruct error; gpu_i2c_info_t gpu_i2c; } gpu_init_args_t; #endif // _GPU_STRUCTS_H <|start_filename|>src/ssx/ppc405/ppc405_irq_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_irq_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppc405_irq_init.c /// \brief PPC405 IRQ initialization routines /// /// The entry points in this file are routines that are typically used during /// initialization, and their code space could be deallocated and recovered if /// no longer needed by the application after initialization. #include "ssx.h" /// Set up a PPC405 Fixed Interval Timer (FIT) handler /// /// See the SSX specification for full details on setting up a FIT handler. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_PPC405_FIT The \a tcr_fp argument was /// invalid when called with a non-null (non-0) \a handler. // Since the SSX_CRITICAL Watchdog interrupt is also controlled by the TCR, we // need to enter an SSX_CRITICAL critical section to manipulate the TCR. int ppc405_fit_setup(int tcr_fp, SsxIrqHandler handler, void* arg) { SsxMachineContext ctx; Ppc405TCR tcr; if (SSX_ERROR_CHECK_API && handler) { SSX_ERROR_IF((tcr_fp < 0) || (tcr_fp > 3), SSX_INVALID_ARGUMENT_PPC405_FIT); } ssx_critical_section_enter(SSX_CRITICAL, &ctx); tcr.value = mfspr(SPRN_TCR); if (handler) { tcr.fields.fp = tcr_fp; tcr.fields.fie = 1; __ppc405_fit_routine = handler; __ppc405_fit_arg = arg; } else { tcr.fields.fie = 0; } mtspr(SPRN_TCR, tcr.value); isync(); ssx_critical_section_exit(&ctx); return SSX_OK; } /// Set up a PPC405 Watchdog interrupt handler /// /// See the SSX specification for full details on setting up a watchdog /// handler. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_PPC405_WATCHDOG One or more of the \a tcr_wp /// or \a tcr_wrc arguments were invalid. int ppc405_watchdog_setup(int tcr_wp, int tcr_wrc, SsxIrqHandler handler, void* arg) { SsxMachineContext ctx; Ppc405TCR tcr; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((tcr_wp < 0) || (tcr_wp > 3) || (tcr_wrc < 0) || (tcr_wrc > 3), SSX_INVALID_ARGUMENT_PPC405_WATCHDOG); } ssx_critical_section_enter(SSX_CRITICAL, &ctx); mtspr(SPRN_TSR, TSR_ENW | TSR_WIS); tcr.value = mfspr(SPRN_TCR); tcr.fields.wp = tcr_wp; tcr.fields.wrc = tcr_wrc; if (handler == 0) { // Reinstall the default handler and clear the interrupt enable. Then // clear any pending interrupt status. // WIS. __ppc405_watchdog_routine = __ppc405_default_irq_handler; __ppc405_watchdog_arg = 0; tcr.fields.wie = 0; mtspr(SPRN_TCR, tcr.value); isync(); mtspr(SPRN_TSR, TSR_WIS); isync(); } else { // Install the new handler and enable the watchdog interrup. __ppc405_watchdog_routine = handler; __ppc405_watchdog_arg = arg; tcr.fields.wie = 1; mtspr(SPRN_TCR, tcr.value); isync(); } ssx_critical_section_exit(&ctx); return SSX_OK; } /// Set up a PPC405 Debug interrupt handler /// /// See the SSX specification for full details on setting up a debug handler. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_PPC405_DEBUG The \a handler argument /// is null (0). // The debug handler is installed in an SSX_CRITICAL critical section with all // debug interrupts disabled as well. int ppc405_debug_setup(SsxIrqHandler handler, void* arg) { SsxMachineContext ctx; ssx_critical_section_enter(SSX_CRITICAL, &ctx); andc_msr(MSR_DE | MSR_DWE); __ppc405_debug_routine = handler; __ppc405_debug_arg = arg; isync(); ssx_critical_section_exit(&ctx); return SSX_OK; } <|start_filename|>src/include/registers/sramctl_register_addresses.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/sramctl_register_addresses.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SRAMCTL_REGISTER_ADDRESSES_H__ #define __SRAMCTL_REGISTER_ADDRESSES_H__ /// \file sramctl_register_addresses.h /// \brief Symbolic addresses for the SRAMCTL unit // *** WARNING *** - This file is generated automatically, do not edit. #define SRAMCTL_OCI_BASE 0x40050000 #define SRAMCTL_SRBAR 0x40050000 #define SRAMCTL_SRMR 0x40050008 #define SRAMCTL_SRMAP 0x40050010 #define SRAMCTL_SREAR 0x40050018 #define SRAMCTL_SRBV0 0x40050020 #define SRAMCTL_SRBV1 0x40050028 #define SRAMCTL_SRBV2 0x40050030 #define SRAMCTL_SRBV3 0x40050038 #define SRAMCTL_SRCHSW 0x40050040 #endif // __SRAMCTL_REGISTER_ADDRESSES_H__ <|start_filename|>src/ssx/ppc405/ppc405_mmu.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_mmu.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_MMU_H__ #define __PPC405_MMU_H__ /// \file ppc405_mmu.h /// \brief Definitions related to the PPC405 MMU and its use in SSX. #ifndef __ASSEMBLER__ #include "ssx_io.h" #include <stdint.h> /// The PPC405 TLBHI (tag) structure /// /// Note that in hardware this is a 36-bit register, as it includes the TID /// field. When writing, TID is set from the current PID, and when reading PID /// is set from the TID entry of the register. typedef union { uint32_t value; struct { uint32_t epn : 22; uint32_t size : 3; uint32_t v : 1; uint32_t e : 1; uint32_t u0 : 1; } fields; } Ppc405Tlbhi; /// The PPC405 TLBLO (Data) structure typedef union { uint32_t value; struct { uint32_t rpn : 22; uint32_t ex : 1; uint32_t wr : 1; uint32_t zsel : 4; uint32_t w : 1; uint32_t i : 1; uint32_t m : 1; uint32_t g : 1; } fields; } Ppc405Tlblo; #endif /* __ASSEMBLER__ */ // TLBHI contains little-endian and U0 flags (probably never used) #define TLBHI_E 0x00000020 #define TLBHI_U0 0x00000010 #define TLBHI_LEGAL_FLAGS (TLBHI_E | TLBHI_U0) // TLBLO contains WIMG + EX/WR bits #define TLBLO_EX 0x00000200 #define TLBLO_WR 0x00000100 #define TLBLO_W 0x00000008 #define TLBLO_I 0x00000004 #define TLBLO_M 0x00000002 #define TLBLO_G 0x00000001 #define TLBLO_LEGAL_FLAGS \ (TLBLO_EX | TLBLO_WR | TLBLO_W | TLBLO_I | TLBLO_M | TLBLO_G) #define PPC405_TLB_ENTRIES 64 #define PPC405_PAGE_SIZE_MIN 1024 #define PPC405_PAGE_SIZE_MAX (16 * 1024 * 1024) #define PPC405_LOG_PAGE_SIZE_MIN 10 #define PPC405_LOG_PAGE_SIZE_MAX 24 #define PPC405_PAGE_SIZE_1K 0 #define PPC405_PAGE_SIZE_4K 1 #define PPC405_PAGE_SIZE_16K 2 #define PPC405_PAGE_SIZE_64K 3 #define PPC405_PAGE_SIZE_256K 4 #define PPC405_PAGE_SIZE_1M 5 #define PPC405_PAGE_SIZE_4M 6 #define PPC405_PAGE_SIZE_16M 7 // PPC405 MMU error and panic codes #define PPC405_MMU_ILLEGAL_CONTEXT 0x00668001 #define PPC405_MMU_INVALID_ARGUMENT 0x00668002 #define PPC405_TOO_MANY_TLB_ENTRIES 0x00668003 #define PPC405_DUPLICATE_TLB_ENTRY 0x00668004 #ifndef __ASSEMBLER__ /// A descriptor of a memory region statically defined in the TLB /// /// These maps are returned by ppc405_mmu_map(), and can be used later /// to unmap the region with ppc405_mmu_unmap(). They can also be used to /// control what gets printed by ppc405_mmu_report(). typedef uint64_t Ppc405MmuMap; /// TLBIA #define tlbia() asm volatile ("tlbia" : : : "memory") /// TLBWEHI #define tlbwehi(entry, tlbhi) \ asm volatile ("tlbwehi %0, %1" : : "r" (tlbhi), "r" (entry) : "memory") /// TLBWELO #define tlbwelo(entry, tlblo) \ asm volatile ("tlbwelo %0, %1" : : "r" (tlblo), "r" (entry) : "memory") /// TLBREHI #define tlbrehi(entry) \ ({ \ uint32_t __tlbhi; \ asm volatile ("tlbrehi %0, %1" : "=r" (__tlbhi) : "r" (entry)); \ __tlbhi;}) /// TLBRELO #define tlbrelo(entry) \ ({ \ uint32_t __tlblo; \ asm volatile ("tlbrelo %0, %1" : "=r" (__tlblo) : "r" (entry)); \ __tlblo;}) /// TLBSX /// /// Returns 1 if the address is mapped, else 0. If positive the integer /// pointed to by \a entry is updated with the TLB index of the matching /// entry, otherwise the return value is undefined. #define tlbsx(address, entry) \ ({ \ uint32_t __cr, __entry; \ asm volatile ("tlbsx. %0, 0, %2; mfcr %1" : \ "=r" (__entry), "=r" (__cr) : "r" (address)); \ *(entry) = __entry; \ ((__cr & CR_EQ(0)) != 0);}) int ppc405_mmu_reset(void); int ppc405_mmu_map(SsxAddress effective_address, SsxAddress real_address, size_t size, int tlbhi_flags, int tlblo_flags, Ppc405MmuMap* map); int ppc405_mmu_unmap(Ppc405MmuMap* map); void ppc405_mmu_start(void); void ppc405_mmu_report(FILE* stream, Ppc405MmuMap* map); #endif /* __ASSEMBLER__ */ #endif /* __PPC405_MMU_H__ */ <|start_filename|>src/lib/occlib/ipc_structs.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/occlib/ipc_structs.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __IPC_STRUCTS_H__ #define __IPC_STRUCTS_H__ /// \file ipc_structs.h /// \brief Common header for Interprocessor Communication structures in the /// OCC complex /// #include "kernel.h" //kernel wrapper macros #include "occhw_common.h" #include "ipc_macros.h" #ifndef IPC_CBUF_SIZE #define IPC_CBUF_SIZE 8 //number of messages must be a power of 2 #endif //the maximum number of multi-target functions (common functions) //This can be overriden in a global header that's included by all occ images //so that it is the same across all processors. #ifndef IPC_MT_MAX_FUNCTIONS #define IPC_MT_MAX_FUNCTIONS 8 #endif //the maximum number of single-target functions (processor-specific functions) //This can be overridden in a local header file and does not need to be the //same across all processors. #ifndef IPC_ST_MAX_FUNCTIONS #define IPC_ST_MAX_FUNCTIONS 16 #endif /// IPC return codes #define IPC_RC_SUCCESS 0 #define IPC_RC_CMD_FAILED 0x00472000 #define IPC_RC_BUFFER_FULL 0x00472001 #define IPC_RC_SELF_BLOCKED 0x00472002 #define IPC_RC_TARGET_BLOCKED 0x00472003 #define IPC_RC_MSG_ACTIVE 0x00472004 #define IPC_RC_INVALID_FUNC_ID 0x00472005 #define IPC_RC_CMD_NOT_SUPPORTED 0x00472006 #define IPC_RC_INVALID_TARGET_ID 0x00472007 #define IPC_RC_INVALID_ARG 0x00472008 #define IPC_RC_MSG_NOT_ACTIVE 0x00472009 #define IPC_RC_NO_MSG 0x0047200a #define IPC_RC_TIMEOUT 0x0047200b /// IPC Message Flags #define IPC_FLAG_MT 0x00000100 #define IPC_FLAG_RESPONSE 0x00000200 #define IPC_FLAG_VALID 0x00000400 #define IPC_FLAG_ACTIVE 0x00000800 // Function ID field masks #define IPC_TARGET_MASK 0xff000000 #define IPC_SENDER_MASK 0x00ff0000 #define IPC_FLAGS_MASK 0x0000ff00 #define IPC_INDEX_MASK 0x000000ff #define IPC_TARGET_SHIFT 24 #define IPC_CBUF_COUNT_BYTES 1 #define IPC_CBUF_COUNT_BITS 8 #ifndef __ASSEMBLER__ // If an occ application does not wish to use IPC then it should not // define the GLOBAL_CFG_USE_IPC macro. This allows IPC to compile // without errors. #ifdef GLOBAL_CFG_USE_IPC #include "ipc_func_ids.h" #else IPC_FUNCIDS_TABLE_START IPC_FUNCIDS_MT_START IPC_FUNCIDS_MT_END IPC_FUNCIDS_ST_START(OCCHW_INST_ID_GPE0) IPC_FUNCIDS_ST_END(OCCHW_INST_ID_GPE0) IPC_FUNCIDS_ST_START(OCCHW_INST_ID_GPE1) IPC_FUNCIDS_ST_END(OCCHW_INST_ID_GPE1) IPC_FUNCIDS_ST_START(OCCHW_INST_ID_GPE2) IPC_FUNCIDS_ST_END(OCCHW_INST_ID_GPE2) IPC_FUNCIDS_ST_START(OCCHW_INST_ID_GPE3) IPC_FUNCIDS_ST_END(OCCHW_INST_ID_GPE3) IPC_FUNCIDS_ST_START(OCCHW_INST_ID_PPC) IPC_FUNCIDS_ST_END(OCCHW_INST_ID_PPC) IPC_FUNCIDS_TABLE_END #endif /*GLOBAL_CFG_USE_IPC*/ //Statically check that the function tables are large enough KERN_STATIC_ASSERT(IPC_MT_NUM_FUNCIDS <= IPC_MT_MAX_FUNCTIONS); KERN_STATIC_ASSERT(IPC_ST_NUM_FUNCIDS <= IPC_ST_MAX_FUNCTIONS); #ifdef __SSX__ extern KERN_DEQUE G_ipc_deferred_queue; #endif struct ipc_msg; typedef struct ipc_msg ipc_msg_t; typedef union { uint64_t counts64; uint8_t counts8[sizeof(uint64_t) / IPC_CBUF_COUNT_BYTES]; } ipc_counts_t; /// Circular buffer read and write counts are grouped together by target_id /// so that an interrupt hander can quickly tell which buffer requires /// service. Each counter is 1 byte. /// /// Note: index 0 (or most significant byte) is for GPE0 typedef struct { ipc_counts_t reads; ipc_counts_t writes; } ipc_rwcounts_t; typedef struct { ipc_rwcounts_t counts; ipc_msg_t* cbufs[OCCHW_MAX_INSTANCES][IPC_CBUF_SIZE]; uint8_t pad[16]; } ipc_target_t; //size is 6 x 32 = 192 bytes /// All of the shared data for IPC is contained in this structure typedef struct { ipc_target_t targets[OCCHW_MAX_INSTANCES]; //880 bytes } ipc_shared_data_t; //prototype for ipc handlers and callback functions typedef void (*ipc_msg_handler_t)(ipc_msg_t*, void*); //function table entry typedef struct { ipc_msg_handler_t handler; void* arg; } ipc_func_table_entry_t; extern ipc_func_table_entry_t G_ipc_mt_handlers[IPC_MT_MAX_FUNCTIONS]; extern ipc_func_table_entry_t G_ipc_st_handlers[IPC_ST_MAX_FUNCTIONS]; typedef union { struct { uint32_t target_id: 8; uint32_t sender_id: 8; uint32_t reserved: 4; uint32_t active_flag: 1; uint32_t valid_flag: 1; uint32_t response_flag: 1; uint32_t multi_target_flag: 1; uint32_t table_index: 8; }; uint32_t word32; } ipc_func_id_t; #define IPC_MSG_DEQUEUE_SZ 8 //expected size of a deque structure struct ipc_msg { // but this file is shared by both, so use a void* type // instead. union { KERN_DEQUE node; uint8_t pad[IPC_MSG_DEQUEUE_SZ]; }; //function ID of the function that the sender wants executed volatile ipc_func_id_t func_id; //The IPC return code volatile uint32_t ipc_rc; //function to call if this is a response message ipc_msg_handler_t resp_callback; //Argument passed into the callback function void* callback_arg; uint32_t begin_time; //!< Send start time uint32_t end_time; //!< Response received time }; //Do a static check on the size of KERN_DEQUE. IPC_MSG_DEQUE_SZ must be <= sizeof(KERN_DEQUE). //If the compiler fails here then you probably need to update the value of IPC_MSG_DEQUEUE_SZ. //NOTE: this is needed because ipc_msg_t is used in both PK and SSX environments and there is // no guarantee that the size of a deque will be the same in both environments. KERN_STATIC_ASSERT(sizeof(KERN_DEQUE) <= IPC_MSG_DEQUEUE_SZ); //A message queue that threads can block on while they wait for new messages. typedef struct { KERN_DEQUE msg_head; KERN_SEMAPHORE msg_sem; //posted whenever a new message is queued } ipc_msgq_t; #endif /*__ASSEMBLER__*/ #endif /* __IPC_STRUCTS_H__ */ <|start_filename|>src/lib/ppc405lib/assert.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/assert.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file assert.c /// \brief Implementation of library routines implied by <assert.h> #include "ssx.h" #include "ssx_io.h" #include "libssx.h" /// The __assert_fail() function is used to implement the assert() interface /// of ISO POSIX (2003). The __assert_fail() function prints the given \a /// file filename, \a line line number, \a function function name and a /// message on the standard error stream then causes a kernel panic. If there /// is no standard error stream then the error message is printed on the \a /// ssxout (printk()) stream. /// /// If function is NULL, __assert_fail() omits information about the /// function. The aguments \a assertion, \a file, and \a line must be /// non-NULL. void __assert_fail(const char *assertion, const char *file, unsigned line, const char *function) { FILE *stream; stream = stderr; if (stream == 0) { stream = ssxout; } fprintf(stream, "%s:%u:%s%s Assertion '%s' failed\n", file, line, function ? function : "", function ? ":" : "", assertion); SSX_PANIC(ASSERTION_FAILURE); } <|start_filename|>src/occ_405/thread/thread.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/thread/thread.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _THREAD_H #define _THREAD_H #include <occ_common.h> #include "ssx.h" // Thread priorities for Thread creation. typedef enum { THREAD_PRIORITY_0, // Reserved for high priority THREAD_PRIORITY_1, // Reserved for high priority THREAD_PRIORITY_2, THREAD_PRIORITY_3, THREAD_PRIORITY_4, THREAD_PRIORITY_5, THREAD_PRIORITY_6, THREAD_PRIORITY_7, THREAD_PRIORITY_8, }THREAD_PRIORITY; // NOTE: Stack sizes are defined by entity // - Non-Critical Stack used by non-critical interrupt handlers, including timer callbacks // - Critical Stack used for critical interrupts // - Stacks for each thread #define NONCRITICAL_STACK_SIZE 8192 // 8kB #define CRITICAL_STACK_SIZE 4096 // 4kB #define THREAD_STACK_SIZE 4096 // 4kB extern uint8_t main_thread_stack[THREAD_STACK_SIZE]; extern uint8_t Cmd_hndl_thread_stack[THREAD_STACK_SIZE]; /*----------------------------------------------------------*/ /* SsxThread Declaration */ /*----------------------------------------------------------*/ // Our idle thread. See main_thread_routine extern SsxThread Main_thread; // Command handler thread extern SsxThread Cmd_Hndl_thread; // Application manager thread extern SsxThread Dcom_thread; void Main_thread_routine(void *private); void Cmd_Hndl_thread_routine(void *arg); void Dcom_thread_routine(void *arg); #endif //_THREAD_H <|start_filename|>src/lib/common/memcpy.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/common/memcpy.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file memcpy.c /// \brief The memcpy() function #include "kernel.h" /// The memcpy() function copies \a n bytes from memory area \a src to memory /// area \a dest. The memory areas should not overlap. Use memmove(3) if the /// memory areas do overlap. The memcpy() function returns a pointer to dest. // This implementation should work well for both 32-bit and 64-bit machines, // assuming they can handle unaligned accesses. The implementation assumes that // it is better to avoid the loop setup overhead by a test and branch for // cases where loops can be bypassed. //void * //memcpy(void *dest, const void *src, size_t n) //{ // while(n--) { // *dest++ = *src++; // } // // return s; //} void * memcpy(void *dest, const void *src, size_t n) { uint8_t *d8, *s8; uint64_t *d64, *s64; size_t doublewords, octawords; // First copy memory 32 bytes at a time. d64 = (uint64_t *)dest; s64 = (uint64_t *)src; octawords = n / 32; if (octawords) { n -= octawords * 32; while(octawords--) { *d64++ = *s64++; *d64++ = *s64++; *d64++ = *s64++; *d64++ = *s64++; } } // Now set memory 8 bytes at a time. This might actually be better done // explicitly rather than as a loop because the maximum loop count is 3 // here. doublewords = n / 8; if (doublewords) { n -= doublewords * 8; while (doublewords--) { *d64++ = *s64++; } } // Finally finish any remaining memory bytewise if (n) { d8 = (uint8_t *)d64; s8 = (uint8_t *)s64; while (n--) { *d8++ = *s8++; } } return dest; } <|start_filename|>src/occ_405/mode.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/mode.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <occ_common.h> #include <common_types.h> #include "ssx_io.h" #include "trac.h" #include "rtls.h" #include "state.h" #include "occ_service_codes.h" #include "amec_freq.h" #include "amec_part.h" #include "amec_data.h" #include "amec_sys.h" errlHndl_t SMGR_mode_transition_to_nominal(); errlHndl_t SMGR_mode_transition_to_powersave(); errlHndl_t SMGR_mode_transition_to_dynpowersave(); errlHndl_t SMGR_mode_transition_to_dynpowersave_fp(); errlHndl_t SMGR_mode_transition_to_turbo(); errlHndl_t SMGR_mode_transition_to_ffo(); errlHndl_t SMGR_mode_transition_to_fmf(); errlHndl_t SMGR_mode_transition_to_nom_perf(); errlHndl_t SMGR_mode_transition_to_max_perf(); // Mode that OCC is currently in OCC_MODE G_occ_internal_mode = OCC_MODE_NOCHANGE; // Mode that OCC is requesting that TMGT put OCC into OCC_MODE G_occ_internal_req_mode = OCC_MODE_NOCHANGE; // Mode that TMGT is requesting OCC go to OCC_MODE G_occ_external_req_mode = OCC_MODE_NOCHANGE; // Mode that TMGT is requesting OCC go to in KVM OCC_MODE G_occ_external_req_mode_kvm = OCC_MODE_NOCHANGE; // Indicates if we are currently in a mode transition bool G_mode_transition_occuring = FALSE; // Mode that OCC Master is in OCC_MODE G_occ_master_mode = OCC_MODE_NOCHANGE; // Semaphore to allow mode change to be called from multiple threads SsxSemaphore G_smgrModeChangeSem; // Table that indicates which functions should be run for a given mode // transition. const smgr_state_trans_t G_smgr_mode_trans[] = { /* Current Mode New Mode Transition Function */ {OCC_MODE_ALL, OCC_MODE_NOMINAL, &SMGR_mode_transition_to_nominal}, {OCC_MODE_ALL, OCC_MODE_PWRSAVE, &SMGR_mode_transition_to_powersave}, {OCC_MODE_ALL, OCC_MODE_DYN_POWER_SAVE, &SMGR_mode_transition_to_dynpowersave}, {OCC_MODE_ALL, OCC_MODE_DYN_POWER_SAVE_FP, &SMGR_mode_transition_to_dynpowersave_fp}, {OCC_MODE_ALL, OCC_MODE_TURBO, &SMGR_mode_transition_to_turbo}, {OCC_MODE_ALL, OCC_MODE_FFO, &SMGR_mode_transition_to_ffo}, {OCC_MODE_ALL, OCC_MODE_FMF, &SMGR_mode_transition_to_fmf}, {OCC_MODE_ALL, OCC_MODE_NOM_PERFORMANCE, &SMGR_mode_transition_to_nom_perf}, {OCC_MODE_ALL, OCC_MODE_MAX_PERFORMANCE, &SMGR_mode_transition_to_max_perf}, }; const uint8_t G_smgr_mode_trans_count = sizeof(G_smgr_mode_trans)/sizeof(smgr_state_trans_t); // Function Specification // // Name: SMGR_is_mode_transitioning // // Description: // // End Function Specification inline bool SMGR_is_mode_transitioning(void) { return G_mode_transition_occuring; } // Function Specification // // Name: SMGR_get_mode // // Description: // // End Function Specification inline OCC_MODE SMGR_get_mode(void) { return G_occ_internal_mode; } // Function Specification // // Name: SMGR_set_mode // // Description: // // End Function Specification errlHndl_t SMGR_set_mode( const OCC_MODE i_mode ) { errlHndl_t l_errlHndl = NULL; int jj=0; OCC_MODE l_mode = i_mode; do { // Get lock for critical section if(ssx_semaphore_pend(&G_smgrModeChangeSem,SSX_WAIT_FOREVER)) { /* @ * @errortype * @moduleid MAIN_MODE_TRANSITION_MID * @reasoncode SSX_GENERIC_FAILURE * @userdata1 none * @userdata4 ERC_RUNNING_SEM_PENDING_FAILURE * @devdesc SSX semaphore related failure */ l_errlHndl = createErrl(MAIN_MODE_TRANSITION_MID, //modId SSX_GENERIC_FAILURE, //reasoncode ERC_RUNNING_SEM_PENDING_FAILURE,//Extended reason code ERRL_SEV_UNRECOVERABLE, //Severity NULL, //Trace Buf DEFAULT_TRACE_SIZE, //Trace Size 0, //userdata1 0); //userdata2 // Callout firmware addCalloutToErrl(l_errlHndl, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_FIRMWARE, ERRL_CALLOUT_PRIORITY_HIGH); break; } //Check to see if we need to make a change if(l_mode == OCC_MODE_NOCHANGE) { break; } // OPAL only accepts DPS-FE mode. In case OCC gets other modes, it should accept the request // and keep reporting back that it is in that mode. However, internally we should not // initiate any mode transition, i.e., OCC should remain internally in DPS-FE mode. if(G_sysConfigData.system_type.kvm) { G_occ_external_req_mode_kvm = l_mode; if (l_mode != OCC_MODE_DYN_POWER_SAVE) { TRAC_ERR("OPAL only accepts DPS-FE mode(6) but requested mode is : %d", l_mode); l_mode = OCC_MODE_DYN_POWER_SAVE; } } // Change Mode via Transition Function do { // Loop through mode transition table, and find the state // transition function that matches the transition we need to do. for(jj=0; jj<G_smgr_mode_trans_count; jj++) { if( ((G_smgr_mode_trans[jj].old_state == G_occ_internal_mode) || (G_smgr_mode_trans[jj].old_state == OCC_MODE_ALL) ) && (G_smgr_mode_trans[jj].new_state == l_mode) ) { // We found the transtion that matches, now run the function // that is associated with that state transition. if(NULL != G_smgr_mode_trans[jj].trans_func_ptr) { // Signal that we are now in a mode transition G_mode_transition_occuring = TRUE; // Run transition function l_errlHndl = (G_smgr_mode_trans[jj].trans_func_ptr)(); // Signal that we are done with the transition G_mode_transition_occuring = FALSE; break; } } } // Check if we hit the end of the table without finding a valid // mode transition. If we did, log an internal error. if(G_smgr_mode_trans_count == jj) { TRAC_ERR("No transition (or NULL) found for the mode change\n"); /* @ * @errortype * @moduleid MAIN_MODE_TRANSITION_MID * @reasoncode INTERNAL_FAILURE * @userdata1 G_occ_internal_mode * @userdata2 l_mode * @userdata4 ERC_SMGR_NO_VALID_MODE_TRANSITION_CALL * @devdesc no valid state transition routine found */ l_errlHndl = createErrl(MAIN_MODE_TRANSITION_MID, //modId INTERNAL_FAILURE, //reasoncode ERC_SMGR_NO_VALID_MODE_TRANSITION_CALL, //Extended reason code ERRL_SEV_UNRECOVERABLE, //Severity NULL, //Trace Buf DEFAULT_TRACE_SIZE, //Trace Size G_occ_internal_mode, //userdata1 l_mode); //userdata2 addCalloutToErrl(l_errlHndl, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_FIRMWARE, ERRL_CALLOUT_PRIORITY_HIGH); break; } // Update the power mode for all core groups that are following system mode AMEC_part_update_sysmode_policy(CURRENT_MODE()); } while(0); if(l_errlHndl) { // Punt !!! :-) break; } // Load correct thermal thresholds based on the current mode l_errlHndl = AMEC_data_write_thrm_thresholds(CURRENT_MODE()); }while(0); // Unlock critical section ssx_semaphore_post(&G_smgrModeChangeSem); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_nominal // // Description: // // End Function Specification errlHndl_t SMGR_mode_transition_to_nominal() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to Nominal Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_NOMINAL); CURRENT_MODE() = OCC_MODE_NOMINAL; // WOF is disabled in nominal mode set_clear_wof_disabled( SET, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to Nominal Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_powersave // // Description: // // End Function Specification errlHndl_t SMGR_mode_transition_to_powersave() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to PowerSave Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_PWRSAVE); CURRENT_MODE() = OCC_MODE_PWRSAVE; // WOF is disabled in SPS mode set_clear_wof_disabled( SET, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to PowerSave Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_dynpowersave // // Description: // // End Function Specification errlHndl_t SMGR_mode_transition_to_dynpowersave() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to Dynamic PowerSave-Favor Energy Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_DYN_POWER_SAVE); CURRENT_MODE() = OCC_MODE_DYN_POWER_SAVE; // WOF is enabled in DPS, clear the mode bit set_clear_wof_disabled( CLEAR, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to Dynamic PowerSave-Favor Energy Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_dynpowersave_fp // // Description: // // End Function Specification errlHndl_t SMGR_mode_transition_to_dynpowersave_fp() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to Dynamic PowerSave-Favor Performance Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_DYN_POWER_SAVE_FP); CURRENT_MODE() = OCC_MODE_DYN_POWER_SAVE_FP; // WOF is enabled in DPS-FP, clear the mode bit set_clear_wof_disabled( CLEAR, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to Dynamic PowerSave-Favor Performance Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_turbo // // Description: // // End Function Specification errlHndl_t SMGR_mode_transition_to_turbo() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to Turbo Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_TURBO); CURRENT_MODE() = OCC_MODE_TURBO; // WOF is disabled in turbo mode set_clear_wof_disabled( SET, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to Turbo Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_ffo // // Description: // // End Function Specification errlHndl_t SMGR_mode_transition_to_ffo() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to FFO Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_FFO); CURRENT_MODE() = OCC_MODE_FFO; // WOF is disabled in FFO set_clear_wof_disabled( SET, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to FFO Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_fmf // // Description: Transition to Fixed Maximum Frequency mode // // End Function Specification errlHndl_t SMGR_mode_transition_to_fmf() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to FMF Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_FMF); CURRENT_MODE() = OCC_MODE_FMF; // WOF is enabled in FMF, clear the mode bit set_clear_wof_disabled( CLEAR, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to FMF Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_nom_perf // // Description: Transition to nominal performance mode // // End Function Specification errlHndl_t SMGR_mode_transition_to_nom_perf() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to Nominal Performance Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_NOM_PERFORMANCE); CURRENT_MODE() = OCC_MODE_NOM_PERFORMANCE; // WOF is enabled in nominal performance mode, clear the mode bit set_clear_wof_disabled( CLEAR, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to Nominal Performance Transition Completed"); return l_errlHndl; } // Function Specification // // Name: SMGR_mode_transition_to_max_perf // // Description: Transition to Maximum Performance mode // // End Function Specification errlHndl_t SMGR_mode_transition_to_max_perf() { errlHndl_t l_errlHndl = NULL; TRAC_IMP("SMGR: Mode to Maximum Performance Transition Started"); // Set Freq Mode for AMEC to use l_errlHndl = amec_set_freq_range(OCC_MODE_MAX_PERFORMANCE); CURRENT_MODE() = OCC_MODE_MAX_PERFORMANCE; // WOF is enabled in max performance mode, clear the mode bit set_clear_wof_disabled( CLEAR, WOF_RC_MODE_NO_SUPPORT_MASK, ERC_WOF_MODE_NO_SUPPORT_MASK ); TRAC_IMP("SMGR: Mode to Maximum Performance Transition Completed"); return l_errlHndl; } <|start_filename|>src/occ_405/amec/amec_oversub.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_oversub.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_OVERSUB_H #define _AMEC_OVERSUB_H /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include <occ_sys_config.h> // Added for sys config access #include <dcom.h> /*----------------------------------------------------------------------------*/ /* Constants */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Globals */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Defines */ /*----------------------------------------------------------------------------*/ #define AMEC_INTF_GET_OVERSUBSCRIPTION() \ (g_amec->oversub_status.oversubPinLive || G_dcom_slv_inbox_rx.emulate_oversub) #define AMEC_INTF_GET_OVERSUBSCRIPTION_EMULATION() g_amec->oversub_status.oversubPinMnfg /*----------------------------------------------------------------------------*/ /* Typedef / Enum */ /*----------------------------------------------------------------------------*/ typedef enum oversub_reason { PENDING_OR_INVALID = 0x00, FANS_FULL_SPEED = 0x01, FAN_ERRROR = 0x02, FAN_WARNING = 0x03, INDETERMINATE = 0xFF }oversub_reason_t; typedef struct oversub_status { // Way to emulate oversub for MNFG or Developers uint32_t oversubPinMnfg : 1; // Live Status of oversub Pin uint32_t oversubPinLive : 1; // Used for SRC logging of performance loss, // need to have countdown b/c we don't get // APSS gpio signals as quick as we get // oversub. uint8_t oversubReasonLatchCount; oversub_reason_t oversubReason; // For debug, tracks time oversub last went inactive SsxTimebase oversubInactiveTime; // For debug, tracks time oversub last went active SsxTimebase oversubActiveTime; }oversub_status_t; /*----------------------------------------------------------------------------*/ /* Function Prototypes */ /*----------------------------------------------------------------------------*/ void amec_oversub_isr(void); void amec_oversub_check(void); bool apss_gpio_get(uint8_t i_pin_number, uint8_t *o_pin_value); #endif //_AMEC_OVERSUB_H <|start_filename|>src/occ_405/sensor/sensor_inband_cmd.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor_inband_cmd.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _SENSOR_INBAND_CMD_H #define _SENSOR_INBAND_CMD_H /** * @file sensor_inband_cmd.h * * This file declares the functions and global variables for supporting the inband * command protocol defined in the OCC Firmware Interface spec * */ //****************************************************************************** // Defines/Structs/Globals //****************************************************************************** // States of inband OCC command processing typedef enum { INBAND_OCC_CMD_NONE = 0x00, // No inband command in process INBAND_OCC_CMD_CHECK_FOR_CMD = 0x01, // Check for cmd when BCE read finishes INBAND_OCC_CMD_START = 0x02, // Start processing the command INBAND_OCC_CMD_RSP_READY = 0x03, // Response ready INBAND_OCC_CMD_RSP_INT = 0x04, // Send Response Interrupt INBAND_OCC_INVALID_BCE_CALLBACK = 0x05, // BCE callback called with invalid OCC cmd state } INBAND_OCC_CMD_STATE; // Current state of inband OCC command processing extern volatile uint8_t G_inband_occ_cmd_state; // Last state saved for error handling extern volatile uint8_t G_inband_occ_bce_saved_state; #define MAX_TICS_INBAND_BCE_CALLBACK_WAIT 0x03 #define IN_BAND_CMD_READY_MASK 0x80 #define IN_BAND_RSP_IN_PROGRESS_MASK 0x02 #define IN_BAND_RSP_READY_MASK 0x01 typedef struct __attribute__ ((packed)) { uint8_t flags; uint8_t seq; uint8_t cmd_type; uint8_t reserved_rc; // as a command reserved, as a response RC uint8_t data_length[2]; } inband_occ_cmd_header_t; // Data Size is Block Copy Engine dependent, 128 min to 4kB max #define INBAND_CMD_MIN_BCE_BUF_SIZE 128 #define INBAND_CMD_MAX_BCE_BUF_SIZE 4096 #define INBAND_MAX_DATA_LENGTH INBAND_CMD_MAX_BCE_BUF_SIZE - sizeof(inband_occ_cmd_header_t) #define INBAND_MIN_DATA_LENGTH INBAND_CMD_MIN_BCE_BUF_SIZE - sizeof(inband_occ_cmd_header_t) typedef struct __attribute__ ((packed)) { inband_occ_cmd_header_t header; // Data bytes uint8_t data[INBAND_MIN_DATA_LENGTH]; }inband_min_cmd_t; typedef struct __attribute__ ((packed)) { inband_occ_cmd_header_t header; // Data bytes uint8_t data[INBAND_MAX_DATA_LENGTH]; }inband_max_cmd_t; //****************************************************************************** // Function Prototypes //****************************************************************************** /** * Check for a command from the inband command/response interface * * There are inband commands to select sensors to write to main memory and * clear sensors min/max by user * * This function is called from amec_slv_common_tasks_post() */ void inband_command_check(void); /** * Handle a command from the inband command/response interface * * This function is called from amec_slv_substate_6_x */ void inband_command_handler(void); #endif // _SENSOR_INBAND_CMD_H <|start_filename|>src/occ_405/proc/proc_pstate.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/proc/proc_pstate.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef PROC_PSTATE_H #define PROC_PSTATE_H #include "ssx.h" #include "cmdh_service_codes.h" #include "errl.h" #include "trac.h" #include "rtls.h" #include "occ_common.h" #include "p9_pstates_common.h" #include "state.h" #include "cmdh_fsp_cmds.h" #include "cmdh_dbug_cmd.h" //#include "gpsm.h" //#include "pstates.h" // The pstate associated with highest possible frequency // is always 0 in POWER9. #define PMAX 0 typedef enum { PSTATES_IN_TRANSITION = -1, PSTATES_DISABLED = 0, PSTATES_ENABLED = 1, PSTATES_FAILED = 2, } pstateStatus; typedef enum { OPAL_STATIC = 0, OPAL_DYNAMIC = 1, } opalDataType; typedef struct __attribute__ ((packed)) { uint8_t valid; uint8_t version; uint8_t occ_role; uint8_t pmin; uint8_t pnominal; uint8_t pturbo; uint8_t puturbo; uint8_t reserved; } opal_config_t; typedef struct __attribute__ ((packed)) { int8_t pstate; uint8_t flag; uint16_t reserved; uint32_t freq_khz; } opal_pstate_data_t; typedef struct __attribute__ ((packed)) { uint8_t occ_state; uint8_t dynamic_major_version; uint8_t dynamic_minor_version; uint8_t gpus_present; uint8_t reserved[1]; uint8_t proc_throt_status; uint8_t mem_throt_status; uint8_t quick_power_drop; uint8_t power_shift_ratio; uint8_t power_cap_type; uint16_t min_power_cap; uint16_t max_power_cap; uint16_t current_power_cap; uint16_t soft_min_power_cap; } opal_dynamic_t; // This size must be a multiple of 128 typedef struct __attribute__ ((packed)) { opal_dynamic_t dynamic; // Dynamic OPAL parameters: 18B uint8_t pad[110]; // Reserved dynamic space: 110B } opal_dynamic_table_t __attribute__ ((aligned (128))); #define PSTATE_ENTRIES 256 // number of generated PSTATES entries in OPAL table #define DYNAMIC_MINOR_V_GPU_PRESENCE 1 // OPAL Dynamic minor version for GPU support // This size must be a multiple of 128 typedef struct __attribute__ ((packed)) { opal_config_t config; // Static OPAL config parameters: 8B uint8_t reserved[16]; // Reserved static space: 16B opal_pstate_data_t pstates[PSTATE_ENTRIES]; // Generated Pstates Table: 2048B uint8_t max_pstate[24]; // Maximum Pstate with N active cores is max_pstate[N-1]: 24B uint8_t pad[80]; // Padding in reserved static space: 80B } opal_static_table_t __attribute__ ((aligned (128))); extern uint32_t G_mhz_per_pstate; // Per quad pstate extern uint8_t G_desired_pstate[MAXIMUM_QUADS]; extern opal_dynamic_table_t G_opal_dynamic_table; extern opal_static_table_t G_opal_static_table; // States for updating opal data in main memory typedef enum { OPAL_TABLE_UPDATE_IDLE = 0x00, // No dynmaic table update in process OPAL_TABLE_UPDATE_DYNAMIC_COPY = 0x01, // BCE scheduled to copy dynamic date to main memory OPAL_TABLE_UPDATE_NOTIFY_HOST = 0x02, // BCE copy finished notify host OPAL_TABLE_UPDATE_BCE_FAIL = 0x03, // BCE failed, retry OPAL_TABLE_UPDATE_CRITICAL_ERROR = 0x04, // Critical BCE error, stop trying to update dynamic data } OPAL_TABLE_UPDATE_STATE; extern volatile uint8_t G_opal_table_update_state; // Helper function to translate from Frequency to nearest Pstate Pstate proc_freq2pstate(uint32_t i_freq_mhz); // Helper function to translate from Pstate to nearest Frequency uint32_t proc_pstate2freq(Pstate i_pstate); // Helper function to determine if we are in HW Pstate mode inline bool proc_is_hwpstate_enabled(void); // Copy pstate data to opal table void populate_opal_dynamic_data(void); // Copy all opal static data to opal table void populate_opal_static_data(void); // Copy pstates sections of opal static data to opal table void populate_opal_static_pstates_data(void); // Copy config section of opal static data to opal table void populate_opal_static_config_data(void); // Copy opal static/dynamic table to mainstore memory at OPAL_OFFSET_HOMER void populate_opal_tbl_to_mem(opalDataType opal_data_type); // Check if opal table needs update void check_for_opal_updates(void); // update dynamic opal data in SRAM & main memory void update_dynamic_opal_data (void); void proc_pstate_kvm_setup(void); #endif <|start_filename|>src/ssx/ppc405/ppc405_dcr.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_dcr.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_DCR_H__ #define __PPC405_DCR_H__ /// \file ppc405_dcr.h /// \brief Everything related to PPC405-specific DCRs /// /// DCRs are chip-specific. This file only defines DCR access methods; DCR /// numbers will be defined by chip-specific headers. /// Move From DCR /// /// Note that \a dcrn must be a compile-time constant. #define mfdcr(dcrn) \ ({uint32_t __value; \ asm volatile ("mfdcr %0, %1" : "=r" (__value) : "i" (dcrn)); \ __value;}) /// Move to DCR /// /// Note that \a dcrn must be a compile-time constant. #define mtdcr(dcrn, value) \ ({uint32_t __value = (value); \ asm volatile ("mtdcr %0, %1" : : "i" (dcrn), "r" (__value)); \ }) /// Read-Modify-Write a DCR with OR (Set DCR bits) /// /// Note that \a dcrn must be a compile-time constant. This operation is only /// guaranteed atomic in a critical section. #define or_dcr(dcrn, x) \ mtdcr(dcrn, mfdcr(dcrn) | (x)) /// Read-Modify-Write a DCR with AND complement (Clear DCR bits) /// /// Note that \a dcrn must be a compile-time constant. This operation is only /// guaranteed atomic in a critical section. #define andc_dcr(dcrn, x) \ mtdcr(dcrn, mfdcr(dcrn) & ~(x)) #endif /* __PPC405_DCR_H__ */ <|start_filename|>src/occ_gpe0/firdata/lpc.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/lpc.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _LPC_H #define _LPC_H #include <native.h> /** * @enum LPC::TransType * @brief LPC Transaction Types */ typedef enum { LPC_TRANS_IO = 0, /* LPC IO Space */ LPC_TRANS_FW = 1, /* LPC Firmware Space */ } LpcTransType; errorHndl_t lpc_read( LpcTransType i_type, uint32_t i_addr, uint8_t* o_data, uint32_t i_size ); errorHndl_t lpc_write( LpcTransType i_type, uint32_t i_addr, uint8_t* i_data, uint32_t i_size ); uint32_t checkAddr(LpcTransType i_type, uint32_t i_addr); #endif <|start_filename|>src/occ_405/dcom/dcom_service_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/dcom/dcom_service_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _DCOM_SERVICE_CODES_H_ #define _DCOM_SERVICE_CODES_H_ #include <comp_ids.h> enum dcomModuleId { DCOM_MID_INIT_ROLES = DCOM_COMP_ID | 0x00, DCOM_MID_TASK_RX_SLV_INBOX = DCOM_COMP_ID | 0x01, DCOM_MID_TASK_TX_SLV_INBOX = DCOM_COMP_ID | 0x02, DCOM_MID_INIT_PBAX_QUEUES = DCOM_COMP_ID | 0x03, DCOM_MID_TASK_RX_SLV_OUTBOX = DCOM_COMP_ID | 0x04, DCOM_MID_TASK_TX_SLV_OUTBOX = DCOM_COMP_ID | 0x05, DCOM_MID_SLV_OUTBOX_TX_DOORBELL = DCOM_COMP_ID | 0x06, DCOM_MID_TASK_WAIT_FOR_MASTER = DCOM_COMP_ID | 0x07, DCOM_MID_ERROR_CHECK = DCOM_COMP_ID | 0x08, DCOM_MID_WAIT_FOR_MASTER = DCOM_COMP_ID | 0x09, DCOM_MID_PBAX_ERROR_HANDLER = DCOM_COMP_ID | 0x0A, DCOM_MID_BUILD_SLV_INBOX = DCOM_COMP_ID | 0x0B, }; #endif /* #ifndef _DCOM_SERVICE_CODES_H_ */ <|start_filename|>src/occ_405/amec/amec_smh.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_smh.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_SMH_H #define _AMEC_SMH_H //************************************************************************* // Includes //************************************************************************* #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include "amec_external.h" //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* #define AMEC_STATE(i_state) (i_state->state); #define AMEC_SUBSTATE(i_state) (i_state->substate); #define AMEC_SUB_SUBSTATE(i_state) (i_state->sub_substate); #define AMEC_STATE_NEXT(i_state) i_state->state++; i_state->state %= AMEC_SMH_STATES_PER_LVL; #define AMEC_SUBSTATE_NEXT(i_state) i_state->substate++; i_state->substate %= AMEC_SMH_STATES_PER_LVL; #define AMEC_SUB_SUBSTATE_NEXT(i_state) i_state->sub_substate++; i_state->sub_substate %= AMEC_SMH_STATES_PER_LVL; #define AMEC_INITIAL_STATE 0 // We cycle through all states twice per tick cycle (8 states, 16 ticks) #define AMEC_SMH_STATES_PER_LVL 8 // Number of uS in 1 RTL tick (250=250us) #define AMEC_US_PER_TICK MICS_PER_TICK // Number of uS in 1 full period of the AMEC State Machine #define AMEC_US_PER_SMH_PERIOD (AMEC_SMH_STATES_PER_LVL * MICS_PER_TICK) // Number of <AMEC_US_PER_SMH_PERIOD> that happen in 1 second #define AMEC_SMH_PERIODS_IN_1SEC (1000000 / AMEC_US_PER_SMH_PERIOD) // Number of times core data is processed. The AMEC SMH goes around twice per tick cycle. #define AMEC_CORE_COLLECTION_1SEC (AMEC_SMH_PERIODS_IN_1SEC / 2) //************************************************************************* // Structures //************************************************************************* // Each State table (including Substates) will take up 64 bytes // of SRAM space. typedef struct smh_tbl { void (*state)(); const struct smh_tbl * substate; } smh_tbl_t; typedef struct { uint8_t state; uint8_t substate; uint8_t sub_substate; } smh_state_t; typedef struct { void (*update_sensor)(int, uint32_t); } smh_state_timing_t; //************************************************************************* // Globals //************************************************************************* //************************************************************************* // Function Prototypes //************************************************************************* void amec_generic_smh(const smh_tbl_t * i_smh_tbl, smh_state_t * i_smh_state, smh_state_timing_t * i_smh_timing); #endif //_AMEC_SMH_H <|start_filename|>src/ssx/ssx/ssx_timer_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_timer_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_timer_init.c /// \brief SSX timer initialization /// /// The entry points in this file might only be used during initialization of /// the application. In this case the code space for these routines could be /// recovered and reused after initialization. #include "ssx.h" // Implementation of timer creation static int _ssx_timer_create(SsxTimer* timer, SsxTimerCallback callback, void* arg, int options) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((timer == 0), SSX_INVALID_TIMER_AT_CREATE); } ssx_deque_element_create((SsxDeque*)timer); timer->timeout = 0; timer->period = 0; timer->callback = callback; timer->arg = arg; timer->options = options; return SSX_OK; } /// Create (initialize) a preemptible timer. /// /// \param timer The SsxTimer to initialize. /// /// \param callback The timer callback /// /// \param arg Private data provided to the callback. /// /// Once created with ssx_timer_create() a timer can be scheduled with /// ssx_timer_schedule() or ssx_timer_schedule_absolute(), which queues the /// timer in the kernel time queue. Timers can be cancelled by a call of /// ssx_timer_cancel(). /// /// Timers created with ssx_timer_create() are always run as noncritical /// interrupt handlers with interrupt preemption enabled. Timer callbacks are /// free to enter critical sections of any priorioty if required, but must /// always exit with noncritical interrupts enabled. /// /// Caution: SSX has no way to know if an SsxTimer structure provided to /// ssx_timer_create() is safe to use as a timer, and will silently modify /// whatever memory is provided. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_TIMER_AT_CREATE The \a timer is a null (0) pointer. int ssx_timer_create(SsxTimer* timer, SsxTimerCallback callback, void* arg) { return _ssx_timer_create(timer, callback, arg, SSX_TIMER_CALLBACK_PREEMPTIBLE); } /// Create (initialize) a nonpreemptible timer. /// /// \param timer The SsxTimer to initialize. /// /// \param callback The timer callback /// /// \param arg Private data provided to the callback. /// /// Once created with ssx_timer_create_preemptible() a timer can be scheduled /// with ssx_timer_schedule() or ssx_timer_schedule_absolute(), which queues /// the timer in the kernel time queue. Timers can be cancelled by a call of /// ssx_timer_cancel(). /// /// Timers created with ssx_timer_create_nonpreemptible() are always run as /// noncritical interrupt handlers with interrupt preemption disabled. Timer /// callbacks are free to later enable preemption if desired, but must always /// exit with noncritical interrupts disabled. /// /// \note The use of ssx_timer_create_nonpreemptible() should be rare, and the /// timer callbacks should be short and sweet to avoid long interrupt /// latencies for other interrupts. This API was initially introduced for use /// by the SSX kernel itself when scheduling thread-timer callbacks to avoid /// potential race conditions with other interrupts that may modify thread /// state or the state of the time queue. Applications may also require this /// facility to guarantee a consistent state in the event that other /// interrupts may cancel the timer. /// /// Caution: SSX has no way to know if an SsxTimer structure provided to /// ssx_timer_create() is safe to use as a timer, and will silently modify /// whatever memory is provided. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_TIMER_AT_CREATE The \a timer is a null (0) pointer. int ssx_timer_create_nonpreemptible(SsxTimer* timer, SsxTimerCallback callback, void* arg) { return _ssx_timer_create(timer, callback, arg, 0); } <|start_filename|>src/occ_405/sensor/sensor_inband_cmd.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor_inband_cmd.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //****************************************************************************** // Includes //****************************************************************************** #include <cmdh_fsp_cmds.h> #include <sensor_inband_cmd.h> #include <homer.h> #include <occ_service_codes.h> #include <sensor_service_codes.h> #include <trac.h> #include <occhw_async.h> #include <common.h> //****************************************************************************** // Block Copy Engine (BCE) Defines/Globals //****************************************************************************** // Buffer in SRAM to copy larger commands cmd/rsp buffer from/to main memory using the BCE DMA_BUFFER(inband_max_cmd_t G_inband_cmd_max_data_bce_buff) = {{0}}; // Buffer in SRAM to copy smaller commands cmd/rsp buffer from/to main memory using the BCE DMA_BUFFER(inband_min_cmd_t G_inband_cmd_min_data_bce_buff) = {{0}}; // BCE request structure. Used by BCE functions to schedule copy request. BceRequest G_inband_cmd_bce_req; /** * Specifies whether the BCE request was scheduled. If false, the request * finished or has never been scheduled/initialized. */ bool G_inband_cmd_req_scheduled = false; // Number of tics passed waiting for BCE callback uint8_t G_bce_callback_wait = 0; volatile uint8_t G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; volatile uint8_t G_inband_occ_bce_saved_state = INBAND_OCC_CMD_NONE; //****************************************************************************** // Functions //****************************************************************************** /** * Logs an error caused by the Block Copy Engine. Does nothing if a BCE error * has already been logged. * * Note that the required error log comment containing tags like 'userdata4' and * 'devdesc' must be located by the call to this function. It is not located * inside this function because the value of those tags varies. * * @param i_modId Module ID * @param i_extReasonCode Extended reason code * @param i_userData1 Userdata1 value * @param i_userData2 Userdata2 value */ void inband_cmd_log_bce_error(uint16_t i_modId, uint16_t i_extReasonCode, uint32_t i_userData1, uint32_t i_userData2) { static bool L_error_logged = false; if (!L_error_logged) { // Create and commit error errlHndl_t l_errl = createErrl(i_modId, // Module ID INBAND_CMD_ERROR, // Reason code i_extReasonCode, // Extended reason code ERRL_SEV_INFORMATIONAL, // Severity NULL, // Trace Buffers DEFAULT_TRACE_SIZE, // Trace Size i_userData1, // Userdata1 i_userData2); // Userdata2 commitErrl(&l_errl); L_error_logged = true; } } /** * Returns whether the global BCE request struct is idle and ready for re-use. * Returns true immediately if the request was not scheduled. If the request * was scheduled, checks to see if it has finished. * * @param i_caller_mod_id Module ID of calling function in case an error occurs * @return True if BCE request is idle, false otherwise */ bool inband_cmd_is_bce_req_idle(uint16_t i_caller_mod_id) { // Number of times we've waited for current request to finish static uint8_t L_wait_count = 0; // If the request was not previously scheduled, then it is idle. This also // handles the case where the request has not been initialized yet. if (!G_inband_cmd_req_scheduled) { return true; } // Request was scheduled; check if it finished and is now idle if (async_request_is_idle(&G_inband_cmd_bce_req.request)) { // Request is now idle and ready for re-use G_inband_cmd_req_scheduled = false; // If we were waiting for request to finish, trace and clear wait count if (L_wait_count > 0) { TRAC_INFO("inband_cmd_is_bce_req_idle: " "Request finished after waiting %u times: caller=0x%04X", L_wait_count, i_caller_mod_id); L_wait_count = 0; } return true; } // Request was scheduled but has not finished. Increment wait count unless // we are already at the max (to avoid overflow). if (L_wait_count < UINT8_MAX) { ++L_wait_count; } // If this is the first time we've waited for this request, trace it if (L_wait_count == 1) { TRAC_INFO("inband_cmd_is_bce_req_idle: " "Waiting for request to finish: caller=0x%04X", i_caller_mod_id); } // If this is the second time we've waited for this request, log BCE error if (L_wait_count == 2) { /* @ * @errortype * @moduleid INBAND_CMD_IS_BCE_REQ_IDLE_MOD * @reasoncode INBAND_CMD_ERROR * @userdata1 Caller module ID * @userdata2 0 * @userdata4 ERC_GENERIC_TIMEOUT * @devdesc BCE request not finished after waiting twice */ inband_cmd_log_bce_error(INBAND_CMD_IS_BCE_REQ_IDLE_MOD, ERC_GENERIC_TIMEOUT, i_caller_mod_id, 0); } // Return false since request is not idle return false; } /** * inband_cmd_bce_callback * * Description: Callback function for G_inband_cmd_bce_req BCE request * NO TRACING OR CALLING FUNCTIONS THAT TRACE ALLOWED */ void inband_cmd_bce_callback( void ) { static bool L_processed_at_least_one_cmd = FALSE; static uint8_t L_last_seq_num_processed = 0; uint8_t seq_num = 0; uint8_t cmd_flags = 0; // Decide what to do next for processing an in-band command for the BCE that finished switch (G_inband_occ_cmd_state) { case INBAND_OCC_CMD_CHECK_FOR_CMD: // check for command uses min bce data buffer // If we processed at least one cmd it is not a new command if same seq number cmd_flags = G_inband_cmd_min_data_bce_buff.header.flags; seq_num = G_inband_cmd_min_data_bce_buff.header.seq; if( ( (!L_processed_at_least_one_cmd) || (L_processed_at_least_one_cmd && (seq_num != L_last_seq_num_processed)) ) && ( (cmd_flags & IN_BAND_CMD_READY_MASK) == IN_BAND_CMD_READY_MASK) ) { // There is a command to process G_inband_occ_cmd_state = INBAND_OCC_CMD_START; // now that we have a cmd save seq num so we don't keep processing the same cmd L_processed_at_least_one_cmd = TRUE; L_last_seq_num_processed = seq_num; } else { // No command G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; } break; case INBAND_OCC_CMD_RSP_READY: // response is ready send interrupt G_inband_occ_cmd_state = INBAND_OCC_CMD_RSP_INT; break; default: // Invalid state. Can't trace here set state to invalid to trace later G_inband_occ_bce_saved_state = G_inband_occ_cmd_state; G_inband_occ_cmd_state = INBAND_OCC_INVALID_BCE_CALLBACK; break; } } /** * Copies the specified number of bytes either to main mem or down from main mem * for handling an inband command using the Block Copy Engine (BCE). * * @param i_main_mem_addr Main memory address for copy. Must be 128-byte aligned * @param i_sram_addr SRAM address for copy. Must be 128-byte aligned * @param i_byte_count Number of bytes to copy. Must be multiple of 128. * Must be <= INBAND_OCC_CMD_BCE_BUF_SIZE. 0 bytes is not valid * @param i_to_main_mem TRUE indicates copy is sram to main memory * FALSE indicates copy is main memory to sram * @param i_caller_mod_id Module ID of the calling function in case an error occurs * @return True if BCE request was successfully scheduled, false otherwise */ bool inband_cmd_bce_copy(uint32_t i_main_mem_addr, uint32_t i_sram_addr, size_t i_byte_count, bool i_to_main_mem, uint16_t i_caller_mod_id) { int l_rc = 0; // Verify address and byte count are valid static bool L_traced_param_error = false; if (((i_main_mem_addr % 128) != 0) || ((i_sram_addr % 128) != 0) || ((i_byte_count % 128) != 0) || (i_byte_count > INBAND_CMD_MAX_BCE_BUF_SIZE) || (i_byte_count == 0) ) { if (!L_traced_param_error) { TRAC_ERR("inband_cmd_bce_copy: Input parameter error: " "address=0x%08X SRAM=0x%08X length=%u caller=0x%04X", i_main_mem_addr, i_sram_addr, i_byte_count, i_caller_mod_id); L_traced_param_error = true; } return false; } // Check if a copy request was previously scheduled and is not yet finished static bool L_traced_sched_error = false; if (!inband_cmd_is_bce_req_idle(i_caller_mod_id)) { if (!L_traced_sched_error) { TRAC_ERR("inband_cmd_bce_copy: Previous request not finished: caller=0x%04X", i_caller_mod_id); L_traced_sched_error = true; } return false; } // Create BCE request based on if copy is up or down from main memory if (i_to_main_mem) { l_rc = bce_request_create(&G_inband_cmd_bce_req, // Block copy request &G_pba_bcue_queue, // SRAM up to mainstore i_main_mem_addr, // Mainstore address i_sram_addr, // SRAM start address i_byte_count, // Size of copy SSX_WAIT_FOREVER, // No timeout (AsyncRequestCallback) inband_cmd_bce_callback, NULL, // No call back args ASYNC_CALLBACK_IMMEDIATE); } else { l_rc = bce_request_create(&G_inband_cmd_bce_req, // Block copy request &G_pba_bcde_queue, // mainstore down to SRAM i_main_mem_addr, // Mainstore address i_sram_addr, // SRAM start address i_byte_count, // Size of copy SSX_WAIT_FOREVER, // No timeout (AsyncRequestCallback) inband_cmd_bce_callback, NULL, // No call back args ASYNC_CALLBACK_IMMEDIATE); } if (l_rc != SSX_OK) // fail to create BCE request? { TRAC_ERR("inband_cmd_bce_copy: Request create failure: rc=0x%08X caller=0x%04X", -l_rc, i_caller_mod_id); /* @ * @errortype * @moduleid INBAND_CMD_BCE_COPY_MOD * @reasoncode INBAND_CMD_ERROR * @userdata1 Return code from bce_request_create() * @userdata2 Caller module ID * @userdata4 ERC_BCE_REQUEST_CREATE_FAILURE * @devdesc Failed to create BCE request */ inband_cmd_log_bce_error(INBAND_CMD_BCE_COPY_MOD, ERC_BCE_REQUEST_CREATE_FAILURE, -l_rc, i_caller_mod_id); return false; } // Schedule BCE request l_rc = bce_request_schedule(&G_inband_cmd_bce_req); if (l_rc != SSX_OK) { TRAC_ERR("inband_cmd_bce_copy: Request schedule failure: rc=0x%08X caller=0x%04X", -l_rc, i_caller_mod_id); /* @ * @errortype * @moduleid INBAND_CMD_BCE_COPY_MOD * @reasoncode INBAND_CMD_ERROR * @userdata1 Return code from bce_request_schedule() * @userdata2 Caller module ID * @userdata4 ERC_BCE_REQUEST_SCHEDULE_FAILURE * @devdesc Failed to schedule BCE request */ inband_cmd_log_bce_error(INBAND_CMD_BCE_COPY_MOD, ERC_BCE_REQUEST_SCHEDULE_FAILURE, -l_rc, i_caller_mod_id); return false; } // Successfully scheduled request. Copy is not blocking, so need to check // whether it finished later. Set flag indicating request is scheduled. G_inband_cmd_req_scheduled = true; return true; } // Function Specification // // Name: inband_command_check // // Description: Check for command from the inband interface // // End Function Specification void inband_command_check(void) { // Only check for a new command if not currently processing an inband command if (G_inband_occ_cmd_state == INBAND_OCC_CMD_NONE) { // Create and Schedule BCE to read minimum bytes of OCC inband command buffer in HOMER memset((void*)&G_inband_cmd_min_data_bce_buff, 0x00, sizeof(inband_min_cmd_t)); bool i_to_main_mem = FALSE; // this request is main mem down to SRAM G_inband_occ_cmd_state = INBAND_OCC_CMD_CHECK_FOR_CMD; G_bce_callback_wait = 0; if (inband_cmd_bce_copy(INBAND_OCC_CMD_ADDRESS_HOMER, (uint32_t)&G_inband_cmd_min_data_bce_buff, INBAND_CMD_MIN_BCE_BUF_SIZE, i_to_main_mem, INBAND_CMD_CHECK_MOD)) { // Copy succeeded. The BCE callback will handle next } else { // copy failed try again next time G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; } } } // Function Specification // // Name: inband_command_handler // // Description: Command handler for inband commands this should only be called if // it is already known that there is an in-band command in process // This is checked to be called on every tick // // End Function Specification void inband_command_handler(void) { uint8_t l_reason_code = ERRL_RC_INTERNAL_FAIL; uint16_t l_cmd_data_len = 0; uint8_t l_seq_num = 0; uint8_t l_cmd_type = 0xFF; uint16_t l_rsp_data_length = 0; uint16_t l_bce_copy_size = 0; uint8_t l_bce_padding = 0; bool l_to_main_mem = TRUE; // BCE requests from here are going SRAM to main memory bool l_bce_scheduled = FALSE; // Decide what to do next for processing an in-band command if(G_inband_occ_cmd_state == INBAND_OCC_CMD_START) { // We use the max buffer for response memset((void*)&G_inband_cmd_max_data_bce_buff, 0x00, INBAND_CMD_MAX_BCE_BUF_SIZE); // When we check for command we used the minimum bce buffer l_seq_num = G_inband_cmd_min_data_bce_buff.header.seq; l_cmd_type = G_inband_cmd_min_data_bce_buff.header.cmd_type; l_cmd_data_len = CONVERT_UINT8_ARRAY_UINT16(G_inband_cmd_min_data_bce_buff.header.data_length[0], G_inband_cmd_min_data_bce_buff.header.data_length[1]); // if data is more than min we will need to do another BCE to read the rest of the cmd if(l_cmd_data_len > INBAND_MIN_DATA_LENGTH) { // invalid command, currently no cmd supported is larger than min requiring 2nd BCE l_reason_code = ERRL_RC_INVALID_CMD_LEN; } else { // Have the full command, process it based on command type. // cmd data is in min data BCE buffer the rsp data will go in the max data BCE buffer uint8_t* l_cmd_data_ptr = (uint8_t*) &G_inband_cmd_min_data_bce_buff.data; uint8_t* l_rsp_data_ptr = (uint8_t*) &G_inband_cmd_max_data_bce_buff.data; switch(l_cmd_type) { case CMDH_CLEAR_SENSOR_DATA: l_reason_code = cmdh_clear_sensor_data(l_cmd_data_len, l_cmd_data_ptr, INBAND_MAX_DATA_LENGTH, &l_rsp_data_length, l_rsp_data_ptr); break; case CMDH_SET_PCAP_INBAND: l_reason_code = cmdh_set_pcap_inband(l_cmd_data_len, l_cmd_data_ptr, INBAND_MAX_DATA_LENGTH, &l_rsp_data_length, l_rsp_data_ptr); break; case CMDH_WRITE_PSR: l_reason_code = cmdh_write_psr(l_cmd_data_len, l_cmd_data_ptr, INBAND_MAX_DATA_LENGTH, &l_rsp_data_length, l_rsp_data_ptr); break; case CMDH_SELECT_SENSOR_GROUPS: l_reason_code = cmdh_select_sensor_groups(l_cmd_data_len, l_cmd_data_ptr, INBAND_MAX_DATA_LENGTH, &l_rsp_data_length, l_rsp_data_ptr); break; default: l_reason_code = ERRL_RC_INVALID_CMD; break; } // end switch } // end cmd process // fill in response header in G_inband_cmd_max_data_bce_buff G_inband_cmd_max_data_bce_buff.header.flags = IN_BAND_RSP_READY_MASK; G_inband_cmd_max_data_bce_buff.header.seq = l_seq_num; G_inband_cmd_max_data_bce_buff.header.cmd_type = l_cmd_type; G_inband_cmd_max_data_bce_buff.header.reserved_rc = l_reason_code; G_inband_cmd_max_data_bce_buff.header.data_length[0] = ((uint8_t *)&l_rsp_data_length)[0]; G_inband_cmd_max_data_bce_buff.header.data_length[1] = ((uint8_t *)&l_rsp_data_length)[1]; // Copy the response from SRAM to main memory // Determine BCE copy size, must be factor of 128 l_bce_copy_size = sizeof(inband_occ_cmd_header_t) + l_rsp_data_length; l_bce_padding = l_bce_copy_size % 128; if(l_bce_padding) { l_bce_copy_size += (128 - l_bce_padding); } G_bce_callback_wait = 0; G_inband_occ_cmd_state = INBAND_OCC_CMD_RSP_READY; l_bce_scheduled = inband_cmd_bce_copy(INBAND_OCC_RSP_ADDRESS_HOMER, (uint32_t)&G_inband_cmd_max_data_bce_buff, l_bce_copy_size, l_to_main_mem, INBAND_CMD_HANDLER_MOD); if (!l_bce_scheduled) { // failed to copy response G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; } else { TRAC_INFO("inband_command_handler: Command 0x%02X with " "seq_num 0x%02X finished with RC 0x%02X", l_cmd_type, l_seq_num, l_reason_code); } } // INBAND_OCC_CMD_START else if(G_inband_occ_cmd_state == INBAND_OCC_CMD_RSP_INT) { // Send interrupt to indciate response is ready in main mem notify_host(INTR_REASON_OPAL_SHARED_MEM_CHANGE); G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; } else if( (G_inband_occ_cmd_state == INBAND_OCC_CMD_CHECK_FOR_CMD) || (G_inband_occ_cmd_state == INBAND_OCC_CMD_RSP_READY) ) { // Waiting for BCE to finish, these states are handled by BCE callback // if the callback is never called (BCE failure) for a max wait log error G_bce_callback_wait++; if(G_bce_callback_wait == MAX_TICS_INBAND_BCE_CALLBACK_WAIT) { TRAC_ERR("inband_command_handler: Timeout waiting for BCE callback cmd state 0x%02X", G_inband_occ_cmd_state); G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; /* @ * @errortype * @moduleid INBAND_CMD_HANDLER_MOD * @reasoncode INBAND_CMD_ERROR * @userdata1 Inband command state * @userdata2 Caller module ID * @userdata4 ERC_BCE_REQ_CALLBACK_TIMEOUT * @devdesc Timeout waiting for BCE callback */ inband_cmd_log_bce_error(INBAND_CMD_HANDLER_MOD, ERC_BCE_REQ_CALLBACK_TIMEOUT, G_inband_occ_cmd_state, INBAND_CMD_HANDLER_MOD); } } else if(G_inband_occ_cmd_state == INBAND_OCC_INVALID_BCE_CALLBACK) { // BCE callback was called with invalid state, trace now and set state to none static bool L_traced_bce_bad_state = FALSE; if (!L_traced_bce_bad_state) { TRAC_ERR("inband_command_handler: inband_cmd_bce_callback detected invalid state %u", G_inband_occ_bce_saved_state); L_traced_bce_bad_state = TRUE; } G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; G_inband_occ_bce_saved_state = INBAND_OCC_CMD_NONE; } else { // Invalid state static bool L_traced_bad_state = FALSE; if (!L_traced_bad_state) { TRAC_ERR("inband_command_handler: Called with invalid state %u", G_inband_occ_cmd_state); L_traced_bad_state = TRUE; } G_inband_occ_cmd_state = INBAND_OCC_CMD_NONE; } } <|start_filename|>src/ssx/ssx/ssx_semaphore_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_semaphore_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_semaphore_init.c /// \brief SSX semaphore API initialization routines /// /// The entry points in this file are routines that are typically used during /// initialization, and their code space could be deallocated and recovered if /// no longer needed by the application after initialization. #include "ssx.h" /// Create (initialize) a semaphore /// /// \param semaphore A pointer to an SsxSemaphore structure to initialize /// /// \param initial_count The initial count of the semaphore /// /// \param max_count The maximum count allowed in the semaphore, for error /// checking /// /// Semaphores are created (initialized) by a call of \c /// ssx_semaphore_create(), using an application-provided instance of an \c /// SsxSemaphore structure. This structure \e is the semaphore, so the /// application must never modify the structure if the semaphore is in use. /// SSX has no way to know if an \c SsxSemaphore structure provided to /// \c ssx_semaphore_create() is safe to use as a semaphore, and will silently /// modify whatever memory is provided. /// /// SSX provides two simple overflow semantics based on the value of max_count /// in the call of \c ssx_semaphore_create(). /// /// If \a max_count = 0, then posting to the semaphore first increments the /// internal count by 1. Overflows are ignored and will wrap the internal /// count through 0. /// /// If \a max_count != 0, then posting to the semaphore first increments the /// internal count by 1, wrapping through 0 in the event of overflow. If the /// resulting count is greater than max_count, \c ssx_semaphore_post() will /// return the error \c -SSX_SEMAPHORE_POST_OVERFLOW to the caller. /// /// In most applications it is probably best to use the \a max_count != 0 /// semantics to trap programming errors, unless there is a specific /// application where overflow is expected and ignorable. As a fine point of /// the specification, a \a max_count of 0 is equivalent to a max_count of /// 0xFFFFFFFF. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_SEMAPHORE_AT_CREATE The \a semaphore is a null (0) /// pointer. /// /// \retval -SSX_INVALID_ARGUMENT_SEMAPHORE The \a max_count is non-zero /// and less than the \a initial_count. int ssx_semaphore_create(SsxSemaphore* semaphore, SsxSemaphoreCount initial_count, SsxSemaphoreCount max_count) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(semaphore == 0, SSX_INVALID_SEMAPHORE_AT_CREATE); SSX_ERROR_IF((max_count != 0) && (initial_count > max_count), SSX_INVALID_ARGUMENT_SEMAPHORE); } __ssx_thread_queue_clear(&(semaphore->pending_threads)); semaphore->count = initial_count; semaphore->max_count = max_count; return SSX_OK; } <|start_filename|>src/ppe/pk/gpe/gpe_common.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/gpe/gpe_common.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __GPE_COMMON_H__ #define __GPE_COMMON_H__ /// \file gpe_common.h /// \brief Common header for GPE /// /// This header is maintained as part of the PK port for GPE, but needs to be /// physically present in the PMX area to allow dropping PMX code as a whole /// to other teams. // -*- WARNING: This file is maintained as part of PK. Do not edit in -*- // -*- the PMX area as your edits will be lost. -*- #ifndef __ASSEMBLER__ #include <stdint.h> #endif #include "occhw_common.h" /// Each GPE instance has it's own interrupt status register these macros /// are added for convenience in accessing the correct register #ifndef UNIFIED_IRQ_HANDLER_GPE #define GPE_GISR0(instance_id) (OCB_G0ISR0 + (instance_id * 8)) #define GPE_GISR1(instance_id) (OCB_G0ISR1 + (instance_id * 8)) #endif #ifdef __ASSEMBLER__ // *INDENT-OFF* /// This macro contains GPE specific code for determining what IRQ caused the /// external exception handler to be invoked by the PPE /// Check for interrupts pending in status register 0 while the IRQ is /// computed. The IRQ is expected to be stored in r4. If no IRQ is /// pending then load the phantom irq # (EXTERNAL_IRQS). /// /// r1, r2, r3, and r13 must not be modified. All other registers may be used. /// /// The pk_unified_irq_prty_mask_handler routine MUST return the task priority /// interrupt vector in d5. /// .macro hwmacro_get_ext_irq #ifdef UNIFIED_IRQ_HANDLER_GPE // Unified approach. _liw r5, pk_unified_irq_prty_mask_handler mtlr r5 blrl // On return, d5 contains task prty irq vec. mfsprg r3, 0 // In case r3 is modified by unified handler, restore to sprg0 #else _lwzi %r5, %r5, GPE_GISR0(APPCFG_OCC_INSTANCE_ID) #endif cntlzw %r4, %r5 cmpwible %r4, 31, call_external_irq_handler #branch if irq is lt or eq to 31 ## No IRQ pending in interrupt set 0. Try set 1. ## Note: irq # will be 64 (EXTERNAL_IRQS) if no bits were set in either register #ifndef UNIFIED_IRQ_HANDLER_GPE _lwzi %r6, %r6, GPE_GISR1(APPCFG_OCC_INSTANCE_ID) #endif cntlzw %r4, %r6 addi %r4, %r4, 32 .endm /// Redirect the .hwmacro_irq_cfg_bitmaps macro to call our macro that is common for both /// GPE's and the 405 inside the OCC complex. This is called from the ppe42_exceptions.S /// file. .macro .hwmacro_irq_cfg_bitmaps .occhw_irq_cfg_bitmaps .endm // *INDENT-ON* #endif /* __ASSEMBLER__ */ #endif /* __GPE_COMMON_H__ */ <|start_filename|>src/ssx/occhw/occhw_pba.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_pba.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_pba.c /// \brief procedures for pba setup and operation. #include "ssx.h" #include "occhw_pba.h" #include "occhw_scom.h" #include "occhw_common.h" #include "polling.h" // Internal API to set up a PBA BAR static int pba_bar_set(int idx, uint64_t pb_base, uint8_t pb_scope) { int rc ; pba_barn_t bar ; bar.fields.cmd_scope = pb_scope ; bar.fields.addr = pb_base >> PBA_LOG_SIZE_MIN ; rc = putscom(PBA_BARN(idx), bar.value); return rc ; } // Internal API to set up a PBA BAR Mask. The mask covers bits 23:43, address // bits 44:63 are always allowed. static int pba_barmask_set(int idx, uint64_t mask) { int rc ; pba_barmskn_t barmask ; barmask.value = mask & 0x000001FFFFF00000ull; rc = putscom(PBA_BARMSKN(idx), barmask.value); return rc ; } /// Procedure to allocate a PowerBus address block using the bridge. /// /// \param idx The BAR set to use, in the range 0..3. /// /// \param base The 50-bit PowerBus base address where the block starts. This /// address must be aligned to the \a log_size. /// /// \param log_size The base 2 logarithm of the block size, in bytes. The /// minimum size is 1MB (2**20), the maximum size is 2TB (2**41) /// /// This is a validation/test procedure only, since setting up the PBA BARs is /// normally reserved to pHyp and FSP. If the MMU is enabled and the PBA /// mapping will be referenced by the 405, then an MMU mapping will also have /// to be created (separately) for the block. /// /// This procedure is not the complete setup for large memory areas. Memory /// areas that require the extended address will have to set that up /// separately. /// /// \retval 0 Success /// /// \retval PBA_INVALID_ARGUMENT_BARSET One or more of the parameter /// restrictions were violated. /// /// \retval PBA_SCOM_ERROR1 or PBA_SCOM_ERROR2 An attempt to write a PBA SCOM /// register to set up the BARs produced a non-zero return code. int pba_barset_initialize(int idx, uint64_t base, int log_size) { uint64_t mask ; mask = (0x1ull << log_size) - 1; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((idx < 0) || (idx > 3) || (log_size < PBA_LOG_SIZE_MIN) || (log_size > PBA_LOG_SIZE_MAX) || ((base & mask) != 0), PBA_INVALID_ARGUMENT_BARSET); } if (pba_bar_set(idx, base, PBA_POWERBUS_COMMAND_SCOPE_DEFAULT)) { SSX_ERROR(PBA_SCOM_ERROR1); } if (pba_barmask_set(idx, mask)) { SSX_ERROR(PBA_SCOM_ERROR2); } return 0 ; } // polling() function for PBA Slave reset // // Slave reset for PBA is a complex issue, especially in cases where the // entity requesting the reset may be executing from main memory, i.e. // continuing to read to or write from the slave being reset. To work around // potential issues if the 405 is attempting to reset its own slave, the code // that polls for reset is PowerBus cache-line aligned, and we re-hit the // reset button each time we get an unsuccessful poll for the reset being // done. This should guarantee that the slave will go to reset status as soon // as any PowerBus blockages (if any) clear and the master stops either // reading or writing the slave port. For details see HW228485. int _pba_slave_reset_poll(void* arg, int* done) ALIGNED_ATTRIBUTE(128); int _pba_slave_reset_poll(void* arg, int* done) { int id; pba_slvrst_t psr; id = (int)arg; psr.value = 0; psr.fields.set = PBA_SLVRST_SET(id); out64(PBA_SLVRST, psr.value); psr.value = in64(PBA_SLVRST); *done = !(psr.fields.in_prog & PBA_SLVRST_IN_PROG(id)); return 0; } /// Reset a PBA slave with explicit timeout. /// /// \param id A PBA slave id in the range 0..3 /// /// \param timeout A value of SsxInterval type. The special value /// SSX_WAIT_FOREVER indicates no timeout. /// /// \param sleep A value of SsxInterval type. Callers using the explicit /// timeout form can request that the thread sleeps between polls; See /// documentation for the polling() API. /// /// This form of pba_slave_reset() gives the caller control over timeouts, /// sleeping and error handling. /// /// \retval 0 Success /// /// \retval -PBA_INVALID_ARGUMENT_RESET The slave \a id parameter /// is invalid. /// /// \retval -PBA_SLVRST_TIMED_OUT1 The procedure timed out waiting for the PBA /// to reset the slave. int _pba_slave_reset(int id, SsxInterval timeout, SsxInterval sleep) { int rc, closureRc; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((id < 0) || (id >= PBA_SLAVES), PBA_INVALID_ARGUMENT_RESET); } rc = polling(&closureRc, _pba_slave_reset_poll, (void*)id, timeout, sleep); if (rc == POLLING_TIMEOUT) { rc = -PBA_SLVRST_TIMED_OUT1; } return rc; } /// Reset a PBA slave with a default timeout /// /// \param id A PBA slave id in the range 0..3 /// /// PBA slaves must be reset before being reprogrammed. Resetting a slave /// also flushes any write buffers and invalidates any read buffers associated /// with the slave. This procedure is for initialization/bringup/test only; /// it has a non-deterministic run time due to the PowerBus so should not be /// run as part of a hard real-time loop. /// /// \retval 0 Success /// /// \retval -SSX_INVALID_ARGUMENT_PBA_RESET The slave \a id parameter is /// invalid. /// /// \retval -PBA_SLVRST_TIMED_OUT2 The procedure timed out waiting for the PBA /// to reset the slave. int pba_slave_reset(int id) { int rc; rc = _pba_slave_reset(id, PBA_SLAVE_RESET_TIMEOUT, 0); if (rc) { SSX_ERROR(PBA_SLVRST_TIMED_OUT2); } return rc; } /// Configure the PBAX mechanism /// /// \param master If non-0, then this OCC will assume the role of the PBAX /// master processor in the power domain. To avoid PBAX livelock there can /// only be a single master in any power domain, and only the master is /// allowed to issue PBAX broadcast transactions. /// /// \param node The PBAX Node Id of this OCC /// /// \param chip The PBAX Chip Id of this OCC /// /// \param group_mask A bit mask indicating the broadcast group(s) (power /// domain(s)) that this OCC belongs to. /// /// This API sets up certain fields of the PBA_XCFG register according to the /// parameters. Other fields in the register controlling hardware timeouts and /// performance monitoring are unchanged. /// /// \retval 0 Success /// /// \retval -PBAX_INVALID_ARGUMENT_CONFIG One of the arguments is /// not valid for some reason. int pbax_configure(int master, int group, int chip, int group_mask) { pba_xcfg_t pxc; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((group < 0) || (group >= PBAX_GROUPS) || (chip < 0) || (chip >= PBAX_CHIPS) || (group_mask < 0) || (group_mask > PBAX_GROUP_MASK_MAX), PBAX_INVALID_ARGUMENT_CONFIG); } pxc.value = in64(PBA_XCFG); pxc.fields.reservation_en = (master != 0); pxc.fields.rcv_groupid = group; pxc.fields.rcv_chipid = chip; pxc.fields.rcv_brdcst_group = group_mask; out64(PBA_XCFG, pxc.value); return 0; } /// Create a PBAX abstract target /// /// \param target An uninitialized or otherwise idle PbaxTarget object /// /// \param type The transmission type, either PBAX_UNICAST or PBAX_BROADCAST /// /// \param scope The PowerBus scope, either PBAX_GROUP or PBAX_SYSTEM /// /// \param queue The receive queue index on the target, either 0 or 1 /// /// \param node The PBAX Node Id of the target /// /// \param chip_or_group Either the PBAX Chip Id of the target (for unicast), /// or the PBAX Group Id of the target (for broadcast) /// /// Create an abstraction of a communication target for PBAX send operations, /// for use with the _pbax_send() and _pbax_send() APIs. This API has no /// knowledge of how the PBAX is configured, and therefore accepts all node, /// chip and broadcast group ids as valid. However this API does assume that /// all broadcast transactions are "real-time" and require a reservation. /// /// \retval 0 Success /// /// \retval -PBAX_INVALID_OBJECT The \a target parameter is NULL (0) or /// otherwise invalid. /// /// \retval -PBAX_INVALID_ARGUMENT_TARGET One or more of the arguments /// is invalid. int pbax_target_create(PbaxTarget* target, int type, int scope, int queue, int group, int chip_or_group, int cnt) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(target == 0, PBAX_INVALID_OBJECT); SSX_ERROR_IF(((type != PBAX_UNICAST) && (type != PBAX_BROADCAST)) || ((scope != PBAX_GROUP) && (scope != PBAX_SYSTEM)) || ((queue < 0) || (queue >= PBAX_QUEUES)), PBAX_INVALID_ARGUMENT_TARGET); } target->target.value = 0; target->target.fields.snd_scope = scope; target->target.fields.snd_qid = queue; target->target.fields.snd_type = type; target->target.fields.snd_reservation = (type == PBAX_BROADCAST); target->target.fields.snd_groupid = group; target->target.fields.snd_chipid = chip_or_group; target->target.fields.snd_cnt = cnt; target->target.fields.vg_targe = 0xffff; return 0; } /// Use PBAX to send 64 bits to a target with a caller-specified timeout /// /// \param target An abstract PBAX target object /// /// \param data The data to send /// /// \param timeout The caller's timeout represented as an /// SsxInterval. Use SSX_WAIT_FOREVER to indicate the caller is willing to /// wait forever. A \a timeout of 0 indicates that the caller is not /// willing to wait at all, and the call will either succeed immediately or /// immediately return -PBAX_TIMEOUT. /// /// The PBAX mechanism has a single outgoing channel that must be shared by /// all processes that need to send messages using PBAX. Since messages sent /// over PBAX may require an unknown amount of time to complete (due to /// PowerBus traffic and blockages), this driver implements an agressive /// policy that allows a sender to initiate a send transaction without waiting /// for the final completion status. However this opens a window where a /// subsequent writer may find the PBAX send mechanism already in use. Here /// the new sender is obligated to busy-wait until the send mechanism is free, /// as the PBAX send does not include an interrupt notification. /// /// This form of the PBAX send operation accepts an explicit \a timeout value /// as previously described. The timeout represents the amount of time that /// the caller is willing to wait for a busy PBAX send mechanism to become /// free. The PBAX hardware also includes mechanisms to time out the hardware /// and modeably interrupt OCC in the event of lack of progress. /// /// <em> This API does not operate in a critical section or enforce any /// synchronization protocol. Synchronization and software timeout management /// in the case of multiple senders is the responsibility of the /// application. </em> /// /// Unlike most other driver APIs this API can not be configured to "panic", /// but instead always terminates with a 0 return code or an error status. /// /// \retval 0 Success. Success only means that a transaction was sucessfully /// initiated on an idle PBAX send machine. /// /// \retval -PBAX_TIMEOUT The caller-specified timeout expired before the PBAX /// send machine became free, but the PBAX send machine does not show error /// status. /// /// \retval -PBAX_SEND_ERROR The PBAXSNDSTAT.snd_error bit is asserted. It /// is expected that this error will cause the PBA error interrupt to fire - /// FFDC is collected by the interrupt handler. int _pbax_send(PbaxTarget* target, uint64_t data, SsxInterval timeout) { pba_xsndstat_t pss; SsxTimebase start; int rc, timed_out; // The PBAX is always polled at least twice to guarantee that we always // poll once after a timeout - unless the caller explicitly requested a 0 // timeout. start = 0; timed_out = 0; do { pss.words.high_order = in32(PBA_XSNDSTAT); if (pss.fields.snd_error) { rc = -PBAX_SEND_ERROR; break; } if (!pss.fields.snd_in_progress) { rc = 0; break; } if (start == 0) { start = ssx_timebase_get(); } if ((timeout == 0) || timed_out) { rc = -PBAX_SEND_TIMEOUT; break; } timed_out = ((timeout != SSX_WAIT_FOREVER) && ((ssx_timebase_get() - start) > timeout)); } while (1); // Configure the send engine and initiate the write, which is kicked off // by writing the high-order word of the send data register. if (!rc) { out64(PBA_XSNDTX, target->target.value); out32(PBA_XSNDDAT + 4, data >> 32); out32(PBA_XSNDDAT, data & 0xffffffff); } return rc; } /// Use PBAX to send 64 bits to a target with a default timeout /// /// \param target An abstract PBAX target object /// /// \param data The data to send /// /// This form of the PBAX send operation uses a default timeout, and may be /// configured to panic in the event of timeouts or send errors. See /// _pbax_send() for the specification of the underlying API. /// /// <em> This API does not operate in a critical section or enforce any /// synchronization protocol. Synchronization and software timeout management /// in the case of multiple senders is the responsibility of the /// application. </em> /// /// \retval 0 Success. Success only means that a transaction was sucessfully /// initiated on an idle PBAX send machine. /// /// \retval -PBAX_TIMEOUT The caller-specified timeout expired before the PBAX /// send machine became free. /// /// \retval -PBAX_SEND_ERROR The PBAXSNDSTAT.snd_error bit is asserted. int pbax_send(PbaxTarget* target, uint64_t data) { int rc; rc = _pbax_send(target, data, PBAX_SEND_DEFAULT_TIMEOUT); if (rc) { if (rc == -PBAX_SEND_TIMEOUT) { SSX_ERROR(PBAX_SEND_TIMEOUT); } else { SSX_ERROR(PBAX_SEND_ERROR); } } return rc; } <|start_filename|>src/include/registers/gpe_register_addresses.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/gpe_register_addresses.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __GPE_REGISTER_ADDRESSES_H__ #define __GPE_REGISTER_ADDRESSES_H__ /// \file gpe_register_addresses.h /// \brief Symbolic addresses for the GPE unit // *** WARNING *** - This file is generated automatically, do not edit. #define GPE_OCI_BASE 0xC0000000 #define GPE_GPENTSEL(n) (GPE_GPE0TSEL + ((GPE_GPE1TSEL - GPE_GPE0TSEL) * (n))) #define GPE_GPE0TSEL 0xc0000000 #define GPE_GPE1TSEL 0xc0010000 #define GPE_GPE2TSEL 0xc0020000 #define GPE_GPE3TSEL 0xc0030000 #define GPE_GPENIVPR(n) (GPE_GPE0IVPR + ((GPE_GPE1IVPR - GPE_GPE0IVPR) * (n))) #define GPE_GPE0IVPR 0xc0000008 #define GPE_GPE1IVPR 0xc0010008 #define GPE_GPE2IVPR 0xc0020008 #define GPE_GPE3IVPR 0xc0030008 #define GPE_GPENDBG(n) (GPE_GPE0DBG + ((GPE_GPE1DBG - GPE_GPE0DBG) * (n))) #define GPE_GPE0DBG 0xc0000010 #define GPE_GPE1DBG 0xc0010010 #define GPE_GPE2DBG 0xc0020010 #define GPE_GPE3DBG 0xc0030010 #define GPE_GPENSTR(n) (GPE_GPE0STR + ((GPE_GPE1STR - GPE_GPE0STR) * (n))) #define GPE_GPE0STR 0xc0000018 #define GPE_GPE1STR 0xc0010018 #define GPE_GPE2STR 0xc0020018 #define GPE_GPE3STR 0xc0030018 #define GPE_GPENMACR(n) (GPE_GPE0MACR + ((GPE_GPE1MACR - GPE_GPE0MACR) * (n))) #define GPE_GPE0MACR 0xc0000020 #define GPE_GPE1MACR 0xc0010020 #define GPE_GPE2MACR 0xc0020020 #define GPE_GPE3MACR 0xc0030020 #define GPE_GPENXIXCR(n) (GPE_GPE0XIXCR + ((GPE_GPE1XIXCR - GPE_GPE0XIXCR) * (n))) #define GPE_GPE0XIXCR 0xc0000080 #define GPE_GPE1XIXCR 0xc0010080 #define GPE_GPE2XIXCR 0xc0020080 #define GPE_GPE3XIXCR 0xc0030080 #define GPE_GPENXIRAMRA(n) (GPE_GPE0XIRAMRA + ((GPE_GPE1XIRAMRA - GPE_GPE0XIRAMRA) * (n))) #define GPE_GPE0XIRAMRA 0xc0000088 #define GPE_GPE1XIRAMRA 0xc0010088 #define GPE_GPE2XIRAMRA 0xc0020088 #define GPE_GPE3XIRAMRA 0xc0030088 #define GPE_GPENXIRAMGA(n) (GPE_GPE0XIRAMGA + ((GPE_GPE1XIRAMGA - GPE_GPE0XIRAMGA) * (n))) #define GPE_GPE0XIRAMGA 0xc0000090 #define GPE_GPE1XIRAMGA 0xc0010090 #define GPE_GPE2XIRAMGA 0xc0020090 #define GPE_GPE3XIRAMGA 0xc0030090 #define GPE_GPENXIRAMDBG(n) (GPE_GPE0XIRAMDBG + ((GPE_GPE1XIRAMDBG - GPE_GPE0XIRAMDBG) * (n))) #define GPE_GPE0XIRAMDBG 0xc0000098 #define GPE_GPE1XIRAMDBG 0xc0010098 #define GPE_GPE2XIRAMDBG 0xc0020098 #define GPE_GPE3XIRAMDBG 0xc0030098 #define GPE_GPENXIRAMEDR(n) (GPE_GPE0XIRAMEDR + ((GPE_GPE1XIRAMEDR - GPE_GPE0XIRAMEDR) * (n))) #define GPE_GPE0XIRAMEDR 0xc00000a0 #define GPE_GPE1XIRAMEDR 0xc00100a0 #define GPE_GPE2XIRAMEDR 0xc00200a0 #define GPE_GPE3XIRAMEDR 0xc00300a0 #define GPE_GPENXIDBGPRO(n) (GPE_GPE0XIDBGPRO + ((GPE_GPE1XIDBGPRO - GPE_GPE0XIDBGPRO) * (n))) #define GPE_GPE0XIDBGPRO 0xc00000a8 #define GPE_GPE1XIDBGPRO 0xc00100a8 #define GPE_GPE2XIDBGPRO 0xc00200a8 #define GPE_GPE3XIDBGPRO 0xc00300a8 #define GPE_GPENXISIB(n) (GPE_GPE0XISIB + ((GPE_GPE1XISIB - GPE_GPE0XISIB) * (n))) #define GPE_GPE0XISIB 0xc00000b0 #define GPE_GPE1XISIB 0xc00100b0 #define GPE_GPE2XISIB 0xc00200b0 #define GPE_GPE3XISIB 0xc00300b0 #define GPE_GPENXIMEM(n) (GPE_GPE0XIMEM + ((GPE_GPE1XIMEM - GPE_GPE0XIMEM) * (n))) #define GPE_GPE0XIMEM 0xc00000b8 #define GPE_GPE1XIMEM 0xc00100b8 #define GPE_GPE2XIMEM 0xc00200b8 #define GPE_GPE3XIMEM 0xc00300b8 #define GPE_GPENXISGB(n) (GPE_GPE0XISGB + ((GPE_GPE1XISGB - GPE_GPE0XISGB) * (n))) #define GPE_GPE0XISGB 0xc00000c0 #define GPE_GPE1XISGB 0xc00100c0 #define GPE_GPE2XISGB 0xc00200c0 #define GPE_GPE3XISGB 0xc00300c0 #define GPE_GPENXIICAC(n) (GPE_GPE0XIICAC + ((GPE_GPE1XIICAC - GPE_GPE0XIICAC) * (n))) #define GPE_GPE0XIICAC 0xc00000c8 #define GPE_GPE1XIICAC 0xc00100c8 #define GPE_GPE2XIICAC 0xc00200c8 #define GPE_GPE3XIICAC 0xc00300c8 #define GPE_GPENXIDCAC(n) (GPE_GPE0XIDCAC + ((GPE_GPE1XIDCAC - GPE_GPE0XIDCAC) * (n))) #define GPE_GPE0XIDCAC 0xc00000d0 #define GPE_GPE1XIDCAC 0xc00100d0 #define GPE_GPE2XIDCAC 0xc00200d0 #define GPE_GPE3XIDCAC 0xc00300d0 #define GPE_GPENOXIXCR(n) (GPE_GPE0OXIXCR + ((GPE_GPE1OXIXCR - GPE_GPE0OXIXCR) * (n))) #define GPE_GPE0OXIXCR 0xc0000100 #define GPE_GPE1OXIXCR 0xc0010100 #define GPE_GPE2OXIXCR 0xc0020100 #define GPE_GPE3OXIXCR 0xc0030100 #define GPE_GPENXIXSR(n) (GPE_GPE0XIXSR + ((GPE_GPE1XIXSR - GPE_GPE0XIXSR) * (n))) #define GPE_GPE0XIXSR 0xc0000108 #define GPE_GPE1XIXSR 0xc0010108 #define GPE_GPE2XIXSR 0xc0020108 #define GPE_GPE3XIXSR 0xc0030108 #define GPE_GPENXISPRG0(n) (GPE_GPE0XISPRG0 + ((GPE_GPE1XISPRG0 - GPE_GPE0XISPRG0) * (n))) #define GPE_GPE0XISPRG0 0xc0000110 #define GPE_GPE1XISPRG0 0xc0010110 #define GPE_GPE2XISPRG0 0xc0020110 #define GPE_GPE3XISPRG0 0xc0030110 #define GPE_GPENXIEDR(n) (GPE_GPE0XIEDR + ((GPE_GPE1XIEDR - GPE_GPE0XIEDR) * (n))) #define GPE_GPE0XIEDR 0xc0000118 #define GPE_GPE1XIEDR 0xc0010118 #define GPE_GPE2XIEDR 0xc0020118 #define GPE_GPE3XIEDR 0xc0030118 #define GPE_GPENXIIR(n) (GPE_GPE0XIIR + ((GPE_GPE1XIIR - GPE_GPE0XIIR) * (n))) #define GPE_GPE0XIIR 0xc0000120 #define GPE_GPE1XIIR 0xc0010120 #define GPE_GPE2XIIR 0xc0020120 #define GPE_GPE3XIIR 0xc0030120 #define GPE_GPENXIIAR(n) (GPE_GPE0XIIAR + ((GPE_GPE1XIIAR - GPE_GPE0XIIAR) * (n))) #define GPE_GPE0XIIAR 0xc0000128 #define GPE_GPE1XIIAR 0xc0010128 #define GPE_GPE2XIIAR 0xc0020128 #define GPE_GPE3XIIAR 0xc0030128 #define GPE_GPENXISIBU(n) (GPE_GPE0XISIBU + ((GPE_GPE1XISIBU - GPE_GPE0XISIBU) * (n))) #define GPE_GPE0XISIBU 0xc0000130 #define GPE_GPE1XISIBU 0xc0010130 #define GPE_GPE2XISIBU 0xc0020130 #define GPE_GPE3XISIBU 0xc0030130 #define GPE_GPENXISIBL(n) (GPE_GPE0XISIBL + ((GPE_GPE1XISIBL - GPE_GPE0XISIBL) * (n))) #define GPE_GPE0XISIBL 0xc0000138 #define GPE_GPE1XISIBL 0xc0010138 #define GPE_GPE2XISIBL 0xc0020138 #define GPE_GPE3XISIBL 0xc0030138 #define GPE_GPENXIMEMU(n) (GPE_GPE0XIMEMU + ((GPE_GPE1XIMEMU - GPE_GPE0XIMEMU) * (n))) #define GPE_GPE0XIMEMU 0xc0000140 #define GPE_GPE1XIMEMU 0xc0010140 #define GPE_GPE2XIMEMU 0xc0020140 #define GPE_GPE3XIMEMU 0xc0030140 #define GPE_GPENXIMEML(n) (GPE_GPE0XIMEML + ((GPE_GPE1XIMEML - GPE_GPE0XIMEML) * (n))) #define GPE_GPE0XIMEML 0xc0000148 #define GPE_GPE1XIMEML 0xc0010148 #define GPE_GPE2XIMEML 0xc0020148 #define GPE_GPE3XIMEML 0xc0030148 #define GPE_GPENXISGBU(n) (GPE_GPE0XISGBU + ((GPE_GPE1XISGBU - GPE_GPE0XISGBU) * (n))) #define GPE_GPE0XISGBU 0xc0000150 #define GPE_GPE1XISGBU 0xc0010150 #define GPE_GPE2XISGBU 0xc0020150 #define GPE_GPE3XISGBU 0xc0030150 #define GPE_GPENXISGBL(n) (GPE_GPE0XISGBL + ((GPE_GPE1XISGBL - GPE_GPE0XISGBL) * (n))) #define GPE_GPE0XISGBL 0xc0000158 #define GPE_GPE1XISGBL 0xc0010158 #define GPE_GPE2XISGBL 0xc0020158 #define GPE_GPE3XISGBL 0xc0030158 #define GPE_GPENXIICACU(n) (GPE_GPE0XIICACU + ((GPE_GPE1XIICACU - GPE_GPE0XIICACU) * (n))) #define GPE_GPE0XIICACU 0xc0000160 #define GPE_GPE1XIICACU 0xc0010160 #define GPE_GPE2XIICACU 0xc0020160 #define GPE_GPE3XIICACU 0xc0030160 #define GPE_GPENXIICACL(n) (GPE_GPE0XIICACL + ((GPE_GPE1XIICACL - GPE_GPE0XIICACL) * (n))) #define GPE_GPE0XIICACL 0xc0000168 #define GPE_GPE1XIICACL 0xc0010168 #define GPE_GPE2XIICACL 0xc0020168 #define GPE_GPE3XIICACL 0xc0030168 #define GPE_GPENXIDCACU(n) (GPE_GPE0XIDCACU + ((GPE_GPE1XIDCACU - GPE_GPE0XIDCACU) * (n))) #define GPE_GPE0XIDCACU 0xc0000170 #define GPE_GPE1XIDCACU 0xc0010170 #define GPE_GPE2XIDCACU 0xc0020170 #define GPE_GPE3XIDCACU 0xc0030170 #define GPE_GPENXIDCACL(n) (GPE_GPE0XIDCACL + ((GPE_GPE1XIDCACL - GPE_GPE0XIDCACL) * (n))) #define GPE_GPE0XIDCACL 0xc0000178 #define GPE_GPE1XIDCACL 0xc0010178 #define GPE_GPE2XIDCACL 0xc0020178 #define GPE_GPE3XIDCACL 0xc0030178 #endif // __GPE_REGISTER_ADDRESSES_H__ <|start_filename|>src/occ_405/rtls/test/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occ_405/rtls/test/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2011,2015 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG rtlstest_CFILES = \ ../../common.c \ ../../errl/errl.c \ ../rtls.c \ rtls_tables.c \ main.c all_cfiles = ${rtlstest_CFILES} APP = rtlstest APP_INCLUDES += -I../../../ssx APP_INCLUDES += -I../../../lib APP_INCLUDES += -I../../incl APP_INCLUDES += -I../../trac APP_INCLUDES += -I../../errl APP_INCLUDES += -I../../thread APP_INCLUDES += -I../../rtls APP_INCLUDES += -I../../aplt/incl APP_INCLUDES += -I. D = -DOCC_FIRMWARE=1 SOURCES = ${all_cfiles} MODE = validation PGP_ASYNC_SUPPORT = 1 include ./app.mk pgas: $(CC) $(CFLAGS) -c -Wa,-al -Wa,--listing-cont-lines='10' <|start_filename|>src/occ_405/proc/test/main.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/proc/test/main.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "ssx_io.h" #include "simics_stdio.h" #include <thread.h> #include <threadSch.h> #include <errl.h> #include <apss.h> #include <appletManager.h> #include <trac.h> #include <occ_service_codes.h> #include <occ_sys_config.h> #include <proc_data.h> #include <timer.h> #include <dcom.h> #include <rtls.h> extern void __ssx_boot; IMAGE_HEADER (G_mainAppImageHdr,__ssx_boot,MAIN_APP_ID,OCC_APLT_TEST); // Period in which to run #timer_routine #define TIMER_INTERVAL (SsxInterval) SSX_MICROSECONDS(5000) int g_j = 0; int g_k = 0; SimicsStdio simics_stdout; SimicsStdio simics_stderr; uint8_t noncritical_stack[NONCRITICAL_STACK_SIZE]; uint8_t critical_stack[CRITICAL_STACK_SIZE]; // Function Specification // // Name: pgp_validation_ssx_main_hook // // Description: // // End Function Specification void pgp_validation_ssx_main_hook(void) { } // Function Specification // // Name: Cmd_Hndl_thread_routine // // Description: // // End Function Specification void Cmd_Hndl_thread_routine(void *arg) { TRAC_INFO("Command Handler Thread Started ... " ); } // Function Specification // // Name: Thermal_Monitor_thread_routine // // Description: // // End Function Specification void Thermal_Monitor_thread_routine(void *arg) { TRAC_INFO("Thermal Monitor Thread Started ... " ); } // Function Specification // // Name: Hlth_Monitor_thread_routine // // Description: // // End Function Specification void Hlth_Monitor_thread_routine(void *arg) { TRAC_INFO("Health Monitor Thread Started ... " ); } // Function Specification // // Name: FFDC_thread_routine // // Description: // // End Function Specification void FFDC_thread_routine(void *arg) { TRAC_INFO("FFDC Thread Started ... " ); } // Function Specification // // Name: get_core_info // // Description: // // End Function Specification void get_core_info() { //uintt64_t l_deconfigured_cores; uint32_t l_deconfigured_cores; uint32_t l_configured_cores; //rc = _getscom( PMC_CORE_DECONFIGURATION_REG, &l_deconfigured_cores, SCOM_TIMEOUT ); l_deconfigured_cores = in32(PMC_CORE_DECONFIGURATION_REG); PROC_DEBUG( "Deconfigured cores in the chip [0x%x]\n", l_deconfigured_cores); l_configured_cores = ~l_deconfigured_cores & ALL_CORES_MASK; PROC_DEBUG( "Configured cores in the chip [0x%x]\n", l_configured_cores); return; } // Function Specification // // Name: main_thread_routine // // Description: This thread currently just loops as the lowest priority thread, handling // the lowest priority tasks. // // End Function Specification void main_thread_routine(void *private) { TRAC_INFO("Main Thread Started ... " ); errlHndl_t l_errl = NULL; SsxSemaphore l_appletComplete; uint8_t l_status = 0; uint32_t l_rc = 0 ; int l_ssxrc = 0; // Start the critical 250uS timer //ssx_timer_schedule(&timer, 1, TIMER_INTERVAL); // Initialize applet semaphore l_ssxrc = ssx_semaphore_create(&l_appletComplete, 0, 1); // Initialize APSS #ifdef OCC_ALONE_SIMICS l_rc = runApplet(OCC_APLT_APSS_INIT, // Applet enum Name NULL, // Applet arguments TRUE, // Blocking call? &l_appletComplete, // Applet finished semaphore &l_errl, // error log handle &l_status); // status from applet manager #endif if( NULL != l_errl ) { TRAC_ERR("APSS Init failed! (retrying) ErrLog[%p]", l_errl ); setErrlSevToInfo(l_errl); // commit & delete commitErrl( &l_errl ); l_rc = runApplet(OCC_APLT_APSS_INIT, // Applet enum Name NULL, // Applet arguments TRUE, // Blocking call? &l_appletComplete, // Applet finished semaphore &l_errl, // error log handle &l_status); // status from applet manager if( NULL != l_errl ) { TRAC_ERR("APSS Init failed again! (OCC will be reset)ErrLog[%p]", l_errl ); // commit & delete commitErrl( &l_errl ); //$TODO: Request OCC Reset } } while(1) { // Only trace the first XX times that this function loops if(g_k < 3) { g_k++; } // Sleep for 1000 before we run the loop again ssx_sleep(SSX_SECONDS(5)); } } // Function Specification // // Name: main // // Description: Entry point for OCC execution // Currently initalizes our trace buffer along with creating threads // and timers for execution. Note that once main runs ssx_start_threads, // we never return as the SSX kernel takes over. // // End Function Specification int main(int argc, char **argv) { // Initialize stdout so we can do printf from within simics env simics_stdout_create(&simics_stdout); simics_stderr_create(&simics_stderr); stdout = (FILE *)(&simics_stdout); stderr = (FILE *)(&simics_stderr); ssxout = (FILE *)(&simics_stdout); TRAC_INFO("Inside OCC Main"); // Initialize SSX Stacks (note that this also reinitializes the time base to 0) ssx_initialize((SsxAddress)noncritical_stack, NONCRITICAL_STACK_SIZE, (SsxAddress)critical_stack, CRITICAL_STACK_SIZE, 0); // Create Threads ssx_thread_create(&main_thread, main_thread_routine, (void *)0, (SsxAddress)main_thread_stack, THREAD_STACK_SIZE, 1); // Make Threads runnable ssx_thread_resume(&main_thread); errlHndl_t l_errl = NULL; //Initialize the thread scheduler l_errl = initThreadScheduler(); if( l_errl ) { // Trace and commit error TRAC_ERR("init thread Scheduler failure"); // commit log // NOTE: log should be deleted by reader mechanism commitErrl( &l_errl ); } // lets map mainstore to oci space only once // NOTE: This will stay mapped for remainder of occ life // TODO: This sounds like a temporary solution and may // end up moving to simics environment setup // TODO: This map needs to be unmapped after done accessing // main memory for the OCC initialization. Ppc405MmuMap pba_mmu_map; int l_ssxrc1 = ppc405_mmu_map( 0, //Mainstore address 0x0 0, //OCI address 0x0 1048576, //Max size = 1 Mb 0, // 0, //no TLBIE permissions only need to read &pba_mmu_map ); if ( l_ssxrc1 != SSX_OK ) { tracDesc_t l_trace = NULL; TRAC_ERR("mmu map failure SsxRc[0x%08X]", -l_ssxrc1 ); /* * @errortype * @moduleid MAIN_MID * @reasoncode SSX_GENERIC_FAILURE * @userdata1 pore_flex_schedule return code * @userdata4 ERC_MMU_MAP_FAILURE * @devdesc Failure mapping OCI space */ l_errl = createErrl( MAIN_MID, //modId SSX_GENERIC_FAILURE, //reasoncode ERC_MMU_MAP_FAILURE, //Extended reason code ERRL_SEV_UNRECOVERABLE, //Severity l_trace, //Trace Buf DEFAULT_TRACE_SIZE, //Trace Size l_ssxrc1, //userdata1 0 //userdata2 ); // Callout firmware addCalloutToErrl(l_errl, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_FIRMWARE, ERRL_CALLOUT_PRIORITY_HIGH); // commit log commitErrl( &l_errl ); // TODO request a reset of OCC since applet manager will // be toast without this working correctly } //Initialize the Applet Manager l_errl = initAppletManager(); if( l_errl ) { // Trace and commit error TRAC_ERR("init Applet Manager failure"); // commit log commitErrl( &l_errl ); // TODO: request a reset of OCC since applet manager will // be toast without this working correctly } //Initialize structures for collecting core data. //It needs to run before RTLoop start. proc_core_init(); get_core_info(); // Initialize Realtime Loop Timer Interrupt rtl_ocb_init(); // Enter SSX Kernel ssx_start_threads(); return 0; } <|start_filename|>src/occ_gpe0/firdata/fsi.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ/firdata/fsi.H $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* Interfaces to read/write FSI registers */ #include <scom_trgt.h> /** * @brief Read a FSI register. * @param i_trgt Chip/unit to read from. * @param i_addr FSI address to read, relative to slave's base address. * @param o_val Returned value. * @return Non-SUCCESS if an internal function fails. SUCCESS otherwise. */ int32_t getfsi( SCOM_Trgt_t* i_trgt, uint32_t i_addr, uint32_t * o_val ); /** * @brief Write a FSI register. * @param i_trgt Chip/unit to write to. * @param i_addr FSI address to write, relative to slave's base address. * @param o_val Value to write. * @return Non-SUCCESS if an internal function fails. SUCCESS otherwise. */ int32_t putfsi( SCOM_Trgt_t* i_trgt, uint32_t i_addr, uint32_t i_val ); <|start_filename|>src/ssx/ssx/ssx_macros.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_macros.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SSX_MACROS_H__ #define __SSX_MACROS_H__ /// \file ssx_macros.h /// \brief Boilerplate macros for SSX /// This macro encapsulates error handling boilerplate for code that uses the /// SSX API-type error handling, for errors that do not occur in critical /// sections. #define SSX_ERROR(code) \ do { \ if (SSX_ERROR_PANIC) { \ SSX_PANIC(code); \ } else { \ return -(code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the SSX API /// functions, for errors that do not occur in critical sections. #define SSX_ERROR_IF(condition, code) \ do { \ if (condition) { \ SSX_ERROR(code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the SSX API /// functions, for errors that do not occur in critical sections and always /// force a kernel panic, indicating a kernel or API bug. #define SSX_PANIC_IF(condition, code) \ do { \ if (condition) { \ SSX_PANIC(code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the SSX API /// functions, for errors that do not occur in critical sections. /// The error handling will only be enabled when SSX_ERROR_CHECK_API /// is enabled. #define SSX_ERROR_IF_CHECK_API(condition, code) \ do { \ if (SSX_ERROR_CHECK_API) { \ SSX_ERROR_IF(condition, code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the SSX API /// functions, for errors that occur in critical sections. #define SSX_ERROR_IF_CRITICAL(condition, code, context) \ do { \ if (condition) { \ if (SSX_ERROR_PANIC) { \ SSX_PANIC(code); \ ssx_critical_section_exit(context); \ } else { \ ssx_critical_section_exit(context); \ return -(code); \ } \ } \ } while (0) /// This is a general macro for errors that require cleanup before returning /// the error code. #define SSX_ERROR_IF_CLEANUP(condition, code, cleanup) \ do { \ if (condition) { \ if (SSX_ERROR_PANIC) { \ SSX_PANIC(code); \ cleanup; \ } else { \ cleanup; \ return -(code); \ } \ } \ } while (0) /// Most SSX APIs can not be called from critical interrupt contexts. #define SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT() \ SSX_ERROR_IF(__ssx_kernel_context_critical_interrupt(), \ SSX_ILLEGAL_CONTEXT_CRITICAL_INTERRUPT) /// Some SSX APIs can only be called from thread contexts - these are APIs /// that threads call on 'themselves'. #define SSX_ERROR_UNLESS_THREAD_CONTEXT() \ SSX_ERROR_IF(!__ssx_kernel_context_thread(), \ SSX_ILLEGAL_CONTEXT_THREAD_CONTEXT) /// Some SSX APIs must be called from an interrupt context only. #define SSX_ERROR_UNLESS_ANY_INTERRUPT_CONTEXT() \ SSX_ERROR_IF(!__ssx_kernel_context_any_interrupt(), \ SSX_ILLEGAL_CONTEXT_INTERRUPT_CONTEXT) #endif /* __SSX_MACROS_H__ */ <|start_filename|>src/occ_405/thread/chom.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/thread/chom.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _CHOM_H #define _CHOM_H #include <occ_common.h> #include <trac_interface.h> #include <apss.h> #define CHOM_GEN_LOG_PERIODIC_TIME 86400 // seconds in a day #define CHOM_VERSION 0x02 // Max size of chom data log #define CHOM_LOG_DATA_MAX 3072 // Max number of memory bandwidth CHOM sensors #define MAX_NUM_MEMORY_SENSORS 32 // Max number of procs Call Home will get data for #define CHOM_MAX_OCCS 4 // Max number of error history entries to add to call home log #define CHOM_MAX_ERRH_ENTRIES 4 // List of call home sensors (Max 126) enum { // Node total power (DC) CHOMPWR = 0, // APSS Channels CHOMPWRAPSSCH0, CHOMPWRAPSSCH1, CHOMPWRAPSSCH2, CHOMPWRAPSSCH3, CHOMPWRAPSSCH4, CHOMPWRAPSSCH5, CHOMPWRAPSSCH6, CHOMPWRAPSSCH7, CHOMPWRAPSSCH8, CHOMPWRAPSSCH9, CHOMPWRAPSSCH10, CHOMPWRAPSSCH11, CHOMPWRAPSSCH12, CHOMPWRAPSSCH13, CHOMPWRAPSSCH14, CHOMPWRAPSSCH15, // Processor frequency CHOMFREQP0, CHOMFREQP1, CHOMFREQP2, CHOMFREQP3, // Processor utilization sensor CHOMUTILP0, CHOMUTILP1, CHOMUTILP2, CHOMUTILP3, // Proc temperatures across all nodes CHOMTEMPPROC0, CHOMTEMPPROC1, CHOMTEMPPROC2, CHOMTEMPPROC3, // Centaur temperature for all Centaurs in the node CHOMTEMPCENTP0, CHOMTEMPCENTP1, CHOMTEMPCENTP2, CHOMTEMPCENTP3, // Dimm temperature for all Dimms in the node CHOMTEMPDIMMP0, CHOMTEMPDIMMP1, CHOMTEMPDIMMP2, CHOMTEMPDIMMP3, // VRM VDD temperature per proc CHOMTEMPVDDP0, CHOMTEMPVDDP1, CHOMTEMPVDDP2, CHOMTEMPVDDP3, // Instructions per second sensor CHOMIPS, // Memory bandwidth for process memory controller CHOMBWP0M0, CHOMBWP0M1, CHOMBWP0M2, CHOMBWP0M3, CHOMBWP0M4, CHOMBWP0M5, CHOMBWP0M6, CHOMBWP0M7, CHOMBWP1M0, CHOMBWP1M1, CHOMBWP1M2, CHOMBWP1M3, CHOMBWP1M4, CHOMBWP1M5, CHOMBWP1M6, CHOMBWP1M7, CHOMBWP2M0, CHOMBWP2M1, CHOMBWP2M2, CHOMBWP2M3, CHOMBWP2M4, CHOMBWP2M5, CHOMBWP2M6, CHOMBWP2M7, CHOMBWP3M0, CHOMBWP3M1, CHOMBWP3M2, CHOMBWP3M3, CHOMBWP3M4, CHOMBWP3M5, CHOMBWP3M6, CHOMBWP3M7, // The number of chom sensors reported CHOM_NUM_OF_SENSORS }; enum chom_supported_modes { CHOM_MODE_NOMINAL, CHOM_MODE_SPS, CHOM_MODE_DPS, CHOM_MODE_DPS_MP, CHOM_MODE_FFO, CHOM_MODE_NOM_PERF, CHOM_MODE_MAX_PERF, CHOM_MODE_FMF, // number of modes required to run Call home NUM_CHOM_MODES }; // Call home sensor Structure struct ChomSensor { uint16_t sample; // last sample value during the polling period uint16_t sampleMin; // min sample value recorded during polling period uint16_t sampleMax; // max sample value recorded during polling period uint16_t average; // average sample value during polling period uint32_t accumulator; // accumulator register to computer the average } __attribute__ ((__packed__)); typedef struct ChomSensor ChomSensor_t; // Power mode structure struct ChomPwrMode { uint8_t mode; // OCC power mode uint32_t numOfSamples; // Number of times samples were polled while in this mode }__attribute__ ((__packed__)); typedef struct ChomPwrMode ChomPwrMode_t; // Call home data structure struct ChomNodeData { uint32_t eyecatcher; // "CHOM" will mark the beginning of the data uint8_t version; // version of call home data being reported uint8_t curPwrMode; // the current power mode at the time of the polling event uint32_t totalTime; // duration of the polling period uint8_t modeInLog; // the number of different power mode in the polling period uint8_t channelFuncIds[MAX_APSS_ADC_CHANNELS]; uint16_t numSensors; // the number of sensors for which call home data was collected // error history counts. Only collect on up to 3 slaves, excluding master error_history_count_t errhCounts[CHOM_MAX_OCCS-1][CHOM_MAX_ERRH_ENTRIES]; uint32_t fClipHist[CHOM_MAX_OCCS-1]; } __attribute__ ((__packed__)); typedef struct ChomNodeData ChomNodeData_t; // Call home sensor data struct ChomSensorData { ChomPwrMode_t pwrMode; ChomSensor_t sensor[CHOM_NUM_OF_SENSORS]; }__attribute__ ((__packed__)); typedef struct ChomSensorData ChomSensorData_t; // Call home log data struct ChomLogData { ChomNodeData_t nodeData; // general node data ChomSensorData_t sensorData[2]; // sensors data (current and previous power mode) }__attribute__ ((__packed__)); typedef struct ChomLogData ChomLogData_t; extern uint32_t g_chom_gen_periodic_log_timer; extern ChomLogData_t * g_chom; extern uint8_t g_chom_force; void chom_data_init(); void chom_update_sensors(); void chom_gen_periodic_log(); void chom_data_reset(); void chom_force_gen_log(); void chom_main(); #endif //_CHOM_H <|start_filename|>src/lib/occlib/ipc_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/occlib/ipc_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ipc_init.c /// \brief Implementation of IPC (InterProcessor Communication) routines for /// Setting up the IPC function tables, messages and message queues. /// /// NOTE: The functions that these interfaces peform can all be done statically. /// This code will not be included in an image if none of the functions are /// referenced. #include "ipc_api.h" #include "ipc_ping.h" /////////////////////////////////////////////////////////////////////////////// /// Associate an IPC function ID with a handler function /// int ipc_set_handler(uint32_t function_id, ipc_msg_handler_t handler, void* callback_arg) { ipc_func_table_entry_t* func_table; uint32_t table_limit; int rc = IPC_RC_SUCCESS; ipc_func_id_t func_id = {{0}}; do { func_id.word32 = function_id; //setup for multi-target commands if(func_id.multi_target_flag) { table_limit = IPC_MT_NUM_FUNCIDS; func_table = G_ipc_mt_handlers; } //setup for single-target commands else { //make sure the function id targets this processor if(func_id.target_id != OCCHW_INST_ID_SELF) { rc = IPC_RC_INVALID_TARGET_ID; break; } table_limit = IPC_ST_NUM_FUNCIDS; func_table = G_ipc_st_handlers; } //make sure the function id is valid if((func_id.table_index >= table_limit) || !func_id.valid_flag) { rc = IPC_RC_INVALID_FUNC_ID; break; } if(!handler) { rc = IPC_RC_INVALID_ARG; break; } func_table[func_id.table_index].handler = handler; func_table[func_id.table_index].arg = callback_arg; } while(0); return rc; } /////////////////////////////////////////////////////////////////////////////// /// Initialize an IPC command message /// void ipc_init_msg(ipc_msg_t* msg, uint32_t func_id, ipc_msg_handler_t resp_callback, void* callback_arg) { KERN_DEQUE_ELEMENT_CREATE(&msg->node); msg->func_id.word32 = func_id; msg->ipc_rc = IPC_RC_SUCCESS; msg->resp_callback = resp_callback; msg->callback_arg = callback_arg; #ifdef GPE_IPC_TIMERS msg->begin_time = 0; msg->end_time = 0; #endif } /////////////////////////////////////////////////////////////////////////////// /// Initialize an IPC message queue. /// void ipc_init_msgq(ipc_msgq_t* msgq) { KERN_DEQUE_SENTINEL_CREATE(&msgq->msg_head); //set the initial count to 0 with no max count KERN_SEMAPHORE_CREATE(&msgq->msg_sem, 0, 0); } /////////////////////////////////////////////////////////////////////////////// /// Initialize an IPC message and associate it with an IPC message queue /// void ipc_init_msgq_msg(ipc_msg_t* msg, uint32_t func_id, ipc_msgq_t* msgq) { ipc_init_msg(msg, func_id, ipc_msgq_handler, msgq); } /////////////////////////////////////////////////////////////////////////////// /// Initialize an IPC ping command message /// #ifdef IPC_ENABLE_PING int ipc_ping_cmd_init(ipc_ping_cmd_t* ping_cmd) { int rc; do { //initialize the message ipc_init_msg(&ping_cmd->msg, IPC_MT_PING, ipc_ping_response, 0); //initialize the semaphore count to 0 and set the max count to 1 rc = KERN_SEMAPHORE_CREATE(&ping_cmd->sem, 0, 1); if(rc) { break; } } while(0); return rc; } #endif /*IPC_ENABLE_PING*/ <|start_filename|>src/include/p9_memmap_occ_sram.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/p9_memmap_occ_sram.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #if !defined(__P9_MEMMAP_OCC_SRAM_H__) #define __P9_MEMMAP_OCC_SRAM_H__ #define OCC_SRAM_BASE_ADDR 0xFFF00000 #define GPE_DEBUG_PTRS_OFFSET 0x180 #define PGPE_DEBUG_PTRS_OFFSET 0x200 #define SGPE_DEBUG_PTRS_OFFSET 0x200 #define PK_TRACE_PTR_OFFSET 0x04 #define PK_TRACE_SIZE_OFFSET 0x08 #define OCC_SRAM_IPC_REGION_SIZE (4 * 1024) #define OCC_SRAM_GPE0_REGION_SIZE (60 * 1024) #define OCC_SRAM_GPE1_REGION_SIZE (64 * 1024) #define GPE0_SRAM_BASE_ADDR OCC_SRAM_BASE_ADDR + OCC_SRAM_IPC_REGION_SIZE #define GPE1_SRAM_BASE_ADDR GPE0_SRAM_BASE_ADDR + OCC_SRAM_GPE0_REGION_SIZE #endif <|start_filename|>src/ppe/tools/ppetracepp/ppe2fsp.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/tools/ppetracepp/ppe2fsp.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk_trace.h" #include "ppe2fsp.h" #include "trac_interface.h" #include <arpa/inet.h> #include <string.h> #include <stdint.h> #define TRACE_BUF_VERSION 0x01 /*!< Trace buffer version */ #define TRACE_FIELDTRACE 0x4654 /*!< Field Trace - "FT" */ #define TRACE_FIELDBIN 0x4644 /*!< Binary Field Trace - "FD" */ #define TRAC_TIME_REAL 0 // upper 32 = seconds, lower 32 = nanoseconds #define TRAC_TIME_50MHZ 1 #define TRAC_TIME_200MHZ 2 #define TRAC_TIME_167MHZ 3 // 166666667Hz typedef struct { trace_entry_stamp_t stamp; trace_entry_head_t head; union { uint8_t data[PK_TRACE_MAX_BINARY + 1]; //add 1 byte for padding uint32_t parms[PK_TRACE_MAX_PARMS]; }; uint32_t size; }largest_fsp_entry_t; typedef struct { union { uint8_t binary_data[PK_TRACE_MAX_BINARY + 1]; struct { uint8_t rsvd[(PK_TRACE_MAX_BINARY + 1) - (PK_TRACE_MAX_PARMS * sizeof(uint32_t))]; uint32_t parms[PK_TRACE_MAX_PARMS]; }; }; PkTraceEntryFooter footer; }LargestPpeEntry; //convert a ppe timestamp to an fsp trace timestamp uint64_t ppe2fsp_time(uint64_t ppe_time, uint32_t hz) { uint32_t seconds; uint32_t remainder; uint32_t nseconds; //convert from ppe ticks to seconds and nanoseconds seconds = ppe_time / hz; remainder = ppe_time - (((uint64_t)seconds) * hz); nseconds = (((uint64_t)remainder) * 1000000000) / hz; return (((uint64_t)seconds) << 32) | nseconds; } //Writes an fsp trace entry to the fsp trace buffer fsp_put_entry(trace_buf_head_t* tb, largest_fsp_entry_t* fte, size_t entry_size, uint32_t bytes_left) { char* buffer = ((char*)tb) + sizeof(trace_buf_head_t); char* tb_start; char* fte_start; uint32_t copy_bytes; if(entry_size <= bytes_left) { tb_start = buffer + bytes_left - entry_size; fte_start = (char*)fte; copy_bytes = entry_size; } else { tb_start = buffer; fte_start = ((char*)fte) + (entry_size - bytes_left); copy_bytes = bytes_left; } memcpy(tb_start, fte_start, copy_bytes); } //convert a ppe trace entry to an fsp trace entry size_t pte2fte(PkTraceBuffer* ptb, LargestPpeEntry* pte, size_t pte_size, largest_fsp_entry_t* fte, uint64_t ppe_time64) { size_t entry_size; PkTraceGeneric* pte_footer = &pte->footer.generic; uint32_t format; uint32_t hash32; uint32_t hash32_partial; uint32_t* parm_start; uint32_t parm_bytes; uint64_t fsp_time64; //convert the ppe trace time to an fsp trace time fsp_time64 = ppe2fsp_time(ppe_time64, ntohl(ptb->hz)); //fill in the 64 bit timestamp fte->stamp.tbh = htonl((uint32_t)(fsp_time64 >> 32)); fte->stamp.tbl = htonl((uint32_t)(fsp_time64 & 0x00000000ffffffffull)); //use the ppe instance id as the thread id. fte->stamp.tid = htonl((uint32_t)ntohs(ptb->instance_id)); //merge the hash prefix and the string_id fields together for a 32 bit hash value hash32 = ((uint32_t)ntohs(ptb->hash_prefix)) << 16; hash32 |= pte_footer->string_id; fte->head.hash = htonl(hash32); //generate the 32bit hash value for a partial trace entry in case it's needed hash32_partial = ((uint32_t)ntohs(ptb->hash_prefix)) << 16; hash32_partial |= ntohs(ptb->partial_trace_hash); //set the line number to 1 fte->head.line = htonl(1); //determine the FSP trace format format = PK_GET_TRACE_FORMAT(pte_footer->time_format.word32); if(format == PK_TRACE_FORMAT_BINARY) { fte->head.tag = htons(TRACE_FIELDBIN); } else { fte->head.tag = htons(TRACE_FIELDTRACE); } parm_start = (uint32_t*)(((char*)pte) + (sizeof(LargestPpeEntry) - pte_size)); //fill in the parameters/binary data and size at the end switch(format) { case PK_TRACE_FORMAT_TINY: //one or 0 parameters entry_size = sizeof(trace_entry_stamp_t) + sizeof(trace_entry_head_t) + sizeof(uint32_t); fte->parms[0] = htonl((uint32_t)(pte_footer->parm16)); fte->head.length = htons(sizeof(uint32_t)); parm_bytes = 0; break; case PK_TRACE_FORMAT_BIG: //1 - 4 parameters // //If the trace entry data is incomplete (not all parm data //had been written at the time the trace was captured) then //we will write a trace to the fsp buffer that says //"PARTIAL TRACE ENTRY. HASH_ID = %d" if(pte_footer->complete) { parm_bytes = pte_footer->bytes_or_parms_count * sizeof(uint32_t); fte->head.length = htons(parm_bytes + sizeof(uint32_t)); entry_size = sizeof(trace_entry_stamp_t) + sizeof(trace_entry_head_t) + parm_bytes + sizeof(uint32_t); } else { parm_bytes = 0; entry_size = sizeof(trace_entry_stamp_t) + sizeof(trace_entry_head_t) + sizeof(uint32_t); fte->parms[0] = fte->head.hash; //already corrected for endianess fte->head.hash = htonl(hash32_partial); fte->head.length = htons(sizeof(uint32_t)); } break; case PK_TRACE_FORMAT_BINARY: //If the trace entry data is incomplete (not all parm data //had been written at the time the trace was captured) then //we will write a trace to the fsp buffer that says //"PARTIAL TRACE ENTRY. HASH_ID = %d" if(pte_footer->complete) { parm_bytes = pte_footer->bytes_or_parms_count; fte->head.length = htons((uint16_t)parm_bytes); entry_size = sizeof(trace_entry_stamp_t) + sizeof(trace_entry_head_t) + parm_bytes; //pad to 4 byte boundary entry_size = (entry_size + 3) & ~3; } else { parm_bytes = 0; entry_size = sizeof(trace_entry_stamp_t) + sizeof(trace_entry_head_t) + sizeof(uint32_t); fte->parms[0] = fte->head.hash; fte->head.hash = htonl(hash32_partial); fte->head.length = htons(sizeof(uint32_t)); fte->head.tag = htons(TRACE_FIELDTRACE); } break; default: entry_size = 0; parm_bytes = 0; break; } //copy parameter bytes to the fsp entry if necessary if(parm_bytes) { memcpy(fte->data, parm_start, parm_bytes); } //add the entry size to the end if(entry_size) { uint32_t new_entry_size = entry_size + sizeof(uint32_t); *((uint32_t*)(((char*)fte) + entry_size)) = htonl(new_entry_size); entry_size = new_entry_size; } return entry_size; } //retrieve a ppe trace entry from a ppe trace buffer size_t ppe_get_entry(PkTraceBuffer* tb, uint32_t offset, LargestPpeEntry* pte) { uint32_t mask = ntohs(tb->size) - 1; PkTraceEntryFooter* footer; size_t entry_size; size_t parm_size; char* dest = (char*)pte; uint32_t format; uint32_t start_index; uint32_t bytes_left; uint32_t bytes_to_copy; //Find the footer in the circular buffer footer = (PkTraceEntryFooter*)(&tb->cb[(offset - sizeof(PkTraceEntryFooter)) & mask]); //always correct endianess for the time and string id words pte->footer.generic.time_format.word32 = ntohl(footer->generic.time_format.word32); pte->footer.generic.string_id = ntohs(footer->generic.string_id); //only need to byte swap the parm16 value if this is a tiny format pte->footer.generic.parm16 = footer->generic.parm16; //use footer data to determine the length of the binary data or parameters format = PK_GET_TRACE_FORMAT(pte->footer.generic.time_format.word32); switch(format) { case PK_TRACE_FORMAT_TINY: pte->footer.generic.parm16 = ntohs(pte->footer.generic.parm16); parm_size = 0; entry_size = sizeof(PkTraceEntryFooter); break; case PK_TRACE_FORMAT_BIG: parm_size = pte->footer.generic.bytes_or_parms_count * sizeof(uint32_t); entry_size = sizeof(PkTraceEntryFooter); break; case PK_TRACE_FORMAT_BINARY: parm_size = pte->footer.generic.bytes_or_parms_count; entry_size = sizeof(PkTraceEntryFooter); break; default: entry_size = 0; parm_size = 0; break; } //pad to 8 byte boundary parm_size = (parm_size + 7) & ~0x00000007ul; //add the parameter size to the total entry size entry_size += parm_size; //copy the entry from the circular buffer to pte start_index = (offset - entry_size) & mask; bytes_left = ntohs(tb->size) - start_index; //only copy up to the end of the circular buffer if(parm_size < bytes_left) { bytes_to_copy = parm_size; } else { bytes_to_copy = bytes_left; } dest += sizeof(LargestPpeEntry) - entry_size; memcpy(dest, &tb->cb[start_index], bytes_to_copy); //now copy the rest of the data starting from the beginning of the //circular buffer. if(bytes_to_copy < parm_size) { memcpy(dest + bytes_to_copy, tb->cb, parm_size - bytes_to_copy); } //return the size of the entry return entry_size; } //convert a ppe trace buffer to an fsp trace buffer int ppe2fsp(void* in, unsigned long in_size, void* out, unsigned long* io_size) { PkTraceBuffer* ptb = (PkTraceBuffer*)in; trace_buf_head_t* ftb = (trace_buf_head_t*)out; uint32_t ppe_bytes_left; uint32_t fsp_bytes_left; int rc = 0; uint32_t ptb_offset; PkTraceEntryFooter* ptb_te; uint64_t ppe_time64; uint32_t fte_size, pte_size; uint32_t fsp_te_count = 0; uint32_t time_diff32, prev_time32, new_time32; PkTraceGeneric* pte_footer; largest_fsp_entry_t fte; LargestPpeEntry pte; uint64_t time_adj64; do { if(!ptb || !ftb || !io_size) { rc = P2F_NULL_POINTER; break; } if(ntohs(ptb->version) != PK_TRACE_VERSION) { rc = P2F_INVALID_VERSION; break; } //check that the input buffer is large enough to have a ppe trace buffer if(in_size < (((uint32_t)(&ptb->cb[0])) - (uint32_t)(ptb))) { rc = P2F_INPUT_BUFFER_TOO_SMALL; break; } //initialize some locals fsp_bytes_left = *io_size - sizeof(trace_buf_head_t); ppe_bytes_left = ntohs(ptb->size); ptb_offset = ntohl(ptb->state.offset); if(htonl(1) == 1) { time_adj64 = ptb->time_adj64; } else { time_adj64 = ntohl((uint32_t)(ptb->time_adj64 >> 32)); time_adj64 |= ((uint64_t)(ntohl((uint32_t)(ptb->time_adj64 & 0x00000000ffffffff)))) << 32; } //make sure the ppe buffer size is a power of two if((ppe_bytes_left - 1) & ppe_bytes_left) { //size is not a power of two rc = P2F_INVALID_INPUT_SIZE; break; } //The ppe bytes field should always be a multiple of 8 if(ptb_offset & 0x7) { rc = P2F_INVALID_PPE_OFFSET; break; } //make sure there is enough room for the fsp header if(*io_size < sizeof(trace_buf_head_t)) { rc = P2F_OUTPUT_BUFFER_TOO_SMALL; break; } //initialize the fsp header ftb->ver = TRACE_BUF_VERSION; ftb->hdr_len = sizeof(trace_buf_head_t); ftb->time_flg = TRAC_TIME_REAL; ftb->endian_flg = 'B'; //big endian memcpy(ftb->comp, ptb->image_str, sizeof(ftb->comp)); ftb->times_wrap = htonl(1); ftb->size = htonl(sizeof(trace_buf_head_t) + sizeof(uint32_t)); ftb->next_free = htonl(sizeof(trace_buf_head_t)); ftb->extracted = htonl(0); ftb->te_count = htonl(0); //find the latest timestamp so that we can work back from there ppe_time64 = ((uint64_t)(ntohl(ptb->state.tbu32) & 0xefffffff)) << 32; pte_size = ppe_get_entry(ptb, ptb_offset, &pte); prev_time32 = PK_GET_TRACE_TIME(pte.footer.generic.time_format.word32); ppe_time64 |= prev_time32; //process all of the input bytes one trace entry at a time //from newest to oldest (backwards) until we run out of input bytes or //we run out of output space. while(1) { //check if we have enough data for a ppe footer if(ppe_bytes_left < sizeof(PkTraceEntryFooter)) { break; } //get the next ppe entry pte_size = ppe_get_entry(ptb, ptb_offset, &pte); //Stop if there are no more entries to retrieve from the ppe trace buffer if(!pte_size) { break; } pte_footer = &pte.footer.generic; //mark the entry as incomplete if we didn't have enough data //for the entire entry if(pte_size > ppe_bytes_left) { pte_footer->complete = 0; ppe_bytes_left = 0; } else { ppe_bytes_left -= pte_size; ptb_offset -= pte_size; } //Calculate the 64 bit timestamp for this entry.... //On PPE, getting the timestamp is not done atomically with writing //the entry to the buffer. This means that an entry with an older //timestamp could possibly be added to the buffer after an entry //with a newer timestamp. Detect this condition by checking if the //time difference is bigger than the max difference. The max //difference is enforced by the PPE having a trace added on a //shorter time boundary (using a timer). new_time32 = PK_GET_TRACE_TIME(pte_footer->time_format.word32); time_diff32 = prev_time32 - new_time32; if(time_diff32 > ntohl(ptb->max_time_change)) { time_diff32 = new_time32 - prev_time32; ppe_time64 += time_diff32; } else { ppe_time64 -= time_diff32; } //save off the lower 32bit timestamp for the next iteration prev_time32 = new_time32; //convert the ppe trace entry to an fsp trace entry fte_size = pte2fte(ptb, &pte, pte_size, &fte, ppe_time64 + time_adj64); //fit as much of the entry into the fsp trace buffer as possible fsp_put_entry(ftb, &fte, fte_size, fsp_bytes_left); //update the fsp trace entry count fsp_te_count++; //stop if there is no more room left in the fsp trace buffer if(fte_size >= fsp_bytes_left) { fsp_bytes_left = 0; ftb->times_wrap = htonl(1); break; } else { fsp_bytes_left -= fte_size; } }//while(1) //shift the trace data up if there is space to do so if(fsp_bytes_left) { char* dest = ((char*)ftb) + sizeof(trace_buf_head_t); char* src = dest + fsp_bytes_left; size_t data_size = *io_size - sizeof(trace_buf_head_t) - fsp_bytes_left; memmove(dest, src, data_size); } //update the fsp header to reflect the true size and entry count ftb->te_count = htonl(fsp_te_count); //inform the caller of how many bytes were actually used *io_size -= fsp_bytes_left; //shrink the size field to what we actually ended up using ftb->size = htonl(*io_size); }while(0); return rc; } <|start_filename|>src/ssx/ppc405/ssx_port_types.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ssx_port_types.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SSX_PORT_TYPES_H__ #define __SSX_PORT_TYPES_H__ /// \file ssx_port_types.h /// \brief Type definitions required by the SSX port. /// /// \todo GCC provides a portable version of cntlzw called __builtin_clz(). /// We should make the SSX priority queues portable by using this facility. /// /// \todo I think that if more of the port-dependent types were moved here, we /// could break the circular dependencies in some of the header inclusion and /// simplify the way the SSX/port/chip headers are included. /// An SsxIrqId is an integer in the range of valid interrupts defined by the /// interrupt controller. typedef uint8_t SsxIrqId; /// SSX requires the port to define the type SsxThreadQueue, which is a /// priority queue (where 0 is the highest priority). This queue must be able /// to handle SSX_THREADS + 1 priorities (the last for the idle thread). The /// port must also define methods for clearing, insertion, deletion and min /// (with assumed legal priorities). The min operation returns SSX_THREADS if /// the queue is empty. (Or a queue could be initialized with the SSX_THREADS /// entry always present - SSX code never tries to delete the idle thread from /// a thread queue). /// /// These queues are used both for the run queue and the pending queue /// associated with every semaphore. /// /// On PPC405 with 32 threads (implied), this is a job for a uint32_t and /// cntlzw(). typedef uint32_t SsxThreadQueue; #endif /* __SSX_PORT_TYPES_H__ */ <|start_filename|>src/occ_405/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occ_405/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2015,2017 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG # This Makefile compiles all of the SSX code required for the P9 port # of SSX. See the "img_defs.mk" file in this directory. #Pull in the definitions that affect all makefiles for this image include img_defs.mk #Use tracepp instead of ppetracepp for 405 code include occ_defs.mk #Pull in object file names for the top directory include topfiles.mk SSX_MAKE_DIR := $(SSX_SRCDIR)/occhw OBJS := $(addprefix $(OBJDIR)/, $(TOP_OBJECTS)) OBJDIRS = $(sort $(dir ${OBJS})) SSXLIB := $(OBJDIR)/ssx/libssx.a COMMONLIB := $(OBJDIR)/common/libcommon.a OCCLIB := $(OBJDIR)/occlib/libocc.a PPC405LIB := $(OBJDIR)/ppc405lib/libppc405.a LINK_OBJS = $(OBJS) $(SSXLIB) $(COMMONLIB) $(OCCLIB) $(PPC405LIB) LINK_SCRIPT = $(addprefix $(OBJDIR)/, linkscript) LINK_CMD_SCRIPT = linkocc.cmd LDFLAGS += --oformat=elf32-powerpc -melf32ppc LIB_DIRS = -L$(OBJDIR) \ -L$(OBJDIR)/ssx \ -L$(OBJDIR)/ssx/ppc405 \ -L$(OBJDIR)/ssx/ppc32 \ -L$(OBJDIR)/commonlib \ -L$(OBJDIR)/occlib \ -L$(OBJDIR)/ppc405lib \ -L$(OBJDIR)/cmdh \ -L$(OBJDIR)/dcom \ -L$(OBJDIR)/dimm \ -L$(OBJDIR)/errl \ -L$(OBJDIR)/gpu \ -L$(OBJDIR)/lock \ -L$(OBJDIR)/pss \ -L$(OBJDIR)/rtls \ -L$(OBJDIR)/sensor \ -L$(OBJDIR)/thread \ -L$(OBJDIR)/timer \ -L$(OBJDIR)/trac \ -L$(OBJDIR)/amec \ -L$(OBJDIR)/dcom \ -L$(OBJDIR)/proc \ -L$(OBJDIR)/firdata \ -L$(OBJDIR)/cent \ -L$(OBJDIR)/mem \ -L$(OBJDIR)/wof \ -L$(OBJDIR)/pgpe #default target is to make a binary application image .PHONY : all all: $(PPETOOLS_OBJDIR)/ppetracepp $(OBJDIR)/$(IMAGE_NAME).bin $(OBJDIR)/$(IMAGE_NAME).dis #This removes all unecessary headers from the ELF executable $(OBJDIR)/$(IMAGE_NAME).bin $(OBJDIR)/$(IMAGE_NAME).dis: $(OBJDIR)/$(IMAGE_NAME).out $(OBJCOPY) -O binary $< $(OBJDIR)/$(IMAGE_NAME).bin $(OBJDUMP) -S $< > $(OBJDIR)/$(IMAGE_NAME).dis # Create a linked ELF executable and verify we aren't missing sensors $(OBJDIR)/$(IMAGE_NAME).out: $(PPETOOLS_OBJDIR)/tracepp $(LINK_OBJS) $(LINK_SCRIPT) $(LD) -e __ssx_boot -T$(LINK_SCRIPT) $(LDFLAGS) -Map $(OBJDIR)/$(IMAGE_NAME).map -Bstatic -o $(OBJDIR)/$(IMAGE_NAME).out $(LIB_DIRS) -lssx -locc -lppc405 -lcommon $(OCCTOOLS)/check-sensors.sh $(OBJDUMP) $(OBJDIR) $(PPETOOLS_OBJDIR)/ppetracepp: $(PPETOOLS_OBJDIR) g++ -O3 -w -g -I$(PPETRACEPP_DIR)/ $(PPETRACEPP_DIR)/ppetracepp.C -o $(PPETOOLS_OBJDIR)/ppetracepp $(PPETOOLS_OBJDIR): mkdir -p $(PPETOOLS_OBJDIR) #pass the link command file through the C preprocessor to evaluate macros and remove comments $(LINK_SCRIPT): $(LINK_CMD_SCRIPT) $(CPP) -E -x c -P $(DEFS) $(LINK_CMD_SCRIPT) -o $(LINK_SCRIPT) #Create an obj directory if needed $(LINK_OBJS) $(OBJS) $(OBJS:.o=.d): | $(OBJDIRS) $(OBJDIRS): mkdir -p $@ #Build the SSX kernel library $(SSXLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(SSX_MAKE_DIR) #Build the code that is common for all processors (PPE's and 405) $(COMMONLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(COMMONLIB_SRCDIR) #Build the code that is common for all OCC processors (GPEs and 405) $(OCCLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(OCCLIB_SRCDIR) #Build the library code that only works on the ppc405 $(PPC405LIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(PPC405LIB_SRCDIR) $(PPETOOLS_OBJDIR)/tracepp: (cd $(TRACEPP_DIR) && make) # collect all of the trace hash files for this image into a single trexStringFile .PHONY : tracehash tracehash: mkdir -p $(OBJDIR) $(THASH) -c -d $(OBJDIR) -s $(OBJDIR)/trexStringFile # load and run the 405 image in simics run: $(OBJDIR)/$(IMAGE_NAME).out $(SIMICS_WS)/simics \ -e '$$occ_405_binary_to_load=$(OBJDIR)/$(IMAGE_NAME).out' modelsetup.simics #clean out all generated files .PHONY : clean clean: rm -fr $(OBJDIR) #Add dependencies to header files ifneq ($(MAKECMDGOALS),clean) -include $(OBJS:.o=.d) endif <|start_filename|>src/occ_gpe1/pk_app_irq_table.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/pk_app_irq_table.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" EXTERNAL_IRQ_TABLE_START IRQ_HANDLER_DEFAULT //OCCHW_IRQ_DEBUGGER IRQ_HANDLER_DEFAULT //OCCHW_IRQ_TRACE_TRIGGER IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBA_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_SRT_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE0_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE1_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE2_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE3_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PPC405_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCB_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_SPIPSS_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_PPC405 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE2 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE3 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_MALF_ALERT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_ADU_MALF_ALERT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_EXTERNAL_TRAP IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IVRM_PVREF_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_TIMER0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_TIMER1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_AVS_SLAVE0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_AVS_SLAVE1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI0_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI1_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI2_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI3_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI4_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_ADCFSM_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_RESERVED_31 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBAX_OCC_SEND IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBAX_OCC_PUSH0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBAX_OCC_PUSH1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBA_BCDE_ATTN IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBA_BCUE_ATTN IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM0_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM0_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM1_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM1_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM2_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM2_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM3_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM3_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE0_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE1_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE2_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE3_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE4_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE5_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE6_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE7_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_0A_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_0B_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_1A_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_1B_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PSSBRIDGE_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI0_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI1_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI2_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI3_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI4_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_RESERVED_63 EXTERNAL_IRQ_TABLE_END <|start_filename|>src/occBootLoader/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occBootLoader/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2011,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG include img_defs.mk include bootfiles.mk #******************************************************************************* # Variables #******************************************************************************* OBJECTS = $(addprefix $(OBJDIR)/, $(notdir ${BOOTLOADER_OBJECTS})) LINK_SCRIPT = $(OBJDIR)/linkscript EXECUTABLE = $(OBJDIR)/bootloader imageHdrScript = $(OBJDIR)/imageHdrScript imageHdrScript_CC = gcc #******************************************************************************* # Flags #******************************************************************************* DEFS += $(D) #******************************************************************************* # Compilation #******************************************************************************* .PHONY : all all: $(PPETOOLS_OBJDIR)/ppetracepp $(OBJDIR) ${OBJECTS} ${imageHdrScript} $(CPP) -P $(DEFS) < linkboot.cmd > $(LINK_SCRIPT) $(LD) ${OBJECTS} -T$(LINK_SCRIPT) $(LDFLAGS) -zmuldefs -Map $(EXECUTABLE).map -melf32ppc --oformat=elf32-powerpc -Bstatic -o $(EXECUTABLE).out -L$(OBJDIR) $(OBJCOPY) -I elf32-powerpc -O binary $(EXECUTABLE).out $(EXECUTABLE).bin $(OBJDUMP) -d $(EXECUTABLE).out > $(EXECUTABLE).dis $(PPETOOLS_OBJDIR)/ppetracepp: $(PPETOOLS_OBJDIR) g++ -O3 -w -g -I$(PPETRACEPP_DIR)/ $(PPETRACEPP_DIR)/ppetracepp.C -o $(PPETOOLS_OBJDIR)/ppetracepp $(PPETOOLS_OBJDIR): mkdir -p $(PPETOOLS_OBJDIR) $(OBJDIR)/imageHdrScript: imageHdrScript.c $(imageHdrScript_CC) -g $(LDFLAGS) -I. -I$(OCC405_INCLDIR)/ -I$(OCC405_SRCDIR)/ imageHdrScript.c -o $(OBJDIR)/imageHdrScript $(OBJDIR)/occbuildname.o: $(TCC) $(CFLAGS) $(DEFS) -o $@ $(OCC405_SRCDIR)/occbuildname.c $(OBJDIR)/savegpr.o: $(TCPP) $(CFLAGS) $(DEFS) -o $@ $(SSX_SRCDIR)/ppc32/savegpr.S $(OBJDIR): mkdir -p $(OBJDIR) #******************************************************************************* # Clean #******************************************************************************* .PHONY : clean clean: rm -rf $(OBJDIR) <|start_filename|>src/occ_gpe0/firdata/pnor_mboxdd.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/pnor_mboxdd.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PNOR_MBOX_H #define __PNOR_MBOX_H //NOTE: Protocol Definition is here: // https://github.com/openbmc/mboxbridge/blob/master/Documentation/mbox_protocol.md #include <ast_mboxdd.h> /** @file pnor_mbox.h * @brief Provides the interfaces to the PNOR via the * MBOX protocol */ typedef struct { astMbox_t iv_mbox; uint32_t iv_protocolVersion; //Block size is either 4k (V1) or BMC defined (V2) // the iv_blockShift parm is a representation of that size // as a power of 2. Most command and response args are specified // in some multiple of block size uint32_t iv_blockShift; uint32_t iv_flashSize; uint32_t iv_flashEraseSize; // Current Window bool iv_curWindowOpen; // Currently open bool iv_curWindowWrite; // Write vs Read window uint32_t iv_curWindowOffset; // Offset into flash uint32_t iv_curWindowSize; // Size uint32_t iv_curWindowLpcOffset; // Offset into LPC FW space // Legacy v1 protocol uint32_t iv_readWindowSize; uint32_t iv_writeWindowSize; } pnorMbox_t; /* * @brief Do base initialization of the MBOX functionality * * @parm[io] io_pnorMbox - Pointer to pnorMbox_t structure * * @return Error from operation */ errorHndl_t hwInit(pnorMbox_t* i_pnorMbox); /* * @brief Read data from the PNOR flash * * @param[in] Pointer to pnorMbox struct * @parm[in] i_addr PNOR flash Address to read * @parm[in] i_size Amount of data to read, in bytes. * @parm[out] o_data Buffer to read data into * * @return Error from operation */ errorHndl_t readFlash(pnorMbox_t* i_pnorMbox, uint32_t i_addr, uint32_t i_size, void* o_data); /** * @brief Write data to the PNOR flash * @param[in] Pointer to pnorMbox struct * @parm i_addr PNOR flash Address to write * @parm i_size Amount of data to write, in bytes. * @parm i_data Buffer containing data to write * * @return Error from operation */ errorHndl_t writeFlash(pnorMbox_t* i_pnorMbox, uint32_t i_addr, uint32_t i_size, void* i_data); /** * @brief Open a window on the BMC for PNOR accesses * if necessary and return adjusted LPC address and chunk size * @param[in] Pointer to pnorMbbox struct * @parm[in] i_isWrite Write or read window * @parm[in] i_reqAddr Requested flash offset * @parm[in] i_reqSize Requested size * @parm[out] o_lpcAddr LPC offset for the requested offset * @parm[out] o_chunkLen i_reqSize adjusted to fit in the window * * @return Error from operation */ errorHndl_t adjustMboxWindow(pnorMbox_t* i_pnorMbox, bool i_isWrite, uint32_t i_reqAddr, uint32_t i_reqSize, uint32_t *o_lpcAddr, uint32_t *o_chunkLen); /** * @brief Mark a range dirty in a write window * @param[in] Pointer to pnorMbox struct * @parm[in] i_addr Flash offset of the range * @parm[in] i_size Size of the range * * @return Error from operation */ errorHndl_t writeDirty(pnorMbox_t* i_pnorMbox, uint32_t i_addr, uint32_t i_size); /** * @brief Flush all pending dirty data to the flash * @param[in] Pointer to pnorMbox struct * @return Error from operation */ errorHndl_t writeFlush(pnorMbox_t* i_pnorMbox); #endif /* __PNOR_MBOX_H */ <|start_filename|>src/occ_405/gpu/gpu.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/gpu/gpu.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _GPU_H #define _GPU_H #include <occ_common.h> #include <trac_interface.h> #include <errl.h> #include <rtls.h> #include "gpu_structs.h" #define GPU_TICK (CURRENT_TICK % MAX_NUM_TICKS) // States for the GPU state machine (task_gpu_sm) typedef enum { GPU_STATE_RESET = 0x00, // Reset and initialize interface GPU_STATE_READ_TEMP = 0x10, // Read GPU core temperature GPU_STATE_READ_MEMORY_TEMP = 0x20, // Read GPU memory temperature GPU_STATE_CHECK_MEM_TEMP_CAPABLE = 0x30, // Read memory temperature capability GPU_STATE_CHECK_DRIVER_LOADED = 0x40, // Check if Driver loaded GPU_STATE_READ_PWR_LIMIT = 0x50, // Read Power Limits GPU_STATE_SET_PWR_LIMIT = 0x70, // Set Power Limit GPU_STATE_IDLE = 0xFE, // Ok to schedule new task GPU_STATE_NO_LOCK = 0xFF // Host owns, no communication allowed } gpuState_e; // States for the GPU reset state machine (gpu_reset_sm) typedef enum { GPU_RESET_STATE_NEW = 0x01, // new reset attempt GPU_RESET_STATE_INIT_BUS = 0x02, GPU_RESET_STATE_RESET_MASTER = 0x03, // Reset master GPU_RESET_STATE_RESET_SLAVE = 0x04, // Start of slave port 4 reset GPU_RESET_STATE_RESET_SLAVE_WAIT = 0x05, GPU_RESET_STATE_RESET_SLAVE_COMPLETE = 0x06, GPU_RESET_STATE_RESET_FINISH = 0x07, } gpuResetState_e; // States for reading GPU core temperature (gpu_read_temp_sm) typedef enum { GPU_STATE_READ_TEMP_NEW = 0x11, // new temp read GPU_STATE_READ_TEMP_START = 0x12, // start write temp reg GPU_STATE_READ_TEMP_FINISH = 0x13, // read temperature GPU_STATE_READ_TEMP_COMPLETE = 0x14, // store temperature read } gpuReadTempState_e; // States for reading GPU memory temperature (gpu_read_mem_temp_sm) typedef enum { GPU_STATE_READ_MEM_TEMP_NEW = 0x21, GPU_STATE_READ_MEM_TEMP_START = 0x22, GPU_STATE_READ_MEM_TEMP_2 = 0x23, GPU_STATE_READ_MEM_TEMP_3 = 0x24, GPU_STATE_READ_MEM_TEMP_READ = 0x25, GPU_STATE_READ_MEM_TEMP_COMPLETE = 0x26, } gpuReadMemTempState_e; // States for checking GPU memory temperature capability (gpu_read_mem_temp_capability_sm) typedef enum { GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW = 0x31, GPU_STATE_READ_MEM_TEMP_CAPABLE_START = 0x32, GPU_STATE_READ_MEM_TEMP_CAPABLE_2 = 0x33, GPU_STATE_READ_MEM_TEMP_CAPABLE_3 = 0x34, GPU_STATE_READ_MEM_TEMP_CAPABLE_READ = 0x35, GPU_STATE_READ_MEM_TEMP_CAPABLE_COMPLETE = 0x36, } gpuReadMemTempCapableState_e; // States for checking if GPU driver is loaded (gpu_check_driver_loaded_sm) typedef enum { GPU_STATE_CHECK_DRIVER_LOADED_NEW = 0x41, GPU_STATE_CHECK_DRIVER_LOADED_START = 0x42, GPU_STATE_CHECK_DRIVER_LOADED_2 = 0x43, GPU_STATE_CHECK_DRIVER_LOADED_3 = 0x44, GPU_STATE_CHECK_DRIVER_LOADED_READ = 0x45, GPU_STATE_CHECK_DRIVER_LOADED_COMPLETE = 0x46, } gpuCheckDriverLoadedState_e; // States for reading GPU power limits (gpu_read_pwr_limit_sm) typedef enum { GPU_STATE_READ_PWR_LIMIT_NEW = 0x51, GPU_STATE_READ_PWR_LIMIT_1_START = 0x52, GPU_STATE_READ_PWR_LIMIT_1_2 = 0x53, GPU_STATE_READ_PWR_LIMIT_1_3 = 0x54, GPU_STATE_READ_PWR_LIMIT_1_FINISH = 0x55, GPU_STATE_READ_PWR_LIMIT_2_START = 0x56, GPU_STATE_READ_PWR_LIMIT_2_2 = 0x57, GPU_STATE_READ_PWR_LIMIT_2_FINISH = 0x58, GPU_STATE_READ_PWR_LIMIT_3_START = 0x59, GPU_STATE_READ_PWR_LIMIT_3_2 = 0x5A, GPU_STATE_READ_PWR_LIMIT_3_3 = 0x5B, GPU_STATE_READ_PWR_LIMIT_3_FINISH = 0x5C, GPU_STATE_READ_PWR_LIMIT_4_START = 0x5D, GPU_STATE_READ_PWR_LIMIT_4_2 = 0x5E, GPU_STATE_READ_PWR_LIMIT_4_3 = 0x5F, GPU_STATE_READ_PWR_LIMIT_4_FINISH = 0x60, GPU_STATE_READ_PWR_LIMIT_5_START = 0x61, GPU_STATE_READ_PWR_LIMIT_5_2 = 0x62, GPU_STATE_READ_PWR_LIMIT_5_3 = 0x63, GPU_STATE_READ_PWR_LIMIT_5_FINISH = 0x64, GPU_STATE_READ_PWR_LIMIT_COMPLETE = 0x65, } gpuReadPwrLimitState_e; // States for setting GPU power limit (gpu_set_pwr_limit_sm) typedef enum { GPU_STATE_SET_PWR_LIMIT_NEW = 0x71, GPU_STATE_SET_PWR_LIMIT_1_START = 0x72, GPU_STATE_SET_PWR_LIMIT_1_2 = 0x73, GPU_STATE_SET_PWR_LIMIT_1_3 = 0x74, GPU_STATE_SET_PWR_LIMIT_1_FINISH = 0x75, GPU_STATE_SET_PWR_LIMIT_2_START = 0x76, GPU_STATE_SET_PWR_LIMIT_2_2 = 0x77, GPU_STATE_SET_PWR_LIMIT_2_3 = 0x78, GPU_STATE_SET_PWR_LIMIT_2_FINISH = 0x79, GPU_STATE_SET_PWR_LIMIT_3_START = 0x7A, GPU_STATE_SET_PWR_LIMIT_3_2 = 0x7B, GPU_STATE_SET_PWR_LIMIT_3_3 = 0x7C, GPU_STATE_SET_PWR_LIMIT_3_FINISH = 0x7D, GPU_STATE_SET_PWR_LIMIT_4_START = 0x7E, GPU_STATE_SET_PWR_LIMIT_4_2 = 0x7F, GPU_STATE_SET_PWR_LIMIT_4_FINISH = 0x80, GPU_STATE_SET_PWR_LIMIT_COMPLETE = 0x81, } gpuSetPwrLimitState_e; // GPU IPC initialization void gpu_ipc_init(); // GPU state machine void task_gpu_sm(struct task *i_self); typedef struct gpuTimingSensor { uint32_t max; uint32_t avg; uint32_t count_1s; uint32_t count_100ms; uint32_t count_lt100ms; uint64_t accum; uint64_t count; } gpuTimingSensor_t; // Table for GPU timings typedef struct gpuTimingTable { gpuTimingSensor_t getpcap[MAX_NUM_GPU_PER_DOMAIN]; gpuTimingSensor_t setpcap[MAX_NUM_GPU_PER_DOMAIN]; gpuTimingSensor_t coretemp[MAX_NUM_GPU_PER_DOMAIN]; gpuTimingSensor_t memtemp[MAX_NUM_GPU_PER_DOMAIN]; gpuTimingSensor_t capabilities[MAX_NUM_GPU_PER_DOMAIN]; gpuTimingSensor_t checkdriver[MAX_NUM_GPU_PER_DOMAIN]; } gpuTimingTable_t; #endif //_GPU_H <|start_filename|>src/occ_405/cmdh/cmdh_service_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_service_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef CMDH_SERVICE_CODES_H #define CMDH_SERVICE_CODES_H #include <comp_ids.h> enum occCmdhModuleId { DATA_STORE_GENERIC_DATA = CMDH_COMP_ID | 0x00, DATA_STORE_FREQ_DATA = CMDH_COMP_ID | 0x01, DATA_STORE_PCAP_DATA = CMDH_COMP_ID | 0x02, // 0x03 free CMDH_GENERIC_CMD_FAILURE = CMDH_COMP_ID | 0x04, DATA_STORE_SYS_DATA = CMDH_COMP_ID | 0x05, DATA_STORE_APSS_DATA = CMDH_COMP_ID | 0x06, DATA_GET_THRM_THRESHOLDS = CMDH_COMP_ID | 0x08, DATA_STORE_IPS_DATA = CMDH_COMP_ID | 0x09, DATA_GET_IPS_DATA = CMDH_COMP_ID | 0x0A, DATA_GET_RESET_PREP_ERRL = CMDH_COMP_ID | 0x0B, CMDH_OCC_INTERRUPT_TYPE = CMDH_COMP_ID | 0x0C, DATA_STORE_VRM_FAULT = CMDH_COMP_ID | 0x0D, }; #endif <|start_filename|>src/common/mem_structs.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/dimm_structs.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* This header file is used by both occ_405 and occ_gpe1. */ /* Contains common structures and globals. */ #ifndef _MEM_STRUCTS_H #define _MEM_STRUCTS_H #include "occ_util.h" #include <gpe_export.h> #include "gpe_err.h" // this enum defines memory power control typedef enum { MEM_PWR_CTL_OFF = 0x00, MEM_PWR_CTL_POWER_DOWN = 0x01, MEM_PWR_CTL_PD_AND_STR = 0x02, MEM_PWR_CTL_PD_AND_STR_CLK_STOP = 0x03, MEM_PWR_CTL_NO_SUPPORT = 0xFF, } eMemoryPowerControlSetting; // memory power control IPC argument typedef struct { GpeErrorStruct error; uint8_t mem_pwr_ctl; uint8_t port; uint8_t mc; } mem_power_control_args_t; #endif //_MEM_STRUCTS_H <|start_filename|>src/ssx/ppc32/ppc32_gcc.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc32/ppc32_gcc.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC32_GCC_H__ #define __PPC32_GCC_H__ /// \file ppc32_gcc.h /// \brief 32-bit PowerPC functions expected by GCC #ifndef __ASSEMBLER__ #include <stdint.h> /// A 64-bit unsigned integer type typedef union { uint64_t value; uint32_t word[2]; } Uint64; /// A 64-bit signed integer type typedef union { int64_t value; int32_t word[2]; } Int64; uint64_t __lshrdi3(uint64_t x, int i); uint64_t __ashldi3(uint64_t x, int i); uint64_t __ashrdi3(uint64_t x, int i); int __popcountsi2(uint32_t x); int __popcountdi2(uint64_t x); /// Unsigned 64/64 bit divide, returning quotient and remainder via pointers. void __ppc32_udiv64(uint64_t u, uint64_t v, uint64_t* q, uint64_t* r); /// Signed 64/64 bit divide, returning quotient and remainder via pointers. void __ppc32_sdiv64(int64_t u, int64_t v, int64_t* q, int64_t* r); uint64_t __udivdi3(uint64_t u, uint64_t v); int64_t __divdi3(int64_t u, int64_t v); int64_t __moddi3(int64_t u, int64_t v); uint64_t __umoddi3(uint64_t u, uint64_t v); int __ucmpdi2(uint64_t a, uint64_t b); #endif /* __ASSEMBLER__ */ #endif /* __PPC32_GCC_H__ */ <|start_filename|>src/ppe/pk/gpe/gpe_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/gpe/gpe_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file gpe_init.c /// \brief PK initialization for GPE /// /// The entry points in this routine are used during initialization. This /// code space can be deallocated and reassigned after application /// initialization if required. #include "pk.h" #include "ocb_register_addresses.h" /// GPE environment initial setup. /// /// This is setup common to all GPE HW Macro applications. This setup takes place /// during boot, before main() is called. void __hwmacro_setup(void) { uint64_t oirrA; uint64_t oirrB; uint64_t oirrC; uint64_t owned_actual; uint64_t reverse_polarity; //verify that this code is running on the correct GPE instance (one time check) if((mfspr(SPRN_PIR) & PIR_PPE_INSTANCE_MASK) != APPCFG_OCC_INSTANCE_ID) { //APPCFG_OCC_INSTANCE_ID does not match actual instance ID! PK_PANIC(OCCHW_INSTANCE_MISMATCH); } #if (APPCFG_OCC_INSTANCE_ID == OCCHW_IRQ_ROUTE_OWNER) //If this instance is the owner of the interrupt routting registers //then write the routing registers for all OCC interrupts. //This instance must be the first instance to run within the OCC //This will be done while all external interrupts are masked. PKTRACE("Initializing External Interrupt Routing Registers"); out32(OCB_OIMR0_OR, 0xffffffff); out32(OCB_OIMR1_OR, 0xffffffff); out32(OCB_OIRR0A, (uint32_t)(g_ext_irqs_routeA >> 32)); out32(OCB_OIRR1A, (uint32_t)g_ext_irqs_routeA); out32(OCB_OIRR0B, (uint32_t)(g_ext_irqs_routeB >> 32)); out32(OCB_OIRR1B, (uint32_t)g_ext_irqs_routeB); out32(OCB_OIRR0C, (uint32_t)(g_ext_irqs_routeC >> 32)); out32(OCB_OIRR1C, (uint32_t)g_ext_irqs_routeC); #endif //Determine from the routing registers which irqs are owned by this instance //NOTE: If a bit is not set in the routeA register, it is not owned by a GPE oirrA = ((uint64_t)in32(OCB_OIRR0A)) << 32; oirrA |= in32(OCB_OIRR1A); oirrB = ((uint64_t)in32(OCB_OIRR0B)) << 32; oirrB |= in32(OCB_OIRR1B); oirrC = ((uint64_t)in32(OCB_OIRR0C)) << 32; oirrC |= in32(OCB_OIRR1C); //All interrupts routed to a GPE will have a bit set in routeA owned_actual = oirrA; //wittle it down by bits in the routeB register #if APPCFG_OCC_INSTANCE_ID & 0x2 owned_actual &= oirrB; #else owned_actual &= ~oirrB; #endif //wittle it down further by bits in the routeC register #if APPCFG_OCC_INSTANCE_ID & 0x1 owned_actual &= oirrC; #else owned_actual &= ~oirrC; #endif //Panic if we don't own the irqs we were expecting //NOTE: we don't panic if we are given more IRQ's than expected if((owned_actual & g_ext_irqs_owned) != g_ext_irqs_owned) { //IRQ's were not routed to us correctly. PK_PANIC(OCCHW_IRQ_ROUTING_ERROR); } //Mask all external interrupts owned by this instance //(even the ones given to us that we weren't expecting) out32(OCB_OIMR0_OR, (uint32_t)(owned_actual >> 32)); out32(OCB_OIMR1_OR, (uint32_t)owned_actual); //Set the interrupt type for all interrupts owned by this instance out32(OCB_OITR0_CLR, (uint32_t)(g_ext_irqs_owned >> 32)); out32(OCB_OITR1_CLR, (uint32_t)g_ext_irqs_owned); out32(OCB_OITR0_OR, (uint32_t)(g_ext_irqs_type >> 32)); out32(OCB_OITR1_OR, (uint32_t)g_ext_irqs_type); //Set the interrupt polarity for all interrupts owned by this instance out32(OCB_OIEPR0_CLR, (uint32_t)(g_ext_irqs_owned >> 32)); out32(OCB_OIEPR1_CLR, (uint32_t)g_ext_irqs_owned); out32(OCB_OIEPR0_OR, (uint32_t)(g_ext_irqs_polarity >> 32)); out32(OCB_OIEPR1_OR, (uint32_t)g_ext_irqs_polarity); //clear the status of all external interrupts owned by this instance out32(OCB_OISR0_CLR, ((uint32_t)(g_ext_irqs_owned >> 32))); out32(OCB_OISR1_CLR, ((uint32_t)g_ext_irqs_owned)); //set the status for interrupts that have reverse polarity reverse_polarity = ~g_ext_irqs_polarity & g_ext_irqs_owned; out32(OCB_OISR0_OR, ((uint32_t)(reverse_polarity >> 32))); out32(OCB_OISR1_OR, ((uint32_t)reverse_polarity)); //Unmask the interrupts owned by this instance that are to be enabled by default out32(OCB_OIMR0_CLR, (uint32_t)(g_ext_irqs_enable >> 32)); out32(OCB_OIMR1_CLR, (uint32_t)g_ext_irqs_enable); //Wait for the last out32 operation to complete sync(); } <|start_filename|>src/occ_405/pgpe/pgpe_interface.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pgpe/pgpe_interface.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _PGPE_INTERFACE_H_ #define _PGPE_INTERFACE_H_ #include "errl.h" #include "state.h" #include "pstate_pgpe_occ_api.h" #include "occhw_async.h" void init_pgpe_ipcs(void); errlHndl_t pgpe_init_clips(void); errlHndl_t pgpe_init_pmcr(void); errlHndl_t pgpe_init_start_suspend(void); errlHndl_t pgpe_init_wof_control(void); errlHndl_t pgpe_init_wof_vfrt(void); int pgpe_set_clip_ranges(Pstate i_pstate); int pgpe_set_clip_blocking(Pstate i_pstate); int pgpe_clip_update(void); int pgpe_pmcr_set(void); int pgpe_start_suspend(uint8_t action, PMCR_OWNER owner); void pgpe_start_suspend_callback(void); int pgpe_request_schedule(GpeRequest* request); int set_nominal_pstate(void); #endif /* #ifndef _PGPE_INTERFACE_H_ */ <|start_filename|>src/occ_405/sensor/sensor_get_tod_task.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor_get_tod_task.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _SENSOR_GET_TOD_TASK_H #define _SENSOR_GET_TOD_TASK_H /** * @file sensor_get_tod_task.h * * This file declares the functions for the task that gets the current Time Of * Day (TOD). */ //****************************************************************************** // Includes //****************************************************************************** #include <rtls.h> // For task_t //****************************************************************************** // Function Prototypes //****************************************************************************** /** * Initial function called by the TASK_ID_GET_TOD task. Gets the current Time * Of Day (TOD) value and stores it in the global variable G_tod. * * @param i_self This task */ void task_get_tod(task_t * i_self); #endif // _SENSOR_GET_TOD_TASK_H <|start_filename|>src/ssx/occhw/occhw_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_init.c /// \brief SSX initialization for OCCHW /// /// The entry points in this routine are used during initialization. This /// code space can be deallocated and reassigned after application /// initialization if required. #include "ssx.h" #include "occhw_async.h" //#include "occhw_vrm.h" #include "simics_stdio.h" #include "string_stream.h" #if USE_RTX_IO // This file is not avilable to OCC FW builds #include "rtx_stdio.h" #endif // We need to make sure that the PLB arbiter is set up correctly to obtain // highest performance in the OCCHW environment, and that PLB error reporting is // appropriate. // The PLB arbiter is configured to support fair arbitration of equal-priority // requests, however we don't set priorities here. The default settings have // been found to be acceptible so far. We do enable arbiter pipelining however. // We do set the "plbarb_lockerr" bit so that the PLB arbiter will trap and // hold the first PLB timeout address. static void plb_arbiter_setup() { //TODO: enable this once OCB support is present in simics #if 0 ocb_oacr_t oacr; ocb_ocichsw_t oo; oacr.value = 0; oacr.fields.oci_priority_mode = 1; /* Fair arbitration */ oacr.fields.oci_hi_bus_mode = 1; /* High bus utilization */ oacr.fields.oci_read_pipeline_control = 1; /* 2-deep read pipelining */ oacr.fields.oci_write_pipeline_control = 1; /* 2-deep write pipelining */ mtdcr(OCB_OACR, oacr.value); oo.value = in32(OCB_OCICHSW); oo.fields.plbarb_lockerr = 1; out32(OCB_OCICHSW, oo.value); #endif } #if PPC405_MMU_SUPPORT #include "ppc405_mmu.h" // MMU regions // // The linker script provides a standard set of symbols that define the base // address and size of each expected section. Any section with a non-0 size // will be mapped in the MMU using protection attributes appropriate for the // section. All sections requiring different MMU attributes must be // 1KB-aligned. The OCI control register space is fixed and also mapped by // the same mechanism. // // By default, caching is enabled for all sections other than the sections // explicitly cache-inhibited. Configuration options are provided to disable // caching of text, data and both. Note that sections that (may) contain code // and data will be marked cache-inhibited if either text or data is globally // configured as cache-inhibited. Also note that "writethrough" can only be // defined on cacheable data sections. #ifdef CACHE_INHIBIT_ALL #define CACHE_INHIBIT_TEXT 1 #define CACHE_INHIBIT_DATA 1 #endif #if CACHE_INHIBIT_TEXT #define TEXT_CACHEABILITY_FLAG TLBLO_I #else #define TEXT_CACHEABILITY_FLAG 0 #endif #if CACHE_INHIBIT_DATA #define DATA_CACHEABILITY_FLAG TLBLO_I #define WRITETHROUGH_FLAG 0 #else #define DATA_CACHEABILITY_FLAG 0 #define WRITETHROUGH_FLAG TLBLO_W #endif // This structure contains all of the fields necessary to create a MMU // mapping. typedef struct { SsxAddress base; size_t size; uint32_t tlbhi_flags; uint32_t tlblo_flags; Ppc405MmuMap* map; } MmuRegion; // The section table along with (default) MMU characteristics. Global // Ppc405MmuMap variables are defined for certain sections so that those // mappings may be later modified. Ppc405MmuMap G_ex_free_mmu_map; static const MmuRegion mmu_regions[] = { { (SsxAddress)& _TEXT0_SECTION_BASE, (size_t)& _TEXT0_SECTION_SIZE, 0, TEXT_CACHEABILITY_FLAG | TLBLO_EX, 0 } , { (SsxAddress)& _TEXT1_SECTION_BASE, (size_t)& _TEXT1_SECTION_SIZE, 0, TEXT_CACHEABILITY_FLAG | TLBLO_EX, 0 } , { (SsxAddress)& _RODATA_SECTION_BASE, (size_t)& _RODATA_SECTION_SIZE, 0, DATA_CACHEABILITY_FLAG, 0 } , { (SsxAddress)& _NONCACHEABLE_RO_SECTION_BASE, (size_t)& _NONCACHEABLE_RO_SECTION_SIZE, 0, TLBLO_I, 0 } , { (SsxAddress)& _NONCACHEABLE_SECTION_BASE, (size_t)& _NONCACHEABLE_SECTION_SIZE, 0, TLBLO_I | TLBLO_WR, 0 } , { (SsxAddress)& _WRITETHROUGH_SECTION_BASE, (size_t)& _WRITETHROUGH_SECTION_SIZE, 0, DATA_CACHEABILITY_FLAG | WRITETHROUGH_FLAG | TLBLO_WR, 0 } , { (SsxAddress)& _DATA_SECTION_BASE, (size_t)& _DATA_SECTION_SIZE, 0, DATA_CACHEABILITY_FLAG | TLBLO_WR, 0 } , { (SsxAddress)& _EX_FREE_SECTION_BASE, (size_t)& _EX_FREE_SECTION_SIZE, 0, DATA_CACHEABILITY_FLAG | TEXT_CACHEABILITY_FLAG | TLBLO_EX | TLBLO_WR, &G_ex_free_mmu_map }, { (SsxAddress)OCI_REGISTER_SPACE_BASE, (size_t)OCI_REGISTER_SPACE_SIZE, 0, TLBLO_WR | TLBLO_I | TLBLO_G, 0 } , }; /// OCCHW MMU setup /// /// Run down the mmu_regions[] array and map all regions with non-0 sizes. /// These are direct maps, setting the effective address to the physical /// address. Once the MMU is set up MMU protection is enabled. /// /// Any OCC mappings of PBA space will have to be done elsewhere, as these /// memory areas are controlled by pHyp, and the product firmware has no plans /// to access main memory from the OCC. static void occhw_mmu_setup() { int i, regions; ppc405_mmu_reset(); regions = sizeof(mmu_regions) / sizeof(MmuRegion); for (i = 0; i < regions; i++) { if (mmu_regions[i].size != 0) { ppc405_mmu_map(mmu_regions[i].base, mmu_regions[i].base, mmu_regions[i].size, mmu_regions[i].tlbhi_flags, mmu_regions[i].tlblo_flags, mmu_regions[i].map); } } ppc405_mmu_start(); } #endif /* PPC405_MMU_SUPPORT */ // I/O Initialization // // Initialize the SSX/Simics/Verification Serial I/O channels. This is done // early in the initialization to allow initialization code to use printk(). // If the application does not select one of the I/O methods then 'ssxout' // defaults to the NULL stream and 'stdin', 'stdout' and 'stderr' are // undefined. #if USE_TRACE_IO || USE_EPM_IO WrappingStream G_ssxout SECTION_ATTRIBUTE(".noncacheable") = {{0}}; uint8_t G_ssxout_buffer[SSXOUT_TRACE_BUFFER_SIZE] SECTION_ATTRIBUTE(".noncacheable") = {0}; #endif // USE_TRACE_IO || USE_EPM_IO static void io_setup() { //NB: These I/O options are listed in priority order - multiple options may //be selected. #if USE_TRACE_IO // If the application chooses to use trace buffer output, the application // must define SSXOUT_TRACE_BUFFER_SIZE, and all output streams are merged // into a single trace buffer which locks low-level file operations in an // SSX_CRITICAL critical secton. /// \todo Split trace I/O mode into multiple streams wrapping_stream_create(&G_ssxout, &G_ssxout_buffer, SSXOUT_TRACE_BUFFER_SIZE, SSX_FILE_OP_LOCK_CRITICAL); stdout = (FILE*)(&G_ssxout); stderr = (FILE*)(&G_ssxout); ssxout = (FILE*)(&G_ssxout); #elif USE_EPM_IO linear_stream_create(&G_ssxout, &G_ssxout_buffer, SSXOUT_TRACE_BUFFER_SIZE, SSX_FILE_OP_LOCK_CRITICAL); stdout = (FILE*)(&G_ssxout); stderr = (FILE*)(&G_ssxout); ssxout = (FILE*)(&G_ssxout); #elif USE_RTX_IO rtx_stdin_create(&rtx_stdin); rtx_stdout_create(&rtx_stdout); rtx_stderr_create(&rtx_stderr); stdin = (FILE*)(&rtx_stdin); stdout = (FILE*)(&rtx_stdout); stderr = (FILE*)(&rtx_stderr); ssxout = (FILE*)(&rtx_stdout); printf("Initialize the RTX stdio.\n"); printf("RTX stdin is not implemented.\n"); #elif USE_SIMICS_IO simics_stdin_create(&simics_stdin); simics_stdout_create(&simics_stdout); simics_stderr_create(&simics_stderr); stdin = (FILE*)(&simics_stdin); stdout = (FILE*)(&simics_stdout); stderr = (FILE*)(&simics_stderr); ssxout = (FILE*)(&simics_stdout); printf("Initialize the Simics stdio.\n"); #endif // I/O Configuration } /// OCCHW environment initial setup. /// /// This is setup common to all OCCHW applications. This setup takes place /// during boot, before main() is called. void __occhw_setup() { uint64_t oirrA; uint64_t oirrB; uint64_t oirrC; uint64_t owned_actual; uint64_t reverse_polarity; #if (APPCFG_OCC_INSTANCE_ID == OCCHW_IRQ_ROUTE_OWNER) //If this instance is the owner of the interrupt routting registers //then write the routing registers for all OCC interrupts. //This instance must be the first instance to run within the OCC //This will be done while all external interrupts are masked. out32(OCB_OIMR0_OR, 0xffffffff); out32(OCB_OIMR1_OR, 0xffffffff); out32(OCB_OIRR0A, (uint32_t)(g_ext_irqs_routeA >> 32)); out32(OCB_OIRR1A, (uint32_t)g_ext_irqs_routeA); out32(OCB_OIRR0B, (uint32_t)(g_ext_irqs_routeB >> 32)); out32(OCB_OIRR1B, (uint32_t)g_ext_irqs_routeB); out32(OCB_OIRR0C, (uint32_t)(g_ext_irqs_routeC >> 32)); out32(OCB_OIRR1C, (uint32_t)g_ext_irqs_routeC); //Note: all interrupts are left in the masked state at this point #endif //Determine from the routing registers which irqs are owned by this instance //NOTE: If a bit is not set in the routeA register, it is not owned by a GPE oirrA = ((uint64_t)in32(OCB_OIRR0A)) << 32; oirrA |= in32(OCB_OIRR1A); oirrB = ((uint64_t)in32(OCB_OIRR0B)) << 32; oirrB |= in32(OCB_OIRR1B); oirrC = ((uint64_t)in32(OCB_OIRR0C)) << 32; oirrC |= in32(OCB_OIRR1C); //All interrupts owned by the 405 will not have a bit set in routeA owned_actual = ~oirrA; //Panic if we don't own the irqs we were expecting //NOTE: we don't panic if we are given more IRQ's than expected if((owned_actual & g_ext_irqs_owned) != g_ext_irqs_owned) { //IRQ's were not routed to us correctly. SSX_PANIC(OCCHW_IRQ_ROUTING_ERROR); } //Mask all external interrupts owned by this instance //(even the ones given to us that we weren't expecting) out32(OCB_OIMR0_OR, (uint32_t)(owned_actual >> 32)); out32(OCB_OIMR1_OR, (uint32_t)owned_actual); //Set the interrupt type for all interrupts owned by this instance out32(OCB_OITR0_CLR, (uint32_t)(g_ext_irqs_owned >> 32)); out32(OCB_OITR1_CLR, (uint32_t)g_ext_irqs_owned); out32(OCB_OITR0_OR, (uint32_t)(g_ext_irqs_type >> 32)); out32(OCB_OITR1_OR, (uint32_t)g_ext_irqs_type); //Set the interrupt polarity for all interrupts owned by this instance out32(OCB_OIEPR0_CLR, (uint32_t)(g_ext_irqs_owned >> 32)); out32(OCB_OIEPR1_CLR, (uint32_t)g_ext_irqs_owned); out32(OCB_OIEPR0_OR, (uint32_t)(g_ext_irqs_polarity >> 32)); out32(OCB_OIEPR1_OR, (uint32_t)g_ext_irqs_polarity); //clear the status of all external interrupts owned by this instance out32(OCB_OISR0_CLR, ((uint32_t)(g_ext_irqs_owned >> 32))); out32(OCB_OISR1_CLR, ((uint32_t)g_ext_irqs_owned)); //set the status for interrupts that have reverse polarity reverse_polarity = ~g_ext_irqs_polarity & g_ext_irqs_owned; out32(OCB_OISR0_OR, ((uint32_t)(reverse_polarity >> 32))); out32(OCB_OISR1_OR, ((uint32_t)reverse_polarity)); //Unmask the interrupts owned by this instance that are to be enabled by default out32(OCB_OIMR0_CLR, (uint32_t)(g_ext_irqs_enable >> 32)); out32(OCB_OIMR1_CLR, (uint32_t)g_ext_irqs_enable); // Setup requires SCOM, which requires a timeout. Therefore we need to set // up a default timebase frequency, which may be overridden during // ssx_initialize(). __ssx_timebase_frequency_hz = 600000000; __ssx_timebase_frequency_khz = 600000; __ssx_timebase_frequency_mhz = 600; // Set up I/O. This is done early in the initialization so that // initialization drivers can use printk(). io_setup(); // TODO: enable once chip id support is present #if 0 // Cache the device identification and chip configuration _occhw_get_ids(); _occhw_get_chip_configuration(); #endif // Set up the PLB arbiter plb_arbiter_setup(); // If the MMU is enabled the base image MMU programming is set up, and the // MMU is activated. #if PPC405_MMU_SUPPORT occhw_mmu_setup(); #endif // The Async drivers are initialized. async_initialize(); } <|start_filename|>src/common/gpe_export.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/common/gpe_export.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _GPE_EXPORT_H #define _GPE_EXPORT_H #include "gpe_err.h" // GPE Error structure (common to both GPEs) typedef struct { union { struct { uint32_t rc; uint32_t addr; }; uint64_t error; }; uint64_t ffdc; } GpeErrorStruct; // Arguments for doing a SCOM from GPE0 typedef struct ipc_scom_op { GpeErrorStruct error; // Error of SCOM operation uint32_t addr; // Register address uint64_t data; // Data for read/write uint32_t size; // Size of data buffer uint8_t read; // Read (1) or write (0) } ipc_scom_op_t; typedef struct nop { GpeErrorStruct error; // Error of operation } nop_t; typedef struct gpe_shared_data { uint32_t nest_freq_div; // Nest freq / 64 uint32_t spipss_spec_p9; // Which APSS spec to use uint32_t fir_heap_buffer_ptr; uint32_t fir_params_buffer_ptr; uint32_t gpe0_tb_ptr; uint32_t gpe0_tb_sz; uint32_t gpe1_tb_ptr; uint32_t gpe1_tb_sz; uint32_t pgpe_tb_ptr; uint32_t pgpe_tb_sz; uint32_t sgpe_tb_ptr; uint32_t sgpe_tb_sz; uint32_t reserved[52]; } gpe_shared_data_t; #define HOMER_FIR_PARM_SIZE (3 * 1024) /* This size has to agree with the size _FIR_PARMS_SECTION_SIZE defined in the */ /* OCC linker command file. */ #define FIR_PARMS_SECTION_SIZE 0x1000 // This size has to agree with the size _FIR_HEAP_SECTION_SIZE defined in the // OCC linker command file. #define FIR_HEAP_SECTION_SIZE 0x3000 #endif //_GPE_EXPORT_H <|start_filename|>src/ppe/pk/kernel/pk_macros.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/kernel/pk_macros.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PK_MACROS_H__ #define __PK_MACROS_H__ /// \file pk_macros.h /// \brief Boilerplate macros for PK /// This macro encapsulates error handling boilerplate for code that uses the /// PK API-type error handling, for errors that do not occur in critical /// sections. #define PK_ERROR(code) \ do { \ if (PK_ERROR_PANIC) { \ PK_PANIC(code); \ } else { \ return -(code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the PK API /// functions, for errors that do not occur in critical sections. #define PK_ERROR_IF(condition, code) \ do { \ if (condition) { \ PK_ERROR(code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the PK API /// functions, for errors that do not occur in critical sections and always /// force a kernel panic, indicating a kernel or API bug. #define PK_PANIC_IF(condition, code) \ do { \ if (condition) { \ PK_PANIC(code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the PK API /// functions, for errors that do not occur in critical sections. /// The error handling will only be enabled when PK_ERROR_CHECK_API /// is enabled. #define PK_ERROR_IF_CHECK_API(condition, code) \ do { \ if (PK_ERROR_CHECK_API) { \ PK_ERROR_IF(condition, code); \ } \ } while (0) /// This macro encapsulates error handling boilerplate in the PK API /// functions, for errors that occur in critical sections. #define PK_ERROR_IF_CRITICAL(condition, code, context) \ do { \ if (condition) { \ if (PK_ERROR_PANIC) { \ PK_PANIC(code); \ pk_critical_section_exit(context); \ } else { \ pk_critical_section_exit(context); \ return -(code); \ } \ } \ } while (0) /// This is a general macro for errors that require cleanup before returning /// the error code. #define PK_ERROR_IF_CLEANUP(condition, code, cleanup) \ do { \ if (condition) { \ if (PK_ERROR_PANIC) { \ PK_PANIC(code); \ cleanup; \ } else { \ cleanup; \ return -(code); \ } \ } \ } while (0) /// Some PK APIs can only be called from thread contexts - these are APIs /// that threads call on 'themselves'. #define PK_ERROR_UNLESS_THREAD_CONTEXT() \ PK_ERROR_IF(!__pk_kernel_context_thread(), \ PK_ILLEGAL_CONTEXT_THREAD_CONTEXT) /// Some PK APIs must be called from an interrupt context only. #define PK_ERROR_UNLESS_ANY_INTERRUPT_CONTEXT() \ PK_ERROR_IF(!__pk_kernel_context_any_interrupt(), \ PK_ILLEGAL_CONTEXT_INTERRUPT_CONTEXT) #endif /* __PK_MACROS_H__ */ <|start_filename|>src/ssx/ssx/ssx_api.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_api.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SSX_API_H__ #define __SSX_API_H__ /// \file ssx_api.h /// \brief Macros and declarations for the SSX API. // Basic constants /// Although the number of threads is defined as a manifest constant, /// numerous parts of the SSX code assume this definition. The number of /// supported threads _can not_ be changed simply by changing this constant. #define SSX_THREADS 32 #define SSX_IDLE_THREAD_PRIORITY SSX_THREADS // Interrupt API #define SSX_NONCRITICAL 0 #define SSX_CRITICAL 1 #define SSX_SUPERCRITICAL 2 #define SSX_IRQ_POLARITY_ACTIVE_LOW 0 #define SSX_IRQ_POLARITY_ACTIVE_HIGH 1 #define SSX_IRQ_TRIGGER_LEVEL_SENSITIVE 0 #define SSX_IRQ_TRIGGER_EDGE_SENSITIVE 1 // API return codes #define SSX_OK 0 #define SSX_ILLEGAL_CONTEXT_CRITICAL_INTERRUPT 0x00779001 #define SSX_ILLEGAL_CONTEXT_THREAD_CONTEXT 0x00779002 #define SSX_ILLEGAL_CONTEXT_INTERRUPT_CONTEXT 0x00779003 #define SSX_ILLEGAL_CONTEXT_THREAD 0x00779004 #define SSX_ILLEGAL_CONTEXT_TIMER 0x00779005 #define SSX_ILLEGAL_CONTEXT_PPC405_CACHE 0x00779006 #define SSX_INVALID_THREAD_AT_RESUME1 0x00779007 #define SSX_INVALID_THREAD_AT_RESUME2 0x00779008 #define SSX_INVALID_THREAD_AT_SUSPEND1 0x00779009 #define SSX_INVALID_THREAD_AT_SUSPEND2 0x0077900a #define SSX_INVALID_THREAD_AT_DELETE 0x0077900b #define SSX_INVALID_THREAD_AT_INFO 0x0077900c #define SSX_INVALID_THREAD_AT_CHANGE 0x0077900d #define SSX_INVALID_THREAD_AT_SWAP1 0x0077900e #define SSX_INVALID_THREAD_AT_SWAP2 0x0077900f #define SSX_INVALID_THREAD_AT_CREATE 0x00779010 #define SSX_INVALID_SEMAPHORE_AT_POST 0x00779011 #define SSX_INVALID_SEMAPHORE_AT_PEND 0x00779012 #define SSX_INVALID_SEMAPHORE_AT_RELEASE 0x00779013 #define SSX_INVALID_SEMAPHORE_AT_INFO 0x00779014 #define SSX_INVALID_SEMAPHORE_AT_CREATE 0x00779015 #define SSX_INVALID_TIMER_AT_SCHEDULE 0x00779016 #define SSX_INVALID_TIMER_AT_CANCEL 0x00779017 #define SSX_INVALID_TIMER_AT_INFO 0x00779018 #define SSX_INVALID_TIMER_AT_CREATE 0x00779019 #define SSX_INVALID_ARGUMENT_IRQ_SETUP 0x0077901a #define SSX_INVALID_ARGUMENT_IRQ_HANDLER 0x0077901b #define SSX_INVALID_ARGUMENT_INTERRUPT 0x00779024 #define SSX_INVALID_ARGUMENT_CONTEXT_SET 0x00779025 #define SSX_INVALID_ARGUMENT_CONTEXT_GET 0x00779026 #define SSX_INVALID_ARGUMENT_PPC405_FIT 0x00779027 #define SSX_INVALID_ARGUMENT_PPC405_WATCHDOG 0x00779028 #define SSX_INVALID_ARGUMENT_INIT 0x00779029 #define SSX_INVALID_ARGUMENT_SEMAPHORE 0x0077902a #define SSX_INVALID_ARGUMENT_THREAD_CHANGE 0x0077902b #define SSX_INVALID_ARGUMENT_THREAD_PRIORITY 0x0077902c #define SSX_INVALID_ARGUMENT_THREAD1 0x0077902d #define SSX_INVALID_ARGUMENT_THREAD2 0x0077902e #define SSX_INVALID_ARGUMENT_THREAD3 0x0077902f #define SSX_STACK_OVERFLOW 0x00779030 #define SSX_TIMER_ACTIVE 0x00779031 #define SSX_TIMER_NOT_ACTIVE 0x00779032 #define SSX_PRIORITY_IN_USE_AT_RESUME 0x00779033 #define SSX_PRIORITY_IN_USE_AT_CHANGE 0x00779034 #define SSX_PRIORITY_IN_USE_AT_SWAP 0x00779035 #define SSX_SEMAPHORE_OVERFLOW 0x00779036 #define SSX_SEMAPHORE_PEND_NO_WAIT 0x00779037 #define SSX_SEMAPHORE_PEND_TIMED_OUT 0x00779038 #define SSX_SEMAPHORE_PEND_WOULD_BLOCK 0x00779039 #define SSX_INVALID_DEQUE_SENTINEL 0x0077903a #define SSX_INVALID_DEQUE_ELEMENT 0x0077903b #define SSX_INVALID_OBJECT 0x0077903c // Kernel panics #define SSX_NO_TIMER_SUPPORT 0x0077903d #define SSX_START_THREADS_RETURNED 0x0077903e #define SSX_UNIMPLEMENTED 0x0077903f #define SSX_SCHEDULING_INVARIANT 0x00779040 #define SSX_TIMER_HANDLER_INVARIANT 0x00779041 #define SSX_THREAD_TIMEOUT_STATE 0x00779045 /// \defgroup ssx_thread_states SSX Thread States /// /// Threads are created in the state SSX_THREAD_STATE_SUSPENDED_RUNNABLE. /// When the thread is mapped it transitions to state SSX_THREAD_STATE_MAPPED. /// A mapped thread is runnable if it appears in the run queue; there is no /// other flag or status to indicate a runnable thread. If a blocked thread /// is suspended it goes into state SSX_THREAD_STATE_SUSPENDED_BLOCKED. For /// all threads the reason for blockage is detailed in the \a flags field of /// the thread; See \ref ssx_thread_flags. SSX_THREAD_STATE_DELETED and /// SSX_THREAD_STATE_COMPLETED are effectively equivalent but named /// individually for reporting purposes. /// /// \note This separation of the thread \a state and \a flags allows the use /// of an SSX semaphore as a thread barrier, as it supports a non-iterative /// implementation of ssx_semaphore_release_all() in which all threads blocked /// on the semaphore are simultaneously inserted into the run queue with an /// atomic operation, followed by each individual thread readjusting its flags /// appropriately once the thread runs again. /// /// @{ #define SSX_THREAD_STATE_SUSPENDED_RUNNABLE 1 #define SSX_THREAD_STATE_MAPPED 2 #define SSX_THREAD_STATE_SUSPENDED_BLOCKED 3 #define SSX_THREAD_STATE_COMPLETED 4 #define SSX_THREAD_STATE_DELETED 5 /// @} /// \defgroup ssx_thread_flags SSX Thread Flags /// /// The \a flag field of the thread extends the information contained in the /// \a state field; See \ref ssx_thread_states. Blocked threads will show /// SSX_THREAD_FLAG_SEMAPHORE_PEND, SSX_THREAD_FLAG_TIMER_PEND or both (if /// blocked on a semaphore with timeout). The flag SSX_THREAD_FLAG_TIMED_OUT /// indicates that a thread timer timed out before the thread became /// runnable. Currently only the semaphore-pend-with-timeout code uses this /// flag. /// /// Note that a thread can be mapped and runnable (in the run queue) even /// though SSX_THREAD_FLAG_SEMAPHORE_PEND and/or SSX_THREAD_FLAG_TIMER_PEND /// are set. These flags are always cleared by the thread itself, not the code /// that unblocks the thread. This allows the implementation of the /// ssx_semaphore_release_all() as explained in \ref ssx_thread_states. /// /// @{ #define SSX_THREAD_FLAG_SEMAPHORE_PEND 0x1 #define SSX_THREAD_FLAG_TIMER_PEND 0x2 #define SSX_THREAD_FLAG_TIMED_OUT 0x4 /// @} // Critical Sections /// Enter a critical section of a given priority, saving the current machine /// context. #define ssx_critical_section_enter(priority, pctx) \ ssx_interrupt_disable(priority, pctx) /// Exit a critical section by restoring the previous machine context. #define ssx_critical_section_exit(pctx) \ ssx_machine_context_set(pctx) /// Execute a statement atomically, in a particular interrupt priority /// context. #define SSX_ATOMIC(priority, stmt) \ do { \ SsxMachineContext __ctx; \ ssx_critical_section_enter((priority), &__ctx); \ stmt; \ ssx_critical_section_exit(&__ctx); \ } while (0) // Application-overrideable definitions /// Control whether or not the API functions check for errors. /// /// This definition can be overriden by the application. #ifndef SSX_ERROR_CHECK_API #define SSX_ERROR_CHECK_API 1 #endif /// Control whether API errors cause kernel panics or return negative error /// codes. /// /// This selection is only valid if \c SSX_ERROR_CHECK_API is defined /// non-0. This definition can be overriden by the application. #ifndef SSX_ERROR_PANIC #define SSX_ERROR_PANIC 1 #endif /// Control whether or not the SSX kernel checks key invariants. /// /// Violations of kernel invariants always cause kernel panics. This /// definition can be overriden by the application. #ifndef SSX_ERROR_CHECK_KERNEL #define SSX_ERROR_CHECK_KERNEL 1 #endif /// Define the time interval type, which must be an unsigned type of a size /// less then or equal to the size of \c SsxTimebase. This definition can be /// overridden by the application. #ifndef SSX_TIME_INTERVAL_TYPE #define SSX_TIME_INTERVAL_TYPE uint64_t #endif /// Provide support for the SsxTimer APIs in addition to the default /// initerrupt APIs. This definition can be overridden by the application. #ifndef SSX_TIMER_SUPPORT #define SSX_TIMER_SUPPORT 1 #endif /// Provide support for the all SSX APIs. Thread support requires/implies /// support for time services and semaphores. This definition can be /// overridden by the application. #ifndef SSX_THREAD_SUPPORT #define SSX_THREAD_SUPPORT 1 #endif /// Control the level of stack checking. /// /// This definition can be overriden by the application. /// /// 0 : No stack prepatterning or checking is made for thread and kernel /// stacks. /// /// 1 : Kernel interrupt stacks are prepatterned during /// \c ssx_initialize(). Thread stacks are prepatterned during /// \c ssx_thread_create(). /// /// 2 : (\b Default - Currently Unimplemented) In addition to prepatterning, /// stack utilization is computed at the exit of context switches and /// noncritical interrupt processing. The maximum utilization is stored in /// the thread data structure. The kernel will panic if stack overflow is /// detected. Stack utilization is not computed for the idle thread. #ifndef SSX_STACK_CHECK #define SSX_STACK_CHECK 1 #endif /// A hook for main() /// /// This hook macro is expanded in the body of __ssx_main() prior to the call /// of the application main(). The application can redefine this hook macro /// in (or in headers referred to in) the application header /// ssx_app_cfg.h. The SSX_MAIN_HOOK will run on the stack of main(). #ifndef SSX_MAIN_HOOK #define SSX_MAIN_HOOK do {} while (0) #endif /// A hook for ssx_start_threads() /// /// This hook macro is expanded in the call-tree of ssx_start_threads() before /// threads are actually started. The application can redefine this hook /// macro in (or in headers referred to in) the application header /// ssx_app_cfg.h. /// /// The SSX_START_THREADS_HOOK runs as a pseudo-interrupt handler on the /// noncritical interrupt stack, with noncritical interrupts disabled. #ifndef SSX_START_THREADS_HOOK #define SSX_START_THREADS_HOOK do {} while (0) #endif /// The maximum value of the \c SsxTimebase type. #define SSX_TIMEBASE_MAX ((SsxTimebase)-1) /// A special value that specifies that the timebase will not be reset during /// ssx_init(). #define SSX_TIMEBASE_CONTINUES SSX_TIMEBASE_MAX /// By convention, a timeout value indicating 'no waiting' in a call of \c /// ssx_semaphore_pend(). #define SSX_NO_WAIT 0 /// By convention, a timeout value indicating 'wait forever' in a call of \c /// ssx_semaphore_pend(). #define SSX_WAIT_FOREVER ((SsxInterval)-1) /// The SSX timebase frequency in Hz /// /// Earlier version of SSX defined the timbase frequency as a preprocessor /// macro. Now, the timebase frequency is specified as a parameter of the /// ssx_initialize() API. The macro remains defined for backwards /// compatibility, however all kernel uses of the timebase frequency are now /// optimized around the timebase parameter. #define SSX_TIMEBASE_FREQUENCY_HZ __ssx_timebase_frequency_hz /// Convert a time in integral seconds to a time interval - overflows are /// ignored. The application can redefine this macro. #ifndef SSX_SECONDS #define SSX_SECONDS(s) ((SsxInterval)(__ssx_timebase_frequency_hz * (SsxInterval)(s))) #endif /// Convert a time in integral milliseconds to a time interval - overflows are /// ignored, and a frequency evenly (or closely) divisible by 1000 is /// assumed. The application can redefine this macro. #ifndef SSX_MILLISECONDS #define SSX_MILLISECONDS(m) ((SsxInterval)(__ssx_timebase_frequency_khz * (SsxInterval)(m))) #endif /// Convert a time in integral microseconds to a time interval - overflows are /// ignored, and a frequncy evenly (or closely) divisible by 1,000,000 is /// assumed. The application can redefine this macro. #ifndef SSX_MICROSECONDS #define SSX_MICROSECONDS(u) ((SsxInterval)(__ssx_timebase_frequency_mhz * (SsxInterval)(u))) #endif /// Convert a time in integral nanoseconds to a time interval - overflows are /// ignored, and a frequeyncy evenly (or closely) divisible by 1,000,000 is /// assumed. The application can redefine this macro. #ifndef SSX_NANOSECONDS #define SSX_NANOSECONDS(n) \ ((SsxInterval)((__ssx_timebase_frequency_mhz * (SsxInterval)(n)) / 1000)) #endif /// Enable SSX application tracing (enabled by default) #ifndef SSX_TRACE_ENABLE #define SSX_TRACE_ENABLE 1 #endif /// Enable SSX kernel tracing (disabled by default) #ifndef SSX_KERNEL_TRACE_ENABLE #define SSX_KERNEL_TRACE_ENABLE 0 #endif #if !SSX_TRACE_ENABLE #define SSX_TRACE(...) #define SSX_TRACE_BIN(str, bufp, buf_size) #else #define SSX_TRACE(...) SSXTRACE(__VA_ARGS__) #define SSX_TRACE_BIN(str, bufp, buf_size) SSXTRACE_BIN(str, bufp, buf_size) #endif //Kernel trace macros #if !SSX_KERNEL_TRACE_ENABLE #define SSX_KERN_TRACE(...) #define SSX_KERN_TRACE_ASM16(...) #else #define SSX_KERN_TRACE(...) SSX_TRACE(__VA_ARGS__) #define SSX_KERN_TRACE_ASM16(...) SSX_TRACE_ASM16(__VA_ARGS__) #endif /* SSX_KERNEL_TRACE_ENABLE */ /// Add a string to the trace buffer with an optional register holding a 16bit value /// WARNING: This calls a c function which may clobber any of the volatile registers #if (SSX_TRACE_SUPPORT && SSX_TIMER_SUPPORT) #define SSX_TRACE_ASM16(...) TRACE_ASM_HELPER16(VARG_COUNT(__VA_ARGS__), __VA_ARGS__) #else #define SSX_TRACE_ASM16(...) #endif /* SSX_TRACE_SUPPORT */ /// The following macros are helper macros for tracing. They should not be called /// directly. #define VARG_COUNT_HELPER(_0, _1, _2, _3, _4, _5, _6, _7, N, ...) N #define VARG_COUNT(...) VARG_COUNT_HELPER(, ##__VA_ARGS__, 7, 6, 5, 4, 3, 2, 1, 0) #ifdef __ASSEMBLER__ #define TRACE_ASM_HELPER16_CALL(count, ...) TINY_TRACE_ASM ## count (__VA_ARGS__) #define TRACE_ASM_HELPER16(count, ...) TRACE_ASM_HELPER16_CALL(count, __VA_ARGS__) #define TINY_TRACE_ASM0() .error "format string required" #define TINY_TRACE_ASM1(str) \ .tiny_trace_asm1 trace_ppe_hash(str, SSX_TRACE_HASH_PREFIX) #define TINY_TRACE_ASM2(str, reg) \ .tiny_trace_asm2 trace_ppe_hash(str, SSX_TRACE_HASH_PREFIX), reg #define TINY_TRACE_ASM3() .error "too many parameters" #define TINY_TRACE_ASM4() .error "too many parameters" #define TINY_TRACE_ASM5() .error "too many parameters" #define TINY_TRACE_ASM6() .error "too many parameters" #define TINY_TRACE_ASM7() .error "too many parameters" //TODO: add support for tracing more than 1 parameter and binary data in assembly // *INDENT-OFF* .global ssx_trace_tiny .macro .tiny_trace_asm1 hash16 lis %r3, \hash16 bl ssx_trace_tiny .endm .macro .tiny_trace_asm2 hash16, parm16 clrlwi %r3, \parm16, 16 oris %r3, %r3, \hash16 bl ssx_trace_tiny .endm // *INDENT-ON* #endif /*__ASSEMBLER__*/ #ifndef __ASSEMBLER__ #include <stddef.h> #include <stdint.h> /// The timebase frequency in Hz; A parameter to ssx_initialize() extern uint32_t __ssx_timebase_frequency_hz; /// The timebase frequency in KHz extern uint32_t __ssx_timebase_frequency_khz; /// The timebase frequency in Mhz extern uint32_t __ssx_timebase_frequency_mhz; typedef unsigned long int SsxAddress; typedef uint8_t SsxThreadState; typedef uint8_t SsxThreadPriority; typedef uint8_t SsxThreadFlags; typedef uint32_t SsxSemaphoreCount; typedef uint64_t SsxTimebase; typedef SSX_TIME_INTERVAL_TYPE SsxInterval; #include "ssx_port_types.h" typedef struct { /// A priority queue of threads pending on the semaphore. SsxThreadQueue pending_threads; /// The current semaphore count. SsxSemaphoreCount count; /// The maximum allowable count - for error checking. SsxSemaphoreCount max_count; } SsxSemaphore; /// Compile-time initialize an SsxSemaphore structure /// /// This low-level macro creates a structure initializatin of an SsxSemaphore /// structure. This can be used for example to create compile-time initialized /// arrays of semaphores. #define SSX_SEMAPHORE_INITIALIZATION(_initial_count, _max_count) \ {.pending_threads = 0, \ .count = (_initial_count), \ .max_count = (_max_count)} /// Declare and initialize a semaphore #define SSX_SEMAPHORE(sem, initial_count, max_count) \ SsxSemaphore sem = SSX_SEMAPHORE_INITIALIZATION(initial_count, max_count) /// Trace macros for C functions #define HASH_ARG_COMBO(str, arg) \ ((((uint32_t)trace_ppe_hash(str, SSX_TRACE_HASH_PREFIX)) << 16) | ((uint32_t)(arg) & 0x0000ffff)) #define SSXTRACE0(...) ssx_trace_tiny() //will fail at compile time #define SSXTRACE1(str) \ ssx_trace_tiny((trace_ppe_hash(str, SSX_TRACE_HASH_PREFIX) << 16)) #define SSXTRACE2(str, parm0) \ ((sizeof(parm0) <= 2)? \ ssx_trace_tiny(HASH_ARG_COMBO(str, parm0)): \ ssx_trace_big(HASH_ARG_COMBO(str, 1), ((uint64_t)parm0) << 32, 0)) #define SSXTRACE3(str, parm0, parm1) \ ssx_trace_big(HASH_ARG_COMBO(str, 2), ((((uint64_t)parm0) << 32) | parm1), 0) #define SSXTRACE4(str, parm0, parm1, parm2) \ ssx_trace_big(HASH_ARG_COMBO(str, 3), ((((uint64_t)parm0) << 32) | parm1),\ ((uint64_t)parm2) << 32 ) #define SSXTRACE5(str, parm0, parm1, parm2, parm3) \ ssx_trace_big(HASH_ARG_COMBO(str, 4), ((((uint64_t)parm0) << 32) | parm1),\ ((((uint64_t)parm2) << 32) | parm3) ) #define SSXTRACE6(...) ssx_trace_tiny() //will fail at compile time #define SSXTRACE7(...) ssx_trace_tiny() //will fail at compile time #define SSXTRACE_HELPER2(count, ...) SSXTRACE ## count (__VA_ARGS__) #define SSXTRACE_HELPER(count, ...) SSXTRACE_HELPER2(count, __VA_ARGS__) #if (SSX_TRACE_SUPPORT && SSX_TIMER_SUPPORT) #define SSXTRACE(...) SSXTRACE_HELPER(VARG_COUNT(__VA_ARGS__), __VA_ARGS__) #define SSXTRACE_BIN(str, bufp, buf_size) \ ssx_trace_binary(((buf_size < 255)? HASH_ARG_COMBO(str, buf_size): HASH_ARG_COMBO(str, 255)), bufp) #else #define SSXTRACE(...) #define SSXTRACE_BIN(str, bufp, buf_size) #endif //SSX_TRACE_SUPPORT //Needed for easy cache flush of trace buffer //Note, in order to use this macro you must declare g_ssx_trace_buf[_size] // as extern SsxTraceBuffer [and size_t] variables in the .c file as well // as include ssx_trace.h. #if (SSX_TRACE_ENABLE && SSX_TRACE_SUPPORT && SSX_TIMER_SUPPORT) #define SSX_FLUSH_TRACE_BUF() dcache_flush(&g_ssx_trace_buf, g_ssx_trace_buf_size) #else #define SSX_FLUSH_TRACE_BUF() #endif //Making sure we can still compile application codes if SSX tracing for some // reason isn't enabled. #if (SSX_TRACE_ENABLE && SSX_TRACE_SUPPORT && SSX_TIMER_SUPPORT) #define SSX_TRACE_INIT(freqhz, time0) ssx_trace_init(freqhz, time0) #else #define SSX_TRACE_INIT(freqhz, time0) #endif /// A generic doubly-linked list object /// /// This object functions both as a sentinel mode for a deque as well as a /// pointer container for elements in deques. The SSX API assumes that /// queueable structures will be defined with an SsxDeque structure as the /// initial 'data member' of the structure. This allows a pointer to a queue /// element to be cast to a pointer to an SsxDeque and vice-versa. typedef struct SsxDeque { /// Pointer to the head or the next element in a deque. /// /// When an SsxDeque is used as the sentinel node for a queue, \a next /// points to the head of the queue, and the condition (next == \<self\>) /// indicates an empty SsxDeque. By convention the condition (\a next == /// 0) is used to indicate that a queue element is not enqueued. struct SsxDeque* next; /// Pointer to the tail or previous element in a deque. /// /// When a DQueue is used as the sentinel node for a queue, \a previous /// points to the tail of the queue. struct SsxDeque* previous; } SsxDeque; typedef void (*SsxTimerCallback)(void*); #define SSX_TIMER_CALLBACK(callback) void callback(void *) struct SsxTimer; /// The SSX timer object typedef struct SsxTimer { /// The time queue management pointers /// /// This pointer container is defined as the first element of the /// structure to allow the SsxTimer to be cast to an SsxDeque and /// vice-versa. SsxDeque deque; /// The absolute timeout of the timer. SsxTimebase timeout; /// The timer period /// /// If not 0, then this is a periodic timer and it will be automatically /// rescheduled in absolute time from the previous timeout. SsxInterval period; /// The timer callback /// /// For SSX thread timers used to implement Sleep and semaphore pend /// timeouts this field is initialized to __ssx_thread_timeout(). SsxTimerCallback callback; /// Private data passed to the callback. /// /// For SSX thread timers used to implement Sleep and semaphore pend this /// field is initialized to a pointer to the thread. void* arg; /// Options for timer processing; See \ref ssx_timer_options uint8_t options; } SsxTimer; /// \defgroup ssx_timer_options SSX Timer Options /// @{ /// Allow interrupt preemption during the callback /// /// This is the normal mode for SsxTimer objects scheduled by SSX kernal /// mechanisms. The timer callbacks effectively run as if inside a /// highest-priority thread, allowing other interrupts to preempt them. #define SSX_TIMER_CALLBACK_PREEMPTIBLE 0x1 /// @} // Threads typedef void (*SsxThreadRoutine)(void* arg); #define SSX_THREAD_ROUTINE(f) void f(void *arg); typedef struct { /// Stack pointer saved during context switches. Assembler code expects /// this to always be at address offset 0 from the thread pointer. SsxAddress saved_stack_pointer; /// This is 1 past the last valid byte address of the thread stack. /// Assembler code expects this to always be at address offset (sizeof /// SsxAddress) from the thread pointer. SsxAddress stack_limit; /// This is the original base of the stack. /// Assembler code expects this to always be at address offset 2 * (sizeof /// SsxAddress) from the thread pointer. SsxAddress stack_base; /// If the thread is blocked on a semaphore, then this is the semaphore the /// thread is blocked on. SsxSemaphore* semaphore; /// The thread priority. SsxThreadPriority priority; /// The thread state; See \ref ssx_thread_states SsxThreadState state; /// Thread flags; See \ref ssx_thread_flags SsxThreadFlags flags; /// The timer structure handles Sleep and blocking on a semaphore with /// timeout. SsxTimer timer; } SsxThread; // Initialization APIs int ssx_initialize(SsxAddress noncritical_stack, size_t noncritical_stack_size, SsxAddress critical_stack, size_t critical_stack_size, SsxTimebase initial_timebase, uint32_t timebase_frequency_hz); // Timebase APIs SsxTimebase ssx_timebase_get(void); #if APPCFG_USE_EXT_TIMEBASE_FOR_TRACE // Retrieve an external timebase SsxTimebase ssx_ext_timebase_get(void); #else static inline SsxTimebase ssx_ext_timebase_get(void) { return ssx_timebase_get(); } #endif /* APPCFG_USE_EXT_TIMEBASE_FOR_TRACE */ void ssx_timebase_set(SsxTimebase timebase); // Interrupt preemption APIs int ssx_interrupt_preemption_enable(void); int ssx_interrupt_preemption_disable(void); // Timer APIs int ssx_timer_create(SsxTimer* timer, SsxTimerCallback callback, void* arg); int ssx_timer_create_nonpreemptible(SsxTimer* timer, SsxTimerCallback callback, void* arg); int ssx_timer_schedule_absolute(SsxTimer* timer, SsxTimebase time, SsxInterval period); int ssx_timer_schedule(SsxTimer* timer, SsxInterval interval, SsxInterval period); int ssx_timer_cancel(SsxTimer* timer); int ssx_timer_info_get(SsxTimer* timer, SsxTimebase* timeout, int* active); // Thread APIs int ssx_thread_create(SsxThread* thread, SsxThreadRoutine thread_routine, void* arg, SsxAddress stack, size_t stack_size, SsxThreadPriority priority); int ssx_start_threads(void); int ssx_thread_resume(SsxThread* thread); int ssx_thread_suspend(SsxThread* thread); int ssx_thread_delete(SsxThread* thread); int ssx_complete(void); int ssx_sleep_absolute(SsxTimebase time); int ssx_sleep(SsxInterval interval); int ssx_thread_info_get(SsxThread* thread, SsxThreadState* state, SsxThreadPriority* priority, int* runnable); int ssx_thread_priority_change(SsxThread* thread, SsxThreadPriority new_priority, SsxThreadPriority* old_priority); int ssx_thread_at_priority(SsxThreadPriority priority, SsxThread** thread); int ssx_thread_priority_swap(SsxThread* thread_a, SsxThread* thread_b); // Semaphore APIs int ssx_semaphore_create(SsxSemaphore* semaphore, SsxSemaphoreCount initial_count, SsxSemaphoreCount max_count); int ssx_semaphore_post(SsxSemaphore* semaphore); int ssx_semaphore_pend(SsxSemaphore* semaphore, SsxInterval timeout); int ssx_semaphore_release_all(SsxSemaphore* semaphore); int ssx_semaphore_info_get(SsxSemaphore* semaphore, SsxSemaphoreCount* count, int* pending); void ssx_semaphore_post_handler(void* arg, SsxIrqId irq, int priority); // Misc. APIs void ssx_halt() __attribute__ ((noreturn)); // Deque APIs int ssx_deque_sentinel_create(SsxDeque* deque); #define SSX_DEQUE_SENTINEL_INIT(dq_addr) \ {\ .next = dq_addr, \ .previous = dq_addr \ } #define SSX_DEQUE_SENTINEL_STATIC_CREATE(deque) \ SsxDeque deque = SSX_DEQUE_SENTINEL_INIT(&deque) int ssx_deque_element_create(SsxDeque* element); #define SSX_DEQUE_ELEMENT_INIT() \ {\ .next = 0, \ .previous = 0 \ } #define SSX_DEQUE_ELEMENT_STATIC_CREATE(deque) \ SsxDeque deque = SSX_DEQUE_ELEMENT_INIT() /// Check for an empty SsxDeque /// /// \param deque The sentinel node of a deque /// /// \retval 0 The SsxDeque is not empty /// /// \retval 1 The SsxDeque is empty static inline int ssx_deque_is_empty(SsxDeque* deque) { return (deque == deque->next); } /// Check if an SsxDeque element is currently enqueued /// /// \param element Typically the SsxDeque object of a queable structure /// /// \retval 0 The element is not currently enqueued /// /// \retval 1 The element is currently enqueued static inline int ssx_deque_is_queued(SsxDeque* element) { return (element->next != 0); } /// Append an element to the tail of a deque (FIFO order) /// /// \param deque The sentinel node of a deque /// /// \param element Typically the SsxDeque object of a queable structure /// /// It is an error to call this API on an element that is already enqueued, /// but the API does not check for this error. static inline void ssx_deque_push_back(SsxDeque* deque, SsxDeque* element) { deque->previous->next = element; element->previous = deque->previous; element->next = deque; deque->previous = element; } /// Push an element at the head of a deque (LIFO order) /// /// \param deque The sentinel node of a deque /// /// \param element Typically the SsxDeque object of a queable structure /// /// It is an error to call this API on an element that is already enqueued, /// but the API does not check for this error. static inline void ssx_deque_push_front(SsxDeque* deque, SsxDeque* element) { deque->next->previous = element; element->next = deque->next; element->previous = deque; deque->next = element; } /// Pop an element from the head of a deque /// /// \param deque The sentinel node of a deque /// /// \retval 0 The SsxDeque was empty prior to the call /// /// \retval non-0 A pointer to the previous head of the deque, which has been /// removed from the deque and marked as no longer queued. // The cast of 'head' is used to remove the 'volatile' attribute. static inline SsxDeque* ssx_deque_pop_front(SsxDeque* deque) { SsxDeque* head; if (ssx_deque_is_empty(deque)) { return 0; } else { head = (SsxDeque*)(deque->next); deque->next = head->next; deque->next->previous = deque; head->next = 0; return head; } } /// Remove a deque element from any position in the deque /// /// \param element Typically the SsxDeque object of a queable structure /// /// It is an error to call this API on an element that is not currently /// enqueued, but the API does not check for this error. static inline void ssx_deque_delete(SsxDeque* element) { element->previous->next = element->next; element->next->previous = element->previous; element->next = 0; } //Trace function prototypes void ssx_trace_tiny(uint32_t i_parm); void ssx_trace_big(uint32_t i_hash_and_count, uint64_t i_parm1, uint64_t i_parm2); void ssx_trace_binary(uint32_t i_hash_and_size, void* bufp); void ssx_trace_set_timebase(SsxTimebase timebase); void ssx_trace_init(uint32_t timebase_frequency_hz, SsxTimebase initial_timebase); /// Cast a pointer to another type, in a way that won't cause warnings #define SSX_CAST_POINTER(t, p) ((t)((SsxAddress)(p))) // Static Assert Macro for Compile time assertions. // - This macro can be used both inside and outside of a function. // - A value of false will cause the ASSERT to produce this error // - This will show up on a compile fail as: // <file>:<line> error: size of array '_static_assert' is negative // - It would be trivial to use the macro to paste a more descriptive // array name for each assert, but we will leave it like this for now. #define SSX_STATIC_ASSERT(cond) extern uint8_t _static_assert[(cond) ? 1 : -1] __attribute__ ((unused)) /// \page ssx_errors SSX API and Kernel Error Handling /// /// Error checking in the SSX API consumes a significant amount of code space. /// Approximately 20% of the object code in the PPC405 port is devoted to /// error checking. Presumably a like amount of time overhead is also added to /// SSX API calls by this checking. /// /// API error checking can be disabled to save space and time in the kernel. /// API errors can also be configured to cause kernel panics, allowing /// applications to be coded without the overhead of error checking but still /// providing an escape in the event of application errors or (unlikely) /// hardware failures. The SSX default is to check for API errors and kernel /// invariants, and panic should errors occur. /// /// SSX follows the Unix convention that a successful call of an API returns 0 /// (SSX_OK), but returns a negative code in the event of failure, or to /// provide further information. The error codes are all defined as manifest /// constants. /// /// Some negative codes returned by SSX APIs are not considered errors. These /// conditions are always checked, never cause a panic if they occur, and /// their interpretation is always left to the application. See the detailed /// documentation for each API for lists of error and non-error codes returned /// by the API. /// /// There are three configuration options that control error handling in the /// SSX API and kernel: /// /// \c SSX_ERROR_CHECK_API /// /// \arg \b 0 - No SSX API error checking. APIs that potentially return error /// codes will always return 0 (SSX_OK) instead of an error code. Those /// APIs that return negative codes that are not errors (see Table 1.5) /// always return the negative non-error codes when appropriate. /// /// \arg \b 1 - (Default) All SSX API errors are checked. The behavior in /// the event of an error is defined by the configuration option /// SSX_ERROR_PANIC. /// /// \c SSX_ERROR_CHECK_KERNEL /// /// \arg \b 0 - No kernel invariant error checking is done. /// /// \arg \b 1 - (Default) Selected kernel invariants are checked. The overhead /// for these checks should be minimal. /// /// \c SSX_ERROR_PANIC /// /// \arg \b 0 - SSX API calls return negative error codes in the event of /// errors. Note that SSX kernel invariants always cause a panic if /// violations occur. /// /// \arg \b 1 - (Default) In the event of errors SSX APIs invoke SSX_PANIC(code), /// where code is a positive error code. Kernel invariant checks always /// cause a panic if violations are detected. #endif /* __ASSEMBLER__ */ #endif /* __SSX_API_H__ */ <|start_filename|>src/occ_405/amec/amec_sensors_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_sensors_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /******************************************************************************/ /* Includes */ /******************************************************************************/ //#include <occ_common.h> #include <ssx.h> #include <errl.h> // Error logging #include "sensor.h" #include "rtls.h" #include "occ_sys_config.h" #include "occ_service_codes.h" // for SSX_GENERIC_FAILURE #include "dcom.h" #include "proc_data.h" #include "amec_smh.h" #include "amec_slave_smh.h" #include <trac.h> #include "amec_sys.h" #include "sensor_enum.h" #include "amec_service_codes.h" #include <amec_sensors_core.h> #include "amec_perfcount.h" #include "proc_shared.h" /******************************************************************************/ /* Globals */ /******************************************************************************/ extern data_cnfg_t * G_data_cnfg; /******************************************************************************/ /* Forward Declarations */ /******************************************************************************/ void amec_calc_dts_sensors(CoreData * i_core_data_ptr, uint8_t i_core); void amec_calc_freq_and_util_sensors(CoreData * i_core_data_ptr, uint8_t i_core); void amec_calc_ips_sensors(CoreData * i_core_data_ptr, uint8_t i_core); void amec_calc_droop_sensors(CoreData * i_core_data_ptr, uint8_t i_core); //*************************************************************************/ // Code //*************************************************************************/ // Function Specification // // Name: amec_update_proc_core_sensors // // Description: Update all the sensors for a given proc // // Thread: RealTime Loop // // End Function Specification void amec_update_proc_core_sensors(uint8_t i_core) { CoreData *l_core_data_ptr; uint32_t l_temp32 = 0; uint16_t l_core_temp = 0; uint16_t l_quad_temp = 0; uint16_t l_temp16 = 0; uint16_t l_core_util = 0; uint16_t l_core_freq = 0; uint16_t l_time_interval = 0; uint8_t i = 0; uint8_t l_quad = i_core / 4; // Quad this core resides in // Make sure the core is present, and that it has updated data. if(CORE_PRESENT(i_core) && CORE_UPDATED(i_core)) { // Clear flag indicating core was updated by proc task CLEAR_CORE_UPDATED(i_core); // Get pointer to core data l_core_data_ptr = proc_get_bulk_core_data_ptr(i_core); //------------------------------------------------------- // Thermal Sensors & Calc //------------------------------------------------------- amec_calc_dts_sensors(l_core_data_ptr, i_core); //------------------------------------------------------- // Util / Freq //------------------------------------------------------- // Skip this update if there was an empath collection error or if previously offline if (!CORE_EMPATH_ERROR(i_core) && !CORE_OFFLINE(i_core)) { amec_calc_freq_and_util_sensors(l_core_data_ptr,i_core); } //------------------------------------------------------- // Performance counter - This function should be called // after amec_calc_freq_and_util_sensors(). //------------------------------------------------------- if(!CORE_OFFLINE(i_core)) { amec_calc_dps_util_counters(i_core); } //------------------------------------------------------- // IPS //------------------------------------------------------- // Skip this update if there was an empath collection error if (!CORE_EMPATH_ERROR(i_core) && !CORE_OFFLINE(i_core)) { amec_calc_ips_sensors(l_core_data_ptr,i_core); } //------------------------------------------------------- // Update voltage droop counters //------------------------------------------------------- amec_calc_droop_sensors(l_core_data_ptr, i_core); // ------------------------------------------------------ // Update PREVIOUS values for next time // ------------------------------------------------------ // Thread raw cycles are equivalent to core raw cycles. g_amec->proc[0].core[i_core].prev_PC_RAW_Th_CYCLES = l_core_data_ptr->empath.raw_cycles; // Skip empath updates if there was an empath collection error on this core if (!CORE_EMPATH_ERROR(i_core)) { g_amec->proc[0].core[i_core].prev_PC_RAW_CYCLES = l_core_data_ptr->empath.raw_cycles; g_amec->proc[0].core[i_core].prev_PC_RUN_CYCLES = l_core_data_ptr->empath.run_cycles; g_amec->proc[0].core[i_core].prev_tod_2mhz = l_core_data_ptr->empath.tod_2mhz; g_amec->proc[0].core[i_core].prev_FREQ_SENS_BUSY = l_core_data_ptr->empath.freq_sens_busy; g_amec->proc[0].core[i_core].prev_FREQ_SENS_FINISH = l_core_data_ptr->empath.freq_sens_finish; } // Need to sum up all thread data for full core data g_amec->proc[0].core[i_core].prev_PC_COMPLETED = 0; g_amec->proc[0].core[i_core].prev_PC_DISPATCH = 0; for(i=0; i<MAX_THREADS_PER_CORE; i++) { g_amec->proc[0].core[i_core].prev_PC_COMPLETED += l_core_data_ptr->per_thread[i].completion; g_amec->proc[0].core[i_core].prev_PC_DISPATCH += l_core_data_ptr->per_thread[i].dispatch; g_amec->proc[0].core[i_core].thread[i].prev_PC_RUN_Th_CYCLES = l_core_data_ptr->per_thread[i].run_cycles; } // Final step is to update TOD sensors // Extract 32 bits with 16usec resolution l_temp32 = (uint32_t)(G_dcom_slv_inbox_doorbell_rx.tod>>13); l_temp16 = (uint16_t)(l_temp32); // low 16 bits is 16usec resolution with 512MHz TOD clock sensor_update( AMECSENSOR_PTR(TODclock0), l_temp16); l_temp16 = (uint16_t)(l_temp32>>16); // mid 16 bits is 1.05sec resolution with 512MHz TOD clock sensor_update( AMECSENSOR_PTR(TODclock1), l_temp16); l_temp16 = (uint16_t)(G_dcom_slv_inbox_doorbell_rx.tod>>45); // hi 3 bits in 0.796 day resolution with 512MHz TOD clock sensor_update( AMECSENSOR_PTR(TODclock2), l_temp16); // Core must be online that it was updated and now that the sensors have been updated make sure // the core offline bit is off for this core. Clearing this prior to updating the temperature // sensors may result in a false processor timeout error in health monitor CLEAR_CORE_OFFLINE(i_core); } // if core present and updated else if(CORE_OFFLINE(i_core)) { // core wasn't updated due to being offline, update sensors accordingly // Determine "core" temperature that will be returned in the poll for fan control // If there is at least 1 core online within the same quad use the quad temp else use the nest // verify quad temp is valid (not zero) this may be 0 if there were no valid quad DTS l_quad_temp = AMECSENSOR_ARRAY_PTR(TEMPQ0, l_quad)->sample; if( (QUAD_ONLINE(l_quad)) && l_quad_temp ) { l_core_temp = l_quad_temp; } else { l_core_temp = getSensorByGsid(TEMPNEST)->sample; } if(l_core_temp) { sensor_update(AMECSENSOR_ARRAY_PTR(TEMPPROCTHRMC0,i_core), l_core_temp); } // Update utilization and frequency sensors to 0 sensor_update(AMECSENSOR_ARRAY_PTR(NUTILC0, i_core), 0); sensor_update(AMECSENSOR_ARRAY_PTR(UTILC0, i_core), 0); sensor_update(AMECSENSOR_ARRAY_PTR(IPSC0, i_core), 0); sensor_update(AMECSENSOR_ARRAY_PTR(NOTBZEC0, i_core), 0); sensor_update(AMECSENSOR_ARRAY_PTR(NOTFINC0, i_core), 0); sensor_update(AMECSENSOR_ARRAY_PTR(FREQAC0, i_core), 0); for(i=0; i<MAX_THREADS_PER_CORE; i++) { g_amec->proc[0].core[i_core].thread[i].util4ms_thread = 0; } // Make updates for rolling average // Determine the time interval for the rolling average calculation l_time_interval = AMEC_DPS_SAMPLING_RATE * AMEC_IPS_AVRG_INTERVAL; // Increment sample count if(g_amec->proc[0].core[i_core].sample_count < UINT16_MAX) { g_amec->proc[0].core[i_core].sample_count++; } if(g_amec->proc[0].core[i_core].sample_count == l_time_interval) { // Increase resolution of the UTIL accumulator by two decimal places l_temp32 = (uint32_t)AMECSENSOR_ARRAY_PTR(UTILC0,i_core)->accumulator * 100; // Calculate average utilization of this core l_temp32 = l_temp32 / g_amec->proc[0].core[i_core].sample_count; g_amec->proc[0].core[i_core].avg_util = l_temp32; // Increase resolution of the FREQA accumulator by two decimal places l_temp32 = (uint32_t)AMECSENSOR_ARRAY_PTR(FREQAC0,i_core)->accumulator * 100; // Calculate average frequency of this core l_temp32 = l_temp32 / g_amec->proc[0].core[i_core].sample_count; g_amec->proc[0].core[i_core].avg_freq = l_temp32; } else if(g_amec->proc[0].core[i_core].sample_count > l_time_interval) { // Calculate average utilization for this core l_temp32 = (uint32_t) g_amec->proc[0].core[i_core].avg_util; l_temp32 = l_temp32 * (l_time_interval-1); l_temp32 = l_temp32 + l_core_util*100; g_amec->proc[0].core[i_core].avg_util = l_temp32 / l_time_interval; // Calculate average frequency for this core l_temp32 = (uint32_t) g_amec->proc[0].core[i_core].avg_freq; l_temp32 = l_temp32 * (l_time_interval-1); l_temp32 = l_temp32 + l_core_freq*100; g_amec->proc[0].core[i_core].avg_freq = l_temp32 / l_time_interval; } } // else if core offline } // Function Specification // // Name: amec_calc_dts_sensors // // Description: Compute core temperature. This function is called every // CORE_DATA_COLLECTION_US/core. // // PreCondition: The core is present. // // Thread: RealTime Loop // // End Function Specification void amec_calc_dts_sensors(CoreData * i_core_data_ptr, uint8_t i_core) { #define DTS_PER_CORE 2 #define QUAD_DTS_PER_CORE 2 uint32_t l_coreTemp = 0; uint8_t k = 0; uint16_t l_coreDts[DTS_PER_CORE] = {0}; uint16_t l_quadDts[QUAD_DTS_PER_CORE] = {0}; uint16_t l_quadDtsTemp = 0; // The one Quad DTS temp closest to the core BOOLEAN l_update_sensor = FALSE; uint16_t l_core_hot = 0; uint8_t l_coreDtsCnt = 0; // Number of valid Core DTSs uint8_t l_quadDtsCnt = 0; // Number of valid Quad DTSs uint32_t l_dtsAvg = 0; // Average of the two core or quad dts readings uint8_t cWt = 0; // core weight: zero unless at least one valid core dts reading uint8_t qWt = 0; // quad weight: zero unless we have a valid quad dts reading uint8_t l_quad = 0; // Quad this core resides in static bool L_bad_read_trace = FALSE; if (i_core_data_ptr != NULL) { //the Core DTS temperatures are considered in the calculation only if: // - They are valid. // - Non-zero // - Non-negative for (k = 0; k < DTS_PER_CORE; k++) { //Check validity if (i_core_data_ptr->dts.core[k].fields.valid) { // temperature is only 8 bits of reading field l_coreDts[k] = (i_core_data_ptr->dts.core[k].fields.reading & 0xFF); l_coreDtsCnt++; //Hardware bug workaround: Module test will detect bad DTS and write coefficients //to force a reading of 0 or negative to indicate the DTS is bad. //Throw out any DTS that is bad if(((l_coreDts[k] & DTS_INVALID_MASK) == DTS_INVALID_MASK) || (l_coreDts[k] == 0)) { l_coreDts[k] = 0; l_coreDtsCnt--; } if (l_coreDts[k] > l_core_hot) { l_core_hot = l_coreDts[k]; } } } //for loop // The core DTSs are considered only if we have at least 1 valid core DTS and // a non-zero G_coreWeight. However we want to keep track of the raw core DTS // values regardless of weight. if (l_coreDtsCnt) { if (G_data_cnfg->thrm_thresh.proc_core_weight) { l_update_sensor = TRUE; cWt = G_data_cnfg->thrm_thresh.proc_core_weight; } // Update the raw core DTS reading (average of the two) l_dtsAvg = (l_coreDts[0] + l_coreDts[1]) / l_coreDtsCnt; sensor_update( AMECSENSOR_ARRAY_PTR(TEMPC0, i_core), l_dtsAvg); } // The Quad DTS value is considered only if we have a valid Quad DTS and // a non-zero quad weight. However we want to keep track of the raw Quad // DTS values regardless of weight. for (k = 0; k < QUAD_DTS_PER_CORE; k++) { // temperature is only 8 bits of reading field l_quadDtsTemp = (i_core_data_ptr->dts.cache[k].fields.reading & 0xFF); if( (i_core_data_ptr->dts.cache[k].fields.valid) && ((l_quadDtsTemp & DTS_INVALID_MASK) != DTS_INVALID_MASK) && (l_quadDtsTemp != 0) ) { l_quadDts[k] = l_quadDtsTemp; l_quadDtsCnt++; } } l_quadDtsTemp = 0; if(l_quadDtsCnt) { if (G_data_cnfg->thrm_thresh.proc_quad_weight) { l_update_sensor = TRUE; qWt = G_data_cnfg->thrm_thresh.proc_quad_weight; } // Determine the quad this core resides in. l_quad = i_core / 4; // Update the raw quad DTS reading (average of the two) l_dtsAvg = (l_quadDts[0] + l_quadDts[1]) / l_quadDtsCnt; sensor_update( AMECSENSOR_ARRAY_PTR(TEMPQ0, l_quad), l_dtsAvg); // Pick the 1 quad DTS closest to the core for updating the thermal sensor // only want 1 quad DTS to handle case when 2 cores from same EX are offline // last 2 cores use dts1, first 2 cores use dts0 if(i_core & 0x02) l_quadDtsTemp = l_quadDts[1]; else l_quadDtsTemp = l_quadDts[0]; if(l_quadDtsTemp == 0) qWt = 0; // No quad temp to include in average } // Update the thermal sensor associated with this core if(l_update_sensor) { do { // Make sure data is valid if ( !((cWt && l_coreDtsCnt) || qWt) ) { if(FALSE == L_bad_read_trace) { TRAC_ERR("amec_calc_dts_sensors: updating DTS sensors skipped. " "core weight: %d, core DTSs: %d, quad weight: %d ", cWt, l_coreDtsCnt, qWt); L_bad_read_trace = TRUE; } // Avoid divide by zero break; } //Formula: // (cWt(CoreDTS1 + CoreDTS2) + qWt(QuadDTS)) // ------------------------------------------ // (2*cWt + qWt) l_coreTemp = ( (cWt * (l_coreDts[0] + l_coreDts[1])) + (qWt * l_quadDtsTemp) ) / // --------------------------------------------------------------------------------- ( (l_coreDtsCnt * cWt) + qWt ); // Update sensors & Interim Data sensor_update( AMECSENSOR_ARRAY_PTR(TEMPPROCTHRMC0,i_core), l_coreTemp); g_amec->proc[0].core[i_core].dts_hottest = l_core_hot; } while(0); } } } // Function Specification // // Name: amec_calc_freq_and_util_sensors // // Description: Compute the frequency and utilization sensors for a given core. // This function is called CORE_DATA_COLLECTION_US per core. // // Thread: RealTime Loop // // End Function Specification void amec_calc_freq_and_util_sensors(CoreData * i_core_data_ptr, uint8_t i_core) { BOOLEAN l_core_sleep_winkle = FALSE; uint32_t l_stop_state_hist_reg = 0; uint32_t temp32 = 0; uint32_t temp32a = 0; uint16_t temp16 = 0; uint16_t l_core_util = 0; uint16_t l_core_freq = 0; uint16_t l_time_interval = 0; uint32_t l_cycles4ms = 0; int i; // Read the high-order bytes of OCC Stop State History Register l_stop_state_hist_reg = (uint32_t) (i_core_data_ptr->stop_state_hist >> 32); // If core is in fast/deep sleep mode or fast/winkle mode, then set a flag // indicating this if(l_stop_state_hist_reg & OCC_CORE_STOP_GATED) { l_core_sleep_winkle = TRUE; } // ------------------------------------------------------ // Per Core Frequency // ------------------------------------------------------ // <amec_formula> // Result: Calculated Core Frequency // Sensor: FREQAC0 // Timescale: CORE_DATA_COLLECTION_US // Units: MHz // Min/Max: 0/6000 (UPPER_LIMIT_PROC_FREQ_MHZ=6000) // Formula: cyc_delta(cycles) = (RAW_CYCLES[t=now] - RAW_CYCLES[t=-CORE_DATA_COLLECTION_US]) // time_delta(TOD ticks) = (TOD[t=now] - TOD[t=-CORE_DATA_COLLECTION_US]) // frequency(MHz) = (cyc_delta / time_delta) * (2M TOD ticks / 1 second) // = (2 * cyc_delta) / time_delta // NOTE: cyc_delta is the total number of cycles in CORE_DATA_COLLECTION_US time for the core // NOTE: In the HWP where we aquire the TOD count, we shift the counter by 8 // which causes each TOD tick here to equate to 0.5us. This is why we // are multiplying by 2 in the above equation. // </amec_formula> // Compute Delta in PC_RAW_CYCLES temp32 = i_core_data_ptr->empath.raw_cycles; temp32a = g_amec->proc[0].core[i_core].prev_PC_RAW_CYCLES; temp32 = l_cycles4ms = temp32 - temp32a; temp32a = (i_core_data_ptr->empath.tod_2mhz - g_amec->proc[0].core[i_core].prev_tod_2mhz); if (0 == temp32a) temp32 = 0; else temp32 = (2 * temp32) / temp32a; if(temp32 < UPPER_LIMIT_PROC_FREQ_MHZ) { // Update Sensor for this core if(l_core_sleep_winkle) { l_core_freq = 0; } else { l_core_freq = (uint16_t) temp32; } sensor_update( AMECSENSOR_ARRAY_PTR(FREQAC0,i_core), l_core_freq); } // ------------------------------------------------------ // Per Core Utilization // ------------------------------------------------------ // <amec_formula> // Result: Calculated Core Utilization // Sensor: UTILC0 // Timescale: CORE_DATA_COLLECTION_US // Units: 0.01 % // Min/Max: 0/10000 (0/100%) // Formula: cyc_delta = (RAW_CYCLES[t=now] - RAW_CYCLES[t=-CORE_DATA_COLLECTION_US]) // run_delta = (RUN_CYCLES[t=now] - RUN_CYCLES[t=-CORE_DATA_COLLECTION_US]) // UTIL(in %) = run_delta / cyc_delta // // NOTE: cyc_delta is the total number of cycles in CORE_DATA_COLLECTION_US time for the core // NOTE: run_delta is the total number of cycles utilized by a specific core in CORE_DATA_COLLECTION_US // </amec_formula> // Compute Delta in PC_RUN_CYCLES temp32 = i_core_data_ptr->empath.run_cycles; temp32a = g_amec->proc[0].core[i_core].prev_PC_RUN_CYCLES; temp32 = temp32 - temp32a; temp32 = temp32 >> 8; // Drop non-significant bits temp32 = temp32 * 10000; // .01% resolution temp32a = l_cycles4ms; // Get Raw cycles temp32a = temp32a >> 8; // Drop non-significant bits // Calculate Utilization if(0 == temp32a) temp32 = 0; // Prevent a divide by zero else temp32 = temp32 / temp32a; // Update Sensor for this core if(l_core_sleep_winkle) { l_core_util = 0; } else { l_core_util = (uint16_t) temp32; } sensor_update(AMECSENSOR_ARRAY_PTR(UTILC0, i_core), l_core_util); // ------------------------------------------------------ // Per Thread Utilization // ------------------------------------------------------ // <amec_formula> // Result: Calculated Core Utilization // Sensor: None // Timescale: CORE_DATA_COLLECTION_US // Units: 0.01 % // Min/Max: 0/10000 (0/100%) // Formula: cyc_delta = (RAW_CYCLES[t=now] - RAW_CYCLES[t=-CORE_DATA_COLLECTION_US]) // run_delta = (RUN_CYCLES[t=now] - RUN_CYCLES[t=-CORE_DATA_COLLECTION_US]) // UTIL(in %) = run_delta / cyc_delta // // NOTE: cyc_delta is the total number of cycles run by the core in CORE_DATA_COLLECTION_US // NOTE: run_delta is the total number of cycles run by a specific thread in CORE_DATA_COLLECTION_US // </amec_formula> // Get RAW CYCLES for Thread // Thread raw cycles are the same as core raw cycles temp32 = i_core_data_ptr->empath.raw_cycles; temp32a = g_amec->proc[0].core[i_core].prev_PC_RAW_Th_CYCLES; l_cycles4ms = temp32 - temp32a; for(i=0; i<MAX_THREADS_PER_CORE; i++) { // Get Run Counters for Thread temp32 = i_core_data_ptr->per_thread[i].run_cycles; temp32a = g_amec->proc[0].core[i_core].thread[i].prev_PC_RUN_Th_CYCLES; temp32 = temp32 - temp32a; temp32 = temp32 >> 8; // Drop non-significant bits temp32 = temp32 * 10000; // resolution 0.01% temp32a = l_cycles4ms; temp32a = temp32a >> 8; // Drop non-significant bits // Calculate Utilization if (0 == temp32a) temp32 = 0; // Prevent divide by 0 else temp32 = temp32 / temp32a; // Update per thread value for this core if(l_core_sleep_winkle) { temp32 = 0; } g_amec->proc[0].core[i_core].thread[i].util4ms_thread = (uint16_t) temp32; } // No sensors to update for perThread Util // ------------------------------------------------------ // Per Core Stop State Sensors // ------------------------------------------------------ // Get deepest idle state requested since the last read. bits 12:15 OCC stop state hist reg temp16 = CONVERT_UINT64_UINT16_UPPER(i_core_data_ptr->stop_state_hist); temp16 &= 0x000F; if(temp16 != 0x000F) // Don't update with reset value { sensor_update(AMECSENSOR_ARRAY_PTR(STOPDEEPREQC0,i_core), temp16); } // Get deepest idle state entered by the chiplet since the last read bits 16:19 OCC stop state hist reg temp16 = CONVERT_UINT64_UINT16_MIDUPPER(i_core_data_ptr->stop_state_hist); temp16 = temp16 >> 12; temp16 = temp16 & 0x000F; if(temp16 != 0x000F) // Don't update with reset value { sensor_update(AMECSENSOR_ARRAY_PTR(STOPDEEPACTC0,i_core), temp16); } // ------------------------------------------------------ // Core Stall counters // ------------------------------------------------------ temp32 = i_core_data_ptr->empath.freq_sens_busy; temp32a = g_amec->proc[0].core[i_core].prev_FREQ_SENS_BUSY; temp32 = temp32 - temp32a; temp32 = temp32 >> 8; // See if core is sleeping/winkled if(l_core_sleep_winkle) { temp32 = 0; } // Update Sensor for this core sensor_update( AMECSENSOR_ARRAY_PTR(NOTBZEC0,i_core), (uint16_t) temp32); temp32 = i_core_data_ptr->empath.freq_sens_finish; temp32a = g_amec->proc[0].core[i_core].prev_FREQ_SENS_FINISH; temp32 = temp32 - temp32a; temp32 = temp32 >> 8; // See if core is sleeping/winkled if(l_core_sleep_winkle) { temp32 = 0; } // Update Sensor for this core sensor_update( AMECSENSOR_ARRAY_PTR(NOTFINC0,i_core), (uint16_t) temp32); // ------------------------------------------------------ // Per Core Normalized Average Utilization // ------------------------------------------------------ // <amec_formula> // Result: Calculated Normalized Average Core Utilization // Sensor: NUTILC0 // Timescale: CORE_DATA_COLLECTION_US (3s rolling average) // Units: 0.01 % // Min/Max: 0/10000 (0/100%) // </amec_formula> // Determine the time interval for the rolling average calculation l_time_interval = AMEC_DPS_SAMPLING_RATE * AMEC_IPS_AVRG_INTERVAL; // Increment our sample count but prevent it from wrapping if(g_amec->proc[0].core[i_core].sample_count < UINT16_MAX) { g_amec->proc[0].core[i_core].sample_count++; } if(g_amec->proc[0].core[i_core].sample_count == l_time_interval) { // Increase resolution of the UTIL accumulator by two decimal places temp32 = (uint32_t)AMECSENSOR_ARRAY_PTR(UTILC0,i_core)->accumulator * 100; // Calculate average utilization of this core temp32 = temp32 / g_amec->proc[0].core[i_core].sample_count; g_amec->proc[0].core[i_core].avg_util = temp32; // Increase resolution of the FREQA accumulator by two decimal places temp32 = (uint32_t)AMECSENSOR_ARRAY_PTR(FREQAC0,i_core)->accumulator * 100; // Calculate average frequency of this core temp32 = temp32 / g_amec->proc[0].core[i_core].sample_count; g_amec->proc[0].core[i_core].avg_freq = temp32; } if(g_amec->proc[0].core[i_core].sample_count > l_time_interval) { // Calculate average utilization for this core temp32 = (uint32_t) g_amec->proc[0].core[i_core].avg_util; temp32 = temp32 * (l_time_interval-1); temp32 = temp32 + l_core_util*100; g_amec->proc[0].core[i_core].avg_util = temp32 / l_time_interval; // Calculate average frequency for this core temp32 = (uint32_t) g_amec->proc[0].core[i_core].avg_freq; temp32 = temp32 * (l_time_interval-1); temp32 = temp32 + l_core_freq*100; g_amec->proc[0].core[i_core].avg_freq = temp32 / l_time_interval; } // Calculate the normalized utilization for this core if(g_amec->proc[0].core[i_core].avg_freq != 0) { // First, revert back to the original resolution of the sensors temp32 = g_amec->proc[0].core[i_core].avg_util / 100; temp32a = g_amec->proc[0].core[i_core].avg_freq / 100; // Compute now the normalized utilization as follows: // Normalized utilization = (Average_utilization)/(Average_frequency) * Fnom // Note: The 100000 constant is to increase the precision of our division temp32 = (temp32 * 100000) / temp32a; temp32 = (temp32 * G_sysConfigData.sys_mode_freq.table[OCC_MODE_NOMINAL]) / 100000; // Update sensor for this core if(l_core_sleep_winkle) { sensor_update(AMECSENSOR_ARRAY_PTR(NUTILC0, i_core), 0); } else { sensor_update(AMECSENSOR_ARRAY_PTR(NUTILC0, i_core), (uint16_t)temp32); } } } void amec_calc_ips_sensors(CoreData * i_core_data_ptr, uint8_t i_core) { #define TWO_PWR_24_MASK 0x00FFFFFF #define TWO_PWR_20_MASK 0x000FFFFF /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ INT32 cyc1 = 0; //cycle counts INT32 cyc2 = 0; UINT32 fin1 = 0; //finished instruction counts UINT32 fin2 = 0; INT32 disp1 = 0; //dispatched instruction counts INT32 disp2 = 0; UINT32 temp32 = 0; UINT32 ticks_2mhz = 0; // IPS sensor interval in 2mhz ticks BOOLEAN l_core_sleep_winkle = FALSE; uint32_t l_stop_state_hist_reg = 0; uint8_t thread = 0; // Read the high-order bytes of OCC Stop State History Register l_stop_state_hist_reg = (uint32_t) (i_core_data_ptr->stop_state_hist >> 32); // If core is in fast/deep sleep mode or fast/winkle mode, then set a flag // indicating this if(l_stop_state_hist_reg & OCC_CORE_STOP_GATED) { l_core_sleep_winkle = TRUE; } /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // Get current and last run Cycles cyc1 = i_core_data_ptr->empath.run_cycles; cyc2 = g_amec->proc[0].core[i_core].prev_PC_RUN_CYCLES; cyc2 = cyc1 - cyc2; // Calculate core completion and dispatch (sum of all threads) for ( thread = 0; thread < MAX_THREADS_PER_CORE; thread++ ) { fin1 += i_core_data_ptr->per_thread[thread].completion; disp1 += i_core_data_ptr->per_thread[thread].dispatch; } // Calculate delta of completed instructions fin2 = g_amec->proc[0].core[i_core].prev_PC_COMPLETED; fin2 = fin1 - fin2; // Calculate delta of dispatched instructions disp2 = g_amec->proc[0].core[i_core].prev_PC_DISPATCH; disp2 = disp1 - disp2; // ------------------------------------------------------ // Per Core IPC Calculation // ------------------------------------------------------ // <amec_formula> // Result: Calculated Instructions per Cycle // Sensor: None // Timescale: CORE_DATA_COLLECTION_US // Units: 0.01 IPC // Min/Max: ? // Formula: ipc_delta = (INST_COMPLETE[t=now] - INST_COMPLETE[t=-CORE_DATA_COLLECTION_US]) // run_cycles = (RUN_CYCLES[t=now] - RUN_CYCLES[t=-CORE_DATA_COLLECTION_US]) // 100 = Convert 0.01 IPC // // IPC(in 0.01 IPC) = (ipc_delta * 100) / run_cycles // </amec_formula> temp32 = (fin2 * 100); // Number of instructions completed (x100) if (0 == cyc2) temp32 = 0; // Prevent divide by zero else temp32 = temp32 / cyc2; // In units of 0.01 IPC g_amec->proc[0].core[i_core].ipc = temp32; // Currently unused // ------------------------------------------------------ // Per Core DPC Calculation // ------------------------------------------------------ // <amec_formula> // Result: Calculated dispatched Instructions per Cycle // Sensor: None // Timescale: CORE_DATA_COLLECTION_US // Units: 0.01 DPC // Min/Max: ? // Formula: dpc_delta = (INST_DISPATCH[t=now] - INST_DISPATCH[t=-CORE_DATA_COLLECTION_US]) // run_cycles = (RUN_CYCLES[t=now] - RUN_CYCLES[t=-CORE_DATA_COLLECTION_US]) // 100 = Convert 0.01 DPC // // DPC(in 0.01DPC) = (dpc_delta * 100) / run_cycles // </amec_formula> temp32 = (disp2 * 100); // Number of instructions dispatched (x100) if (0 == cyc2) temp32 = 0; // Prevent divide by zero else temp32 = temp32 / cyc2; // In units of 0.01 DPC g_amec->proc[0].core[i_core].dpc = temp32; // Currently unused // ------------------------------------------------------ // Per Core DPS Calculation // ------------------------------------------------------ // <amec_formula> // Result: Calculated dispatched Instructions per Second // Sensor: None // Timescale: CORE_DATA_COLLECTION_US // Units: 0.2Mips // Min/Max: ? // Formula: dps_delta = (INST_DISPATCH[t=now] - INST_DISPATCH[t=-CORE_DATA_COLLECTION_US]) // 250 = # of CORE_DATA_COLLECTION_US periods in 1 second // 50,000 = Convert IPS to 0.2MIPS // // DPS(in 0.2Mips) = (dps_delta * 250) / 50,000 // </amec_formula> temp32 = (disp2 * AMEC_CORE_COLLECTION_1SEC); // Number of instructions dispatched extrapolated to 1s. temp32 = temp32 / 50000; // In units of 0.2Mips (max 327675 Mips for uint16_t) g_amec->proc[0].core[i_core].dps = temp32; // Currently unused // ------------------------------------------------------ // Per Core IPS Calculation // ------------------------------------------------------ // <amec_formula> // Result: Calculated Instructions per Second // Sensor: IPSC0 // Timescale: CORE_DATA_COLLECTION_US // Units: 0.2Mips // Min/Max: ? // Formula: // comp_delta = (INST_COMPLETE[t=now] - INST_COMPLETE[t=-CORE_DATA_COLLECTION_US]) // ticks_delta = (TOD[t=now] - TOD[t=-CORE_DATA_COLLECTION_US]) // MIPS = comp_delta (insns/interval) * (1 interval per ticks_delta 2mhz ticks) * (2M 2mhz ticks / s) / 1M // = (2* fin2) / ticks_2mhz // // Note: For best resolution do multiply first and division last. // Note: For an explanation regarding the multiply by 2, see the note under FREQAC0. // </amec_formula> ticks_2mhz = i_core_data_ptr->empath.tod_2mhz - g_amec->proc[0].core[i_core].prev_tod_2mhz; if (0 == ticks_2mhz) temp32 = 0; else temp32 = (fin2 << 1) / ticks_2mhz; // See if core is sleeping/winkled if(l_core_sleep_winkle) { temp32 = 0; } sensor_update( AMECSENSOR_ARRAY_PTR(IPSC0,i_core), (uint16_t) temp32); } // ------------------------------------------------- // Droop count sum for core and quad // ------------------------------------------------ void amec_calc_droop_sensors(CoreData * i_core_data_ptr, uint8_t i_core) { //CoreData only has any new droop events since the last time CoreData was read uint32_t l_quad_droops = i_core_data_ptr->droop.cache_large_event; uint32_t l_core_droops = i_core_data_ptr->droop.core_small_event; int l_quad = i_core / 4; sensor_t * l_quad_sensor = AMECSENSOR_ARRAY_PTR(VOLTDROOPCNTQ0, l_quad); sensor_t * l_core_sensor = AMECSENSOR_ARRAY_PTR(VOLTDROOPCNTC0, i_core); sensor_update( l_core_sensor, l_core_droops); sensor_update( l_quad_sensor, l_quad_droops); // Update ERRH counters so it is known voltage droops are happening in call home data if(l_core_droops) { INCREMENT_ERR_HISTORY(ERRH_CORE_SMALL_DROOP); } if(l_quad_droops) { INCREMENT_ERR_HISTORY(ERRH_CACHE_LARGE_DROOP); } } /*----------------------------------------------------------------------------*/ /* End */ /*----------------------------------------------------------------------------*/ <|start_filename|>src/occ_gpe0/pk_app_irq_table.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/pk_app_irq_table.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" EXTERNAL_IRQ_TABLE_START IRQ_HANDLER_DEFAULT //OCCHW_IRQ_DEBUGGER IRQ_HANDLER_DEFAULT //OCCHW_IRQ_TRACE_TRIGGER IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBA_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_SRT_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE0_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE1_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE2_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_GPE3_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PPC405_HALT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCB_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_SPIPSS_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_PPC405 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE2 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_CHECK_STOP_GPE3 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_MALF_ALERT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_ADU_MALF_ALERT IRQ_HANDLER_DEFAULT //OCCHW_IRQ_EXTERNAL_TRAP IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IVRM_PVREF_ERROR IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_TIMER0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_OCC_TIMER1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_AVS_SLAVE0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_AVS_SLAVE1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI0_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI1_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI2_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI3_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI4_HI_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_ADCFSM_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_RESERVED_31 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBAX_OCC_SEND IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBAX_OCC_PUSH0 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBAX_OCC_PUSH1 IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBA_BCDE_ATTN IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PBA_BCUE_ATTN IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM0_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM0_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM1_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM1_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM2_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM2_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM3_PULL IRQ_HANDLER_DEFAULT //OCCHW_IRQ_STRM3_PUSH IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE0_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE1_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE2_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE3_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE4_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE5_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE6_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_PCB_INTR_TYPE7_PENDING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_0A_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_0B_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_1A_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PMC_O2S_1B_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_PSSBRIDGE_ONGOING IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI0_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI1_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI2_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI3_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_IPI4_LO_PRIORITY IRQ_HANDLER_DEFAULT //OCCHW_IRQ_RESERVED_63 EXTERNAL_IRQ_TABLE_END <|start_filename|>src/occ_405/pgpe/pgpe_service_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pgpe/pgpe_service_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _PGPE_SERVICE_CODES_H_ #define _PGPE_SERVICE_CODES_H_ #include <comp_ids.h> enum pgpeModuleId { PGPE_INIT_CLIPS_MOD = PGPE_COMP_ID | 0x00, PGPE_INIT_PMCR_MOD = PGPE_COMP_ID | 0x01, PGPE_INIT_START_SUSPEND_MOD = PGPE_COMP_ID | 0x02, PGPE_INIT_WOF_CONTROL_MOD = PGPE_COMP_ID | 0x03, PGPE_INIT_WOF_VFRT_MOD = PGPE_COMP_ID | 0x04, PGPE_CLIP_UPDATE_MOD = PGPE_COMP_ID | 0x05, PGPE_START_SUSPEND_MOD = PGPE_COMP_ID | 0x06, PGPE_PMCR_SET_MOD = PGPE_COMP_ID | 0x07, PGPE_SET_CLIP_RANGES_MOD = PGPE_COMP_ID | 0x08, PGPE_SET_CLIP_BLOCKING_MOD = PGPE_COMP_ID | 0x09, PGPE_START_SUSPEND_CALLBACK_MOD = PGPE_COMP_ID | 0x0A, }; #endif /* #ifndef _PGPE_SERVICE_CODES_H_ */ <|start_filename|>src/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2014,2017 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG ifndef BASE_OBJDIR BASE_OBJDIR = $(abspath ../obj) endif ifndef BASE_SRCDIR BASE_SRCDIR = $(abspath ./) endif ifndef BASE_BINDIR BASE_BINDIR = $(abspath ../bin) endif OBJDIR = $(BASE_OBJDIR)$(SUB_OBJDIR) SRCDIR = $(BASE_SRCDIR)$(SUB_SRCDIR) ifndef PPETRACEPP_DIR export PPETRACEPP_DIR = $(abspath ppe/tools/ppetracepp) endif ifndef PPETOOLS_OBJDIR export PPETOOLS_OBJDIR = $(abspath ../obj/ppetools) endif ifndef TRACEPP_DIR export TRACEPP_DIR = $(abspath tools/tracepp) endif ifndef PK_SRCDIR export PK_SRCDIR = $(abspath ppe/pk) endif ifndef GPE1_BIN_IMAGE_PATH export GPE1_BIN_IMAGE_PATH = $(BASE_BINDIR) endif THASH = $(PPETRACEPP_DIR)/tracehash.pl OCC_405_IMAGE_NAME = occ_405 OCC_GPE0_IMAGE_NAME = occ_gpe0 ifndef OPOCC_GPU_SUPPORT OCC_GPE1_IMAGE_NAME = occ_gpe1 else OCC_GPE1_IMAGE_NAME = gpu_gpe1 endif OCC_BOOTLOADER_DIR_NAME = occBootLoader OCC_BOOTLOADER_NAME = bootloader IMAGE_HDR_SCRIPT = imageHdrScript COMBINE_IMAGE_SUBDIRS = occBootLoader occ_405 occ_gpe0 occ_gpe1 COMBINEIMAGE = $(MAKE) combineImage -C $(dir) IMAGEFILE = $(OBJDIR)/image.bin ifndef OPOCC_GPU_SUPPORT NEEDED_IMAGES = \ $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(IMAGE_HDR_SCRIPT) \ $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).out \ $(OBJDIR)/$(OCC_GPE0_IMAGE_NAME)/$(OCC_GPE0_IMAGE_NAME).out \ $(OBJDIR)/$(OCC_GPE1_IMAGE_NAME)/$(OCC_GPE1_IMAGE_NAME).out \ $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(OCC_BOOTLOADER_NAME).out else NEEDED_IMAGES = \ $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(IMAGE_HDR_SCRIPT) \ $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).out \ $(OBJDIR)/$(OCC_GPE0_IMAGE_NAME)/$(OCC_GPE0_IMAGE_NAME).out \ $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(OCC_BOOTLOADER_NAME).out endif .PHONY : all all: ppetools $(NEEDED_IMAGES) combineImage tracehash .PHONY: ppetools ppetools: $(PPETOOLS_OBJDIR)/ppetracepp $(PPETOOLS_OBJDIR)/ppe2fsp $(PPETOOLS_OBJDIR)/tracepp $(PPETOOLS_OBJDIR)/ppetracepp: $(PPETOOLS_OBJDIR) g++ -O3 -w -g -I$(PPETRACEPP_DIR)/ $(PPETRACEPP_DIR)/ppetracepp.C -o $(PPETOOLS_OBJDIR)/ppetracepp $(PPETOOLS_OBJDIR)/ppe2fsp: $(PPETOOLS_OBJDIR) gcc -w -g -I./ -I$(PK_SRCDIR)/trace $(PPETRACEPP_DIR)/ppe2fsp.c $(PPETRACEPP_DIR)/ppe2fsp_cmd.c -o $(PPETOOLS_OBJDIR)/ppe2fsp $(PPETOOLS_OBJDIR): mkdir -p $(PPETOOLS_OBJDIR)/ .PHONY : needed_images needed_images: $(NEEDED_IMAGES) ifndef OPOCC_GPU_SUPPORT .PHONY : combineImage combineImage: $(NEEDED_IMAGES) rm -rf $(IMAGEFILE) BASE_OBJDIR=$(BASE_OBJDIR) $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(IMAGE_HDR_SCRIPT) \ $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(OCC_BOOTLOADER_NAME).bin \ $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).bin \ $(OBJDIR)/$(OCC_GPE0_IMAGE_NAME)/$(OCC_GPE0_IMAGE_NAME).bin \ $(OBJDIR)/$(OCC_GPE1_IMAGE_NAME)/$(OCC_GPE1_IMAGE_NAME).bin \ t2 \ `md5sum $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).bin | cut -c 1-4` else .PHONY : combineImage combineImage: $(NEEDED_IMAGES) rm -rf $(IMAGEFILE) BASE_OBJDIR=$(BASE_OBJDIR) $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(IMAGE_HDR_SCRIPT) \ $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(OCC_BOOTLOADER_NAME).bin \ $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).bin \ $(OBJDIR)/$(OCC_GPE0_IMAGE_NAME)/$(OCC_GPE0_IMAGE_NAME).bin \ $(GPE1_BIN_IMAGE_PATH)/$(OCC_GPE1_IMAGE_NAME).bin \ t2 \ `md5sum $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).bin | cut -c 1-4` endif #clean the obj directory .PHONY : clean clean: rm -fr $(OBJDIR) # Make binary application images .PHONY : $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).out $(OBJDIR)/$(OCC_405_IMAGE_NAME)/$(OCC_405_IMAGE_NAME).out: (cd $(SRCDIR)/$(OCC_405_IMAGE_NAME) && make) .PHONY : $(OBJDIR)/$(OCC_GPE0_IMAGE_NAME)/$(OCC_GPE0_IMAGE_NAME).out $(OBJDIR)/$(OCC_GPE0_IMAGE_NAME)/$(OCC_GPE0_IMAGE_NAME).out: (cd $(SRCDIR)/$(OCC_GPE0_IMAGE_NAME) && make) .PHONY : $(OBJDIR)/$(OCC_GPE1_IMAGE_NAME)/$(OCC_GPE1_IMAGE_NAME).out $(OBJDIR)/$(OCC_GPE1_IMAGE_NAME)/$(OCC_GPE1_IMAGE_NAME).out: (cd $(SRCDIR)/$(OCC_GPE1_IMAGE_NAME) && make) .PHONY : $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(OCC_BOOTLOADER_NAME).out $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(OCC_BOOTLOADER_NAME).out $(OBJDIR)/$(OCC_BOOTLOADER_DIR_NAME)/$(IMAGE_HDR_SCRIPT): (cd $(SRCDIR)/$(OCC_BOOTLOADER_DIR_NAME) && make) $(PPETOOLS_OBJDIR)/tracepp: (cd $(TRACEPP_DIR) && make) # collect all of the trace hash files for all OCC images into a single trexStringFile .PHONY : tracehash tracehash: mkdir -p $(BASE_OBJDIR) $(THASH) -c -d $(BASE_OBJDIR) -s $(BASE_OBJDIR)/occStringFile <|start_filename|>src/occ_gpe0/core_data.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/core_data.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file core_data.c /// \brief The GPE program that collect raw data for DTS and EMPATH /// #include "core_data.h" #include "p9_config.h" #include "ppe42_msr.h" #include "ppe42_scom.h" #include "cme_register_addresses.h" #include "cppm_register_addresses.h" #include "cppm_firmware_registers.h" #include "pk.h" #define CME_VDSR_BASE (CME_SCOM_VDSR & 0x00ffffff) // Global variables uint32_t g_vdm_cache_large_droop_count[MAX_NUM_QUADS]__attribute__((section (".sbss"))); uint32_t g_vdm_core_small_droop_count[MAX_NUM_CORES]__attribute__((section (".sbss"))); int g_fused_core = FUSED_UNKNOWN; uint32_t get_core_data(uint32_t i_core, CoreData* o_data) { uint32_t rc = 0; uint32_t size = sizeof(CoreData) / sizeof(uint64_t); uint64_t* ptr = (uint64_t*)o_data; uint32_t coreSelect = CHIPLET_CORE_ID(i_core); uint32_t quadSelect = CHIPLET_CACHE_ID((i_core / CORES_PER_QUAD)); uint64_t value64 = 0; uint32_t i,idx; for(i = 0; i < size; ++i) { ptr[i] = 0; } // Turn off MCR bit to prevent machine check on error on scom readings bits 1:7 // rc == 1 resource occupied (see ppe42_scom.h) // rc == 2 Core is fenced, offline // rc == 3 partial good // rc == 4 address error (Can be caused by other device using bus) // rc == 5 clock error // rc == 6 packet error // rc == 7 timeout uint32_t org_sem = mfmsr() & MSR_SEM; // Clear SIBRC and SIBRCA // mask off SIB errors as machine checks, return rc instead mtmsr((mfmsr() & ~(MSR_SIBRC | MSR_SIBRCA)) | MSR_SEM); // ============== // DTS // ============== do { dts_sensor_result_reg_t dts_scom_data; rc = getscom(quadSelect,THERM_DTS_RESULT, &(dts_scom_data.value)); if (rc) { break; } // Store the quad DTS readings o_data->dts.cache[0].result = dts_scom_data.half_words.reading[0]; o_data->dts.cache[1].result = dts_scom_data.half_words.reading[1]; rc = getscom(coreSelect, THERM_DTS_RESULT, &(dts_scom_data.value)); if (rc) { break; } o_data->dts.core[0].result = dts_scom_data.half_words.reading[0]; o_data->dts.core[1].result = dts_scom_data.half_words.reading[1]; // ============= // DROOP // ============= // Read Droop events. Event bit == 0 indicates event occurred. // Side effect of read: event bits are reset to 1 (no event) in hw // Only quad large droop and core small drop events are of interest rc = getscom(quadSelect, CME_VDSR_BASE, &value64); if (rc) { // DROOP events are not critial. Leave event counts as zero // and continue. PK_TRACE("Could not read droop events! rc = %d",rc); rc = 0; } else // update droop event counts { if((value64 & CACHE_VDM_LARGE_DROOP) == 0) { ++g_vdm_cache_large_droop_count[i_core / CORES_PER_QUAD]; } idx = (i_core / CORES_PER_QUAD) * CORES_PER_QUAD; if((value64 & CORE0_VDM_SMALL_DROOP) == 0) { ++g_vdm_core_small_droop_count[idx]; } if((value64 & CORE1_VDM_SMALL_DROOP) == 0) { ++g_vdm_core_small_droop_count[idx+1]; } if((value64 & CORE2_VDM_SMALL_DROOP) == 0) { ++g_vdm_core_small_droop_count[idx+2]; } if((value64 & CORE3_VDM_SMALL_DROOP) == 0) { ++g_vdm_core_small_droop_count[idx+3]; } // return the event status for the requested core and // corresponding quad. // Clear the counter for only the droop events returned. if(g_vdm_cache_large_droop_count[i_core / CORES_PER_QUAD] != 0) { o_data->droop.cache_large_event = 1; g_vdm_cache_large_droop_count[i_core / CORES_PER_QUAD] = 0; } if(g_vdm_core_small_droop_count[i_core] != 0) { o_data->droop.core_small_event = 1; g_vdm_core_small_droop_count[i_core] = 0; } } // ============= // EMPATH // ============= // Send command to select which emmpath counter to read do { uint64_t empath_scom_data = CORE_RAW_CYCLES; if(FUSED_UNKNOWN == g_fused_core) { cppm_cpmmr_t cpmmr; rc = getscom(coreSelect, CPPM_CPMMR, &(cpmmr.value)); if (rc) { // Retry on next tick break; } if (1 == cpmmr.fields.fused_core_mode) { g_fused_core = FUSED_TRUE; } else { g_fused_core = FUSED_FALSE; } } if(g_fused_core == FUSED_TRUE && ((i_core % 2) != 0)) { empath_scom_data |= SELECT_ODD_CORE; } rc = putscom(coreSelect, PC_OCC_SPRC, empath_scom_data); if (rc) { break; } // Read counters. // Counter selected auto increments to the next counter after each read. //CORE_RAW_CYCLES rc = getscom(coreSelect, PC_OCC_SPRD, &empath_scom_data); if (rc) { break; } o_data->empath.raw_cycles = (uint32_t)empath_scom_data; //CORE_RUN_CYCLES rc = getscom(coreSelect, PC_OCC_SPRD, &empath_scom_data); if (rc) { break; } o_data->empath.run_cycles = (uint32_t)empath_scom_data; //CORE_WORKRATE_BUSY rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->empath.freq_sens_busy = (uint32_t)empath_scom_data; //CORE_WORKRATE_FINISH rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->empath.freq_sens_finish = (uint32_t)empath_scom_data; //CORE_MEM_HIER_A_LATENCY rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->empath.mem_latency_a = (uint32_t)empath_scom_data; //CORE_MEM_HIER_B_LATENCY rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->empath.mem_latency_b = (uint32_t)empath_scom_data; //CORE_MEM_HIER_C_ACCESS rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->empath.mem_access_c = (uint32_t)empath_scom_data; int thread = 0; for( ; thread < EMPATH_CORE_THREADS; ++thread ) { // THREAD_RUN_CYCLES rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->per_thread[thread].run_cycles = (uint32_t)empath_scom_data; // THREAD_INST_DISP_UTIL rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->per_thread[thread].dispatch = (uint32_t)empath_scom_data; // THREAD_INST_COMP_UTIL rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->per_thread[thread].completion = (uint32_t)empath_scom_data; // THREAD_MEM_HEIR_C_ACCESS rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->per_thread[thread].mem_c = (uint32_t)empath_scom_data; } if (rc) { break; } //IFU_THROTTLE_BLOCK_FETCH rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->throttle.ifu_throttle = (uint32_t)empath_scom_data; //IFU_THROTTLE_ACTIVE rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->throttle.ifu_active = (uint32_t)empath_scom_data; //VOLT_DROOP_THROTTLE_ACTIVE rc = getscom(coreSelect, PC_OCC_SPRD,&empath_scom_data); if (rc) { break; } o_data->throttle.v_droop = (uint32_t)empath_scom_data; // TOD value rc = getscom_abs(TOD_VALUE_REG,&empath_scom_data); if (rc) { break; } o_data->empath.tod_2mhz = (uint32_t)(empath_scom_data >> 8); //[24..56] // STOP_STATE_HIST_OCC_REG rc = getscom(coreSelect, STOP_STATE_HIST_OCC_REG, &empath_scom_data); if (rc) { break; } o_data->stop_state_hist = empath_scom_data; o_data->empathValid = EMPATH_VALID; } while(0); // EMPATH if (rc) { // Work-around for HW problem. See SW407201 // If ADDRESS_ERROR then perform a SCOM write of all zeros to // 2n010800 where n is the core number. Ignore ADDRESS_ERROR // returned. EMPATH_VALID will be left unset to indicate the // EMPATH data is not valid, however, return SUCCESS to indicate // the DTS data is good. if(rc == SIBRC_ADDRESS_ERROR) { uint64_t zeros = 0; putscom(coreSelect,WORKAROUND_SCOM_ADDRESS, zeros); rc = 0; } } } while(0); // Clear masks SIB masks (MSR_SEM) // Clear SIBRC and SIMBRCA // Restore any SIB masks that may have been on before. mtmsr((mfmsr() & ~(MSR_SEM | MSR_SIBRC | MSR_SIBRCA)) | (org_sem & MSR_SEM)); return rc; } <|start_filename|>src/occ_405/sensor/sensor_query_list.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor_query_list.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _SENSORQUERYLIST_H #define _SENSORQUERYLIST_H //************************************************************************* // Includes //************************************************************************* #include <occ_common.h> //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* //************************************************************************* // Structures //************************************************************************* // Structure that is passed into querySensorList command // when it is called typedef struct { uint16_t i_startGsid; uint8_t i_present; uint16_t i_type; uint16_t i_loc; uint16_t * io_numOfSensors; sensorQueryList_t * o_sensors; sensor_info_t * o_sensorInfoPtrs; } querySensorListArg_t; //************************************************************************* // Globals //************************************************************************* //************************************************************************* // Function Prototypes //************************************************************************* errlHndl_t querySensorList(const querySensorListArg_t * i_argPtr); //************************************************************************* // Functions //************************************************************************* #endif <|start_filename|>src/occ_405/amec/amec_data.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_data.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_DATA_H #define _AMEC_DATA_H //************************************************************************* // Includes //************************************************************************* #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include <amec_smh.h> #include <errl.h> #include <mode.h> //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* //************************************************************************* // Structures //************************************************************************* //************************************************************************* // Globals //************************************************************************* //************************************************************************* // Function Prototypes //************************************************************************* //************************************************************************* // Functions //************************************************************************* // This is used to change the current Freq data AMEC is using errlHndl_t AMEC_data_write_fcurr(const OCC_MODE i_mode); // This is used to store the thermal thresholds AMEC is using errlHndl_t AMEC_data_write_thrm_thresholds(const OCC_MODE i_mode); // This is used to store the IPS config data AMEC is using errlHndl_t AMEC_data_write_ips_cnfg(void); // This is used to notify AMEC that there is a change to the configuration data errlHndl_t AMEC_data_change(const uint32_t i_data_mask); // Writes pcap data sent by master to slave accessable structure. void amec_data_write_pcap(); #endif <|start_filename|>src/occ_gpe1/gpe_gpu_init.c<|end_filename|> #include "pk.h" #include "ppe42_scom.h" #include "gpu_structs.h" #include "ipc_async_cmd.h" #include "gpe_err.h" #include "gpe_util.h" #include "p9_misc_scom_addresses.h" gpu_i2c_info_t G_gpu_i2c __attribute__((section(".sbss.G_gpu_i2c"))); void gpe_gpu_init(ipc_msg_t* cmd, void* arg) { int rc = 0; int i; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; gpu_init_args_t *args = (gpu_init_args_t*)async_cmd->cmd_data; args->error.ffdc = 0; // Prevent MCK attention on scom failes (PK kernel fix?) mtmsr((mfmsr() & ~(MSR_SIBRC | MSR_SIBRCA)) | MSR_SEM); // According to <NAME>, Setting PV_CP0_P_PRV_GPIO0 pin on the // processor chip to low enables HW to automatically apply GPU power brake. // GPIO1 (GPU_PWR_BRAKE_FORCE_N) will not be controlled by FW, so needs to // be configured as input. uint64_t data64 = 0x8000000000000000ull; rc = putscom_abs(PU_GPIO_OUTPUT_CLR,data64); if(rc) { PK_TRACE("gpe_gpu_init: PU_GPIO0_OUTPUT failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_GPU_INIT_FAILED, rc); } rc = getscom_abs(PU_GPIO_OUTPUT_EN, &data64); if(rc) { PK_TRACE("gpe_gpu_init: Read PU_GPIO0_OUTPUT_EN failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_GPU_INIT_FAILED, rc); } // pin0 as output, pin1 as input, pin2 unchanged data64 &= 0xBfffffffffffffffull; data64 |= 0x8000000000000000ull; rc = putscom_abs(PU_GPIO_OUTPUT_EN, data64); if(rc) { PK_TRACE("gpe_gpu_init: PU_GPIO0_OUTPUT_EN failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_GPU_INIT_FAILED, rc); } // Get i2c data G_gpu_i2c.pib_master = args->gpu_i2c.pib_master; G_gpu_i2c.bus_voltage = args->gpu_i2c.bus_voltage; for(i = 0; i < MAX_GPUS; ++i) { G_gpu_i2c.port[i] = args->gpu_i2c.port[i]; G_gpu_i2c.addr[i] = args->gpu_i2c.addr[i]; } rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("E>gpu_init: Failed to send response back. Halting GPE1", rc); pk_halt(); } } <|start_filename|>src/ssx/ssx/ssx_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_core.c /// \brief Core routines for the SSX kernel. /// /// The entry points in this file are routines that are expected to be needed /// at runtime by all SSX applications. This file also serves as a place for /// kernel global variables to be realized. #define __SSX_CORE_C__ #include "ssx.h" #if !SSX_TIMER_SUPPORT /// If there is no timer support, then any call of the timer interrupt handler /// is considered a fatal error. void __ssx_timer_handler() { SSX_PANIC(SSX_NO_TIMER_SUPPORT); } #endif /* SSX_TIMER_SUPPORT */ /// Initialize an SsxDeque sentinel node /// /// \param deque The sentinel node of the deque /// /// SSX has no way of knowing whether the \a deque is currently in use, so /// this API must only be called on unitialized or otherwise unused sentinel /// nodes. /// /// \retval 0 success /// /// \retval -SSX_INVALID_DEQUE_SENTINEL The \a deque pointer was null int ssx_deque_sentinel_create(SsxDeque* deque) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(deque == 0, SSX_INVALID_DEQUE_SENTINEL); } deque->next = deque->previous = deque; return 0; } /// Initialize an SsxDeque element /// /// \param element Typically the SsxDeque object of a queable structure /// /// SSX has no way of knowing whether the \a element is currently in use, so /// this API must only be called on unitialized or otherwise unused deque /// elements. /// /// \retval 0 success /// /// \retval -SSX_INVALID_DEQUE_ELEMENT The \a element pointer was null int ssx_deque_element_create(SsxDeque* element) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(element == 0, SSX_INVALID_DEQUE_ELEMENT); } element->next = 0; return 0; } #undef __SSX_CORE_C__ <|start_filename|>src/ssx/ppc405/ppc405_context.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_context.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_CONTEXT_H__ #define __PPC405_CONTEXT_H__ /// \file ppc405_context.h /// \brief PPC405 Machine and Thread context for SSX /// \page ppc405_machine_context PPC405 Assembler Macros for SSX Machine /// Context (Critical Sections) /// /// \section _ssx_enter_critical \b _ssx_critical_section_enter/exit /// /// These macro encapsulates the instruction sequences required to enter and /// exit critical sections, along with the machine context save for later /// exiting the critical section. /// /// \arg \c priority Either \c SSX_CRITICAL, \c SSX_NON_CRITICAL or /// SSX_SUPERCRITICAL (for \c ssx_critical_section_enter). /// /// \arg \c ctxreg A register that will hold (holds) the machine context (MSR) /// prior to entering the critical section (to be restored) for \c /// _ssx_critical_section_enter (\c _ssx_critical_section_exit). /// /// \arg \c scrreg A scratch register required for the computation of /// \c _ssx_critical_section_enter. /// /// Forms: /// /// \b _ssx_critical_section_enter \a priority, \a ctxreg, \a scrreg - Enter a /// critical section \n /// \b _ssx_critical_section_exit \a ctxreg - Exit a critical section #ifdef __ASSEMBLER__ // *INDENT-OFF* .set _msr_ee_bit, MSR_EE_BIT .set _msr_ce_bit, MSR_CE_BIT .macro _ssx_critical_section_enter priority, ctxreg, scrreg mfmsr \ctxreg .if ((\priority) == SSX_CRITICAL) _clrbit \scrreg, \ctxreg, _msr_ee_bit _clrbit \scrreg, \scrreg, _msr_ce_bit mtmsr \scrreg .elseif ((\priority) == SSX_SUPERCRITICAL) _liwa \scrreg, (MSR_APE | MSR_WE | MSR_CE | MSR_EE | MSR_ME | MSR_DWE | MSR_DE) andc \scrreg, \ctxreg, \scrreg mtmsr \scrreg .elseif ((\priority) == SSX_NONCRITICAL) wrteei 0 .else .error "'priority' was not one of SSX_CRITICAL, SSX_NONCRITICAL or SSX_SUPERCRITICAL" .endif isync .endm .macro _ssx_critical_section_exit ctxreg mtmsr \ctxreg isync .endm // **************************************************************************** // SSX context save/restore macros for 32-bit Embedded PowerPC // **************************************************************************** // All stack frames are 8-byte aligned in conformance with the EABI. SSX // never saves or restores GPR2 or GPR13. GPR13 is constant in (E)ABI // applications - the base of the read-write small data area. GPR2 is // system-reserved in ABI applications, and is the base for read-only small data // in EABI applications. // A fair amount of complexity is involved in handling the non-critical and // critical interrupt levels, and the emphasis on performance of fast-mode // interrupt handlers. Several different approaches and philosophies could // have been implemented - this is only one. In this implementation // critical/non-critical interrupt levels are treated more or less the same, // and the interrupt priority is just that - a kind of preemption priority. // Critical interrupt handling does have a little less overhead because it // does not have a thread scheduling step at the end. // A full context save takes place in 3 or 4 steps. Thread switches always do // steps 1, 2 and 3. // 1. The fast context that is always saved in response to every interrupt; // 1a. The optional save/update of the kernel context for interrupts. // 2. The (volatile - fast) context that is saved if an interrupt handler // switches from fast-mode to full-mode. // 3. The non-volatile context that is saved when a thread is switched out. // USPRG0 holds the __SsxKernelContext structure (defined in ppc405.h) that // represents the current kernel context. The layout is as follows: // // Bits Meaning // ============== // 0:7 The critical interrupt count // 8:15 The non-critical interrupt count // 16:23 The IRQ currently being processed // 24 The 'thread_mode' flag // 25:31 The thread priority of the running thread // // When SSX is initialized USPRG0 is initialized to 0. When thread-mode is // entered (by ssx_start_threads()) bit 24 is set to 1. In order to support // OCC firmware, once initialized (with ssx_initialize()) SSX can simply // handle interrupts, reverting back to the non-thread-mode idle loop when // there's nothing to do. // // Note that it would require a serious error for the interrupt counts to ever // equal or exceed 2**8 as this would imply runaway reentrancy and stack // overflow. In fact it is most likely an error if an interrupt handler is // ever re-entered while active. // Registers SRR2 and SRR3 are always saved in IRQ context because // __ssx_irq_fast2full must save the (volatile - fast) context to provide // working registers before it can look at USPRG0 to determine critical // vs. non-critical context. However, when restoring a non-critical interrupt // or thread these registers need not be restored. SRR2 and SRR3 are never // saved or restored for thread context switches, because threads always // operate at noncritical level. // When MMU protection is enabled, relocation/protection is re-established // immediately upon entry to the interrupt handler, before any memory // operations (load/store) take place. This requires using SPRG0 and SPGR4 // for temporary storage for noncritical/critical handlers respectively in // accordance with the SSX conventions for SPRGn usage by fast-mode // interrupts. ## ------------------------------------------------------------ ## Unused registers for embedded PowerPC ## ------------------------------------------------------------ ## Registers GPR2 and GPR13 are never saved or restored. In ABI and ## EABI applications these registers are constant. .set UNUSED_GPR2, 0x2 # Dedicated; EABI read-only small data area .set UNUSED_GPR13, 0xd # Dedicated; (E)ABI read-write small data area ## ------------------------------------------------------------ ## Flags for context push/pop ## ------------------------------------------------------------ .set SSX_THREAD_CONTEXT, 0 .set SSX_IRQ_CONTEXT, 1 ## ------------------------------------------------------------ ## The SSX fast context layout for Embedded PowerPC ## ------------------------------------------------------------ .set SSX_FAST_CTX_GPR1, 0x00 # Dedicated; Stack pointer .set SSX_FAST_CTX_HANDLER_LR, 0x04 # Slot for handler to store LR .set SSX_FAST_CTX_GPR3, 0x08 # Volatile; Parameter; Return Value .set SSX_FAST_CTX_GPR4, 0x0c # Volatile; Parameter .set SSX_FAST_CTX_GPR5, 0x10 # Volatile; Parameter .set SSX_FAST_CTX_GPR6, 0x14 # Volatile; Parameter .set SSX_FAST_CTX_GPR7, 0x18 # Volatile; Parameter .set SSX_FAST_CTX_CR, 0x1c # Condition register .set SSX_FAST_CTX_LR, 0x20 # Link register SPRN 0x008 .set SSX_FAST_CTX_KERNEL_CTX, 0x24 # Saved __SsxKernelContext for IRQ .set SSX_FAST_CTX_SIZE, 0x28 # Must be 8-byte aligned ## ------------------------------------------------------------ ## The SSX (volatile - fast) context layout for Embedded PowerPC ## ------------------------------------------------------------ .set SSX_VOL_FAST_CTX_GPR1, 0x00 # Dedicated; Stack pointer .set SSX_VOL_FAST_CTX_HANDLER_LR, 0x04 # Slot for handler to store LR .set SSX_VOL_FAST_CTX_GPR0, 0x08 # Volatile; Language specific .set SSX_VOL_FAST_CTX_GPR8, 0x0c # Volatile; Parameter .set SSX_VOL_FAST_CTX_GPR9, 0x10 # Volatile; Parameter .set SSX_VOL_FAST_CTX_GPR10, 0x14 # Volatile; Parameter .set SSX_VOL_FAST_CTX_GPR11, 0x18 # Volatile .set SSX_VOL_FAST_CTX_GPR12, 0x1c # Volatile .set SSX_VOL_FAST_CTX_XER, 0x20 # Fixed-point exception register SPRN 0x001 .set SSX_VOL_FAST_CTX_CTR, 0x24 # Count register SPRN 0x009 .set SSX_VOL_FAST_CTX_SRR0, 0x28 # Save/restore register 0 SPRN 0x01a .set SSX_VOL_FAST_CTX_SRR1, 0x2c # Save/restore register 1 SPRN 0x01b .set SSX_VOL_FAST_CTX_SRR2, 0x30 # Save/restore register 2 SPRN 0x3de .set SSX_VOL_FAST_CTX_SRR3, 0x34 # Save/restore register 3 SPRN 0x3df .set SSX_VOL_FAST_CTX_SIZE, 0x38 # Must be 8-byte aligned ## ------------------------------------------------------------ ## The SSX non-volatile context layout for Embedded PowerPC ## ------------------------------------------------------------ ## The 'preferred form' for stmw is for the LSB of R31 to fall into the ## end of a 16-byte aligned block. .set SSX_NON_VOL_CTX_GPR1, 0x0 # Dedicated; Stack Pointer .set SSX_NON_VOL_CTX_HANDLER_LR, 0x4 # Slot for handler to store LR .set SSX_NON_VOL_CTX_GPR14, 0x8 # Non-volatile .set SSX_NON_VOL_CTX_GPR15, 0xc # Non-volatile .set SSX_NON_VOL_CTX_GPR16, 0x10 # Non-volatile .set SSX_NON_VOL_CTX_GPR17, 0x14 # Non-volatile .set SSX_NON_VOL_CTX_GPR18, 0x18 # Non-volatile .set SSX_NON_VOL_CTX_GPR19, 0x1c # Non-volatile .set SSX_NON_VOL_CTX_GPR20, 0x20 # Non-volatile .set SSX_NON_VOL_CTX_GPR21, 0x24 # Non-volatile .set SSX_NON_VOL_CTX_GPR22, 0x28 # Non-volatile .set SSX_NON_VOL_CTX_GPR23, 0x2c # Non-volatile .set SSX_NON_VOL_CTX_GPR24, 0x30 # Non-volatile .set SSX_NON_VOL_CTX_GPR25, 0x34 # Non-volatile .set SSX_NON_VOL_CTX_GPR26, 0x38 # Non-volatile .set SSX_NON_VOL_CTX_GPR27, 0x3c # Non-volatile .set SSX_NON_VOL_CTX_GPR28, 0x40 # Non-volatile .set SSX_NON_VOL_CTX_GPR29, 0x44 # Non-volatile .set SSX_NON_VOL_CTX_GPR30, 0x48 # Non-volatile .set SSX_NON_VOL_CTX_GPR31, 0x4c # Non-volatile .set SSX_NON_VOL_CTX_SIZE, 0x50 # Must be 8-byte aligned ## ------------------------------------------------------------ ## Save/restore the fast context ## ## 11 Instructions, 8 Loads/Stores : If MMU is disabled ## 17 Instructions, 8 Loads/Stores : If MMU is enabled ## ------------------------------------------------------------ ## ## Without MMU support, an EIEIO is always executed at the entry point ## to gauarantee that all memory operations (especially MMIO ## operations) have completed prior to execution of the interrupt ## handler. ## ## If MMU support is enabled, address translation is re-established ## immediately at the entry of each interrupt, prior to performing any ## loads or stores. SSX currently only supports using the MMU for ## protection, not for address translation. Therfore it is 'legal' ## to change translation modes a with an MTMSR followed by an ## ISYNC. This is much simpler then the complex instruction sequence ## that would be required if we had to set up RFI/RFCI sequences to ## change the execution context at this point. ## ## Note that since we are not really doing address translation, it ## would also be in keeping with the 'fast interrupt' idea to defer ## reenabling translation (protection) until the fast-to-full sequence ## was executed for full-mode interrupts, and run fast-mode interrupts ## unprotected. However here we chose to run all interrupts with MMU ## protection. ## ## Unfortunately the simple MTMSR;ISYNC sequence exposes a serious bug ## in the 405-S core that causes the stack-pointer store instruction ## to generate a seemingly random, *real-mode* address in certain cases ## when this instruction in a noncritical interrupt prologue is ## interrupted by a critical interrupt. This bug is described in ## HW239446. The workaround is to follow the ISYNC sith a SYNC - which ## eliminates the problem for reasons still unknown. On the bright side ## this SYNC might also serve the same purpose as the EIEIO in the ## non-MMU case, guaranteeing that all MMIO has completed prior to the ## interrupt handler. However without the initial EIEIO we still ## experience failures, so this seemingly redundant instruction also ## remains in place. This requirement is assumed to be related to the ## HW239446 issue. .macro _ssx_fast_ctx_push, critical .if !PPC405_MMU_SUPPORT eieio .elseif \critical eieio # HW239446? mtsprg4 %r3 mfmsr %r3 ori %r3, %r3, PPC405_RELOCATION_MODE mtmsr %r3 isync #ifndef ALLOW_HW239446 sync # HW239446! #endif mfsprg4 %r3 .else eieio # HW239446? mtsprg0 %r3 mfmsr %r3 ori %r3, %r3, PPC405_RELOCATION_MODE mtmsr %r3 isync #ifndef ALLOW_HW239446 sync # HW239446! #endif mfsprg0 %r3 .endif stwu %r1, -SSX_FAST_CTX_SIZE(%r1) # May be corrupted w/o HW239446 stw %r3, SSX_FAST_CTX_GPR3(%r1) stw %r4, SSX_FAST_CTX_GPR4(%r1) stw %r5, SSX_FAST_CTX_GPR5(%r1) stw %r6, SSX_FAST_CTX_GPR6(%r1) stw %r7, SSX_FAST_CTX_GPR7(%r1) mfcr %r3 mflr %r4 stw %r3, SSX_FAST_CTX_CR(%r1) stw %r4, SSX_FAST_CTX_LR(%r1) .endm .macro _ssx_fast_ctx_pop lwz %r3, SSX_FAST_CTX_CR(%r1) lwz %r4, SSX_FAST_CTX_LR(%r1) mtcr %r3 mtlr %r4 lwz %r3, SSX_FAST_CTX_GPR3(%r1) lwz %r4, SSX_FAST_CTX_GPR4(%r1) lwz %r5, SSX_FAST_CTX_GPR5(%r1) lwz %r6, SSX_FAST_CTX_GPR6(%r1) lwz %r7, SSX_FAST_CTX_GPR7(%r1) lwz %r1, 0(%r1) .endm ## ------------------------------------------------------------ ## Save/update the kernel context in response to an interrupt. This is ## not part of the fast context save because for external interupts the ## IRQ is not determined until later. ## ------------------------------------------------------------ ## The kernel context is saved, then updated with the currently active ## IRQ in bits 16:23. The correct interrupt count is incremented and ## the context is returned to USPRG0. .macro _save_update_kernel_context critical, irqreg, ctxreg //.if \critical //SSX_TRACE_CRITICAL_IRQ_ENTRY \irqreg, \ctxreg //.else //SSX_TRACE_NONCRITICAL_IRQ_ENTRY \irqreg, \ctxreg //.endif mfusprg0 \ctxreg stw \ctxreg, SSX_FAST_CTX_KERNEL_CTX(%r1) rlwimi \ctxreg, \irqreg, 8, 16, 23 .if \critical addis \ctxreg, \ctxreg, 0x0100 .else addis \ctxreg, \ctxreg, 0x0001 .endif mtusprg0 \ctxreg .endm ## ------------------------------------------------------------ ## Fast-mode context pop and RF(C)I. This is only used by ## interrupt handlers - the thread context switch has its own ## code to handle updating USPRG0 for thread mode. ## ------------------------------------------------------------ .macro _ssx_fast_ctx_pop_exit critical //.if SSX_KERNEL_TRACE_ENABLE //.if \critical //bl __ssx_trace_critical_irq_exit //.else //bl __ssx_trace_noncritical_irq_exit //.endif //.endif lwz %r3, SSX_FAST_CTX_KERNEL_CTX(%r1) mtusprg0 %r3 _ssx_fast_ctx_pop .if \critical rfci .else rfi .endif .endm ## ------------------------------------------------------------ ## Save/restore the (volatile - fast) context ## ## Thread - 15 Instructions, 11 Loads/Stores ## IRQ - 19(15) Instructions, 13(11) Loads/Stores ## ------------------------------------------------------------ .macro _ssx_vol_fast_ctx_push, irq_context, critical=1 stwu %r1, -SSX_VOL_FAST_CTX_SIZE(%r1) stw %r0, SSX_VOL_FAST_CTX_GPR0(%r1) stw %r8, SSX_VOL_FAST_CTX_GPR8(%r1) stw %r9, SSX_VOL_FAST_CTX_GPR9(%r1) stw %r10, SSX_VOL_FAST_CTX_GPR10(%r1) stw %r11, SSX_VOL_FAST_CTX_GPR11(%r1) stw %r12, SSX_VOL_FAST_CTX_GPR12(%r1) mfxer %r8 mfctr %r9 mfsrr0 %r10 mfsrr1 %r11 stw %r8, SSX_VOL_FAST_CTX_XER(%r1) stw %r9, SSX_VOL_FAST_CTX_CTR(%r1) stw %r10, SSX_VOL_FAST_CTX_SRR0(%r1) stw %r11, SSX_VOL_FAST_CTX_SRR1(%r1) .if (\irq_context & \critical) mfsrr2 %r8 mfsrr3 %r9 stw %r8, SSX_VOL_FAST_CTX_SRR2(%r1) stw %r9, SSX_VOL_FAST_CTX_SRR3(%r1) .endif .endm .macro _ssx_vol_fast_ctx_pop, irq_context, critical .if (\irq_context & \critical) lwz %r8, SSX_VOL_FAST_CTX_SRR2(%r1) lwz %r9, SSX_VOL_FAST_CTX_SRR3(%r1) mtsrr2 %r8 mtsrr3 %r9 .endif lwz %r8, SSX_VOL_FAST_CTX_XER(%r1) lwz %r9, SSX_VOL_FAST_CTX_CTR(%r1) lwz %r10, SSX_VOL_FAST_CTX_SRR0(%r1) lwz %r11, SSX_VOL_FAST_CTX_SRR1(%r1) mtxer %r8 mtctr %r9 mtsrr0 %r10 mtsrr1 %r11 lwz %r0, SSX_VOL_FAST_CTX_GPR0(%r1) lwz %r8, SSX_VOL_FAST_CTX_GPR8(%r1) lwz %r9, SSX_VOL_FAST_CTX_GPR9(%r1) lwz %r10, SSX_VOL_FAST_CTX_GPR10(%r1) lwz %r11, SSX_VOL_FAST_CTX_GPR11(%r1) lwz %r12, SSX_VOL_FAST_CTX_GPR12(%r1) lwz %r1, 0(%r1) .endm ## ------------------------------------------------------------ ## Save/restore the non-volatile context on the stack ## ## 2 Instructions, 19 Loads/Stores ## ------------------------------------------------------------ .macro _ssx_non_vol_ctx_push stwu %r1, -SSX_NON_VOL_CTX_SIZE(%r1) stmw %r14, SSX_NON_VOL_CTX_GPR14(%r1) .endm .macro _ssx_non_vol_ctx_pop lmw %r14, SSX_NON_VOL_CTX_GPR14(%r1) lwz %r1, 0(%r1) .endm // *INDENT-ON* #else /* __ASSEMBLER__ */ /// SSX thread context layout as a C structure. /// /// This is the structure of the stack area pointed to by /// thread->saved_stack_pointer when a thread is fully context-switched out. typedef struct { uint32_t r1_nv; uint32_t link_nv; uint32_t r14; uint32_t r15; uint32_t r16; uint32_t r17; uint32_t r18; uint32_t r19; uint32_t r20; uint32_t r21; uint32_t r22; uint32_t r23; uint32_t r24; uint32_t r25; uint32_t r26; uint32_t r27; uint32_t r28; uint32_t r29; uint32_t r30; uint32_t r31; uint32_t r1_vf; uint32_t link_vf; uint32_t r0; uint32_t r8; uint32_t r9; uint32_t r10; uint32_t r11; uint32_t r12; uint32_t xer; uint32_t ctr; uint32_t srr0; uint32_t srr1; uint32_t srr2; uint32_t srr3; uint32_t r1; uint32_t link_fast; uint32_t r3; uint32_t r4; uint32_t r5; uint32_t r6; uint32_t r7; uint32_t cr; uint32_t lr; uint32_t usprg0; } SsxThreadContext; /// SSX thread context of an interrupted thread (full-mode handler) /// /// When a thread is interrupted by a full-mode interrupt handler, this is the /// layout of the stack area pointed to by either __ssx_saved_sp_noncritical /// or __ssx_saved_sp_critical. typedef struct { uint32_t r1_vf; uint32_t link_vf; uint32_t r0; uint32_t r8; uint32_t r9; uint32_t r10; uint32_t r11; uint32_t r12; uint32_t xer; uint32_t ctr; uint32_t srr0; uint32_t srr1; uint32_t srr2; uint32_t srr3; uint32_t r1; uint32_t link_fast; uint32_t r3; uint32_t r4; uint32_t r5; uint32_t r6; uint32_t r7; uint32_t cr; uint32_t lr; uint32_t usprg0; } SsxThreadContextFullIrq; /// SSX thread context of an interrupted thread (fast-mode handler) /// /// When a thread is interrupted by a fast-mode interrupt handler, this is the /// layout of the stack area pointed to by R1 - unless the fast-mode interrupt /// handler extends the stack. typedef struct { uint32_t r1; uint32_t link_fast; uint32_t r3; uint32_t r4; uint32_t r5; uint32_t r6; uint32_t r7; uint32_t cr; uint32_t lr; uint32_t usprg0; } SsxThreadContextFastIrq; #endif /* __ASSEMBLER__ */ #endif /* __PPC405_CONTEXT_H__ */ <|start_filename|>src/occ_405/mem/memory_power_control.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/mem/memory_power_control.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <occ_common.h> // perform memory power control (if needed) void amec_mem_power_control(void); // Check whether the OCC is in IPS inline bool is_occ_in_ips(void); // create the memory power control gpe request IPC task void gpe_init_mem_power_control(void); // schedule the memory power control IPC task int gpe_mem_power_control(uint8_t mem_pwr_ctl, uint8_t memIndex, uint8_t wait_idle_gpe); <|start_filename|>src/include/registers/centaur_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/common/pmlib/include/registers/centaur_firmware_registers.h $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CENTAUR_FIRMWARE_REGISTERS_H__ #define __CENTAUR_FIRMWARE_REGISTERS_H__ #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union centaur_device_id { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cfam_id : 32; uint64_t module_id : 2; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t module_id : 2; uint64_t cfam_id : 32; #endif // _BIG_ENDIAN } fields; } centaur_device_id_t; typedef union centaur_mbs_fir_reg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_reg_t; typedef union centaur_mbs_fir_reg_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_reg_and_t; typedef union centaur_mbs_fir_reg_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_reg_or_t; typedef union centaur_mbs_fir_mask_reg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_mask_reg_t; typedef union centaur_mbs_fir_mask_reg_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_mask_reg_and_t; typedef union centaur_mbs_fir_mask_reg_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_mask_reg_or_t; typedef union centaur_mbs_fir_action0_reg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_fir_action0_reg_t; typedef union centaur_mbs_firact1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t host_protocol_error : 1; uint64_t int_protocol_error : 1; uint64_t invalid_address_error : 1; uint64_t external_timeout : 1; uint64_t internal_timeout : 1; uint64_t int_buffer_ce : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_sue : 1; uint64_t int_parity_error : 1; uint64_t cache_srw_ce : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_sue : 1; uint64_t cache_co_ce : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_sue : 1; uint64_t dir_ce : 1; uint64_t dir_ue : 1; uint64_t dir_member_deleted : 1; uint64_t dir_all_members_deleted : 1; uint64_t lru_error : 1; uint64_t edram_error : 1; uint64_t emergency_throttle_set : 1; uint64_t host_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t occ_inband_write_error : 1; uint64_t srb_buffer_ce : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_sue : 1; uint64_t dir_purge_ce : 1; uint64_t spare_fir30 : 1; uint64_t spare_fir31 : 1; uint64_t internal_scom_error : 1; uint64_t internal_scom_error_copy : 1; uint64_t _reserved0 : 30; #else uint64_t _reserved0 : 30; uint64_t internal_scom_error_copy : 1; uint64_t internal_scom_error : 1; uint64_t spare_fir31 : 1; uint64_t spare_fir30 : 1; uint64_t dir_purge_ce : 1; uint64_t srb_buffer_sue : 1; uint64_t srb_buffer_ue : 1; uint64_t srb_buffer_ce : 1; uint64_t occ_inband_write_error : 1; uint64_t occ_inband_read_error : 1; uint64_t host_inband_write_error : 1; uint64_t host_inband_read_error : 1; uint64_t emergency_throttle_set : 1; uint64_t edram_error : 1; uint64_t lru_error : 1; uint64_t dir_all_members_deleted : 1; uint64_t dir_member_deleted : 1; uint64_t dir_ue : 1; uint64_t dir_ce : 1; uint64_t cache_co_sue : 1; uint64_t cache_co_ue : 1; uint64_t cache_co_ce : 1; uint64_t cache_srw_sue : 1; uint64_t cache_srw_ue : 1; uint64_t cache_srw_ce : 1; uint64_t int_parity_error : 1; uint64_t int_buffer_sue : 1; uint64_t int_buffer_ue : 1; uint64_t int_buffer_ce : 1; uint64_t internal_timeout : 1; uint64_t external_timeout : 1; uint64_t invalid_address_error : 1; uint64_t int_protocol_error : 1; uint64_t host_protocol_error : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbs_firact1_t; typedef union centaur_mbscfgq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t eccbp_exit_sel : 1; uint64_t dram_ecc_bypass_dis : 1; uint64_t mbs_scom_wat_trigger : 1; uint64_t mbs_prq_ref_avoidance_en : 1; uint64_t reserved4_6 : 3; uint64_t occ_deadman_timer_sel : 4; uint64_t sync_fsync_mba_strobe_en : 1; uint64_t hca_timebase_op_mode : 1; uint64_t hca_local_timer_inc_select : 3; uint64_t mbs_01_rdtag_delay : 4; uint64_t mbs_01_rdtag_force_dead_cycle : 1; uint64_t sync_lat_pol_01 : 1; uint64_t sync_lat_adj_01 : 2; uint64_t mbs_23_rdtag_delay : 4; uint64_t mbs_23_rdtag_force_dead_cycle : 1; uint64_t sync_lat_pol_23 : 1; uint64_t sync_lat_adj_23 : 2; uint64_t _reserved0 : 32; #else uint64_t _reserved0 : 32; uint64_t sync_lat_adj_23 : 2; uint64_t sync_lat_pol_23 : 1; uint64_t mbs_23_rdtag_force_dead_cycle : 1; uint64_t mbs_23_rdtag_delay : 4; uint64_t sync_lat_adj_01 : 2; uint64_t sync_lat_pol_01 : 1; uint64_t mbs_01_rdtag_force_dead_cycle : 1; uint64_t mbs_01_rdtag_delay : 4; uint64_t hca_local_timer_inc_select : 3; uint64_t hca_timebase_op_mode : 1; uint64_t sync_fsync_mba_strobe_en : 1; uint64_t occ_deadman_timer_sel : 4; uint64_t reserved4_6 : 3; uint64_t mbs_prq_ref_avoidance_en : 1; uint64_t mbs_scom_wat_trigger : 1; uint64_t dram_ecc_bypass_dis : 1; uint64_t eccbp_exit_sel : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbscfgq_t; typedef union centaur_mbsemerthroq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t emergency_throttle_ip : 1; uint64_t _reserved0 : 63; #else uint64_t _reserved0 : 63; uint64_t emergency_throttle_ip : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbsemerthroq_t; typedef union centaur_mbsocc01hq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_01_rd_hit : 32; uint64_t occ_01_wr_hit : 32; #else uint64_t occ_01_wr_hit : 32; uint64_t occ_01_rd_hit : 32; #endif // _BIG_ENDIAN } fields; } centaur_mbsocc01hq_t; typedef union centaur_mbsocc23hq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_23_rd_hit : 32; uint64_t occ_23_wr_hit : 32; #else uint64_t occ_23_wr_hit : 32; uint64_t occ_23_rd_hit : 32; #endif // _BIG_ENDIAN } fields; } centaur_mbsocc23hq_t; typedef union centaur_mbsoccitcq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_cent_idle_th_cnt : 32; uint64_t _reserved0 : 32; #else uint64_t _reserved0 : 32; uint64_t occ_cent_idle_th_cnt : 32; #endif // _BIG_ENDIAN } fields; } centaur_mbsoccitcq_t; typedef union centaur_mbsoccscanq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_01_spec_can : 32; uint64_t occ_23_spec_can : 32; #else uint64_t occ_23_spec_can : 32; uint64_t occ_01_spec_can : 32; #endif // _BIG_ENDIAN } fields; } centaur_mbsoccscanq_t; typedef union centaur_mbarpc0qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cfg_lp2_entry_req : 1; uint64_t cfg_lp2_state : 1; uint64_t cfg_min_max_domains_enable : 1; uint64_t cfg_min_max_domains : 3; uint64_t cfg_pup_avail : 5; uint64_t cfg_pdn_pup : 5; uint64_t cfg_pup_pdn : 5; uint64_t reserved0 : 1; uint64_t cfg_min_domain_reduction_enable : 1; uint64_t cfg_min_domain_reduction_on_time : 10; uint64_t cfg_pup_after_activate_wait_enable : 1; uint64_t cfg_pup_after_activate_wait_time : 8; uint64_t cfg_force_spare_pup : 1; uint64_t _reserved0 : 21; #else uint64_t _reserved0 : 21; uint64_t cfg_force_spare_pup : 1; uint64_t cfg_pup_after_activate_wait_time : 8; uint64_t cfg_pup_after_activate_wait_enable : 1; uint64_t cfg_min_domain_reduction_on_time : 10; uint64_t cfg_min_domain_reduction_enable : 1; uint64_t reserved0 : 1; uint64_t cfg_pup_pdn : 5; uint64_t cfg_pdn_pup : 5; uint64_t cfg_pup_avail : 5; uint64_t cfg_min_max_domains : 3; uint64_t cfg_min_max_domains_enable : 1; uint64_t cfg_lp2_state : 1; uint64_t cfg_lp2_entry_req : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbarpc0qn_t; typedef union centaur_mba_farb3qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cfg_nm_n_per_mba : 15; uint64_t cfg_nm_n_per_chip : 16; uint64_t cfg_nm_m : 14; uint64_t cfg_nm_ras_weight : 3; uint64_t cfg_nm_cas_weight : 3; uint64_t cfg_nm_per_slot_enabled : 1; uint64_t cfg_nm_count_other_mba_dis : 1; uint64_t _reserved0 : 11; #else uint64_t _reserved0 : 11; uint64_t cfg_nm_count_other_mba_dis : 1; uint64_t cfg_nm_per_slot_enabled : 1; uint64_t cfg_nm_cas_weight : 3; uint64_t cfg_nm_ras_weight : 3; uint64_t cfg_nm_m : 14; uint64_t cfg_nm_n_per_chip : 16; uint64_t cfg_nm_n_per_mba : 15; #endif // _BIG_ENDIAN } fields; } centaur_mba_farb3qn_t; typedef union centaur_mbapcn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t mode_hp_sub_cnt : 1; uint64_t mode_lp_sub_cnt : 1; uint64_t mode_static_idle_dly : 5; uint64_t mode_emer_min_max_domain : 3; uint64_t mode_pup_all_wr_pending : 2; uint64_t mode_lp_ref_sim_enq : 1; uint64_t _reserved0 : 51; #else uint64_t _reserved0 : 51; uint64_t mode_lp_ref_sim_enq : 1; uint64_t mode_pup_all_wr_pending : 2; uint64_t mode_emer_min_max_domain : 3; uint64_t mode_static_idle_dly : 5; uint64_t mode_lp_sub_cnt : 1; uint64_t mode_hp_sub_cnt : 1; #endif // _BIG_ENDIAN } fields; } centaur_mbapcn_t; typedef union centaur_mbasrqn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t emergency_m : 14; uint64_t emergency_n : 15; uint64_t _reserved0 : 35; #else uint64_t _reserved0 : 35; uint64_t emergency_n : 15; uint64_t emergency_m : 14; #endif // _BIG_ENDIAN } fields; } centaur_mbasrqn_t; typedef union centaur_pmu0qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t read_count : 32; uint64_t write_count : 32; #else uint64_t write_count : 32; uint64_t read_count : 32; #endif // _BIG_ENDIAN } fields; } centaur_pmu0qn_t; typedef union centaur_pmu1qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t activate_count : 32; uint64_t pu_counts : 32; #else uint64_t pu_counts : 32; uint64_t activate_count : 32; #endif // _BIG_ENDIAN } fields; } centaur_pmu1qn_t; typedef union centaur_pmu2qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t frame_count : 32; uint64_t _reserved0 : 32; #else uint64_t _reserved0 : 32; uint64_t frame_count : 32; #endif // _BIG_ENDIAN } fields; } centaur_pmu2qn_t; typedef union centaur_pmu3qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t low_idle_threshold : 16; uint64_t med_idle_threshold : 16; uint64_t high_idle_threshold : 32; #else uint64_t high_idle_threshold : 32; uint64_t med_idle_threshold : 16; uint64_t low_idle_threshold : 16; #endif // _BIG_ENDIAN } fields; } centaur_pmu3qn_t; typedef union centaur_pmu4qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t base_idle_count : 32; uint64_t low_idle_count : 32; #else uint64_t low_idle_count : 32; uint64_t base_idle_count : 32; #endif // _BIG_ENDIAN } fields; } centaur_pmu4qn_t; typedef union centaur_pmu5qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t med_idle_count : 32; uint64_t high_idle_count : 32; #else uint64_t high_idle_count : 32; uint64_t med_idle_count : 32; #endif // _BIG_ENDIAN } fields; } centaur_pmu5qn_t; typedef union centaur_pmu6qn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t total_gap_counts : 18; uint64_t specific_gap_counts : 18; uint64_t gap_length_adder : 3; uint64_t specific_gap_condition : 4; uint64_t cmd_to_cmd_count : 18; uint64_t command_pattern_to_count : 3; #else uint64_t command_pattern_to_count : 3; uint64_t cmd_to_cmd_count : 18; uint64_t specific_gap_condition : 4; uint64_t gap_length_adder : 3; uint64_t specific_gap_counts : 18; uint64_t total_gap_counts : 18; #endif // _BIG_ENDIAN } fields; } centaur_pmu6qn_t; typedef union centaur_sensor_cache_data0_3 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t crittrip0 : 1; uint64_t abovetrip0 : 1; uint64_t belowtrip0 : 1; uint64_t signbit0 : 1; uint64_t temperature0 : 8; uint64_t temp_frac0 : 2; uint64_t status0 : 2; uint64_t crittrip1 : 1; uint64_t abovetrip1 : 1; uint64_t belowtrip1 : 1; uint64_t signbit1 : 1; uint64_t temperature1 : 8; uint64_t temp_frac1 : 2; uint64_t status1 : 2; uint64_t crittrip2 : 1; uint64_t abovetrip2 : 1; uint64_t belowtrip2 : 1; uint64_t signbit2 : 1; uint64_t temperature2 : 8; uint64_t temp_frac2 : 2; uint64_t status2 : 2; uint64_t crittrip3 : 1; uint64_t abovetrip3 : 1; uint64_t belowtrip3 : 1; uint64_t signbit3 : 1; uint64_t temperature3 : 8; uint64_t temp_frac3 : 2; uint64_t status3 : 2; #else uint64_t status3 : 2; uint64_t temp_frac3 : 2; uint64_t temperature3 : 8; uint64_t signbit3 : 1; uint64_t belowtrip3 : 1; uint64_t abovetrip3 : 1; uint64_t crittrip3 : 1; uint64_t status2 : 2; uint64_t temp_frac2 : 2; uint64_t temperature2 : 8; uint64_t signbit2 : 1; uint64_t belowtrip2 : 1; uint64_t abovetrip2 : 1; uint64_t crittrip2 : 1; uint64_t status1 : 2; uint64_t temp_frac1 : 2; uint64_t temperature1 : 8; uint64_t signbit1 : 1; uint64_t belowtrip1 : 1; uint64_t abovetrip1 : 1; uint64_t crittrip1 : 1; uint64_t status0 : 2; uint64_t temp_frac0 : 2; uint64_t temperature0 : 8; uint64_t signbit0 : 1; uint64_t belowtrip0 : 1; uint64_t abovetrip0 : 1; uint64_t crittrip0 : 1; #endif // _BIG_ENDIAN } fields; } centaur_sensor_cache_data0_3_t; typedef union centaur_sensor_cache_data4_7 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t crittrip4 : 1; uint64_t abovetrip4 : 1; uint64_t belowtrip4 : 1; uint64_t signbit4 : 1; uint64_t temperature4 : 8; uint64_t temp_frac4 : 2; uint64_t status4 : 2; uint64_t crittrip5 : 1; uint64_t abovetrip5 : 1; uint64_t belowtrip5 : 1; uint64_t signbit5 : 1; uint64_t temperature5 : 8; uint64_t temp_frac5 : 2; uint64_t status5 : 2; uint64_t crittrip6 : 1; uint64_t abovetrip6 : 1; uint64_t belowtrip6 : 1; uint64_t signbit6 : 1; uint64_t temperature6 : 8; uint64_t temp_frac6 : 2; uint64_t status6 : 2; uint64_t crittrip7 : 1; uint64_t abovetrip7 : 1; uint64_t belowtrip7 : 1; uint64_t signbit7 : 1; uint64_t temperature7 : 8; uint64_t temp_frac7 : 2; uint64_t status7 : 2; #else uint64_t status7 : 2; uint64_t temp_frac7 : 2; uint64_t temperature7 : 8; uint64_t signbit7 : 1; uint64_t belowtrip7 : 1; uint64_t abovetrip7 : 1; uint64_t crittrip7 : 1; uint64_t status6 : 2; uint64_t temp_frac6 : 2; uint64_t temperature6 : 8; uint64_t signbit6 : 1; uint64_t belowtrip6 : 1; uint64_t abovetrip6 : 1; uint64_t crittrip6 : 1; uint64_t status5 : 2; uint64_t temp_frac5 : 2; uint64_t temperature5 : 8; uint64_t signbit5 : 1; uint64_t belowtrip5 : 1; uint64_t abovetrip5 : 1; uint64_t crittrip5 : 1; uint64_t status4 : 2; uint64_t temp_frac4 : 2; uint64_t temperature4 : 8; uint64_t signbit4 : 1; uint64_t belowtrip4 : 1; uint64_t abovetrip4 : 1; uint64_t crittrip4 : 1; #endif // _BIG_ENDIAN } fields; } centaur_sensor_cache_data4_7_t; typedef union centaur_dts_thermal_sensor_results { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dts0 : 12; uint64_t thermal_trip0 : 2; uint64_t spare0 : 1; uint64_t valid0 : 1; uint64_t dts1 : 12; uint64_t thermal_trip1 : 2; uint64_t spare1 : 1; uint64_t valid1 : 1; uint64_t _reserved0 : 32; #else uint64_t _reserved0 : 32; uint64_t valid1 : 1; uint64_t spare1 : 1; uint64_t thermal_trip1 : 2; uint64_t dts1 : 12; uint64_t valid0 : 1; uint64_t spare0 : 1; uint64_t thermal_trip0 : 2; uint64_t dts0 : 12; #endif // _BIG_ENDIAN } fields; } centaur_dts_thermal_sensor_results_t; #endif // __ASSEMBLER__ #endif // __CENTAUR_FIRMWARE_REGISTERS_H__ <|start_filename|>src/occ_405/pss/dpss.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pss/dpss.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _DPSS_H #define _DPSS_H #include <errl.h> #include <rtls.h> // dpss_initialize is part of the dpss init applet // DPSS oversubscription IRQ handler void isr_dpss_oversubscription_handler_full(void *private, SsxIrqId irq, int priority); // Installs the DPSS oversubscription IRQ handler errlHndl_t dpss_oversubscription_irq_initialize(); #endif //_DPSS_H <|start_filename|>src/occ_405/amec/amec_sensors_fw.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_sensors_fw.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_SENSORS_FW_H #define _AMEC_SENSORS_FW_H /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include "amec_external.h" /*----------------------------------------------------------------------------*/ /* Defines/Constants */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Function Declarations */ /*----------------------------------------------------------------------------*/ // Function that updates the AMEC interim structures with AMEC State Durations void amec_slv_update_smh_sensors(int i_smh_state, uint32_t i_duration); // Function that updates the AMEC interim structures with GPE Engine Durations void amec_slv_update_gpe_sensors(uint8_t i_gpe_engine); // Function to kick of GPE timing nop task on both GPEs void task_gpe_timings( task_t * i_task ); // Function that updates the AMEC FW sensors void amec_update_fw_sensors(void); #endif // _AMEC_SENSORS_FW_H <|start_filename|>src/lib/common/kernel.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/common/kernel.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __KERNEL_H__ #define __KERNEL_H__ /// \file kernel.h /// \brief Kernel agnostic macros that allow the same code to work with /// different kernels. /// /// Programmers can include this instead of pk.h or ssx.h /// /// #ifndef __ASSEMBLER__ #ifdef __SSX__ /// ----------------------- Use SSX kernel interfaces -------------------------- #include "ssx.h" //Types #define KERN_SEMAPHORE SsxSemaphore #define KERN_SEMAPHORE_COUNT SsxSemaphoreCount #define KERN_DEQUE SsxDeque #define KERN_THREAD SsxThread #define KERN_THREAD_PRIORITY SsxThreadPriority #define KERN_THREAD_STATE SsxThreadState #define KERN_THREAD_ROUTINE SsxThreadRoutine #define KERN_THREAD_FLAGS SsxThreadFlags #define KERN_ADDRESS SsxAddress #define KERN_TIMER SsxTimer #define KERN_TIMER_CALLBACK SsxTimerCallback #define KERN_INTERVAL SsxInterval #define KERN_TIMEBASE SsxTimebase #define KERN_IRQ_ID SsxIrqId #define KERN_MACHINE_CONTEXT SsxMachineContext //Constants #define KERN_SEMAPHORE_PEND_TIMED_OUT SSX_SEMAPHORE_PEND_TIMED_OUT #define KERN_SEMAPHORE_PEND_NO_WAIT SSX_SEMAPHORE_PEND_NO_WAIT #define KERN_NONCRITICAL SSX_NONCRITICAL #define KERN_CRITICAL SSX_CRITICAL #define KERN_SUPERCRITICAL SSX_SUPERCRITICAL #define KERN_ERROR_CHECK_API SSX_ERROR_CHECK_API #define KERN_NO_WAIT SSX_NO_WAIT #define KERN_WAIT_FOREVER SSX_WAIT_FOREVER //Functions #define KERN_SECONDS(s) SSX_SECONDS(s) #define KERN_MILLISECONDS(m) SSX_MILLISECONDS(m) #define KERN_MICROSECONDS(u) SSX_MICROSECONDS(u) #define KERN_NANOSECONDS(n) SSX_NANOSECONDS(n) #define KERN_TIMEBASE_GET() ssx_timebase_get() #define KERN_TIMEBASE_SET(tb) ssx_timebase_set(tb) #define KERN_INTERRUPT_PREEMPTION_ENABLE() ssx_interrupt_preemption_enable() #define KERN_INTERRUPT_PREEMPTION_DISABLE() ssx_interrupt_preemption_disable() #define KERN_TIMER_CREATE(timer, callback, arg) \ ssx_timer_create(timer, callback, arg) #define KERN_TIMER_CREATE_NONPREEMPTIBLE(timer, callback, arg) \ ssx_timer_create_nonpreemptible(timer, callback, arg) #define KERN_TIMER_SCHEDULE_ABSOLUTE(timer, time, period) \ ssx_timer_schedule_absolute(timer, time, period) #define KERN_TIMER_SCHEDULE(timer, interval, period) \ ssx_timer_schedule(timer, interval, period) #define KERN_TIMER_CANCEL(timer) \ ssx_timer_cancel(timer) #define KERN_TIMER_INFO_GET(timer, timeout, active) \ ssx_timer_info_get(timer, timeout, active) #define KERN_THREAD_CREATE(thread, thread_routine, arg, stack, stack_size, priority) \ ssx_thread_create(thread, thread_routine, arg, stack, stack_size, priority) #define KERN_THREAD_INFO_GET(thread, state, priority, runnable) \ ssx_thread_info_get(thread, state, priority, runnable) #define KERN_THREAD_PRIORTY_CHANGE(thread, new_priority, old_priority) \ ssx_thread_priority_change(thread, new_priority, old_priority) #define KERN_THREAD_AT_PRIORITY(priority, thread) \ ssx_thread_at_priority(priority, thread) #define KERN_THREAD_PRIORITY_SWAP(thread_a, thread_b) \ ssx_thread_priority_swap(thread_a, thread_b) #define KERN_START_THREADS() ssx_start_threads() #define KERN_THREAD_RESUME(thread) ssx_thread_resume(thread) #define KERN_THREAD_SUSPEND(thread) ssx_thread_suspend(thread) #define KERN_THREAD_DELETE(thread) ssx_thread_delete(thread) #define KERN_COMPLETE() ssx_complete() #define KERN_SLEEP_ABSOLUTE(time) ssx_sleep_absolute(time) #define KERN_SLEEP(interval) ssx_sleep(interval) #define KERN_SEMAPHORE_CREATE(semaphore, initial_count, max_count) \ ssx_semaphore_create(semaphore, initial_count,max_count) #define KERN_SEMAPHORE_STATIC_CREATE(sem, initial_count, max_count) \ SSX_SEMAPHORE(sem, initial_count, max_count) #define KERN_SEMAPHORE_INITIALIZATION(_initial_count, _max_count) \ SSX_SEMAPHORE_INITIALIZATION(_initial_count, _max_count) #define KERN_SEMAPHORE_INFO_GET(semaphore, count, pending) \ ssx_semaphore_info_get(semaphore, count, pending) #define KERN_SEMAPHORE_POST(semaphore) \ ssx_semaphore_post(semaphore) #define KERN_SEMAPHORE_PEND(semaphore, timeout) \ ssx_semaphore_pend(semaphore, timeout) #define KERN_SEMAPHORE_RELEASE_ALL(semaphore) \ ssx_semaphore_release_all(semaphore) #define KERN_SEMAPHORE_POST_HANDLER(arg, irq, priority) \ ssx_semaphore_post_handler(arg, irq, priority) #define KERN_HALT() \ ssx_halt() #define KERN_PANIC(code) \ SSX_PANIC(code) #define KERN_DEQUE_SENTINEL_CREATE(deque) \ ssx_deque_sentinel_create(deque) #define KERN_DEQUE_SENTINEL_STATIC_CREATE(deque) \ SSX_DEQUE_SENTINEL_STATIC_CREATE(deque) #define KERN_DEQUE_SENTINEL_INIT(dq_addr) \ SSX_DEQUE_SENTINEL_INIT(dq_addr) #define KERN_DEQUE_ELEMENT_CREATE(element) \ ssx_deque_element_create(element) #define KERN_DEQUE_ELEMENT_STATIC_CREATE(deque) \ SSX_DEQUE_ELEMENT_STATIC_CREATE(deque) #define KERN_DEQUE_ELEMENT_INIT() \ SSX_DEQUE_ELEMENT_INIT() #define KERN_DEQUE_IS_EMPTY(deque) \ ssx_deque_is_empty(deque) #define KERN_DEQUE_IS_QUEUED(element) \ ssx_deque_is_queued(element) #define KERN_DEQUE_PUSH_BACK(deque, element) \ ssx_deque_push_back(deque, element) #define KERN_DEQUE_PUSH_FRONT(deque, element) \ ssx_deque_push_front(deque, element) #define KERN_DEQUE_POP_FRONT(deque) \ ssx_deque_pop_front(deque) #define KERN_DEQUE_DELETE(element) \ ssx_deque_delete(element) #define KERN_IRQ_HANDLER(f) \ SSX_IRQ_HANDLER(f) #define KERN_IRQ_SETUP(irq, polarity, trigger) \ ssx_irq_setup(irq, polarity, trigger) #define KERN_IRQ_HANDLER_SET(irq, handler, arg, priority) \ ssx_irq_handler_set(irq, handler, arg, priority) #define KERN_IRQ_ENABLE(irq) \ ssx_irq_enable(irq) #define KERN_IRQ_DISABLE(irq) \ ssx_irq_disable(irq) #define KERN_IRQ_STATUS_CLEAR(irq) \ ssx_irq_status_clear(irq) #define KERN_IRQ_STATUS_SET(irq, value) \ ssx_irq_status_set(irq, value) #define KERN_IRQ_FAST2FULL(fast_handler, full_handler) \ SSX_IRQ_FAST2FULL(fast_handler, full_handler) #define KERN_CRITICAL_SECTION_ENTER(priority, pctx) \ ssx_critical_section_enter(priority, pctx) #define KERN_CRITICAL_SECTION_EXIT(pctx) \ ssx_critical_section_exit(pctx) #define KERN_CONTEXT_CRITICAL_INTERRUPT() \ __ssx_kernel_context_critical_interrupt() #define KERN_ERROR_IF(condition, code) SSX_ERROR_IF(condition, code) #define KERN_CAST_POINTER(t, p) SSX_CAST_POINTER(t, p) #define KERN_STATIC_ASSERT(cond) SSX_STATIC_ASSERT(cond) #elif defined(__PK__) /// ----------------------- Use PK kernel interfaces -------------------------- #include "pk.h" //Types #define KERN_SEMAPHORE PkSemaphore #define KERN_SEMAPHORE_COUNT PkSemaphoreCount #define KERN_DEQUE PkDeque #define KERN_THREAD PkThread #define KERN_THREAD_PRIORITY PkThreadPriority #define KERN_THREAD_STATE PkThreadState #define KERN_THREAD_ROUTINE PkThreadRoutine #define KERN_THREAD_FLAGS PkThreadFlags #define KERN_ADDRESS PkAddress #define KERN_TIMER PkTimer #define KERN_TIMER_CALLBACK PkTimerCallback #define KERN_INTERVAL PkInterval #define KERN_TIMEBASE PkTimebase #define KERN_IRQ_ID PkIrqId #define KERN_MACHINE_CONTEXT PkMachineContext //Constants #define KERN_SEMAPHORE_PEND_TIMED_OUT PK_SEMAPHORE_PEND_TIMED_OUT #define KERN_SEMAPHORE_PEND_NO_WAIT PK_SEMAPHORE_PEND_NO_WAIT #define KERN_NONCRITICAL 0 #define KERN_CRITICAL 0 #define KERN_SUPERCRITICAL 0 #define KERN_ERROR_CHECK_API PK_ERROR_CHECK_API #define KERN_NO_WAIT PK_NO_WAIT #define KERN_WAIT_FOREVER PK_WAIT_FOREVER //Functions #define KERN_SECONDS(s) PK_SECONDS(s) #define KERN_MILLISECONDS(m) PK_MILLISECONDS(m) #define KERN_MICROSECONDS(u) PK_MICROSECONDS(u) #define KERN_NANOSECONDS(n) PK_NANOSECONDS(n) #define KERN_TIMEBASE_GET() pk_timebase_get() #define KERN_TIMEBASE_SET(tb) pk_timebase_set(tb) #define KERN_INTERRUPT_PREEMPTION_ENABLE() pk_interrupt_preemption_enable() #define KERN_INTERRUPT_PREEMPTION_DISABLE() pk_interrupt_preemption_disable() #define KERN_TIMER_CREATE(timer, callback, arg) \ pk_timer_create(timer, callback, arg) #define KERN_TIMER_CREATE_NONPREEMPTIBLE(timer, callback, arg) \ pk_timer_create_nonpreemptible(timer, callback, arg) #define KERN_TIMER_SCHEDULE_ABSOLUTE(timer, time, period) \ pk_timer_schedule_absolute(timer, time, period) #define KERN_TIMER_SCHEDULE(timer, interval, period) \ pk_timer_schedule(timer, interval, period) #define KERN_TIMER_CANCEL(timer) \ pk_timer_cancel(timer) #define KERN_TIMER_INFO_GET(timer, timeout, active) \ pk_timer_info_get(timer, timeout, active) #define KERN_THREAD_CREATE(thread, thread_routine, arg, stack, stack_size, priority) \ pk_thread_create(thread, thread_routine, arg, stack, stack_size, priority) #define KERN_THREAD_INFO_GET(thread, state, priority, runnable) \ pk_thread_info_get(thread, state, priority, runnable) #define KERN_THREAD_PRIORTY_CHANGE(thread, new_priority, old_priority) \ pk_thread_priority_change(thread, new_priority, old_priority) #define KERN_THREAD_AT_PRIORITY(priority, thread) \ pk_thread_at_priority(priority, thread) #define KERN_THREAD_PRIORITY_SWAP(thread_a, thread_b) \ pk_thread_priority_swap(thread_a, thread_b) #define KERN_START_THREADS() pk_start_threads() #define KERN_THREAD_RESUME(thread) pk_thread_resume(thread) #define KERN_THREAD_SUSPEND(thread) pk_thread_suspend(thread) #define KERN_THREAD_DELETE(thread) pk_thread_delete(thread) #define KERN_COMPLETE() pk_complete() #define KERN_SLEEP_ABSOLUTE(time) pk_sleep_absolute(time) #define KERN_SLEEP(interval) pk_sleep(interval) #define KERN_SEMAPHORE_CREATE(semaphore, initial_count, max_count) \ pk_semaphore_create(semaphore, initial_count,max_count) #define KERN_SEMAPHORE_STATIC_CREATE(sem, initial_count, max_count) \ PK_SEMAPHORE(sem, initial_count, max_count) #define KERN_SEMAPHORE_INITIALIZATION(_initial_count, _max_count) \ PK_SEMAPHORE_INITIALIZATION(_initial_count, _max_count) #define KERN_SEMAPHORE_INFO_GET(semaphore, count, pending) \ pk_semaphore_info_get(semaphore, count, pending) #define KERN_SEMAPHORE_POST(semaphore) \ pk_semaphore_post(semaphore) #define KERN_SEMAPHORE_PEND(semaphore, timeout) \ pk_semaphore_pend(semaphore, timeout) #define KERN_SEMAPHORE_RELEASE_ALL(semaphore) \ pk_semaphore_release_all(semaphore) #define KERN_SEMAPHORE_POST_HANDLER(arg, irq, priority) \ pk_semaphore_post_handler(arg, irq, priority) #define KERN_HALT() \ pk_halt() #define KERN_PANIC(code) \ PK_PANIC(code) #define KERN_DEQUE_SENTINEL_CREATE(deque) \ pk_deque_sentinel_create(deque) #define KERN_DEQUE_SENTINEL_STATIC_CREATE(deque) \ PK_DEQUE_SENTINEL_STATIC_CREATE(deque) #define KERN_DEQUE_SENTINEL_INIT(dq_addr) \ PK_DEQUE_SENTINEL_INIT(dq_addr) #define KERN_DEQUE_ELEMENT_CREATE(element) \ pk_deque_element_create(element) #define KERN_DEQUE_ELEMENT_STATIC_CREATE(deque) \ PK_DEQUE_ELEMENT_STATIC_CREATE(deque) #define KERN_DEQUE_ELEMENT_INIT() \ PK_DEQUE_ELEMENT_INIT() #define KERN_DEQUE_IS_EMPTY(deque) \ pk_deque_is_empty(deque) #define KERN_DEQUE_IS_QUEUED(element) \ pk_deque_is_queued(element) #define KERN_DEQUE_PUSH_BACK(deque, element) \ pk_deque_push_back(deque, element) #define KERN_DEQUE_PUSH_FRONT(deque, element) \ pk_deque_push_front(deque, element) #define KERN_DEQUE_POP_FRONT(deque) \ pk_deque_pop_front(deque) #define KERN_DEQUE_DELETE(element) \ pk_deque_delete(element) #define KERN_IRQ_HANDLER(f) \ PK_IRQ_HANDLER(f) #define KERN_IRQ_SETUP(irq, polarity, trigger) \ pk_irq_setup(irq, polarity, trigger) #define KERN_IRQ_HANDLER_SET(irq, handler, arg, priority) \ pk_irq_handler_set(irq, handler, arg) #define KERN_IRQ_ENABLE(irq) \ pk_irq_enable(irq) #define KERN_IRQ_DISABLE(irq) \ pk_irq_disable(irq) #define KERN_IRQ_STATUS_CLEAR(irq) \ pk_irq_status_clear(irq) #define KERN_IRQ_STATUS_SET(irq, value) \ pk_irq_status_set(irq, value) #define KERN_IRQ_FAST2FULL(fast_handler, full_handler) \ PK_IRQ_FAST2FULL(fast_handler, full_handler) #define KERN_CRITICAL_SECTION_ENTER(priority, pctx) \ pk_critical_section_enter(pctx) #define KERN_CRITICAL_SECTION_EXIT(pctx) \ pk_critical_section_exit(pctx) #define KERN_CONTEXT_CRITICAL_INTERRUPT() \ (0) #define KERN_ERROR_IF(condition, code) PK_ERROR_IF(condition, code) #define KERN_CAST_POINTER(t, p) PK_CAST_POINTER(t, p) #define KERN_STATIC_ASSERT(cond) PK_STATIC_ASSERT(cond) #else /// ----------------------- Kernel type not defined -------------------------- #error "Kernel type must be defined in img_defs.mk" #endif /*__SSX__*/ #endif /*__ASSEMBLER__*/ #endif /* __KERNEL_H__ */ <|start_filename|>src/ppe/pk/ppe42/pk_panic_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/pk_panic_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PK_PANIC_CODES_H__ #define __PK_PANIC_CODES_H__ // On PPE42, PANIC codes are stored as part of the trap word instruction. // tw 31, RA, RB Where RA and RB would used to encode the trap code. // There are 16 valid gprs on PP42, so this gives 256 possible trap codes. // The trap code is defined as a two byte code defined as 0xYYZZ where YY // is encoded into the RA field and ZZ is incoded into the RB field // YY and ZZ are limited to the values: // 00,01,02,03,04,05,06,07,08,09,0a,0d,1c,1d,1e,1f (valid gpr ids) // // To add a new panic code, select an unused values and rename it. // This enum contains all the valid values that can be used. Using a // panic code not in this list will result in a compiler/assembler error. #ifndef __ASSEMBLER__ typedef enum { PPE42_MACHINE_CHECK_PANIC = 0x0001, PPE42_DATA_STORAGE_PANIC = 0x0002, PPE42_INSTRUCTION_STORAGE_PANIC = 0x0003, PPE42_DATA_ALIGNMENT_PANIC = 0x0004, PK_BOOT_VECTORS_NOT_ALIGNED = 0x0005, PK_DEFAULT_IRQ_HANDLER = 0x0006, PK_DEFAULT_SPECIAL_HANDLER = 0x0007, PPE42_PHANTOM_INTERRUPT = 0x0008, PPE42_ILLEGAL_INSTRUCTION = 0x0009, PK_UNUSED_000a = 0x000a, PK_UNUSED_000d = 0x000d, PK_UNUSED_001c = 0x001c, PK_UNUSED_001d = 0x001d, PK_UNUSED_001e = 0x001e, PK_UNUSED_001f = 0x001f, // API return codes PK_ILLEGAL_CONTEXT_THREAD_CONTEXT = 0x0100, PK_ILLEGAL_CONTEXT_INTERRUPT_CONTEXT = 0x0101, PK_ILLEGAL_CONTEXT_THREAD = 0x0102, PK_ILLEGAL_CONTEXT_TIMER = 0x0103, PK_INVALID_THREAD_AT_RESUME1 = 0x0104, PK_INVALID_THREAD_AT_RESUME2 = 0x0105, PK_INVALID_THREAD_AT_SUSPEND1 = 0x0106, PK_INVALID_THREAD_AT_SUSPEND2 = 0x0107, PK_INVALID_THREAD_AT_DELETE = 0x0108, PK_INVALID_THREAD_AT_INFO = 0x0109, PK_INVALID_THREAD_AT_CHANGE = 0x010a, PK_INVALID_THREAD_AT_SWAP1 = 0x010d, PK_INVALID_THREAD_AT_SWAP2 = 0x011c, PK_INVALID_THREAD_AT_CREATE = 0x011d, PK_INVALID_SEMAPHORE_AT_POST = 0x011e, PK_INVALID_SEMAPHORE_AT_PEND = 0x011f, PK_INVALID_SEMAPHORE_AT_RELEASE = 0x0200, PK_INVALID_SEMAPHORE_AT_INFO = 0x0201, PK_INVALID_SEMAPHORE_AT_CREATE = 0x0202, PK_INVALID_TIMER_AT_SCHEDULE = 0x0203, PK_INVALID_TIMER_AT_CANCEL = 0x0204, PK_INVALID_TIMER_AT_INFO = 0x0205, PK_INVALID_TIMER_AT_CREATE = 0x0206, PK_INVALID_ARGUMENT_IRQ_SETUP = 0x0207, PK_INVALID_ARGUMENT_IRQ_HANDLER = 0x0208, PK_INVALID_ARGUMENT_INTERRUPT = 0x0209, PK_INVALID_ARGUMENT_CONTEXT_SET = 0x020a, PK_INVALID_ARGUMENT_CONTEXT_GET = 0x020d, PK_INVALID_ARGUMENT_FIT = 0x021c, PK_INVALID_ARGUMENT_WATCHDOG = 0x021d, PK_INVALID_ARGUMENT_INIT = 0x021e, PK_INVALID_ARGUMENT_SEMAPHORE = 0x021f, PK_INVALID_ARGUMENT_THREAD_CHANGE = 0x0300, PK_INVALID_ARGUMENT_THREAD_PRIORITY = 0x0301, PK_INVALID_ARGUMENT_THREAD1 = 0x0302, PK_INVALID_ARGUMENT_THREAD2 = 0x0303, PK_INVALID_ARGUMENT_THREAD3 = 0x0304, PK_STACK_OVERFLOW = 0x0305, PK_TIMER_ACTIVE = 0x0306, PK_TIMER_NOT_ACTIVE = 0x0307, PK_PRIORITY_IN_USE_AT_RESUME = 0x0308, PK_PRIORITY_IN_USE_AT_CHANGE = 0x0309, PK_PRIORITY_IN_USE_AT_SWAP = 0x030a, PK_SEMAPHORE_OVERFLOW = 0x030d, PK_SEMAPHORE_PEND_NO_WAIT = 0x031c, PK_SEMAPHORE_PEND_TIMED_OUT = 0x031d, PK_SEMAPHORE_PEND_WOULD_BLOCK = 0x031e, PK_INVALID_DEQUE_SENTINEL = 0x031f, PK_INVALID_DEQUE_ELEMENT = 0x0400, PK_INVALID_OBJECT = 0x0401, // PK Kernel panics PK_NO_TIMER_SUPPORT = 0x0402, PK_START_THREADS_RETURNED = 0x0403, PK_UNIMPLEMENTED = 0x0404, PK_SCHEDULING_INVARIANT = 0x0405, PK_TIMER_HANDLER_INVARIANT = 0x0406, PK_THREAD_TIMEOUT_STATE = 0x0407, // PK PK_UNUSED_0408 = 0x0408, PK_UNUSED_0409 = 0x0409, PK_UNUSED_040a = 0x040a, PK_UNUSED_040d = 0x040d, PK_UNUSED_041c = 0x041c, PK_UNUSED_041d = 0x041d, PK_UNUSED_041e = 0x041e, PK_UNUSED_041f = 0x041f, // Sync panic codes SYNC_INVALID_OBJECT = 0x0500, SYNC_INVALID_ARGUMENT = 0x0501, SYNC_BARRIER_PEND_TIMED_OUT = 0x0502, SYNC_BARRIER_OVERFLOW = 0x0503, SYNC_BARRIER_UNDERFLOW = 0x0504, SYNC_BARRIER_INVARIANT = 0x0505, SYNC_SHARED_UNDERFLOW = 0x0506, OCCHW_INSTANCE_MISMATCH = 0x0507, OCCHW_IRQ_ROUTING_ERROR = 0x0508, OCCHW_XIR_INVALID_POINTER = 0x0509, OCCHW_XIR_INVALID_GPE = 0x050a, PK_UNUSED_050d = 0x050d, PK_UNUSED_051c = 0x051c, PK_UNUSED_051d = 0x051d, PK_UNUSED_051e = 0x051e, PK_UNUSED_051f = 0x051f, PK_UNUSED_0600 = 0x0600, PK_UNUSED_0601 = 0x0601, PK_UNUSED_0602 = 0x0602, PK_UNUSED_0603 = 0x0603, PK_UNUSED_0604 = 0x0604, PK_UNUSED_0605 = 0x0605, PK_UNUSED_0606 = 0x0606, PK_UNUSED_0607 = 0x0607, PK_UNUSED_0608 = 0x0608, PK_UNUSED_0609 = 0x0609, PK_UNUSED_060a = 0x060a, PK_UNUSED_060d = 0x060d, PK_UNUSED_061c = 0x061c, PK_UNUSED_061d = 0x061d, PK_UNUSED_061e = 0x061e, PK_UNUSED_061f = 0x061f, PK_UNUSED_0700 = 0x0700, PK_UNUSED_0701 = 0x0701, PK_UNUSED_0702 = 0x0702, PK_UNUSED_0703 = 0x0703, PK_UNUSED_0704 = 0x0704, PK_UNUSED_0705 = 0x0705, PK_UNUSED_0706 = 0x0706, PK_UNUSED_0707 = 0x0707, PK_UNUSED_0708 = 0x0708, PK_UNUSED_0709 = 0x0709, PK_UNUSED_070a = 0x070a, PK_UNUSED_070d = 0x070d, PK_UNUSED_071c = 0x071c, PK_UNUSED_071d = 0x071d, PK_UNUSED_071e = 0x071e, PK_UNUSED_071f = 0x071f, PK_UNUSED_0800 = 0x0800, PK_UNUSED_0801 = 0x0801, PK_UNUSED_0802 = 0x0802, PK_UNUSED_0803 = 0x0803, PK_UNUSED_0804 = 0x0804, PK_UNUSED_0805 = 0x0805, PK_UNUSED_0806 = 0x0806, PK_UNUSED_0807 = 0x0807, PK_UNUSED_0808 = 0x0808, PK_UNUSED_0809 = 0x0809, PK_UNUSED_080a = 0x080a, PK_UNUSED_080d = 0x080d, PK_UNUSED_081c = 0x081c, PK_UNUSED_081d = 0x081d, PK_UNUSED_081e = 0x081e, PK_UNUSED_081f = 0x081f, PK_UNUSED_0900 = 0x0900, PK_UNUSED_0901 = 0x0901, PK_UNUSED_0902 = 0x0902, PK_UNUSED_0903 = 0x0903, PK_UNUSED_0904 = 0x0904, PK_UNUSED_0905 = 0x0905, PK_UNUSED_0906 = 0x0906, PK_UNUSED_0907 = 0x0907, PK_UNUSED_0908 = 0x0908, PK_UNUSED_0909 = 0x0909, PK_UNUSED_090a = 0x090a, PK_UNUSED_090d = 0x090d, PK_UNUSED_091c = 0x091c, PK_UNUSED_091d = 0x091d, PK_UNUSED_091e = 0x091e, PK_UNUSED_091f = 0x091f, PK_UNUSED_0a00 = 0x0a00, PK_UNUSED_0a01 = 0x0a01, PK_UNUSED_0a02 = 0x0a02, PK_UNUSED_0a03 = 0x0a03, PK_UNUSED_0a04 = 0x0a04, PK_UNUSED_0a05 = 0x0a05, PK_UNUSED_0a06 = 0x0a06, PK_UNUSED_0a07 = 0x0a07, PK_UNUSED_0a08 = 0x0a08, PK_UNUSED_0a09 = 0x0a09, PK_UNUSED_0a0a = 0x0a0a, PK_UNUSED_0a0d = 0x0a0d, PK_UNUSED_0a1c = 0x0a1c, PK_UNUSED_0a1d = 0x0a1d, PK_UNUSED_0a1e = 0x0a1e, PK_UNUSED_0a1f = 0x0a1f, PK_UNUSED_0d00 = 0x0d00, PK_UNUSED_0d01 = 0x0d01, PK_UNUSED_0d02 = 0x0d02, PK_UNUSED_0d03 = 0x0d03, PK_UNUSED_0d04 = 0x0d04, PK_UNUSED_0d05 = 0x0d05, PK_UNUSED_0d06 = 0x0d06, PK_UNUSED_0d07 = 0x0d07, PK_UNUSED_0d08 = 0x0d08, PK_UNUSED_0d09 = 0x0d09, PK_UNUSED_0d0a = 0x0d0a, PK_UNUSED_0d0d = 0x0d0d, PK_UNUSED_0d1c = 0x0d1c, PK_UNUSED_0d1d = 0x0d1d, PK_UNUSED_0d1e = 0x0d1e, PK_UNUSED_0d1f = 0x0d1f, // The following are reserved for instance specific use. // Each engine must define its own XXX_panic_codes.h // Where XXX = SBE, CME, GPE0, GPE1, PGPE, SGPE // They are listed here to show the valid trap values that // can be used. #ifdef PLATFORM_PANIC_CODES_H #include PLATFORM_PANIC_CODES_H #endif //_UNUSED_1c00 = 0x1c00, //_UNUSED_1c01 = 0x1c01, //_UNUSED_1c02 = 0x1c02, //_UNUSED_1c03 = 0x1c03, //_UNUSED_1c04 = 0x1c04, //_UNUSED_1c05 = 0x1c05, //_UNUSED_1c06 = 0x1c06, //_UNUSED_1c07 = 0x1c07, //_UNUSED_1c08 = 0x1c08, //_UNUSED_1c09 = 0x1c09, //_UNUSED_1c0a = 0x1c0a, //_UNUSED_1c0d = 0x1c0d, //_UNUSED_1c1c = 0x1c1c, //_UNUSED_1c1d = 0x1c1d, //_UNUSED_1c1e = 0x1c1e, //_UNUSED_1c1f = 0x1c1f, //_UNUSED_1d00 = 0x1d00, //_UNUSED_1d01 = 0x1d01, //_UNUSED_1d02 = 0x1d02, //_UNUSED_1d03 = 0x1d03, //_UNUSED_1d04 = 0x1d04, //_UNUSED_1d05 = 0x1d05, //_UNUSED_1d06 = 0x1d06, //_UNUSED_1d07 = 0x1d07, //_UNUSED_1d08 = 0x1d08, //_UNUSED_1d09 = 0x1d09, //_UNUSED_1d0a = 0x1d0a, //_UNUSED_1d0d = 0x1d0d, //_UNUSED_1d1c = 0x1d1c, //_UNUSED_1d1d = 0x1d1d, //_UNUSED_1d1e = 0x1d1e, //_UNUSED_1d1f = 0x1d1f, //_UNUSED_1e00 = 0x1e00, //_UNUSED_1e01 = 0x1e01, //_UNUSED_1e02 = 0x1e02, //_UNUSED_1e03 = 0x1e03, //_UNUSED_1e04 = 0x1e04, //_UNUSED_1e05 = 0x1e05, //_UNUSED_1e06 = 0x1e06, //_UNUSED_1e07 = 0x1e07, //_UNUSED_1e08 = 0x1e08, //_UNUSED_1e09 = 0x1e09, //_UNUSED_1e0a = 0x1e0a, //_UNUSED_1e0d = 0x1e0d, //_UNUSED_1e1c = 0x1e1c, //_UNUSED_1e1d = 0x1e1d, //_UNUSED_1e1e = 0x1e1e, //_UNUSED_1e1f = 0x1e1f, //_UNUSED_1f00 = 0x1f00, //_UNUSED_1f01 = 0x1f01, //_UNUSED_1f02 = 0x1f02, //_UNUSED_1f03 = 0x1f03, //_UNUSED_1f04 = 0x1f04, //_UNUSED_1f05 = 0x1f05, //_UNUSED_1f06 = 0x1f06, //_UNUSED_1f07 = 0x1f07, //_UNUSED_1f08 = 0x1f08, //_UNUSED_1f09 = 0x1f09, //_UNUSED_1f0a = 0x1f0a, //_UNUSED_1f0d = 0x1f0d, //_UNUSED_1f1c = 0x1f1c, //_UNUSED_1f1d = 0x1f1d, //_UNUSED_1f1e = 0x1f1e, //_UNUSED_1f1f = 0x1f1f } pkPanicCode_t; #else /// Assembler specific panic codes #define PPE42_MACHINE_CHECK_PANIC 0x0001 #define PPE42_DATA_STORAGE_PANIC 0x0002 #define PPE42_INSTRUCTION_STORAGE_PANIC 0x0003 #define PPE42_DATA_ALIGNMENT_PANIC 0x0004 #define PK_BOOT_VECTORS_NOT_ALIGNED 0x0005 #define PPE42_ILLEGAL_INSTRUCTION 0x001c #define PK_STACK_OVERFLOW 0x0305 #endif // __ASSEMBLER__ #endif <|start_filename|>src/occ_gpe0/ipc_func_tables.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/ipc_func_tables.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ipc_api.h" #include "ipc_ping.h" #include "core_data.h" #include "proc_shared.h" void apss_init_gpio(ipc_msg_t* cmd, void* arg); void apss_init_mode(ipc_msg_t* cmd, void* arg); void apss_start_pwr_meas_read(ipc_msg_t* cmd, void* arg); void apss_continue_pwr_meas_read(ipc_msg_t* cmd, void* arg); void apss_complete_pwr_meas_read(ipc_msg_t* cmd, void* arg); void apss_toggle_hw_reset(ipc_msg_t* cmd, void* arg); void gpe_get_core_data(ipc_msg_t* cmd, void* arg); void gpe_get_nest_dts(ipc_msg_t* cmd, void* arg); void gpe_get_tod(ipc_msg_t* cmd, void* arg); void ipc_scom_operation(ipc_msg_t* cmd, void* arg); void ipc_fir_collection(ipc_msg_t* cmd, void* arg); void gpe0_nop(ipc_msg_t* cmd, void* arg); extern ipc_msgq_t G_gpe0_test_msgq0; // Function table for multi target (common) functions IPC_MT_FUNC_TABLE_START #ifdef IPC_ENABLE_PING IPC_HANDLER(ipc_ping_handler, 0) // 0 - IPC_MT_PING #else IPC_HANDLER_DEFAULT // 0 #endif IPC_HANDLER_DEFAULT // 1 IPC_HANDLER_DEFAULT // 2 IPC_HANDLER_DEFAULT // 3 IPC_HANDLER_DEFAULT // 4 IPC_HANDLER_DEFAULT // 5 IPC_HANDLER_DEFAULT // 6 IPC_HANDLER_DEFAULT // 7 IPC_MT_FUNC_TABLE_END // Function table for single target (processor-specific) functions IPC_ST_FUNC_TABLE_START IPC_MSGQ_HANDLER(&G_gpe0_test_msgq0) // 0 - IPC_ST_TEST_FUNC0 IPC_HANDLER(apss_init_gpio, 0) // 1 - IPC_ST_APSS_INIT_GPIO_FUNCID IPC_HANDLER(apss_init_mode, 0) // 2 - IPC_ST_APSS_INIT_MODE_FUNCID IPC_HANDLER(apss_start_pwr_meas_read, 0) // 3 - IPC_ST_APSS_START_PWR_MEAS_READ_FUNCID IPC_HANDLER(apss_continue_pwr_meas_read, 0) // 4 - IPC_ST_APSS_CONTINUE_PWR_MEAS_READ_FUNCID IPC_HANDLER(apss_complete_pwr_meas_read, 0) // 5 - IPC_ST_APSS_COMPLETE_PWR_MEAS_READ_FUNCID IPC_HANDLER(gpe_get_core_data, 0) // 6 - IPC_ST_GET_CORE_DATA_FUNCID IPC_HANDLER(ipc_scom_operation, 0) // 7 - IPC_ST_SCOM_OPERATION IPC_HANDLER(gpe0_nop, 0) // 8 - IPC_ST_GPE0_NOP IPC_HANDLER(gpe_get_nest_dts, 0) // 9 - IPC_ST_GET_NEST_DTS_FUNCID IPC_HANDLER(ipc_fir_collection, 0) // 10 - IPC_ST_FIR_COLLECTION IPC_HANDLER(gpe_get_tod, 0) // 11 - IPC_ST_GET_TOD_FUNCID IPC_HANDLER(apss_toggle_hw_reset, 0) // 12 - IPC_ST_APSS_RESET_FUNCID IPC_HANDLER_DEFAULT // 13 IPC_HANDLER_DEFAULT // 14 IPC_HANDLER_DEFAULT // 15 IPC_ST_FUNC_TABLE_END <|start_filename|>src/occ_405/amec/amec_perfcount.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_perfcount.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_PERFCOUNT_H #define _AMEC_PERFCOUNT_H /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Constants */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Globals */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Defines */ /*----------------------------------------------------------------------------*/ #define MAX_UTIL_SLACK_AVG_LEN 64 // Max # of samples in utilization slack averaging buffer /*----------------------------------------------------------------------------*/ /* Typedef / Enum */ /*----------------------------------------------------------------------------*/ /// Core Performance Counter Model typedef struct amec_core_perf_counter { ///32-bit accumulator of util_slack counter uint32_t util_slack_accumulator; ///32-bit accumulator of util_active counter uint32_t util_active_accumulator; ///Circular buffer pointer to put Utilslack signal uint16_t ptr_putUtilslack; ///Frequency request uint16_t dps_freq_request; ///32-bit pointer to utilization slack averaging buffer uint8_t ptr_util_slack_avg_buffer[2*MAX_UTIL_SLACK_AVG_LEN]; ///32-bit pointer to utilization active averaging buffer uint8_t ptr_util_active_avg_buffer[2*MAX_UTIL_SLACK_AVG_LEN]; ///8-bit counter of cores that are active (utilization>CPU_utilization_threshold) uint8_t util_active_core_counter; ///8-bit counter of cores with slack (utilization<type 1 alg UTIL tlutil) uint8_t util_slack_core_counter; }amec_core_perf_counter_t; /*----------------------------------------------------------------------------*/ /* Function Prototypes */ /*----------------------------------------------------------------------------*/ /** * Calculate the performance counter for a core * */ void amec_calc_dps_util_counters(const uint8_t i_core_id); /** * Build the performance counter for a core * */ amec_core_perf_counter_t* amec_core_perf_counter_ctor(amec_core_perf_counter_t* i_this_ptr, const uint8_t i_proc_id, const uint8_t i_core_id); #endif <|start_filename|>src/occ_405/dimm/dimm_control.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/dimm/dimm_control.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <occ_common.h> #include "dimm_structs.h" #include "rtls.h" #ifndef _DIMM_CONTROL_H #define _DIMM_CONTROL_H bool dimm_control(uint8_t mc, uint8_t port); void dimm_update_nlimits(uint8_t mc, uint8_t port); void populate_dimm_control_args(uint16_t i_throttle, uint8_t mc, uint8_t port, dimm_control_args_t * dimm_control_args); uint16_t convert_speed2numerator(uint16_t i_throttle, uint16_t min_n_value, uint16_t max_n_value); #endif //_DIMM_CONTROL_H <|start_filename|>src/common/gpe_util.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/common/gpe_util.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _APSS_UTIL_H #define _APSS_UTIL_H #include <apss_structs.h> #include <common_types.h> #include <ipc_structs.h> #include <ipc_async_cmd.h> void gpe_set_ffdc(GpeErrorStruct *o_error, uint32_t i_addr, uint32_t i_rc, uint64_t i_ffdc); int wait_spi_completion(GpeErrorStruct *error, uint32_t reg, uint32_t timeout); // Read decrementer register #define MFDEC(reg_var) \ asm volatile \ ( \ " mfdec %[dec_var] \n" \ : [dec_var]"=r"(reg_var) \ ); void busy_wait(uint32_t t_microseconds); #endif //_APSS_UTIL_H <|start_filename|>src/occ_gpe0/gpe0_main.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/gpe0_main.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" #include "pk_trace.h" #include "ipc_api.h" #include "ipc_ping.h" #include "gpe_export.h" /* Checkstop analysis is using at least 700 bytes */ #define KERNEL_STACK_SIZE 1024 uint8_t G_kernel_stack[KERNEL_STACK_SIZE]; //Point to the GPE shared structure #define GPE_SHARED_DATA_ADDR 0xFFFB3C00 #define GPE_SHARED_DATA_SIZE 256 gpe_shared_data_t * G_gpe_shared_data = (gpe_shared_data_t*) GPE_SHARED_DATA_ADDR; extern PkTraceBuffer* g_pk_trace_buf_ptr; //statically initialize a ping command message IPC_PING_CMD_CREATE(G_ping_cmd); //statically initialize an IPC message queue IPC_MSGQ_CREATE(G_gpe0_test_msgq0); //statically initialize an IPC message queue message. Responses to //this message will automatically be placed on the message queue. IPC_MSGQ_MSG_CREATE(G_test_msg, IPC_ST_TEST_FUNC0, &G_gpe0_test_msgq0); // The main function is called by the boot code (after initializing some // registers) int main(int argc, char **argv) { int rc; uint32_t l_timebase = G_gpe_shared_data->nest_freq_div; // Don't initialize with a 0 if (!l_timebase) { l_timebase = PPE_TIMEBASE_HZ; } // Mark the location of the trace buffer in shared data G_gpe_shared_data->gpe0_tb_ptr = (uint32_t) g_pk_trace_buf_ptr; G_gpe_shared_data->gpe0_tb_sz = sizeof(PkTraceBuffer); // initializes kernel data (stack, threads, timebase, timers, etc.) pk_initialize((PkAddress)G_kernel_stack, KERNEL_STACK_SIZE, PK_TIMEBASE_CONTINUES, l_timebase); PK_TRACE("Kernel init completed, timebase is %d Hz", l_timebase); // Disable IPC's and register the IPC interrupt handler rc = ipc_init(); if(rc) { PK_TRACE("ipc_init failed with rc = 0x%08x", rc); pk_halt(); } // enable IPC's rc = ipc_enable(); if(rc) { PK_TRACE("ipc_enable failed with rc = 0x%08x", rc); pk_halt(); } return 0; } <|start_filename|>src/ssx/occhw/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/ssx/occhw/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2015,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG # This Makefile compiles all of the SSX code required for the OCC port # of SSX. See the "img_defs.mk" file in the top directory. #all generated files from this makefile will end up in obj/$(IMAGE_NAME)/ssx export SUB_OBJDIR = /ssx include img_defs.mk include ssxocchwfiles.mk ifeq "$(SSX_TIMER_SUPPORT)" "1" OCCHW_OBJECTS += ${OCCHW-TIMER-C-SOURCES:.c=.o} ${OCCHW-TIMER-S-SOURCES:.S=.o} endif ifeq "$(SSX_THREAD_SUPPORT)" "1" OCCHW_OBJECTS += ${OCCHW-THREAD-C-SOURCES:.c=.o} ${OCCHW-THREAD-S-SOURCES:.S=.o} endif ifeq "$(OCCHW_ASYNC_SUPPORT)" "1" OCCHW_OBJECTS += ${OCCHW-ASYNC-C-SOURCES:.c=.o} ${OCCHW-ASYNC-S-SOURCES:.S=.o} endif OBJS := $(addprefix $(OBJDIR)/, $(OCCHW_OBJECTS)) libssx.a: ssx ppc405 ppc32 trace occhw $(AR) crs $(OBJDIR)/libssx.a $(OBJDIR)/*.o .PHONY: clean occhw ssx ppc405 ppc32 trace occhw: $(OBJS) trace: $(MAKE) -I $(IMAGE_SRCDIR) -C ../trace ssx: $(MAKE) -I $(IMAGE_SRCDIR) -C ../ssx ppc405: $(MAKE) -I $(IMAGE_SRCDIR) -C ../ppc405 ppc32: $(MAKE) -I $(IMAGE_SRCDIR) -C ../ppc32 $(OBJS) $(OBJS:.o=.d): | $(OBJDIR) $(OBJDIR): mkdir -p $(OBJDIR) clean: rm -fr $(OBJDIR) ifneq ($(MAKECMDGOALS),clean) -include $(OBJS:.o=.d) endif <|start_filename|>src/occ_405/mem/memory_power_control.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/mem/memory_power_control.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <occhw_async.h> #include <mem_structs.h> #include <memory_power_control.h> #include <memory_service_codes.h> #include <amec_sys.h> // GPE Requests GpeRequest G_mem_power_control_req; // GPE arguments GPE_BUFFER(mem_power_control_args_t G_mem_power_control_args); /** * GPE shared data area for gpe1 tracebuffer and size */ extern gpe_shared_data_t G_shared_gpe_data; // Function Specification // // Name: is_occ_in_ips // // Description: checks whether OCC is inside IPS (Idle Power Save). // // returns a bool: // True: if OCC is in IPS now (IPS requested frequency is not 0) // False: if OCC is not in IPS // // End Function Specification inline bool is_occ_in_ips(void) { // Check if IPS frequency request is sent by Master OCC return (g_amec->slv_ips_freq_request != 0); } // Function Specification // // Name: amec_mem_power_control // // Description: Performs memory Power control -if needed- through an IPC task // sent to the GPE1. This function is called only inside active state. // // End Function Specification // max number of tick cycles to wait while memory power control // task is still busy processing previous contron task #define WAIT_GPE_MEM_PWR_CTRL_BUSY_LIMIT 1 void amec_mem_power_control(void) { // a boolean indicating that a transition occured, and that // updating the memory power control registers is still in progress. // Set once the transition starts, and clear when all mc/port // memory power control and STR registers are already set. static bool L_memory_power_control_in_progress = false; // track the next memIndex (MC pair and port) to send // memory power control settings to. static uint8_t L_memIndex = 0; static uint8_t L_wait_idle_gpe = 0; // tick cycles waited while GPE is still not idle // New memory Power control setting uint8_t new_mem_pwr_ctl; // OCC is in Idle Power Save if(is_occ_in_ips()) { new_mem_pwr_ctl = G_sysConfigData.ips_mem_pwr_ctl; } else { new_mem_pwr_ctl = G_sysConfigData.default_mem_pwr_ctl; } if(!L_memory_power_control_in_progress) { // Apply new memory power control only if different than the current // setting (already sent to GPE1), and previous IPS trnsition's // memory power control is not currently in progress: // set in progress latch and new memory power control parameter. if(new_mem_pwr_ctl != g_amec->sys.current_mem_pwr_ctl) { // start sending memory power control IPC messages. L_memory_power_control_in_progress = true; // update the current memory power control setting g_amec->sys.current_mem_pwr_ctl = new_mem_pwr_ctl; } } if(L_memory_power_control_in_progress) { // return code from gpe_mem_power_control() int rc = 0; // send memory power control settings only if MC/port is configured // (through memory throttle config packet) if(NIMBUS_DIMM_INDEX_THROTTLING_CONFIGURED(L_memIndex)) { rc = gpe_mem_power_control(g_amec->sys.current_mem_pwr_ctl, L_memIndex, L_wait_idle_gpe); } // if memory power control task is not idle, don't increment, // DIMM index, just wait for up to WAIT_GPE_MEM_PWR_CTRL_BUSY_LIMIT // additional ticks. if( (rc != GPE_REQUEST_TASK_NOT_IDLE) || (L_wait_idle_gpe >= WAIT_GPE_MEM_PWR_CTRL_BUSY_LIMIT) ) { L_memIndex++; L_wait_idle_gpe = 0; } else // GPE task is not idle, and L_wait_idle_gpe is still within limit { L_wait_idle_gpe++; } // Memory power control settings are sent to all MC/port control registers if(L_memIndex >= NUM_NIMBUS_MCAS) { // turn off the memory power control in progress latch, // and reset memory index variable. L_memory_power_control_in_progress = false; L_memIndex = 0; } } } // Function Specification // // Name: gpe_init_mem_power_control // // Description: create a gpe request IPC task on GPE1 for memory power control // // End Function Specification void gpe_init_mem_power_control(void) { int rc; // return code errlHndl_t err = NULL; // Error handler do { //Initializes the GpeRequest object for gpe memory control IPC rc = gpe_request_create(&G_mem_power_control_req, // GpeRequest for task &G_async_gpe_queue1, // Queue IPC_ST_MEM_POWER_CONTROL_FUNCID, // Function ID &G_mem_power_control_args, // Task parameters SSX_WAIT_FOREVER, // Timeout (none) NULL, // Callback NULL, // Callback arguments ASYNC_CALLBACK_IMMEDIATE ); // Options if( rc ) { // If we failed to create the GpeRequest then there is a serious problem. MAIN_TRAC_ERR("gpe_init_mem_power_control: Failure creating the " "IPC_ST_MEM_POWER_CONTROL_FUNCID GpeRequest. [RC=0x%08x]", rc ); /* * @errortype * @moduleid MEM_MID_MEM_INIT_POWER_CONTROL * @reasoncode GPE_REQUEST_CREATE_FAILURE * @userdata1 gpe_request_create return code * @userdata4 OCC_NO_EXTENDED_RC * @devdesc Failure to create memory power control GpeRequest object */ err = createErrl( MEM_MID_MEM_INIT_POWER_CONTROL, //ModId GPE_REQUEST_CREATE_FAILURE, //Reasoncode OCC_NO_EXTENDED_RC, //Extended reason code ERRL_SEV_PREDICTIVE, //Severity NULL, //Trace Buf DEFAULT_TRACE_SIZE, //Trace Size rc, //Userdata1 0 //Userdata2 ); REQUEST_RESET(err); } } while (0); return; } // Function Specification // // Name: gpe_mem_power_control // // Description: schedule a memory power control IPC task on GPE1 // // End Function Specification int gpe_mem_power_control(uint8_t mem_pwr_ctl, uint8_t mca, uint8_t wait_idle_gpe) { int rc = 0; // return code errlHndl_t err = NULL; // Error handler static bool L_busy_error_traced = false; // IPC task still busy static bool L_fail_error_traced = false; // IPC task completed with errors static bool L_sched_error_traced = false; // IPC task couldn't be scheduled do { // Check the completion of previous invocation of memory power control. if(!async_request_is_idle(&G_mem_power_control_req.request)) { // Report idle GPEs once only, then no need to track idle wait cycles. if(!L_busy_error_traced) { // gpe_mem_power_control() will no longer be called for this DIMM in this transition if(wait_idle_gpe >= WAIT_GPE_MEM_PWR_CTRL_BUSY_LIMIT ) { // an earlier memory power control IPC has not completed, trace and log an error TRAC_ERR("gpe_mem_power_control: memory power control IPC task is not Idle"); /* * @errortype * @moduleid MEM_MID_GPE_MEM_POWER_CONTROL * @reasoncode GPE_REQUEST_TASK_NOT_IDLE * @userdata1 0 * @userdata4 OCC_NO_EXTENDED_RC * @devdesc gpe memory power control task not idle */ err = createErrl( MEM_MID_GPE_MEM_POWER_CONTROL, //ModId GPE_REQUEST_TASK_NOT_IDLE, //Reasoncode OCC_NO_EXTENDED_RC, //Extended reason code ERRL_SEV_INFORMATIONAL, //Severity NULL, //Trace Buf DEFAULT_TRACE_SIZE, //Trace Size 0, //Userdata1 0 //Userdata2 ); addUsrDtlsToErrl(err, (uint8_t *) G_shared_gpe_data.gpe1_tb_ptr, G_shared_gpe_data.gpe1_tb_sz, ERRL_USR_DTL_STRUCT_VERSION_1, ERRL_USR_DTL_TRACE_DATA); commitErrl(&err); L_busy_error_traced = true; } } rc = GPE_REQUEST_TASK_NOT_IDLE; break; } // Verify that last memory power control (if any) completed with no errors. if(GPE_RC_SUCCESS != G_mem_power_control_args.error.rc) { if(!L_fail_error_traced) { // an earlier memory power control IPC call returned an error, // trace and log that error TRAC_ERR("gpe_mem_power_control: memory power control IPC task returned an error" "rc[%x], MC-Pair[%d], Port[%d]", G_mem_power_control_args.error.rc, G_mem_power_control_args.mc, G_mem_power_control_args.port); /* * @errortype * @moduleid MEM_MID_GPE_MEM_POWER_CONTROL * @reasoncode GPE_REQUEST_RC_FAILURE * @userdata1 rc * @userdata2 mca * @userdata4 OCC_NO_EXTENDED_RC * @devdesc gpe memory power control task returned an error */ err = createErrl( MEM_MID_GPE_MEM_POWER_CONTROL, //ModId GPE_REQUEST_RC_FAILURE, //Reasoncode OCC_NO_EXTENDED_RC, //Extended reason code ERRL_SEV_INFORMATIONAL, //Severity NULL, //Trace Buf DEFAULT_TRACE_SIZE, //Trace Size G_mem_power_control_args.error.rc, //Userdata1 ((G_mem_power_control_args.mc<<2) + G_mem_power_control_args.port) //Userdata2 ); commitErrl(&err); L_fail_error_traced = true; } rc = GPE_REQUEST_RC_FAILURE; break; } // set memory power control arguments to GPE1 G_mem_power_control_args.mem_pwr_ctl = mem_pwr_ctl; G_mem_power_control_args.port = mca & 0x03; G_mem_power_control_args.mc = mca >> 2; // Schedule GPE1 memory power control IPC task rc = gpe_request_schedule(&G_mem_power_control_req); // Confirm Successfull completion of GPE1 memory power control task if(rc != 0) { if(!L_sched_error_traced) { //Error in scheduling memory power control task TRAC_ERR("gpe_mem_power_control: Failed to schedule memory power " "control task rc=%x. Can't perform memory Power Control", rc); /* @ * @errortype * @moduleid MEM_MID_GPE_MEM_POWER_CONTROL * @reasoncode GPE_REQUEST_SCHEDULE_FAILURE * @userdata1 rc - gpe_request_schedule return code * @userdata2 0 * @userdata4 OCC_NO_EXTENDED_RC * @devdesc OCC Failed to schedule memory power control IPC task */ err = createErrl( MEM_MID_GPE_MEM_POWER_CONTROL, // modId GPE_REQUEST_SCHEDULE_FAILURE, // reasoncode OCC_NO_EXTENDED_RC, // Extended reason code ERRL_SEV_UNRECOVERABLE, // Severity NULL, // Trace Buf DEFAULT_TRACE_SIZE, // Trace Size rc, // userdata1 0 // userdata2 ); commitErrl(&err); L_sched_error_traced = true; } rc = GPE_REQUEST_SCHEDULE_FAILURE; } }while(0); return rc; } <|start_filename|>src/occ_405/dcom/dcom_thread.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/dcom/dcom_thread.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _DCOM_THREAD_C #define _DCOM_THREAD_C #include "ssx.h" #include "occhw_pba.h" #include <rtls.h> #include <apss.h> #include <dcom.h> #include <dcom_service_codes.h> #include <occ_service_codes.h> #include <trac.h> #include <state.h> #include <proc_pstate.h> #include <amec_freq.h> // Reset Prep command received from (H)TMGT? bool G_reset_prep = false; // Debug Counter to make sure dcom thread is running uint16_t G_dcom_thread_counter = 0; SsxSemaphore G_dcomThreadWakeupSem; // Function Specification // // Name: Dcom_thread_routine // // Description: Purpose of this task is to handle messages passed from // Master to Slave and vice versa. // // Nothing in this thread should be time-critical, but should // happen more often than the 1-second that other threads run // at. // // FWIW -- It is pointless to set this thread to run any more // often than the length of the RTL loop, since it is acting // on data passed back and forth via that loop. // // End Function Specification void Dcom_thread_routine(void *arg) { OCC_STATE l_newOccState = 0; OCC_MODE l_newOccMode = 0; SsxTimer l_timeout_timer; errlHndl_t l_errlHndl = NULL; // -------------------------------------------------- // Create a timer that pops every 10 seconds to wake up // this thread, in case a semaphore never gets posted. // -------------------------------------------------- ssx_timer_create(&l_timeout_timer, (SsxTimerCallback) ssx_semaphore_post, (void *) &G_dcomThreadWakeupSem); ssx_timer_schedule(&l_timeout_timer, SSX_SECONDS(10), SSX_SECONDS(10)); DCOM_TRAC_INFO("DCOM Thread Started"); for(;;) { // -------------------------------------------------- // Wait on Semaphore until we get new data over DCOM // (signalled by sem_post() or timeout occurs. // Sem timeout is designed to be the slowest // interval we will attempt to run this thread at. // -------------------------------------------------- // Wait for sem_post before we run through this thread. ssx_semaphore_pend(&G_dcomThreadWakeupSem, SSX_WAIT_FOREVER); // -------------------------------------------------- // Counter to ensure thread is running (can wrap) // -------------------------------------------------- G_dcom_thread_counter++; // -------------------------------------------------- // Check if we need to update the opal table // only start checking after OCC has gone thru state change // -------------------------------------------------- if( (CURRENT_STATE() >= OCC_STATE_OBSERVATION) || (isSafeStateRequested()) ) { // stop checking if we hit a critical error trying to update memory if(G_opal_table_update_state != OPAL_TABLE_UPDATE_CRITICAL_ERROR) { check_for_opal_updates(); } } // -------------------------------------------------- // Set Mode and State Based on Master // -------------------------------------------------- l_newOccState = (G_occ_master_state == CURRENT_STATE()) ? OCC_STATE_NOCHANGE : G_occ_master_state; if(G_sysConfigData.system_type.kvm) { l_newOccMode = (G_occ_master_mode == G_occ_external_req_mode_kvm ) ? OCC_MODE_NOCHANGE : G_occ_master_mode; } else { l_newOccMode = (G_occ_master_mode == CURRENT_MODE() ) ? OCC_MODE_NOCHANGE : G_occ_master_mode; } // Override State if SAFE state is requested l_newOccState = ( isSafeStateRequested() ) ? OCC_STATE_SAFE : l_newOccState; // Override State if we are in SAFE state already l_newOccState = ( OCC_STATE_SAFE == CURRENT_STATE() ) ? OCC_STATE_NOCHANGE : l_newOccState; // Don't allow state change if reset prep was recieved l_newOccState = G_reset_prep ? OCC_STATE_NOCHANGE : l_newOccState; if( (OCC_STATE_NOCHANGE != l_newOccState) || (OCC_MODE_NOCHANGE != l_newOccMode) ) { // If we're active, then we should always process the mode change first // If we're not active, then we should always process the state change first if(OCC_STATE_ACTIVE == CURRENT_STATE()) { // Set the new mode l_errlHndl = SMGR_set_mode(l_newOccMode); if(l_errlHndl) { commitErrl(&l_errlHndl); } // Set the new state l_errlHndl = SMGR_set_state(l_newOccState); if(l_errlHndl) { commitErrl(&l_errlHndl); } } else { // Set the new state l_errlHndl = SMGR_set_state(l_newOccState); if(l_errlHndl) { commitErrl(&l_errlHndl); } // Set the new mode l_errlHndl = SMGR_set_mode(l_newOccMode); if(l_errlHndl) { commitErrl(&l_errlHndl); } } } // -------------------------------------------------- // SSX Sleep // -------------------------------------------------- // Even if semaphores are continually posted, there is no reason // for us to run this thread any more often than once every tick // so we don't starve any other thread ssx_sleep(SSX_MICROSECONDS(MICS_PER_TICK)); } } #endif //_DCOM_THREAD_C <|start_filename|>src/include/p9_config.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/p9_config.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file p9_config.h /// \brief Chip configuration data structures for P9 OCC procedures #ifndef __P9_GPE_CONFIG_H__ #define __P9_GPE_CONFIG_H__ #include <stdint.h> #define THERM_DTS_RESULT 0x00050000 #define MAX_NUM_CORES 24 #define CORES_PER_QUAD 4 #define MAX_NUM_QUADS (MAX_NUM_CORES/CORES_PER_QUAD) typedef union dts_sensor_result_reg { uint64_t value; struct { uint16_t reading[2]; uint16_t unused_hw2; uint16_t unused_hw3; } half_words; } dts_sensor_result_reg_t; typedef union sensor_result { uint16_t result; struct { uint16_t reading : 12; uint16_t thermal_trip : 2; uint16_t spare : 1; uint16_t valid : 1; } fields; } sensor_result_t; /// SCOM address Ranges: // Cores (EX chiplet): 0x20000000 - 0x37000000 // Caches: 0x10000000 - 0x15000000 // #define CHIPLET_CORE_SCOM_BASE 0x20000000 #define CHIPLET_CACHE_SCOM_BASE 0x10000000 #define CHIPLET_NEST_SCOM_BASE 0x02000000 #define CHIPLET_CORE_ID(n) \ (((n) << 24) + CHIPLET_CORE_SCOM_BASE) #define CHIPLET_CACHE_ID(n) \ (((n) << 24) + CHIPLET_CACHE_SCOM_BASE) #define CHIPLET_NEST_ID(n) \ (((n) << 24) + CHIPLET_NEST_SCOM_BASE) #endif /* __P9_GPE_CONFIG_H__ */ <|start_filename|>src/ppe/pk/gpe/gpe_pba_cntl.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/gpe/gpe_pba_cntl.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __GPE_PBA_CNTL_H__ #define __GPE_PBA_CNTL_H__ #include "pk.h" #include "occhw_pba_common.h" #define PBA_BUF_W 0x000008000 #define PBA_BUF_A 0x000004000 #define PBA_BUF_B 0x000002000 #define PBA_BUF_C 0x000001000 /** * Reset PBA slave * @note global PBASLVCTLN selects with slave (0-3) default is 0 * PBASLVCTLN can be set as a compile-time env var. * @return NONE */ void gpe_pba_reset(); /** * Setup PBA slave * * @note global PBASLVCTLN selects which slave (0-3) default is 0 * @param[in] i_gpeInstanceId OCCHW_INST_ID_GPE0 to OCCHW_INST_ID_GPE3 * @param[in] i_write_ttype One of: * PBA_WRITE_TTYPE_DMA_PR_WR * PBA_WRITE_TTYPE_ATOMIC_RMW * * @param[in] i_write_tsize. * If ttype is PBA_WRITE_TTYPE_DMA_PR_WR then * tsize is chiplet ID of L3 Cache. Set to PBA_WRITE_TSIZE_DC(0) * If ttype is PBA_WRITE_TTYPE_ATOMIC_RMW then * tsize must be one of: * PBA_WRITE_TSIZE_ARMW_ADD * PBA_WRITE_TSIZE_ARMW_AND * PBA_WRITE_TSIZE_ARMW_OR * PBA_WRITE_TSIZE_ARMW_XOR * * @param[in] i_read_ttype One of: * PBA_READ_TTYPE_CL_RD_NC * PBA_READ_TTYPE_CI_PR_RD * * @param[in] i_buf_alloc Buffers to assign Any/ALL of * [PBA_BUF_W | PBA_BUF_A | PBA_BUF_B | PBA_BUF_C] * * example: * gpe_pba_slave_setup(OCCHW_INST_ID_GPE0, * PBA_WRITE_TTYPE_DMA_PR_WR, * PBA_WRITE_TSIZE_DC, * PBA_READ_TTYPE_CL_RD_NC, * PBA_BUF_W | PBA_BUF_A | PBA_BUF_B | PBA_BUF_C * ); */ void gpe_pba_slave_setup(uint32_t i_gpeInstanceId, uint32_t i_write_ttype, uint32_t i_write_tsize, uint32_t i_read_ttype, uint32_t i_buf_alloc); #endif <|start_filename|>src/ssx/occhw/occhw_pba.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_pba.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_PBA_H__ #define __OCCHW_PBA_H__ /// \file occhw_pba.h /// \brief PBA unit header. Local and mechanically generated macros. /// \todo Add Doxygen grouping to constant groups #include "pba_register_addresses.h" #include "pba_firmware_registers.h" #include "occhw_pba_common.h" #define POWERBUS_CACHE_LINE_SIZE 128 #define LOG_POWERBUS_CACHE_LINE_SIZE 7 /// The PBA OCI region is always either 0 or 3 #define PBA_OCI_REGION 0 // It is assumed the the PBA BAR sets will be assigned according to the // following scheme. There are still many open questions concerning PBA // setup. /// The number of PBA Base Address Registers (BARS) #define PBA_BARS 4 #define PBA_BAR_CHIP 0 #define PBA_BAR_NODE 2 #define PBA_BAR_SYSTEM 3 #define PBA_BAR_CENTAUR 1 #define PBA_BAR_OCC 0 /* OCC image (HOMER) */ #define PBA_BAR_PORE_SLW 2 /* Redundant mapping for SLW offset into HOMER */ // Standard PBA slave assignments, set up by FAPI procedure prior to releasing // OCC from reset. /// The number of PBA slaves #define PBA_SLAVES 4 #define PBA_SLAVE_PORE_GPE 0 /* GPE0/1, but only 1 can access mainstore */ #define PBA_SLAVE_OCC 1 /* 405 I- and D-cache */ #define PBA_SLAVE_PORE_SLW 2 #define PBA_SLAVE_OCB 3 /// The maximum number of bytes a PBA block-copy engine can transfer at once #define PBA_BCE_SIZE_MAX 4096 /// The base-2 log of the minimum PBA translation window size in bytes #define PBA_LOG_SIZE_MIN 20 /// The base-2 log of the maximum PBA translation window size in bytes /// /// Note that windows > 2**27 bytes require the extended address. #define PBA_LOG_SIZE_MAX 41 /// The number of PBA slaves #define PBA_SLAVES 4 /// The number of PBA read buffers #define PBA_READ_BUFFERS 6 /// The number of PBA write buffers #define PBA_WRITE_BUFFERS 2 // PBASLVCTLn and PBASLVRST macros defined in occhw_pba_common.h // PBA PowerBus command scope and priority, and PBA defaults /// Nodal, Local Node #define POWERBUS_COMMAND_SCOPE_NODAL 0x0 /// Group, Local 4-chip, (aka, node pump) #define POWERBUS_COMMAND_SCOPE_GROUP 0x1 /// System, All units in the system #define POWERBUS_COMMAND_SCOPE_SYSTEM 0x2 /// RGP, All units in the system (aka, system pump) #define POWERBUS_COMMAND_SCOPE_RGP 0x3 /// Foreign, All units on the local chip, local SMP, and remote chip (pivot /// nodes), In P8, only 100 and 101 are valid. #define POWERBUS_COMMAND_SCOPE_FOREIGN0 0x4 /// Foreign, All units on the local chip, local SMP, and remote chip (pivot /// nodes), In P8, only 100 and 101 are valid. #define POWERBUS_COMMAND_SCOPE_FOREIGN1 0x5 /// Default command scope for BCDE/BCUE transfers #define PBA_POWERBUS_COMMAND_SCOPE_DEFAULT POWERBUS_COMMAND_SCOPE_NODAL // PBA Error/Panic codes #define PBA_SCOM_ERROR1 0x00722001 #define PBA_SCOM_ERROR2 0x00722002 #define PBA_SLVRST_TIMED_OUT1 0x00722003 #define PBA_SLVRST_TIMED_OUT2 0x00722004 #define PBA_INVALID_ARGUMENT_BARSET 0x00779005 #define PBA_INVALID_ARGUMENT_RESET 0x00779006 #define PBAX_INVALID_ARGUMENT_CONFIG 0x00779007 #define PBAX_INVALID_ARGUMENT_TARGET 0x00779008 #define PBAX_INVALID_OBJECT 0x00722009 #ifndef __ASSEMBLER__ /// The PBA extended address in the form of a 'firmware register' /// /// The extended address covers only bits 23:36 of the 50-bit PowerBus address. typedef union pba_extended_address { uint64_t value; uint32_t word[2]; struct { uint64_t reserved0 : 23; uint64_t extended_address : 14; uint64_t reserved1 : 27; } fields; } pba_extended_address_t; int pba_barset_initialize(int idx, uint64_t base, int log_size); int _pba_slave_reset(int id, SsxInterval timeout, SsxInterval sleep); int pba_slave_reset(int id); //////////////////////////////////////////////////////////////////////////// // PBAX //////////////////////////////////////////////////////////////////////////// // PBAX error/panic codes #define PBAX_SEND_TIMEOUT 0x00722901 #define PBAX_SEND_ERROR 0x00722902 #define PBAX_RECEIVE_ERROR 0x00722903 /// The number of receive queues implemented by PBAX #define PBAX_QUEUES 2 /// The number of PBAX Node Ids #define PBAX_GROUPS 16 /// The number of PBAX Chip Ids (and group Ids) #define PBAX_CHIPS 8 /// The maximum legal PBAX group mask #define PBAX_GROUP_MASK_MAX 0xff // PBAX Send Message Scope #define PBAX_GROUP 3 #define PBAX_SYSTEM 5 // PBAX Send Type #define PBAX_UNICAST 0 #define PBAX_BROADCAST 1 // Default timeout for pbax_send() #ifndef PBAX_SEND_DEFAULT_TIMEOUT #define PBAX_SEND_DEFAULT_TIMEOUT SSX_MICROSECONDS(30) #endif /// An abstract target for PBAX send operations /// /// This structure contains an abstraction of a communication target for PBAX /// send operations. An application using PBAX to transmit data first creates /// an instance of the PbaxTarget for each abstract target using /// pbax_target_create(), then calls pbax_send() or _pbax_send() with a /// PbaxTarget and an 8-byte data packet to effect a transmission. /// /// For applications that use GPE programs to implement PBAX sends, a pointer /// to this object could also be passed to the GPE program. typedef struct { /// The abstract target /// /// pbax_target_create() condenses the target parameters into a copy of /// the PBAXSNDTX register used to configure the transmission. pba_xsndtx_t target; } PbaxTarget; int pbax_target_create(PbaxTarget* target, int type, int scope, int queue, int node, int chip_or_group, int cnt); int pbax_configure(int master, int node, int chip, int group_mask); int _pbax_send(PbaxTarget* target, uint64_t data, SsxInterval timeout); int pbax_send(PbaxTarget* target, uint64_t data); /// Enable the PBAX send mechanism static inline void pbax_send_enable(void) { pba_xcfg_t pxc; pxc.words.high_order = in32(PBA_XCFG); pxc.fields.pbax_en = 1; out32(PBA_XCFG, pxc.words.high_order); } /// Disable the PBAX send mechanism static inline void pbax_send_disable(void) { pba_xcfg_t pxc; pxc.words.high_order = in32(PBA_XCFG); pxc.fields.pbax_en = 0; out32(PBA_XCFG, pxc.words.high_order); } /// Clear the PBAX send error condition static inline void pbax_clear_send_error(void) { pba_xcfg_t pxc; pxc.words.high_order = in32(PBA_XCFG); pxc.fields.snd_reset = 1; out32(PBA_XCFG, pxc.words.high_order); } /// Clear the PBAX receive error condition static inline void pbax_clear_receive_error(void) { pba_xcfg_t pxc; pxc.words.high_order = in32(PBA_XCFG); pxc.fields.rcv_reset = 1; out32(PBA_XCFG, pxc.words.high_order); } #endif /* __ASSEMBLER__ */ #endif /* __OCCHW_PBA_H__ */ <|start_filename|>src/include/p9_pstates_cmeqm.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/p9_pstates_cmeqm.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_pstates_cmeqm.h /// @brief Pstate structures and support routines for CME Hcode /// // *HWP HW Owner : <NAME> <<EMAIL>> // *HWP HW Owner : <NAME> <<EMAIL>> // *HWP Team : PM // *HWP Level : 1 // *HWP Consumed by : CME:PGPE #ifndef __P9_PSTATES_CME_H__ #define __P9_PSTATES_CME_H__ #include <p9_pstates_common.h> /// \defgroup QM Flags /// /// These are flag bits for the \a Quad Manager field. /// /// @{ /// qmflag() - Disable Resonant Clock use. #define PSTATE_RESCLK_DISABLE 0x8000 /// qmflag() - Disable IVRM use. #define PSTATE_IVRMS_DISABLE 0x4000 /// qmflag() - Disable VDM use. #define PSTATE_VDM_DISABLE 0x2000 /// qmflag() - Disable WOF. #define PSTATE_WOF_DISABLE 0x1000 /// qmflag() - dpll_dynamic_fmax_enable #define PSTATE_DPLL_DYNAMIC_FMAX_ENABLE 0x0800 /// qmflag() - dpll_dynamic_fmin_enable #define PSTATE_DPLL_DYNAMIC_FMIN_ENABLE 0x0400 /// qmflag() - dpll_droop_protect_enable #define PSTATE_DPLL_DROOP_PROTECT_ENABLE 0x0200 /// @} #ifndef __ASSEMBLER__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> /// LocalParmsBlock Magic Number /// /// This magic number identifies a particular version of the /// PstateParmsBlock and its substructures. The version number should be /// kept up to date as changes are made to the layout or contents of the /// structure. #define LOCAL_PARMSBLOCK_MAGIC 0x434d455050423030ull /* CMEPPB00 */ /// Quad Manager Flags /// typedef union { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t resclk_enable : 1; uint16_t ivrm_enable : 1; uint16_t wof_enable : 1; uint16_t dpll_dynamic_fmax_enable : 1; uint16_t dpll_dynamic_fmin_enable : 1; uint16_t dpll_droop_protect_enable : 1; uint16_t reserved : 10; #else uint16_t reserved : 10; uint16_t dpll_droop_protect_enable : 1; uint16_t dpll_dynamic_fmin_enable : 1; uint16_t dpll_dynamic_fmax_enable : 1; uint16_t wof_enable : 1; uint16_t ivrm_enable : 1; uint16_t resclk_enable : 1; #endif // _BIG_ENDIAN } fields; } QuadManagerFlags; /// Resonant Clock Stepping Entry /// typedef union { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t sector_buffer : 4; uint16_t spare1 : 1; uint16_t pulse_enable : 1; uint16_t pulse_mode : 2; uint16_t resonant_switch : 4; uint16_t spare4 : 4; #else uint16_t spare4 : 4; uint16_t resonant_switch : 4; uint16_t pulse_mode : 2; uint16_t pulse_enable : 1; uint16_t spare1 : 1; uint16_t sector_buffer : 4; #endif // _BIG_ENDIAN } fields; } ResonantClockingStepEntry; #define RESCLK_FREQ_REGIONS 8 #define RESCLK_STEPS 64 #define RESCLK_L3_STEPS 4 typedef struct ResonantClockControl { uint8_t resclk_freq[RESCLK_FREQ_REGIONS]; // Lower frequency of Resclk Regions uint8_t resclk_index[RESCLK_FREQ_REGIONS]; // Index into value array for the // respective Resclk Region /// Array containing the transition steps ResonantClockingStepEntry steparray[RESCLK_STEPS]; /// Delay between steps (in nanoseconds) /// Maximum delay: 65.536us uint16_t step_delay_ns; /// L3 Clock Stepping Array uint8_t l3_steparray[RESCLK_L3_STEPS]; /// Resonant Clock Voltage Threshold (in millivolts) /// This value is used to choose the appropriate L3 clock region setting. uint16_t l3_threshold_mv; } ResonantClockingSetup; // #W data points (version 2) typedef struct { uint16_t ivdd_tdp_ac_current_10ma; uint16_t ivdd_tdp_dc_current_10ma; uint8_t vdm_overvold_small_thresholds; uint8_t vdm_large_extreme_thresholds; uint8_t vdm_small_frequency_drop; uint8_t vdm_large_frequency_drop; uint16_t vdm_spare; } poundw_entry_t; typedef struct { uint16_t r_package_common; uint16_t r_quad; uint16_t r_core; uint16_t r_quad_header; uint16_t r_core_header; } resistance_entry_t; typedef struct { poundw_entry_t poundw_nominal; poundw_entry_t poundw_powersave; poundw_entry_t poundw_turbo; poundw_entry_t poundw_ultraturbo; resistance_entry_t resistance_data; uint64_t reserved1; uint16_t reserved2; } PoundW_data; /// VDM/Droop Parameter Block /// typedef struct { uint8_t vid_compare_override_mv_enable; uint8_t vid_compare_override_mv[VPD_PV_POINTS]; uint8_t vdm_response; // For the following *_enable fields, bits are defined to indicate // which of the respective *override* array entries are valid. // bit 0: UltraTurbo; bit 1: Turbo; bit 2: Nominal; bit 3: PowSave uint8_t droop_small_override_enable; uint8_t droop_large_override_enable; uint8_t droop_extreme_override_enable; uint8_t overvolt_override_enable; uint16_t fmin_override_khz_enable; uint16_t fmax_override_khz_enable; // The respecitve *_enable above indicate which index values are valid uint8_t droop_small_override[VPD_PV_POINTS]; uint8_t droop_large_override[VPD_PV_POINTS]; uint8_t droop_extreme_override[VPD_PV_POINTS]; uint8_t overvolt_override[VPD_PV_POINTS]; uint16_t fmin_override_khz[VPD_PV_POINTS]; uint16_t fmax_override_khz[VPD_PV_POINTS]; /// Pad structure to 8-byte alignment /// @todo pad once fully structure is complete. // uint8_t pad[1]; } VDMParmBlock; /// The layout of the data created by the Pstate table creation firmware for /// comsumption by the Pstate GPE. This data will reside in the Quad /// Power Management Region (QPMR). /// /// Standard options controlling Pstate setup procedures /// System Power Distribution Paramenters /// /// Parameters set by system design that influence the power distribution /// for a rail to the processor module. This values are typically set in the /// system machine readable workbook and are used in the generation of the /// Global Pstate Table. This values are carried in the Pstate SuperStructure /// for use and/or reference by OCC firmware (eg the WOF algorithm) /// IVRM Parameter Block /// /// @todo Major work item. Largely will seed the CME Quad Manager to perform /// iVRM voltage calculations #define IVRM_ARRAY_SIZE 64 typedef struct iVRMInfo { /// Pwidth from 0.03125 to 1.96875 in 1/32 increments at Vin=Vin_Max uint8_t strength_lookup[IVRM_ARRAY_SIZE]; // Each entry is a six bit value, right justified /// Scaling factor for the Vin_Adder calculation. uint8_t vin_multiplier[IVRM_ARRAY_SIZE]; // Each entry is from 0 to 255. /// Vin_Max used in Vin_Adder calculation (in millivolts) uint16_t vin_max_mv; /// Delay between steps (in nanoseconds) /// Maximum delay: 65.536us uint16_t step_delay_ns; /// Stabilization delay once target voltage has been reached (in nanoseconds) /// Maximum delay: 65.536us uint16_t stablization_delay_ns; /// Deadzone (in millivolts) /// Maximum: 255mV. If this value is 0, 50mV is assumed. uint8_t deadzone_mv; /// Pad to 8B uint8_t pad; } IvrmParmBlock; /// The layout of the data created by the Pstate table creation firmware for /// comsumption by the CME Quad Manager. This data will reside in the Core /// Power Management Region (CPMR). /// typedef struct { /// Magic Number uint64_t magic; // the last byte of this number the structure's version. // QM Flags QuadManagerFlags qmflags; /// Operating points /// /// VPD operating points are stored without load-line correction. Frequencies /// are in MHz, voltages are specified in units of 5mV, and currents are /// in units of 500mA. VpdOperatingPoint operating_points[VPD_PV_POINTS]; /// Loadlines and Distribution values for the VDD rail SysPowerDistParms vdd_sysparm; /// External Biases /// /// Biases applied to the VPD operating points prior to load-line correction /// in setting the external voltages. This is used to recompute the Vin voltage /// based on the Global Actual Pstate . /// Values in 0.5% VpdBias ext_biases[VPD_PV_POINTS]; /// Internal Biases /// /// Biases applied to the VPD operating points that are used for interpolation /// in setting the internal voltages (eg Vout to the iVRMs) as part of the /// Local Actual Pstate. /// Values in 0.5% VpdBias int_biases[VPD_PV_POINTS]; /// IVRM Data IvrmParmBlock ivrm; /// Resonant Clock Grid Management Setup ResonantClockingSetup resclk; /// VDM Data VDMParmBlock vdm; } LocalPstateParmBlock; #ifdef __cplusplus } // end extern C #endif #endif /* __ASSEMBLER__ */ #endif /* __P9_PSTATES_CME_H__ */ <|start_filename|>src/ppe/pk/ppe/pkppefiles.mk<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/ppe/pk/ppe/pkppefiles.mk $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2015,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG # @file pkppefiles.mk # # @brief mk for including ppe object files ########################################################################## # Object Files ########################################################################## PPE-C-SOURCES = ppe_init.c PPE-S-SOURCES = PPE-TIMER-C-SOURCES = PPE-TIMER-S-SOURCES = PPE-THREAD-C-SOURCES = PPE-THREAD-S-SOURCES = PPE-ASYNC-C-SOURCES = PPE-ASYNC-S-SOURCES = PPE_OBJECTS += $(PPE-C-SOURCES:.c=.o) $(PPE-S-SOURCES:.S=.o) <|start_filename|>src/occ_405/incl/comp_ids.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/incl/comp_ids.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //Note: Be sure to mirror changes in this file to occ/plugins/tmgtTpmdCompIds.H!!! // If you don't, the ERRL plugin will eventually break, and you might break the // fips build for TMGT. #ifndef _COMP_IDS_H #define _COMP_IDS_H #define COMP_NAME_SIZE 4 #define MAIN_COMP_ID 0x0100 #define MAIN_COMP_NAME "MAIN" #define ERRL_COMP_ID 0x0200 #define ERRL_COMP_NAME "ERRL" #define TRAC_COMP_ID 0x0300 #define TRAC_COMP_NAME "TRAC" #define RTLS_COMP_ID 0x0400 #define RTLS_COMP_NAME "RTLS" #define THRD_COMP_ID 0x0500 #define THRD_COMP_NAME "THRD" #define SNSR_COMP_ID 0x0600 #define SNSR_COMP_NAME "SNSR" // Applet Manager #define APLT_COMP_ID 0x0700 #define APLT_COMP_NAME "APLT" #define PSS_COMP_ID 0x0800 #define PSS_COMP_NAME "PSS" #define TMER_COMP_ID 0x0900 #define TMER_COMP_NAME "TMER" #define DCOM_COMP_ID 0x0A00 #define DCOM_COMP_NAME "DCOM" // Proc data #define PROC_COMP_ID 0x0B00 #define PROC_COMP_NAME "PROC" // Amec data #define AMEC_COMP_ID 0x0C00 #define AMEC_COMP_NAME "AMEC" // Centaur data #define CENT_COMP_ID 0x0D00 #define CENT_COMP_NAME "CENT" // Command Handler #define CMDH_COMP_ID 0x0E00 #define CMDH_COMP_NAME "CMDH" // DIMM State Manager #define DIMM_COMP_ID 0x0F00 #define DIMM_COMP_NAME "DIMM" // MEMORY Control #define MEM_COMP_ID 0x1000 #define MEM_COMP_NAME "MEM" // Workload Optimize Frequency #define WOF_COMP_ID 0x1100 #define WOF_COMP_NAME "WOF" // PGPE Interface #define PGPE_COMP_ID 0x1200 #define PGPE_COMP_NAME "PGPE" // GPU Interface #define GPU_COMP_ID 0x1300 #define GPU_COMP_NAME "GPU" #endif <|start_filename|>src/occ_405/reset.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/reset.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <occ_common.h> #include <common_types.h> #include "ssx_io.h" #include "trac.h" #include "rtls.h" #include "state.h" #include "dcom.h" // Holds the state of the reset state machine uint8_t G_reset_state = RESET_NOT_REQUESTED; // Flag indicating if we should halt on a reset request, or if we should // enter the reset state machine. Default this to false bool G_halt_on_reset_request = FALSE; // Function Specification // // Name: reset_disable_halt // // Description: Clear Flag that indicates if OCC should call halt // // End Function Specification inline void reset_disable_halt(void) { G_halt_on_reset_request = FALSE; } // Function Specification // // Name: isSafeStateRequested // // Description: Helper function for determining if we should go to safe state // // End Function Specification bool isSafeStateRequested(void) { return ((RESET_REQUESTED_DUE_TO_ERROR == G_reset_state) ? TRUE : FALSE); } // Function Specification // // Name: reset_state_request // // Description: Request Reset States // // End Function Specification void reset_state_request(uint8_t i_request) { switch(i_request) { case RESET_REQUESTED_DUE_TO_ERROR: // In case we want to just halt() if fw requests a reset, this is // the place to do it. It is disabled by default, and there is no // code to eanble it. if( G_halt_on_reset_request ) { TRAC_ERR("Halt()"); // This isn't modeled very well in simics. OCC will go into an // infinite loop, which eventually would crash Simics. HALT_WITH_FIR_SET; } // If we have TMGT comm, and we aren't already in reset, set the reset // state to reset to enter the reset state machine. if( G_reset_state < RESET_REQUESTED_DUE_TO_ERROR ) { TRAC_IMP("Activating reset required state."); G_reset_state = RESET_REQUESTED_DUE_TO_ERROR; // Post the semaphore to wakeup the thread that // will put us into SAFE state. ssx_semaphore_post(&G_dcomThreadWakeupSem); // Set RTL Flags here too, depending how urgent it is that we stop // running tasks. rtl_set_run_mask(RTL_FLAG_RST_REQ); } break; case NOMINAL_REQUESTED_DUE_TO_ERROR: if( G_reset_state < NOMINAL_REQUESTED_DUE_TO_ERROR ) { TRAC_ERR("Going to Nominal because of error"); // May need to add counter if multiple places request nominal G_reset_state = NOMINAL_REQUESTED_DUE_TO_ERROR; } break; case RESET_NOT_REQUESTED: if( G_reset_state == NOMINAL_REQUESTED_DUE_TO_ERROR ) { TRAC_IMP("Clearing Nominal Reset State because of error"); // May need to add counter check if multiple places request nominal G_reset_state = RESET_NOT_REQUESTED; } break; default: break; } } <|start_filename|>src/occ_405/pss/avsbus.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pss/avsbus.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "avsbus.h" #include <trac.h> #include <occ_common.h> #include <comp_ids.h> #include <occ_sys_config.h> #include <trac_interface.h> #include "ocb_register_addresses.h" #include "occ_service_codes.h" #include "pss_service_codes.h" #include "ssx.h" #include "occ_util.h" #include "cmdh_fsp_cmds_datacnfg.h" #include "common.h" //#define AVSDEBUG #ifdef AVSDEBUG #define DEBUG_TRACE_MAX 2 static bool G_trace_scoms = TRUE; #define AVS_DBG(frmt,args...) TRAC_INFO(frmt,##args) #define DEBUG_IN32(reg, result, name) if (G_trace_scoms) { TRAC_INFO(" in32(%08X) returned 0x%08X "name, reg, result); } #define DEBUG_OUT32(reg, value, name) if (G_trace_scoms) { TRAC_INFO("out32(%08X) = 0x%08X "name, reg, value); } #else #define AVS_DBG(frmt,args...) #define DEBUG_IN32(reg, result, name) #define DEBUG_OUT32(reg, value, name) #endif // // 64 bit operations are only directly supported by the GPE. On the 405 the // opreations will get broken up into two 32 bit operations. // // FYI: Using out64 was not working for writing OCB registers. // The problem was that when it breaks it down into two operations, // it winds up writing the wdata register twice. // AVS Bus usage will be determined after receiving config data from TMGT bool G_avsbus_vdd_monitoring = FALSE; bool G_avsbus_vdn_monitoring = FALSE; // Vdd Current reading to check if it rolled over (0 when no roll over checking required) uint32_t G_check_vdd_current_10mA_for_rollover = 0; extern uint16_t G_allow_trace_flags; extern uint32_t G_nest_frequency_mhz; #define AVSBUS_FREQUENCY_MHZ 10 extern bool G_vrm_vdd_temp_expired; void amec_health_check_vrm_vdd_temp(const sensor_t *i_sensor); // Number of read failures allowed before elog is created and reset requested. // If readings take longer than 4ms, it will impact WOF calculations. // Voltage/Current are read every 3 ticks (1.5ms). // Because 3 read attemps would take 4.5ms (> 4ms), an error needs to be logged. const uint8_t MAX_READ_ATTEMPTS = 3; const uint16_t AVSBUS_STATUS_READ_ERROR = 0xFFFF; extern data_cnfg_t * G_data_cnfg; uint32_t avs_crc_calculate(const uint32_t i_avs_cmd); // NOTE: OCC must use Bridge B, because Bridge A is reserved for PGPE // Registers are based on bus number const uint32_t OCB_O2SCMDxB[2] = { OCB_O2SCMD0B, OCB_O2SCMD1B }; const uint32_t OCB_O2SWDxB[2] = { OCB_O2SWD0B, OCB_O2SWD1B }; const uint32_t OCB_O2SSTxB[2] = { OCB_O2SST0B, OCB_O2SST1B }; const uint32_t OCB_O2SRDxB[2] = { OCB_O2SRD0B, OCB_O2SRD1B }; // Wait for operation to complete (clear ongoing) uint32_t wait_for_complete(const uint8_t i_bus) { uint32_t l_status = in32(OCB_O2SSTxB[i_bus]); DEBUG_IN32(OCB_O2SSTxB[i_bus], l_status, "OCB_O2SSTxB"); unsigned int loops = 0; while ((l_status & AVSBUS_STATUS_ONGOING) && (loops < 500)) { // o2s_ongoing bit was still set (operation did not complete) l_status = in32(OCB_O2SSTxB[i_bus]); ++loops; } DEBUG_IN32(OCB_O2SSTxB[i_bus], l_status, "OCB_O2SSTxB"); if (0 != (l_status & AVSBUS_STATUS_ERRORS)) { TRAC_ERR("wait_for_complete(): error in status register: 0x%08X", l_status); } else if (l_status & AVSBUS_STATUS_ONGOING) // o2s_ongoing { TRAC_ERR("wait_for_complete(): timeout waiting for ongoing bit to clear (%d loops) 0x%08X", loops, l_status); } return l_status; } // Clear bits i_status_mask in status reg for i_bus uint32_t clear_status_errors(const uint8_t i_bus, const uint32_t i_status_mask) { // Write O2SCMD[a][n] // o2s_clear_sticky_bits = 1 uint32_t value = 0x40000000; DEBUG_OUT32(OCB_O2SCMDxB[i_bus], value, "OCB_O2SCMDxB"); out32(OCB_O2SCMDxB[i_bus], value); // To clear status bits write the status bits you wish to clear with a 1. (in CmdData) // AVS Bus command (write status): // 0:1 StartCode = 0b01 // 2:3 Cmd = 0b00 (write+commit) // 4 CmdGroup = 0b0 (AVSBus) // 5:8 CmdDataType (STATUS = 01110b) // 9:12 Select (All rails / broadcast = 01111b ) // 13:28 CmdData (status bits to clear) // 29:31 CRC // 01000DDD DRRRRXXX XXXXXXXX XXXXXCCC // 01000111 01111--- -------- -----CCC uint32_t cmd_data = i_status_mask; value = 0x47780000 | (cmd_data << 3); // Calculate/add CRC value |= avs_crc_calculate(value); DEBUG_OUT32(OCB_O2SWDxB[i_bus], value, "OCB_O2SWDxB"); out32(OCB_O2SWDxB[i_bus], value); // Wait for operation to complete (clear ongoing) const uint32_t l_status = wait_for_complete(i_bus); // return the last read status return l_status; } // end clear_status_errors() // Re-sync AVS bus to try to recover from errors // Reference: chips/p9/procedures/hwp/lib/p9_avsbus_lib.C // chips/p9/procedures/ppe_closed/pgpe/pstate_gpe/avs_driver.c uint32_t avsbus_resync(const uint8_t i_bus) { // clear sticky bits in o2s_status_reg // Write O2SCMD[a][n] // o2s_clear_sticky_bits = 1 uint32_t value = 0x40000000; DEBUG_OUT32(OCB_O2SCMDxB[i_bus], value, "OCB_O2SCMDxB"); out32(OCB_O2SCMDxB[i_bus], value); // Drive AVS transaction with a frame value 0xFFFFFFFF (idle frame) // to initialize the AVS slave. // In principle this only has to be done once. Though docs suggest // that due to noise on the chip this init should be done periodically. TRAC_INFO("avsbus_resync: Send idle frame (bus %d)", i_bus); value = 0xFFFFFFFF; DEBUG_OUT32(OCB_O2SWDxB[i_bus], value, "OCB_O2SWDxB"); out32(OCB_O2SWDxB[i_bus], value); // Wait for operation to complete (clear ongoing) const uint32_t l_status = wait_for_complete(i_bus); // return the last read status return l_status; } // end avsbus_resync() // AVS Bus setup that must be done once (common between read/write operations) void avsbus_init() { uint32_t value; TRAC_INFO("avsbus_init: Vdd=%c Vdn=%c", G_avsbus_vdd_monitoring?'Y':'N', G_avsbus_vdn_monitoring?'Y':'N'); bool bus0_monitoring = FALSE; bool bus1_monitoring = FALSE; if (G_avsbus_vdd_monitoring) { if (0 == G_sysConfigData.avsbus_vdd.bus) { bus0_monitoring = TRUE; } else { bus1_monitoring = TRUE; } } if (G_avsbus_vdn_monitoring) { if (0 == G_sysConfigData.avsbus_vdn.bus) { bus0_monitoring = TRUE; } else { bus1_monitoring = TRUE; } } // Write O2SCTRLF_[a][n] // o2s_frame_size = 0x20 (32d) // o2s_out_count1 = 0x20 (32d) - 5b header, 8b command type/select,16b info, 3b CRC // o2s_in_delay1 = 0xFF (long delay - no read data) // o2s_in_count1 = 0x0 (no read data) value = 0x820FC000; if (bus0_monitoring) { DEBUG_OUT32(OCB_O2SCTRLF0B, value, "OCB_O2SCTRLF0B"); out32(OCB_O2SCTRLF0B, value); } if (bus1_monitoring) { DEBUG_OUT32(OCB_O2SCTRLF1B, value, "OCB_O2SCTRLF1B"); out32(OCB_O2SCTRLF1B, value); } // Write O2SCTRLS_[a][n] // 0:5 o2s_out_count2 = 0 (no output) // 6:11 o2s_in_delay2 = 0 (no delay - immediate read data) // 12:17 o2s_in_count2 = 32 (bits captured) value = 0x00080000; if (bus0_monitoring) { DEBUG_OUT32(OCB_O2SCTRLS0B, value, "OCB_O2SCTRLS0B"); out32(OCB_O2SCTRLS0B, value); } if (bus1_monitoring) { DEBUG_OUT32(OCB_O2SCTRLS1B, value, "OCB_O2SCTRLS1B"); out32(OCB_O2SCTRLS1B, value); } // Write O2SCTRL1_[a][n] // 0 o2s_bridge_enable = 1 (make the O2S bridge active if not already) // 1 reserved // 2 o2s_cpol = 0 (positive active clock) // 3 o2s_cpha = 1 (second edge data sample) // 4:13 o2s_clock_divider = set based on the nest frequency for the desired frequency of 10MHz (assumed speed) per O2SCTRL1_[a][n] description. // 14:16 reserved // 17 o2s_nr_of_frames = 1 (2 frames to account for the first and second frames of an AVSBus command) // 18:63 reserved // 1r00DDDD DDDDDDrr r1rrrrrr rrrrrrrrr value = 0x90004000; // calculate o2s_clock_divider based on nest freq and target bus freq const uint32_t divider = (G_nest_frequency_mhz / (AVSBUS_FREQUENCY_MHZ * 8)) - 1; value |= (divider << 18); if (bus0_monitoring) { TRAC_INFO("avsbus_init: reg[OCB_O2SCTRL10B] = 0x%08X", value); out32(OCB_O2SCTRL10B, value); } if (bus1_monitoring) { TRAC_INFO("avsbus_init: reg[OCB_O2SCTRL11B] = 0x%08X", value); out32(OCB_O2SCTRL11B, value); } // Write O2SCTRL2_[a][n] // o2s_inter_frame_delay = 0 (Wait 1 SPI clock). The AVSBus spec does not define any inter-frame delay so set this to the smallest value. // Note: the value 0 is the hardware reset value and, thus, this step can be omitted if the value desired to to be left at 0. value = 0x00000000; if (bus0_monitoring) { DEBUG_OUT32(OCB_O2SCTRL20B, value, "OCB_O2SCTRL20B"); out32(OCB_O2SCTRL20B, value); } if (bus1_monitoring) { DEBUG_OUT32(OCB_O2SCTRL21B, value, "OCB_O2SCTRL21B"); out32(OCB_O2SCTRL21B, value); } // Re-sync AVS bus and clear OC bits in status regs and const uint32_t error_mask = AVSBUS_STATUS_OVER_CURRENT_MASK; if (bus0_monitoring) { avsbus_resync(0); clear_status_errors(0, error_mask); } if (bus1_monitoring) { avsbus_resync(1); clear_status_errors(1, error_mask); } } // end avsbus_init() // Calculate CRC for specified AVS Bus command // Function which generates a 3 bit CRC value for 29 bit data // from: ekb/chips/p9/procedures/hwp/lib/p9_avsbus_lib.C // (CRC is bits 29:31 in the AVS bus command) #define AVS_CRC_MASK 0x00000007 #define AVS_CRC_DATA_MASK 0xFFFFFFF8 uint32_t avs_crc_calculate(const uint32_t i_avs_cmd) { //Polynomial= x^3 + x^1 + x^0 = 1*x^3 + 0*x^2 + 1*x^1 + 1*x^0 = divisor(1011) uint32_t o_crc_value = 0; uint32_t l_polynomial = 0xB0000000; uint32_t l_msb = 0x80000000; o_crc_value = i_avs_cmd & AVS_CRC_DATA_MASK; while (o_crc_value & AVS_CRC_DATA_MASK) { if (o_crc_value & l_msb) { //if l_msb is 1'b1, divide by l_polynomial and shift l_polynomial // to the right o_crc_value = o_crc_value ^ l_polynomial; l_polynomial = l_polynomial >> 1; } else { // if l_msb is zero, shift l_polynomial l_polynomial = l_polynomial >> 1; } l_msb = l_msb >> 1; } return o_crc_value; } // Initiate read for specified type (Vdd/Vdn) and cmd (Voltage/Current) void avsbus_read_start(const avsbus_type_e i_type, const avsbus_cmdtype_e i_cmdtype) { if (isSafeStateRequested()) { // No need to attempt read if OCC will be reset return; } avsbusData_t l_data; // Create error array for each type (Vdd/Vdn) and command (Voltage/Current) if (AVSBUS_VDD == i_type) { l_data = G_sysConfigData.avsbus_vdd; } else { l_data = G_sysConfigData.avsbus_vdn; } #ifdef AVSDEBUG uint8_t l_cmd_index = 0; char l_trace_cmd = 'V'; char l_trace_type = 'd'; if (i_cmdtype == AVSBUS_CURRENT) { l_cmd_index = 1; l_trace_cmd = 'C'; } else if (i_cmdtype == AVSBUS_TEMPERATURE) { l_cmd_index = 2; l_trace_cmd = 'T'; } if (AVSBUS_VDD != i_type) { l_trace_type = 'n'; } static uint32_t L_trace_count[AVSBUS_TYPE_MAX][AVSBUS_CMDS_MAX] = {{0}}; uint32_t * l_trace_count = &L_trace_count[i_type][l_cmd_index]; if (*l_trace_count < DEBUG_TRACE_MAX) { TRAC_INFO("avsbus_read_start: Vd%c %c - bus[%d] rail[%d]", l_trace_type, l_trace_cmd, l_data.bus, l_data.rail); } #endif // Write O2SCMD[a][n] // o2s_clear_sticky_bits = 1 uint32_t value = 0x40000000; DEBUG_OUT32(OCB_O2SCMDxB[l_data.bus], value, "OCB_O2SCMDxB"); out32(OCB_O2SCMDxB[l_data.bus], value); // Write O2SWD[a][n] - write commands and initiate hardware operation // o2s_wdata with content // AVS Bus command (read voltage/current): // 0:1 StartCode = 0b01 // 2:3 Cmd = 0b11 (read) // 4 CmdGroup = 0b0 (AVSBus) // 5:8 CmdDataType (read/write voltage or read current) // 9:12 Select (Rail Select) // 13:28 CmdData (reserved / must be 1s) // 29:31 CRC // 01110DDD DRRRR111 11111111 11111CCC value = 0x7007FFF8 | ((uint32_t) i_cmdtype << 23) | ((uint32_t)l_data.rail << 19); // Calculate/add CRC value |= avs_crc_calculate(value); DEBUG_OUT32(OCB_O2SWDxB[l_data.bus], value, "OCB_O2SWDxB"); out32(OCB_O2SWDxB[l_data.bus], value); // Read has been started so now just wait for HW to complete // HW: Wait for bus op to complete // HW: arbitration between two bridges // HW: o2s_ongoing: 0 -> 1 // HW: execution completes // HW: o2s_ongoing 1 -> 0 #ifdef AVSDEBUG ++*l_trace_count; #endif } // end avsbus_read_start() // Read and return the voltage, current, or temperature for specified rail // (voltage units are mV, current units are in 10mA, temperature in 0.1 C) uint16_t avsbus_read(const avsbus_type_e i_type, const avsbus_cmdtype_e i_cmdtype) { if (isSafeStateRequested()) { // No need to process data if OCC will be reset return 0; } uint16_t o_reading = 0; bool l_failure = FALSE; uint8_t l_cmd_index = 0; char l_trace_cmd = 'V'; if (i_cmdtype == AVSBUS_CURRENT) { l_cmd_index = 1; l_trace_cmd = 'C'; } else if (i_cmdtype == AVSBUS_TEMPERATURE) { l_cmd_index = 2; l_trace_cmd = 'T'; } // Static error counters for each type (Vdd/Vdn) and command (Voltage/Current) static uint32_t L_error_count[AVSBUS_TYPE_MAX][AVSBUS_CMDS_MAX] = {{0}}; uint32_t * l_error_count = &L_error_count[i_type][l_cmd_index]; char l_trace_type = 'd'; avsbusData_t l_data = G_sysConfigData.avsbus_vdd; if (AVSBUS_VDN == i_type) { l_trace_type = 'n'; l_data = G_sysConfigData.avsbus_vdn; } #ifdef AVSDEBUG static uint32_t L_trace_count[AVSBUS_TYPE_MAX][AVSBUS_CMDS_MAX] = {{0}}; uint32_t * l_trace_count = &L_trace_count[i_type][l_cmd_index]; if (*l_trace_count < DEBUG_TRACE_MAX) { TRAC_INFO("avsbus_read: Vd%c %c - bus[%d] rail[%d]", l_trace_type, l_trace_cmd, l_data.bus, l_data.rail); } #endif // HW: Wait for bus op to complete // HW: arbitration between two bridges // HW: o2s_ongoing: 0 -> 1 // HW: execution completes // HW: o2s_ongoing 1 -> 0 // Since read was started in previous tick, it should have already completed // (no need to poll/wait on o2s_ongoing) enum occReasonCode rc = OCC_SUCCESS_REASON_CODE; uint32_t l_status = in32(OCB_O2SSTxB[l_data.bus]); DEBUG_IN32(OCB_O2SSTxB[l_data.bus], l_status, "OCB_O2SSTxB"); // OCC O2S Status Register // 0 o2s_ongoing // 1:4 reserved // 5 write_while_bridge_busy_error // 6 reserved // 7 FSM error // 8:63 reserved // GrrrrBrF rrrrrrrr rrrrrrrr rrrrrrrr if (0 != (l_status & AVSBUS_STATUS_ERRORS)) { // error bit was set l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read: Error found in Vd%c %c O2SST[0x%08X] = [0x%08X]", l_trace_type, l_trace_cmd, OCB_O2SSTxB[l_data.bus], l_status); /* * @errortype * @moduleid PSS_MID_AVSBUS_READ * @reasoncode AVSBUS_ERROR * @userdata1 AVS Bus type/bus/rail * @userdata2 status * @devdesc Error encountered when reading AVS Bus */ rc = AVSBUS_ERROR; } } else if (l_status & AVSBUS_STATUS_ONGOING) // o2s_ongoing { // o2s_ongoing bit was still set (operation did not complete) l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read: Vd%c %c timeout waiting for o2s_ongoing change O2SST[0x%08X] = [0x%08X]", l_trace_type, l_trace_cmd, OCB_O2SSTxB[l_data.bus], l_status); /* * @errortype * @moduleid PSS_MID_AVSBUS_READ * @reasoncode AVSBUS_TIMEOUT * @userdata1 AVS Bus type/bus/rail * @userdata2 status * @devdesc Timeout when reading AVS Bus */ rc = AVSBUS_TIMEOUT; } } if (FALSE == l_failure) { // Read the response data uint32_t value = in32(OCB_O2SRDxB[l_data.bus]); DEBUG_IN32(OCB_O2SRDxB[l_data.bus], value, "OCB_O2SRDxB"); // AVS Bus response (read voltage, current, or temperature): // 0:1 SlaveAck (0b00 from slave indicates good CRC and action was taken) // 2 0 // 3:7 StatusResp // 8:23 CmdData (LSB = 1mV or 10mA or 0.1C) // 24:28 Reserved (must be all 1s) // 29:31 CRC // AA0SSSSS VVVVVVVV VVVVVVVV 11111CCC // Validate CRC const uint32_t crc = avs_crc_calculate(value); if (crc != (value & AVS_CRC_MASK)) { l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read: CRC mismatch in Vd%c %c rsp O2SRD[0x%08X] = [0x%08X] (calculated CRC 0x%08X)", l_trace_type, l_trace_cmd, OCB_O2SRDxB[l_data.bus], value, crc); /* * @errortype * @moduleid PSS_MID_AVSBUS_READ * @reasoncode AVSBUS_CRC_ERROR * @userdata1 AVS Bus type/bus/rail * @userdata2 status * @devdesc CRC error reading AVS Bus */ rc = AVSBUS_CRC_ERROR; } } // Check for valid command operation and extract read data else if (0 == (value & 0xC0000000)) { o_reading = (value >> 8) & 0x0000FFFF; #ifdef AVSDEBUG if (*l_trace_count < DEBUG_TRACE_MAX) { if (i_cmdtype == AVSBUS_VOLTAGE) { TRAC_INFO("avsbus_read: Successfully read Vd%c voltage %dmV [0x%08X]", l_trace_type, o_reading, value); } else if (i_cmdtype == AVSBUS_CURRENT) { TRAC_INFO("avsbus_read: Successfully read Vd%c current %dx10mA [0x%08X]", l_trace_type, o_reading, value); } } #endif if (i_cmdtype == AVSBUS_TEMPERATURE) { #ifdef AVSDEBUG if (*l_trace_count < DEBUG_TRACE_MAX) { TRAC_INFO("avsbus_read: Successfully read Vd%c temperature %d/10 C [0x%08X]", l_trace_type, o_reading, value); } #endif // Update sensor (convert to degrees C) and validate it sensor_t * l_sensor = AMECSENSOR_PTR(TEMPVDD); sensor_update(l_sensor, (uint16_t)o_reading/10); G_vrm_vdd_temp_expired = false; amec_health_check_vrm_vdd_temp(l_sensor); } if (*l_error_count) { // Trace and clear the error count TRAC_INFO("avsbus_read: Successfully read Vd%c %c [0x%08X] (error count=%d)", l_trace_type, l_trace_cmd, value, *l_error_count); *l_error_count = 0; } } else { l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read: SlaveAck reported no action taken[0x%08X]", value); rc = AVSBUS_ERROR; } } } if (l_failure) { enum occExtReasonCode exrc = ERC_AVSBUS_VDD_VOLTAGE_FAILURE; if (AVSBUS_VDD == i_type) { if (i_cmdtype == AVSBUS_CURRENT) { exrc = ERC_AVSBUS_VDD_CURRENT_FAILURE; INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDD_CURRENT); } else if (i_cmdtype == AVSBUS_VOLTAGE) { INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDD_VOLTAGE); } else if (i_cmdtype == AVSBUS_TEMPERATURE) { exrc = ERC_AVSBUS_VDD_TEMPERATURE_FAILURE; INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDD_TEMPERATURE); } } else { if (i_cmdtype == AVSBUS_CURRENT) { exrc = ERC_AVSBUS_VDN_CURRENT_FAILURE; INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDN_CURRENT); } else if (i_cmdtype == AVSBUS_VOLTAGE) { exrc = ERC_AVSBUS_VDN_VOLTAGE_FAILURE; INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDN_VOLTAGE); } } if (*l_error_count == MAX_READ_ATTEMPTS) { TRAC_ERR("avsbus_read: Reached %d consecutive Vd%c %c errors, requesting reset", *l_error_count, l_trace_type, l_trace_cmd); G_avsbus_vdd_monitoring = FALSE; G_avsbus_vdn_monitoring = FALSE; errlHndl_t l_err = createErrl(PSS_MID_AVSBUS_READ, rc, exrc, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, (i_type << 16) | (l_data.bus << 8) | l_data.rail, l_status); // add processor callout and request reset addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_HUID, G_sysConfigData.proc_huid, ERRL_CALLOUT_PRIORITY_MED); REQUEST_RESET(l_err); } else { // Force a re-sync after any failure avsbus_resync(l_data.bus); } } #ifdef AVSDEBUG ++*l_trace_count; #endif return o_reading; } // end avsbus_read() // Start the AVS Bus read for both buses (if enabled) void initiate_avsbus_reads(avsbus_cmdtype_e i_cmdType) { if (G_avsbus_vdd_monitoring) { // AVS Bus Vdd config data was received: // Initiate AVS Bus read for Vdd (voltage or current) avsbus_read_start(AVSBUS_VDD, i_cmdType); } if (G_avsbus_vdn_monitoring) { // AVS Bus Vdn config data was received: // Initiate AVS Bus read for Vdn (voltage or current) avsbus_read_start(AVSBUS_VDN, i_cmdType); } } // end initiate_avsbus_reads() // Initiate read for error status bits (over-current) void initiate_avsbus_read_status() { if (isSafeStateRequested()) { // No need to attempt read if OCC will be reset return; } #ifdef AVSDEBUG static uint32_t L_trace_count = 0; #endif unsigned int index; for (index = 0; index < AVSBUS_TYPE_MAX; ++index) { // Determine busses that are being monitored uint8_t bus = 0xFF; if ((index == 0) && G_avsbus_vdd_monitoring) { bus = G_sysConfigData.avsbus_vdd.bus; } else if ((index == 1) && G_avsbus_vdn_monitoring) { bus = G_sysConfigData.avsbus_vdn.bus; } if (bus != 0xFF) { #ifdef AVSDEBUG if (L_trace_count < DEBUG_TRACE_MAX) { TRAC_INFO("initiate_avsbus_read_status: read Status - bus[%d], rail[broadcast]", bus); } #endif // Write O2SCMD[a][n] // o2s_clear_sticky_bits = 1 uint32_t value = 0x40000000; DEBUG_OUT32(OCB_O2SCMDxB[bus], value, "OCB_O2SCMDxB"); out32(OCB_O2SCMDxB[bus], value); // Write O2SWD[a][n] - write commands and initiate hardware operation // o2s_wdata with content // AVS Bus command (read staus): // 0:1 StartCode = 0b01 // 2:3 Cmd = 0b11 (read) // 4 CmdGroup = 0b0 (AVSBus) // 5:8 CmdDataType (STATUS = 01110b) // 9:12 Select (All rails / broadcast = 01111b ) // 13:28 CmdData (reserved / must be 1s) // 29:31 CRC // 01110DDD DRRRR111 11111111 11111CCC // 01110111 01111111 11111111 11111CCC value = 0x777FFFF8; // Calculate/add CRC value |= avs_crc_calculate(value); DEBUG_OUT32(OCB_O2SWDxB[bus], value, "OCB_O2SWDxB"); out32(OCB_O2SWDxB[bus], value); } } // Read has been started so now just wait for HW to complete // HW: Wait for bus op to complete // HW: arbitration between two bridges // HW: o2s_ongoing: 0 -> 1 // HW: execution completes // HW: o2s_ongoing 1 -> 0 #ifdef AVSDEBUG ++L_trace_count; #endif } // end initiate_avsbus_read_status() // Process AVS Bus read status results (or errors) // Returns the status data or AVSBUS_STATUS_READ_ERROR on error uint16_t avsbus_read_status(const avsbus_type_e i_type) { if (isSafeStateRequested()) { // No need to process data if OCC will be reset return 0; } uint16_t o_reading = 0; bool l_failure = FALSE; // Static error counters for each type (Vdd/Vdn) static uint32_t L_error_count[AVSBUS_TYPE_MAX] = {0}; uint32_t * l_error_count = &L_error_count[i_type]; char l_trace_type = 'd'; avsbusData_t l_data = G_sysConfigData.avsbus_vdd; if (AVSBUS_VDN == i_type) { l_trace_type = 'n'; l_data = G_sysConfigData.avsbus_vdn; } #ifdef AVSDEBUG static uint32_t L_trace_count = 0; if (L_trace_count < DEBUG_TRACE_MAX) { TRAC_INFO("avsbus_read_status: Vd%c - bus[%d] rail[%d]", l_trace_type, l_data.bus, l_data.rail); } #endif // HW: Wait for bus op to complete // HW: arbitration between two bridges // HW: o2s_ongoing: 0 -> 1 // HW: execution completes // HW: o2s_ongoing 1 -> 0 // Since read was started in previous tick, it should have already completed // (no need to poll/wait on o2s_ongoing) uint32_t l_status = in32(OCB_O2SSTxB[l_data.bus]); DEBUG_IN32(OCB_O2SSTxB[l_data.bus], l_status, "OCB_O2SSTxB"); // OCC O2S Status Register // 0 o2s_ongoing // 1:4 reserved // 5 write_while_bridge_busy_error // 6 reserved // 7 FSM error // 8:63 reserved // GrrrrBrF rrrrrrrr rrrrrrrr rrrrrrrr if (0 != (l_status & AVSBUS_STATUS_ERRORS)) { // error bit was set l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read_status: Error found in Vd%c O2SST[0x%08X] = [0x%08X]", l_trace_type, OCB_O2SSTxB[l_data.bus], l_status); } } else if (l_status & AVSBUS_STATUS_ONGOING) // o2s_ongoing { // o2s_ongoing bit was still set (operation did not complete) l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read_status: Vd%c timeout waiting for o2s_ongoing change O2SST[0x%08X] = [0x%08X]", l_trace_type, OCB_O2SSTxB[l_data.bus], l_status); } } if (FALSE == l_failure) { // Read the response data uint32_t value = in32(OCB_O2SRDxB[l_data.bus]); DEBUG_IN32(OCB_O2SRDxB[l_data.bus], value, "OCB_O2SRDxB"); // AVS Bus response (read status): // 0:1 SlaveAck (0b00 from slave indicates good CRC and action was taken) // 2 0 // 3:7 StatusResp // 8:23 CmdData (LSB = 1mV or 10mA) // 24:28 Reserved (must be all 1s) // 29:31 CRC // AA0SSSSS VVVVVVVV VVVVVVVV 11111CCC // Validate CRC const uint32_t crc = avs_crc_calculate(value); if (crc != (value & AVS_CRC_MASK)) { l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read_status: CRC mismatch in Vd%c rsp O2SRD[0x%08X] = [0x%08X] (calculated CRC 0x%08X)", l_trace_type, OCB_O2SRDxB[l_data.bus], value, crc); } } // Check for valid command operation and extract read data else if (0 == (value & 0xC0000000)) { // AVS Bus Status: // 0 VDone // 1 IOUT_OC_WARNING (over-current) // 2 VOUT_UV_WARNING (under-voltage) // 3 IOUT_OT_WARNING (over-temperature) // 4 POUT_OP_WARNING (over power) // 5-7 reserved // 8-15 reserved o_reading = (value >> 8) & 0x0000FFFF; #ifdef AVSDEBUG static uint16_t L_lastReading = 0; if ((L_trace_count < DEBUG_TRACE_MAX) || (o_reading != L_lastReading)) { TRAC_INFO("avsbus_read_status: Successfully read Vd%c status 0x%04X [0x%08X]", l_trace_type, o_reading, value); L_lastReading = o_reading; } #endif if (*l_error_count) { // Trace and clear the error count TRAC_INFO("avsbus_read_status: Successfully read Vd%c status [0x%08X] (error count=%d)", l_trace_type, value, *l_error_count); *l_error_count = 0; } } else { l_failure = TRUE; (*l_error_count)++; if ((*l_error_count == 1) || (*l_error_count == MAX_READ_ATTEMPTS)) { TRAC_ERR("avsbus_read_status: SlaveAck reported no action taken[0x%08X]", value); } } } if (l_failure) { if (*l_error_count == MAX_READ_ATTEMPTS) { TRAC_ERR("avsbus_read_status: Reached %d consecutive Vd%c errors reading status", *l_error_count, l_trace_type); // Reading AVS bus status is not critical, so don't stop monitoring or commit error } // Force a re-sync after any failure avsbus_resync(l_data.bus); o_reading = AVSBUS_STATUS_READ_ERROR; } #ifdef AVSDEBUG ++L_trace_count; if (L_trace_count >= DEBUG_TRACE_MAX) { G_trace_scoms = FALSE; } #endif return o_reading; } // end avsbus_read_status() // Read the status from AVS Bus and apply Vdd current roll over workaround if needed // Error history counters will be incremented for any over-current condition. void process_avsbus_status() { uint16_t vdd_status = 0; uint16_t vdn_status = 0; static bool L_vdd_oc_found = FALSE; static bool L_vdn_oc_found = FALSE; if (G_avsbus_vdd_monitoring) { vdd_status = avsbus_read_status(AVSBUS_VDD); if (vdd_status != AVSBUS_STATUS_READ_ERROR) { if ((vdd_status & AVSBUS_STATUS_OVER_CURRENT_MASK) == 0) { // No OC errors found if (L_vdd_oc_found) { L_vdd_oc_found = FALSE; if(G_allow_trace_flags & ALLOW_AVSBUS_TRACE) TRAC_INFO("process_avsbus_status: Vdd OC cleared"); } } else // Over current warning bit is set { INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDD_OVER_CURRENT); L_vdd_oc_found = TRUE; } // Was updating Vdd Current sensor on hold to check if the reading rolled over? if (G_check_vdd_current_10mA_for_rollover) { uint32_t l_current = G_check_vdd_current_10mA_for_rollover; // over current bit gets set when there is a roll over if (L_vdd_oc_found) { // add the rollover point (from AVSbus config data) to the Current reading l_current += G_sysConfigData.vdd_current_rollover_10mA; // sanity check for valid rollover, make sure it isn't over the theoretical max (from AVSbus config data) if(l_current > G_sysConfigData.vdd_max_current_10mA) { // went over the theoretical max don't apply the roll over INCREMENT_ERR_HISTORY(ERRH_VDD_CURRENT_ROLLOVER_MAX); if(G_allow_trace_flags & ALLOW_AVSBUS_TRACE) { TRAC_INFO("process_avsbus_status: Current with rollover %d > %d max", l_current, G_sysConfigData.vdd_max_current_10mA); } l_current = G_check_vdd_current_10mA_for_rollover; } } // Now it is ok to update the sensor with Current value in unit 10mA sensor_update(AMECSENSOR_PTR(CURVDD), (uint16_t)l_current); // Update the chip voltage and power sensors after every current reading update_avsbus_power_sensors(AVSBUS_VDD); // clear so we know we have a new reading next time G_check_vdd_current_10mA_for_rollover = 0; } } else { // error reading status INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDD_STATUS_READ_FAIL); } } if (G_avsbus_vdn_monitoring) { vdn_status = avsbus_read_status(AVSBUS_VDN); if (vdn_status != AVSBUS_STATUS_READ_ERROR) { if ((vdn_status & AVSBUS_STATUS_OVER_CURRENT_MASK) == 0) { // No OC errors found if (L_vdn_oc_found) TRAC_INFO("process_avsbus_status: Vdn OC cleared"); L_vdn_oc_found = FALSE; } else // Over current warning bit is set { INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDN_OVER_CURRENT); L_vdn_oc_found = TRUE; // Clear the over current error bit so we get a new read next time clear_status_errors(G_sysConfigData.avsbus_vdn.bus, AVSBUS_STATUS_OVER_CURRENT_MASK); } } else { // error reading status INCREMENT_ERR_HISTORY(ERRH_AVSBUS_VDN_STATUS_READ_FAIL); } } return; } // end process_avsbus_status() <|start_filename|>src/ssx/ssx/ssx_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_init.c /// \brief SSX initialization /// /// The entry points in this file are initialization routines - they are never /// needed after SSX initialization and their code space could be reclaimed by /// the application after initialization if required. #include "ssx.h" uint32_t __ssx_timebase_frequency_hz; uint32_t __ssx_timebase_frequency_khz; uint32_t __ssx_timebase_frequency_mhz; /// Initialize SSX. /// /// \param noncritical_stack A stack area for noncritical interrupt handlers. /// /// \param noncritical_stack_size The size (in bytes) of the stack area for /// noncritical interrupt handlers. /// /// \param critical_stack A stack area for critical interrupt handlers. /// /// \param critical_stack_size The size (in bytes) of the stack area for /// critical interrupt handlers. /// /// \param initial_timebase The initial value of the SSX timebase. If this /// argument is given as the special value \c SSX_TIMEBASE_CONTINUE, then the /// timebase is not reset. /// /// \param timebase_frequency_hz The frequency of the SSX timebase in Hz. /// /// This routine \e must be called before any other SSX / routines, and \e /// should be called before any interrupts are enabled. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_INIT A stack pointer is 0 or is given /// a 0 size. /// /// \retval -SSX_STACK_OVERFLOW One or both stacks are not large enough to /// support a minimum context save in the event of an interrupt. // Note that SSX does not rely on any static initialization of dynamic // variables. In debugging sessions using RAM-resident SSX images it is // assumed that the processor may be reset at any time, so we always need to // reset everything at initialization. int ssx_initialize(SsxAddress noncritical_stack, size_t noncritical_stack_size, SsxAddress critical_stack, size_t critical_stack_size, SsxTimebase initial_timebase, uint32_t timebase_frequency_hz) { int rc; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((noncritical_stack == 0) || (noncritical_stack_size == 0) || (critical_stack == 0) || (critical_stack_size == 0), SSX_INVALID_ARGUMENT_INIT); } if (initial_timebase != SSX_TIMEBASE_CONTINUES) { __ssx_timebase_set(initial_timebase); } __ssx_timebase_frequency_hz = timebase_frequency_hz; __ssx_timebase_frequency_khz = timebase_frequency_hz / 1000; __ssx_timebase_frequency_mhz = timebase_frequency_hz / 1000000; __ssx_thread_machine_context_default = SSX_THREAD_MACHINE_CONTEXT_DEFAULT; rc = __ssx_stack_init(&noncritical_stack, &noncritical_stack_size); if (rc) { return rc; } __ssx_noncritical_stack = noncritical_stack; __ssx_noncritical_stack_size = noncritical_stack_size; rc = __ssx_stack_init(&critical_stack, &critical_stack_size); if (rc) { return rc; } __ssx_critical_stack = critical_stack; __ssx_critical_stack_size = critical_stack_size; #if SSX_TIMER_SUPPORT // Initialize the time queue sentinel as a circular queue, set the next // timeout and clear the cursor. ssx_deque_sentinel_create((SsxDeque*)&__ssx_time_queue); __ssx_time_queue.cursor = 0; __ssx_time_queue.next_timeout = SSX_TIMEBASE_MAX; #endif /* SSX_TIMER_SUPPORT */ #if SSX_THREAD_SUPPORT // Clear the priority map. The final entry [SSX_THREADS] is for the idle // thread. int i; for (i = 0; i <= SSX_THREADS; i++) { __ssx_priority_map[i] = 0; } // Initialize the thread scheduler __ssx_thread_queue_clear(&__ssx_run_queue); __ssx_current_thread = 0; __ssx_next_thread = 0; __ssx_delayed_switch = 0; #endif /* SSX_THREAD_SUPPORT */ return SSX_OK; } /// Call the application main() /// /// __ssx_main() is called from the bootloader. It's only purpose is to /// provide a place for the SSX_MAIN_HOOK to be called before main() is /// called. void __ssx_main(int argc, char** argv) { SSX_MAIN_HOOK; int main(int argc, char** argv); main(argc, argv); } <|start_filename|>src/occ_gpe1/gpe1_dimm_reset.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/gpe1_dimm_reset.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file gpe1_dimm_reset.c /// \brief Functions to handle resetting the I2C engine /// //#define GPE1_DEBUG #include "pk.h" #include "ipc_api.h" #include "ppe42_scom.h" #include "ipc_async_cmd.h" #include "gpe1.h" #include "gpe1_dimm.h" #include "dimm_structs.h" #include "i2c.h" /* * Function Specifications: * * Name: dimm_reset_master * * Description: Reset the I2C master * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_reset_master(ipc_msg_t* cmd, void* arg) { // Note: arg was set to 0 in ipc func table (ipc_func_tables.c), so don't use it. // the ipc arguments passed through the ipc_msg_t structure, has a pointer // to the G_gpe_start_pwr_meas_read_args struct. int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // Reset I2C Master scomAddr = I2C_IMM_RESET_I2C | SCOM_ENGINE_OFFSET(args->i2cEngine); regValue = 0x0000000000000000; rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_reset_master: I2C_IMM_RESET_I2C putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_reset_master: putscom(0x%08X,0x%08X%08X) SUCCESS - IMM_RESET_I2C", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); // Force reset of Port_busy_register scomAddr = I2C_BUSY_REGISTER | SCOM_ENGINE_OFFSET(args->i2cEngine); regValue = 0x8000000000000000; rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_reset_master: I2C_BUSY_REGISTER putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_reset_master: putscom(0x%08X,0x%08X%08X) SUCCESS - I2C_BUSY_REGISTER", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); } } } // end dimm_reset_master() /* * Function Specifications: * * Name: dimm_reset_slave * * Description: Start reset of I2C slave * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_reset_slave(ipc_msg_t* cmd, void* arg) { int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // Write I2C mode register with the speed/port scomAddr = I2C_MODE_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); // 0-15: Bit Rate Divisor - 0x0049 gives approx 391kHz (and allows margin for clock variation) // 16-21: Port Number (0-5) // 22-26: reserved (0s) regValue = I2C_MODE_REG_DIVISOR; if ((args->i2cPort > 0) && (args->i2cPort < 6)) { regValue |= ((uint64_t)args->i2cPort << 42); } rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_reset_slave: I2C_MODE_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_reset_slave: putscom(0x%08X,0x%08X%08X) SUCCESS - MODE", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); // Force a stop-condition to the I2C slave scomAddr = I2C_COMMAND_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); // stop bit regValue = 0x1000000000000000; rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_reset_slave: I2C_COMMAND_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_reset_slave: putscom(0x%08X,0x%08X%08X) SUCCESS - COMMAND (stop)", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); } } } // end dimm_reset_slave() /* * Function Specifications: * * Name: dimm_reset_slave_status * * Description: Read I2C status register to ensure slave has been reset * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_reset_slave_status(ipc_msg_t* cmd, void* arg) { int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // Read I2C status register scomAddr = I2C_STATUS_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); rc = getscom_abs(scomAddr, &regValue); if(rc) { PK_TRACE("dimm_reset_slave_status: I2C_STATUS_REG getscom 0x%08X FAILED. rc = 0x%08x - STATUS #1", scomAddr, rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_GET_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_reset_slave_status: getscom(0x%08X) returned 0x%08X%08X) - STATUS #1", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); // Wait until command complete is set if (regValue & STATUS_COMPLETE_MASK) { // Reset completed args->error.rc = GPE_RC_SUCCESS; PK_TRACE("dimm_reset_slave_status: I2C Slave Port %d Reset completed", args->i2cPort); if ((regValue & STATUS_ERROR_OR_COMPLETE_MASK) != STATUS_COMPLETE_MASK) { // I2C errors found PK_TRACE("dimm_reset_slave_status: I2C errors in status register: %08X%08X", WORD_HIGH(regValue), WORD_LOW(regValue)); // Continue with other slave resets and may trigger another reset... } } else { // reset not complete yet... args->error.rc = GPE_RC_NOT_COMPLETE; } } } // end dimm_reset_slave_status() <|start_filename|>src/include/registers/cme_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/cme_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CME_FIRMWARE_REGISTERS_H__ #define __CME_FIRMWARE_REGISTERS_H__ /// \file cme_firmware_registers.h /// \brief C register structs for the CME unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union cme_scom_lfir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ppe_internal_error : 1; uint64_t ppe_external_error : 1; uint64_t ppe_progress_error : 1; uint64_t ppe_breakpoint_error : 1; uint64_t ppe_watchdog : 1; uint64_t ppe_halted : 1; uint64_t ppe_debug_trigger : 1; uint64_t sram_ue : 1; uint64_t sram_ce : 1; uint64_t sram_scrub_err : 1; uint64_t bce_error : 1; uint64_t spare11 : 1; uint64_t fir_parity_err_dup : 1; uint64_t fir_parity_err : 1; uint64_t reserved1 : 50; #else uint64_t reserved1 : 50; uint64_t fir_parity_err : 1; uint64_t fir_parity_err_dup : 1; uint64_t spare11 : 1; uint64_t bce_error : 1; uint64_t sram_scrub_err : 1; uint64_t sram_ce : 1; uint64_t sram_ue : 1; uint64_t ppe_debug_trigger : 1; uint64_t ppe_halted : 1; uint64_t ppe_watchdog : 1; uint64_t ppe_breakpoint_error : 1; uint64_t ppe_progress_error : 1; uint64_t ppe_external_error : 1; uint64_t ppe_internal_error : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_lfir_t; typedef union cme_scom_lfir_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ppe_internal_error : 1; uint64_t ppe_external_error : 1; uint64_t ppe_progress_error : 1; uint64_t ppe_breakpoint_error : 1; uint64_t ppe_watchdog : 1; uint64_t ppe_halted : 1; uint64_t ppe_debug_trigger : 1; uint64_t sram_ue : 1; uint64_t sram_ce : 1; uint64_t sram_scrub_err : 1; uint64_t bce_error : 1; uint64_t spare11 : 1; uint64_t fir_parity_err_dup : 1; uint64_t fir_parity_err : 1; uint64_t reserved1 : 50; #else uint64_t reserved1 : 50; uint64_t fir_parity_err : 1; uint64_t fir_parity_err_dup : 1; uint64_t spare11 : 1; uint64_t bce_error : 1; uint64_t sram_scrub_err : 1; uint64_t sram_ce : 1; uint64_t sram_ue : 1; uint64_t ppe_debug_trigger : 1; uint64_t ppe_halted : 1; uint64_t ppe_watchdog : 1; uint64_t ppe_breakpoint_error : 1; uint64_t ppe_progress_error : 1; uint64_t ppe_external_error : 1; uint64_t ppe_internal_error : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_lfir_and_t; typedef union cme_scom_lfir_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ppe_internal_error : 1; uint64_t ppe_external_error : 1; uint64_t ppe_progress_error : 1; uint64_t ppe_breakpoint_error : 1; uint64_t ppe_watchdog : 1; uint64_t ppe_halted : 1; uint64_t ppe_debug_trigger : 1; uint64_t sram_ue : 1; uint64_t sram_ce : 1; uint64_t sram_scrub_err : 1; uint64_t bce_error : 1; uint64_t spare11 : 1; uint64_t fir_parity_err_dup : 1; uint64_t fir_parity_err : 1; uint64_t reserved1 : 50; #else uint64_t reserved1 : 50; uint64_t fir_parity_err : 1; uint64_t fir_parity_err_dup : 1; uint64_t spare11 : 1; uint64_t bce_error : 1; uint64_t sram_scrub_err : 1; uint64_t sram_ce : 1; uint64_t sram_ue : 1; uint64_t ppe_debug_trigger : 1; uint64_t ppe_halted : 1; uint64_t ppe_watchdog : 1; uint64_t ppe_breakpoint_error : 1; uint64_t ppe_progress_error : 1; uint64_t ppe_external_error : 1; uint64_t ppe_internal_error : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_lfir_or_t; typedef union cme_scom_lfirmask { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_mask : 18; uint64_t reserved1 : 46; #else uint64_t reserved1 : 46; uint64_t fir_mask : 18; #endif // _BIG_ENDIAN } fields; } cme_scom_lfirmask_t; typedef union cme_scom_lfirmask_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_mask : 18; uint64_t reserved1 : 46; #else uint64_t reserved1 : 46; uint64_t fir_mask : 18; #endif // _BIG_ENDIAN } fields; } cme_scom_lfirmask_and_t; typedef union cme_scom_lfirmask_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_mask : 18; uint64_t reserved1 : 46; #else uint64_t reserved1 : 46; uint64_t fir_mask : 18; #endif // _BIG_ENDIAN } fields; } cme_scom_lfirmask_or_t; typedef union cme_scom_lfiract0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_action0 : 18; uint64_t reserved1 : 46; #else uint64_t reserved1 : 46; uint64_t fir_action0 : 18; #endif // _BIG_ENDIAN } fields; } cme_scom_lfiract0_t; typedef union cme_scom_lfiract1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_action1 : 18; uint64_t reserved1 : 46; #else uint64_t reserved1 : 46; uint64_t fir_action1 : 18; #endif // _BIG_ENDIAN } fields; } cme_scom_lfiract1_t; typedef union cme_scom_cscr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sram_access_mode : 1; uint64_t sram_scrub_enable : 1; uint64_t ecc_correct_dis : 1; uint64_t ecc_detect_dis : 1; uint64_t ecc_inject_type : 1; uint64_t ecc_inject_err : 1; uint64_t spare_6_7 : 2; uint64_t reserved1 : 39; uint64_t sram_scrub_index : 13; uint64_t reserved2 : 4; #else uint64_t reserved2 : 4; uint64_t sram_scrub_index : 13; uint64_t reserved1 : 39; uint64_t spare_6_7 : 2; uint64_t ecc_inject_err : 1; uint64_t ecc_inject_type : 1; uint64_t ecc_detect_dis : 1; uint64_t ecc_correct_dis : 1; uint64_t sram_scrub_enable : 1; uint64_t sram_access_mode : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_cscr_t; typedef union cme_scom_cscr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sram_access_mode : 1; uint64_t sram_scrub_enable : 1; uint64_t ecc_correct_dis : 1; uint64_t ecc_detect_dis : 1; uint64_t ecc_inject_type : 1; uint64_t ecc_inject_err : 1; uint64_t spare_6_7 : 2; uint64_t reserved1 : 39; uint64_t sram_scrub_index : 13; uint64_t reserved2 : 4; #else uint64_t reserved2 : 4; uint64_t sram_scrub_index : 13; uint64_t reserved1 : 39; uint64_t spare_6_7 : 2; uint64_t ecc_inject_err : 1; uint64_t ecc_inject_type : 1; uint64_t ecc_detect_dis : 1; uint64_t ecc_correct_dis : 1; uint64_t sram_scrub_enable : 1; uint64_t sram_access_mode : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_cscr_clr_t; typedef union cme_scom_cscr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sram_access_mode : 1; uint64_t sram_scrub_enable : 1; uint64_t ecc_correct_dis : 1; uint64_t ecc_detect_dis : 1; uint64_t ecc_inject_type : 1; uint64_t ecc_inject_err : 1; uint64_t spare_6_7 : 2; uint64_t reserved1 : 39; uint64_t sram_scrub_index : 13; uint64_t reserved2 : 4; #else uint64_t reserved2 : 4; uint64_t sram_scrub_index : 13; uint64_t reserved1 : 39; uint64_t spare_6_7 : 2; uint64_t ecc_inject_err : 1; uint64_t ecc_inject_type : 1; uint64_t ecc_detect_dis : 1; uint64_t ecc_correct_dis : 1; uint64_t sram_scrub_enable : 1; uint64_t sram_access_mode : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_cscr_or_t; typedef union cme_scom_csar { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 3; uint64_t reserved2 : 13; uint64_t sram_address : 13; uint64_t reserved3 : 35; #else uint64_t reserved3 : 35; uint64_t sram_address : 13; uint64_t reserved2 : 13; uint64_t reserved1 : 3; #endif // _BIG_ENDIAN } fields; } cme_scom_csar_t; typedef union cme_scom_csdr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sram_data : 64; #else uint64_t sram_data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_csdr_t; typedef union cme_scom_bcecsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t busy : 1; uint64_t error : 1; uint64_t start : 1; uint64_t stop : 1; uint64_t rnw : 1; uint64_t barsel : 1; uint64_t priority : 1; uint64_t inject_err : 1; uint64_t reserved1 : 5; uint64_t type : 3; uint64_t reserved2 : 1; uint64_t num_blocks : 11; uint64_t sbase : 12; uint64_t reserved3 : 2; uint64_t mbase : 22; #else uint64_t mbase : 22; uint64_t reserved3 : 2; uint64_t sbase : 12; uint64_t num_blocks : 11; uint64_t reserved2 : 1; uint64_t type : 3; uint64_t reserved1 : 5; uint64_t inject_err : 1; uint64_t priority : 1; uint64_t barsel : 1; uint64_t rnw : 1; uint64_t stop : 1; uint64_t start : 1; uint64_t error : 1; uint64_t busy : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_bcecsr_t; typedef union cme_scom_bcebar0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 8; uint64_t base : 36; uint64_t reserved2 : 13; uint64_t rd_scope : 2; uint64_t wr_scope : 1; uint64_t vg_target_sel : 1; uint64_t size : 3; #else uint64_t size : 3; uint64_t vg_target_sel : 1; uint64_t wr_scope : 1; uint64_t rd_scope : 2; uint64_t reserved2 : 13; uint64_t base : 36; uint64_t reserved1 : 8; #endif // _BIG_ENDIAN } fields; } cme_scom_bcebar0_t; typedef union cme_scom_bcebar1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 8; uint64_t base : 36; uint64_t reserved2 : 13; uint64_t rd_scope : 2; uint64_t wr_scope : 1; uint64_t vg_target_sel : 1; uint64_t size : 3; #else uint64_t size : 3; uint64_t vg_target_sel : 1; uint64_t wr_scope : 1; uint64_t rd_scope : 2; uint64_t reserved2 : 13; uint64_t base : 36; uint64_t reserved1 : 8; #endif // _BIG_ENDIAN } fields; } cme_scom_bcebar1_t; typedef union cme_scom_qfmr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t timebase : 32; uint64_t cycles : 32; #else uint64_t cycles : 32; uint64_t timebase : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_qfmr_t; typedef union cme_scom_afsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t inst_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t avg_cycle_sample : 20; uint64_t reserved2 : 11; uint64_t sample_valid : 1; #else uint64_t sample_valid : 1; uint64_t reserved2 : 11; uint64_t avg_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t inst_cycle_sample : 20; #endif // _BIG_ENDIAN } fields; } cme_scom_afsr_t; typedef union cme_scom_aftr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t max_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t min_cycle_sample : 20; uint64_t reserved2 : 12; #else uint64_t reserved2 : 12; uint64_t min_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t max_cycle_sample : 20; #endif // _BIG_ENDIAN } fields; } cme_scom_aftr_t; typedef union cme_scom_vtsr0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_extreme_droop_ctr : 16; uint64_t vdm_large_droop_ctr : 24; uint64_t vdm_small_droop_ctr : 24; #else uint64_t vdm_small_droop_ctr : 24; uint64_t vdm_large_droop_ctr : 24; uint64_t vdm_extreme_droop_ctr : 16; #endif // _BIG_ENDIAN } fields; } cme_scom_vtsr0_t; typedef union cme_scom_vtsr1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 16; uint64_t vdm_no_droop_ctr : 24; uint64_t vdm_overvolt_ctr : 24; #else uint64_t vdm_overvolt_ctr : 24; uint64_t vdm_no_droop_ctr : 24; uint64_t reserved1 : 16; #endif // _BIG_ENDIAN } fields; } cme_scom_vtsr1_t; typedef union cme_scom_vdsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t instant_vdm_control_summary : 4; uint64_t instant_cache_vdm_data : 4; uint64_t instant_core0_vdm_data : 4; uint64_t instant_core1_vdm_data : 4; uint64_t instant_core2_vdm_data : 4; uint64_t instant_core3_vdm_data : 4; uint64_t reserved1 : 8; uint64_t sticky_vdm_control_summary : 4; uint64_t sticky_cache_vdm_data : 4; uint64_t sticky_core0_vdm_data : 4; uint64_t sticky_core1_vdm_data : 4; uint64_t sticky_core2_vdm_data : 4; uint64_t sticky_core3_vdm_data : 4; uint64_t reserved2 : 8; #else uint64_t reserved2 : 8; uint64_t sticky_core3_vdm_data : 4; uint64_t sticky_core2_vdm_data : 4; uint64_t sticky_core1_vdm_data : 4; uint64_t sticky_core0_vdm_data : 4; uint64_t sticky_cache_vdm_data : 4; uint64_t sticky_vdm_control_summary : 4; uint64_t reserved1 : 8; uint64_t instant_core3_vdm_data : 4; uint64_t instant_core2_vdm_data : 4; uint64_t instant_core1_vdm_data : 4; uint64_t instant_core0_vdm_data : 4; uint64_t instant_cache_vdm_data : 4; uint64_t instant_vdm_control_summary : 4; #endif // _BIG_ENDIAN } fields; } cme_scom_vdsr_t; typedef union cme_scom_eiir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t debugger : 1; uint64_t debug_trigger : 1; uint64_t reserved_2_81 : 7; uint64_t bce_timeout : 1; uint64_t reserved_10_112 : 2; uint64_t pc_intr_pending_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t reserved_18_193 : 2; uint64_t pc_pm_state_active_c0 : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t l2_purge_done : 1; uint64_t ncu_purge_done : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t reserved4 : 38; #else uint64_t reserved4 : 38; uint64_t chtm_purge_done_c1 : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t ncu_purge_done : 1; uint64_t l2_purge_done : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t reserved_18_193 : 2; uint64_t reg_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t reserved_10_112 : 2; uint64_t bce_timeout : 1; uint64_t reserved_2_81 : 7; uint64_t debug_trigger : 1; uint64_t debugger : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_eiir_t; typedef union cme_scom_fwmr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pmcr_override_en : 1; uint64_t pscr_override_en : 1; uint64_t pmsr_override_en : 1; uint64_t bcecsr_override_en : 1; uint64_t reserved_41 : 1; uint64_t vdm_lcl_sample_en : 1; uint64_t freq_lcl_sample_en : 1; uint64_t lock_pcb_on_err : 1; uint64_t queued_wr_en : 1; uint64_t queued_rd_en : 1; uint64_t mask_purge_interface : 1; uint64_t spare_11_15 : 5; uint64_t stop_override_mode : 1; uint64_t stop_active_mask : 1; uint64_t auto_stop1_disable : 1; uint64_t stop1_active_enable : 1; uint64_t fence_eisr : 1; uint64_t spare_21_23 : 3; uint64_t avg_freq_tsel : 4; uint64_t reserved2 : 4; uint64_t cme_lcl_lcr : 32; #else uint64_t cme_lcl_lcr : 32; uint64_t reserved2 : 4; uint64_t avg_freq_tsel : 4; uint64_t spare_21_23 : 3; uint64_t fence_eisr : 1; uint64_t stop1_active_enable : 1; uint64_t auto_stop1_disable : 1; uint64_t stop_active_mask : 1; uint64_t stop_override_mode : 1; uint64_t spare_11_15 : 5; uint64_t mask_purge_interface : 1; uint64_t queued_rd_en : 1; uint64_t queued_wr_en : 1; uint64_t lock_pcb_on_err : 1; uint64_t freq_lcl_sample_en : 1; uint64_t vdm_lcl_sample_en : 1; uint64_t reserved_41 : 1; uint64_t bcecsr_override_en : 1; uint64_t pmsr_override_en : 1; uint64_t pscr_override_en : 1; uint64_t pmcr_override_en : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_fwmr_t; typedef union cme_scom_fwmr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pmcr_override_en : 1; uint64_t pscr_override_en : 1; uint64_t pmsr_override_en : 1; uint64_t bcecsr_override_en : 1; uint64_t reserved_41 : 1; uint64_t vdm_lcl_sample_en : 1; uint64_t freq_lcl_sample_en : 1; uint64_t lock_pcb_on_err : 1; uint64_t queued_wr_en : 1; uint64_t queued_rd_en : 1; uint64_t mask_purge_interface : 1; uint64_t spare_11_15 : 5; uint64_t stop_override_mode : 1; uint64_t stop_active_mask : 1; uint64_t auto_stop1_disable : 1; uint64_t stop1_active_enable : 1; uint64_t fence_eisr : 1; uint64_t spare_21_23 : 3; uint64_t avg_freq_tsel : 4; uint64_t reserved2 : 4; uint64_t cme_lcl_lcr : 32; #else uint64_t cme_lcl_lcr : 32; uint64_t reserved2 : 4; uint64_t avg_freq_tsel : 4; uint64_t spare_21_23 : 3; uint64_t fence_eisr : 1; uint64_t stop1_active_enable : 1; uint64_t auto_stop1_disable : 1; uint64_t stop_active_mask : 1; uint64_t stop_override_mode : 1; uint64_t spare_11_15 : 5; uint64_t mask_purge_interface : 1; uint64_t queued_rd_en : 1; uint64_t queued_wr_en : 1; uint64_t lock_pcb_on_err : 1; uint64_t freq_lcl_sample_en : 1; uint64_t vdm_lcl_sample_en : 1; uint64_t reserved_41 : 1; uint64_t bcecsr_override_en : 1; uint64_t pmsr_override_en : 1; uint64_t pscr_override_en : 1; uint64_t pmcr_override_en : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_fwmr_clr_t; typedef union cme_scom_fwmr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pmcr_override_en : 1; uint64_t pscr_override_en : 1; uint64_t pmsr_override_en : 1; uint64_t bcecsr_override_en : 1; uint64_t reserved_41 : 1; uint64_t vdm_lcl_sample_en : 1; uint64_t freq_lcl_sample_en : 1; uint64_t lock_pcb_on_err : 1; uint64_t queued_wr_en : 1; uint64_t queued_rd_en : 1; uint64_t mask_purge_interface : 1; uint64_t spare_11_15 : 5; uint64_t stop_override_mode : 1; uint64_t stop_active_mask : 1; uint64_t auto_stop1_disable : 1; uint64_t stop1_active_enable : 1; uint64_t fence_eisr : 1; uint64_t spare_21_23 : 3; uint64_t avg_freq_tsel : 4; uint64_t reserved2 : 4; uint64_t cme_lcl_lcr : 32; #else uint64_t cme_lcl_lcr : 32; uint64_t reserved2 : 4; uint64_t avg_freq_tsel : 4; uint64_t spare_21_23 : 3; uint64_t fence_eisr : 1; uint64_t stop1_active_enable : 1; uint64_t auto_stop1_disable : 1; uint64_t stop_active_mask : 1; uint64_t stop_override_mode : 1; uint64_t spare_11_15 : 5; uint64_t mask_purge_interface : 1; uint64_t queued_rd_en : 1; uint64_t queued_wr_en : 1; uint64_t lock_pcb_on_err : 1; uint64_t freq_lcl_sample_en : 1; uint64_t vdm_lcl_sample_en : 1; uint64_t reserved_41 : 1; uint64_t bcecsr_override_en : 1; uint64_t pmsr_override_en : 1; uint64_t pscr_override_en : 1; uint64_t pmcr_override_en : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_fwmr_or_t; typedef union cme_scom_sicr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 40; uint64_t reserved1 : 24; #else uint64_t reserved1 : 24; uint64_t data : 40; #endif // _BIG_ENDIAN } fields; } cme_scom_sicr_t; typedef union cme_scom_sicr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 40; uint64_t reserved1 : 24; #else uint64_t reserved1 : 24; uint64_t data : 40; #endif // _BIG_ENDIAN } fields; } cme_scom_sicr_clr_t; typedef union cme_scom_sicr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 40; uint64_t reserved1 : 24; #else uint64_t reserved1 : 24; uint64_t data : 40; #endif // _BIG_ENDIAN } fields; } cme_scom_sicr_or_t; typedef union cme_scom_flags { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_flags_t; typedef union cme_scom_flags_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_flags_clr_t; typedef union cme_scom_flags_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_flags_or_t; typedef union cme_scom_srtch0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_srtch0_t; typedef union cme_scom_srtch1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_srtch1_t; typedef union cme_scom_eisr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t data : 44; #endif // _BIG_ENDIAN } fields; } cme_scom_eisr_t; typedef union cme_scom_eimr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t data : 44; #endif // _BIG_ENDIAN } fields; } cme_scom_eimr_t; typedef union cme_scom_eipr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t data : 44; #endif // _BIG_ENDIAN } fields; } cme_scom_eipr_t; typedef union cme_scom_eitr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t data : 44; #endif // _BIG_ENDIAN } fields; } cme_scom_eitr_t; typedef union cme_scom_eistr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t data : 44; #endif // _BIG_ENDIAN } fields; } cme_scom_eistr_t; typedef union cme_scom_einr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t data : 44; #endif // _BIG_ENDIAN } fields; } cme_scom_einr_t; typedef union cme_scom_sisr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_sisr_t; typedef union cme_scom_icrr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_icrr_t; typedef union cme_scom_xixcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xcr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t xcr : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_xixcr_t; typedef union cme_scom_xiramra { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xcr : 32; uint64_t sprg0 : 32; #else uint64_t sprg0 : 32; uint64_t xcr : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_xiramra_t; typedef union cme_scom_xiramga { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ir : 32; uint64_t sprg0 : 32; #else uint64_t sprg0 : 32; uint64_t ir : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_xiramga_t; typedef union cme_scom_xiramdbg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xsr : 32; uint64_t sprg0 : 32; #else uint64_t sprg0 : 32; uint64_t xsr : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_xiramdbg_t; typedef union cme_scom_xiramedr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ir : 32; uint64_t edr : 32; #else uint64_t edr : 32; uint64_t ir : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_xiramedr_t; typedef union cme_scom_xidbgpro { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xsr : 32; uint64_t iar : 32; #else uint64_t iar : 32; uint64_t xsr : 32; #endif // _BIG_ENDIAN } fields; } cme_scom_xidbgpro_t; typedef union cme_scom_xisib { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sib_info : 64; #else uint64_t sib_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xisib_t; typedef union cme_scom_ximem { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t memory_info : 64; #else uint64_t memory_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_ximem_t; typedef union cme_scom_cmexisgb { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t storegatherbuffer_info : 64; #else uint64_t storegatherbuffer_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_cmexisgb_t; typedef union cme_scom_xiicac { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t icache_info : 64; #else uint64_t icache_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xiicac_t; typedef union cme_scom_xipcbq0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbqn_info : 64; #else uint64_t pcbqn_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xipcbq0_t; typedef union cme_scom_xipcbq1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbqn_info : 64; #else uint64_t pcbqn_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xipcbq1_t; typedef union cme_scom_xipcbmd0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_data : 64; #else uint64_t pcbm_data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xipcbmd0_t; typedef union cme_scom_xipcbmd1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_data : 64; #else uint64_t pcbm_data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xipcbmd1_t; typedef union cme_scom_xipcbmi0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_info : 64; #else uint64_t pcbm_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xipcbmi0_t; typedef union cme_scom_xipcbmi1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_info : 64; #else uint64_t pcbm_info : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_xipcbmi1_t; typedef union cme_scom_pmsrs0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_pmsrs0_t; typedef union cme_scom_pmsrs1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_pmsrs1_t; typedef union cme_scom_pmcrs0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_pmcrs0_t; typedef union cme_scom_pmcrs1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_scom_pmcrs1_t; typedef union cme_scom_pscrs00 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs00_t; typedef union cme_scom_pscrs10 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs10_t; typedef union cme_scom_pscrs01 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs01_t; typedef union cme_scom_pscrs11 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs11_t; typedef union cme_scom_pscrs02 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs02_t; typedef union cme_scom_pscrs12 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs12_t; typedef union cme_scom_pscrs03 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs03_t; typedef union cme_scom_pscrs13 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t spare_0 : 1; uint64_t sd_a_n : 1; uint64_t esl_a_n : 1; uint64_t ec_a_n : 1; uint64_t psll_a_n : 4; uint64_t hyp_virt_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t hmi_exit_enable : 1; uint64_t tr_a_n : 2; uint64_t mtl_a_n : 4; uint64_t rl_a_n : 4; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t rl_a_n : 4; uint64_t mtl_a_n : 4; uint64_t tr_a_n : 2; uint64_t hmi_exit_enable : 1; uint64_t dec_exit_enable : 1; uint64_t ext_exit_enable : 1; uint64_t hyp_db_exit_enable : 1; uint64_t reserved_enable : 1; uint64_t hyp_virt_exit_enable : 1; uint64_t psll_a_n : 4; uint64_t ec_a_n : 1; uint64_t esl_a_n : 1; uint64_t sd_a_n : 1; uint64_t spare_0 : 1; #endif // _BIG_ENDIAN } fields; } cme_scom_pscrs13_t; typedef union cme_lcl_eisr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t debugger : 1; uint64_t debug_trigger : 1; uint64_t quad_checkstop : 1; uint64_t pvref_fail : 1; uint64_t occ_heartbeat_lost : 1; uint64_t core_checkstop : 1; uint64_t spare_6_7 : 2; uint64_t bce_busy_high : 1; uint64_t bce_timeout : 1; uint64_t doorbell3_c0 : 1; uint64_t doorbell3_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t doorbell2_c0 : 1; uint64_t doorbell2_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t l2_purge_done : 1; uint64_t ncu_purge_done : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t bce_busy_low : 1; uint64_t spare_27_28 : 2; uint64_t comm_recvd : 1; uint64_t comm_send_ack : 1; uint64_t comm_send_nack : 1; uint64_t spare_32_33 : 2; uint64_t pmcr_update_c0 : 1; uint64_t pmcr_update_c1 : 1; uint64_t doorbell0_c0 : 1; uint64_t doorbell0_c1 : 1; uint64_t spare_38_39 : 2; uint64_t doorbell1_c0 : 1; uint64_t doorbell1_c1 : 1; uint64_t reserved_42_431 : 2; uint64_t reserved2 : 20; #else uint64_t reserved2 : 20; uint64_t reserved_42_431 : 2; uint64_t doorbell1_c1 : 1; uint64_t doorbell1_c0 : 1; uint64_t spare_38_39 : 2; uint64_t doorbell0_c1 : 1; uint64_t doorbell0_c0 : 1; uint64_t pmcr_update_c1 : 1; uint64_t pmcr_update_c0 : 1; uint64_t spare_32_33 : 2; uint64_t comm_send_nack : 1; uint64_t comm_send_ack : 1; uint64_t comm_recvd : 1; uint64_t spare_27_28 : 2; uint64_t bce_busy_low : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t ncu_purge_done : 1; uint64_t l2_purge_done : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t doorbell2_c1 : 1; uint64_t doorbell2_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t doorbell3_c1 : 1; uint64_t doorbell3_c0 : 1; uint64_t bce_timeout : 1; uint64_t bce_busy_high : 1; uint64_t spare_6_7 : 2; uint64_t core_checkstop : 1; uint64_t occ_heartbeat_lost : 1; uint64_t pvref_fail : 1; uint64_t quad_checkstop : 1; uint64_t debug_trigger : 1; uint64_t debugger : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_eisr_t; typedef union cme_lcl_eisr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t debugger : 1; uint64_t debug_trigger : 1; uint64_t quad_checkstop : 1; uint64_t pvref_fail : 1; uint64_t occ_heartbeat_lost : 1; uint64_t core_checkstop : 1; uint64_t spare_6_7 : 2; uint64_t bce_busy_high : 1; uint64_t bce_timeout : 1; uint64_t doorbell3_c0 : 1; uint64_t doorbell3_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t doorbell2_c0 : 1; uint64_t doorbell2_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t l2_purge_done : 1; uint64_t ncu_purge_done : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t bce_busy_low : 1; uint64_t spare_27_28 : 2; uint64_t comm_recvd : 1; uint64_t comm_send_ack : 1; uint64_t comm_send_nack : 1; uint64_t spare_32_33 : 2; uint64_t pmcr_update_c0 : 1; uint64_t pmcr_update_c1 : 1; uint64_t doorbell0_c0 : 1; uint64_t doorbell0_c1 : 1; uint64_t spare_38_39 : 2; uint64_t doorbell1_c0 : 1; uint64_t doorbell1_c1 : 1; uint64_t reserved_42_431 : 2; uint64_t reserved2 : 20; #else uint64_t reserved2 : 20; uint64_t reserved_42_431 : 2; uint64_t doorbell1_c1 : 1; uint64_t doorbell1_c0 : 1; uint64_t spare_38_39 : 2; uint64_t doorbell0_c1 : 1; uint64_t doorbell0_c0 : 1; uint64_t pmcr_update_c1 : 1; uint64_t pmcr_update_c0 : 1; uint64_t spare_32_33 : 2; uint64_t comm_send_nack : 1; uint64_t comm_send_ack : 1; uint64_t comm_recvd : 1; uint64_t spare_27_28 : 2; uint64_t bce_busy_low : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t ncu_purge_done : 1; uint64_t l2_purge_done : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t doorbell2_c1 : 1; uint64_t doorbell2_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t doorbell3_c1 : 1; uint64_t doorbell3_c0 : 1; uint64_t bce_timeout : 1; uint64_t bce_busy_high : 1; uint64_t spare_6_7 : 2; uint64_t core_checkstop : 1; uint64_t occ_heartbeat_lost : 1; uint64_t pvref_fail : 1; uint64_t quad_checkstop : 1; uint64_t debug_trigger : 1; uint64_t debugger : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_eisr_or_t; typedef union cme_lcl_eisr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t debugger : 1; uint64_t debug_trigger : 1; uint64_t quad_checkstop : 1; uint64_t pvref_fail : 1; uint64_t occ_heartbeat_lost : 1; uint64_t core_checkstop : 1; uint64_t spare_6_7 : 2; uint64_t bce_busy_high : 1; uint64_t bce_timeout : 1; uint64_t doorbell3_c0 : 1; uint64_t doorbell3_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t doorbell2_c0 : 1; uint64_t doorbell2_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t l2_purge_done : 1; uint64_t ncu_purge_done : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t bce_busy_low : 1; uint64_t spare_27_28 : 2; uint64_t comm_recvd : 1; uint64_t comm_send_ack : 1; uint64_t comm_send_nack : 1; uint64_t spare_32_33 : 2; uint64_t pmcr_update_c0 : 1; uint64_t pmcr_update_c1 : 1; uint64_t doorbell0_c0 : 1; uint64_t doorbell0_c1 : 1; uint64_t spare_38_39 : 2; uint64_t doorbell1_c0 : 1; uint64_t doorbell1_c1 : 1; uint64_t reserved_42_431 : 2; uint64_t reserved2 : 20; #else uint64_t reserved2 : 20; uint64_t reserved_42_431 : 2; uint64_t doorbell1_c1 : 1; uint64_t doorbell1_c0 : 1; uint64_t spare_38_39 : 2; uint64_t doorbell0_c1 : 1; uint64_t doorbell0_c0 : 1; uint64_t pmcr_update_c1 : 1; uint64_t pmcr_update_c0 : 1; uint64_t spare_32_33 : 2; uint64_t comm_send_nack : 1; uint64_t comm_send_ack : 1; uint64_t comm_recvd : 1; uint64_t spare_27_28 : 2; uint64_t bce_busy_low : 1; uint64_t chtm_purge_done_c1 : 1; uint64_t chtm_purge_done_c0 : 1; uint64_t ncu_purge_done : 1; uint64_t l2_purge_done : 1; uint64_t pc_pm_state_active_c1 : 1; uint64_t pc_pm_state_active_c0 : 1; uint64_t doorbell2_c1 : 1; uint64_t doorbell2_c0 : 1; uint64_t reg_wakeup_c1 : 1; uint64_t reg_wakeup_c0 : 1; uint64_t special_wakeup_c1 : 1; uint64_t special_wakeup_c0 : 1; uint64_t pc_intr_pending_c1 : 1; uint64_t pc_intr_pending_c0 : 1; uint64_t doorbell3_c1 : 1; uint64_t doorbell3_c0 : 1; uint64_t bce_timeout : 1; uint64_t bce_busy_high : 1; uint64_t spare_6_7 : 2; uint64_t core_checkstop : 1; uint64_t occ_heartbeat_lost : 1; uint64_t pvref_fail : 1; uint64_t quad_checkstop : 1; uint64_t debug_trigger : 1; uint64_t debugger : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_eisr_clr_t; typedef union cme_lcl_eimr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_mask : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_mask : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eimr_t; typedef union cme_lcl_eimr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_mask : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_mask : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eimr_or_t; typedef union cme_lcl_eimr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_mask : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_mask : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eimr_clr_t; typedef union cme_lcl_eipr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_polarity : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_polarity : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eipr_t; typedef union cme_lcl_eipr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_polarity : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_polarity : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eipr_or_t; typedef union cme_lcl_eipr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_polarity : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_polarity : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eipr_clr_t; typedef union cme_lcl_eitr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_type : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_type : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eitr_t; typedef union cme_lcl_eitr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_type : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_type : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eitr_or_t; typedef union cme_lcl_eitr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_type : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_type : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eitr_clr_t; typedef union cme_lcl_eistr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_status : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_status : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_eistr_t; typedef union cme_lcl_einr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t interrupt_input : 44; uint64_t reserved1 : 20; #else uint64_t reserved1 : 20; uint64_t interrupt_input : 44; #endif // _BIG_ENDIAN } fields; } cme_lcl_einr_t; typedef union cme_lcl_tsel { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fit_sel : 4; uint64_t watchdog_sel : 4; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t watchdog_sel : 4; uint64_t fit_sel : 4; #endif // _BIG_ENDIAN } fields; } cme_lcl_tsel_t; typedef union cme_lcl_dbg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t en_dbg : 1; uint64_t halt_on_xstop : 1; uint64_t halt_on_trig : 1; uint64_t en_risctrace : 1; uint64_t en_intr_addr : 1; uint64_t en_trace_extra : 1; uint64_t en_trace_stall : 1; uint64_t en_wait_cycles : 1; uint64_t en_full_speed : 1; uint64_t en_wide_trace : 1; uint64_t reserved_10_11 : 2; uint64_t sync_timer_sel : 4; uint64_t fir_trigger : 1; uint64_t mib_gpio : 3; uint64_t halt_input : 1; uint64_t reserved1 : 43; #else uint64_t reserved1 : 43; uint64_t halt_input : 1; uint64_t mib_gpio : 3; uint64_t fir_trigger : 1; uint64_t sync_timer_sel : 4; uint64_t reserved_10_11 : 2; uint64_t en_wide_trace : 1; uint64_t en_full_speed : 1; uint64_t en_wait_cycles : 1; uint64_t en_trace_stall : 1; uint64_t en_trace_extra : 1; uint64_t en_intr_addr : 1; uint64_t en_risctrace : 1; uint64_t halt_on_trig : 1; uint64_t halt_on_xstop : 1; uint64_t en_dbg : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_dbg_t; typedef union cme_lcl_dbg_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t en_dbg : 1; uint64_t halt_on_xstop : 1; uint64_t halt_on_trig : 1; uint64_t en_risctrace : 1; uint64_t en_intr_addr : 1; uint64_t en_trace_extra : 1; uint64_t en_trace_stall : 1; uint64_t en_wait_cycles : 1; uint64_t en_full_speed : 1; uint64_t en_wide_trace : 1; uint64_t reserved_10_11 : 2; uint64_t sync_timer_sel : 4; uint64_t fir_trigger : 1; uint64_t mib_gpio : 3; uint64_t halt_input : 1; uint64_t reserved1 : 43; #else uint64_t reserved1 : 43; uint64_t halt_input : 1; uint64_t mib_gpio : 3; uint64_t fir_trigger : 1; uint64_t sync_timer_sel : 4; uint64_t reserved_10_11 : 2; uint64_t en_wide_trace : 1; uint64_t en_full_speed : 1; uint64_t en_wait_cycles : 1; uint64_t en_trace_stall : 1; uint64_t en_trace_extra : 1; uint64_t en_intr_addr : 1; uint64_t en_risctrace : 1; uint64_t halt_on_trig : 1; uint64_t halt_on_xstop : 1; uint64_t en_dbg : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_dbg_or_t; typedef union cme_lcl_dbg_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t en_dbg : 1; uint64_t halt_on_xstop : 1; uint64_t halt_on_trig : 1; uint64_t en_risctrace : 1; uint64_t en_intr_addr : 1; uint64_t en_trace_extra : 1; uint64_t en_trace_stall : 1; uint64_t en_wait_cycles : 1; uint64_t en_full_speed : 1; uint64_t en_wide_trace : 1; uint64_t reserved_10_11 : 2; uint64_t sync_timer_sel : 4; uint64_t fir_trigger : 1; uint64_t mib_gpio : 3; uint64_t halt_input : 1; uint64_t reserved1 : 43; #else uint64_t reserved1 : 43; uint64_t halt_input : 1; uint64_t mib_gpio : 3; uint64_t fir_trigger : 1; uint64_t sync_timer_sel : 4; uint64_t reserved_10_11 : 2; uint64_t en_wide_trace : 1; uint64_t en_full_speed : 1; uint64_t en_wait_cycles : 1; uint64_t en_trace_stall : 1; uint64_t en_trace_extra : 1; uint64_t en_intr_addr : 1; uint64_t en_risctrace : 1; uint64_t halt_on_trig : 1; uint64_t halt_on_xstop : 1; uint64_t en_dbg : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_dbg_clr_t; typedef union cme_lcl_tbr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t timebase : 32; uint64_t cycles : 32; #else uint64_t cycles : 32; uint64_t timebase : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_tbr_t; typedef union cme_lcl_afsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t inst_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t avg_cycle_sample : 20; uint64_t reserved2 : 11; uint64_t sample_valid : 1; #else uint64_t sample_valid : 1; uint64_t reserved2 : 11; uint64_t avg_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t inst_cycle_sample : 20; #endif // _BIG_ENDIAN } fields; } cme_lcl_afsr_t; typedef union cme_lcl_aftr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t max_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t min_cycle_sample : 20; uint64_t reserved2 : 12; #else uint64_t reserved2 : 12; uint64_t min_cycle_sample : 20; uint64_t reserved1 : 12; uint64_t max_cycle_sample : 20; #endif // _BIG_ENDIAN } fields; } cme_lcl_aftr_t; typedef union cme_lcl_lmcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t scom_fwmr_data : 32; uint64_t reset_imprecise_qerr : 1; uint64_t set_ecc_inject_err : 1; uint64_t c0_halted_stop_override_disable : 1; uint64_t c1_halted_stop_override_disable : 1; uint64_t fence_eisr : 1; uint64_t reserved1 : 27; #else uint64_t reserved1 : 27; uint64_t fence_eisr : 1; uint64_t c1_halted_stop_override_disable : 1; uint64_t c0_halted_stop_override_disable : 1; uint64_t set_ecc_inject_err : 1; uint64_t reset_imprecise_qerr : 1; uint64_t scom_fwmr_data : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_lmcr_t; typedef union cme_lcl_bcecsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t bce_data : 64; #else uint64_t bce_data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_bcecsr_t; typedef union cme_lcl_pmsrs0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_pmsrs0_t; typedef union cme_lcl_pmsrs1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_pmsrs1_t; typedef union cme_lcl_pmcrs0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_pmcrs0_t; typedef union cme_lcl_pmcrs1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_pmcrs1_t; typedef union cme_lcl_pecesr0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pece_cn_t0 : 6; uint64_t reserved1 : 2; uint64_t pece_cn_t1 : 6; uint64_t reserved2 : 2; uint64_t pece_cn_t2 : 6; uint64_t reserved3 : 2; uint64_t pece_cn_t3 : 6; uint64_t reserved4 : 2; uint64_t use_pece : 4; uint64_t pc_fused_core_mode : 1; uint64_t reserved5 : 27; #else uint64_t reserved5 : 27; uint64_t pc_fused_core_mode : 1; uint64_t use_pece : 4; uint64_t reserved4 : 2; uint64_t pece_cn_t3 : 6; uint64_t reserved3 : 2; uint64_t pece_cn_t2 : 6; uint64_t reserved2 : 2; uint64_t pece_cn_t1 : 6; uint64_t reserved1 : 2; uint64_t pece_cn_t0 : 6; #endif // _BIG_ENDIAN } fields; } cme_lcl_pecesr0_t; typedef union cme_lcl_pecesr1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pece_cn_t0 : 6; uint64_t reserved1 : 2; uint64_t pece_cn_t1 : 6; uint64_t reserved2 : 2; uint64_t pece_cn_t2 : 6; uint64_t reserved3 : 2; uint64_t pece_cn_t3 : 6; uint64_t reserved4 : 2; uint64_t use_pece : 4; uint64_t pc_fused_core_mode : 1; uint64_t reserved5 : 27; #else uint64_t reserved5 : 27; uint64_t pc_fused_core_mode : 1; uint64_t use_pece : 4; uint64_t reserved4 : 2; uint64_t pece_cn_t3 : 6; uint64_t reserved3 : 2; uint64_t pece_cn_t2 : 6; uint64_t reserved2 : 2; uint64_t pece_cn_t1 : 6; uint64_t reserved1 : 2; uint64_t pece_cn_t0 : 6; #endif // _BIG_ENDIAN } fields; } cme_lcl_pecesr1_t; typedef union cme_lcl_pscrs00 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs00_t; typedef union cme_lcl_pscrs10 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs10_t; typedef union cme_lcl_pscrs20 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs20_t; typedef union cme_lcl_pscrs30 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs30_t; typedef union cme_lcl_pscrs01 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs01_t; typedef union cme_lcl_pscrs11 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs11_t; typedef union cme_lcl_pscrs21 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs21_t; typedef union cme_lcl_pscrs31 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 24; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t data : 24; #endif // _BIG_ENDIAN } fields; } cme_lcl_pscrs31_t; typedef union cme_lcl_flags { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_flags_t; typedef union cme_lcl_flags_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_flags_or_t; typedef union cme_lcl_flags_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_flags_clr_t; typedef union cme_lcl_srtch0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_srtch0_t; typedef union cme_lcl_srtch1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_srtch1_t; typedef union cme_lcl_sicr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pc_entry_ack_c0 : 1; uint64_t pc_block_interrupts_c0 : 1; uint64_t pc_wakeup_c0 : 1; uint64_t pcbmux_req_c0 : 1; uint64_t reserved_4_5 : 2; uint64_t pcc_core_intf_quiesce_c0 : 1; uint64_t l2_core_intf_quiesce_c0 : 1; uint64_t reserved_8_111 : 4; uint64_t pc_entry_ack_c1 : 1; uint64_t pc_block_interrupts_c1 : 1; uint64_t pc_wakeup_c1 : 1; uint64_t pcbmux_req_c1 : 1; uint64_t reserved_16_17 : 2; uint64_t pcc_core_intf_quiesce_c1 : 1; uint64_t l2_core_intf_quiesce_c1 : 1; uint64_t reserved_20_212 : 2; uint64_t special_wkup_done_c0 : 1; uint64_t special_wkup_done_c1 : 1; uint64_t l2_purge : 1; uint64_t l2_purge_abort : 1; uint64_t reserved263 : 1; uint64_t ncu_tlbie_quiesce : 1; uint64_t ncu_purge : 1; uint64_t ncu_purge_abort : 1; uint64_t chtm_purge_c0 : 1; uint64_t chtm_purge_c1 : 1; uint64_t hmi_request_c0 : 1; uint64_t hmi_request_c1 : 1; uint64_t ppm_spare_out_c0 : 1; uint64_t ppm_spare_out_c1 : 1; uint64_t reserved_36_394 : 4; uint64_t reserved5 : 24; #else uint64_t reserved5 : 24; uint64_t reserved_36_394 : 4; uint64_t ppm_spare_out_c1 : 1; uint64_t ppm_spare_out_c0 : 1; uint64_t hmi_request_c1 : 1; uint64_t hmi_request_c0 : 1; uint64_t chtm_purge_c1 : 1; uint64_t chtm_purge_c0 : 1; uint64_t ncu_purge_abort : 1; uint64_t ncu_purge : 1; uint64_t ncu_tlbie_quiesce : 1; uint64_t reserved263 : 1; uint64_t l2_purge_abort : 1; uint64_t l2_purge : 1; uint64_t special_wkup_done_c1 : 1; uint64_t special_wkup_done_c0 : 1; uint64_t reserved_20_212 : 2; uint64_t l2_core_intf_quiesce_c1 : 1; uint64_t pcc_core_intf_quiesce_c1 : 1; uint64_t reserved_16_17 : 2; uint64_t pcbmux_req_c1 : 1; uint64_t pc_wakeup_c1 : 1; uint64_t pc_block_interrupts_c1 : 1; uint64_t pc_entry_ack_c1 : 1; uint64_t reserved_8_111 : 4; uint64_t l2_core_intf_quiesce_c0 : 1; uint64_t pcc_core_intf_quiesce_c0 : 1; uint64_t reserved_4_5 : 2; uint64_t pcbmux_req_c0 : 1; uint64_t pc_wakeup_c0 : 1; uint64_t pc_block_interrupts_c0 : 1; uint64_t pc_entry_ack_c0 : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_sicr_t; typedef union cme_lcl_sicr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pc_entry_ack_c0 : 1; uint64_t pc_block_interrupts_c0 : 1; uint64_t pc_wakeup_c0 : 1; uint64_t pcbmux_req_c0 : 1; uint64_t reserved_4_5 : 2; uint64_t pcc_core_intf_quiesce_c0 : 1; uint64_t l2_core_intf_quiesce_c0 : 1; uint64_t reserved_8_111 : 4; uint64_t pc_entry_ack_c1 : 1; uint64_t pc_block_interrupts_c1 : 1; uint64_t pc_wakeup_c1 : 1; uint64_t pcbmux_req_c1 : 1; uint64_t reserved_16_17 : 2; uint64_t pcc_core_intf_quiesce_c1 : 1; uint64_t l2_core_intf_quiesce_c1 : 1; uint64_t reserved_20_212 : 2; uint64_t special_wkup_done_c0 : 1; uint64_t special_wkup_done_c1 : 1; uint64_t l2_purge : 1; uint64_t l2_purge_abort : 1; uint64_t reserved263 : 1; uint64_t ncu_tlbie_quiesce : 1; uint64_t ncu_purge : 1; uint64_t ncu_purge_abort : 1; uint64_t chtm_purge_c0 : 1; uint64_t chtm_purge_c1 : 1; uint64_t hmi_request_c0 : 1; uint64_t hmi_request_c1 : 1; uint64_t ppm_spare_out_c0 : 1; uint64_t ppm_spare_out_c1 : 1; uint64_t reserved_36_394 : 4; uint64_t reserved5 : 24; #else uint64_t reserved5 : 24; uint64_t reserved_36_394 : 4; uint64_t ppm_spare_out_c1 : 1; uint64_t ppm_spare_out_c0 : 1; uint64_t hmi_request_c1 : 1; uint64_t hmi_request_c0 : 1; uint64_t chtm_purge_c1 : 1; uint64_t chtm_purge_c0 : 1; uint64_t ncu_purge_abort : 1; uint64_t ncu_purge : 1; uint64_t ncu_tlbie_quiesce : 1; uint64_t reserved263 : 1; uint64_t l2_purge_abort : 1; uint64_t l2_purge : 1; uint64_t special_wkup_done_c1 : 1; uint64_t special_wkup_done_c0 : 1; uint64_t reserved_20_212 : 2; uint64_t l2_core_intf_quiesce_c1 : 1; uint64_t pcc_core_intf_quiesce_c1 : 1; uint64_t reserved_16_17 : 2; uint64_t pcbmux_req_c1 : 1; uint64_t pc_wakeup_c1 : 1; uint64_t pc_block_interrupts_c1 : 1; uint64_t pc_entry_ack_c1 : 1; uint64_t reserved_8_111 : 4; uint64_t l2_core_intf_quiesce_c0 : 1; uint64_t pcc_core_intf_quiesce_c0 : 1; uint64_t reserved_4_5 : 2; uint64_t pcbmux_req_c0 : 1; uint64_t pc_wakeup_c0 : 1; uint64_t pc_block_interrupts_c0 : 1; uint64_t pc_entry_ack_c0 : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_sicr_or_t; typedef union cme_lcl_sicr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pc_entry_ack_c0 : 1; uint64_t pc_block_interrupts_c0 : 1; uint64_t pc_wakeup_c0 : 1; uint64_t pcbmux_req_c0 : 1; uint64_t reserved_4_5 : 2; uint64_t pcc_core_intf_quiesce_c0 : 1; uint64_t l2_core_intf_quiesce_c0 : 1; uint64_t reserved_8_111 : 4; uint64_t pc_entry_ack_c1 : 1; uint64_t pc_block_interrupts_c1 : 1; uint64_t pc_wakeup_c1 : 1; uint64_t pcbmux_req_c1 : 1; uint64_t reserved_16_17 : 2; uint64_t pcc_core_intf_quiesce_c1 : 1; uint64_t l2_core_intf_quiesce_c1 : 1; uint64_t reserved_20_212 : 2; uint64_t special_wkup_done_c0 : 1; uint64_t special_wkup_done_c1 : 1; uint64_t l2_purge : 1; uint64_t l2_purge_abort : 1; uint64_t reserved263 : 1; uint64_t ncu_tlbie_quiesce : 1; uint64_t ncu_purge : 1; uint64_t ncu_purge_abort : 1; uint64_t chtm_purge_c0 : 1; uint64_t chtm_purge_c1 : 1; uint64_t hmi_request_c0 : 1; uint64_t hmi_request_c1 : 1; uint64_t ppm_spare_out_c0 : 1; uint64_t ppm_spare_out_c1 : 1; uint64_t reserved_36_394 : 4; uint64_t reserved5 : 24; #else uint64_t reserved5 : 24; uint64_t reserved_36_394 : 4; uint64_t ppm_spare_out_c1 : 1; uint64_t ppm_spare_out_c0 : 1; uint64_t hmi_request_c1 : 1; uint64_t hmi_request_c0 : 1; uint64_t chtm_purge_c1 : 1; uint64_t chtm_purge_c0 : 1; uint64_t ncu_purge_abort : 1; uint64_t ncu_purge : 1; uint64_t ncu_tlbie_quiesce : 1; uint64_t reserved263 : 1; uint64_t l2_purge_abort : 1; uint64_t l2_purge : 1; uint64_t special_wkup_done_c1 : 1; uint64_t special_wkup_done_c0 : 1; uint64_t reserved_20_212 : 2; uint64_t l2_core_intf_quiesce_c1 : 1; uint64_t pcc_core_intf_quiesce_c1 : 1; uint64_t reserved_16_17 : 2; uint64_t pcbmux_req_c1 : 1; uint64_t pc_wakeup_c1 : 1; uint64_t pc_block_interrupts_c1 : 1; uint64_t pc_entry_ack_c1 : 1; uint64_t reserved_8_111 : 4; uint64_t l2_core_intf_quiesce_c0 : 1; uint64_t pcc_core_intf_quiesce_c0 : 1; uint64_t reserved_4_5 : 2; uint64_t pcbmux_req_c0 : 1; uint64_t pc_wakeup_c0 : 1; uint64_t pc_block_interrupts_c0 : 1; uint64_t pc_entry_ack_c0 : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_sicr_clr_t; typedef union cme_lcl_sisr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pc_unmasked_attn_c0 : 1; uint64_t pc_instr_running_c0 : 1; uint64_t pm_state_all_hv_c0 : 1; uint64_t pm_state_active_c0 : 1; uint64_t pm_state_c0 : 4; uint64_t allow_reg_wakeup_c0 : 1; uint64_t spare_9 : 1; uint64_t pcbmux_grant_c0 : 1; uint64_t pcbmux_grant_c1 : 1; uint64_t pc_non_hv_running_c0 : 4; uint64_t pc_unmasked_attn_c1 : 1; uint64_t pc_instr_running_c1 : 1; uint64_t pm_state_all_hv_c1 : 1; uint64_t pm_state_active_c1 : 1; uint64_t pm_state_c1 : 4; uint64_t allow_reg_wakeup_c1 : 1; uint64_t spare_25_27 : 3; uint64_t pc_non_hv_running_c1 : 4; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t pc_non_hv_running_c1 : 4; uint64_t spare_25_27 : 3; uint64_t allow_reg_wakeup_c1 : 1; uint64_t pm_state_c1 : 4; uint64_t pm_state_active_c1 : 1; uint64_t pm_state_all_hv_c1 : 1; uint64_t pc_instr_running_c1 : 1; uint64_t pc_unmasked_attn_c1 : 1; uint64_t pc_non_hv_running_c0 : 4; uint64_t pcbmux_grant_c1 : 1; uint64_t pcbmux_grant_c0 : 1; uint64_t spare_9 : 1; uint64_t allow_reg_wakeup_c0 : 1; uint64_t pm_state_c0 : 4; uint64_t pm_state_active_c0 : 1; uint64_t pm_state_all_hv_c0 : 1; uint64_t pc_instr_running_c0 : 1; uint64_t pc_unmasked_attn_c0 : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_sisr_t; typedef union cme_lcl_xipcbmd0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_data : 64; #else uint64_t pcbm_data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_xipcbmd0_t; typedef union cme_lcl_xipcbmd1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_data : 64; #else uint64_t pcbm_data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_xipcbmd1_t; typedef union cme_lcl_xipcbmi0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_info : 64; #else uint64_t pcbm_info : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_xipcbmi0_t; typedef union cme_lcl_xipcbmi1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcbm_info : 64; #else uint64_t pcbm_info : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_xipcbmi1_t; typedef union cme_lcl_vtsr0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_thresh_data : 64; #else uint64_t vdm_thresh_data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_vtsr0_t; typedef union cme_lcl_vtsr1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_thresh_data : 64; #else uint64_t vdm_thresh_data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_vtsr1_t; typedef union cme_lcl_vdsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_data : 64; #else uint64_t vdm_data : 64; #endif // _BIG_ENDIAN } fields; } cme_lcl_vdsr_t; typedef union cme_lcl_iccr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_comm_ack : 1; uint64_t cme_comm_nack : 1; uint64_t reserved1 : 62; #else uint64_t reserved1 : 62; uint64_t cme_comm_nack : 1; uint64_t cme_comm_ack : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_iccr_t; typedef union cme_lcl_iccr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_comm_ack : 1; uint64_t cme_comm_nack : 1; uint64_t reserved1 : 62; #else uint64_t reserved1 : 62; uint64_t cme_comm_nack : 1; uint64_t cme_comm_ack : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_iccr_or_t; typedef union cme_lcl_iccr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_comm_ack : 1; uint64_t cme_comm_nack : 1; uint64_t reserved1 : 62; #else uint64_t reserved1 : 62; uint64_t cme_comm_nack : 1; uint64_t cme_comm_ack : 1; #endif // _BIG_ENDIAN } fields; } cme_lcl_iccr_clr_t; typedef union cme_lcl_icsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_comm_send : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t cme_comm_send : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_icsr_t; typedef union cme_lcl_icrr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_comm_recv : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t cme_comm_recv : 32; #endif // _BIG_ENDIAN } fields; } cme_lcl_icrr_t; #endif // __ASSEMBLER__ #endif // __CME_FIRMWARE_REGISTERS_H__ <|start_filename|>src/ssx/occhw/occhw_async_gpe.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_async_gpe.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_async_gpe.c /// \brief Async driver code for GPE #include "ssx.h" #include "occhw_async.h" /////////////////////////////////////////////////////////////////////////////// /// Global Data /////////////////////////////////////////////////////////////////////////////// #define ASYNC_NUM_GPE_QUEUES 4 #define ASYNC_ENG2GPE(eng) ((eng) & 0x0000000f) // The GPE queue objects. GpeQueue G_async_gpe_queue0; GpeQueue G_async_gpe_queue1; GpeQueue G_async_gpe_queue2; GpeQueue G_async_gpe_queue3; // Each GPE queue gets one IPC command. These are allocated separately so that // they can be allocated in a non-cacheable section. ipc_async_cmd_t G_async_ipc_cmd[ASYNC_NUM_GPE_QUEUES] SECTION_ATTRIBUTE(".noncacheable"); /////////////////////////////////////////////////////////////////////////////// /// GpeQueue /////////////////////////////////////////////////////////////////////////////// /// Create (initialize) a GpeQueue /// /// \param queue An uninitialized or otherwise idle GpeeQueue /// /// \param engine The identifier of a GPE engine associated with this queue. /// /// This API initializes the GpeQueue structure. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_PORE_QUEUE The \a queue was NULL (0). /// /// \retval -ASYNC_INVALID_ENGINE_GPE The \a engine is not a (valid) /// GPE engine. int gpe_queue_create(GpeQueue* queue, int engine) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(queue == 0, ASYNC_INVALID_OBJECT_GPE_QUEUE); SSX_ERROR_IF(!(engine & ASYNC_ENGINE_GPE), ASYNC_INVALID_ENGINE_GPE); SSX_ERROR_IF((ASYNC_ENG2GPE(engine) >= ASYNC_NUM_GPE_QUEUES), ASYNC_INVALID_ENGINE_GPE); } //initialize the base async queue async_queue_create(&queue->queue, engine); //assign an IPC message to be used with the queue //This is kept as a pointer so that the message can kept in a //cache-inhibited section of SRAM. queue->ipc_cmd = &G_async_ipc_cmd[ASYNC_ENG2GPE(engine)]; //The IPC target ID that all messages on this queue will be sent to queue->ipc_target_id = ASYNC_ENG2GPE(engine); return 0; } //////////////////////////////////////////////////////////////////////////// // async_ipc_callback //////////////////////////////////////////////////////////////////////////// /// Internal function that handles aysnc IPC command responses void gpe_async_handler(ipc_msg_t* rsp, void* arg) { // check for errors detected by the GPE code if(rsp->ipc_rc != IPC_RC_SUCCESS) { //calls gpe_error_method before calling async_handler async_error_handler((AsyncQueue*)arg, ASYNC_REQUEST_STATE_FAILED); } else { //handle async callbacks and process the next gpe request in the queue //(if any) async_handler((AsyncQueue*) arg); } } //////////////////////////////////////////////////////////////////////////// // GpeRequest //////////////////////////////////////////////////////////////////////////// /// Create (initialize) the GpeRequest base class /// /// \param request An uninitialized or otherwise idle GpeRequest. /// /// \param queue An initialized GpeQueue. /// /// \param func_id The IPC function ID of the GPE command. /// /// \param cmd_data A pointer to command-specific input and output data. /// /// \param timeout If not specified as SSX_WAIT_FOREVER, then this request /// will be governed by a private watchdog timer that will cancel a queued job /// or kill a running job if the hardware operation does not complete before /// it times out. /// /// \param callback The callback to execute when the GPE command completes, /// or NULL (0) to indicate no callback. /// /// \param arg The parameter to the callback routine; ignored if the \a /// callback is NULL. /// /// \param options Options to control request priority and callback context. /// /// This routine has no way to know if the GpeRequest structure is currently /// in use, so this API should only be called on uninitialized or otherwise /// idle GpeRequest structures. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_GPE_REQUEST The \a request was NULL (0) /// or the \a queue was NULL (0) or not a GpeQueue. /// /// \retval IPC_RC_INVALID_FUNC_ID The func_id has an invalid target id /// for the specified GPE queue. /// /// See async_request_create() for other errors that may be returned by this /// call. int gpe_request_create(GpeRequest* request, GpeQueue* queue, ipc_func_enum_t func_id, void* cmd_data, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options) { AsyncQueue* async_queue = (AsyncQueue*)queue; uint32_t targeted_func_id; int rc; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(!(async_queue->engine & ASYNC_ENGINE_GPE), ASYNC_INVALID_OBJECT_GPE_REQUEST); } //initialize the base async request rc = async_request_create(&(request->request), async_queue, gpe_run_method, gpe_error_method, timeout, callback, arg, options); if(!rc) { //If this is a multi-target function ID we need to set the target id. if(IPC_FUNCID_IS_MT(func_id)) { //This macro will set the target to an invalid target id if this //function id is not a multi-target function ID and this condition //will be caught when we check that the target id for the request //matches the target id for the queue. targeted_func_id = IPC_SET_MT_TARGET(func_id, queue->ipc_target_id); } else { //single target function IDs already have a target targeted_func_id = func_id; } //check that target id of the command matches the target id //of the queue. if (IPC_GET_TARGET_ID(targeted_func_id) != queue->ipc_target_id) { rc = IPC_RC_INVALID_FUNC_ID; } else { //initialize data that will be used when sending the command request->cmd_data = cmd_data; request->targeted_func_id = targeted_func_id; } } return rc; } // Start a GpeRequest on a GPE // // \param async_request A GpeRequest upcast to an AsyncRequest. // // This is an internal API. // // This routine sends an async_request to a GPE. // int gpe_run_method(AsyncRequest* async_request) { GpeQueue* queue = (GpeQueue*)(async_request->queue); GpeRequest* request = (GpeRequest*)async_request; ipc_async_cmd_t* ipc_cmd = queue->ipc_cmd; int rc; //Initialize the IPC command message ipc_init_msg(&ipc_cmd->cmd, request->targeted_func_id, gpe_async_handler, queue); ipc_cmd->cmd_data = request->cmd_data; //Send the IPC command rc = ipc_send_cmd(&ipc_cmd->cmd); //If there's an error in the send, collect ffdc and mark it as //having failed. if(rc) { gpe_error_method(async_request); async_request->completion_state = ASYNC_REQUEST_STATE_FAILED; rc = -ASYNC_REQUEST_COMPLETE; } return rc; } // GPE FFDC collection // // \param async_request A GpeRequest upcast to an AsyncRequest // // This is an internal API, called from the async base code when an async // request times out. // // GPE async error handling procedure: // // - Collect FFDC from the failing engine // // Currently all GPE errors are treated as recoverable int gpe_error_method(AsyncRequest* async_request) { GpeQueue* queue = (GpeQueue*)(async_request->queue); GpeRequest* request = (GpeRequest*)async_request; // Collect data that could explain why a GPE command // couldn't be sent or timed out on the response and save it // in the ffdc fields //retrieve IPC data request->ffdc.func_id = queue->ipc_cmd->cmd.func_id.word32; request->ffdc.ipc_rc = queue->ipc_cmd->cmd.ipc_rc; //retrieve XIR data request->ffdc.xir_dump_rc = occhw_xir_dump(queue->ipc_target_id, &request->ffdc.xir_dump); return 0; } //////////////////////////////////////////////////////////////////////////// // Initialization //////////////////////////////////////////////////////////////////////////// void async_gpe_initialize(GpeQueue* queue, int engine) { gpe_queue_create(queue, engine); } <|start_filename|>src/include/registers/qppm_register_addresses.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/qppm_register_addresses.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __QPPM_REGISTER_ADDRESSES_H__ #define __QPPM_REGISTER_ADDRESSES_H__ /// \file qppm_register_addresses.h /// \brief Symbolic addresses for the QPPM unit // *** WARNING *** - This file is generated automatically, do not edit. #define QPPM_PIB_BASE 0x100F0000 #define QPPM_QPMMR 0x100f0103 #define QPPM_QPMMR_CLR 0x100f0104 #define QPPM_QPMMR_OR 0x100f0105 #define QPPM_ERRSUM 0x100f0120 #define QPPM_ERR 0x100f0121 #define QPPM_ERRMSK 0x100f0122 #define QPPM_DPLL_FREQ 0x100f0151 #define QPPM_DPLL_CTRL 0x100f0152 #define QPPM_DPLL_CTRL_CLR 0x100f0153 #define QPPM_DPLL_CTRL_OR 0x100f0154 #define QPPM_DPLL_STAT 0x100f0155 #define QPPM_DPLL_OCHAR 0x100f0156 #define QPPM_DPLL_ICHAR 0x100f0157 #define QPPM_OCCHB 0x100f015f #define QPPM_QACCR 0x100f0160 #define QPPM_QACCR_CLR 0x100f0161 #define QPPM_QACCR_OR 0x100f0162 #define QPPM_QACSR 0x100f0163 #define QPPM_VDMCFGR 0x100f01b6 #define QPPM_EDRAM_CTRL 0x100f01bd #define QPPM_EDRAM_CTRL_CLR 0x100f01be #define QPPM_EDRAM_CTRL_OR 0x100f01bf #endif // __QPPM_REGISTER_ADDRESSES_H__ <|start_filename|>src/ssx/ssx/ssx_debug_ptrs.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_debug_ptrs.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_debug_ptrs.c /// \brief Defines a table of pointers to important kernel debug data. /// /// This table is placed in a special section named .debug_ptrs which can be /// placed at a well-known memory location for tools to find. /// #include "ssx.h" #include "ssx_trace.h" #include "ssx_debug_ptrs.h" extern SsxTimebase ppc405_64bit_ext_timebase; #if SSX_TRACE_SUPPORT extern SsxTraceBuffer g_ssx_trace_buf; #endif ssx_debug_ptrs_t ssx_debug_ptrs SECTION_ATTRIBUTE(".debug_ptrs") = { .debug_ptrs_size = sizeof(ssx_debug_ptrs), .debug_ptrs_version = SSX_DEBUG_PTRS_VERSION, #if SSX_TRACE_SUPPORT .debug_trace_ptr = &g_ssx_trace_buf, .debug_trace_size = sizeof(g_ssx_trace_buf), #else .debug_trace_ptr = 0, .debug_trace_size = 0, #endif /* SSX_TRACE_SUPPORT */ #if SSX_THREAD_SUPPORT .debug_thread_table_ptr = &__ssx_priority_map, .debug_thread_table_size = sizeof(__ssx_priority_map), .debug_thread_runq_ptr = (void*)& __ssx_run_queue, .debug_thread_runq_size = sizeof(__ssx_run_queue), #else .debug_thread_table_ptr = 0, .debug_thread_table_size = 0, .debug_thread_runq_ptr = 0, .debug_thread_runq_size = 0, #endif /* SSX_THREAD_SUPPORT */ .debug_timebase_ptr = &ppc405_64bit_ext_timebase, .debug_timebase_size = sizeof(ppc405_64bit_ext_timebase), }; <|start_filename|>src/occ_405/dimm/dimm_control.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/dimm/dimm_control.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //*************************************************************************/ // Includes //*************************************************************************/ #include "dimm_control.h" #include "dimm_structs.h" #include "errl.h" #include "trac.h" #include "rtls.h" #include "apss.h" #include "state.h" #include "amec_sys.h" #include "memory.h" #include "common.h" //GPE IPC request and parms for the GPE job used for DIMM modules control. //extern GpeRequest G_dimm_control_request; extern dimm_control_args_t G_dimm_control_args; extern memory_control_task_t G_memory_control_task; // A bit vector that indicated that the dimms (mbas) are configured // in a nimbus (cumulus) system. // Bit 0 (MSB) encodes the configuration status for port 0 on MC01 // (mba01 on centaur 0). // a 1 indicated a dimm (mba) is configured for throttling. // most significant 8 bits are used to cover nimbus' two MC pairs of 4 ports each. // Initialized to 0, sat by the FSP memory throttling configuration command // (0x21, format 0x12) extern uint16_t G_configured_mbas; // Bit vector that allows certain traces to run extern uint16_t G_allow_trace_flags; ////////////////////////// // Function Specification // // Name: dimm_control // // Description: RDIMM modules control. // Schedule a GPE IPC task to control the DIMMs whose // speed requested by the thermal controller has changed. // // Thread: RTL // // End Function Specification bool dimm_control(uint8_t mc, uint8_t port) { DIMM_DBG("dimm_control: called at tick %d", CURRENT_TICK); //update the min/max settings for all DIMMs according to mode dimm_update_nlimits(mc, port); // Convert speed request to N value, load N values into // GPE1 G_dimm_control_args.dimmNumeratorValues struct // and populate G_dimm_control_args.mc/port values // corresponding to dimm to be throttled. // Reset New N Value Flag prior to calling G_dimm_control_args.dimmNumeratorValues.new_n = FALSE; populate_dimm_control_args(g_amec->mem_speed_request, mc, port, &G_dimm_control_args); // Only need to update the static throttle sensors once static bool L_mem_static_throttle_update[NUM_NIMBUS_MC_PAIRS][MAX_NUM_MCU_PORTS] = {{0}}; // Update memory throttle sensors if( (g_amec->sys.dimm_m_values[mc][port].need_m != TRUE) && (g_amec->sys.dimm_m_values[mc][port].m_value != 0) ) { uint32_t l_nm_val, l_sensor_offset = 0; l_sensor_offset = (mc * MAX_NUM_MCU_PORTS) + port; // Update current memory throttle l_nm_val = g_amec->sys.current_dimm_n_values[mc][port].slot_n * 4000; l_nm_val /= g_amec->sys.dimm_m_values[mc][port].m_value; sensor_update( AMECSENSOR_ARRAY_PTR(MEMSPM0,l_sensor_offset), l_nm_val); if(!L_mem_static_throttle_update[mc][port]) { // Update static memory throttle l_nm_val = G_sysConfigData.mem_throt_limits[mc][port].nom_n_per_mba * 4000; l_nm_val /= g_amec->sys.dimm_m_values[mc][port].m_value; sensor_update( AMECSENSOR_ARRAY_PTR(MEMSPSTATM0,l_sensor_offset), l_nm_val); L_mem_static_throttle_update[mc][port] = TRUE; } } // Check if the throttle value has been updated since the last time we // sent it. If it has, then send a new value, otherwise do nothing. if(G_dimm_control_args.need_run) { if(G_dimm_control_args.dimmNumeratorValues.new_n) { DIMM_DBG("dimm throttle control changed: MC=%d. port=%d , Throttle=%d", mc, port, g_amec->mem_speed_request); } return TRUE; } return FALSE; } ////////////////////////// // Function Specification // // Name: dimm_update_nlimits // // Description: Updates all memory dimms throttle settings, including: // 1) new settings from FSP // 2) change to/from TURBO or DPS mode // 3) enter/exit oversubscription // // // Thread: RTL // // End Function Specification void dimm_update_nlimits(uint8_t mc, uint8_t port) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ static bool L_first_trace = true; uint16_t l_port_dimm_maxn = 0, l_slot_dimm_maxn = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { memory_throttle_t* l_active_limits; mem_throt_config_data_t* l_state_limits; // convert N Values for configured DIMMs only if(NIMBUS_DIMM_THROTTLING_CONFIGURED(G_configured_mbas,mc,port)) { l_active_limits = &G_memoryThrottleLimits[mc][port]; l_state_limits = &G_sysConfigData.mem_throt_limits[mc][port]; //Minimum N value is not state dependent l_active_limits->min_n_per_mba = l_state_limits->min_n_per_mba; //Power Capping memory? if(g_amec->pcap.active_mem_level == 1) { l_port_dimm_maxn = l_state_limits->pcap_n_per_chip; l_slot_dimm_maxn = l_state_limits->pcap_n_per_mba; } else if(CURRENT_MODE() == OCC_MODE_NOMINAL) { l_port_dimm_maxn = l_state_limits->nom_n_per_chip; l_slot_dimm_maxn = l_state_limits->nom_n_per_mba; } else //all other modes will use turbo settings { l_port_dimm_maxn = l_state_limits->turbo_n_per_chip; l_slot_dimm_maxn = l_state_limits->turbo_n_per_mba; } l_active_limits->max_n_per_chip = l_port_dimm_maxn; //Trace when the dimm slot max N value changes if(l_slot_dimm_maxn != l_active_limits->max_n_per_mba) { l_active_limits->max_n_per_mba = l_slot_dimm_maxn; if( (L_first_trace) || (G_allow_trace_flags & ALLOW_MEM_TRACE) ) { TRAC_IMP("dimm_update_nlimits: New DIMM slot throttle values: " "MC#|Port:[0x%04x], " "Max|Min N_PER_MBA:[0x%08x], Max N_PER_CHIP:[0x%04x] ", (uint16_t)((mc << 8) | port), (uint32_t)( (l_active_limits->max_n_per_mba << 16) | l_active_limits->min_n_per_mba), l_active_limits->max_n_per_chip); L_first_trace = false; } } } // NIMBUS_DIMM_THROTTLING_CONFIGURED ? }while(0); } ////////////////////////// // Function Specification // // Name: populate_dimm_control_args // // Description: Converts dimm throttle percentage into 'N' value // that can be written to the hardware, load N values // into GPE1 G_dimm_control_args.dimmNumeratorValue, // and populate G_dimm_control_args.mc/port for the // corresponding dimm. // // // Thread: RTL // // End Function Specification #define DIMM_THROTTLE_100_PERCENT_VALUE 1000 void populate_dimm_control_args(uint16_t i_throttle, uint8_t mc, uint8_t port, dimm_control_args_t * dimm_control_args) { dimm_n_value_t dimm_nvalue; memory_throttle_t* l_dimm_throttle; // MC01 = 0, MC23 = 1 l_dimm_throttle = &G_memoryThrottleLimits[mc][port]; // a DIMM is configured? if(NIMBUS_DIMM_THROTTLING_CONFIGURED(G_configured_mbas,mc,port)) { // Convert the dimm throttle (in units of 0.1 %) to "N" value dimm_nvalue.slot_n = convert_speed2numerator(i_throttle, l_dimm_throttle->min_n_per_mba, l_dimm_throttle->max_n_per_mba); dimm_nvalue.port_n = l_dimm_throttle->max_n_per_chip; // A change in the N value for dimm control args(mc,port)? if(dimm_nvalue.word32 != g_amec->sys.current_dimm_n_values[mc][port].word32) { dimm_control_args->dimmNumeratorValues.word32 = dimm_nvalue.word32; g_amec->sys.current_dimm_n_values[mc][port].word32 = dimm_nvalue.word32; dimm_control_args->dimmNumeratorValues.new_n = TRUE; } // Indicate if we need the M value dimm_control_args->dimmDenominatorValues.need_m = g_amec->sys.dimm_m_values[mc][port].need_m; if(dimm_control_args->dimmDenominatorValues.need_m || dimm_control_args->dimmNumeratorValues.new_n) { dimm_control_args->mc = mc; dimm_control_args->port = port; dimm_control_args->need_run = TRUE; } else { dimm_control_args->need_run = FALSE; } } } ////////////////////////// // Function Specification // // Name: convertSpeed2Numerator // // Description: Converts dimm throttle percentages into 'N' value // that can be written to the hardware. // // Thread: RTL // // End Function Specification uint16_t convert_speed2numerator(uint16_t i_throttle, uint16_t min_n_value, uint16_t max_n_value) { uint16_t l_nvalue = 0; // Convert the throttle (in units of 0.1 %) to "N" value l_nvalue = (max_n_value * i_throttle) / DIMM_THROTTLE_100_PERCENT_VALUE; //Clip to DIMM's per-slot min and max values if(l_nvalue < min_n_value) { l_nvalue = min_n_value; } if(l_nvalue > max_n_value) { l_nvalue = max_n_value; } return l_nvalue; } <|start_filename|>src/include/registers/ocb_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/ocb_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCB_FIRMWARE_REGISTERS_H__ #define __OCB_FIRMWARE_REGISTERS_H__ /// \file ocb_firmware_registers.h /// \brief C register structs for the OCB unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union ocb_oisr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t debugger : 1; uint32_t trace_trigger : 1; uint32_t occ_error : 1; uint32_t pba_error : 1; uint32_t srt_error : 1; uint32_t gpe0_error : 1; uint32_t gpe1_error : 1; uint32_t gpe2_error : 1; uint32_t gpe3_error : 1; uint32_t ppc405_halt : 1; uint32_t ocb_error : 1; uint32_t spipss_error : 1; uint32_t check_stop_ppc405 : 1; uint32_t check_stop_gpe0 : 1; uint32_t check_stop_gpe1 : 1; uint32_t check_stop_gpe2 : 1; uint32_t check_stop_gpe3 : 1; uint32_t occ_malf_alert : 1; uint32_t adu_malf_alert : 1; uint32_t external_trap : 1; uint32_t ivrm_pvref_error : 1; uint32_t occ_timer0 : 1; uint32_t occ_timer1 : 1; uint32_t avs_slave0 : 1; uint32_t avs_slave1 : 1; uint32_t ipi0_hi_priority : 1; uint32_t ipi1_hi_priority : 1; uint32_t ipi2_hi_priority : 1; uint32_t ipi3_hi_priority : 1; uint32_t ipi4_hi_priority : 1; uint32_t adcfsm_ongoing : 1; uint32_t spare_31 : 1; #else uint32_t spare_31 : 1; uint32_t adcfsm_ongoing : 1; uint32_t ipi4_hi_priority : 1; uint32_t ipi3_hi_priority : 1; uint32_t ipi2_hi_priority : 1; uint32_t ipi1_hi_priority : 1; uint32_t ipi0_hi_priority : 1; uint32_t avs_slave1 : 1; uint32_t avs_slave0 : 1; uint32_t occ_timer1 : 1; uint32_t occ_timer0 : 1; uint32_t ivrm_pvref_error : 1; uint32_t external_trap : 1; uint32_t adu_malf_alert : 1; uint32_t occ_malf_alert : 1; uint32_t check_stop_gpe3 : 1; uint32_t check_stop_gpe2 : 1; uint32_t check_stop_gpe1 : 1; uint32_t check_stop_gpe0 : 1; uint32_t check_stop_ppc405 : 1; uint32_t spipss_error : 1; uint32_t ocb_error : 1; uint32_t ppc405_halt : 1; uint32_t gpe3_error : 1; uint32_t gpe2_error : 1; uint32_t gpe1_error : 1; uint32_t gpe0_error : 1; uint32_t srt_error : 1; uint32_t pba_error : 1; uint32_t occ_error : 1; uint32_t trace_trigger : 1; uint32_t debugger : 1; #endif // _BIG_ENDIAN } fields; } ocb_oisr0_t; typedef union ocb_oisr0_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t debugger : 1; uint32_t trace_trigger : 1; uint32_t occ_error : 1; uint32_t pba_error : 1; uint32_t srt_error : 1; uint32_t gpe0_error : 1; uint32_t gpe1_error : 1; uint32_t gpe2_error : 1; uint32_t gpe3_error : 1; uint32_t ppc405_halt : 1; uint32_t ocb_error : 1; uint32_t spipss_error : 1; uint32_t check_stop_ppc405 : 1; uint32_t check_stop_gpe0 : 1; uint32_t check_stop_gpe1 : 1; uint32_t check_stop_gpe2 : 1; uint32_t check_stop_gpe3 : 1; uint32_t occ_malf_alert : 1; uint32_t adu_malf_alert : 1; uint32_t external_trap : 1; uint32_t ivrm_pvref_error : 1; uint32_t occ_timer0 : 1; uint32_t occ_timer1 : 1; uint32_t avs_slave0 : 1; uint32_t avs_slave1 : 1; uint32_t ipi0_hi_priority : 1; uint32_t ipi1_hi_priority : 1; uint32_t ipi2_hi_priority : 1; uint32_t ipi3_hi_priority : 1; uint32_t ipi4_hi_priority : 1; uint32_t adcfsm_ongoing : 1; uint32_t spare_31 : 1; #else uint32_t spare_31 : 1; uint32_t adcfsm_ongoing : 1; uint32_t ipi4_hi_priority : 1; uint32_t ipi3_hi_priority : 1; uint32_t ipi2_hi_priority : 1; uint32_t ipi1_hi_priority : 1; uint32_t ipi0_hi_priority : 1; uint32_t avs_slave1 : 1; uint32_t avs_slave0 : 1; uint32_t occ_timer1 : 1; uint32_t occ_timer0 : 1; uint32_t ivrm_pvref_error : 1; uint32_t external_trap : 1; uint32_t adu_malf_alert : 1; uint32_t occ_malf_alert : 1; uint32_t check_stop_gpe3 : 1; uint32_t check_stop_gpe2 : 1; uint32_t check_stop_gpe1 : 1; uint32_t check_stop_gpe0 : 1; uint32_t check_stop_ppc405 : 1; uint32_t spipss_error : 1; uint32_t ocb_error : 1; uint32_t ppc405_halt : 1; uint32_t gpe3_error : 1; uint32_t gpe2_error : 1; uint32_t gpe1_error : 1; uint32_t gpe0_error : 1; uint32_t srt_error : 1; uint32_t pba_error : 1; uint32_t occ_error : 1; uint32_t trace_trigger : 1; uint32_t debugger : 1; #endif // _BIG_ENDIAN } fields; } ocb_oisr0_clr_t; typedef union ocb_oisr0_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t debugger : 1; uint32_t trace_trigger : 1; uint32_t occ_error : 1; uint32_t pba_error : 1; uint32_t srt_error : 1; uint32_t gpe0_error : 1; uint32_t gpe1_error : 1; uint32_t gpe2_error : 1; uint32_t gpe3_error : 1; uint32_t ppc405_halt : 1; uint32_t ocb_error : 1; uint32_t spipss_error : 1; uint32_t check_stop_ppc405 : 1; uint32_t check_stop_gpe0 : 1; uint32_t check_stop_gpe1 : 1; uint32_t check_stop_gpe2 : 1; uint32_t check_stop_gpe3 : 1; uint32_t occ_malf_alert : 1; uint32_t adu_malf_alert : 1; uint32_t external_trap : 1; uint32_t ivrm_pvref_error : 1; uint32_t occ_timer0 : 1; uint32_t occ_timer1 : 1; uint32_t avs_slave0 : 1; uint32_t avs_slave1 : 1; uint32_t ipi0_hi_priority : 1; uint32_t ipi1_hi_priority : 1; uint32_t ipi2_hi_priority : 1; uint32_t ipi3_hi_priority : 1; uint32_t ipi4_hi_priority : 1; uint32_t adcfsm_ongoing : 1; uint32_t spare_31 : 1; #else uint32_t spare_31 : 1; uint32_t adcfsm_ongoing : 1; uint32_t ipi4_hi_priority : 1; uint32_t ipi3_hi_priority : 1; uint32_t ipi2_hi_priority : 1; uint32_t ipi1_hi_priority : 1; uint32_t ipi0_hi_priority : 1; uint32_t avs_slave1 : 1; uint32_t avs_slave0 : 1; uint32_t occ_timer1 : 1; uint32_t occ_timer0 : 1; uint32_t ivrm_pvref_error : 1; uint32_t external_trap : 1; uint32_t adu_malf_alert : 1; uint32_t occ_malf_alert : 1; uint32_t check_stop_gpe3 : 1; uint32_t check_stop_gpe2 : 1; uint32_t check_stop_gpe1 : 1; uint32_t check_stop_gpe0 : 1; uint32_t check_stop_ppc405 : 1; uint32_t spipss_error : 1; uint32_t ocb_error : 1; uint32_t ppc405_halt : 1; uint32_t gpe3_error : 1; uint32_t gpe2_error : 1; uint32_t gpe1_error : 1; uint32_t gpe0_error : 1; uint32_t srt_error : 1; uint32_t pba_error : 1; uint32_t occ_error : 1; uint32_t trace_trigger : 1; uint32_t debugger : 1; #endif // _BIG_ENDIAN } fields; } ocb_oisr0_or_t; typedef union ocb_oimr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_mask_n : 32; #else uint32_t interrupt_mask_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oimr0_t; typedef union ocb_oimr0_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_mask_n : 32; #else uint32_t interrupt_mask_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oimr0_clr_t; typedef union ocb_oimr0_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_mask_n : 32; #else uint32_t interrupt_mask_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oimr0_or_t; typedef union ocb_oitr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_type_n : 32; #else uint32_t interrupt_type_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oitr0_t; typedef union ocb_oitr0_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_type_n : 32; #else uint32_t interrupt_type_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oitr0_clr_t; typedef union ocb_oitr0_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_type_n : 32; #else uint32_t interrupt_type_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oitr0_or_t; typedef union ocb_oiepr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_edge_pol_n : 32; #else uint32_t interrupt_edge_pol_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oiepr0_t; typedef union ocb_oiepr0_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_edge_pol_n : 32; #else uint32_t interrupt_edge_pol_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oiepr0_clr_t; typedef union ocb_oiepr0_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_edge_pol_n : 32; #else uint32_t interrupt_edge_pol_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oiepr0_or_t; typedef union ocb_oisr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pbax_occ_send_attn : 1; uint32_t pbax_occ_push0 : 1; uint32_t pbax_occ_push1 : 1; uint32_t pba_bcde_attn : 1; uint32_t pba_bcue_attn : 1; uint32_t occ_strm0_pull : 1; uint32_t occ_strm0_push : 1; uint32_t occ_strm1_pull : 1; uint32_t occ_strm1_push : 1; uint32_t occ_strm2_pull : 1; uint32_t occ_strm2_push : 1; uint32_t occ_strm3_pull : 1; uint32_t occ_strm3_push : 1; uint32_t pmc_pcb_intr_type0_pending : 1; uint32_t pmc_pcb_intr_type1_pending : 1; uint32_t pmc_pcb_intr_type2_pending : 1; uint32_t pmc_pcb_intr_type3_pending : 1; uint32_t pmc_pcb_intr_type4_pending : 1; uint32_t pmc_pcb_intr_type5_pending : 1; uint32_t pmc_pcb_intr_type6_pending : 1; uint32_t pmc_pcb_intr_type7_pending : 1; uint32_t pmc_o2s_0a_ongoing : 1; uint32_t pmc_o2s_0b_ongoing : 1; uint32_t pmc_o2s_1a_ongoing : 1; uint32_t pmc_o2s_1b_ongoing : 1; uint32_t pssbridge_ongoing : 1; uint32_t ipi0_lo_priority : 1; uint32_t ipi1_lo_priority : 1; uint32_t ipi2_lo_priority : 1; uint32_t ipi3_lo_priority : 1; uint32_t ipi4_lo_priority : 1; uint32_t spare_31 : 1; #else uint32_t spare_31 : 1; uint32_t ipi4_lo_priority : 1; uint32_t ipi3_lo_priority : 1; uint32_t ipi2_lo_priority : 1; uint32_t ipi1_lo_priority : 1; uint32_t ipi0_lo_priority : 1; uint32_t pssbridge_ongoing : 1; uint32_t pmc_o2s_1b_ongoing : 1; uint32_t pmc_o2s_1a_ongoing : 1; uint32_t pmc_o2s_0b_ongoing : 1; uint32_t pmc_o2s_0a_ongoing : 1; uint32_t pmc_pcb_intr_type7_pending : 1; uint32_t pmc_pcb_intr_type6_pending : 1; uint32_t pmc_pcb_intr_type5_pending : 1; uint32_t pmc_pcb_intr_type4_pending : 1; uint32_t pmc_pcb_intr_type3_pending : 1; uint32_t pmc_pcb_intr_type2_pending : 1; uint32_t pmc_pcb_intr_type1_pending : 1; uint32_t pmc_pcb_intr_type0_pending : 1; uint32_t occ_strm3_push : 1; uint32_t occ_strm3_pull : 1; uint32_t occ_strm2_push : 1; uint32_t occ_strm2_pull : 1; uint32_t occ_strm1_push : 1; uint32_t occ_strm1_pull : 1; uint32_t occ_strm0_push : 1; uint32_t occ_strm0_pull : 1; uint32_t pba_bcue_attn : 1; uint32_t pba_bcde_attn : 1; uint32_t pbax_occ_push1 : 1; uint32_t pbax_occ_push0 : 1; uint32_t pbax_occ_send_attn : 1; #endif // _BIG_ENDIAN } fields; } ocb_oisr1_t; typedef union ocb_oisr1_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pbax_occ_send_attn : 1; uint32_t pbax_occ_push0 : 1; uint32_t pbax_occ_push1 : 1; uint32_t pba_bcde_attn : 1; uint32_t pba_bcue_attn : 1; uint32_t occ_strm0_pull : 1; uint32_t occ_strm0_push : 1; uint32_t occ_strm1_pull : 1; uint32_t occ_strm1_push : 1; uint32_t occ_strm2_pull : 1; uint32_t occ_strm2_push : 1; uint32_t occ_strm3_pull : 1; uint32_t occ_strm3_push : 1; uint32_t pmc_pcb_intr_type0_pending : 1; uint32_t pmc_pcb_intr_type1_pending : 1; uint32_t pmc_pcb_intr_type2_pending : 1; uint32_t pmc_pcb_intr_type3_pending : 1; uint32_t pmc_pcb_intr_type4_pending : 1; uint32_t pmc_pcb_intr_type5_pending : 1; uint32_t pmc_pcb_intr_type6_pending : 1; uint32_t pmc_pcb_intr_type7_pending : 1; uint32_t pmc_o2s_0a_ongoing : 1; uint32_t pmc_o2s_0b_ongoing : 1; uint32_t pmc_o2s_1a_ongoing : 1; uint32_t pmc_o2s_1b_ongoing : 1; uint32_t pssbridge_ongoing : 1; uint32_t ipi0_lo_priority : 1; uint32_t ipi1_lo_priority : 1; uint32_t ipi2_lo_priority : 1; uint32_t ipi3_lo_priority : 1; uint32_t ipi4_lo_priority : 1; uint32_t spare_31 : 1; #else uint32_t spare_31 : 1; uint32_t ipi4_lo_priority : 1; uint32_t ipi3_lo_priority : 1; uint32_t ipi2_lo_priority : 1; uint32_t ipi1_lo_priority : 1; uint32_t ipi0_lo_priority : 1; uint32_t pssbridge_ongoing : 1; uint32_t pmc_o2s_1b_ongoing : 1; uint32_t pmc_o2s_1a_ongoing : 1; uint32_t pmc_o2s_0b_ongoing : 1; uint32_t pmc_o2s_0a_ongoing : 1; uint32_t pmc_pcb_intr_type7_pending : 1; uint32_t pmc_pcb_intr_type6_pending : 1; uint32_t pmc_pcb_intr_type5_pending : 1; uint32_t pmc_pcb_intr_type4_pending : 1; uint32_t pmc_pcb_intr_type3_pending : 1; uint32_t pmc_pcb_intr_type2_pending : 1; uint32_t pmc_pcb_intr_type1_pending : 1; uint32_t pmc_pcb_intr_type0_pending : 1; uint32_t occ_strm3_push : 1; uint32_t occ_strm3_pull : 1; uint32_t occ_strm2_push : 1; uint32_t occ_strm2_pull : 1; uint32_t occ_strm1_push : 1; uint32_t occ_strm1_pull : 1; uint32_t occ_strm0_push : 1; uint32_t occ_strm0_pull : 1; uint32_t pba_bcue_attn : 1; uint32_t pba_bcde_attn : 1; uint32_t pbax_occ_push1 : 1; uint32_t pbax_occ_push0 : 1; uint32_t pbax_occ_send_attn : 1; #endif // _BIG_ENDIAN } fields; } ocb_oisr1_clr_t; typedef union ocb_oisr1_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pbax_occ_send_attn : 1; uint32_t pbax_occ_push0 : 1; uint32_t pbax_occ_push1 : 1; uint32_t pba_bcde_attn : 1; uint32_t pba_bcue_attn : 1; uint32_t occ_strm0_pull : 1; uint32_t occ_strm0_push : 1; uint32_t occ_strm1_pull : 1; uint32_t occ_strm1_push : 1; uint32_t occ_strm2_pull : 1; uint32_t occ_strm2_push : 1; uint32_t occ_strm3_pull : 1; uint32_t occ_strm3_push : 1; uint32_t pmc_pcb_intr_type0_pending : 1; uint32_t pmc_pcb_intr_type1_pending : 1; uint32_t pmc_pcb_intr_type2_pending : 1; uint32_t pmc_pcb_intr_type3_pending : 1; uint32_t pmc_pcb_intr_type4_pending : 1; uint32_t pmc_pcb_intr_type5_pending : 1; uint32_t pmc_pcb_intr_type6_pending : 1; uint32_t pmc_pcb_intr_type7_pending : 1; uint32_t pmc_o2s_0a_ongoing : 1; uint32_t pmc_o2s_0b_ongoing : 1; uint32_t pmc_o2s_1a_ongoing : 1; uint32_t pmc_o2s_1b_ongoing : 1; uint32_t pssbridge_ongoing : 1; uint32_t ipi0_lo_priority : 1; uint32_t ipi1_lo_priority : 1; uint32_t ipi2_lo_priority : 1; uint32_t ipi3_lo_priority : 1; uint32_t ipi4_lo_priority : 1; uint32_t spare_31 : 1; #else uint32_t spare_31 : 1; uint32_t ipi4_lo_priority : 1; uint32_t ipi3_lo_priority : 1; uint32_t ipi2_lo_priority : 1; uint32_t ipi1_lo_priority : 1; uint32_t ipi0_lo_priority : 1; uint32_t pssbridge_ongoing : 1; uint32_t pmc_o2s_1b_ongoing : 1; uint32_t pmc_o2s_1a_ongoing : 1; uint32_t pmc_o2s_0b_ongoing : 1; uint32_t pmc_o2s_0a_ongoing : 1; uint32_t pmc_pcb_intr_type7_pending : 1; uint32_t pmc_pcb_intr_type6_pending : 1; uint32_t pmc_pcb_intr_type5_pending : 1; uint32_t pmc_pcb_intr_type4_pending : 1; uint32_t pmc_pcb_intr_type3_pending : 1; uint32_t pmc_pcb_intr_type2_pending : 1; uint32_t pmc_pcb_intr_type1_pending : 1; uint32_t pmc_pcb_intr_type0_pending : 1; uint32_t occ_strm3_push : 1; uint32_t occ_strm3_pull : 1; uint32_t occ_strm2_push : 1; uint32_t occ_strm2_pull : 1; uint32_t occ_strm1_push : 1; uint32_t occ_strm1_pull : 1; uint32_t occ_strm0_push : 1; uint32_t occ_strm0_pull : 1; uint32_t pba_bcue_attn : 1; uint32_t pba_bcde_attn : 1; uint32_t pbax_occ_push1 : 1; uint32_t pbax_occ_push0 : 1; uint32_t pbax_occ_send_attn : 1; #endif // _BIG_ENDIAN } fields; } ocb_oisr1_or_t; typedef union ocb_oimr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_mask_n : 32; #else uint32_t interrupt_mask_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oimr1_t; typedef union ocb_oimr1_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_mask_n : 32; #else uint32_t interrupt_mask_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oimr1_clr_t; typedef union ocb_oimr1_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_mask_n : 32; #else uint32_t interrupt_mask_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oimr1_or_t; typedef union ocb_oitr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_type_n : 32; #else uint32_t interrupt_type_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oitr1_t; typedef union ocb_oitr1_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_type_n : 32; #else uint32_t interrupt_type_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oitr1_clr_t; typedef union ocb_oitr1_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_type_n : 32; #else uint32_t interrupt_type_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oitr1_or_t; typedef union ocb_oiepr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_edge_pol_n : 32; #else uint32_t interrupt_edge_pol_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oiepr1_t; typedef union ocb_oiepr1_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_edge_pol_n : 32; #else uint32_t interrupt_edge_pol_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oiepr1_clr_t; typedef union ocb_oiepr1_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_edge_pol_n : 32; #else uint32_t interrupt_edge_pol_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oiepr1_or_t; typedef union ocb_oirr0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0a_t; typedef union ocb_oirr0a_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0a_clr_t; typedef union ocb_oirr0a_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0a_or_t; typedef union ocb_oirr0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0b_t; typedef union ocb_oirr0b_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0b_clr_t; typedef union ocb_oirr0b_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0b_or_t; typedef union ocb_oirr0c { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0c_t; typedef union ocb_oirr0c_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0c_clr_t; typedef union ocb_oirr0c_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr0c_or_t; typedef union ocb_oirr1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1a_t; typedef union ocb_oirr1a_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1a_clr_t; typedef union ocb_oirr1a_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1a_or_t; typedef union ocb_oirr1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1b_t; typedef union ocb_oirr1b_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1b_clr_t; typedef union ocb_oirr1b_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1b_or_t; typedef union ocb_oirr1c { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1c_t; typedef union ocb_oirr1c_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1c_clr_t; typedef union ocb_oirr1c_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_route_a_n : 32; #else uint32_t interrupt_route_a_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_oirr1c_or_t; typedef union ocb_onisr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_noncrit_status_n : 32; #else uint32_t interrupt_noncrit_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_onisr0_t; typedef union ocb_ocisr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_crit_status_n : 32; #else uint32_t interrupt_crit_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_ocisr0_t; typedef union ocb_ouisr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_uncon_status_n : 32; #else uint32_t interrupt_uncon_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_ouisr0_t; typedef union ocb_odisr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_debug_status_n : 32; #else uint32_t interrupt_debug_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_odisr0_t; typedef union ocb_g0isr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe0_status_n : 32; #else uint32_t interrupt_gpe0_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g0isr0_t; typedef union ocb_g1isr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe1_status_n : 32; #else uint32_t interrupt_gpe1_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g1isr0_t; typedef union ocb_g2isr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe2_status_n : 32; #else uint32_t interrupt_gpe2_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g2isr0_t; typedef union ocb_g3isr0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe3_status_n : 32; #else uint32_t interrupt_gpe3_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g3isr0_t; typedef union ocb_onisr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_noncrit_status_n : 32; #else uint32_t interrupt_noncrit_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_onisr1_t; typedef union ocb_ocisr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_crit_status_n : 32; #else uint32_t interrupt_crit_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_ocisr1_t; typedef union ocb_ouisr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_uncon_status_n : 32; #else uint32_t interrupt_uncon_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_ouisr1_t; typedef union ocb_odisr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_debug_status_n : 32; #else uint32_t interrupt_debug_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_odisr1_t; typedef union ocb_g0isr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe0_status_n : 32; #else uint32_t interrupt_gpe0_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g0isr1_t; typedef union ocb_g1isr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe1_status_n : 32; #else uint32_t interrupt_gpe1_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g1isr1_t; typedef union ocb_g2isr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe2_status_n : 32; #else uint32_t interrupt_gpe2_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g2isr1_t; typedef union ocb_g3isr1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t interrupt_gpe3_status_n : 32; #else uint32_t interrupt_gpe3_status_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_g3isr1_t; typedef union ocb_occmisc { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t core_ext_intr : 1; uint32_t ext_intr_service_required : 1; uint32_t ext_intr_i2c_change : 1; uint32_t ext_intr_shmem_change : 1; uint32_t spare : 12; uint32_t i2cm_intr_status : 3; uint32_t reserved1 : 13; #else uint32_t reserved1 : 13; uint32_t i2cm_intr_status : 3; uint32_t spare : 11; uint32_t ext_intr_shmem_change : 1; uint32_t ext_intr_i2c_change : 1; uint32_t ext_intr_service_required : 1; uint32_t core_ext_intr : 1; #endif // _BIG_ENDIAN } fields; } ocb_occmisc_t; typedef union ocb_ohtmcr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t htm_src_sel : 2; uint32_t htm_stop : 1; uint32_t htm_marker_slave_adrs : 3; uint32_t event2halt_mode : 2; uint32_t event2halt_en : 11; uint32_t reserved1 : 4; uint32_t event2halt_occ : 1; uint32_t event2halt_gpe0 : 1; uint32_t event2halt_gpe1 : 1; uint32_t event2halt_gpe2 : 1; uint32_t event2halt_gpe3 : 1; uint32_t reserved2 : 3; uint32_t event2halt_halt_state : 1; #else uint32_t event2halt_halt_state : 1; uint32_t reserved2 : 3; uint32_t event2halt_gpe3 : 1; uint32_t event2halt_gpe2 : 1; uint32_t event2halt_gpe1 : 1; uint32_t event2halt_gpe0 : 1; uint32_t event2halt_occ : 1; uint32_t reserved1 : 4; uint32_t event2halt_en : 11; uint32_t event2halt_mode : 2; uint32_t htm_marker_slave_adrs : 3; uint32_t htm_stop : 1; uint32_t htm_src_sel : 2; #endif // _BIG_ENDIAN } fields; } ocb_ohtmcr_t; typedef union ocb_oehdr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t event2halt_delay : 20; uint32_t reserved1 : 12; #else uint32_t reserved1 : 12; uint32_t event2halt_delay : 20; #endif // _BIG_ENDIAN } fields; } ocb_oehdr_t; typedef union ocb_ocicfg { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t m0_priority : 2; uint32_t m1_priority : 2; uint32_t m2_priority : 2; uint32_t m3_priority : 2; uint32_t m4_priority : 2; uint32_t m5_priority : 2; uint32_t m6_priority : 2; uint32_t m7_priority : 2; uint32_t m0_priority_sel : 1; uint32_t m1_priority_sel : 1; uint32_t m2_priority_sel : 1; uint32_t m3_priority_sel : 1; uint32_t ocicfg_reserved_20 : 1; uint32_t m5_priority_sel : 1; uint32_t ocicfg_reserved_23 : 1; uint32_t m7_priority_sel : 1; uint32_t plbarb_lockerr : 1; uint32_t spare_24_31 : 7; #else uint32_t spare_24_31 : 7; uint32_t plbarb_lockerr : 1; uint32_t m7_priority_sel : 1; uint32_t ocicfg_reserved_23 : 1; uint32_t m5_priority_sel : 1; uint32_t ocicfg_reserved_20 : 1; uint32_t m3_priority_sel : 1; uint32_t m2_priority_sel : 1; uint32_t m1_priority_sel : 1; uint32_t m0_priority_sel : 1; uint32_t m7_priority : 2; uint32_t m6_priority : 2; uint32_t m5_priority : 2; uint32_t m4_priority : 2; uint32_t m3_priority : 2; uint32_t m2_priority : 2; uint32_t m1_priority : 2; uint32_t m0_priority : 2; #endif // _BIG_ENDIAN } fields; } ocb_ocicfg_t; typedef union ocb_occs0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t occ_scratch_n : 32; #else uint32_t occ_scratch_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_occs0_t; typedef union ocb_occs1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t occ_scratch_n : 32; #else uint32_t occ_scratch_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_occs1_t; typedef union ocb_occs2 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t occ_scratch_n : 32; #else uint32_t occ_scratch_n : 32; #endif // _BIG_ENDIAN } fields; } ocb_occs2_t; typedef union ocb_occflg { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved_gpe : 16; uint32_t i2c_engine1_lock_host : 1; uint32_t i2c_engine1_lock_occ : 1; uint32_t i2c_engine2_lock_host : 1; uint32_t i2c_engine2_lock_occ : 1; uint32_t i2c_engine3_lock_host : 1; uint32_t i2c_engine3_lock_occ : 1; uint32_t gpu0_reset_status : 1; uint32_t gpu1_reset_status : 1; uint32_t gpu2_reset_status : 1; uint32_t reserved_occ : 2; uint32_t pm_reset_suppress : 1; uint32_t wof_hcode_mode : 2; uint32_t active_quad_update : 1; uint32_t request_occ_safe : 1; #else uint32_t request_occ_safe : 1; uint32_t active_quad_update : 1; uint32_t wof_hcode_mode : 2; uint32_t pm_reset_suppress : 1; uint32_t reserved_occ : 2; uint32_t gpu2_reset_status : 1; uint32_t gpu1_reset_status : 1; uint32_t gpu0_reset_status : 1; uint32_t i2c_engine3_lock_occ : 1; uint32_t i2c_engine3_lock_host : 1; uint32_t i2c_engine2_lock_occ : 1; uint32_t i2c_engine2_lock_host : 1; uint32_t i2c_engine1_lock_occ : 1; uint32_t i2c_engine1_lock_host : 1; uint32_t reserved_gpe : 16; #endif // _BIG_ENDIAN } fields; } ocb_occflg_t; typedef union ocb_occhbr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t occ_heartbeat_count : 16; uint32_t occ_heartbeat_en : 1; uint32_t reserved1 : 15; #else uint32_t reserved1 : 15; uint32_t occ_heartbeat_en : 1; uint32_t occ_heartbeat_count : 16; #endif // _BIG_ENDIAN } fields; } ocb_occhbr_t; typedef union ocb_ccsr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t core_config : 24; uint32_t reserved_24_1 : 7; uint32_t change_in_progress : 1; #else uint32_t change_in_progress : 1; uint32_t reserved_24_1 : 7; uint32_t core_config : 24; #endif // _BIG_ENDIAN } fields; } ocb_ccsr_t; typedef union ocb_ccsr_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t core_config : 24; uint32_t reserved_24_1 : 7; uint32_t change_in_progress : 1; #else uint32_t change_in_progress : 1; uint32_t reserved_24_1 : 7; uint32_t core_config : 24; #endif // _BIG_ENDIAN } fields; } ocb_ccsr_clr_t; typedef union ocb_ccsr_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t core_config : 24; uint32_t reserved_24_1 : 7; uint32_t change_in_progress : 1; #else uint32_t change_in_progress : 1; uint32_t reserved_24_1 : 7; uint32_t core_config : 24; #endif // _BIG_ENDIAN } fields; } ocb_ccsr_or_t; typedef union ocb_qcsr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t ex_config : 12; uint32_t reserved_12_301 : 19; uint32_t change_in_progress : 1; #else uint32_t change_in_progress : 1; uint32_t reserved_12_301 : 19; uint32_t ex_config : 12; #endif // _BIG_ENDIAN } fields; } ocb_qcsr_t; typedef union ocb_qcsr_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t ex_config : 12; uint32_t reserved_12_301 : 19; uint32_t change_in_progress : 1; #else uint32_t change_in_progress : 1; uint32_t reserved_12_301 : 19; uint32_t ex_config : 12; #endif // _BIG_ENDIAN } fields; } ocb_qcsr_clr_t; typedef union ocb_qcsr_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t ex_config : 12; uint32_t reserved_12_301 : 19; uint32_t change_in_progress : 1; #else uint32_t change_in_progress : 1; uint32_t reserved_12_301 : 19; uint32_t ex_config : 12; #endif // _BIG_ENDIAN } fields; } ocb_qcsr_or_t; typedef union ocb_qssr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t l2_stopped : 12; uint32_t l3_stopped : 12; uint32_t quad_stopped : 6; uint32_t reserved1 : 1; uint32_t stop_in_progress : 1; #else uint32_t stop_in_progress : 1; uint32_t reserved1 : 1; uint32_t quad_stopped : 6; uint32_t l3_stopped : 12; uint32_t l2_stopped : 12; #endif // _BIG_ENDIAN } fields; } ocb_qssr_t; typedef union ocb_qssr_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t l2_stopped : 12; uint32_t l3_stopped : 12; uint32_t quad_stopped : 6; uint32_t reserved1 : 1; uint32_t stop_in_progress : 1; #else uint32_t stop_in_progress : 1; uint32_t reserved1 : 1; uint32_t quad_stopped : 6; uint32_t l3_stopped : 12; uint32_t l2_stopped : 12; #endif // _BIG_ENDIAN } fields; } ocb_qssr_clr_t; typedef union ocb_qssr_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t l2_stopped : 12; uint32_t l3_stopped : 12; uint32_t quad_stopped : 6; uint32_t reserved1 : 1; uint32_t stop_in_progress : 1; #else uint32_t stop_in_progress : 1; uint32_t reserved1 : 1; uint32_t quad_stopped : 6; uint32_t l3_stopped : 12; uint32_t l2_stopped : 12; #endif // _BIG_ENDIAN } fields; } ocb_qssr_or_t; typedef union ocb_otbr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t ocb_timebase : 32; #else uint32_t ocb_timebase : 32; #endif // _BIG_ENDIAN } fields; } ocb_otbr_t; typedef union ocb_otrn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t timeout : 1; uint32_t control : 1; uint32_t auto_reload : 1; uint32_t spare : 13; uint32_t timer : 16; #else uint32_t timer : 16; uint32_t spare : 13; uint32_t auto_reload : 1; uint32_t control : 1; uint32_t timeout : 1; #endif // _BIG_ENDIAN } fields; } ocb_otrn_t; typedef union ocb_ocbslbrn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pull_oci_region : 3; uint32_t pull_start : 26; uint32_t reserved1 : 3; #else uint32_t reserved1 : 3; uint32_t pull_start : 26; uint32_t pull_oci_region : 3; #endif // _BIG_ENDIAN } fields; } ocb_ocbslbrn_t; typedef union ocb_ocbslcsn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pull_full : 1; uint32_t pull_empty : 1; uint32_t spare : 2; uint32_t pull_intr_action : 2; uint32_t pull_length : 5; uint32_t reserved1 : 2; uint32_t pull_write_ptr : 5; uint32_t reserved2 : 3; uint32_t pull_read_ptr : 5; uint32_t reserved3 : 5; uint32_t pull_enable : 1; #else uint32_t pull_enable : 1; uint32_t reserved3 : 5; uint32_t pull_read_ptr : 5; uint32_t reserved2 : 3; uint32_t pull_write_ptr : 5; uint32_t reserved1 : 2; uint32_t pull_length : 5; uint32_t pull_intr_action : 2; uint32_t spare : 2; uint32_t pull_empty : 1; uint32_t pull_full : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocbslcsn_t; typedef union ocb_ocbslin { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 32; #else uint32_t reserved1 : 32; #endif // _BIG_ENDIAN } fields; } ocb_ocbslin_t; typedef union ocb_ocbshbrn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t push_oci_region : 3; uint32_t push_start : 26; uint32_t reserved1 : 3; #else uint32_t reserved1 : 3; uint32_t push_start : 26; uint32_t push_oci_region : 3; #endif // _BIG_ENDIAN } fields; } ocb_ocbshbrn_t; typedef union ocb_ocbshcsn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t push_full : 1; uint32_t push_empty : 1; uint32_t spare : 2; uint32_t push_intr_action : 2; uint32_t push_length : 5; uint32_t reserved1 : 2; uint32_t push_write_ptr : 5; uint32_t reserved2 : 3; uint32_t push_read_ptr : 5; uint32_t reserved3 : 5; uint32_t push_enable : 1; #else uint32_t push_enable : 1; uint32_t reserved3 : 5; uint32_t push_read_ptr : 5; uint32_t reserved2 : 3; uint32_t push_write_ptr : 5; uint32_t reserved1 : 2; uint32_t push_length : 5; uint32_t push_intr_action : 2; uint32_t spare : 2; uint32_t push_empty : 1; uint32_t push_full : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocbshcsn_t; typedef union ocb_ocbshin { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 32; #else uint32_t reserved1 : 32; #endif // _BIG_ENDIAN } fields; } ocb_ocbshin_t; typedef union ocb_ocbsesn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t push_read_underflow : 1; uint32_t pull_write_overflow : 1; uint32_t reserved1 : 30; #else uint32_t reserved1 : 30; uint32_t pull_write_overflow : 1; uint32_t push_read_underflow : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocbsesn_t; typedef union ocb_ocblwcrn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t linear_window_enable : 1; uint32_t spare_0 : 2; uint32_t linear_window_bar : 17; uint32_t linear_window_mask : 12; #else uint32_t linear_window_mask : 12; uint32_t linear_window_bar : 17; uint32_t spare_0 : 2; uint32_t linear_window_enable : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocblwcrn_t; typedef union ocb_ocblwsrn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t linear_window_scresp : 3; uint32_t spare0 : 5; uint32_t reserved1 : 24; #else uint32_t reserved1 : 24; uint32_t spare0 : 5; uint32_t linear_window_scresp : 3; #endif // _BIG_ENDIAN } fields; } ocb_ocblwsrn_t; typedef union ocb_ocblwsbrn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t linear_window_region : 3; uint32_t linear_window_base : 7; uint32_t reserved1 : 22; #else uint32_t reserved1 : 22; uint32_t linear_window_base : 7; uint32_t linear_window_region : 3; #endif // _BIG_ENDIAN } fields; } ocb_ocblwsbrn_t; typedef union ocb_opit0cn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 20; uint32_t pcb_intr_type_a_core_n : 12; #else uint32_t pcb_intr_type_a_core_n : 12; uint32_t reserved1 : 20; #endif // _BIG_ENDIAN } fields; } ocb_opit0cn_t; typedef union ocb_opit1cn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 20; uint32_t pcb_intr_type_a_core_n : 12; #else uint32_t pcb_intr_type_a_core_n : 12; uint32_t reserved1 : 20; #endif // _BIG_ENDIAN } fields; } ocb_opit1cn_t; typedef union ocb_opit2cn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 20; uint32_t pcb_intr_type_a_core_n : 12; #else uint32_t pcb_intr_type_a_core_n : 12; uint32_t reserved1 : 20; #endif // _BIG_ENDIAN } fields; } ocb_opit2cn_t; typedef union ocb_opit3cn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 20; uint32_t pcb_intr_type_a_core_n : 12; #else uint32_t pcb_intr_type_a_core_n : 12; uint32_t reserved1 : 20; #endif // _BIG_ENDIAN } fields; } ocb_opit3cn_t; typedef union ocb_opit4cn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 20; uint32_t pcb_intr_type_a_core_n : 12; #else uint32_t pcb_intr_type_a_core_n : 12; uint32_t reserved1 : 20; #endif // _BIG_ENDIAN } fields; } ocb_opit4cn_t; typedef union ocb_opit5cn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 20; uint32_t pcb_intr_type_a_core_n : 12; #else uint32_t pcb_intr_type_a_core_n : 12; uint32_t reserved1 : 20; #endif // _BIG_ENDIAN } fields; } ocb_opit5cn_t; typedef union ocb_opit6qn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 28; uint32_t pcb_intr_type_a_quad_n : 4; #else uint32_t pcb_intr_type_a_quad_n : 4; uint32_t reserved1 : 28; #endif // _BIG_ENDIAN } fields; } ocb_opit6qn_t; typedef union ocb_opit7qn { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 31; uint32_t pcb_intr_type_a_quad_n : 1; #else uint32_t pcb_intr_type_a_quad_n : 1; uint32_t reserved1 : 31; #endif // _BIG_ENDIAN } fields; } ocb_opit7qn_t; typedef union ocb_opit0cnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_core_n : 10; #else uint32_t pcb_intr_type_a_reset_core_n : 10; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit0cnrp_t; typedef union ocb_opit1cnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_core_n : 10; #else uint32_t pcb_intr_type_a_reset_core_n : 10; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit1cnrp_t; typedef union ocb_opit2cnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_core_n : 10; #else uint32_t pcb_intr_type_a_reset_core_n : 10; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit2cnrp_t; typedef union ocb_opit3cnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_core_n : 10; #else uint32_t pcb_intr_type_a_reset_core_n : 10; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit3cnrp_t; typedef union ocb_opit4cnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_core_n : 10; #else uint32_t pcb_intr_type_a_reset_core_n : 10; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit4cnrp_t; typedef union ocb_opit5cnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_core_n : 10; #else uint32_t pcb_intr_type_a_reset_core_n : 10; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit5cnrp_t; typedef union ocb_opit6qnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_quad_n : 1; uint32_t reserved2 : 9; #else uint32_t reserved2 : 9; uint32_t pcb_intr_type_a_reset_quad_n : 1; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit6qnrp_t; typedef union ocb_opit7qnrp { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved1 : 22; uint32_t pcb_intr_type_a_reset_quad_n : 1; uint32_t reserved2 : 9; #else uint32_t reserved2 : 9; uint32_t pcb_intr_type_a_reset_quad_n : 1; uint32_t reserved1 : 22; #endif // _BIG_ENDIAN } fields; } ocb_opit7qnrp_t; typedef union ocb_opitnpra { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_6 : 1; uint32_t pcb_intr_type_n_pending_7 : 1; uint32_t pcb_intr_type_n_pending_8 : 1; uint32_t pcb_intr_type_n_pending_9 : 1; uint32_t pcb_intr_type_n_pending_10 : 1; uint32_t pcb_intr_type_n_pending_11 : 1; uint32_t pcb_intr_type_n_pending_12 : 1; uint32_t pcb_intr_type_n_pending_13 : 1; uint32_t pcb_intr_type_n_pending_14 : 1; uint32_t pcb_intr_type_n_pending_15 : 1; uint32_t pcb_intr_type_n_pending_16 : 1; uint32_t pcb_intr_type_n_pending_17 : 1; uint32_t pcb_intr_type_n_pending_18 : 1; uint32_t pcb_intr_type_n_pending_19 : 1; uint32_t pcb_intr_type_n_pending_20 : 1; uint32_t pcb_intr_type_n_pending_21 : 1; uint32_t pcb_intr_type_n_pending_22 : 1; uint32_t pcb_intr_type_n_pending_23 : 1; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t pcb_intr_type_n_pending_23 : 1; uint32_t pcb_intr_type_n_pending_22 : 1; uint32_t pcb_intr_type_n_pending_21 : 1; uint32_t pcb_intr_type_n_pending_20 : 1; uint32_t pcb_intr_type_n_pending_19 : 1; uint32_t pcb_intr_type_n_pending_18 : 1; uint32_t pcb_intr_type_n_pending_17 : 1; uint32_t pcb_intr_type_n_pending_16 : 1; uint32_t pcb_intr_type_n_pending_15 : 1; uint32_t pcb_intr_type_n_pending_14 : 1; uint32_t pcb_intr_type_n_pending_13 : 1; uint32_t pcb_intr_type_n_pending_12 : 1; uint32_t pcb_intr_type_n_pending_11 : 1; uint32_t pcb_intr_type_n_pending_10 : 1; uint32_t pcb_intr_type_n_pending_9 : 1; uint32_t pcb_intr_type_n_pending_8 : 1; uint32_t pcb_intr_type_n_pending_7 : 1; uint32_t pcb_intr_type_n_pending_6 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opitnpra_t; typedef union ocb_opitnpra_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_6 : 1; uint32_t pcb_intr_type_n_pending_7 : 1; uint32_t pcb_intr_type_n_pending_8 : 1; uint32_t pcb_intr_type_n_pending_9 : 1; uint32_t pcb_intr_type_n_pending_10 : 1; uint32_t pcb_intr_type_n_pending_11 : 1; uint32_t pcb_intr_type_n_pending_12 : 1; uint32_t pcb_intr_type_n_pending_13 : 1; uint32_t pcb_intr_type_n_pending_14 : 1; uint32_t pcb_intr_type_n_pending_15 : 1; uint32_t pcb_intr_type_n_pending_16 : 1; uint32_t pcb_intr_type_n_pending_17 : 1; uint32_t pcb_intr_type_n_pending_18 : 1; uint32_t pcb_intr_type_n_pending_19 : 1; uint32_t pcb_intr_type_n_pending_20 : 1; uint32_t pcb_intr_type_n_pending_21 : 1; uint32_t pcb_intr_type_n_pending_22 : 1; uint32_t pcb_intr_type_n_pending_23 : 1; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t pcb_intr_type_n_pending_23 : 1; uint32_t pcb_intr_type_n_pending_22 : 1; uint32_t pcb_intr_type_n_pending_21 : 1; uint32_t pcb_intr_type_n_pending_20 : 1; uint32_t pcb_intr_type_n_pending_19 : 1; uint32_t pcb_intr_type_n_pending_18 : 1; uint32_t pcb_intr_type_n_pending_17 : 1; uint32_t pcb_intr_type_n_pending_16 : 1; uint32_t pcb_intr_type_n_pending_15 : 1; uint32_t pcb_intr_type_n_pending_14 : 1; uint32_t pcb_intr_type_n_pending_13 : 1; uint32_t pcb_intr_type_n_pending_12 : 1; uint32_t pcb_intr_type_n_pending_11 : 1; uint32_t pcb_intr_type_n_pending_10 : 1; uint32_t pcb_intr_type_n_pending_9 : 1; uint32_t pcb_intr_type_n_pending_8 : 1; uint32_t pcb_intr_type_n_pending_7 : 1; uint32_t pcb_intr_type_n_pending_6 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opitnpra_clr_t; typedef union ocb_opitnpra_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_6 : 1; uint32_t pcb_intr_type_n_pending_7 : 1; uint32_t pcb_intr_type_n_pending_8 : 1; uint32_t pcb_intr_type_n_pending_9 : 1; uint32_t pcb_intr_type_n_pending_10 : 1; uint32_t pcb_intr_type_n_pending_11 : 1; uint32_t pcb_intr_type_n_pending_12 : 1; uint32_t pcb_intr_type_n_pending_13 : 1; uint32_t pcb_intr_type_n_pending_14 : 1; uint32_t pcb_intr_type_n_pending_15 : 1; uint32_t pcb_intr_type_n_pending_16 : 1; uint32_t pcb_intr_type_n_pending_17 : 1; uint32_t pcb_intr_type_n_pending_18 : 1; uint32_t pcb_intr_type_n_pending_19 : 1; uint32_t pcb_intr_type_n_pending_20 : 1; uint32_t pcb_intr_type_n_pending_21 : 1; uint32_t pcb_intr_type_n_pending_22 : 1; uint32_t pcb_intr_type_n_pending_23 : 1; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t pcb_intr_type_n_pending_23 : 1; uint32_t pcb_intr_type_n_pending_22 : 1; uint32_t pcb_intr_type_n_pending_21 : 1; uint32_t pcb_intr_type_n_pending_20 : 1; uint32_t pcb_intr_type_n_pending_19 : 1; uint32_t pcb_intr_type_n_pending_18 : 1; uint32_t pcb_intr_type_n_pending_17 : 1; uint32_t pcb_intr_type_n_pending_16 : 1; uint32_t pcb_intr_type_n_pending_15 : 1; uint32_t pcb_intr_type_n_pending_14 : 1; uint32_t pcb_intr_type_n_pending_13 : 1; uint32_t pcb_intr_type_n_pending_12 : 1; uint32_t pcb_intr_type_n_pending_11 : 1; uint32_t pcb_intr_type_n_pending_10 : 1; uint32_t pcb_intr_type_n_pending_9 : 1; uint32_t pcb_intr_type_n_pending_8 : 1; uint32_t pcb_intr_type_n_pending_7 : 1; uint32_t pcb_intr_type_n_pending_6 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opitnpra_or_t; typedef union ocb_opit6prb { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t reserved1 : 26; #else uint32_t reserved1 : 26; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opit6prb_t; typedef union ocb_opit6prb_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t reserved1 : 26; #else uint32_t reserved1 : 26; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opit6prb_clr_t; typedef union ocb_opit6prb_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t reserved1 : 26; #else uint32_t reserved1 : 26; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opit6prb_or_t; typedef union ocb_opit7prb { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t reserved1 : 26; #else uint32_t reserved1 : 26; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opit7prb_t; typedef union ocb_opit7prb_clr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t reserved1 : 26; #else uint32_t reserved1 : 26; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opit7prb_clr_t; typedef union ocb_opit7prb_or { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t pcb_intr_type_n_pending_0 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t reserved1 : 26; #else uint32_t reserved1 : 26; uint32_t pcb_intr_type_n_pending_5 : 1; uint32_t pcb_intr_type_n_pending_4 : 1; uint32_t pcb_intr_type_n_pending_3 : 1; uint32_t pcb_intr_type_n_pending_2 : 1; uint32_t pcb_intr_type_n_pending_1 : 1; uint32_t pcb_intr_type_n_pending_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_opit7prb_or_t; typedef union ocb_o2sctrlf0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_frame_size_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_in_count1_an : 6; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t o2s_in_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_frame_size_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrlf0a_t; typedef union ocb_o2sctrls0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_out_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_in_count2_an : 6; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_in_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_out_count2_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrls0a_t; typedef union ocb_o2sctrl10a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_bridge_enable_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_cpol_an : 1; uint32_t o2s_cpha_an : 1; uint32_t o2s_clock_divider_an : 10; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_nr_of_frames_an : 1; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_nr_of_frames_an : 1; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_clock_divider_an : 10; uint32_t o2s_cpha_an : 1; uint32_t o2s_cpol_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_bridge_enable_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl10a_t; typedef union ocb_o2sctrl20a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_inter_frame_delay_an : 17; uint32_t reserved1 : 15; #else uint32_t reserved1 : 15; uint32_t o2s_inter_frame_delay_an : 17; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl20a_t; typedef union ocb_o2sst0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_ongoing_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_fsm_err_an : 1; uint32_t reserved1 : 24; #else uint32_t reserved1 : 24; uint32_t o2s_fsm_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_ongoing_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sst0a_t; typedef union ocb_o2scmd0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2scmdan_reserved_0 : 1; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t reserved1 : 30; #else uint32_t reserved1 : 30; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t o2scmdan_reserved_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2scmd0a_t; typedef union ocb_o2swd0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_wdata_an : 32; #else uint32_t o2s_wdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2swd0a_t; typedef union ocb_o2srd0a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_rdata_an : 32; #else uint32_t o2s_rdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2srd0a_t; typedef union ocb_o2sctrlf0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_frame_size_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_in_count1_an : 6; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t o2s_in_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_frame_size_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrlf0b_t; typedef union ocb_o2sctrls0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_out_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_in_count2_an : 6; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_in_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_out_count2_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrls0b_t; typedef union ocb_o2sctrl10b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_bridge_enable_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_cpol_an : 1; uint32_t o2s_cpha_an : 1; uint32_t o2s_clock_divider_an : 10; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_nr_of_frames_an : 1; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_nr_of_frames_an : 1; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_clock_divider_an : 10; uint32_t o2s_cpha_an : 1; uint32_t o2s_cpol_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_bridge_enable_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl10b_t; typedef union ocb_o2sctrl20b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_inter_frame_delay_an : 17; uint32_t reserved1 : 15; #else uint32_t reserved1 : 15; uint32_t o2s_inter_frame_delay_an : 17; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl20b_t; typedef union ocb_o2sst0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_ongoing_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_fsm_err_an : 1; uint32_t reserved1 : 24; #else uint32_t reserved1 : 24; uint32_t o2s_fsm_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_ongoing_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sst0b_t; typedef union ocb_o2scmd0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2scmdan_reserved_0 : 1; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t reserved1 : 30; #else uint32_t reserved1 : 30; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t o2scmdan_reserved_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2scmd0b_t; typedef union ocb_o2swd0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_wdata_an : 32; #else uint32_t o2s_wdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2swd0b_t; typedef union ocb_o2srd0b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_rdata_an : 32; #else uint32_t o2s_rdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2srd0b_t; typedef union ocb_o2sctrlf1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_frame_size_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_in_count1_an : 6; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t o2s_in_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_frame_size_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrlf1a_t; typedef union ocb_o2sctrls1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_out_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_in_count2_an : 6; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_in_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_out_count2_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrls1a_t; typedef union ocb_o2sctrl11a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_bridge_enable_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_cpol_an : 1; uint32_t o2s_cpha_an : 1; uint32_t o2s_clock_divider_an : 10; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_nr_of_frames_an : 1; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_nr_of_frames_an : 1; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_clock_divider_an : 10; uint32_t o2s_cpha_an : 1; uint32_t o2s_cpol_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_bridge_enable_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl11a_t; typedef union ocb_o2sctrl21a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_inter_frame_delay_an : 17; uint32_t reserved1 : 15; #else uint32_t reserved1 : 15; uint32_t o2s_inter_frame_delay_an : 17; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl21a_t; typedef union ocb_o2sst1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_ongoing_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_fsm_err_an : 1; uint32_t reserved1 : 24; #else uint32_t reserved1 : 24; uint32_t o2s_fsm_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_ongoing_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sst1a_t; typedef union ocb_o2scmd1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2scmdan_reserved_0 : 1; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t reserved1 : 30; #else uint32_t reserved1 : 30; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t o2scmdan_reserved_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2scmd1a_t; typedef union ocb_o2swd1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_wdata_an : 32; #else uint32_t o2s_wdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2swd1a_t; typedef union ocb_o2srd1a { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_rdata_an : 32; #else uint32_t o2s_rdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2srd1a_t; typedef union ocb_o2sctrlf1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_frame_size_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_in_count1_an : 6; uint32_t reserved1 : 8; #else uint32_t reserved1 : 8; uint32_t o2s_in_count1_an : 6; uint32_t o2s_in_delay1_an : 6; uint32_t o2s_out_count1_an : 6; uint32_t o2s_frame_size_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrlf1b_t; typedef union ocb_o2sctrls1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_out_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_in_count2_an : 6; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_in_count2_an : 6; uint32_t o2s_in_delay2_an : 6; uint32_t o2s_out_count2_an : 6; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrls1b_t; typedef union ocb_o2sctrl11b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_bridge_enable_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_cpol_an : 1; uint32_t o2s_cpha_an : 1; uint32_t o2s_clock_divider_an : 10; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_nr_of_frames_an : 1; uint32_t reserved1 : 14; #else uint32_t reserved1 : 14; uint32_t o2s_nr_of_frames_an : 1; uint32_t o2sctrl1an_reserved_14_16 : 3; uint32_t o2s_clock_divider_an : 10; uint32_t o2s_cpha_an : 1; uint32_t o2s_cpol_an : 1; uint32_t o2sctrl1an_reserved_1 : 1; uint32_t o2s_bridge_enable_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl11b_t; typedef union ocb_o2sctrl21b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_inter_frame_delay_an : 17; uint32_t reserved1 : 15; #else uint32_t reserved1 : 15; uint32_t o2s_inter_frame_delay_an : 17; #endif // _BIG_ENDIAN } fields; } ocb_o2sctrl21b_t; typedef union ocb_o2sst1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_ongoing_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_fsm_err_an : 1; uint32_t reserved1 : 24; #else uint32_t reserved1 : 24; uint32_t o2s_fsm_err_an : 1; uint32_t o2sstan_reserved_6 : 1; uint32_t o2s_write_while_bridge_busy_err_an : 1; uint32_t o2sstan_reserved_1_4 : 4; uint32_t o2s_ongoing_an : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2sst1b_t; typedef union ocb_o2scmd1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2scmdan_reserved_0 : 1; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t reserved1 : 30; #else uint32_t reserved1 : 30; uint32_t o2s_clear_sticky_bits_an : 1; uint32_t o2scmdan_reserved_0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_o2scmd1b_t; typedef union ocb_o2swd1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_wdata_an : 32; #else uint32_t o2s_wdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2swd1b_t; typedef union ocb_o2srd1b { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t o2s_rdata_an : 32; #else uint32_t o2s_rdata_an : 32; #endif // _BIG_ENDIAN } fields; } ocb_o2srd1b_t; typedef union ocb_ocr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t core_reset : 1; uint64_t chip_reset : 1; uint64_t system_reset : 1; uint64_t oci_arb_reset : 1; uint64_t trace_disable : 1; uint64_t trace_event : 1; uint64_t dbg_unconditional_event : 1; uint64_t ext_interrupt : 1; uint64_t critical_interrupt : 1; uint64_t pib_slave_reset_to_405_enable : 1; uint64_t ocr_dbg_halt : 1; uint64_t spare : 5; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare : 5; uint64_t ocr_dbg_halt : 1; uint64_t pib_slave_reset_to_405_enable : 1; uint64_t critical_interrupt : 1; uint64_t ext_interrupt : 1; uint64_t dbg_unconditional_event : 1; uint64_t trace_event : 1; uint64_t trace_disable : 1; uint64_t oci_arb_reset : 1; uint64_t system_reset : 1; uint64_t chip_reset : 1; uint64_t core_reset : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocr_t; typedef union ocb_ocr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t core_reset : 1; uint64_t chip_reset : 1; uint64_t system_reset : 1; uint64_t oci_arb_reset : 1; uint64_t trace_disable : 1; uint64_t trace_event : 1; uint64_t dbg_unconditional_event : 1; uint64_t ext_interrupt : 1; uint64_t critical_interrupt : 1; uint64_t pib_slave_reset_to_405_enable : 1; uint64_t ocr_dbg_halt : 1; uint64_t spare : 5; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare : 5; uint64_t ocr_dbg_halt : 1; uint64_t pib_slave_reset_to_405_enable : 1; uint64_t critical_interrupt : 1; uint64_t ext_interrupt : 1; uint64_t dbg_unconditional_event : 1; uint64_t trace_event : 1; uint64_t trace_disable : 1; uint64_t oci_arb_reset : 1; uint64_t system_reset : 1; uint64_t chip_reset : 1; uint64_t core_reset : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocr_clr_t; typedef union ocb_ocr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t core_reset : 1; uint64_t chip_reset : 1; uint64_t system_reset : 1; uint64_t oci_arb_reset : 1; uint64_t trace_disable : 1; uint64_t trace_event : 1; uint64_t dbg_unconditional_event : 1; uint64_t ext_interrupt : 1; uint64_t critical_interrupt : 1; uint64_t pib_slave_reset_to_405_enable : 1; uint64_t ocr_dbg_halt : 1; uint64_t spare : 5; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare : 5; uint64_t ocr_dbg_halt : 1; uint64_t pib_slave_reset_to_405_enable : 1; uint64_t critical_interrupt : 1; uint64_t ext_interrupt : 1; uint64_t dbg_unconditional_event : 1; uint64_t trace_event : 1; uint64_t trace_disable : 1; uint64_t oci_arb_reset : 1; uint64_t system_reset : 1; uint64_t chip_reset : 1; uint64_t core_reset : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocr_or_t; typedef union ocb_ocdbg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t mst_dis_abusparen : 1; uint64_t mst_dis_beparen : 1; uint64_t mst_dis_wrdbusparen : 1; uint64_t mst_dis_rddbuspar : 1; uint64_t mst_spare : 1; uint64_t slv_dis_sack : 1; uint64_t slv_dis_abuspar : 1; uint64_t slv_dis_bepar : 1; uint64_t slv_dis_be : 1; uint64_t slv_dis_wrdbuspar : 1; uint64_t slv_dis_rddbusparen : 1; uint64_t slv_spare : 1; uint64_t spare : 4; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare : 4; uint64_t slv_spare : 1; uint64_t slv_dis_rddbusparen : 1; uint64_t slv_dis_wrdbuspar : 1; uint64_t slv_dis_be : 1; uint64_t slv_dis_bepar : 1; uint64_t slv_dis_abuspar : 1; uint64_t slv_dis_sack : 1; uint64_t mst_spare : 1; uint64_t mst_dis_rddbuspar : 1; uint64_t mst_dis_wrdbusparen : 1; uint64_t mst_dis_beparen : 1; uint64_t mst_dis_abusparen : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocdbg_t; typedef union ocb_ojcfg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t jtag_src_sel : 1; uint64_t run_tck : 1; uint64_t tck_width : 3; uint64_t jtag_trst_b : 1; uint64_t dbg_halt : 1; uint64_t reserved1 : 57; #else uint64_t reserved1 : 57; uint64_t dbg_halt : 1; uint64_t jtag_trst_b : 1; uint64_t tck_width : 3; uint64_t run_tck : 1; uint64_t jtag_src_sel : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojcfg_t; typedef union ocb_ojcfg_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t jtag_src_sel : 1; uint64_t run_tck : 1; uint64_t tck_width : 3; uint64_t jtag_trst_b : 1; uint64_t dbg_halt : 1; uint64_t reserved1 : 57; #else uint64_t reserved1 : 57; uint64_t dbg_halt : 1; uint64_t jtag_trst_b : 1; uint64_t tck_width : 3; uint64_t run_tck : 1; uint64_t jtag_src_sel : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojcfg_clr_t; typedef union ocb_ojcfg_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t jtag_src_sel : 1; uint64_t run_tck : 1; uint64_t tck_width : 3; uint64_t jtag_trst_b : 1; uint64_t dbg_halt : 1; uint64_t reserved1 : 57; #else uint64_t reserved1 : 57; uint64_t dbg_halt : 1; uint64_t jtag_trst_b : 1; uint64_t tck_width : 3; uint64_t run_tck : 1; uint64_t jtag_src_sel : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojcfg_or_t; typedef union ocb_ojfrst { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 64; #else uint64_t reserved1 : 64; #endif // _BIG_ENDIAN } fields; } ocb_ojfrst_t; typedef union ocb_ojic { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t start_jtag_cmd : 1; uint64_t do_ir : 1; uint64_t do_dr : 1; uint64_t do_tap_reset : 1; uint64_t wr_valid : 1; uint64_t reserved1 : 7; uint64_t jtag_instr : 4; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t jtag_instr : 4; uint64_t reserved1 : 7; uint64_t wr_valid : 1; uint64_t do_tap_reset : 1; uint64_t do_dr : 1; uint64_t do_ir : 1; uint64_t start_jtag_cmd : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojic_t; typedef union ocb_ojic_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t start_jtag_cmd : 1; uint64_t do_ir : 1; uint64_t do_dr : 1; uint64_t do_tap_reset : 1; uint64_t wr_valid : 1; uint64_t reserved1 : 7; uint64_t jtag_instr : 4; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t jtag_instr : 4; uint64_t reserved1 : 7; uint64_t wr_valid : 1; uint64_t do_tap_reset : 1; uint64_t do_dr : 1; uint64_t do_ir : 1; uint64_t start_jtag_cmd : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojic_clr_t; typedef union ocb_ojic_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t start_jtag_cmd : 1; uint64_t do_ir : 1; uint64_t do_dr : 1; uint64_t do_tap_reset : 1; uint64_t wr_valid : 1; uint64_t reserved1 : 7; uint64_t jtag_instr : 4; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t jtag_instr : 4; uint64_t reserved1 : 7; uint64_t wr_valid : 1; uint64_t do_tap_reset : 1; uint64_t do_dr : 1; uint64_t do_ir : 1; uint64_t start_jtag_cmd : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojic_or_t; typedef union ocb_ojstat { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t jtag_inprog : 1; uint64_t src_sel_eq1_err : 1; uint64_t run_tck_eq0_err : 1; uint64_t trst_b_eq0_err : 1; uint64_t ir_dr_eq0_err : 1; uint64_t inprog_wr_err : 1; uint64_t fsm_error : 1; uint64_t reserved1 : 57; #else uint64_t reserved1 : 57; uint64_t fsm_error : 1; uint64_t inprog_wr_err : 1; uint64_t ir_dr_eq0_err : 1; uint64_t trst_b_eq0_err : 1; uint64_t run_tck_eq0_err : 1; uint64_t src_sel_eq1_err : 1; uint64_t jtag_inprog : 1; #endif // _BIG_ENDIAN } fields; } ocb_ojstat_t; typedef union ocb_ojtdi { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t jtag_tdi : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t jtag_tdi : 32; #endif // _BIG_ENDIAN } fields; } ocb_ojtdi_t; typedef union ocb_ojtdo { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t jtag_tdo : 32; uint64_t jtag_src_sel : 1; uint64_t run_tck : 1; uint64_t tck_width : 3; uint64_t jtag_trst_b : 1; uint64_t dbg_halt : 1; uint64_t reserved1 : 1; uint64_t jtag_inprog : 1; uint64_t src_sel_eq1_err : 1; uint64_t run_tck_eq0_err : 1; uint64_t trst_b_eq0_err : 1; uint64_t ir_dr_eq0_err : 1; uint64_t inprog_wr_err : 1; uint64_t fsm_error : 1; uint64_t reserved2 : 2; uint64_t do_ir : 1; uint64_t do_dr : 1; uint64_t do_tap_reset : 1; uint64_t wr_valid : 1; uint64_t reserved3 : 7; uint64_t jtag_instr : 4; #else uint64_t jtag_instr : 4; uint64_t reserved3 : 7; uint64_t wr_valid : 1; uint64_t do_tap_reset : 1; uint64_t do_dr : 1; uint64_t do_ir : 1; uint64_t reserved2 : 2; uint64_t fsm_error : 1; uint64_t inprog_wr_err : 1; uint64_t ir_dr_eq0_err : 1; uint64_t trst_b_eq0_err : 1; uint64_t run_tck_eq0_err : 1; uint64_t src_sel_eq1_err : 1; uint64_t jtag_inprog : 1; uint64_t reserved1 : 1; uint64_t dbg_halt : 1; uint64_t jtag_trst_b : 1; uint64_t tck_width : 3; uint64_t run_tck : 1; uint64_t jtag_src_sel : 1; uint64_t jtag_tdo : 32; #endif // _BIG_ENDIAN } fields; } ocb_ojtdo_t; typedef union ocb_ocbarn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t oci_region : 3; uint64_t ocb_address : 26; uint64_t reserved1 : 35; #else uint64_t reserved1 : 35; uint64_t ocb_address : 26; uint64_t oci_region : 3; #endif // _BIG_ENDIAN } fields; } ocb_ocbarn_t; typedef union ocb_ocbcsrn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pull_read_underflow : 1; uint64_t push_write_overflow : 1; uint64_t pull_read_underflow_en : 1; uint64_t push_write_overflow_en : 1; uint64_t ocb_stream_mode : 1; uint64_t ocb_stream_type : 1; uint64_t spare0 : 2; uint64_t ocb_oci_timeout : 1; uint64_t ocb_oci_read_data_parity : 1; uint64_t ocb_oci_slave_error : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_pib_data_parity_err : 1; uint64_t spare1 : 1; uint64_t ocb_fsm_err : 1; uint64_t spare2 : 1; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare2 : 1; uint64_t ocb_fsm_err : 1; uint64_t spare1 : 1; uint64_t ocb_pib_data_parity_err : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_oci_slave_error : 1; uint64_t ocb_oci_read_data_parity : 1; uint64_t ocb_oci_timeout : 1; uint64_t spare0 : 2; uint64_t ocb_stream_type : 1; uint64_t ocb_stream_mode : 1; uint64_t push_write_overflow_en : 1; uint64_t pull_read_underflow_en : 1; uint64_t push_write_overflow : 1; uint64_t pull_read_underflow : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocbcsrn_t; typedef union ocb_ocbcsrn_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pull_read_underflow : 1; uint64_t push_write_overflow : 1; uint64_t pull_read_underflow_en : 1; uint64_t push_write_overflow_en : 1; uint64_t ocb_stream_mode : 1; uint64_t ocb_stream_type : 1; uint64_t spare0 : 2; uint64_t ocb_oci_timeout : 1; uint64_t ocb_oci_read_data_parity : 1; uint64_t ocb_oci_slave_error : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_pib_data_parity_err : 1; uint64_t spare1 : 1; uint64_t ocb_fsm_err : 1; uint64_t spare2 : 1; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare2 : 1; uint64_t ocb_fsm_err : 1; uint64_t spare1 : 1; uint64_t ocb_pib_data_parity_err : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_oci_slave_error : 1; uint64_t ocb_oci_read_data_parity : 1; uint64_t ocb_oci_timeout : 1; uint64_t spare0 : 2; uint64_t ocb_stream_type : 1; uint64_t ocb_stream_mode : 1; uint64_t push_write_overflow_en : 1; uint64_t pull_read_underflow_en : 1; uint64_t push_write_overflow : 1; uint64_t pull_read_underflow : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocbcsrn_clr_t; typedef union ocb_ocbcsrn_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pull_read_underflow : 1; uint64_t push_write_overflow : 1; uint64_t pull_read_underflow_en : 1; uint64_t push_write_overflow_en : 1; uint64_t ocb_stream_mode : 1; uint64_t ocb_stream_type : 1; uint64_t spare0 : 2; uint64_t ocb_oci_timeout : 1; uint64_t ocb_oci_read_data_parity : 1; uint64_t ocb_oci_slave_error : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_pib_data_parity_err : 1; uint64_t spare1 : 1; uint64_t ocb_fsm_err : 1; uint64_t spare2 : 1; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t spare2 : 1; uint64_t ocb_fsm_err : 1; uint64_t spare1 : 1; uint64_t ocb_pib_data_parity_err : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_oci_slave_error : 1; uint64_t ocb_oci_read_data_parity : 1; uint64_t ocb_oci_timeout : 1; uint64_t spare0 : 2; uint64_t ocb_stream_type : 1; uint64_t ocb_stream_mode : 1; uint64_t push_write_overflow_en : 1; uint64_t pull_read_underflow_en : 1; uint64_t push_write_overflow : 1; uint64_t pull_read_underflow : 1; #endif // _BIG_ENDIAN } fields; } ocb_ocbcsrn_or_t; typedef union ocb_ocbesrn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ocb_error_addr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ocb_error_addr : 32; #endif // _BIG_ENDIAN } fields; } ocb_ocbesrn_t; typedef union ocb_ocbdrn { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ocb_data : 64; #else uint64_t ocb_data : 64; #endif // _BIG_ENDIAN } fields; } ocb_ocbdrn_t; typedef union ocb_otdcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t trace_bus_en : 1; uint64_t ocb_trace_mux_sel : 1; uint64_t occ_trace_mux_sel : 2; uint64_t oci_trace_mux_sel : 4; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t oci_trace_mux_sel : 4; uint64_t occ_trace_mux_sel : 2; uint64_t ocb_trace_mux_sel : 1; uint64_t trace_bus_en : 1; #endif // _BIG_ENDIAN } fields; } ocb_otdcr_t; typedef union ocb_oppcinj { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t oci_err_inj_dcu : 1; uint64_t oci_err_inj_icu : 1; uint64_t oci_err_inj_ce_ue : 1; uint64_t oci_err_inj_singl_cont : 1; uint64_t reserved1 : 60; #else uint64_t reserved1 : 60; uint64_t oci_err_inj_singl_cont : 1; uint64_t oci_err_inj_ce_ue : 1; uint64_t oci_err_inj_icu : 1; uint64_t oci_err_inj_dcu : 1; #endif // _BIG_ENDIAN } fields; } ocb_oppcinj_t; typedef union ocb_ostoear { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_spcl_timeout_addr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t occ_spcl_timeout_addr : 32; #endif // _BIG_ENDIAN } fields; } ocb_ostoear_t; typedef union ocb_ostoesr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t icu_timeout_error : 1; uint64_t icu_rnw : 1; uint64_t reserved1 : 2; uint64_t dcu_timeout_error : 1; uint64_t dcu_rnw : 1; uint64_t reserved2 : 58; #else uint64_t reserved2 : 58; uint64_t dcu_rnw : 1; uint64_t dcu_timeout_error : 1; uint64_t reserved1 : 2; uint64_t icu_rnw : 1; uint64_t icu_timeout_error : 1; #endif // _BIG_ENDIAN } fields; } ocb_ostoesr_t; typedef union ocb_orev { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t oci_arb_revision : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t oci_arb_revision : 32; #endif // _BIG_ENDIAN } fields; } ocb_orev_t; typedef union ocb_oesr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t oci_m0_timeout_error : 1; uint64_t oci_m0_rw_status : 1; uint64_t oci_m0_oesr_flck : 1; uint64_t oci_m0_oear_lock : 1; uint64_t oci_m1_timeout_error : 1; uint64_t oci_m1_rw_status : 1; uint64_t oci_m1_oesr_flck : 1; uint64_t oci_m1_oear_lock : 1; uint64_t oci_m2_timeout_error : 1; uint64_t oci_m2_rw_status : 1; uint64_t oci_m2_oesr_flck : 1; uint64_t oci_m2_oear_lock : 1; uint64_t oci_m3_timeout_error : 1; uint64_t oci_m3_rw_status : 1; uint64_t oci_m3_oesr_flck : 1; uint64_t oci_m3_oear_lock : 1; uint64_t oci_m4_timeout_error : 1; uint64_t oci_m4_rw_status : 1; uint64_t oci_m4_oesr_flck : 1; uint64_t oci_m4_oear_lock : 1; uint64_t oci_m5_timeout_error : 1; uint64_t oci_m5_rw_status : 1; uint64_t oci_m5_oesr_flck : 1; uint64_t oci_m5_oear_lock : 1; uint64_t oci_m6_timeout_error : 1; uint64_t oci_m6_rw_status : 1; uint64_t oci_m6_oesr_flck : 1; uint64_t oci_m6_oear_lock : 1; uint64_t oci_m7_timeout_error : 1; uint64_t oci_m7_rw_status : 1; uint64_t oci_m7_oesr_flck : 1; uint64_t oci_m7_oear_lock : 1; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t oci_m7_oear_lock : 1; uint64_t oci_m7_oesr_flck : 1; uint64_t oci_m7_rw_status : 1; uint64_t oci_m7_timeout_error : 1; uint64_t oci_m6_oear_lock : 1; uint64_t oci_m6_oesr_flck : 1; uint64_t oci_m6_rw_status : 1; uint64_t oci_m6_timeout_error : 1; uint64_t oci_m5_oear_lock : 1; uint64_t oci_m5_oesr_flck : 1; uint64_t oci_m5_rw_status : 1; uint64_t oci_m5_timeout_error : 1; uint64_t oci_m4_oear_lock : 1; uint64_t oci_m4_oesr_flck : 1; uint64_t oci_m4_rw_status : 1; uint64_t oci_m4_timeout_error : 1; uint64_t oci_m3_oear_lock : 1; uint64_t oci_m3_oesr_flck : 1; uint64_t oci_m3_rw_status : 1; uint64_t oci_m3_timeout_error : 1; uint64_t oci_m2_oear_lock : 1; uint64_t oci_m2_oesr_flck : 1; uint64_t oci_m2_rw_status : 1; uint64_t oci_m2_timeout_error : 1; uint64_t oci_m1_oear_lock : 1; uint64_t oci_m1_oesr_flck : 1; uint64_t oci_m1_rw_status : 1; uint64_t oci_m1_timeout_error : 1; uint64_t oci_m0_oear_lock : 1; uint64_t oci_m0_oesr_flck : 1; uint64_t oci_m0_rw_status : 1; uint64_t oci_m0_timeout_error : 1; #endif // _BIG_ENDIAN } fields; } ocb_oesr_t; typedef union ocb_oear { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t oci_timeout_addr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t oci_timeout_addr : 32; #endif // _BIG_ENDIAN } fields; } ocb_oear_t; typedef union ocb_oacr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t oci_priority_mode : 1; uint64_t oci_priority_order : 3; uint64_t oci_hi_bus_mode : 1; uint64_t oci_read_pipeline_control : 2; uint64_t oci_write_pipeline_control : 1; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t oci_write_pipeline_control : 1; uint64_t oci_read_pipeline_control : 2; uint64_t oci_hi_bus_mode : 1; uint64_t oci_priority_order : 3; uint64_t oci_priority_mode : 1; #endif // _BIG_ENDIAN } fields; } ocb_oacr_t; typedef union ocb_ocbear { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ocb_error_address : 32; uint64_t reserved1 : 3; uint64_t direct_bridge_source : 1; uint64_t indirect_bridge_0_source : 1; uint64_t indirect_bridge_1_source : 1; uint64_t indirect_bridge_2_source : 1; uint64_t indirect_bridge_3_source : 1; uint64_t reserved2 : 24; #else uint64_t reserved2 : 24; uint64_t indirect_bridge_3_source : 1; uint64_t indirect_bridge_2_source : 1; uint64_t indirect_bridge_1_source : 1; uint64_t indirect_bridge_0_source : 1; uint64_t direct_bridge_source : 1; uint64_t reserved1 : 3; uint64_t ocb_error_address : 32; #endif // _BIG_ENDIAN } fields; } ocb_ocbear_t; typedef union ocb_occlfir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_fw0 : 1; uint64_t occ_fw1 : 1; uint64_t cme_error_notify : 1; uint64_t stop_recovery_notify_prd : 1; uint64_t occ_hb_error : 1; uint64_t gpe0_watchdog_timeout : 1; uint64_t gpe1_watchdog_timeout : 1; uint64_t gpe2_watchdog_timeout : 1; uint64_t gpe3_watchdog_timeout : 1; uint64_t gpe0_error : 1; uint64_t gpe1_error : 1; uint64_t gpe2_error : 1; uint64_t gpe3_error : 1; uint64_t ocb_error : 1; uint64_t srt_ue : 1; uint64_t srt_ce : 1; uint64_t srt_read_error : 1; uint64_t srt_write_error : 1; uint64_t srt_dataout_perr : 1; uint64_t srt_oci_write_data_parity : 1; uint64_t srt_oci_be_parity_err : 1; uint64_t srt_oci_addr_parity_err : 1; uint64_t gpe0_halted : 1; uint64_t gpe1_halted : 1; uint64_t gpe2_halted : 1; uint64_t gpe3_halted : 1; uint64_t external_trap : 1; uint64_t ppc405_core_reset : 1; uint64_t ppc405_chip_reset : 1; uint64_t ppc405_system_reset : 1; uint64_t ppc405_dbgmsrwe : 1; uint64_t ppc405_dbgstopack : 1; uint64_t ocb_db_oci_timeout : 1; uint64_t ocb_db_oci_read_data_parity : 1; uint64_t ocb_db_oci_slave_error : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_db_pib_data_parity_err : 1; uint64_t ocb_idc0_error : 1; uint64_t ocb_idc1_error : 1; uint64_t ocb_idc2_error : 1; uint64_t ocb_idc3_error : 1; uint64_t srt_fsm_err : 1; uint64_t jtagacc_err : 1; uint64_t spare_err_38 : 1; uint64_t c405_ecc_ue : 1; uint64_t c405_ecc_ce : 1; uint64_t c405_oci_machinecheck : 1; uint64_t sram_spare_direct_error0 : 1; uint64_t sram_spare_direct_error1 : 1; uint64_t sram_spare_direct_error2 : 1; uint64_t sram_spare_direct_error3 : 1; uint64_t gpe0_ocislv_err : 1; uint64_t gpe1_ocislv_err : 1; uint64_t gpe2_ocislv_err : 1; uint64_t gpe3_ocislv_err : 1; uint64_t c405icu_m_timeout : 1; uint64_t c405dcu_m_timeout : 1; uint64_t occ_complex_fault_safe : 1; uint64_t spare_58_61 : 4; uint64_t fir_parity_err_dup : 1; uint64_t fir_parity_err : 1; #else uint64_t fir_parity_err : 1; uint64_t fir_parity_err_dup : 1; uint64_t spare_58_61 : 4; uint64_t occ_complex_fault_safe : 1; uint64_t c405dcu_m_timeout : 1; uint64_t c405icu_m_timeout : 1; uint64_t gpe3_ocislv_err : 1; uint64_t gpe2_ocislv_err : 1; uint64_t gpe1_ocislv_err : 1; uint64_t gpe0_ocislv_err : 1; uint64_t sram_spare_direct_error3 : 1; uint64_t sram_spare_direct_error2 : 1; uint64_t sram_spare_direct_error1 : 1; uint64_t sram_spare_direct_error0 : 1; uint64_t c405_oci_machinecheck : 1; uint64_t c405_ecc_ce : 1; uint64_t c405_ecc_ue : 1; uint64_t spare_err_38 : 1; uint64_t jtagacc_err : 1; uint64_t srt_fsm_err : 1; uint64_t ocb_idc3_error : 1; uint64_t ocb_idc2_error : 1; uint64_t ocb_idc1_error : 1; uint64_t ocb_idc0_error : 1; uint64_t ocb_db_pib_data_parity_err : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_db_oci_slave_error : 1; uint64_t ocb_db_oci_read_data_parity : 1; uint64_t ocb_db_oci_timeout : 1; uint64_t ppc405_dbgstopack : 1; uint64_t ppc405_dbgmsrwe : 1; uint64_t ppc405_system_reset : 1; uint64_t ppc405_chip_reset : 1; uint64_t ppc405_core_reset : 1; uint64_t external_trap : 1; uint64_t gpe3_halted : 1; uint64_t gpe2_halted : 1; uint64_t gpe1_halted : 1; uint64_t gpe0_halted : 1; uint64_t srt_oci_addr_parity_err : 1; uint64_t srt_oci_be_parity_err : 1; uint64_t srt_oci_write_data_parity : 1; uint64_t srt_dataout_perr : 1; uint64_t srt_write_error : 1; uint64_t srt_read_error : 1; uint64_t srt_ce : 1; uint64_t srt_ue : 1; uint64_t ocb_error : 1; uint64_t gpe3_error : 1; uint64_t gpe2_error : 1; uint64_t gpe1_error : 1; uint64_t gpe0_error : 1; uint64_t gpe3_watchdog_timeout : 1; uint64_t gpe2_watchdog_timeout : 1; uint64_t gpe1_watchdog_timeout : 1; uint64_t gpe0_watchdog_timeout : 1; uint64_t occ_hb_error : 1; uint64_t stop_recovery_notify_prd : 1; uint64_t cme_error_notify : 1; uint64_t occ_fw1 : 1; uint64_t occ_fw0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_occlfir_t; typedef union ocb_occlfir_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_fw0 : 1; uint64_t occ_fw1 : 1; uint64_t cme_error_notify : 1; uint64_t stop_recovery_notify_prd : 1; uint64_t occ_hb_error : 1; uint64_t gpe0_watchdog_timeout : 1; uint64_t gpe1_watchdog_timeout : 1; uint64_t gpe2_watchdog_timeout : 1; uint64_t gpe3_watchdog_timeout : 1; uint64_t gpe0_error : 1; uint64_t gpe1_error : 1; uint64_t gpe2_error : 1; uint64_t gpe3_error : 1; uint64_t ocb_error : 1; uint64_t srt_ue : 1; uint64_t srt_ce : 1; uint64_t srt_read_error : 1; uint64_t srt_write_error : 1; uint64_t srt_dataout_perr : 1; uint64_t srt_oci_write_data_parity : 1; uint64_t srt_oci_be_parity_err : 1; uint64_t srt_oci_addr_parity_err : 1; uint64_t gpe0_halted : 1; uint64_t gpe1_halted : 1; uint64_t gpe2_halted : 1; uint64_t gpe3_halted : 1; uint64_t external_trap : 1; uint64_t ppc405_core_reset : 1; uint64_t ppc405_chip_reset : 1; uint64_t ppc405_system_reset : 1; uint64_t ppc405_dbgmsrwe : 1; uint64_t ppc405_dbgstopack : 1; uint64_t ocb_db_oci_timeout : 1; uint64_t ocb_db_oci_read_data_parity : 1; uint64_t ocb_db_oci_slave_error : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_db_pib_data_parity_err : 1; uint64_t ocb_idc0_error : 1; uint64_t ocb_idc1_error : 1; uint64_t ocb_idc2_error : 1; uint64_t ocb_idc3_error : 1; uint64_t srt_fsm_err : 1; uint64_t jtagacc_err : 1; uint64_t spare_err_38 : 1; uint64_t c405_ecc_ue : 1; uint64_t c405_ecc_ce : 1; uint64_t c405_oci_machinecheck : 1; uint64_t sram_spare_direct_error0 : 1; uint64_t sram_spare_direct_error1 : 1; uint64_t sram_spare_direct_error2 : 1; uint64_t sram_spare_direct_error3 : 1; uint64_t gpe0_ocislv_err : 1; uint64_t gpe1_ocislv_err : 1; uint64_t gpe2_ocislv_err : 1; uint64_t gpe3_ocislv_err : 1; uint64_t c405icu_m_timeout : 1; uint64_t c405dcu_m_timeout : 1; uint64_t occ_complex_fault_safe : 1; uint64_t spare_58_61 : 4; uint64_t fir_parity_err_dup : 1; uint64_t fir_parity_err : 1; #else uint64_t fir_parity_err : 1; uint64_t fir_parity_err_dup : 1; uint64_t spare_58_61 : 4; uint64_t occ_complex_fault_safe : 1; uint64_t c405dcu_m_timeout : 1; uint64_t c405icu_m_timeout : 1; uint64_t gpe3_ocislv_err : 1; uint64_t gpe2_ocislv_err : 1; uint64_t gpe1_ocislv_err : 1; uint64_t gpe0_ocislv_err : 1; uint64_t sram_spare_direct_error3 : 1; uint64_t sram_spare_direct_error2 : 1; uint64_t sram_spare_direct_error1 : 1; uint64_t sram_spare_direct_error0 : 1; uint64_t c405_oci_machinecheck : 1; uint64_t c405_ecc_ce : 1; uint64_t c405_ecc_ue : 1; uint64_t spare_err_38 : 1; uint64_t jtagacc_err : 1; uint64_t srt_fsm_err : 1; uint64_t ocb_idc3_error : 1; uint64_t ocb_idc2_error : 1; uint64_t ocb_idc1_error : 1; uint64_t ocb_idc0_error : 1; uint64_t ocb_db_pib_data_parity_err : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_db_oci_slave_error : 1; uint64_t ocb_db_oci_read_data_parity : 1; uint64_t ocb_db_oci_timeout : 1; uint64_t ppc405_dbgstopack : 1; uint64_t ppc405_dbgmsrwe : 1; uint64_t ppc405_system_reset : 1; uint64_t ppc405_chip_reset : 1; uint64_t ppc405_core_reset : 1; uint64_t external_trap : 1; uint64_t gpe3_halted : 1; uint64_t gpe2_halted : 1; uint64_t gpe1_halted : 1; uint64_t gpe0_halted : 1; uint64_t srt_oci_addr_parity_err : 1; uint64_t srt_oci_be_parity_err : 1; uint64_t srt_oci_write_data_parity : 1; uint64_t srt_dataout_perr : 1; uint64_t srt_write_error : 1; uint64_t srt_read_error : 1; uint64_t srt_ce : 1; uint64_t srt_ue : 1; uint64_t ocb_error : 1; uint64_t gpe3_error : 1; uint64_t gpe2_error : 1; uint64_t gpe1_error : 1; uint64_t gpe0_error : 1; uint64_t gpe3_watchdog_timeout : 1; uint64_t gpe2_watchdog_timeout : 1; uint64_t gpe1_watchdog_timeout : 1; uint64_t gpe0_watchdog_timeout : 1; uint64_t occ_hb_error : 1; uint64_t stop_recovery_notify_prd : 1; uint64_t cme_error_notify : 1; uint64_t occ_fw1 : 1; uint64_t occ_fw0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_occlfir_and_t; typedef union ocb_occlfir_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_fw0 : 1; uint64_t occ_fw1 : 1; uint64_t cme_error_notify : 1; uint64_t stop_recovery_notify_prd : 1; uint64_t occ_hb_error : 1; uint64_t gpe0_watchdog_timeout : 1; uint64_t gpe1_watchdog_timeout : 1; uint64_t gpe2_watchdog_timeout : 1; uint64_t gpe3_watchdog_timeout : 1; uint64_t gpe0_error : 1; uint64_t gpe1_error : 1; uint64_t gpe2_error : 1; uint64_t gpe3_error : 1; uint64_t ocb_error : 1; uint64_t srt_ue : 1; uint64_t srt_ce : 1; uint64_t srt_read_error : 1; uint64_t srt_write_error : 1; uint64_t srt_dataout_perr : 1; uint64_t srt_oci_write_data_parity : 1; uint64_t srt_oci_be_parity_err : 1; uint64_t srt_oci_addr_parity_err : 1; uint64_t gpe0_halted : 1; uint64_t gpe1_halted : 1; uint64_t gpe2_halted : 1; uint64_t gpe3_halted : 1; uint64_t external_trap : 1; uint64_t ppc405_core_reset : 1; uint64_t ppc405_chip_reset : 1; uint64_t ppc405_system_reset : 1; uint64_t ppc405_dbgmsrwe : 1; uint64_t ppc405_dbgstopack : 1; uint64_t ocb_db_oci_timeout : 1; uint64_t ocb_db_oci_read_data_parity : 1; uint64_t ocb_db_oci_slave_error : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_db_pib_data_parity_err : 1; uint64_t ocb_idc0_error : 1; uint64_t ocb_idc1_error : 1; uint64_t ocb_idc2_error : 1; uint64_t ocb_idc3_error : 1; uint64_t srt_fsm_err : 1; uint64_t jtagacc_err : 1; uint64_t spare_err_38 : 1; uint64_t c405_ecc_ue : 1; uint64_t c405_ecc_ce : 1; uint64_t c405_oci_machinecheck : 1; uint64_t sram_spare_direct_error0 : 1; uint64_t sram_spare_direct_error1 : 1; uint64_t sram_spare_direct_error2 : 1; uint64_t sram_spare_direct_error3 : 1; uint64_t gpe0_ocislv_err : 1; uint64_t gpe1_ocislv_err : 1; uint64_t gpe2_ocislv_err : 1; uint64_t gpe3_ocislv_err : 1; uint64_t c405icu_m_timeout : 1; uint64_t c405dcu_m_timeout : 1; uint64_t occ_complex_fault_safe : 1; uint64_t spare_58_61 : 4; uint64_t fir_parity_err_dup : 1; uint64_t fir_parity_err : 1; #else uint64_t fir_parity_err : 1; uint64_t fir_parity_err_dup : 1; uint64_t spare_58_61 : 4; uint64_t occ_complex_fault_safe : 1; uint64_t c405dcu_m_timeout : 1; uint64_t c405icu_m_timeout : 1; uint64_t gpe3_ocislv_err : 1; uint64_t gpe2_ocislv_err : 1; uint64_t gpe1_ocislv_err : 1; uint64_t gpe0_ocislv_err : 1; uint64_t sram_spare_direct_error3 : 1; uint64_t sram_spare_direct_error2 : 1; uint64_t sram_spare_direct_error1 : 1; uint64_t sram_spare_direct_error0 : 1; uint64_t c405_oci_machinecheck : 1; uint64_t c405_ecc_ce : 1; uint64_t c405_ecc_ue : 1; uint64_t spare_err_38 : 1; uint64_t jtagacc_err : 1; uint64_t srt_fsm_err : 1; uint64_t ocb_idc3_error : 1; uint64_t ocb_idc2_error : 1; uint64_t ocb_idc1_error : 1; uint64_t ocb_idc0_error : 1; uint64_t ocb_db_pib_data_parity_err : 1; uint64_t ocb_pib_addr_parity_err : 1; uint64_t ocb_db_oci_slave_error : 1; uint64_t ocb_db_oci_read_data_parity : 1; uint64_t ocb_db_oci_timeout : 1; uint64_t ppc405_dbgstopack : 1; uint64_t ppc405_dbgmsrwe : 1; uint64_t ppc405_system_reset : 1; uint64_t ppc405_chip_reset : 1; uint64_t ppc405_core_reset : 1; uint64_t external_trap : 1; uint64_t gpe3_halted : 1; uint64_t gpe2_halted : 1; uint64_t gpe1_halted : 1; uint64_t gpe0_halted : 1; uint64_t srt_oci_addr_parity_err : 1; uint64_t srt_oci_be_parity_err : 1; uint64_t srt_oci_write_data_parity : 1; uint64_t srt_dataout_perr : 1; uint64_t srt_write_error : 1; uint64_t srt_read_error : 1; uint64_t srt_ce : 1; uint64_t srt_ue : 1; uint64_t ocb_error : 1; uint64_t gpe3_error : 1; uint64_t gpe2_error : 1; uint64_t gpe1_error : 1; uint64_t gpe0_error : 1; uint64_t gpe3_watchdog_timeout : 1; uint64_t gpe2_watchdog_timeout : 1; uint64_t gpe1_watchdog_timeout : 1; uint64_t gpe0_watchdog_timeout : 1; uint64_t occ_hb_error : 1; uint64_t stop_recovery_notify_prd : 1; uint64_t cme_error_notify : 1; uint64_t occ_fw1 : 1; uint64_t occ_fw0 : 1; #endif // _BIG_ENDIAN } fields; } ocb_occlfir_or_t; typedef union ocb_occlfirmask { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_fw0_mask : 1; uint64_t occ_fw1_mask : 1; uint64_t spare_2_mask : 1; uint64_t spare_3_mask : 1; uint64_t occ_hb_malf_mask : 1; uint64_t gpe0_watchdog_timeout_mask : 1; uint64_t gpe1_watchdog_timeout_mask : 1; uint64_t gpe2_watchdog_timeout_mask : 1; uint64_t gpe3_watchdog_timeout_mask : 1; uint64_t gpe0_error_mask : 1; uint64_t gpe1_error_mask : 1; uint64_t gpe2_error_mask : 1; uint64_t gpe3_error_mask : 1; uint64_t ocb_error_mask : 1; uint64_t srt_ue_mask : 1; uint64_t srt_ce_mask : 1; uint64_t srt_read_error_mask : 1; uint64_t srt_write_error_mask : 1; uint64_t srt_dataout_perr_mask : 1; uint64_t srt_oci_write_data_parity_mask : 1; uint64_t srt_oci_be_parity_err_mask : 1; uint64_t srt_oci_addr_parity_err_mask : 1; uint64_t gpe0_halted_mask : 1; uint64_t gpe1_halted_mask : 1; uint64_t gpe2_halted_mask : 1; uint64_t gpe3_halted_mask : 1; uint64_t external_trap_mask : 1; uint64_t ppc405_core_reset_mask : 1; uint64_t ppc405_chip_reset_mask : 1; uint64_t ppc405_system_reset_mask : 1; uint64_t ppc405_dbgmsrwe_mask : 1; uint64_t ppc405_dbgstopack_mask : 1; uint64_t ocb_db_oci_timeout_mask : 1; uint64_t ocb_db_oci_read_data_parity_mask : 1; uint64_t ocb_db_oci_slave_error_mask : 1; uint64_t ocb_pib_addr_parity_err_mask : 1; uint64_t ocb_db_pib_data_parity_err_mask : 1; uint64_t ocb_idc0_error_mask : 1; uint64_t ocb_idc1_error_mask : 1; uint64_t ocb_idc2_error_mask : 1; uint64_t ocb_idc3_error_mask : 1; uint64_t srt_fsm_err_mask : 1; uint64_t jtagacc_err_mask : 1; uint64_t spare_err_38_mask : 1; uint64_t c405_ecc_ue_mask : 1; uint64_t c405_ecc_ce_mask : 1; uint64_t c405_oci_machinecheck_mask : 1; uint64_t sram_spare_direct_error0_mask : 1; uint64_t sram_spare_direct_error1_mask : 1; uint64_t sram_spare_direct_error2_mask : 1; uint64_t sram_spare_direct_error3_mask : 1; uint64_t gpe0_ocislv_err_mask : 1; uint64_t gpe1_ocislv_err_mask : 1; uint64_t gpe2_ocislv_err_mask : 1; uint64_t gpe3_ocislv_err_mask : 1; uint64_t c405icu_m_timeout_mask : 1; uint64_t c405dcu_m_timeout_mask : 1; uint64_t occ_complex_fault_safe_mask : 1; uint64_t spare_58_61_mask : 4; uint64_t fir_parity_err_dup_mask : 1; uint64_t fir_parity_err_mask : 1; #else uint64_t fir_parity_err_mask : 1; uint64_t fir_parity_err_dup_mask : 1; uint64_t spare_58_61_mask : 4; uint64_t occ_complex_fault_safe_mask : 1; uint64_t c405dcu_m_timeout_mask : 1; uint64_t c405icu_m_timeout_mask : 1; uint64_t gpe3_ocislv_err_mask : 1; uint64_t gpe2_ocislv_err_mask : 1; uint64_t gpe1_ocislv_err_mask : 1; uint64_t gpe0_ocislv_err_mask : 1; uint64_t sram_spare_direct_error3_mask : 1; uint64_t sram_spare_direct_error2_mask : 1; uint64_t sram_spare_direct_error1_mask : 1; uint64_t sram_spare_direct_error0_mask : 1; uint64_t c405_oci_machinecheck_mask : 1; uint64_t c405_ecc_ce_mask : 1; uint64_t c405_ecc_ue_mask : 1; uint64_t spare_err_38_mask : 1; uint64_t jtagacc_err_mask : 1; uint64_t srt_fsm_err_mask : 1; uint64_t ocb_idc3_error_mask : 1; uint64_t ocb_idc2_error_mask : 1; uint64_t ocb_idc1_error_mask : 1; uint64_t ocb_idc0_error_mask : 1; uint64_t ocb_db_pib_data_parity_err_mask : 1; uint64_t ocb_pib_addr_parity_err_mask : 1; uint64_t ocb_db_oci_slave_error_mask : 1; uint64_t ocb_db_oci_read_data_parity_mask : 1; uint64_t ocb_db_oci_timeout_mask : 1; uint64_t ppc405_dbgstopack_mask : 1; uint64_t ppc405_dbgmsrwe_mask : 1; uint64_t ppc405_system_reset_mask : 1; uint64_t ppc405_chip_reset_mask : 1; uint64_t ppc405_core_reset_mask : 1; uint64_t external_trap_mask : 1; uint64_t gpe3_halted_mask : 1; uint64_t gpe2_halted_mask : 1; uint64_t gpe1_halted_mask : 1; uint64_t gpe0_halted_mask : 1; uint64_t srt_oci_addr_parity_err_mask : 1; uint64_t srt_oci_be_parity_err_mask : 1; uint64_t srt_oci_write_data_parity_mask : 1; uint64_t srt_dataout_perr_mask : 1; uint64_t srt_write_error_mask : 1; uint64_t srt_read_error_mask : 1; uint64_t srt_ce_mask : 1; uint64_t srt_ue_mask : 1; uint64_t ocb_error_mask : 1; uint64_t gpe3_error_mask : 1; uint64_t gpe2_error_mask : 1; uint64_t gpe1_error_mask : 1; uint64_t gpe0_error_mask : 1; uint64_t gpe3_watchdog_timeout_mask : 1; uint64_t gpe2_watchdog_timeout_mask : 1; uint64_t gpe1_watchdog_timeout_mask : 1; uint64_t gpe0_watchdog_timeout_mask : 1; uint64_t occ_hb_malf_mask : 1; uint64_t spare_3_mask : 1; uint64_t spare_2_mask : 1; uint64_t occ_fw1_mask : 1; uint64_t occ_fw0_mask : 1; #endif // _BIG_ENDIAN } fields; } ocb_occlfirmask_t; typedef union ocb_occlfirmask_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_fw0_mask : 1; uint64_t occ_fw1_mask : 1; uint64_t spare_2_mask : 1; uint64_t spare_3_mask : 1; uint64_t occ_hb_malf_mask : 1; uint64_t gpe0_watchdog_timeout_mask : 1; uint64_t gpe1_watchdog_timeout_mask : 1; uint64_t gpe2_watchdog_timeout_mask : 1; uint64_t gpe3_watchdog_timeout_mask : 1; uint64_t gpe0_error_mask : 1; uint64_t gpe1_error_mask : 1; uint64_t gpe2_error_mask : 1; uint64_t gpe3_error_mask : 1; uint64_t ocb_error_mask : 1; uint64_t srt_ue_mask : 1; uint64_t srt_ce_mask : 1; uint64_t srt_read_error_mask : 1; uint64_t srt_write_error_mask : 1; uint64_t srt_dataout_perr_mask : 1; uint64_t srt_oci_write_data_parity_mask : 1; uint64_t srt_oci_be_parity_err_mask : 1; uint64_t srt_oci_addr_parity_err_mask : 1; uint64_t gpe0_halted_mask : 1; uint64_t gpe1_halted_mask : 1; uint64_t gpe2_halted_mask : 1; uint64_t gpe3_halted_mask : 1; uint64_t external_trap_mask : 1; uint64_t ppc405_core_reset_mask : 1; uint64_t ppc405_chip_reset_mask : 1; uint64_t ppc405_system_reset_mask : 1; uint64_t ppc405_dbgmsrwe_mask : 1; uint64_t ppc405_dbgstopack_mask : 1; uint64_t ocb_db_oci_timeout_mask : 1; uint64_t ocb_db_oci_read_data_parity_mask : 1; uint64_t ocb_db_oci_slave_error_mask : 1; uint64_t ocb_pib_addr_parity_err_mask : 1; uint64_t ocb_db_pib_data_parity_err_mask : 1; uint64_t ocb_idc0_error_mask : 1; uint64_t ocb_idc1_error_mask : 1; uint64_t ocb_idc2_error_mask : 1; uint64_t ocb_idc3_error_mask : 1; uint64_t srt_fsm_err_mask : 1; uint64_t jtagacc_err_mask : 1; uint64_t spare_err_38_mask : 1; uint64_t c405_ecc_ue_mask : 1; uint64_t c405_ecc_ce_mask : 1; uint64_t c405_oci_machinecheck_mask : 1; uint64_t sram_spare_direct_error0_mask : 1; uint64_t sram_spare_direct_error1_mask : 1; uint64_t sram_spare_direct_error2_mask : 1; uint64_t sram_spare_direct_error3_mask : 1; uint64_t gpe0_ocislv_err_mask : 1; uint64_t gpe1_ocislv_err_mask : 1; uint64_t gpe2_ocislv_err_mask : 1; uint64_t gpe3_ocislv_err_mask : 1; uint64_t c405icu_m_timeout_mask : 1; uint64_t c405dcu_m_timeout_mask : 1; uint64_t occ_complex_fault_safe_mask : 1; uint64_t spare_58_61_mask : 4; uint64_t fir_parity_err_dup_mask : 1; uint64_t fir_parity_err_mask : 1; #else uint64_t fir_parity_err_mask : 1; uint64_t fir_parity_err_dup_mask : 1; uint64_t spare_58_61_mask : 4; uint64_t occ_complex_fault_safe_mask : 1; uint64_t c405dcu_m_timeout_mask : 1; uint64_t c405icu_m_timeout_mask : 1; uint64_t gpe3_ocislv_err_mask : 1; uint64_t gpe2_ocislv_err_mask : 1; uint64_t gpe1_ocislv_err_mask : 1; uint64_t gpe0_ocislv_err_mask : 1; uint64_t sram_spare_direct_error3_mask : 1; uint64_t sram_spare_direct_error2_mask : 1; uint64_t sram_spare_direct_error1_mask : 1; uint64_t sram_spare_direct_error0_mask : 1; uint64_t c405_oci_machinecheck_mask : 1; uint64_t c405_ecc_ce_mask : 1; uint64_t c405_ecc_ue_mask : 1; uint64_t spare_err_38_mask : 1; uint64_t jtagacc_err_mask : 1; uint64_t srt_fsm_err_mask : 1; uint64_t ocb_idc3_error_mask : 1; uint64_t ocb_idc2_error_mask : 1; uint64_t ocb_idc1_error_mask : 1; uint64_t ocb_idc0_error_mask : 1; uint64_t ocb_db_pib_data_parity_err_mask : 1; uint64_t ocb_pib_addr_parity_err_mask : 1; uint64_t ocb_db_oci_slave_error_mask : 1; uint64_t ocb_db_oci_read_data_parity_mask : 1; uint64_t ocb_db_oci_timeout_mask : 1; uint64_t ppc405_dbgstopack_mask : 1; uint64_t ppc405_dbgmsrwe_mask : 1; uint64_t ppc405_system_reset_mask : 1; uint64_t ppc405_chip_reset_mask : 1; uint64_t ppc405_core_reset_mask : 1; uint64_t external_trap_mask : 1; uint64_t gpe3_halted_mask : 1; uint64_t gpe2_halted_mask : 1; uint64_t gpe1_halted_mask : 1; uint64_t gpe0_halted_mask : 1; uint64_t srt_oci_addr_parity_err_mask : 1; uint64_t srt_oci_be_parity_err_mask : 1; uint64_t srt_oci_write_data_parity_mask : 1; uint64_t srt_dataout_perr_mask : 1; uint64_t srt_write_error_mask : 1; uint64_t srt_read_error_mask : 1; uint64_t srt_ce_mask : 1; uint64_t srt_ue_mask : 1; uint64_t ocb_error_mask : 1; uint64_t gpe3_error_mask : 1; uint64_t gpe2_error_mask : 1; uint64_t gpe1_error_mask : 1; uint64_t gpe0_error_mask : 1; uint64_t gpe3_watchdog_timeout_mask : 1; uint64_t gpe2_watchdog_timeout_mask : 1; uint64_t gpe1_watchdog_timeout_mask : 1; uint64_t gpe0_watchdog_timeout_mask : 1; uint64_t occ_hb_malf_mask : 1; uint64_t spare_3_mask : 1; uint64_t spare_2_mask : 1; uint64_t occ_fw1_mask : 1; uint64_t occ_fw0_mask : 1; #endif // _BIG_ENDIAN } fields; } ocb_occlfirmask_and_t; typedef union ocb_occlfirmask_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_fw0_mask : 1; uint64_t occ_fw1_mask : 1; uint64_t spare_2_mask : 1; uint64_t spare_3_mask : 1; uint64_t occ_hb_malf_mask : 1; uint64_t gpe0_watchdog_timeout_mask : 1; uint64_t gpe1_watchdog_timeout_mask : 1; uint64_t gpe2_watchdog_timeout_mask : 1; uint64_t gpe3_watchdog_timeout_mask : 1; uint64_t gpe0_error_mask : 1; uint64_t gpe1_error_mask : 1; uint64_t gpe2_error_mask : 1; uint64_t gpe3_error_mask : 1; uint64_t ocb_error_mask : 1; uint64_t srt_ue_mask : 1; uint64_t srt_ce_mask : 1; uint64_t srt_read_error_mask : 1; uint64_t srt_write_error_mask : 1; uint64_t srt_dataout_perr_mask : 1; uint64_t srt_oci_write_data_parity_mask : 1; uint64_t srt_oci_be_parity_err_mask : 1; uint64_t srt_oci_addr_parity_err_mask : 1; uint64_t gpe0_halted_mask : 1; uint64_t gpe1_halted_mask : 1; uint64_t gpe2_halted_mask : 1; uint64_t gpe3_halted_mask : 1; uint64_t external_trap_mask : 1; uint64_t ppc405_core_reset_mask : 1; uint64_t ppc405_chip_reset_mask : 1; uint64_t ppc405_system_reset_mask : 1; uint64_t ppc405_dbgmsrwe_mask : 1; uint64_t ppc405_dbgstopack_mask : 1; uint64_t ocb_db_oci_timeout_mask : 1; uint64_t ocb_db_oci_read_data_parity_mask : 1; uint64_t ocb_db_oci_slave_error_mask : 1; uint64_t ocb_pib_addr_parity_err_mask : 1; uint64_t ocb_db_pib_data_parity_err_mask : 1; uint64_t ocb_idc0_error_mask : 1; uint64_t ocb_idc1_error_mask : 1; uint64_t ocb_idc2_error_mask : 1; uint64_t ocb_idc3_error_mask : 1; uint64_t srt_fsm_err_mask : 1; uint64_t jtagacc_err_mask : 1; uint64_t spare_err_38_mask : 1; uint64_t c405_ecc_ue_mask : 1; uint64_t c405_ecc_ce_mask : 1; uint64_t c405_oci_machinecheck_mask : 1; uint64_t sram_spare_direct_error0_mask : 1; uint64_t sram_spare_direct_error1_mask : 1; uint64_t sram_spare_direct_error2_mask : 1; uint64_t sram_spare_direct_error3_mask : 1; uint64_t gpe0_ocislv_err_mask : 1; uint64_t gpe1_ocislv_err_mask : 1; uint64_t gpe2_ocislv_err_mask : 1; uint64_t gpe3_ocislv_err_mask : 1; uint64_t c405icu_m_timeout_mask : 1; uint64_t c405dcu_m_timeout_mask : 1; uint64_t occ_complex_fault_safe_mask : 1; uint64_t spare_58_61_mask : 4; uint64_t fir_parity_err_dup_mask : 1; uint64_t fir_parity_err_mask : 1; #else uint64_t fir_parity_err_mask : 1; uint64_t fir_parity_err_dup_mask : 1; uint64_t spare_58_61_mask : 4; uint64_t occ_complex_fault_safe_mask : 1; uint64_t c405dcu_m_timeout_mask : 1; uint64_t c405icu_m_timeout_mask : 1; uint64_t gpe3_ocislv_err_mask : 1; uint64_t gpe2_ocislv_err_mask : 1; uint64_t gpe1_ocislv_err_mask : 1; uint64_t gpe0_ocislv_err_mask : 1; uint64_t sram_spare_direct_error3_mask : 1; uint64_t sram_spare_direct_error2_mask : 1; uint64_t sram_spare_direct_error1_mask : 1; uint64_t sram_spare_direct_error0_mask : 1; uint64_t c405_oci_machinecheck_mask : 1; uint64_t c405_ecc_ce_mask : 1; uint64_t c405_ecc_ue_mask : 1; uint64_t spare_err_38_mask : 1; uint64_t jtagacc_err_mask : 1; uint64_t srt_fsm_err_mask : 1; uint64_t ocb_idc3_error_mask : 1; uint64_t ocb_idc2_error_mask : 1; uint64_t ocb_idc1_error_mask : 1; uint64_t ocb_idc0_error_mask : 1; uint64_t ocb_db_pib_data_parity_err_mask : 1; uint64_t ocb_pib_addr_parity_err_mask : 1; uint64_t ocb_db_oci_slave_error_mask : 1; uint64_t ocb_db_oci_read_data_parity_mask : 1; uint64_t ocb_db_oci_timeout_mask : 1; uint64_t ppc405_dbgstopack_mask : 1; uint64_t ppc405_dbgmsrwe_mask : 1; uint64_t ppc405_system_reset_mask : 1; uint64_t ppc405_chip_reset_mask : 1; uint64_t ppc405_core_reset_mask : 1; uint64_t external_trap_mask : 1; uint64_t gpe3_halted_mask : 1; uint64_t gpe2_halted_mask : 1; uint64_t gpe1_halted_mask : 1; uint64_t gpe0_halted_mask : 1; uint64_t srt_oci_addr_parity_err_mask : 1; uint64_t srt_oci_be_parity_err_mask : 1; uint64_t srt_oci_write_data_parity_mask : 1; uint64_t srt_dataout_perr_mask : 1; uint64_t srt_write_error_mask : 1; uint64_t srt_read_error_mask : 1; uint64_t srt_ce_mask : 1; uint64_t srt_ue_mask : 1; uint64_t ocb_error_mask : 1; uint64_t gpe3_error_mask : 1; uint64_t gpe2_error_mask : 1; uint64_t gpe1_error_mask : 1; uint64_t gpe0_error_mask : 1; uint64_t gpe3_watchdog_timeout_mask : 1; uint64_t gpe2_watchdog_timeout_mask : 1; uint64_t gpe1_watchdog_timeout_mask : 1; uint64_t gpe0_watchdog_timeout_mask : 1; uint64_t occ_hb_malf_mask : 1; uint64_t spare_3_mask : 1; uint64_t spare_2_mask : 1; uint64_t occ_fw1_mask : 1; uint64_t occ_fw0_mask : 1; #endif // _BIG_ENDIAN } fields; } ocb_occlfirmask_or_t; typedef union ocb_occlfiract0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_action0 : 64; #else uint64_t fir_action0 : 64; #endif // _BIG_ENDIAN } fields; } ocb_occlfiract0_t; typedef union ocb_occlfiract1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_action1 : 64; #else uint64_t fir_action1 : 64; #endif // _BIG_ENDIAN } fields; } ocb_occlfiract1_t; typedef union ocb_occlfirwof { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t wof : 64; #else uint64_t wof : 64; #endif // _BIG_ENDIAN } fields; } ocb_occlfirwof_t; typedef union ocb_occerrrpt { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sram_cerrrpt : 10; uint64_t jtagacc_cerrpt : 6; uint64_t c405_dcu_ecc_ue : 1; uint64_t c405_dcu_ecc_ce : 1; uint64_t c405_icu_ecc_ue : 1; uint64_t c405_icu_ecc_ce : 1; uint64_t gpe0_ocislv_err : 7; uint64_t reserved1 : 1; uint64_t gpe1_ocislv_err : 7; uint64_t reserved2 : 1; uint64_t gpe2_ocislv_err : 7; uint64_t reserved3 : 1; uint64_t gpe3_ocislv_err : 7; uint64_t reserved4 : 1; uint64_t ocb_ocislv_err : 7; uint64_t reserved5 : 5; #else uint64_t reserved5 : 5; uint64_t ocb_ocislv_err : 7; uint64_t reserved4 : 1; uint64_t gpe3_ocislv_err : 7; uint64_t reserved3 : 1; uint64_t gpe2_ocislv_err : 7; uint64_t reserved2 : 1; uint64_t gpe1_ocislv_err : 7; uint64_t reserved1 : 1; uint64_t gpe0_ocislv_err : 7; uint64_t c405_icu_ecc_ce : 1; uint64_t c405_icu_ecc_ue : 1; uint64_t c405_dcu_ecc_ce : 1; uint64_t c405_dcu_ecc_ue : 1; uint64_t jtagacc_cerrpt : 6; uint64_t sram_cerrrpt : 10; #endif // _BIG_ENDIAN } fields; } ocb_occerrrpt_t; #endif // __ASSEMBLER__ #endif // __OCB_FIRMWARE_REGISTERS_H__ <|start_filename|>src/include/registers/centaur_register_addresses.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/common/pmlib/include/registers/centaur_register_addresses.h $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CENTAUR_REGISTER_ADDRESSES_H__ #define __CENTAUR_REGISTER_ADDRESSES_H__ /// \file centaur_register_addresses.h /// \brief Symbolic addresses for the CENTAUR unit // //See MC chiplet //MBA_FARBnQ where (0 <= n <= 8) 0x7010913 #define CENTAUR_PIB_BASE 0 #define CENTAUR_DEVICE_ID 0x000f000f #define CENTAUR_MBS_FIR_REG 0x02011400 #define CENTAUR_MBS_FIR_REG_AND 0x02011401 #define CENTAUR_MBS_FIR_REG_OR 0x02011402 #define CENTAUR_MBS_FIR_MASK_REG 0x02011403 #define CENTAUR_MBS_FIR_MASK_REG_AND 0x02011404 #define CENTAUR_MBS_FIR_MASK_REG_OR 0x02011405 #define CENTAUR_MBS_FIR_ACTION0_REG 0x02011406 #define CENTAUR_MBS_FIRACT1 0x02011407 #define CENTAUR_MBSCFGQ 0x02011411 #define CENTAUR_MBSEMERTHROQ 0x0201142d #define CENTAUR_MBSOCC01HQ 0x02011429 #define CENTAUR_MBSOCC23HQ 0x0201142a #define CENTAUR_MBSOCCITCQ 0x02011428 #define CENTAUR_MBSOCCSCANQ 0x0201142b #define CENTAUR_MBARPC0QN(n) (CENTAUR_MBARPC0Q0 + ((CENTAUR_MBARPC0Q1 - CENTAUR_MBARPC0Q0) * (n))) #define CENTAUR_MBARPC0Q0 0x03010434 #define CENTAUR_MBARPC0Q1 0x03010c34 #define CENTAUR_MBA_FARB3QN(n) (CENTAUR_MBA_FARB3Q0 + ((CENTAUR_MBA_FARB3Q1 - CENTAUR_MBA_FARB3Q0) * (n))) #define CENTAUR_MBA_FARB3Q0 0x03010416 #define CENTAUR_MBA_FARB3Q1 0x03010c16 #define CENTAUR_PMU0QN(n) (CENTAUR_PMU0Q0 + ((CENTAUR_PMU0Q1 - CENTAUR_PMU0Q0) * (n))) #define CENTAUR_PMU0Q0 0x03010437 #define CENTAUR_PMU0Q1 0x03010c37 #define CENTAUR_PMU1QN(n) (CENTAUR_PMU1Q0 + ((CENTAUR_PMU1Q1 - CENTAUR_PMU1Q0) * (n))) #define CENTAUR_PMU1Q0 0x03010438 #define CENTAUR_PMU1Q1 0x03010c38 #define CENTAUR_PMU2QN(n) (CENTAUR_PMU2Q0 + ((CENTAUR_PMU2Q1 - CENTAUR_PMU2Q0) * (n))) #define CENTAUR_PMU2Q0 0x03010439 #define CENTAUR_PMU2Q1 0x03010c39 #define CENTAUR_PMU3QN(n) (CENTAUR_PMU3Q0 + ((CENTAUR_PMU3Q1 - CENTAUR_PMU3Q0) * (n))) #define CENTAUR_PMU3Q0 0x0301043a #define CENTAUR_PMU3Q1 0x03010c3a #define CENTAUR_PMU4QN(n) (CENTAUR_PMU4Q0 + ((CENTAUR_PMU4Q1 - CENTAUR_PMU4Q0) * (n))) #define CENTAUR_PMU4Q0 0x0301043b #define CENTAUR_PMU4Q1 0x03010c3b #define CENTAUR_PMU5QN(n) (CENTAUR_PMU5Q0 + ((CENTAUR_PMU5Q1 - CENTAUR_PMU5Q0) * (n))) #define CENTAUR_PMU5Q0 0x0301043c #define CENTAUR_PMU5Q1 0x03010c3c #define CENTAUR_PMU6QN(n) (CENTAUR_PMU6Q0 + ((CENTAUR_PMU6Q1 - CENTAUR_PMU6Q0) * (n))) #define CENTAUR_PMU6Q0 0x0301043d #define CENTAUR_PMU6Q1 0x03010c3d #define CENTAUR_SENSOR_CACHE_DATA0_3 0x020115ca #define CENTAUR_SENSOR_CACHE_DATA4_7 0x020115cb #define CENTAUR_DTS_THERMAL_SENSOR_RESULTS 0x02050000 #endif // __CENTAUR_REGISTER_ADDRESSES_H__ <|start_filename|>src/include/centaur_mem_data.h<|end_filename|> #if !defined(__CENTAUR_MEM_DATA_H__) #define __CENTAUR_MEM_DATA_H__ typedef union { uint16_t value; struct { uint16_t value; } fields; } centaur_sensor_t; /// The layout of a Centaur DIMM sensor /// /// Mnemonic macros for the 2-bit status codes (DIMM_SENSOR_STATUS_*) are /// currently defined in ssx/pgp/pgp_common.h /// /// \todo Waiting for more info from Centaur team on how to interpret typedef union { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t crit_trip : 1; uint16_t alarm_trip : 1; uint16_t below_trip : 1; uint16_t sign_bit : 1; uint16_t temperature : 8; uint16_t temp_fraction : 2; uint16_t status : 2; #else uint16_t status : 2; uint16_t temp_fraction : 2; uint16_t temperature : 8; uint16_t sign_bit : 1; uint16_t below_trip : 1; uint16_t alarm_trip : 1; uint16_t crit_trip : 1; #endif } fields; } centaur_dimm_sensor_t; /// The layout of the status bits of the sensor cache line /// /// The sensor cache-line aggregator gets each element of the sensor cache /// line by an internal SCOM. The individual PCB return codes for each SCOM /// are collected here (3 bits each) - note that many of the 32-bit registers /// come back in a single 64-bit internal SCOM. Normally this register will /// always read as 0 indicating all data was collected successfully. The PCB /// error codes (PCB_ERROR_*) are currently defined in ssx/pgp/pgp_common.h. typedef union { uint64_t value; struct { #ifdef _BIG_ENDIAN uint64_t mba01_rw : 3; /// mba01_rd[+ wr] uint64_t mba01_ap : 3; /// mba01_act[+ powerups] uint64_t mba23_rw : 3; /// mba23_rd[+ wr] uint64_t mba23_ap : 3; /// mba23_act[+ powerups] uint64_t mba_sc : 3; /// mba01[+ 23]_spec_cancels uint64_t lp2_exits : 3; /// lp2_exits uint64_t frame_count : 3; /// frame_count uint64_t mba01_chrw : 3; /// mba01_cache_hits_rd[+ wr] uint64_t mba23_chrw : 3; /// mba23_cache_hits_rd[+ wr] uint64_t mba01_iac_bl : 3; /// mba01_intreq_arr_cnt_base[+ low] uint64_t mba01_iac_mh : 3; /// mba01_intreq_arr_cnt_med[+ high] uint64_t mba23_iac_bl : 3; /// mba23_intreq_arr_cnt_base[+ low] uint64_t mba23_iac_mh : 3; /// mba23_intreq_arr_cnt_med[+ high] uint64_t iac_high_latency : 3; /// intereq_arr_cnt_high_latency uint64_t centaur01 : 3; /// centaur_thermal_sensor[0 - 1] uint64_t dimm03 : 3; /// dimm_thermal_sensor[0 - 3] uint64_t dimm47 : 3; /// dimm_thermal_sensor[4 - 7] uint64_t reserved : 13; #else uint64_t reserved : 13; uint64_t dimm47 : 3; /// dimm_thermal_sensor[4 - 7] uint64_t dimm03 : 3; /// dimm_thermal_sensor[0 - 3] uint64_t centaur01 : 3; /// centaur_thermal_sensor[0 - 1] uint64_t iac_high_latency : 3; /// intereq_arr_cnt_high_latency uint64_t mba23_iac_mh : 3; /// mba23_intreq_arr_cnt_med[+ high] uint64_t mba23_iac_bl : 3; /// mba23_intreq_arr_cnt_base[+ low] uint64_t mba01_iac_mh : 3; /// mba01_intreq_arr_cnt_med[+ high] uint64_t mba01_iac_bl : 3; /// mba01_intreq_arr_cnt_base[+ low] uint64_t mba23_chrw : 3; /// mba23_cache_hits_rd[+ wr] uint64_t mba01_chrw : 3; /// mba01_cache_hits_rd[+ wr] uint64_t frame_count : 3; /// frame_count uint64_t lp2_exits : 3; /// lp2_exits uint64_t mba_sc : 3; /// mba01[+ 23]_spec_cancels uint64_t mba23_ap : 3; /// mba23_act[+ powerups] uint64_t mba23_rw : 3; /// mba23_rd[+ wr] uint64_t mba01_ap : 3; /// mba01_act[+ powerups] uint64_t mba01_rw : 3; /// mba01_rd[+ wr] #endif } fields; } centaur_scom_status_t; /// The layout of the Centaur sensor cache line typedef struct { uint32_t mba01_rd; // PP1/MBA01 Reads uint32_t mba01_wr; // PP1/MBA01 Writes uint32_t mba01_act; // PP1/MBA01 Activations uint32_t mba01_powerups; // PP1/MBA01 PowerUps uint32_t mba23_rd; // PP2/MBA23 Reads uint32_t mba23_wr; // PP2/MBA23 Writes uint32_t mba23_act; // PP2/MBA23 Activations uint32_t mba23_powerups; // PP2/MBA23 PowerUps uint32_t mba01_spec_cancels; // PP1/MBA01 Speculative Cancels uint32_t mba23_spec_cancels; // PP2/MBA23 Speculative Cancels #ifdef _BIG_ENDIAN uint32_t eventn :4; // EVENTN uint32_t reserved_0 :20; // Reserved uint32_t lp2_exits :8; // LP2 Exits #else uint32_t lp2_exits :8; // LP2 Exits uint32_t reserved_0 :20; // Reserved uint32_t eventn :4; // EVENTN #endif uint32_t frame_count; // Frame Count (timestamp) uint32_t mba01_cache_hits_rd; // PP1/MBA01 Cache Hits Reads uint32_t mba01_cache_hits_wr; // PP1/MBA01 Cache Hits Writes uint32_t mba23_cache_hits_rd; // PP2/MBA23 Cache Hits Reads uint32_t mba23_cache_hits_wr; // PP2/MBA23 Cache Hits Writes uint32_t mba01_intreq_arr_cnt_base; // PP1/MBA01 Inter-Req Arrival Count Base uint32_t mba01_intreq_arr_cnt_low; // PP1/MBA01 Inter-Req Arrival Count Low uint32_t mba01_intreq_arr_cnt_med; // PP1/MBA01 Inter-Req Arrival Count Med uint32_t mba01_intreq_arr_cnt_high; // PP1/MBA01 Inter-Req Arrival Count High uint32_t mba23_intreq_arr_cnt_base; // PP2/MBA23 Inter-Req Arrival Count Base uint32_t mba23_intreq_arr_cnt_low; // PP2/MBA23 Inter-Req Arrival Count Low uint32_t mba23_intreq_arr_cnt_med; // PP2/MBA23 Inter-Req Arrival Count Med uint32_t mba23_intreq_arr_cnt_high; // PP2/MBA23 Inter-Req Arrival Count High uint32_t intreq_arr_cnt_high_latency; // Inter-Req Arrival Count High Latency centaur_sensor_t centaur_thermal_sensor[2]; // Centaur Thermal Sensors 0-1 centaur_dimm_sensor_t dimm_thermal_sensor[8]; // DIMM Thermal Sensors 0-7 centaur_scom_status_t status; // Aggregated internal SCOM status } MemDataSensorCache; typedef struct { MemDataSensorCache scache; // OCC Centaur Sensor Cache Line (128 bytes) } CentaurMemData; /// \defgroup gpe_mem_data_rc gpe_get_mem_data() Error Return Codes /// /// The gpe_get_mem_data() procedure deposits a non-0 return code into the \a /// rc field of its parameter structure in the event of failure. Note that the /// procedure stops on the first failure, and in particular the TOD timestamp /// is not valid in the event of failure. /// /// @{ /// The global G_centaurConfiguration is not valid #define CENTAUR_GET_MEM_DATA_NOT_CONFIGURED 4 /// The workaround for HW256773 failed. To diagnose the failure look at the /// 'rc' field of the global variable G_hw256773. #define CENTAUR_GET_MEM_DATA_HW256773_FAILED 5 /// This code is established in the RC field prior to collecting the Centaur /// sensor cache data. If this RC is observed on a hard failure it most likely /// indicates an error assiciated with the Centaur whose data was being /// collected. #define CENTAUR_GET_MEM_DATA_SENSOR_CACHE_FAILED 6 /// This code is established in the RC field prior to "poking" the Centaur (if /// any) that is being updated this pass. If this RC is observed on a hard /// failure it most likely indicates an error associated with the Centaur /// being updated. #define CENTAUR_GET_MEM_DATA_UPDATE_FAILED 7 #endif <|start_filename|>src/include/cmehw_interrupts.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/cmehw_interrupts.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CMEHW_INTERRUPTS_H__ #define __CMEHW_INTERRUPTS_H__ /// \file cmehw_interrupts.h /// \brief Interrupt assignments and macros for the CME /// //////////////////////////////////////////////////////////////////////////// // IRQ //////////////////////////////////////////////////////////////////////////// // The CME interrupt controller consists of 1 x 64-bit controller. // // All 64 interrupts are or'd together and presented to the PPE as a single // external interrupt exception. #define CMEHW_IRQ_DEBUGGER 0 /* 0x00 */ #define CMEHW_IRQ_DEBUG_TRIGGER 1 /* 0x01 */ #define CMEHW_IRQ_QUAD_CHECKSTOP 2 /* 0x02 */ #define CMEHW_IRQ_SPARE_3 3 /* 0x03 */ #define CMEHW_IRQ_OCC_HEARTBEAT_LOST 4 /* 0x04 */ #define CMEHW_IRQ_CORE_CHECKSTOP 5 /* 0x05 */ #define CMEHW_IRQ_BCE_BUSY_HIGH 6 /* 0x06 */ #define CMEHW_IRQ_SPARE_7 7 /* 0x07 */ #define CMEHW_IRQ_DOORBELL3_C0 8 /* 0x08 */ #define CMEHW_IRQ_DOORBELL3_C1 9 /* 0x09 */ #define CMEHW_IRQ_PC_INTR_PENDING_C0 10 /* 0x0a */ #define CMEHW_IRQ_PC_INTR_PENDING_C1 11 /* 0x0b */ #define CMEHW_IRQ_REG_WAKEUP_C0 12 /* 0x0c */ #define CMEHW_IRQ_REG_WAKEUP_C1 13 /* 0x0d */ #define CMEHW_IRQ_SPECIAL_WAKEUP_C0 14 /* 0x0e */ #define CMEHW_IRQ_SPECIAL_WAKEUP_C1 15 /* 0x0f */ #define CMEHW_IRQ_SPARE_16 16 /* 0x10 */ #define CMEHW_IRQ_SPARE_17 17 /* 0x11 */ #define CMEHW_IRQ_DOORBELL2_C0 18 /* 0x12 */ #define CMEHW_IRQ_DOORBELL2_C1 19 /* 0x13 */ #define CMEHW_IRQ_PC_PM_STATE_ACTIVE_C0 20 /* 0x14 */ #define CMEHW_IRQ_PC_PM_STATE_ACTIVE_C1 21 /* 0x15 */ #define CMEHW_IRQ_L2_PURGE_DONE 22 /* 0x16 */ #define CMEHW_IRQ_NCU_PURGE_DONE 23 /* 0x17 */ #define CMEHW_IRQ_CHTM_PURGE_DONE_C0 24 /* 0x18 */ #define CMEHW_IRQ_CHTM_PURGE_DONE_C1 25 /* 0x19 */ #define CMEHW_IRQ_BCE_BUSY_LOW 26 /* 0x1a */ #define CMEHW_IRQ_SPARE_27 27 /* 0x1b */ #define CMEHW_IRQ_SPARE_28 28 /* 0x1c */ #define CMEHW_IRQ_COMM_RECVD 29 /* 0x1d */ #define CMEHW_IRQ_COMM_SEND_ACK 30 /* 0x1e */ #define CMEHW_IRQ_COMM_SEND_NACK 31 /* 0x1f */ #define CMEHW_IRQ_SPARE_32 32 /* 0x20 */ #define CMEHW_IRQ_SPARE_33 33 /* 0x21 */ #define CMEHW_IRQ_PMCR_UPDATE_C0 34 /* 0x22 */ #define CMEHW_IRQ_PMCR_UPDATE_C1 35 /* 0x23 */ #define CMEHW_IRQ_DOORBELL0_C0 36 /* 0x24 */ #define CMEHW_IRQ_DOORBELL0_C1 37 /* 0x25 */ #define CMEHW_IRQ_SPARE_38 38 /* 0x26 */ #define CMEHW_IRQ_SPARE_39 39 /* 0x27 */ #define CMEHW_IRQ_DOORBELL1_C0 40 /* 0x28 */ #define CMEHW_IRQ_DOORBELL1_C1 41 /* 0x29 */ #define CMEHW_IRQ_PECE_INTR_DISABLED_C0 42 /* 0x2a */ #define CMEHW_IRQ_PECE_INTR_DISABLED_C1 43 /* 0x2b */ #define CMEHW_IRQ_RESERVED_44 44 /* 0x2c */ #define CMEHW_IRQ_RESERVED_45 45 /* 0x2d */ #define CMEHW_IRQ_RESERVED_46 46 /* 0x2e */ #define CMEHW_IRQ_RESERVED_47 47 /* 0x2f */ #define CMEHW_IRQ_RESERVED_48 48 /* 0x30 */ #define CMEHW_IRQ_RESERVED_49 49 /* 0x31 */ #define CMEHW_IRQ_RESERVED_50 50 /* 0x32 */ #define CMEHW_IRQ_RESERVED_51 51 /* 0x33 */ #define CMEHW_IRQ_RESERVED_52 52 /* 0x34 */ #define CMEHW_IRQ_RESERVED_53 53 /* 0x35 */ #define CMEHW_IRQ_RESERVED_54 54 /* 0x36 */ #define CMEHW_IRQ_RESERVED_55 55 /* 0x37 */ #define CMEHW_IRQ_RESERVED_56 56 /* 0x38 */ #define CMEHW_IRQ_RESERVED_57 57 /* 0x39 */ #define CMEHW_IRQ_RESERVED_58 58 /* 0x3a */ #define CMEHW_IRQ_RESERVED_59 59 /* 0x3b */ #define CMEHW_IRQ_RESERVED_60 60 /* 0x3c */ #define CMEHW_IRQ_RESERVED_61 61 /* 0x3d */ #define CMEHW_IRQ_RESERVED_62 62 /* 0x3e */ #define CMEHW_IRQ_RESERVED_63 63 /* 0x3f */ // Please keep the string definitions up-to-date as they are used for // reporting in the Simics simulation. #define CMEHW_IRQ_STRINGS(var) \ const char* var[CMEHW_IRQS] = { \ "CMEHW_IRQ_DEBUGGER", \ "CMEHW_IRQ_DEBUG_TRIGGER", \ "CMEHW_IRQ_QUAD_CHECKSTOP", \ "CMEHW_IRQ_SPARE_3", \ "CMEHW_IRQ_OCC_HEARTBEAT_LOST", \ "CMEHW_IRQ_CORE_CHECKSTOP", \ "CMEHW_IRQ_BCE_BUSY_HIGH", \ "CMEHW_IRQ_SPARE_7", \ "CMEHW_IRQ_DOORBELL3_C0", \ "CMEHW_IRQ_DOORBELL3_C1", \ "CMEHW_IRQ_PC_INTR_PENDING_C0", \ "CMEHW_IRQ_PC_INTR_PENDING_C1", \ "CMEHW_IRQ_REG_WAKEUP_C0", \ "CMEHW_IRQ_REG_WAKEUP_C1", \ "CMEHW_IRQ_SPECIAL_WAKEUP_C0", \ "CMEHW_IRQ_SPECIAL_WAKEUP_C1", \ "CMEHW_IRQ_SPARE_16", \ "CMEHW_IRQ_SPARE_17", \ "CMEHW_IRQ_DOORBELL2_C0", \ "CMEHW_IRQ_DOORBELL2_C1", \ "CMEHW_IRQ_PC_PM_STATE_ACTIVE_C0", \ "CMEHW_IRQ_PC_PM_STATE_ACTIVE_C1", \ "CMEHW_IRQ_L2_PURGE_DONE", \ "CMEHW_IRQ_NCU_PURGE_DONE", \ "CMEHW_IRQ_CHTM_PURGE_DONE_C0", \ "CMEHW_IRQ_CHTM_PURGE_DONE_C1", \ "CMEHW_IRQ_BCE_BUSY_LOW", \ "CMEHW_IRQ_SPARE_27", \ "CMEHW_IRQ_SPARE_28", \ "CMEHW_IRQ_COMM_RECVD", \ "CMEHW_IRQ_COMM_SEND_ACK", \ "CMEHW_IRQ_COMM_SEND_NACK", \ "CMEHW_IRQ_SPARE_32", \ "CMEHW_IRQ_SPARE_33", \ "CMEHW_IRQ_PMCR_UPDATE_C0", \ "CMEHW_IRQ_PMCR_UPDATE_C1", \ "CMEHW_IRQ_DOORBELL0_C0", \ "CMEHW_IRQ_DOORBELL0_C1", \ "CMEHW_IRQ_SPARE_38", \ "CMEHW_IRQ_SPARE_39", \ "CMEHW_IRQ_DOORBELL1_C0", \ "CMEHW_IRQ_DOORBELL1_C1", \ "CMEHW_IRQ_PECE_INTR_DISABLED_C0", \ "CMEHW_IRQ_PECE_INTR_DISABLED_C1", \ "CMEHW_IRQ_RESERVED_44", \ "CMEHW_IRQ_RESERVED_45", \ "CMEHW_IRQ_RESERVED_46", \ "CMEHW_IRQ_RESERVED_47", \ "CMEHW_IRQ_RESERVED_48", \ "CMEHW_IRQ_RESERVED_49", \ "CMEHW_IRQ_RESERVED_50", \ "CMEHW_IRQ_RESERVED_51", \ "CMEHW_IRQ_RESERVED_52", \ "CMEHW_IRQ_RESERVED_53", \ "CMEHW_IRQ_RESERVED_54", \ "CMEHW_IRQ_RESERVED_55", \ "CMEHW_IRQ_RESERVED_56", \ "CMEHW_IRQ_RESERVED_57", \ "CMEHW_IRQ_RESERVED_58", \ "CMEHW_IRQ_RESERVED_59", \ "CMEHW_IRQ_RESERVED_60", \ "CMEHW_IRQ_RESERVED_61", \ "CMEHW_IRQ_RESERVED_62", \ "CMEHW_IRQ_RESERVED_63", \ }; #endif /* __CMEHW_INTERRUPTS_H__ */ <|start_filename|>src/ssx/trace/ssx_trace_big.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/trace/ssx_trace_big.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_trace_big.c /// \brief SSX Trace function that supports up to four 32-bit parameters /// /// The ssx_trace_big function is only called (via some macro magic) if the /// caller passes in a single parameter (not including the format string) /// that is larger than 16 bits to the SSX_TRACE(...) macro. /// #include "ssx.h" #include "ssx_trace.h" #if (SSX_TRACE_SUPPORT && SSX_TIMER_SUPPORT) void ssx_trace_big(uint32_t i_hash_and_count, uint64_t i_parm1, uint64_t i_parm2) { SsxTraceBig footer; SsxTraceBig* footer_ptr; SsxTraceState state; uint64_t* ptr64; uint64_t tb64; SsxMachineContext ctx; uint32_t parm_size; uint32_t cur_offset; uint32_t footer_offset; //fill in the footer data tb64 = ssx_ext_timebase_get(); footer.parms.word32 = i_hash_and_count; //this has the parm count and hash state.tbu32 = tb64 >> 32; footer.time_format.word32 = tb64 & 0x00000000ffffffffull; footer.time_format.format = SSX_TRACE_FORMAT_BIG; //round up to 8 byte boundary if(footer.parms.num_parms <= 2) { parm_size = 8; } else { parm_size = 16; } //*****The following operations must be done atomically***** ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); //load in the offset in the cb for the entry we are adding cur_offset = g_ssx_trace_buf.state.offset; //Find the offset for the footer (at the end of the entry) footer_offset = cur_offset + parm_size; //calculate the address of the footer ptr64 = (uint64_t*)&g_ssx_trace_buf.cb[footer_offset & SSX_TRACE_CB_MASK]; //calculate the offset for the next entry in the cb state.offset = footer_offset + sizeof(SsxTraceBig); //update the cb state (tbu and offset) g_ssx_trace_buf.state.word64 = state.word64; //write the data to the circular buffer including the //timesamp, string hash, and 16bit parameter *ptr64 = footer.word64; //*******************exit the critical section*************** ssx_critical_section_exit(&ctx); //write parm values to the circular buffer footer_ptr = (SsxTraceBig*)ptr64; ptr64 = (uint64_t*)&g_ssx_trace_buf.cb[cur_offset & SSX_TRACE_CB_MASK]; *ptr64 = i_parm1; if(parm_size > 8) { ptr64 = (uint64_t*)&g_ssx_trace_buf.cb[(cur_offset + 8) & SSX_TRACE_CB_MASK]; *ptr64 = i_parm2; } //Mark the trace entry update as being completed footer_ptr->parms.complete = 1; } #endif <|start_filename|>src/occ_405/amec/amec_dps.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_dps.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_DPS_H #define _AMEC_DPS_H /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Constants */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Globals */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Defines */ /*----------------------------------------------------------------------------*/ #define TWO_TO_THE_POWER_OF_FIFTEEN 32768 /*----------------------------------------------------------------------------*/ /* Typedef / Enum */ /*----------------------------------------------------------------------------*/ ///DPS Algorithm Model typedef struct amec_dps { ///Frequency request for core voting box uint16_t freq_request; ///Utilization speed request uint16_t util_speed_request; ///Utilization threshold for moving down in frequency (low side) uint16_t tlutil; ///Step size for going up in speed uint16_t step_up; ///Step size for going down in speed uint16_t step_down; ///Number of utilization samples in sliding window uint16_t sample_count_util; ///Epsilon used for determining if a core is active (units of 0.01%) uint16_t epsilon_perc; ///Threshold for going up in frequency uint16_t alpha_up; ///Threshold for going down in frequency uint16_t alpha_down; ///8-bit mask for dynamic power save type (=0:none active) uint8_t type; }amec_dps_t; /*----------------------------------------------------------------------------*/ /* Function Prototypes */ /*----------------------------------------------------------------------------*/ /** * Update per-core utilization variables. * * This function updates all the per-core utilization variables. These * variables are used to populate the slack sensors. * */ void amec_dps_update_core_util(void); /** * Update utilization sensors for a core group. * * This function updates the utilization (slack) sensors for a * given core group. * */ void amec_dps_partition_update_sensors(const uint16_t i_part_id); /** * DPS algorithm function. * * This function implements the different DPS algorithms for a * given core group. * */ void amec_dps_partition_alg(const uint16_t i_part_id); /** * Main DPS function. * * This function is the entry-point for running DPS algorithms * and is aware of the different core groups defined. * */ void amec_dps_main(void); #endif /* #ifndef _AMEC_DPS_H */ <|start_filename|>src/occ_gpe0/apss_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/apss_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" #include "ppe42_scom.h" #include "ipc_api.h" #include "ipc_async_cmd.h" #include "pss_constants.h" #include <apss_structs.h> //H file common with occ_405 #include "gpe_util.h" #include "p9_misc_scom_addresses.h" // PV_CP0_P_PRV_GPIO2 #define APSS_RESET_GPIO (0x2000000000000000ull) // Default to Auto-2 for now, should get set when the mode // is initialized, and before any APSS data is gathered. uint8_t G_apss_mode = APSS_MODE_AUTO2; /* * Function Specification * * Name: apss_start_spi_command * * Description: Writes the P2S_COMMAND register to trigger the execution * of a command loaded into the P2S_WDATA_REG * * End Function Specification */ uint32_t apss_start_spi_command(initGpioArgs_t * args, uint8_t i_noWait) { uint32_t rc = 0; uint64_t regValue = 0x8000000000000000; // Start SPI transaction rc = putscom_abs(SPIPSS_P2S_COMMAND_REG, regValue); if (rc) { PK_TRACE("apss_start_spi_command: SPIPSS_P2S_COMMAND_REG putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_COMMAND_REG, rc, 0x8000000000000000); } else { busy_wait(5); if (!i_noWait) { rc = wait_spi_completion(&(args->error), SPIPSS_P2S_STATUS_REG, 10); if (rc) { PK_TRACE("apss_start_spi_command: Timed out waiting for ops to complete. rc = 0x%08x", rc); //FFDC set in wait_spi_completion } } } return rc; } /* * Function Specification * * Name: apss_init_gpio * * Description: Initialize the APSS GPIO ports * * End Function Specification */ void apss_init_gpio(ipc_msg_t* cmd, void* arg) { //Note: arg was set to 0 in ipc func table (ipc_func_tables.c), so don't use it uint32_t rc; uint32_t ipc_send_rc; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; initGpioArgs_t *args = (initGpioArgs_t*)async_cmd->cmd_data; uint64_t regValue = 0; PK_TRACE("apss_init_gpio: started."); do { // Wait for SPI operations to be complete (up to 10usec timeout) rc = wait_spi_completion(&(args->error), SPIPSS_P2S_STATUS_REG, 10); if (rc) { PK_TRACE("apss_init_gpio: Timed out waiting for ops to complete. rc = 0x%08x", rc); //FFDC set in wait_spi_completion break; } //////////////////////////// // Setup the control regs // frame_size=16, out_count=16, in_delay1=never, in_count2=16 regValue = 0x410FC00004000000; rc = putscom_abs(SPIPSS_P2S_CTRL_REG0, regValue); if (rc) { PK_TRACE("apss_init_gpio: SPIPSS_P2S_CTRL_REG0 putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_CTRL_REG0, rc, regValue); break; } // bridge_enable, clock_divider=36, 2 frames regValue = 0x8090400000000000; rc = putscom_abs(SPIPSS_P2S_CTRL_REG1, regValue); if (rc) { PK_TRACE("apss_init_gpio: SPIPSS_P2S_CTRL_REG1 putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_CTRL_REG1, rc, regValue); break; } // inter_frame_delay=50 (5usec) regValue = 0x0019000000000000; rc = putscom_abs(SPIPSS_P2S_CTRL_REG2, regValue); if (rc) { PK_TRACE("apss_init_gpio: SPIPSS_P2S_CTRL_REG2 putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_CTRL_REG2, rc, regValue); break; } uint64_t port = 0; //Loop through the 2 ports setup for (port=0; port <= 1; port++) { ////////////////////// // Direction (APSS cmd 0x4xxx); Configure GPIO mode (input or output) regValue = args->config0.direction; regValue = regValue << 48; regValue |= 0x4000000000000000; regValue |= (port << 56); rc = putscom_abs(SPIPSS_P2S_WDATA_REG, regValue); if (rc) { PK_TRACE("apss_init_gpio: SPIPSS_P2S_WDATA_REG putscom failed. value:0x%X. rc = 0x%08x", regValue, rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_WDATA_REG, rc, regValue); break; } // Start SPI transaction rc = apss_start_spi_command(args,0); if (rc) { PK_TRACE("apss_init_gpio: SPI command start failed. rc = 0x%08x", rc); //FFDC already added break; } //--------------- // Drive (APSS cmd 0x5xxx) regValue = args->config0.drive; regValue = regValue << 48; regValue |= 0x5000000000000000; regValue |= (port << 56); rc = putscom_abs(SPIPSS_P2S_WDATA_REG, regValue); if (rc) { PK_TRACE("apss_init_gpio: SPIPSS_P2S_WDATA_REG putscom failed. value:0x%X. rc = 0x%08x", regValue, rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_WDATA_REG, rc, regValue); break; } // Start SPI transaction if (port == 0) { rc = apss_start_spi_command(args, 0); }else { //No need to wait since it's the last command. rc = apss_start_spi_command(args, 1); } if (rc) { PK_TRACE("apss_init_gpio: SPI command start failed. rc = 0x%08x", rc); //FFDC already set break; } }//End of port while loop. if (rc) { break; } // Enable GPIO that's used for APSS resets // // Set APSS_RESET_GPIO output high before enabling it's output regValue = APSS_RESET_GPIO; rc = putscom_abs(PU_GPIO_OUTPUT_OR, regValue); if(rc) { PK_TRACE("apss_init: APSS_RESET_GPIO_OUTPUT low failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_SCOM_PUT_FAILED, rc); break; } // Read output enable pins. rc = getscom_abs(PU_GPIO_OUTPUT_EN, &regValue); if(rc) { PK_TRACE("apss_init: Read APSS_RESET_GPIO_OUTPUT_EN failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_SCOM_GET_FAILED, rc); break; } // Enable APSS_RESET_GPIO as output regValue |= APSS_RESET_GPIO; rc = putscom_abs(PU_GPIO_OUTPUT_EN, regValue); if(rc) { PK_TRACE("apss_init: APSS_RESET_GPIO_OUTPUT_EN failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_SCOM_PUT_FAILED, rc); break; } }while(0); // send back a successful response. OCC will check rc and ffdc ipc_send_rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(ipc_send_rc) { PK_TRACE("apss_init_gpio: Failed to send response back. rc = 0x%08x. Halting GPE0", ipc_send_rc); gpe_set_ffdc(&(args->error), 0x00, ipc_send_rc, regValue); pk_halt(); } if(rc == 0) // if ipc_send_rc is 0, wont reach this instruction (pk_halt) { PK_TRACE("apss_init_gpio: completed successfully."); } } /* * Function Specification * * Name: apss_init_mode * * Description: Initialize the APSS mode * * End Function Specification */ void apss_init_mode(ipc_msg_t* cmd, void* arg) { //Note: arg was set to 0 in ipc func table (ipc_func_tables.c), so don't use it uint32_t rc = GPE_RC_SUCCESS; uint32_t ipc_rc = IPC_RC_SUCCESS; uint32_t ipc_send_rc; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; setApssModeArgs_t *args = (setApssModeArgs_t*)async_cmd->cmd_data; uint64_t regValue = 0; PK_TRACE("apss_init_mode: started."); do { // Wait for SPI operations to be complete (up to 10usec timeout) rc = wait_spi_completion(&(args->error), SPIPSS_P2S_STATUS_REG, 10); if (rc) { PK_TRACE("apss_init_mode: Timed out waiting for ops to complete. rc = 0x%08x", rc); //FFDC set in wait_spi_completion break; } //////////////////////////// // Setup the control regs // frame_size=16, out_count1=16 regValue = 0x4100000000000000; rc = putscom_abs(SPIPSS_P2S_CTRL_REG0, regValue); if (rc) { PK_TRACE("apss_init_mode: SPIPSS_P2S_CTRL_REG0 putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_CTRL_REG0, rc, regValue); break; } // bridge_enable, clock_divider=36, 1 frames regValue = 0x8090000000000000; rc = putscom_abs(SPIPSS_P2S_CTRL_REG1, regValue); if (rc) { PK_TRACE("apss_init_mode: SPIPSS_P2S_CTRL_REG1 putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_CTRL_REG1, rc, regValue); break; } // inter_frame_delay=50 (5usec) regValue = 0x0019000000000000; rc = putscom_abs(SPIPSS_P2S_CTRL_REG2, regValue); if (rc) { PK_TRACE("apss_init_mode: SPIPSS_P2S_CTRL_REG2 putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_CTRL_REG2, rc, regValue); break; } //Check for requested APSS mode. if (args->config.mode == APSS_MODE_COMPOSITE) { // APSS command to set composite data streaming mode (APSS cmd 0x8xxx, reserved bits are 1) // binary: 100011aaaa0000gg000000000000000000000000000000000000000000000000 regValue = args->config.numAdcChannelsToRead - 1; //aaaa => Address of last ADC channel (countOfADCChannels - 1) regValue = regValue << 6; //Make space for GPIO port count regValue |= (args->config.numGpioPortsToRead) & 0x03; //gg => Num of GPIO ports regValue = (regValue << 48) | 0x8C00000000000000; //Add Command at D15-D12 G_apss_mode = APSS_MODE_COMPOSITE; } else if (args->config.mode == APSS_MODE_AUTO2) { // Set Auto2 mode to scan all 16 ADC channels regValue = 0x3FC0000000000000; G_apss_mode = APSS_MODE_AUTO2; } else { //Invalid mode. PK_TRACE("apss_init_mode: Given invalid APSS Mode. Mode:0x%X", args->config.mode); rc = GPE_RC_INVALID_APSS_MODE; gpe_set_ffdc(&(args->error), 0x00, rc, args->config.mode); ipc_rc = IPC_RC_CMD_FAILED; break; } rc = putscom_abs(SPIPSS_P2S_WDATA_REG, regValue); if (rc) { PK_TRACE("apss_init_mode: SPIPSS_P2S_WDATA_REG putscom to set MODE failed. value:0x%X. rc = 0x%08x", regValue, rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_WDATA_REG, rc, regValue); break; } regValue = 0x8000000000000000; // Start SPI transaction rc = putscom_abs(SPIPSS_P2S_COMMAND_REG, regValue); if (rc) { PK_TRACE("apss_init_mode: SPIPSS_P2S_COMMAND_REG putscom failed. rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), SPIPSS_P2S_COMMAND_REG, rc, 0x8000000000000000); } }while(0); // send back a response PK_TRACE("apss_init_mode: Sending APSS response ReturnCode:0x%X. APSSrc:0x%X (0 = Success)", ipc_rc, rc); ipc_send_rc = ipc_send_rsp(cmd, ipc_rc); //If we fail to send ipc response, then this error takes prescedence over any other error. //TODO: See if there's another space to write the error out to. if(ipc_send_rc) { PK_TRACE("apss_init_mode: Failed to send response back to mode initialization. Halting GPE0", ipc_send_rc); gpe_set_ffdc(&(args->error), 0x00, ipc_send_rc, regValue); pk_halt(); } if(rc == 0 && ipc_rc == IPC_RC_SUCCESS) // if ipc_send_rc, wont reach this instruction (pk_halt) { PK_TRACE("apss_init_mode: completed successfully."); } } // ---------------------------------------------------- // Toggle the output of the APSS RESET pin // ---------------------------------------------------- void apss_toggle_hw_reset(ipc_msg_t* cmd, void* arg) { static int g_apss_reset_state = ~(0); int rc = 0; uint32_t apss_reset_address; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; initGpioArgs_t *args = (initGpioArgs_t*)async_cmd->cmd_data; if(g_apss_reset_state) // not in reset { apss_reset_address = PU_GPIO_OUTPUT_CLR; } else { apss_reset_address = PU_GPIO_OUTPUT_OR; } g_apss_reset_state = ~g_apss_reset_state; PK_TRACE("apss_toggle_apss_hw_reset: %d",(uint16_t)g_apss_reset_state); // Set/clear GPIO2 output rc = putscom_abs(apss_reset_address, APSS_RESET_GPIO); if(rc) { PK_TRACE("apss_toggle_hw_reset: APSS_RESET_GPIO_OUTPUT toggle failed. rc:0x%08x",rc); gpe_set_ffdc(&(args->error), 0, GPE_RC_SCOM_PUT_FAILED, rc); } // send back a successful response. OCC will check rc and ffdc rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("apss_toggle_hw_reset: Failed to send response back. rc = 0x%08x. Halting GPE0", rc); gpe_set_ffdc(&(args->error), 0x00, rc, 0); pk_halt(); } } <|start_filename|>src/occ_405/proc/test/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occ_405/proc/test/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2011,2015 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG proctest_CFILES = \ ../../common.c \ ../../errl/errl.c \ ../../pss/apss.c \ ../../rtls/rtls.c \ ../../thread/threadSch.c \ ../../aplt/appletManager.c \ ../proc_data.c \ ../../rtls/rtls_tables.c \ ../../timer/timer.c \ ../../dcom/dcom.c \ ../../occ_sys_config.c \ main.c all_cfiles = ${proctest_CFILES} occ_GPEFILES = ../../gpe/apss_init.S \ ../../gpe/apss_composite.S \ ../../gpe/apss_meas_read_start.S \ ../../gpe/apss_meas_read_cont.S \ ../../gpe/apss_meas_read_complete.S \ ../../gpe/pore_test.S all_gpefiles = ${occ_GPEFILES} APP = proctest APP_INCLUDES += -I../../../ssx APP_INCLUDES += -I../../../lib APP_INCLUDES += -I../../incl APP_INCLUDES += -I../../trac APP_INCLUDES += -I../../errl APP_INCLUDES += -I../../thread APP_INCLUDES += -I../../gpe APP_INCLUDES += -I../../aplt APP_INCLUDES += -I../../aplt/incl APP_INCLUDES += -I../../sensor APP_INCLUDES += -I../../pss APP_INCLUDES += -I../../rtls APP_INCLUDES += -I../../async APP_INCLUDES += -I../../proc APP_INCLUDES += -I../../timer APP_INCLUDES += -I../../dcom APP_INCLUDES += -I. D = -DOCC_FIRMWARE=1 #D = -DVERIFICATION=1 \ -DSSX_STACK_CHECK=0 \ -DINITIALIZE_PMC=0 \ -DINITIALIZE_SIMICS_IO=0 \ -DINITIALIZE_RTX_IO=1 \ -DINITIALIZE_PBA=1 \ -DSIMICS_MAGIC_PANIC=1 \ -DSSX_KERNEL_TRACE_ENABLE=1 SOURCES = ${all_cfiles} ${all_gpefiles} MODE = validation PGP_ASYNC_SUPPORT = 1 include ./app.mk pgas: $(CC) $(CFLAGS) -c -Wa,-al -Wa,--listing-cont-lines='10' ${all_gpefiles} <|start_filename|>src/occ_405/trac/trac_interface.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/trac/trac_interface.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _TRAC_INTERFACE_H #define _TRAC_INTERFACE_H //************************************************************************* // Includes //************************************************************************* #include "ssx.h" #include <occ_common.h> //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* /* Used to trace 0 - 5 arguments or a binary buffer when using a hash value. */ #define TRACE(i_td,i_string,args...) \ trace_adal_write_all(i_td,trace_adal_hash(i_string,-1),__LINE__,0,##args) #define TRACEBIN(i_td,i_string,i_ptr,i_size) \ trac_write_bin(i_td,trace_adal_hash(i_string,0),__LINE__,i_ptr,i_size) #ifndef NO_TRAC_STRINGS #define FIELD(a) \ printf("%s",a) #define FIELD1(a,b) \ printf("%s%lx",a,(unsigned long)b) #else // NO_TRAC_STRINGS #define FIELD(a) #define FIELD1(a,b) #endif // NO_TRAC_STRINGS #define SUCCESS 0 //************************************************************************* // Defines/Enums //************************************************************************* #define TRACE_MAX_ARGS 5 /* Maximum number of args to trace */ typedef uint32_t trace_hash_val; // NOTE! Increment this when new components are added! #define TRAC_NUM_TRACE_COMPONENTS 1 #define TRACE_BUFFER_SIZE 8192 #define NUMBER_TRACE_BUFFERS 3 #define ALL_TRACE_BUFFERS_SZ (TRACE_BUFFER_SIZE * NUMBER_TRACE_BUFFERS) #define CIRCULAR_BUFFER_SIZE 4 // These are indicies into g_des_array #define INF_TRACE_DESCRIPTOR 0 #define ERR_TRACE_DESCRIPTOR 1 #define IMP_TRACE_DESCRIPTOR 2 //************************************************************************* // Structures //************************************************************************* /* * Structure is put at beginning of all trace buffers */ typedef struct trace_buf_head { UCHAR ver; /* version of this struct (1) */ UCHAR hdr_len; /* size of this struct in bytes */ UCHAR time_flg; /* meaning of timestamp entry field */ UCHAR endian_flg; /* flag for big ('B') or little ('L') endian */ CHAR comp[16]; /* the buffer name as specified in init call */ UINT32 size; /* size of buffer, including this struct */ UINT32 times_wrap; /* how often the buffer wrapped */ UINT32 next_free; /* offset of the byte behind the latest entry */ UINT32 te_count; /* Updated each time a trace is done */ UINT32 extracted; /* Not currently used */ }trace_buf_head_t; /* * Timestamp and thread id for each trace entry. */ typedef struct trace_entry_stamp { UINT32 tbh; /* timestamp upper part */ UINT32 tbl; /* timestamp lower part */ UINT32 tid; /* process/thread id */ }trace_entry_stamp_t; /* * Structure is used by adal app. layer to fill in trace info. */ typedef struct trace_entry_head { UINT16 length; /* size of trace entry */ UINT16 tag; /* type of entry: xTRACE xDUMP, (un)packed */ UINT32 hash; /* a value for the (format) string */ UINT32 line; /* source file line number of trace call */ }trace_entry_head_t; /* * Parameter traces can be all contained in one write. */ typedef struct trace_entire_entry { trace_entry_stamp_t stamp; trace_entry_head_t head; UINT32 args[TRACE_MAX_ARGS + 1]; } trace_entire_entry_t; /* * Binary first writes header and time stamp. */ typedef struct trace_bin_entry { trace_entry_stamp_t stamp; trace_entry_head_t head; } trace_bin_entry_t; /* * Used as input to traces to get to correct buffer. */ typedef trace_buf_head_t * tracDesc_t; /* * Structure is used to hold array of all trace descriptors */ typedef struct trace_descriptor_array { tracDesc_t *entry; /* Pointer to trace descriptor */ CHAR *comp; /* Pointer to component name */ SsxSemaphore *sem; /* Pointer to semaphore */ }trace_descriptor_array_t; typedef struct circular_buf_head { UINT32 head; // pointer to head UINT32 tail; // pointer to tail UINT32 entryCount; // nums of entry } circular_buf_header_t; typedef struct circular_entire_data { UINT32 len; CHAR comp[4]; trace_entire_entry_t entry; } circular_entire_data_t; //************************************************************************* // Globals //************************************************************************* // All TPMF component trace descriptors. extern tracDesc_t g_trac_inf; extern tracDesc_t g_trac_err; extern tracDesc_t g_trac_imp; extern const trace_descriptor_array_t g_des_array[]; //************************************************************************* // Function Prototypes //************************************************************************* /* * Allocate and initialize all trace buffers in memory. * * This function will allocate memory for each of the pre-defined trace * buffers, initialize the buffers with starting data, and set up the * trace descriptors which each component will use to trace. * * This function must be called first before any components try to trace! * * return Non-zero return code on error. */ UINT TRAC_init_buffers(void); /* * Retrieve full trace buffer for component i_comp * * This function assumes memory has already been allocated for * the full trace buffer in o_data. * * param i_td_ptr Trace descriptor of buffer to retrieve. * param o_data Pre-allocated pointer to where data will be stored. * * return Non-zero return code on error */ UINT TRAC_get_buffer(const trace_descriptor_array_t *i_td_ptr, void *o_data); /* * Retrieve partial trace buffer for component i_comp * * This function assumes memory has already been allocated for * the trace buffer (size io_size). This function will copy * in up to io_size in bytes to the buffer and set io_size * to the exact size that is copied in. * * param i_td_ptr Trace descriptor of buffer to retrieve. * param o_data Pre-allocated pointer to where data will be stored. * param io_size Size of trace data to retrieve (input) * Actual size of trace data stored (output) * * return Non-zero return code on error */ UINT TRAC_get_buffer_partial(const trace_descriptor_array_t *i_td_ptr, void *o_data, UINT *io_size); /* * Retrieve trace descriptor for input component name * * param i_comp Component name to retrieve trace descriptor for. * * return Valid trace descriptor on success, NULL on failure. */ const trace_descriptor_array_t* TRAC_get_td(const char *i_comp); /* * Reset all trace buffers * * return Non-zero return code on error */ UINT TRAC_reset_buf(void); /* * Trace input integers to trace buffer. * * This function assumes i_td has been initialized. * * param io_td Initialized trace descriptor pointer to buffer to trace to. * param i_hash Hash value to be recorded for this trace. * param i_fmt Output format * param i_line Line number trace is occurring on. * param i_type trace type. field or debug. * param ... params that are limited to a size of 4 bytes, i.e. int, uint32_t, nnn* * * return Non-zero return code on error. */ UINT trace_adal_write_all(const trace_descriptor_array_t *io_td,const trace_hash_val i_hash, const char *i_fmt,const ULONG i_line, const ULONG i_type,...); /* * Trace input integers to trace buffer. * * This function assumes i_td has been initialized. * * param io_td Initialized trace descriptor pointer to buffer to trace to. * param i_hash Hash value to be recorded for this trace. * param i_line Line number trace is occurring on. * param i_num_args Number of arguments to trace. * param i_1 Input Parameter 1 * param i_2 Input Parameter 2 * param i_3 Input Parameter 3 * param i_4 Input Parameter 4 * param i_5 Input Parameter 5 * * return Non-zero return code on error. */ UINT trac_write_int(const trace_descriptor_array_t *io_td,const trace_hash_val i_hash, const ULONG i_line, const UINT i_num_args, const ULONG i_1,const ULONG i_2,const ULONG i_3, const ULONG i_4,const ULONG i_5 ); //************************************************************************* // Functions //************************************************************************* #endif //_TRAC_INTERFACE_H <|start_filename|>src/occ_405/gpu/gpu_service_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/gpu/gpu_service_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _GPU_SERVICE_CODES_H_ #define _GPU_SERVICE_CODES_H_ #include <comp_ids.h> enum gpuModuleId { GPU_MID_INIT = GPU_COMP_ID | 0x00, GPU_MID_GPU_SM = GPU_COMP_ID | 0x01, GPU_MID_MARK_GPU_FAILED = GPU_COMP_ID | 0x02, GPU_MID_GPU_SCHED_REQ = GPU_COMP_ID | 0x03, GPU_MID_GPU_SCHED_RSP = GPU_COMP_ID | 0x04, GPU_MID_GPU_RESET_SM = GPU_COMP_ID | 0x05, GPU_MID_GPU_READ_TEMP = GPU_COMP_ID | 0x06, GPU_MID_GPU_READ_MEM_TEMP = GPU_COMP_ID | 0x07, GPU_MID_GPU_READ_MEM_TEMP_CAPABLE = GPU_COMP_ID | 0x08, GPU_MID_GPU_CHECK_DRIVER_LOADED = GPU_COMP_ID | 0x09, GPU_MID_GPU_READ_PWR_LIMIT = GPU_COMP_ID | 0x0A, GPU_MID_GPU_SET_PWR_LIMIT = GPU_COMP_ID | 0x0B, GPU_MID_GPE_GPU_INIT_SCHED_REQ = GPU_COMP_ID | 0x0C, }; #endif /* #ifndef _GPU_SERVICE_CODES_H_ */ <|start_filename|>src/occ_405/amec/amec_parm.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_parm.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //*************************************************************************/ // Includes //*************************************************************************/ #include <common_types.h> #include <amec_parm.h> #include <string.h> #include <occ_common.h> #include <amec_amester.h> //*************************************************************************/ // Externs //*************************************************************************/ extern uint16_t G_amester_max_data_length; //*************************************************************************/ // Defines/Enums //*************************************************************************/ //*************************************************************************/ // Globals //*************************************************************************/ ///Array that maintains a list of all parameters built extern amec_parm_t g_amec_parm_list[]; //*************************************************************************/ // Function Declarations //*************************************************************************/ //*************************************************************************/ // Functions //*************************************************************************/ void amec_parm_get_number(const IPMIMsg_t *i_psMsg, UINT8 *o_pu8Resp, UINT16 *o_pu16RespLength, UINT8 *o_retval) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ o_pu8Resp[0] = (UINT8)(AMEC_PARM_NUMBER_OF_PARAMETERS>>8); o_pu8Resp[1] = (UINT8)(AMEC_PARM_NUMBER_OF_PARAMETERS); *o_pu16RespLength=2; *o_retval=COMPCODE_NORMAL; return; } void amec_parm_get_config(const IPMIMsg_t *i_psMsg, UINT8 *o_pu8Resp, UINT16 *o_pu16RespLength, UINT8 *o_retval) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ AMEC_PARM_GUID l_id; // parameter id UINT16 l_j; // index into return message UINT16 l_length = 0; // response length CHAR *l_src; //pointer for copying name /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ l_id = (AMEC_PARM_GUID) CONVERT_UINT8_ARRAY_UINT16( i_psMsg->au8CmdData_ptr[1], i_psMsg->au8CmdData_ptr[2]); l_j = 0; // write index byte for response for (; l_id < AMEC_PARM_NUMBER_OF_PARAMETERS; l_id++) { if (l_j + strlen(g_amec_parm_list[l_id].name) + 1 + 10 >= G_amester_max_data_length) { // +1 = null terminator in name. // +10 = type, mode, vector_length, length (optional) break; // hit end of response buffer } // Copy name into output buffer l_src = g_amec_parm_list[l_id].name; do { o_pu8Resp[l_j++] = *l_src; } while (*l_src++ != 0); /* copy string until \0 */ o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].type); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].mode); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].vector_length>>24); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].vector_length>>16); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].vector_length>>8); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].vector_length); // If base type is unstructured data or string, send length if (g_amec_parm_list[l_id].type == AMEC_PARM_TYPE_STRING || g_amec_parm_list[l_id].type == AMEC_PARM_TYPE_RAW) { o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].length>>24); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].length>>16); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].length>>8); o_pu8Resp[l_j++] = (UINT8)(g_amec_parm_list[l_id].length); } // update length of response parameter just copied l_length = l_j; } *o_pu16RespLength=l_length; *o_retval=COMPCODE_NORMAL; return; } void amec_parm_read(const IPMIMsg_t *const i_psMsg, UINT8 *const o_pu8Resp, UINT16 *const o_pu16RespLength, UINT8 *const o_retval) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ AMEC_PARM_GUID l_id; UINT16 i=0; // output index UINT16 l_maxresponse = G_amester_max_data_length - 1; // -1 since return code is 1B UINT8 *l_src_ptr; // pointer to first byte of data UINT8 *l_end_ptr; // mark end of data UINT32 b; // start byte /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { *o_retval = COMPCODE_NORMAL; /* assume no error */ // Parse input command // Get the byte offset b = CONVERT_UINT8_ARRAY_UINT32( i_psMsg->au8CmdData_ptr[1], i_psMsg->au8CmdData_ptr[2], i_psMsg->au8CmdData_ptr[3], i_psMsg->au8CmdData_ptr[4]); // Get parameter id l_id = CONVERT_UINT8_ARRAY_UINT16( i_psMsg->au8CmdData_ptr[5], i_psMsg->au8CmdData_ptr[6]); if (l_id >= AMEC_PARM_NUMBER_OF_PARAMETERS) { *o_retval = COMPCODE_PARAM_OUT_OF_RANGE; *o_pu16RespLength = 0; break; } if (g_amec_parm_list[l_id].preread) { amec_parm_preread(l_id); } // Copy value to output buffer // Set src to first byte to send back l_src_ptr = g_amec_parm_list[l_id].value_ptr + b; // Set end pointer 1 beyond last byte to send. It is limited either // on the value size, or the IPMI message size. l_end_ptr = g_amec_parm_list[l_id].value_ptr + (g_amec_parm_list[l_id].vector_length * g_amec_parm_list[l_id].length); if (l_src_ptr + l_maxresponse < l_end_ptr) { l_end_ptr = l_src_ptr + l_maxresponse; } while ((UINT32)l_src_ptr < (UINT32)l_end_ptr) { //Copy next byte to output o_pu8Resp[i++] = (UINT8)*l_src_ptr++; } *o_pu16RespLength = i; } while (FALSE); } void amec_parm_write(const IPMIMsg_t *const i_psMsg, UINT8 *const o_pu8Resp, UINT16 *const o_pu16RespLength, UINT8 *const o_retval) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ AMEC_PARM_GUID l_id; UINT16 i=0; // output index UINT8 *l_dest_ptr = NULL; // pointer to first byte of data UINT8 *l_start_ptr; // mark end of data UINT8 *l_end_ptr = NULL; // mark end of data UINT32 b; // start byte UINT32 l_bytes = 0; // number of bytes written /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { *o_retval = COMPCODE_NORMAL; /* assume no error */ // Parse input command // Get parameter id l_id = CONVERT_UINT8_ARRAY_UINT16( i_psMsg->au8CmdData_ptr[1], i_psMsg->au8CmdData_ptr[2]); // Get the starting byte of element b = CONVERT_UINT8_ARRAY_UINT32( i_psMsg->au8CmdData_ptr[3], i_psMsg->au8CmdData_ptr[4], i_psMsg->au8CmdData_ptr[5], i_psMsg->au8CmdData_ptr[6]); if (l_id >= AMEC_PARM_NUMBER_OF_PARAMETERS) { *o_retval = COMPCODE_PARAM_OUT_OF_RANGE; *o_pu16RespLength = 0; break; } i = 7; // start of data to write in input buffer // Check if read-only if (g_amec_parm_list[l_id].mode & AMEC_PARM_MODE_READONLY) { *o_retval = COMPCODE_WRONG_PRIV; *o_pu16RespLength = 0; break; } l_start_ptr = g_amec_parm_list[l_id].value_ptr + b; l_dest_ptr = l_start_ptr; // Set end pointer 1 beyond last byte to send. It is limited either // on the value size, or the IPMI message size. l_end_ptr = g_amec_parm_list[l_id].value_ptr + (g_amec_parm_list[l_id].vector_length * g_amec_parm_list[l_id].length); // Copy value from input buffer while ((UINT32)l_dest_ptr < (UINT32)l_end_ptr && i < i_psMsg->u8CmdDataLen) { *l_dest_ptr++ = i_psMsg->au8CmdData_ptr[i++]; } l_bytes = l_dest_ptr - l_start_ptr; // Return number of bytes written *o_pu16RespLength = 4; o_pu8Resp[0] = (UINT8)(l_bytes >> 24); o_pu8Resp[1] = (UINT8)(l_bytes >> 16); o_pu8Resp[2] = (UINT8)(l_bytes >> 8); o_pu8Resp[3] = (UINT8)(l_bytes); // Run post-write routine only if last byte of parameter was written // Some long parameters require multiple write calls due to IPMI // message limits, so we only call the postwrite routine when the // last byte of the parameter is written. if (l_dest_ptr == l_end_ptr && g_amec_parm_list[l_id].postwrite) { amec_parm_postwrite(l_id); } } while (FALSE); } /*----------------------------------------------------------------------------*/ /* End */ /*----------------------------------------------------------------------------*/ <|start_filename|>src/ssx/ssx/ssx_thread_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_thread_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_thread_core.c /// \brief SSX thread APIs /// /// The entry points in this file are considered 'core' routines that will /// always be present at runtime in any SSX application that enables threads. #include "ssx.h" #define __SSX_THREAD_CORE_C__ // This routine is only used locally. Noncritical interrupts must be disabled // at entry. static inline int __ssx_thread_is_active(SsxThread* thread) { return ((thread->state != SSX_THREAD_STATE_COMPLETED) && (thread->state != SSX_THREAD_STATE_DELETED)); } // This routine is only used locally. Noncritical interrupts must be disabled // at entry. static inline int __ssx_thread_is_mapped(SsxThread* thread) { return (thread->state == SSX_THREAD_STATE_MAPPED); } // This routine is only used locally. Noncritical interrupts must be disabled // at entry. This is only called on mapped threads. static inline int __ssx_thread_is_runnable(SsxThread* thread) { return __ssx_thread_queue_member(&__ssx_run_queue, thread->priority); } // This routine is only used locally. Noncritical interrupts must be disabled // at entry. static inline SsxThread* __ssx_thread_at_priority(SsxThreadPriority priority) { return (SsxThread*)__ssx_priority_map[priority]; } // This routine is only used locally. Noncritical interrupts must be disabled // at entry. The caller must also have checked that the priority is free. // This routine is only called on threads known to be in a suspended state, // either SSX_THREAD_STATE_SUSPENDED_RUNNABLE or // SSX_THREAD_STATE_SUSPENDED_BLOCKED. Mapping a runnable thread adds it to // the run queue. Mapping a thread pending on a semaphore either takes the // count and becomes runnable or adds the thread to the pending queue for the // semaphore. Mapping a sleeping thread requires no further action // here. Scheduling after the map must be handled by the caller. void __ssx_thread_map(SsxThread* thread) { SsxThreadPriority priority; priority = thread->priority; __ssx_priority_map[priority] = thread; if (thread->state == SSX_THREAD_STATE_SUSPENDED_RUNNABLE) { __ssx_thread_queue_insert(&__ssx_run_queue, priority); } else if (thread->flags & SSX_THREAD_FLAG_SEMAPHORE_PEND) { if (thread->semaphore->count) { thread->semaphore->count--; __ssx_thread_queue_insert(&__ssx_run_queue, priority); } else { __ssx_thread_queue_insert(&(thread->semaphore->pending_threads), priority); } } thread->state = SSX_THREAD_STATE_MAPPED; if (SSX_KERNEL_TRACE_ENABLE) { if (__ssx_thread_is_runnable(thread)) { SSX_KERN_TRACE("THREAD_MAPPED_RUNNABLE(%d)", priority); } else if (thread->flags & SSX_THREAD_FLAG_SEMAPHORE_PEND) { SSX_KERN_TRACE("THREAD_MAPPED_SEMAPHORE_PEND(%d)", priority); } else { SSX_KERN_TRACE("THREAD_MAPPED_SLEEPING(%d)", priority); } } } // This routine is only used locally. Noncritical interrupts must be disabled // at entry. This routine is only ever called on threads in the // SSX_THREAD_STATE_MAPPED. Unmapping a thread removes it from the priority // map, the run queue and any semaphore pend, but does not cancel any // timers. Scheduling must be handled by the code calling // __ssx_thread_unmap(). void __ssx_thread_unmap(SsxThread* thread) { SsxThreadPriority priority; priority = thread->priority; __ssx_priority_map[priority] = 0; if (__ssx_thread_is_runnable(thread)) { thread->state = SSX_THREAD_STATE_SUSPENDED_RUNNABLE; __ssx_thread_queue_delete(&__ssx_run_queue, priority); } else { thread->state = SSX_THREAD_STATE_SUSPENDED_BLOCKED; if (thread->flags & SSX_THREAD_FLAG_SEMAPHORE_PEND) { __ssx_thread_queue_delete(&(thread->semaphore->pending_threads), priority); } } } // Schedule and run the highest-priority mapped runnable thread. // // The priority of the next thread to run is first computed. This may be // SSX_THREADS, indicating that the only thread to run is the idle thread. // This will always cause (or defer) a 'context switch' to the idle thread. // Otherwise, if the new thread is not equal to the current thread this will // also cause (or defer) a context switch. Note that scheduling is defined in // terms of priorities but actually implemented in terms of SsxThread pointers. // // If we are not yet in thread mode we're done - threads will be started by // ssx_start_threads() later. If we're in thread context a context switch // happens immediately. In an interrupt context the switch is deferred to the // end of SSX_NONCRITICAL interrupt processing. void __ssx_schedule(void) { __ssx_next_priority = __ssx_thread_queue_min(&__ssx_run_queue); __ssx_next_thread = __ssx_priority_map[__ssx_next_priority]; if ((__ssx_next_thread == 0) || (__ssx_next_thread != __ssx_current_thread)) { if (__ssx_kernel_mode_thread()) { if (__ssx_kernel_context_thread()) { if (__ssx_current_thread != 0) { __ssx_switch(); } else { __ssx_next_thread_resume(); } } else { __ssx_delayed_switch = 1; } } } } // This routine is only used locally. // // Completion and deletion are pretty much the same thing. Completion is // simply self-deletion of the current thread (which is mapped by // definition.) The complete/delete APIs have slightly different error // conditions but are otherwise the same. // // Deleting a mapped thread first unmaps (suspends) the thread, which takes // care of removing the thread from any semaphores it may be pending on. Then // any outstanding timer is also cancelled. // // If the current thread is being deleted we install the idle thread as // __ssx_current_thread, so scheduling is forced and no context is saved on // the context switch. // // Note that we do not create trace events for unmapped threads since the trace // tag only encodes the priority, which may be in use by a mapped thread. void __ssx_thread_delete(SsxThread* thread, SsxThreadState final_state) { SsxMachineContext ctx; int mapped; ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); mapped = __ssx_thread_is_mapped(thread); if (mapped) { __ssx_thread_unmap(thread); } __ssx_timer_cancel(&(thread->timer)); thread->state = final_state; if (mapped) { if (SSX_KERNEL_TRACE_ENABLE) { if (final_state == SSX_THREAD_STATE_DELETED) { SSX_KERN_TRACE("THREAD_DELETED(%d)", thread->priority); } else { SSX_KERN_TRACE("THREAD_COMPLETED(%d)", thread->priority); } } if (thread == __ssx_current_thread) { __ssx_current_thread = 0; } __ssx_schedule(); } ssx_critical_section_exit(&ctx); } // Generic thread timeout // // This routine is called as a timer callback either because a sleeping thread // has timed out or a thread pending on a semaphore has timed out. If the // thread is not already runnable then the the timeout flag is set, and if the // thread is mapped it is scheduled. // // This implementation allows that a thread blocked on a timer may have been // made runnable by some other mechanism, such as acquiring a semaphore. In // order to provide an iteration-free implementation of // ssx_semaphore_release_all(), cancelling any semaphore timeouts is deferred // until the thread runs again. // // __ssx_thread_timeout() is currenly the only timer interrupt called from a // critical section. // // Note that we do not create trace events for unmapped threads since the trace // tag only encodes the priority, which may be in use by a mapped thread. void __ssx_thread_timeout(void* arg) { SsxThread* thread = (SsxThread*)arg; switch (thread->state) { case SSX_THREAD_STATE_MAPPED: if (!__ssx_thread_is_runnable(thread)) { thread->flags |= SSX_THREAD_FLAG_TIMED_OUT; __ssx_thread_queue_insert(&__ssx_run_queue, thread->priority); __ssx_schedule(); } break; case SSX_THREAD_STATE_SUSPENDED_RUNNABLE: break; case SSX_THREAD_STATE_SUSPENDED_BLOCKED: thread->flags |= SSX_THREAD_FLAG_TIMED_OUT; thread->state = SSX_THREAD_STATE_SUSPENDED_RUNNABLE; break; default: SSX_PANIC(SSX_THREAD_TIMEOUT_STATE); } } // This routine serves as a container for the SSX_START_THREADS_HOOK and // actually starts threads. The helper routine __ssx_call_ssx_start_threads() // arranges this routine to be called with interrupts disabled while running // on the noncritical interrupt stack. // // The reason for this roundabout is that we want to be able to run a hook // routine (transparent to the application) that can hand over every last byte // of free memory to "malloc()" - including the stack of main(). Since we // always need to run on some stack, we chose to run the hook on the kernel // noncritical interrupt stack. However to do this safely we need to make sure // that no interrupts will happen during this time. When __ssx_thread_resume() // is finally called all stack-based context is lost but it doesn't matter at // that point - it's a one-way street into thread execution. // // This is considered part of ssx_start_threads() and so is also considered a // 'core' routine. void __ssx_start_threads(void) { SSX_START_THREADS_HOOK; __ssx_next_thread_resume(); SSX_PANIC(SSX_START_THREADS_RETURNED); } /// Start SSX threads /// /// This routine starts the SSX thread scheduler infrastructure. This routine /// must be called after a call of \c ssx_initialize(). This routine never /// returns. Interrupt (+ timer) only configurations of SSX need not call this /// routine. /// /// Note: This tiny routine is considered a 'core' routine so that the /// initialziation code can safely recover all 'init' code space before /// starting threads. /// /// This routine typically does not return - any return value indicates an /// error; see \ref ssx_errors /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was called twice. int ssx_start_threads(void) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(__ssx_kernel_mode_thread(), SSX_ILLEGAL_CONTEXT_THREAD); } __ssx_call_ssx_start_threads(); return 0; } /// Resume a suspended thread /// /// \param thread The thread to resume /// /// SSX only allows one thread at a time to run at a given priority, and /// implements the notion of a thread \e claiming a priority. A suspended /// thread claims a priority when it is mapped by a call of /// ssx_thread_resume(). This API will succeed only if no other active thread /// is currently mapped at the priority assigned to the thread. SSX provides /// the ssx_thread_at_priority() API which allows an application-level /// scheduler to correctly manage multiple threads running at the same /// priority. /// /// If the thread was sleeping while suspended it remains asleep. However if /// the sleep timer timed out while the thread was suspended it will be /// resumed runnable. /// /// If the thread was blocked on a semaphore when it was suspended, then when /// the thread is resumed it will attempt to reacquire the semaphore. /// However, if the thread was blocked on a semaphore with timeout while /// suspended and the timeout interval has passed, the thread will be resumed /// runnable and see that the semaphore pend timed out. /// /// It is not an error to call ssx_thread_resume() on a mapped /// thread. However it is an error to call ssx_thread_resume() on a completed /// or deleted thread. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion, including calls on a \a thread that is /// already mapped. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was called /// from a critical interrupt context. /// /// \retval -SSX_INVALID_THREAD_AT_RESUME1 The \a thread is a null (0) pointer. /// /// \retval -SSX_INVALID_THREAD_AT_RESUME2 The \a thread is not active, /// i.e. has completed or been deleted. /// /// \retval -SSX_PRIORITY_IN_USE_AT_RESUME Another thread is already mapped at /// the priority of the \a thread. int ssx_thread_resume(SsxThread* thread) { SsxMachineContext ctx; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT(); SSX_ERROR_IF(thread == 0, SSX_INVALID_THREAD_AT_RESUME1); } ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL(!__ssx_thread_is_active(thread), SSX_INVALID_THREAD_AT_RESUME2, &ctx); } if (!__ssx_thread_is_mapped(thread)) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL(__ssx_priority_map[thread->priority] != 0, SSX_PRIORITY_IN_USE_AT_RESUME, &ctx); } __ssx_thread_map(thread); __ssx_schedule(); } ssx_critical_section_exit(&ctx); return SSX_OK; } /// Suspend a thread /// /// Any active thread can be suspended. A suspended thread 1) remains active /// but will not be scheduled; 2) relinquishes its priority assignment, /// allowing another thread to be resumed at the suspended thread's priority; /// and 3) disassociates from any semaphore mutual exclusion it may have been /// participating in. /// /// If a sleeping thread is suspended, the sleep timer remains active but a /// timeout of the timer simply marks the thread as runnable, but does not /// resume the thread. /// /// If a thread blocked on a semaphore is suspended, the thread no longer /// participates in the semaphore mutual exclusion. If the thread is later /// resumed it will attempt to acquire the semaphore again the next time it /// runs (unless it was blocked with a timeout and the timeout has expired). /// /// If a thread blocked on a semaphore with timeout is suspended, the /// semaphore timeout timer continues to run. If the timer times out while the /// thread is suspended the thread is simply marked runnable. If the thread is /// later resumed, the suspended call of \c ssx_semaphore_pend() will return the /// timeout code -SSX_SEMAPHORE_PEND_TIMED_OUT. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion, including calls on a \a thread that is /// already suspended. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was called from a critical /// interrupt context. /// /// \retval -SSX_INVALID_THREAD_AT_SUSPEND1 The \a thread is a null (0) pointer /// /// \retval -SSX_INVALID_THREAD_AT_SUSPEND2 The \a thread is not active, /// i.e. has completed or been deleted. int ssx_thread_suspend(SsxThread* thread) { SsxMachineContext ctx; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT(); SSX_ERROR_IF((thread == 0), SSX_INVALID_THREAD_AT_SUSPEND1); } ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL(!__ssx_thread_is_active(thread), SSX_INVALID_THREAD_AT_SUSPEND2, &ctx); } if (__ssx_thread_is_mapped(thread)) { SSX_KERN_TRACE("THREAD_SUSPENDED(%d)", thread->priority); __ssx_thread_unmap(thread); __ssx_schedule(); } ssx_critical_section_exit(&ctx); return SSX_OK; } /// Delete a thread /// /// Any active thread can be deleted. If a thread is deleted it is removed /// from the run queue, deleted from the timer queue (if sleeping or blocked /// on a semaphore with timeout), and deleted from the semaphore mutual /// exclusion if blocked on a semaphore. The thread control block is then /// marked as deleted. /// /// Once a thread has completed or been deleted the thread structure and /// thread stack areas can be used for other purposes. /// /// \param thread The thread to delete /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors. If a /// thread deletes itself this API does not return at all. /// /// \retval 0 Successful completion, including calls on a \a thread that has /// completed or had already been deleted. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was called from a critical /// interrupt context. /// /// \retval -SSX_INVALID_THREAD_AT_DELETE The \a thread is a null (0) pointer. int ssx_thread_delete(SsxThread* thread) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT(); SSX_ERROR_IF(thread == 0, SSX_INVALID_THREAD_AT_DELETE); } __ssx_thread_delete(thread, SSX_THREAD_STATE_DELETED); return SSX_OK; } /// Complete a thread /// /// If a thread ever returns from the subroutine defining the thread entry /// point, the thread is removed from all SSX kernel data structures and /// marked completed. The thread routine can also use the API ssx_complete() /// to make this more explicit if desired. SSX makes no distinction between /// completed and deleted threads, but provides these indications for /// the benefit of the application. /// /// Note that this API is only available from the current thread to mark its /// own completion. /// /// Once a thread has completed or been deleted the thread structure and /// thread stack areas can be used for other purposes. /// /// Any return value indicates an error; see \ref ssx_errors. In the event of /// a successful completion this API does not return to the caller, which is /// always the thread context being completed. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was not called from a thread /// context. // Note: Casting __ssx_current_thread removes the 'volatile' attribute. int ssx_complete(void) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_UNLESS_THREAD_CONTEXT(); } __ssx_thread_delete((SsxThread*)__ssx_current_thread, SSX_THREAD_STATE_COMPLETED); return SSX_OK; } /// Sleep a thread until an absolute time /// /// \param time An absolute time as measured by the SSX timebase /// /// Threads can use this API to sleep until an absolute time. Sleeping threads /// are not scheduled, although they maintain their priorities. This differs /// from thread suspension, where the suspended thread relinquishes its /// priority. When the sleep timer times out the thread becomes runnable /// again, and will run as soon as it becomes the highest-priority mapped /// runnable thread. /// /// Sleeping threads may also be later suspended. In this case the Sleep timer /// continues to run, and if it times out before the thread is resumed the /// thread will be immediately runnable when it is resumed. /// /// See the SSX specification for a full discussion of how SSX handles /// scheduling events at absolute times "in the past". Briefly stated, if the /// \a time is in the past, the thread will Sleep for the briefest possible /// period supported by the hardware. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was not called from a thread /// context. // Note: Casting __ssx_current_thread removes the 'volatile' attribute. int ssx_sleep_absolute(SsxTimebase time) { SsxMachineContext ctx; SsxThread* current; if (SSX_ERROR_CHECK_API) { SSX_ERROR_UNLESS_THREAD_CONTEXT(); } ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); current = (SsxThread*)__ssx_current_thread; current->timer.timeout = time; __ssx_timer_schedule(&(current->timer)); current->flags |= SSX_THREAD_FLAG_TIMER_PEND; SSX_KERN_TRACE("THREAD_SLEEP(%d)", current->priority); __ssx_thread_queue_delete(&__ssx_run_queue, current->priority); __ssx_schedule(); current->flags &= ~(SSX_THREAD_FLAG_TIMER_PEND | SSX_THREAD_FLAG_TIMED_OUT); ssx_critical_section_exit(&ctx); return SSX_OK; } /// Sleep a thread for an interval relative to the current time. /// /// \param interval A time interval relative to the current timebase. /// /// Threads can use this API to sleep for a time relative to the current /// timebase. The absolute timeout is \c ssx_timebase_get() + \a interval. /// /// Sleeping threads are not scheduled, although they maintain their /// priorities. This differs from thread suspension, where the suspended /// thread relinquishes its priority. When the sleep timer times out the /// thread becomes runnable again, and will run as soon as it becomes the /// highest-priority mapped runnable thread. /// /// Sleeping threads may also be later suspended. In this case the Sleep timer /// continues to run, and if it times out before the thread is resumed the /// thread will be immediately runnable when it is resumed. /// /// See the SSX specification for a full discussion of how SSX handles /// scheduling events at absolute times "in the past". Briefly stated, if the /// \a interval is 0 or is so small that the absolute time becomes a "past" /// time before the Sleep is actually scheduled, the thread will Sleep for the /// briefest possible period supported by the hardware. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD The API was not called from a thread /// context. int ssx_sleep(SsxInterval interval) { return ssx_sleep_absolute(ssx_timebase_get() + interval); } /// Get information about a thread. /// /// \param thread A pointer to the SsxThread to query /// /// \param state The value returned through this pointer is the current state /// of the thread; See \ref ssx_thread_states. The caller can set this /// parameter to the null pointer (0) if this information is not required. /// /// \param priority The value returned through this pointer is the current /// priority of the thread. The caller can set this parameter to the null /// pointer (0) if this information is not required. /// /// \param runnable The value returned through this pointer is 1 if the thread /// is in state SSX_THREAD_STATE_MAPPED and is currently in the run queue /// (i.e., neither blocked on a semaphore nor sleeping), otherwise 0. The /// caller can set this parameter to the null pointer (0) if this information /// is not required. /// /// The information returned by this API can only be guaranteed consistent if /// the API is called from an SSX_NONCRITICAL critical section. Since the /// implementation of this API does not enforce a critical section, it is not /// an error to call this API from a critical interrupt context. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_THREAD_AT_INFO The \a thread is a null (0) pointer. int ssx_thread_info_get(SsxThread* thread, SsxThreadState* state, SsxThreadPriority* priority, int* runnable) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(thread == 0, SSX_INVALID_THREAD_AT_INFO); } if (state) { *state = thread->state; } if (priority) { *priority = thread->priority; } if (runnable) { *runnable = ((thread->state == SSX_THREAD_STATE_MAPPED) && __ssx_thread_queue_member(&__ssx_run_queue, thread->priority)); } return SSX_OK; } /// Change the priority of a thread. /// /// \param thread The thread whose priority will be changed /// /// \param new_priority The new priority of the thread /// /// \param old_priority The value returned through this pointer is the /// old priority of the thread prior to the change. The caller can set /// this parameter to the null pointer (0) if this information is not /// required. /// /// Thread priorities can be changed by the \c ssx_thread_priority_change() /// API. This call will fail if the thread pointer is invalid or if the thread /// is mapped and the new priority is currently in use. The call will succeed /// even if the \a thread is suspended, completed or deleted. The /// application-level scheduling algorithm is completely responsible for the /// correctness of the application in the event of suspended, completed or /// deleted threads. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion, including the redundant case of /// attempting to change the priority of the thread to its current priority. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD the API was called from a critical /// interrupt context. /// /// \retval -SSX_INVALID_THREAD_AT_CHANGE The \a thread is null (0) or /// otherwise invalid. /// /// \retval -SSX_INVALID_ARGUMENT_THREAD_CHANGE The \a new_priority is invalid. /// /// \retval -SSX_PRIORITY_IN_USE_AT_CHANGE The \a thread is mapped and the \a /// new_priority is currently in use by another thread. int ssx_thread_priority_change(SsxThread* thread, SsxThreadPriority new_priority, SsxThreadPriority* old_priority) { SsxMachineContext ctx; SsxThreadPriority priority; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT(); SSX_ERROR_IF(thread == 0, SSX_INVALID_THREAD_AT_CHANGE); SSX_ERROR_IF(new_priority > SSX_THREADS, SSX_INVALID_ARGUMENT_THREAD_CHANGE); } ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); priority = thread->priority; if (priority != new_priority) { if (!__ssx_thread_is_mapped(thread)) { thread->priority = new_priority; } else { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL(__ssx_priority_map[new_priority] != 0, SSX_PRIORITY_IN_USE_AT_CHANGE, &ctx); } __ssx_thread_unmap(thread); thread->priority = new_priority; __ssx_thread_map(thread); __ssx_schedule(); } } if (old_priority) { *old_priority = priority; } ssx_critical_section_exit(&ctx); return SSX_OK; } /// Return a pointer to the thread (if any) mapped at a given priority. /// /// \param priority The thread priority of interest /// /// \param thread The value returned through this pointer is a pointer to the /// thread currently mapped at the given priority level. If no thread is /// mapped, or if the \a priority is the priority of the idle thread, the /// pointer returned will be null (0). /// /// The information returned by this API can only be guaranteed consistent if /// the API is called from an SSX_NONCRITICAL critical section. Since the /// implementation of this API does not require a critical section, it is not /// an error to call this API from a critical interrupt context. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion. /// /// \retval -SSX_INVALID_ARGUMENT_THREAD_PRIORITY The \a priority is invalid /// or the \a thread parameter is null (0). int ssx_thread_at_priority(SsxThreadPriority priority, SsxThread** thread) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((priority > SSX_THREADS) || (thread == 0), SSX_INVALID_ARGUMENT_THREAD_PRIORITY); } *thread = __ssx_thread_at_priority(priority); return SSX_OK; } /// Swap thread priorities /// /// \param thread_a A pointer to an initialized SsxThread /// /// \param thread_b A pointer to an initialized SsxThread /// /// This API swaps the priorities of \a thread_a and \a thread_b. The API is /// provided to support general and efficient application-directed scheduling /// algorithms. The requirements on the \a thread_a and \a thread_b arguments /// are that they are valid pointers to initialized SsxThread structures, that /// the current thread priorities of both threads are legal, and that if a /// thread is currently mapped, that the new thread priority is not otherwise /// in use. /// /// The API does not require either thread to be mapped, or even to be active. /// It is legal for one or both of the swap partners to be suspended, deleted /// or completed threads. The application is completely responsible for the /// correctness of scheduling algorithms that might operate on inactive or /// suspended threads. /// /// The API does not change the mapped status of a thread. A thread will be /// mapped after the call of ssx_thread_priority_swap() if and only if it was /// mapped prior to the call. If the new priority of a mapped thread is /// currently in use (by a thread other than the swap partner), then the /// SSX_PRIORITY_IN_USE_AT_SWAP error is signalled and the swap does not take /// place. This could only happen if the swap partner is not currently mapped. /// /// It is legal for a thread to swap its own priority with another thread. The /// degenerate case that \a thread_a and \a thread_b are equal is also legal - /// but has no effect. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion, including the redundant cases that do not /// actually change priorities, or the cases that assign new priorities to /// suspended, completed or deleted threads. /// /// \retval -SSX_ILLEGAL_CONTEXT_THREAD the API was called from a critical /// interrupt context. /// /// \retval -SSX_INVALID_THREAD_AT_SWAP1 One or both of \a thread_a and /// \a thread_b is null (0) or otherwise invalid, /// /// \retval -SSX_INVALID_THREAD_AT_SWAP2 the priorities of One or both of /// \a thread_a and \a thread_b are invalid. /// /// \retval -SSX_INVALID_ARGUMENT One or both of the priorities /// of \a thread_a and \a thread_b is invalid. /// /// \retval -SSX_PRIORITY_IN_USE_AT_SWAP Returned if a thread is mapped and the /// new thread priority is currently in use by another thread (other than the /// swap partner). int ssx_thread_priority_swap(SsxThread* thread_a, SsxThread* thread_b) { SsxMachineContext ctx; SsxThreadPriority priority_a, priority_b; int mapped_a, mapped_b; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT(); SSX_ERROR_IF((thread_a == 0) || (thread_b == 0), SSX_INVALID_THREAD_AT_SWAP1); } ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); if (thread_a != thread_b) { mapped_a = __ssx_thread_is_mapped(thread_a); mapped_b = __ssx_thread_is_mapped(thread_b); priority_a = thread_a->priority; priority_b = thread_b->priority; if (SSX_ERROR_CHECK_API) { int priority_in_use; SSX_ERROR_IF_CRITICAL((priority_a > SSX_THREADS) || (priority_b > SSX_THREADS), SSX_INVALID_THREAD_AT_SWAP2, &ctx); priority_in_use = (mapped_a && !mapped_b && (__ssx_thread_at_priority(priority_b) != 0)) || (!mapped_a && mapped_b && (__ssx_thread_at_priority(priority_a) != 0)); SSX_ERROR_IF_CRITICAL(priority_in_use, SSX_PRIORITY_IN_USE_AT_SWAP, &ctx); } if (mapped_a) { __ssx_thread_unmap(thread_a); } if (mapped_b) { __ssx_thread_unmap(thread_b); } thread_a->priority = priority_b; thread_b->priority = priority_a; if (mapped_a) { __ssx_thread_map(thread_a); } if (mapped_b) { __ssx_thread_map(thread_b); } __ssx_schedule(); } ssx_critical_section_exit(&ctx); return SSX_OK; } #undef __SSX_THREAD_CORE_C__ <|start_filename|>src/lib/ppc405lib/fgetc.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/fgetc.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file fgetc.c /// \brief Implementation of fgetc() and ungetc() /// /// The implementations of these APIs are split out to save code space for /// applications that do not require them. #include "ssx_io.h" /// Read a character from a stream /// /// fgetc() reads the next character from \a stream and returns it as an /// unsigned char cast to an int, or EOF on end of file or error. int fgetc(FILE* stream) { unsigned char c; size_t read; int rc; if (stream->flags & SSX_FILE_HAS_CHARACTER) { stream->flags &= ~SSX_FILE_HAS_CHARACTER; rc = stream->character; } else { rc = sread(stream, &c, 1, &read); if (rc || (read != 1)) { rc = EOF; } else { rc = c; if (c == '\n') { stream->lines++; } } } return rc; } /// Push a character back onto a stream /// /// ungetc() pushes \a c back to \a stream, cast to unsigned char, where it is /// available for subsequent fgetc() operations. Only one pushback is /// implemented. A call of ungetc() on a stream that already has a character /// pushed back will drop the new push-back and return EOF. Otherwise /// ungetc() returns \a c. int ungetc(int c, FILE* stream) { int rc; if (stream->flags & SSX_FILE_HAS_CHARACTER) { rc = EOF; } else { stream->flags |= SSX_FILE_HAS_CHARACTER; stream->character = c; rc = c; } return rc; } /// Return the number of newline characters read from a stream /// /// This API is an SSX entension to the \<stdio\> APIs. It returns the number /// of newline characters read from the stream using fgetc(). Newline /// characters read via direct calls to sread() in the stream are not counted. /// /// An application that sees an error while reading from a stream can print /// flines() or flines() + 1 (depending on the application) to help users /// track down errors in their input. size_t flines(FILE* stream) { return stream->lines; } <|start_filename|>src/ppe/pk/kernel/pk_thread_util.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/kernel/pk_thread_util.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file pk_thread_util.c /// \brief PK thread utility APIs /// /// The entry points in this file are considered extra routines that will /// only be included in a PK application that enables threads and uses at /// least one of these interfaces. #include "pk.h" #include "pk_thread.h" /// Get information about a thread. /// /// \param thread A pointer to the PkThread to query /// /// \param state The value returned through this pointer is the current state /// of the thread; See \ref pk_thread_states. The caller can set this /// parameter to the null pointer (0) if this information is not required. /// /// \param priority The value returned through this pointer is the current /// priority of the thread. The caller can set this parameter to the null /// pointer (0) if this information is not required. /// /// \param runnable The value returned through this pointer is 1 if the thread /// is in state PK_THREAD_STATE_MAPPED and is currently in the run queue /// (i.e., neither blocked on a semaphore nor sleeping), otherwise 0. The /// caller can set this parameter to the null pointer (0) if this information /// is not required. /// /// The information returned by this API can only be guaranteed consistent if /// the API is called from a critical section. /// /// Return values other than PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_THREAD_AT_INFO The \a thread is a null (0) pointer. int pk_thread_info_get(PkThread *thread, PkThreadState *state, PkThreadPriority *priority, int *runnable) { if (PK_ERROR_CHECK_API) { PK_ERROR_IF(thread == 0, PK_INVALID_THREAD_AT_INFO); } if (state) { *state = thread->state; } if (priority) { *priority = thread->priority; } if (runnable) { *runnable = ((thread->state == PK_THREAD_STATE_MAPPED) && __pk_thread_queue_member(&__pk_run_queue, thread->priority)); } return PK_OK; } /// Change the priority of a thread. /// /// \param thread The thread whose priority will be changed /// /// \param new_priority The new priority of the thread /// /// \param old_priority The value returned through this pointer is the /// old priority of the thread prior to the change. The caller can set /// this parameter to the null pointer (0) if this information is not /// required. /// /// Thread priorities can be changed by the \c pk_thread_priority_change() /// API. This call will fail if the thread pointer is invalid or if the thread /// is mapped and the new priority is currently in use. The call will succeed /// even if the \a thread is suspended, completed or deleted. The /// application-level scheduling algorithm is completely responsible for the /// correctness of the application in the event of suspended, completed or /// deleted threads. /// /// Return values other than PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion, including the redundant case of /// attempting to change the priority of the thread to its current priority. /// /// \retval -PK_INVALID_THREAD_AT_CHANGE The \a thread is null (0) or /// otherwise invalid. /// /// \retval -PK_INVALID_ARGUMENT_THREAD_CHANGE The \a new_priority is invalid. /// /// \retval -PK_PRIORITY_IN_USE_AT_CHANGE The \a thread is mapped and the \a /// new_priority is currently in use by another thread. int pk_thread_priority_change(PkThread *thread, PkThreadPriority new_priority, PkThreadPriority *old_priority) { PkMachineContext ctx; PkThreadPriority priority; if (PK_ERROR_CHECK_API) { PK_ERROR_IF(thread == 0, PK_INVALID_THREAD_AT_CHANGE); PK_ERROR_IF(new_priority > PK_THREADS, PK_INVALID_ARGUMENT_THREAD_CHANGE); } pk_critical_section_enter(&ctx); priority = thread->priority; if (priority != new_priority) { if (!__pk_thread_is_mapped(thread)) { thread->priority = new_priority; } else { if (PK_ERROR_CHECK_API) { PK_ERROR_IF_CRITICAL(__pk_priority_map[new_priority] != 0, PK_PRIORITY_IN_USE_AT_CHANGE, &ctx); } __pk_thread_unmap(thread); thread->priority = new_priority; __pk_thread_map(thread); __pk_schedule(); } } if (old_priority) { *old_priority = priority; } pk_critical_section_exit(&ctx); return PK_OK; } /// Return a pointer to the thread (if any) mapped at a given priority. /// /// \param priority The thread priority of interest /// /// \param thread The value returned through this pointer is a pointer to the /// thread currently mapped at the given priority level. If no thread is /// mapped, or if the \a priority is the priority of the idle thread, the /// pointer returned will be null (0). /// /// The information returned by this API can only be guaranteed consistent if /// the API is called from a critical section. /// /// Return values other than PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion. /// /// \retval -PK_INVALID_ARGUMENT_THREAD_PRIORITY The \a priority is invalid /// or the \a thread parameter is null (0). int pk_thread_at_priority(PkThreadPriority priority, PkThread **thread) { if (PK_ERROR_CHECK_API) { PK_ERROR_IF((priority > PK_THREADS) || (thread == 0), PK_INVALID_ARGUMENT_THREAD_PRIORITY); } *thread = __pk_thread_at_priority(priority); return PK_OK; } /// Swap thread priorities /// /// \param thread_a A pointer to an initialized PkThread /// /// \param thread_b A pointer to an initialized PkThread /// /// This API swaps the priorities of \a thread_a and \a thread_b. The API is /// provided to support general and efficient application-directed scheduling /// algorithms. The requirements on the \a thread_a and \a thread_b arguments /// are that they are valid pointers to initialized PkThread structures, that /// the current thread priorities of both threads are legal, and that if a /// thread is currently mapped, that the new thread priority is not otherwise /// in use. /// /// The API does not require either thread to be mapped, or even to be active. /// It is legal for one or both of the swap partners to be suspended, deleted /// or completed threads. The application is completely responsible for the /// correctness of scheduling algorithms that might operate on inactive or /// suspended threads. /// /// The API does not change the mapped status of a thread. A thread will be /// mapped after the call of pk_thread_priority_swap() if and only if it was /// mapped prior to the call. If the new priority of a mapped thread is /// currently in use (by a thread other than the swap partner), then the /// PK_PRIORITY_IN_USE_AT_SWAP error is signalled and the swap does not take /// place. This could only happen if the swap partner is not currently mapped. /// /// It is legal for a thread to swap its own priority with another thread. The /// degenerate case that \a thread_a and \a thread_b are equal is also legal - /// but has no effect. /// /// Return values other than PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion, including the redundant cases that do not /// actually change priorities, or the cases that assign new priorities to /// suspended, completed or deleted threads. /// /// \retval -PK_INVALID_THREAD_AT_SWAP1 One or both of \a thread_a and /// \a thread_b is null (0) or otherwise invalid, /// /// \retval -PK_INVALID_THREAD_AT_SWAP2 the priorities of One or both of /// \a thread_a and \a thread_b are invalid. /// /// \retval -PK_INVALID_ARGUMENT One or both of the priorities /// of \a thread_a and \a thread_b is invalid. /// /// \retval -PK_PRIORITY_IN_USE_AT_SWAP Returned if a thread is mapped and the /// new thread priority is currently in use by another thread (other than the /// swap partner). int pk_thread_priority_swap(PkThread* thread_a, PkThread* thread_b) { PkMachineContext ctx; PkThreadPriority priority_a, priority_b; int mapped_a, mapped_b; if (PK_ERROR_CHECK_API) { PK_ERROR_IF((thread_a == 0) || (thread_b == 0), PK_INVALID_THREAD_AT_SWAP1); } pk_critical_section_enter(&ctx); if (thread_a != thread_b) { mapped_a = __pk_thread_is_mapped(thread_a); mapped_b = __pk_thread_is_mapped(thread_b); priority_a = thread_a->priority; priority_b = thread_b->priority; if (PK_ERROR_CHECK_API) { int priority_in_use; PK_ERROR_IF_CRITICAL((priority_a > PK_THREADS) || (priority_b > PK_THREADS), PK_INVALID_THREAD_AT_SWAP2, &ctx); priority_in_use = (mapped_a && !mapped_b && (__pk_thread_at_priority(priority_b) != 0)) || (!mapped_a && mapped_b && (__pk_thread_at_priority(priority_a) != 0)); PK_ERROR_IF_CRITICAL(priority_in_use, PK_PRIORITY_IN_USE_AT_SWAP, &ctx); } if (mapped_a) { __pk_thread_unmap(thread_a); } if (mapped_b) { __pk_thread_unmap(thread_b); } thread_a->priority = priority_b; thread_b->priority = priority_a; if (mapped_a) { __pk_thread_map(thread_a); } if (mapped_b) { __pk_thread_map(thread_b); } __pk_schedule(); } pk_critical_section_exit(&ctx); return PK_OK; } <|start_filename|>src/occ_405/thread/threadSch.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/thread/threadSch.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <occ_common.h> #include <threadSch.h> #include "ssx.h" #include "thread_service_codes.h" #include "occ_service_codes.h" #include <trac.h> #include <state.h> #include "cmdh_snapshot.h" // Numbers of threads to schedule #define THREADS_TO_SCHEDULE (sizeof(G_scheduledThreads)/sizeof(SsxThread*)) #define THREAD_TIME_SLICE (SsxInterval) SSX_MILLISECONDS(10) // 10ms // Thread Timer to reprioritize the threads SsxTimer G_threadSchTimer; // Snapshot timer object extern SsxTimer G_snapshotTimer; // Index of highest priority thread in G_scheduledThreads uint16_t G_threadSchedulerIndex = 0; // Array that holds the threads that need scheduling SsxThread* G_scheduledThreads[] = { &Main_thread, &Cmd_Hndl_thread, &Dcom_thread, }; // Error log counter for the callback so that only 1 error log is created uint8_t G_threadSwapErrlCounter = 0; //Thread Stacks uint8_t main_thread_stack[THREAD_STACK_SIZE]; uint8_t Cmd_hndl_thread_stack[THREAD_STACK_SIZE]; uint8_t dcomThreadStack[THREAD_STACK_SIZE]; // Our idle thread. See main_thread_routine SsxThread Main_thread; // Command handler thread SsxThread Cmd_Hndl_thread; // Dcom thread SsxThread Dcom_thread; // Function Specification // // Name: createAndResumeThreadHelper // // Description: create and resume thread helper // // End Function Specification int createAndResumeThreadHelper(SsxThread *io_thread, SsxThreadRoutine i_thread_routine, void *io_arg, SsxAddress i_stack, size_t i_stack_size, THREAD_PRIORITY i_priority) { // Locals int l_rc = SSX_OK; // Thread creation l_rc = ssx_thread_create(io_thread, i_thread_routine, io_arg, i_stack, i_stack_size, (SsxThreadPriority)i_priority); //check for errors creating a thread if(l_rc != SSX_OK) { MAIN_TRAC_ERR("Failure creating thread. rc: 0x%x", -l_rc); } else { //resume thread once created l_rc = ssx_thread_resume(io_thread); } return l_rc; } // Function Specification // // Name: initThreadScheduler // // Description: Init the threads in the scheduler and start the // timer. // // End Function Specification void initThreadScheduler(void) { // Locals int l_cmdThreadRc = SSX_OK; int l_timerRc = SSX_OK; int l_dcomThreadRc = SSX_OK; int l_snapshotTimerRc = SSX_OK; // Creating threads that need to be scheduled // Thread priority range should match scheduled // threads in G_scheduledThreads ie highest priority thread should be // index 0 of G_scheduledThreads l_cmdThreadRc = createAndResumeThreadHelper(&Cmd_Hndl_thread, Cmd_Hndl_thread_routine, (void *)0, (SsxAddress)Cmd_hndl_thread_stack, THREAD_STACK_SIZE, THREAD_PRIORITY_3); l_dcomThreadRc = createAndResumeThreadHelper(&Dcom_thread, Dcom_thread_routine, (void *)0, (SsxAddress)dcomThreadStack, THREAD_STACK_SIZE, THREAD_PRIORITY_4); // Create the thread scheduler timer l_timerRc = ssx_timer_create(&G_threadSchTimer, threadSwapcallback, 0); // Check for errors creating the timer if(l_timerRc == SSX_OK) { MAIN_TRAC_INFO("timer created and scheduled"); //schedule the timer so that it runs every THREAD_TIME_SLICE l_timerRc = ssx_timer_schedule(&G_threadSchTimer, 1, THREAD_TIME_SLICE); } else { MAIN_TRAC_INFO("Error creating timer: RC: %d", l_timerRc); } // Create snapshot timer l_snapshotTimerRc = ssx_timer_create(&G_snapshotTimer, cmdh_snapshot_callback, 0); // Check for errors creating the timer if(l_snapshotTimerRc == SSX_OK) { // Schedule the timer so that it runs every 30 seconds. l_snapshotTimerRc = ssx_timer_schedule(&G_snapshotTimer, 0, SSX_SECONDS(30)); if (l_snapshotTimerRc != SSX_OK) { MAIN_TRAC_ERR("cmdh_snapshot_sync: reseting the snapshot timer failed."); } } else { MAIN_TRAC_INFO("Error creating timer: RC: %d", l_snapshotTimerRc); } // If there are any errors creating the threads or starting the // timer create an error log to pass back. if( l_cmdThreadRc || l_dcomThreadRc || l_timerRc || l_snapshotTimerRc ) { MAIN_TRAC_ERR("Error creating thread: snapshopTimerTc: %d, timerRc: %d, cmdThreadRc: %d, dcomThreadRc: %d", l_snapshotTimerRc, l_timerRc, l_cmdThreadRc,l_dcomThreadRc); // Create error log and log it const trace_descriptor_array_t* l_trace = NULL; /* @ * @errortype * @moduleid THRD_MID_INIT_THREAD_SCHDLR * @reasoncode SSX_GENERIC_FAILURE * @userdata1 Schedule timer return code * @userdata2 Snapshot timer return code * @userdata4 OCC_NO_EXTENDED_RC * @devdesc SSX thread related failure */ errlHndl_t l_errl = createErrl(THRD_MID_INIT_THREAD_SCHDLR, // ModId SSX_GENERIC_FAILURE, // Reasoncode OCC_NO_EXTENDED_RC, // Extended reasoncode ERRL_SEV_UNRECOVERABLE, // Severity l_trace, // Trace Buf DEFAULT_TRACE_SIZE, // Trace Size l_timerRc, // Userdata1 l_snapshotTimerRc); // Userdata2 CHECKPOINT(COMM_INIT_FAILURE); REQUEST_RESET(l_errl); } } // Function Specification // // Name: threadSwapcallback // // Description: a periodic timer callback to swap prorities of scheduled threads // // End Function Specification void threadSwapcallback(void * arg) { // Locals int l_rc = SSX_OK; // Current location of index in scheduled thread array int l_threadAIndex = G_threadSchedulerIndex; // If global index == last item swap priorities with 1st int l_threadBIndex = (G_threadSchedulerIndex == (THREADS_TO_SCHEDULE-1)) ? 0 : ++G_threadSchedulerIndex; // Swap priorities with global index +1 l_rc = ssx_thread_priority_swap(G_scheduledThreads[l_threadAIndex],G_scheduledThreads[l_threadBIndex]); if(l_rc != SSX_OK) { MAIN_TRAC_ERR("SSX thread priority swap failure! rc=0x%x," "Thread A index=%d, Thread B index=%d", l_rc, l_threadAIndex, l_threadBIndex ); // Create and commit error log if(G_threadSwapErrlCounter == 0) { const trace_descriptor_array_t* l_trace = NULL; /* * @errortype * @moduleid THRD_MID_THREAD_SWAP_CALLBACK * @reasoncode SSX_GENERIC_FAILURE * @userdata1 Return code of thread priority swap * @userdata2 Current location of index in scheduled thread array * @userdata4 OCC_NO_EXTENDED_RC * @devdesc SSX thread related failure */ errlHndl_t l_err = createErrl( THRD_MID_THREAD_SWAP_CALLBACK, // ModId SSX_GENERIC_FAILURE, // Reasoncode OCC_NO_EXTENDED_RC, // Extended reasoncode ERRL_SEV_PREDICTIVE, // Severity l_trace, // Trace Buf DEFAULT_TRACE_SIZE, // Trace Size l_rc, // Userdata1 l_threadAIndex // Userdata2 ); // Commit log // NOTE: Log should be deleted by reader mechanism commitErrl( &l_err ); // Increment errl counter G_threadSwapErrlCounter++; }// End thread swap counter if } else { // Reset counter since it started working again G_threadSwapErrlCounter = 0; // Set the global to the new location of the highest priority thread G_threadSchedulerIndex = l_threadBIndex; } } <|start_filename|>src/occ_405/sensor/sensor_service_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor_service_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _SENSOR_SERVICE_CODES_H_ #define _SENSOR_SERVICE_CODES_H_ #include <comp_ids.h> enum occSensorModuleId { // Sensors SENSOR_QUERY_LIST = SNSR_COMP_ID | 0x00, SENSOR_INITIALIZE = SNSR_COMP_ID | 0x01, // Main memory sensors MM_SENSORS_INIT_MOD = SNSR_COMP_ID | 0x10, MM_SENSORS_UPDATE_MOD = SNSR_COMP_ID | 0x11, MM_SENSORS_BCE_COPY_MOD = SNSR_COMP_ID | 0x12, MM_SENSORS_IS_BCE_REQ_IDLE_MOD = SNSR_COMP_ID | 0x13, MM_SENSORS_WRITE_DATA_HDR_MOD = SNSR_COMP_ID | 0x14, MM_SENSORS_VALIDATE_DATA_HDR_MOD = SNSR_COMP_ID | 0x15, MM_SENSORS_WRITE_NAMES_MOD = SNSR_COMP_ID | 0x16, MM_SENSORS_WRITE_READINGS_MOD = SNSR_COMP_ID | 0x17, MM_SENSORS_VALIDATE_READINGS_MOD = SNSR_COMP_ID | 0x18, // Inband commands INBAND_CMD_IS_BCE_REQ_IDLE_MOD = SNSR_COMP_ID | 0x20, INBAND_CMD_BCE_COPY_MOD = SNSR_COMP_ID | 0x21, INBAND_CMD_HANDLER_MOD = SNSR_COMP_ID | 0x22, INBAND_CMD_CHECK_MOD = SNSR_COMP_ID | 0x23, // Get time of day task GET_TOD_IS_REQ_IDLE_MOD = SNSR_COMP_ID | 0x30, GET_TOD_HNDL_REQ_RSLT_MOD = SNSR_COMP_ID | 0x31, GET_TOD_SCHED_REQ_MOD = SNSR_COMP_ID | 0x32, }; #endif /* #ifndef _SENSOR_SERVICE_CODES_H_ */ <|start_filename|>src/occ_405/cmdh/cmdh_mnfg_intf.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_mnfg_intf.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "cmdh_mnfg_intf.h" #include "cmdh_service_codes.h" #include "cmdh_fsp_cmds.h" #include "dcom.h" #include "amec_oversub.h" #include "amec_sys.h" #include "sensor_query_list.h" #include "amec_smh.h" #include "amec_master_smh.h" #include <pgpe_shared.h> // SSX Block Copy Request for copying mfg Pstate table from HOMER to SRAM BceRequest G_mfg_pba_request; DMA_BUFFER(mfg_read_pstate_table_t G_mfg_read_pstate_table) = {{0}}; extern task_t G_task_table[TASK_END]; // Function Specification // // Name: cmdh_mnfg_run_stop_slew // // Description: This function handles the manufacturing command to start // or stop frequency autoslewing. // // End Function Specification uint8_t cmdh_mnfg_run_stop_slew(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; uint16_t l_fmin = 0; uint16_t l_fmax = 0; uint16_t l_step_size = 0; uint16_t l_step_delay = 0; uint32_t l_temp = 0; mnfg_run_stop_slew_cmd_t *l_cmd_ptr = (mnfg_run_stop_slew_cmd_t*) i_cmd_ptr; mnfg_run_stop_slew_rsp_t *l_rsp_ptr = (mnfg_run_stop_slew_rsp_t*) o_rsp_ptr; do { // This command is only supported on Master OCC if (G_occ_role == OCC_SLAVE) { TRAC_ERR("cmdh_mnfg_run_stop_slew: Mnfg command not supported on Slave OCCs!"); break; } // Do some basic input verification if ((l_cmd_ptr->action > MNFG_INTF_SLEW_STOP) || (l_cmd_ptr->step_mode > MNFG_INTF_FULL_SLEW)) { // Invalid values were passed by the user! TRAC_ERR("cmdh_mnfg_run_stop_slew: Invalid values were detected! action[0x%02x] step_mode[0x%02x]", l_cmd_ptr->action, l_cmd_ptr->step_mode); l_rc = ERRL_RC_INVALID_DATA; break; } // Are we stopping the auto-slew function? if (l_cmd_ptr->action == MNFG_INTF_SLEW_STOP) { // Collect the slew count l_rsp_ptr->slew_count = AMEC_MST_CUR_SLEW_COUNT(); // Collect the frequency range used for the auto-slew l_rsp_ptr->fstart = AMEC_MST_CUR_MNFG_FMIN(); l_rsp_ptr->fstop = AMEC_MST_CUR_MNFG_FMAX(); TRAC_INFO("cmdh_mnfg_run_stop_slew: Auto-slewing has been stopped. Count[%u] fstart[%u] fstop[%u]", AMEC_MST_CUR_SLEW_COUNT(), AMEC_MST_CUR_MNFG_FMIN(), AMEC_MST_CUR_MNFG_FMAX()); // Send a signal to RTL to stop auto-slewing AMEC_MST_STOP_AUTO_SLEW(); // We are done break; } // If we made it here, that means we are starting up a slew run // First, determine the Fmax and Fmin for the slew run if (l_cmd_ptr->bottom_mode == OCC_MODE_PWRSAVE) { // If bottom mode is Static Power Save, use the min frequency // available l_fmin = G_sysConfigData.sys_mode_freq.table[OCC_MODE_MIN_FREQUENCY]; } else { l_fmin = G_sysConfigData.sys_mode_freq.table[l_cmd_ptr->bottom_mode]; } l_fmax = G_sysConfigData.sys_mode_freq.table[l_cmd_ptr->high_mode]; // Add the percentages to compute the min/max frequencies l_fmin = l_fmin + (l_fmin * l_cmd_ptr->bottom_percent)/100; l_fmax = l_fmax + (l_fmax * l_cmd_ptr->high_percent)/100; TRAC_INFO("cmdh_mnfg_run_stop_slew: We are about to start auto-slewing function"); TRAC_INFO("cmdh_mnfg_run_stop_slew: bottom_mode[0x%.2X] freq[%u] high_mode[0x%.2X] freq[%u]", l_cmd_ptr->bottom_mode, l_fmin, l_cmd_ptr->high_mode, l_fmax); // Determine the frequency step size and the step delay if (l_cmd_ptr->step_mode == MNFG_INTF_FULL_SLEW) { l_step_size = l_fmax - l_fmin; // Disable step delays if full slew mode has been selected l_step_delay = 0; TRAC_INFO("cmdh_mnfg_run_stop_slew: Enabling full-slew mode with step_size[%u] step_delay[%u]", l_step_size, l_step_delay); } else { l_step_size = (uint16_t)G_mhz_per_pstate; // Translate the step delay to internal OCC ticks l_temp = (l_cmd_ptr->step_delay * 1000) / AMEC_US_PER_TICK; l_step_delay = (uint16_t) l_temp; TRAC_INFO("cmdh_mnfg_run_stop_slew: Enabling single-step mode with step_size[%u] step_delay[%u]", l_step_size, l_step_delay); } // Now, load the values for RTL consumption AMEC_MST_SET_MNFG_FMIN(l_fmin); AMEC_MST_SET_MNFG_FMAX(l_fmax); AMEC_MST_SET_MNFG_FSTEP(l_step_size); AMEC_MST_SET_MNFG_DELAY(l_step_delay); // Reset the slew-counter before we start auto-slewing AMEC_MST_CUR_SLEW_COUNT() = 0; // Wait a little bit for RTL to process above parameters ssx_sleep(SSX_MILLISECONDS(5)); // Send a signal to RTL to start auto-slewing AMEC_MST_START_AUTO_SLEW(); // We are auto-slewing now, populate the response packet l_rsp_ptr->slew_count = 0; l_rsp_ptr->fstart = l_fmin; l_rsp_ptr->fstop = l_fmax; }while(0); // Populate the response data packet G_rsp_status = l_rc; l_rsp_ptr->data_length[0] = 0; l_rsp_ptr->data_length[1] = MNFG_INTF_RUN_STOP_SLEW_RSP_SIZE; return l_rc; } // Function Specification // // Name: cmdh_mnfg_mem_slew // // Description: This function handles the manufacturing command to start // or stop memory autoslewing. // // End Function Specification uint8_t cmdh_mnfg_mem_slew(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; mnfg_mem_slew_cmd_t *l_cmd_ptr = (mnfg_mem_slew_cmd_t*) i_cmd_ptr; mnfg_mem_slew_rsp_t *l_rsp_ptr = (mnfg_mem_slew_rsp_t*) o_rsp_ptr; do { // Do some basic input verification if (l_cmd_ptr->action > MNFG_INTF_SLEW_STOP) { // Invalid values were passed by the user! TRAC_ERR("cmdh_mnfg_mem_slew: Invalid value was detected! action[0x%02x]", l_cmd_ptr->action); l_rc = ERRL_RC_INVALID_DATA; break; } // Are we stopping the auto-slew function? if (l_cmd_ptr->action == MNFG_INTF_SLEW_STOP) { // Send a signal to RTL to stop auto-slewing g_amec->mnfg_parms.mem_autoslew = FALSE; // Collect the slew count if(g_amec->mnfg_parms.mem_slew_counter > 0x0000FFFF) { l_rsp_ptr->slew_count = 0xFFFF; } else { l_rsp_ptr->slew_count = g_amec->mnfg_parms.mem_slew_counter; } // Zero out the slew count; g_amec->mnfg_parms.mem_slew_counter = 0; TRAC_INFO("cmdh_mnfg_mem_slew: Auto-slewing has been stopped. Count[%u]", l_rsp_ptr->slew_count); // We are done break; } // If we made it here, that means we are starting up a slew run TRAC_INFO("cmdh_mnfg_mem_slew: We are about to start auto-slewing function"); // If the OCC is active (we can only run auto-slew in active state) the memory control // task must be running and there is no support (or need) to force activation of // memory monitoring and control if(!IS_OCC_STATE_ACTIVE()) { TRAC_ERR("cmdh_mnfg_mem_slew: OCC must be active to start mem slewing"); l_rc = ERRL_RC_INVALID_STATE; break; } if(!rtl_task_is_runnable(TASK_ID_MEMORY_CONTROL)) { TRAC_ERR("cmdh_mnfg_mem_slew: memory control task not running"); l_rc = ERRL_RC_INTERNAL_FAIL; break; } // Zero out the slew count g_amec->mnfg_parms.mem_slew_counter = 0; // Send a signal to RTL to start memory auto-slewing g_amec->mnfg_parms.mem_autoslew = TRUE; // We are auto-slewing now, populate the response packet l_rsp_ptr->slew_count = 0; TRAC_INFO("cmdh_mnfg_mem_slew: memory slewing started."); }while(0); // Populate the response data packet G_rsp_status = l_rc; l_rsp_ptr->data_length[0] = 0; l_rsp_ptr->data_length[1] = MNFG_INTF_MEM_SLEW_RSP_SIZE; return l_rc; } // Function Specification // // Name: cmdh_mnfg_emulate_oversub // // Description: This function handles the manufacturing command to emulate // oversubscription. // // End Function Specification uint8_t cmdh_mnfg_emulate_oversub(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = 0; mnfg_emul_oversub_cmd_t *l_cmd_ptr = (mnfg_emul_oversub_cmd_t*) i_cmd_ptr; mnfg_emul_oversub_rsp_t *l_rsp_ptr = (mnfg_emul_oversub_rsp_t*) o_rsp_ptr; do { // This command is only supported on Master OCC if (G_occ_role == OCC_SLAVE) { TRAC_ERR("cmdh_mnfg_emulate_oversub: Mnfg command not supported on Slave OCCs!"); break; } switch (l_cmd_ptr->action) { case 0x00: TRAC_INFO("cmdh_mnfg_emulate_oversub: Disable oversubscription emulation"); AMEC_INTF_GET_OVERSUBSCRIPTION_EMULATION() = 0; l_rsp_ptr->state = l_cmd_ptr->action; break; case 0x01: TRAC_INFO("cmdh_mnfg_emulate_oversub: Enable oversubscription emulation"); AMEC_INTF_GET_OVERSUBSCRIPTION_EMULATION() = 1; l_rsp_ptr->state = l_cmd_ptr->action; break; case 0xFF: TRAC_INFO("cmdh_mnfg_emulate_oversub: Query oversubscription emulation"); l_rsp_ptr->state = AMEC_INTF_GET_OVERSUBSCRIPTION_EMULATION(); break; default: TRAC_INFO("cmdh_mnfg_emulate_oversub: Invalid oversubscription emulation action"); l_rsp_ptr->state = AMEC_INTF_GET_OVERSUBSCRIPTION_EMULATION(); break; } }while(0); // Populate the response data packet G_rsp_status = ERRL_RC_SUCCESS; l_rsp_ptr->data_length[0] = 0; l_rsp_ptr->data_length[1] = 1; return l_rc; } // Function Specification // // Name: cmdh_mnfg_list_sensors // // Description: Returns a list of selected sensors // // End Function Specification uint8_t cmdh_mnfg_list_sensors(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; uint16_t l_type = 0; uint16_t l_location = 0; uint16_t l_start_gsid; uint16_t i = 0; uint16_t l_resp_data_length = 0; uint16_t l_datalength; uint16_t l_num_of_sensors = MFG_MAX_NUM_SENSORS + 1; cmdh_mfg_list_sensors_query_t *l_cmd_ptr = (cmdh_mfg_list_sensors_query_t*) i_cmd_ptr; cmdh_mfg_list_sensors_resp_t *l_resp_ptr = (cmdh_mfg_list_sensors_resp_t*) o_rsp_ptr; sensorQueryList_t l_sensor_list[MFG_MAX_NUM_SENSORS + 1]; errlHndl_t l_err = NULL; do { // Do sanity check on the function inputs if ((NULL == i_cmd_ptr) || (NULL == o_rsp_ptr)) { TRAC_ERR("cmdh_mnfg_list_sensors: invalid pointers. cmd[0x%08x] rsp[0x%08x]", (uint32_t) i_cmd_ptr, (uint32_t) o_rsp_ptr); l_rc = ERRL_RC_INTERNAL_FAIL; break; } // Check packet data length l_datalength = CMDH_DATALEN_FIELD_UINT16(i_cmd_ptr); if(l_datalength < (sizeof(cmdh_mfg_list_sensors_query_t) - sizeof(cmdh_fsp_cmd_header_t))) { TRAC_ERR("cmdh_mnfg_list_sensors: incorrect data length. exp[%d] act[%d]", (sizeof(cmdh_mfg_list_sensors_query_t) - sizeof(cmdh_fsp_cmd_header_t)), l_datalength); l_rc = ERRL_RC_INVALID_CMD_LEN; break; } // Check version if(l_cmd_ptr->version != MFG_LIST_SENSOR_VERSION) { TRAC_ERR("cmdh_mnfg_list_sensors: incorrect version. exp[%d] act[%d]", MFG_LIST_SENSOR_VERSION, l_cmd_ptr->version); l_rc = ERRL_RC_INVALID_DATA; break; } // Capture user inputs l_type = l_cmd_ptr->type; l_location = l_cmd_ptr->location; l_start_gsid = l_cmd_ptr->start_gsid; TRAC_INFO("cmdh_mnfg_list_sensors: Type[0x%04x] Location[0x%04x]", l_type, l_location); // Initialize the sensor query arguments const querySensorListArg_t l_qsl_arg = { l_start_gsid, // i_startGsid - passed by the caller l_cmd_ptr->present, // i_present - passed by the caller l_type, // i_type - passed by the caller l_location, // i_loc - passed by the caller &l_num_of_sensors, // io_numOfSensors l_sensor_list, // o_sensors NULL // o_sensorInfoPtr - not needed }; // Get the list of sensors l_err = querySensorList(&l_qsl_arg); if (NULL != l_err) { // Query failure TRAC_ERR("cmdh_mnfg_list_sensors: Failed to query sensor list. Error status is: 0x%x", l_err->iv_reasonCode); // Commit error log commitErrl(&l_err); l_rc = ERRL_RC_INTERNAL_FAIL; break; } else { TRAC_INFO("cmdh_mnfg_list_sensors: Numbers of sensors found[%u]", l_num_of_sensors); if (l_num_of_sensors > MFG_MAX_NUM_SENSORS) { // Got too many sensors back, need to truncate the list TRAC_INFO("cmdh_mnfg_list_sensors: Got too many sensors back[%u]. Truncating number of sensors to %u", l_num_of_sensors, MFG_MAX_NUM_SENSORS); l_num_of_sensors = MFG_MAX_NUM_SENSORS; l_resp_ptr->truncated = 1; } else { l_resp_ptr->truncated = 0; } // Clear out the sensor fields memset((void*) &(l_resp_ptr->sensor[0]), 0, (sizeof(cmdh_dbug_sensor_list_t)*l_num_of_sensors) ); // Populate the response data packet l_resp_ptr->num_sensors = l_num_of_sensors; for (i=0; i<l_num_of_sensors; i++) { l_resp_ptr->sensor[i].gsid = l_sensor_list[i].gsid; l_resp_ptr->sensor[i].sample = l_sensor_list[i].sample; strcpy(l_resp_ptr->sensor[i].name, l_sensor_list[i].name); } } }while(0); // Populate the response data header l_resp_data_length = 2 + l_num_of_sensors * sizeof(cmdh_mfg_sensor_rec_t); G_rsp_status = l_rc; o_rsp_ptr->data_length[0] = ((uint8_t *)&l_resp_data_length)[0]; o_rsp_ptr->data_length[1] = ((uint8_t *)&l_resp_data_length)[1]; return l_rc; } // Function Specification // // Name: cmdh_mnfg_get_sensor // // Description: Returns a list of selected sensors // // End Function Specification uint8_t cmdh_mnfg_get_sensor(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; uint16_t l_gsid; uint16_t l_resp_data_length = 0; uint16_t l_datalength; uint16_t l_num_of_sensors = 1; cmdh_mfg_get_sensor_query_t *l_cmd_ptr = (cmdh_mfg_get_sensor_query_t*) i_cmd_ptr; cmdh_mfg_get_sensor_resp_t *l_resp_ptr = (cmdh_mfg_get_sensor_resp_t*) o_rsp_ptr; sensor_info_t l_sensor_info; errlHndl_t l_err = NULL; sensor_t* l_sensor_ptr; do { // Do sanity check on the function inputs if ((NULL == i_cmd_ptr) || (NULL == o_rsp_ptr)) { TRAC_ERR("cmdh_mnfg_get_sensor: invalid pointers. cmd[0x%08x] rsp[0x%08x]", (uint32_t) i_cmd_ptr, (uint32_t) o_rsp_ptr); l_rc = ERRL_RC_INTERNAL_FAIL; break; } // Check packet data length l_datalength = CMDH_DATALEN_FIELD_UINT16(i_cmd_ptr); if(l_datalength < (sizeof(cmdh_mfg_get_sensor_query_t) - sizeof(cmdh_fsp_cmd_header_t))) { TRAC_ERR("cmdh_mnfg_get_sensor: incorrect data length. exp[%d] act[%d]", (sizeof(cmdh_mfg_get_sensor_query_t) - sizeof(cmdh_fsp_cmd_header_t)), l_datalength); l_rc = ERRL_RC_INVALID_CMD_LEN; break; } // Check version if(l_cmd_ptr->version != MFG_LIST_SENSOR_VERSION) { TRAC_ERR("cmdh_mnfg_get_sensor: incorrect version. exp[%d] act[%d]", MFG_GET_SENSOR_VERSION, l_cmd_ptr->version); l_rc = ERRL_RC_INVALID_DATA; break; } // Capture user inputs l_gsid = l_cmd_ptr->gsid; TRAC_INFO("cmdh_mnfg_get_sensor: gsid[0x%04x]", l_gsid); // Initialize the sensor query arguments querySensorListArg_t l_qsl_arg = { l_gsid, // i_startGsid - passed by the caller 0, // i_present - passed by the caller AMEC_SENSOR_TYPE_ALL, // i_type AMEC_SENSOR_LOC_ALL, // i_loc &l_num_of_sensors, // io_numOfSensors NULL, // o_sensors - not needed &l_sensor_info // o_sensorInfoPtr }; // Get the sensor list l_err = querySensorList(&l_qsl_arg); if (NULL != l_err) { // Query failure TRAC_ERR("cmdh_mnfg_get_sensor: Failed to get sensor list. Error status is: 0x%x", l_err->iv_reasonCode); // Commit error log commitErrl(&l_err); l_rc = ERRL_RC_INTERNAL_FAIL; break; } else { l_resp_ptr->gsid = l_gsid; // Some of the response comes from the sensor l_sensor_ptr = getSensorByGsid(l_gsid); if (l_sensor_ptr == NULL) { TRAC_INFO("cmdh_mnfg_get_sensor: Didn't find sensor with gsid[0x%.4X]. Min/Max values won't be accurate.", l_gsid); l_resp_ptr->sample = 0; l_resp_ptr->min = 0xFFFF; l_resp_ptr->max = 0; l_resp_ptr->accumulator = 0; l_resp_ptr->status = 0; } else { l_resp_ptr->sample = l_sensor_ptr->sample; l_resp_ptr->min = l_sensor_ptr->sample_min; l_resp_ptr->max = l_sensor_ptr->sample_max; // Truncate accumulator to 4 bytes (should not be used) l_resp_ptr->accumulator = (uint32_t)l_sensor_ptr->accumulator; l_resp_ptr->status = *(uint8_t*)(&l_sensor_ptr->status); } // The rest of the response comes from the sensor info memcpy(l_resp_ptr->name, l_sensor_info.name, sizeof(l_resp_ptr->name)); memcpy(l_resp_ptr->units, l_sensor_info.sensor.units, sizeof(l_resp_ptr->units)); l_resp_ptr->freq = l_sensor_info.sensor.freq; l_resp_ptr->scalefactor = l_sensor_info.sensor.scalefactor; l_resp_ptr->location = l_sensor_info.sensor.location; l_resp_ptr->type = l_sensor_info.sensor.type; } }while(0); // Populate the response data header l_resp_data_length = sizeof(cmdh_mfg_get_sensor_resp_t) - sizeof(cmdh_fsp_rsp_header_t); G_rsp_status = l_rc; o_rsp_ptr->data_length[0] = ((uint8_t *)&l_resp_data_length)[0]; o_rsp_ptr->data_length[1] = ((uint8_t *)&l_resp_data_length)[1]; return l_rc; } // Function Specification // // Name: cmdh_mnfg_request_quad_pstate // // Description: This function handles the manufacturing command to request // a Pstate per Quad. // // End Function Specification uint8_t cmdh_mnfg_request_quad_pstate(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; uint16_t l_datalength = 0; uint16_t l_resp_data_length = 0; uint8_t l_pmin = 0xFF; uint8_t l_pmax = 0xFF; uint8_t l_pstate_request = 0xFF; uint8_t l_quad = 0; mnfg_quad_pstate_cmd_t *l_cmd_ptr = (mnfg_quad_pstate_cmd_t*) i_cmd_ptr; mnfg_quad_pstate_rsp_t *l_rsp_ptr = (mnfg_quad_pstate_rsp_t*) o_rsp_ptr; do { if(!IS_OCC_STATE_ACTIVE()) { TRAC_ERR("cmdh_mnfg_request_quad_pstate: OCC must be active to request pstate"); l_rc = ERRL_RC_INVALID_STATE; break; } if(G_sysConfigData.system_type.kvm) { TRAC_ERR("cmdh_mnfg_request_quad_pstate: Must be PowerVM to request pstate"); l_rc = ERRL_RC_INVALID_CMD; break; } // Check command packet data length l_datalength = CMDH_DATALEN_FIELD_UINT16(i_cmd_ptr); if(l_datalength != (sizeof(mnfg_quad_pstate_cmd_t) - sizeof(cmdh_fsp_cmd_header_t))) { TRAC_ERR("cmdh_mnfg_request_quad_pstate: incorrect data length. exp[%d] act[%d]", (sizeof(mnfg_quad_pstate_cmd_t) - sizeof(cmdh_fsp_cmd_header_t)), l_datalength); l_rc = ERRL_RC_INVALID_CMD_LEN; break; } // Check version if(l_cmd_ptr->version != MFG_QUAD_PSTATE_VERSION) { TRAC_ERR("cmdh_mnfg_request_quad_pstate: incorrect version. exp[%d] act[%d]", MFG_QUAD_PSTATE_VERSION, l_cmd_ptr->version); l_rc = ERRL_RC_INVALID_DATA; break; } // only allow a Pstate within the current range based on mode l_pmin = proc_freq2pstate(g_amec->sys.fmin); l_pmax = proc_freq2pstate(g_amec->sys.fmax); // Process each quad Pstate request, clip any request to min/max // 0xFF has special meaning that OCC is in control for(l_quad = 0; l_quad < MAXIMUM_QUADS; l_quad++) { l_pstate_request = l_cmd_ptr->quad_pstate_in[l_quad]; if(l_pstate_request != 0xFF) { // pmin is lowest frequency corresponding to highest pState value if(l_pstate_request > l_pmin) l_pstate_request = l_pmin; // pmax is highest frequency corresponding to lowest pState value else if(l_pstate_request < l_pmax) l_pstate_request = l_pmax; } // save the quad pState request for amec and return in rsp data g_amec->mnfg_parms.quad_pstate[l_quad] = l_pstate_request; l_rsp_ptr->quad_pstate_out[l_quad] = l_pstate_request; TRAC_INFO("cmdh_mnfg_request_quad_pstate: Quad %d Pstate in = 0x%02x Pstate out = 0x%02x", l_quad, l_cmd_ptr->quad_pstate_in[l_quad], l_rsp_ptr->quad_pstate_out[l_quad]); } }while(0); // Populate the response data header G_rsp_status = l_rc; l_resp_data_length = sizeof(mnfg_quad_pstate_rsp_t) - sizeof(cmdh_fsp_rsp_header_t); l_rsp_ptr->data_length[0] = ((uint8_t *)&l_resp_data_length)[0]; l_rsp_ptr->data_length[1] = ((uint8_t *)&l_resp_data_length)[1]; return l_rc; } // Function Specification // // Name: cmdh_mnfg_read_pstate_table // // Description: This function handles the manufacturing command to read // the generated Pstate table from main memory 3K blocks at a time // // End Function Specification uint8_t cmdh_mnfg_read_pstate_table(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; uint16_t l_datalength = 0; uint16_t l_resp_data_length = 0; uint32_t block_offset = 0; uint32_t main_mem_address = 0; int l_ssxrc = SSX_OK; mnfg_read_pstate_table_cmd_t *l_cmd_ptr = (mnfg_read_pstate_table_cmd_t*) i_cmd_ptr; do { // Check command packet data length l_datalength = CMDH_DATALEN_FIELD_UINT16(i_cmd_ptr); if(l_datalength != (sizeof(mnfg_read_pstate_table_cmd_t) - sizeof(cmdh_fsp_cmd_header_t))) { TRAC_ERR("cmdh_mnfg_read_pstate_table: incorrect data length. exp[%d] act[%d]", (sizeof(mnfg_read_pstate_table_cmd_t) - sizeof(cmdh_fsp_cmd_header_t)), l_datalength); l_rc = ERRL_RC_INVALID_CMD_LEN; break; } // Process request if(l_cmd_ptr->request == MFG_PSTATE_READ_REQUEST_QUERY) { memcpy(&o_rsp_ptr->data[0], &G_pgpe_header.generated_pstate_table_homer_offset, 4); memcpy(&o_rsp_ptr->data[4], &G_pgpe_header.generated_pstate_table_length, 4); l_resp_data_length = MFG_PSTATE_READ_QUERY_RSP_SIZE; TRAC_INFO("cmdh_mnfg_read_pstate_table: Query table memory offset[0x%08x] table length[%d]", G_pgpe_header.generated_pstate_table_homer_offset, G_pgpe_header.generated_pstate_table_length); break; } // Calculate the starting main memory address for block to read block_offset = MFG_PSTATE_READ_MAX_RSP_SIZE * l_cmd_ptr->request; if(block_offset > G_pgpe_header.generated_pstate_table_length) { TRAC_ERR("cmdh_mnfg_read_pstate_table: Block request %d out of range. Pstate Table size %d", l_cmd_ptr->request, G_pgpe_header.generated_pstate_table_length); l_rc = ERRL_RC_INVALID_DATA; break; } main_mem_address = G_pgpe_header.generated_pstate_table_homer_offset + block_offset; // Copy Pstate table from main memory to SRAM // Set up a copy request l_ssxrc = bce_request_create(&G_mfg_pba_request, // block copy object &G_pba_bcde_queue, // mainstore to sram copy engine main_mem_address, // mainstore address (uint32_t)&G_mfg_read_pstate_table, // sram starting address sizeof(mfg_read_pstate_table_t), // size of copy SSX_SECONDS(1), // timeout NULL, // no call back NULL, // no call back arguments ASYNC_REQUEST_BLOCKING); // blocking request if(l_ssxrc != SSX_OK) { TRAC_ERR("cmdh_mnfg_read_pstate_table: BCDE request create failure rc=[%08X]", -l_ssxrc); l_rc = ERRL_RC_INTERNAL_FAIL; break; } // Do actual copying l_ssxrc = bce_request_schedule(&G_mfg_pba_request); if(l_ssxrc != SSX_OK) { TRAC_ERR("cmdh_mnfg_read_pstate_table: BCE request schedule failure rc=[%08X]", -l_ssxrc); l_rc = ERRL_RC_INTERNAL_FAIL; break; } // Determine the rsp data length l_resp_data_length = MFG_PSTATE_READ_MAX_RSP_SIZE; if((block_offset + MFG_PSTATE_READ_MAX_RSP_SIZE) > G_pgpe_header.generated_pstate_table_length) { l_resp_data_length = G_pgpe_header.generated_pstate_table_length - block_offset; } // Copy to response buffer memcpy(o_rsp_ptr->data, &G_mfg_read_pstate_table, l_resp_data_length); TRAC_INFO("cmdh_mnfg_read_pstate_table: Read from main memory[0x%08x] block offset[%d] length[%d]", main_mem_address, block_offset, l_resp_data_length); }while(0); // Populate the response data header G_rsp_status = l_rc; o_rsp_ptr->data_length[0] = ((uint8_t *)&l_resp_data_length)[0]; o_rsp_ptr->data_length[1] = ((uint8_t *)&l_resp_data_length)[1]; return l_rc; } // Function Specification // // Name: cmdh_mnfg_test_parse // // Description: This function parses the manufacturing commands sent via TMGT. // // End Function Specification errlHndl_t cmdh_mnfg_test_parse (const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = 0; uint8_t l_sub_cmd = 0; errlHndl_t l_errl = NULL; // Sub-command is always first byte of data l_sub_cmd = i_cmd_ptr->data[0]; TRAC_INFO("cmdh_mnfg_test_parse: Mnfg sub-command [0x%02x]", l_sub_cmd); switch (l_sub_cmd) { case MNFG_RUN_STOP_SLEW: l_rc = cmdh_mnfg_run_stop_slew(i_cmd_ptr, o_rsp_ptr); break; case MNFG_OVERSUB_EMULATION: l_rc = cmdh_mnfg_emulate_oversub(i_cmd_ptr, o_rsp_ptr); break; case MNFG_LIST_SENSORS: l_rc = cmdh_mnfg_list_sensors(i_cmd_ptr, o_rsp_ptr); break; case MNFG_GET_SENSOR: l_rc = cmdh_mnfg_get_sensor(i_cmd_ptr, o_rsp_ptr); break; case MNFG_MEMORY_SLEW: l_rc = cmdh_mnfg_mem_slew(i_cmd_ptr, o_rsp_ptr); break; case MNFG_QUAD_PSTATE: l_rc = cmdh_mnfg_request_quad_pstate(i_cmd_ptr, o_rsp_ptr); break; case MNFG_READ_PSTATE_TABLE: l_rc = cmdh_mnfg_read_pstate_table(i_cmd_ptr, o_rsp_ptr); break; default: // Should never get here... l_rc = ERRL_RC_INVALID_DATA; break; } // All errors in MNFG logged internally if (l_rc) { TRAC_ERR("Mfg command 0x%02x failed with rc = %d", l_sub_cmd, l_rc); // Build Error Response packet cmdh_build_errl_rsp(i_cmd_ptr, o_rsp_ptr, l_rc, &l_errl); } return l_errl; } <|start_filename|>src/ssx/occhw/occhw_ocb.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_ocb.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_OCB_H__ #define __OCCHW_OCB_H__ /// \file occhw_ocb.h /// \brief OCB unit header. Local and mechanically generated macros and APIs. #include "ssx.h" #include "ppc32.h" #include "occhw_common.h" #include "ocb_register_addresses.h" #include "ocb_firmware_registers.h" #include "ppc405_irq.h" #define OCB_TIMER0 0 #define OCB_TIMER1 1 #define OCB_TIMERS 2 #define OCB_TIMER_ONE_SHOT 0 #define OCB_TIMER_AUTO_RELOAD 1 #define OCB_LW_LOG_SIZE_MIN 3 #define OCB_LW_LOG_SIZE_MAX 15 #define OCB_INVALID_ARGUMENT_TIMER 0x00622001 #define OCB_INVALID_ARGUMENT_LW_INIT 0x00622002 #define OCB_INVALID_ARGUMENT_LW_DISABLE 0x00622003 #define OCB_INVALID_ARGUMENT_UNTRUST 0x00622004 #ifndef __ASSEMBLER__ int ocb_timer_reset(int timer, int auto_reload, int timeout_ns); #ifdef OCC int ocb_timer_setup(int timer, int auto_reload, int timeout_ns, SsxIrqHandler handler, void* arg, int priority) INIT_SECTION; #else int ocb_timer_setup(int timer, int auto_reload, int timeout_ns, SsxIrqHandler handler, void* arg, int priority); #endif /// Clear OCB timer status based on the IRQ /// /// This API can be called from OCB timer interrupt handlers, using the IRQ /// provided to the handler. No error checks are provided. static inline void ocb_timer_status_clear(SsxIrqId irq) { ocb_otrn_t otrn_reg; otrn_reg.value = 0; otrn_reg.fields.timeout = 1; out32(OCB_OTRN(irq - OCCHW_IRQ_OCC_TIMER0), otrn_reg.value); } int ocb_linear_window_initialize(int channel, uint32_t base, int log_size); int ocb_linear_window_disable(int channel); int ocb_allow_untrusted_initialize(int channel, int allow_untrusted); #endif /* __ASSEMBLER__ */ #endif /* __OCCHW_OCB_H__ */ <|start_filename|>src/include/registers/gpe_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/gpe_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __GPE_FIRMWARE_REGISTERS_H__ #define __GPE_FIRMWARE_REGISTERS_H__ /// \file gpe_firmware_registers.h /// \brief C register structs for the GPE unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union gpe_gpentsel { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fit_sel : 4; uint64_t watchdog_sel : 4; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t watchdog_sel : 4; uint64_t fit_sel : 4; #endif // _BIG_ENDIAN } fields; } gpe_gpentsel_t; typedef union gpe_gpenivpr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivpr : 23; uint64_t reserved1 : 41; #else uint64_t reserved1 : 41; uint64_t ivpr : 23; #endif // _BIG_ENDIAN } fields; } gpe_gpenivpr_t; typedef union gpe_gpendbg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t en_dbg : 1; uint64_t halt_on_xstop : 1; uint64_t halt_on_trig : 1; uint64_t en_risctrace : 1; uint64_t en_trace_full_iva : 1; uint64_t dis_trace_extra : 1; uint64_t dis_trace_stall : 1; uint64_t en_wide_trace : 1; uint64_t sync_timer_sel : 4; uint64_t fir_trigger : 1; uint64_t spare : 3; uint64_t halt_input : 1; uint64_t reserved1 : 47; #else uint64_t reserved1 : 47; uint64_t halt_input : 1; uint64_t spare : 3; uint64_t fir_trigger : 1; uint64_t sync_timer_sel : 4; uint64_t en_wide_trace : 1; uint64_t dis_trace_stall : 1; uint64_t dis_trace_extra : 1; uint64_t en_trace_full_iva : 1; uint64_t en_risctrace : 1; uint64_t halt_on_trig : 1; uint64_t halt_on_xstop : 1; uint64_t en_dbg : 1; #endif // _BIG_ENDIAN } fields; } gpe_gpendbg_t; typedef union gpe_gpenstr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 12; uint64_t pbase : 10; uint64_t reserved2 : 7; uint64_t size : 3; uint64_t reserved3 : 32; #else uint64_t reserved3 : 32; uint64_t size : 3; uint64_t reserved2 : 7; uint64_t pbase : 10; uint64_t reserved1 : 12; #endif // _BIG_ENDIAN } fields; } gpe_gpenstr_t; typedef union gpe_gpenmacr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t mem_low_priority : 2; uint64_t mem_high_priority : 2; uint64_t local_low_priority : 2; uint64_t local_high_priority : 2; uint64_t sram_low_priority : 2; uint64_t sram_high_priority : 2; uint64_t reserved1 : 52; #else uint64_t reserved1 : 52; uint64_t sram_high_priority : 2; uint64_t sram_low_priority : 2; uint64_t local_high_priority : 2; uint64_t local_low_priority : 2; uint64_t mem_high_priority : 2; uint64_t mem_low_priority : 2; #endif // _BIG_ENDIAN } fields; } gpe_gpenmacr_t; typedef union gpe_gpenxixcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xcr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t xcr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxixcr_t; typedef union gpe_gpenxiramra { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xcr : 32; uint64_t sprg0 : 32; #else uint64_t sprg0 : 32; uint64_t xcr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiramra_t; typedef union gpe_gpenxiramga { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ir : 32; uint64_t sprg0 : 32; #else uint64_t sprg0 : 32; uint64_t ir : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiramga_t; typedef union gpe_gpenxiramdbg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xsr : 32; uint64_t sprg0 : 32; #else uint64_t sprg0 : 32; uint64_t xsr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiramdbg_t; typedef union gpe_gpenxiramedr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ir : 32; uint64_t edr : 32; #else uint64_t edr : 32; uint64_t ir : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiramedr_t; typedef union gpe_gpenxidbgpro { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xsr : 32; uint64_t iar : 32; #else uint64_t iar : 32; uint64_t xsr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxidbgpro_t; typedef union gpe_gpenxisib { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sib_info : 64; #else uint64_t sib_info : 64; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisib_t; typedef union gpe_gpenximem { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t memory_info : 64; #else uint64_t memory_info : 64; #endif // _BIG_ENDIAN } fields; } gpe_gpenximem_t; typedef union gpe_gpenxisgb { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t storegatherbuffer_info : 64; #else uint64_t storegatherbuffer_info : 64; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisgb_t; typedef union gpe_gpenxiicac { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t icache_info : 64; #else uint64_t icache_info : 64; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiicac_t; typedef union gpe_gpenxidcac { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dcache_info : 64; #else uint64_t dcache_info : 64; #endif // _BIG_ENDIAN } fields; } gpe_gpenxidcac_t; typedef union gpe_gpenoxixcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xcr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t xcr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenoxixcr_t; typedef union gpe_gpenxixsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t xsr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t xsr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxixsr_t; typedef union gpe_gpenxisprg0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sprg0 : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t sprg0 : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisprg0_t; typedef union gpe_gpenxiedr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t edr : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t edr : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiedr_t; typedef union gpe_gpenxiir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ir : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ir : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiir_t; typedef union gpe_gpenxiiar { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t iar : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t iar : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiiar_t; typedef union gpe_gpenxisibu { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sib_info_upper : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t sib_info_upper : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisibu_t; typedef union gpe_gpenxisibl { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sib_info_lower : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t sib_info_lower : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisibl_t; typedef union gpe_gpenximemu { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t memory_info_upper : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t memory_info_upper : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenximemu_t; typedef union gpe_gpenximeml { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t memory_info_lower : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t memory_info_lower : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenximeml_t; typedef union gpe_gpenxisgbu { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sgb_info_upper : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t sgb_info_upper : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisgbu_t; typedef union gpe_gpenxisgbl { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t sgb_info_lower : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t sgb_info_lower : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxisgbl_t; typedef union gpe_gpenxiicacu { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t icache_info_upper : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t icache_info_upper : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiicacu_t; typedef union gpe_gpenxiicacl { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t icache_info_lower : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t icache_info_lower : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxiicacl_t; typedef union gpe_gpenxidcacu { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dcache_info_upper : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t dcache_info_upper : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxidcacu_t; typedef union gpe_gpenxidcacl { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dcache_info_lower : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t dcache_info_lower : 32; #endif // _BIG_ENDIAN } fields; } gpe_gpenxidcacl_t; #endif // __ASSEMBLER__ #endif // __GPE_FIRMWARE_REGISTERS_H__ <|start_filename|>src/occ_405/cmdh/cmdh_mnfg_intf.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_mnfg_intf.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef CMDH_MNFG_INTF_H #define CMDH_MNFG_INTF_H #include "cmdh_fsp.h" #include "sensor.h" #include "p9_pstates_common.h" typedef enum { MNFG_RUN_STOP_SLEW = 0x02, MNFG_LIST_SENSORS = 0x05, MNFG_GET_SENSOR = 0x06, MNFG_OVERSUB_EMULATION = 0x07, MNFG_MEMORY_SLEW = 0x09, MNFG_QUAD_PSTATE = 0x0A, MNFG_READ_PSTATE_TABLE = 0x0B, } MNFG_CMD; #define MNFG_INTF_SLEW_START 0x00 #define MNFG_INTF_SLEW_STOP 0x01 #define MNFG_INTF_SINGLE_STEP 0x00 #define MNFG_INTF_FULL_SLEW 0x01 #define MNFG_INTF_RUN_STOP_SLEW_RSP_SIZE 6 // Used by OCC to get mnfg run/stop slew command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint8_t action; uint8_t bottom_mode; int8_t bottom_percent; uint8_t high_mode; int8_t high_percent; uint8_t step_mode; uint8_t step_delay; }mnfg_run_stop_slew_cmd_t; // Used by OCC firmware to respond to mnfg run/stop slew command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint16_t slew_count; uint16_t fstart; uint16_t fstop; uint16_t checksum; }mnfg_run_stop_slew_rsp_t; // Used by OCC to get mnfg memory slew command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint8_t action; }mnfg_mem_slew_cmd_t; #define MNFG_INTF_MEM_SLEW_RSP_SIZE 2 // Used by OCC firmware to respond to mnfg memory slew command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint16_t slew_count; uint16_t checksum; }mnfg_mem_slew_rsp_t; // Used by OCC to get mnfg emulate oversubscription command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint8_t action; uint8_t reserved; }mnfg_emul_oversub_cmd_t; // Used by OCC firmware to respond to mnfg emulate oversubscription command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint8_t state; uint16_t checksum; }mnfg_emul_oversub_rsp_t; #define MFG_LIST_SENSOR_VERSION 0 #define MFG_MAX_NUM_SENSORS 50 // 20 bytes per sensor, 4k response packet (4k stack is limiting factor here). // Used by mfg to get sensor data typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint16_t start_gsid; uint8_t present; uint16_t location; uint16_t type; }cmdh_mfg_list_sensors_query_t; typedef struct __attribute__ ((packed)) { uint16_t gsid; char name[MAX_SENSOR_NAME_SZ]; //16 bytes uint16_t sample; }cmdh_mfg_sensor_rec_t; // Used by OCC firmware to respond to the "MFG_LIST_SENSORS" mfg command. Follows the TMGT/OCC specification. typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint8_t truncated; uint8_t num_sensors; cmdh_mfg_sensor_rec_t sensor[MFG_MAX_NUM_SENSORS]; uint16_t checksum; }cmdh_mfg_list_sensors_resp_t; #define MFG_GET_SENSOR_VERSION 0 // Used by mfg to get sensor data typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint16_t gsid; }cmdh_mfg_get_sensor_query_t; // Used by OCC firmware to respond to the "MFG_GET_SENSOR" mfg command. Follows the TMGT/OCC specification. typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint16_t gsid; uint16_t sample; uint8_t status; uint32_t accumulator; uint16_t min; uint16_t max; char name[MAX_SENSOR_NAME_SZ]; char units[MAX_SENSOR_UNIT_SZ]; uint32_t freq; uint32_t scalefactor; uint16_t location; uint16_t type; uint16_t checksum; }cmdh_mfg_get_sensor_resp_t; #define MFG_QUAD_PSTATE_VERSION 0 // Used by OCC to get mnfg request quad pstate command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint8_t quad_pstate_in[MAXIMUM_QUADS]; }mnfg_quad_pstate_cmd_t; // Used by OCC firmware to respond to mnfg request quad pstate command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint8_t quad_pstate_out[MAXIMUM_QUADS]; }mnfg_quad_pstate_rsp_t; #define MFG_PSTATE_READ_REQUEST_QUERY 0xFF #define MFG_PSTATE_READ_QUERY_RSP_SIZE 8 #define MFG_PSTATE_READ_MAX_RSP_SIZE 1024 // Used by OCC to get mnfg read pstate table command typedef struct __attribute__ ((packed)) { // Need 128 byte aligned buffer for BCE request uint8_t data[MFG_PSTATE_READ_MAX_RSP_SIZE]; } mfg_read_pstate_table_t __attribute ((aligned(128))); typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t request; }mnfg_read_pstate_table_cmd_t; errlHndl_t cmdh_mnfg_test_parse (const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_mnfg_emulate_oversub(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_mnfg_list_sensors(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_mnfg_get_sensor(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_mnfg_run_stop_slew(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_mnfg_request_quad_pstate(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_mnfg_read_pstate_table(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); #endif <|start_filename|>src/ppe/pk/gpe/gpe_irq_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/gpe/gpe_irq_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file gpe_irq_init.c /// \brief OCCHW IRQ initialization code for PK /// /// The entry points in this file are initialization rotines that could be /// eliminated/deallocated by the application to free up storage if they are /// no longer needed after initialization. #include "pk.h" /// Define the polarity and trigger condition for an interrupt. /// /// It is up to the application to take care of any side effects that may /// occur from programming or reprogramming the interrupt controller. For /// example, changing edge/level sensitivity or active level may set or clear /// interrupt status in the controller. /// /// Note that PK allows this API to be called from any context, and changes /// to the interrupt controller are made from a critical section. /// /// Return values other then PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_ARGUMENT_IRQ_SETUP One or more arguments are invalid, /// including an invalid \a irq, or invalid \a polarity or \a trigger parameters. int pk_irq_setup(PkIrqId irq, int polarity, int trigger) { PkMachineContext ctx; if (PK_ERROR_CHECK_API) { PK_ERROR_IF(!OCCHW_IRQ_VALID(irq) || !OCCHW_IRQ_OWNED(irq) || !((polarity == PK_IRQ_POLARITY_ACTIVE_HIGH) || (polarity == PK_IRQ_POLARITY_ACTIVE_LOW)) || !((trigger == PK_IRQ_TRIGGER_LEVEL_SENSITIVE) || (trigger == PK_IRQ_TRIGGER_EDGE_SENSITIVE)), PK_INVALID_ARGUMENT_IRQ_SETUP); } pk_critical_section_enter(&ctx); if (polarity == PK_IRQ_POLARITY_ACTIVE_HIGH) { out32(OCCHW_OIEPR_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OIEPR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } if (trigger == PK_IRQ_TRIGGER_EDGE_SENSITIVE) { out32(OCCHW_OITR_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OITR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } pk_critical_section_exit(&ctx); return PK_OK; } /// (Re)define the IRQ handler and priority for an interrupt. /// Return values other then PK_OK (0) are errors; see \ref pk_errors /// /// Note that PK allows this API to be called from any context, and changes /// to the interrupt controller are made from a critical section. /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_ARGUMENT_IRQ_HANDLER One or more arguments are /// invalid, including an invalid \a irq, a null (0) \a handler, /// or invalid \a priority. int pk_irq_handler_set(PkIrqId irq, PkIrqHandler handler, void* arg) { PkMachineContext ctx; if (PK_ERROR_CHECK_API) { PK_ERROR_IF(!OCCHW_IRQ_VALID(irq) || (handler == 0), PK_INVALID_ARGUMENT_IRQ_HANDLER); } pk_critical_section_enter(&ctx); __ppe42_irq_handlers[irq].handler = handler; __ppe42_irq_handlers[irq].arg = arg; pk_critical_section_exit(&ctx); return PK_OK; } <|start_filename|>src/ssx/occhw/occhw_async.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_async.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_ASYNC_H__ #define __OCCHW_ASYNC_H__ /// \file occhw_async.h /// \brief Support for asynchronous request/callback mechanisms /// /// The data structures defined here provide a 'C' implementation of multiple /// single-inheritance class hierarchies. The 'subclasses' always include the /// 'superclass' as the initial element of the structure, allowing subclass /// pointers to be safely cast to the superclass, and vice-versa (assuming /// that the subclass is known). One benefit of this approach is that it /// allows code sharing between requests targeting GPE, /// PBA-BCDE, PBA-BCUE and the deferred callback queue. /// /// The 'class hierarchy' : /// /// SsxDeque /// AsyncRequest /// GpeRequest /// BceRequest /// OcbRequest /// Pbaxrequest /// /// AsyncQueue /// GpeQueue /// BceQueue /// OcbQueue /// PbaxQueue /// #include "ipc_async_cmd.h" #include "occhw_xir_dump.h" // OCCHW Execution engines for the purposes of the generic request mechanism. #define ASYNC_ENGINE_ANONYMOUS 0x00 #define ASYNC_ENGINE_GPE 0x10 #define ASYNC_ENGINE_GPE0 0x10 #define ASYNC_ENGINE_GPE1 0x11 #define ASYNC_ENGINE_GPE2 0x12 #define ASYNC_ENGINE_GPE3 0x13 #define ASYNC_ENGINE_BCE 0x20 #define ASYNC_ENGINE_BCDE 0x20 #define ASYNC_ENGINE_BCUE 0x21 // Indirect channel 3 is now back online to support push/pull queues in P9. #define ASYNC_ENGINE_OCB 0x40 #define ASYNC_ENGINE_OCB_PUSH0 0x41 #define ASYNC_ENGINE_OCB_PUSH1 0x42 #define ASYNC_ENGINE_OCB_PUSH2 0x43 #define ASYNC_ENGINE_OCB_PUSH3 0x44 #define ASYNC_ENGINE_OCB_PULL0 0x45 #define ASYNC_ENGINE_OCB_PULL1 0x46 #define ASYNC_ENGINE_OCB_PULL2 0x47 #define ASYNC_ENGINE_OCB_PULL3 0x48 #define ASYNC_ENGINE_PBAX 0x80 #define ASYNC_ENGINE_PBAX_PUSH0 0x81 #define ASYNC_ENGINE_PBAX_PUSH1 0x82 #ifndef __ASSEMBLER__ typedef uint8_t AsyncEngine; #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // FFDC Structures //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ /// FFDC from the PLB (OCI) arbiter /// /// The PLB arbiter records errors from all OCI masters, including the address /// of the transaction that caused the error. The PLB arbiter is set up to /// 'lock' the first error data until the lock is reset. This structure is /// included in all of the unit FFDC structures for peripherals that can /// master on the OCI (SLW/GPE/OCB/PBA). Note that OCI errors from the 405 /// core will cause an immediate machine check exception. typedef struct { /// PLB arbiter Error Address Register /// /// This is the address of the last PLB timeout or other error recorded in /// the PEAR. This is an error for the unit in question only if the /// \a mine data member is non-zero. ocb_oear_t oear; /// PLB arbiter Error Status Register /// /// The PESR at the time of the error. ocb_oesr_t oesr; /// Is the unit in question responsible for the error address recorded in /// the PEARL? int mine; } OciFfdc; void oci_ffdc(OciFfdc* ffdc, int master_id); #endif // __ASSEMBLER__ //////////////////////////////////////////////////////////////////////////// // AsyncRequest //////////////////////////////////////////////////////////////////////////// /// \defgroup async_request_states ASYNC Request States /// /// Request states for async requests are group into 5 logical states for /// error handling and timeout handling purposes. /// /// - Queued Group : Queued requests are still waiting to execute in the device queue, /// so these requests can be cancelled simply by removing them from the queue. /// /// - Running Group : Running requests are running on the hardware, so killing /// these jobs may require a forced stop and restart of the device. /// /// - Callback Group : By specification callbacks are always run if provided, /// even if a job dies or is timed out. This includes post-processing only /// work like unblocking blocked threads. These processes are not interrupted. /// /// - Idle Group : These jobs are no longer in process, and their states are /// final. /// /// Only idle requests can be (re)scheduled. Only jobs in the Queued or /// Running states can time out. Once the job has moved to the Callback group /// it is considered complete as far as timeout processing is concerned. /// /// @{ /// The request is waiting in the queue #define ASYNC_REQUEST_STATE_QUEUED 0x10 /// The request is running on the hardware #define ASYNC_REQUEST_STATE_RUNNING 0x20 /// The request is complete but a deferred callback has yet to run #define ASYNC_REQUEST_STATE_CALLBACK_QUEUED 0x40 /// The request callback is running #define ASYNC_REQUEST_STATE_CALLBACK_RUNNING 0x41 /// Thread unblocking and/or timeout cancellation has been deferred to a /// noncritical interrupt context. #define ASYNC_REQUEST_STATE_POSTPROCESSING 0x42 /// The request has been initialized but never run #define ASYNC_REQUEST_STATE_INITIALIZED 0x80 /// The request failed due to an error signalled by hardware #define ASYNC_REQUEST_STATE_FAILED 0x81 /// The request completed normally #define ASYNC_REQUEST_STATE_COMPLETE 0x82 /// The application cancelled the request #define ASYNC_REQUEST_STATE_CANCELLED 0x83 /// The request timed out #define ASYNC_REQUEST_STATE_TIMED_OUT 0x84 #define ASYNC_REQUEST_QUEUED_GROUP 0x10 #define ASYNC_REQUEST_RUNNING_GROUP 0x20 #define ASYNC_REQUEST_CALLBACK_GROUP 0x40 #define ASYNC_REQUEST_IDLE_GROUP 0x80 /// @} /// \defgroup async_request_options ASYNC Request Options /// /// These are the option flags for the \a options field of the AsyncRequest. /// These are generic options applicable to all requests. /// /// @{ #define ASYNC_CALLBACK_IMMEDIATE 0x0001 #define ASYNC_CALLBACK_DEFERRED 0x0002 #define ASYNC_CALLBACK_NONCRITICAL 0x0004 #define ASYNC_CALLBACK_OPTIONS 0x0007 #define ASYNC_REQUEST_PRIORITY 0x0008 #define ASYNC_CALLBACK_PRIORITY 0x0010 #define ASYNC_REQUEST_BLOCKING 0x0020 #define ASYNC_GENERIC_OPTIONS 0x003f /// @} #ifndef __ASSEMBLER__ struct AsyncRequest; struct AsyncQueue; typedef int (*AsyncRunMethod)(struct AsyncRequest* request); typedef int (*AsyncErrorMethod)(struct AsyncRequest* request); typedef int (*AsyncRequestCallback)(void*); /// A generic request for the asynchronous request drivers /// /// Note: Normally the application will not explicitly manipulate this /// structure, but will instead manipulate derived structures. /// /// A request is queued for a particular engine, with a callback to be /// executed once the request has been processed by the engine. The \a /// callback may be NULL, but at a minimum the requestor can observe the \a /// state of the request to determine the state of request processing. If a /// deferred callback is requested, then once processing is done the generic /// handler will requeue the request in a callback queue. /// /// The \a run_method is a "pure virtual" function of this class. The \a /// run_method encapsulates the procedure for starting a job on the /// engine. The \a run_method may make assumptions about and use data /// contained in the AsyncQueue class used to queue the requests. /// /// The \a error_method is also "pure virtual" function of this class. The \a /// error_method encapsulates the procedure for collecting FFDC and preparing /// the engine to run the next job. The \a error_method may make assumptions /// about and use data contained in the AsyncQueue class used to queue the /// requests. If the \a error_method returns a non-0 code then the error is /// considered fatal and the queue stops. typedef struct AsyncRequest { /// Generic queue management - the "base class" SsxDeque deque; /// The time the job was started on the hardware. /// /// For jobs requiring multiple passes on the hardware, e.g., BCE jobs /// that move more data than the PBA supports with a single pass, this /// time is the time the first hardware pass started. In this case the /// interval time computed as the difference with \a start_time includes /// interrupt handling overhead required to process the completion/restart /// of intermediate passes. /// /// This timestamp is inserted into the request by the generic routine /// async_request_run(). SsxTimebase start_time; /// The time the job finished on the hardware. /// /// This timestamp is inserted into the request by the generic routine /// async_handler(). SsxTimebase end_time; /// A semaphore for thread-mode requests to block on if desired. SsxSemaphore sem; /// A timer used for timeout management SsxTimer timer; /// The engine queue the request is/was scheduled on struct AsyncQueue* queue; /// The "virtual" run method for the class AsyncRunMethod run_method; /// The "virtual" error handler method for the class AsyncErrorMethod error_method; /// The routine Called (or deferred) with the \a arg parameter once /// the engine has completed the request. /// /// The callback may be NULL (0), in which case the \a arg parameter /// is ignored, and the only status available to the requestor is the /// request \a state. AsyncRequestCallback callback; /// The argument of the callback void* arg; /// The timeout value /// /// AsyncRequest objects with \a timeout other than SSX_WAIT_FOREVER are /// governed by a private watchdog timer that will cancel a queued job or /// kill a running job if the hardware operation does not complete before /// it times out. SsxInterval timeout; /// The return value of the callback (if any) is stored here /// /// The success or failure of the callback is recorded here; it is not /// recorded in the \a state variable. If there is no callback this field /// will always read as 0 at job completion. int callback_rc; /// Options controlling request processing uint8_t options; /// The current state of the request /// /// This field is declared volatile because applications may poll this /// field which is set asynchronously by the async interrupt handlers, and /// optimizing compilers transform polling a variable into an infinite /// loop if the variable is not set on the initial test! volatile uint8_t state; /// The state of the request when the request was aborted /// /// This field is valid when the state of the request is read as /// ASYNC_REQUEST_STATE_FAILED, ASYNC_REQUEST_STATE_CANCELLED, or /// ASYNC_REQUEST_STATE_TIMED_OUT. This field records the state of the /// job when it was forceably cancelled or killed either due to the /// application's request or due to a hardware error or timeout. uint8_t abort_state; /// The completion state of the request. /// /// This is the state that will be reported when the request completes and /// the callback has been run. Normally this is /// ASYNC_REQUEST_STATE_COMPLETE. However the specification requires that /// even jobs that terminate due to an errors, timeouts or being cancelled /// or killed must run their callbacks. In this case this variable will be /// set to ASYNC_REQUEST_STATE_FAILED, ASYNC_REQUEST_STATE_TIMED_OUT, /// ASYNC_REQUEST_STATE_CANCELLED or ASYNC_REQUEST_STATE_KILLED /// respectively. uint8_t completion_state; } AsyncRequest; int async_request_create(AsyncRequest* request, struct AsyncQueue* queue, AsyncRunMethod run_method, AsyncErrorMethod error_method, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options); void async_request_finalize(AsyncRequest* request); /// Check that an asynchronous request is idle /// /// \param request An initialized request /// /// A request is considered idle if it is not attached to any of the /// asynchronous request queues, \e or the request has terminated with an /// error. This includes requests that have never been scheduled, have /// completed or been cancelled or killed. Only idle requests can be /// rescheduled. /// /// \retval 0 The request is not idle /// /// \retval 1 The request is idle static inline int async_request_is_idle(AsyncRequest* request) { return (request->state & ASYNC_REQUEST_IDLE_GROUP) != 0; } /// Check an asynchronous request for successful completion /// /// \param request A request that had been previosuly scheduled /// /// Note that a request is not considered complete until both the engine job /// has finshed without error and any callback has run to completion. Thus /// jobs that have error-ed out, been cancelled or killed will be idle (and /// rescheduleable), but not complete. /// /// \retval 0 The request has not yet completed successfully /// /// \retval 1 The request has completed successfully. static inline int async_request_completed(AsyncRequest* request) { return (request->state == ASYNC_REQUEST_STATE_COMPLETE); } int async_request_timestamps_get(AsyncRequest* request, SsxTimebase* start_time, SsxTimebase* end_time); int async_request_latency(AsyncRequest* request, SsxTimebase* latency); void async_request_printk(AsyncRequest* request); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // AsyncQueue //////////////////////////////////////////////////////////////////////////// #define ASYNC_QUEUE_STATE_IDLE 0x00 #define ASYNC_QUEUE_STATE_RUNNING 0x01 #define ASYNC_QUEUE_STATE_ERROR 0x02 #ifndef __ASSEMBLER__ /// A generic asynchronous request queue /// /// Note: This structure is normally not manipulated directly by application /// code, but only by the device drivers. /// /// Request queues support 2 priorities - Normal and High. Normal priority /// requests are queued FIFO order, while high-priority requests are queued /// LIFO order. Requests queued with high priority always execute before any /// queued with normal priority, however there is no concept of preemption of /// a currently running request. /// /// Because high-priority requests are queued in LIFO order, multiple /// high-priority jobs will run in the reverse order from which they were /// enqueued. typedef struct AsyncQueue { /// The sentinel of the request queue SsxDeque deque; /// The currently running request, or NULL (0) AsyncRequest* current; /// The engine associated with the queue. AsyncEngine engine; /// The state of the queue uint8_t state; } AsyncQueue; int async_queue_create(AsyncQueue* queue, AsyncEngine engine); void async_handler(AsyncQueue* queue); int async_request_schedule(AsyncRequest* request); void async_error_handler(AsyncQueue* queue, uint8_t completion_state); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // Async Initialization //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ void async_edge_handler_setup(SsxIrqHandler handler, void* arg, SsxIrqId irq, int priority); void async_level_handler_setup(SsxIrqHandler handler, void* arg, SsxIrqId irq, int priority, int polarity); void async_callbacks_initialize(SsxIrqId irq); #endif // __ASSEMBLER__ //////////////////////////////////////////////////////////////////////////// // GpeRequest //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ struct GpeQueue; /// GPE FFDC typedef struct { uint32_t func_id; int32_t ipc_rc; int xir_dump_rc; occhw_xir_dump_t xir_dump; } GpeFfdc; /// A request to run a GPE command /// /// A GPE request extends the generic AsyncRequest request by the addition of /// several fields required for running a job on a GPE /// including the program parameter for the routine. /// /// As long as the request is known to be idle the application is free to /// change the \a parameter value between executions of the GPE command, /// e.g., to do ping-pong buffer management. None of the other fields should /// be directly modified by the application. typedef struct { /// The generic request AsyncRequest request; /// Error information collected by the 405 GpeFfdc ffdc; /// The targeted IPC function ID for this request ipc_func_enum_t targeted_func_id; /// A pointer to any command data that is used by the GPE or /// returned by the GPE. void* cmd_data; } GpeRequest; int gpe_run_method(AsyncRequest* request); int gpe_error_method(AsyncRequest* request); int gpe_request_create(GpeRequest* request, struct GpeQueue* queue, ipc_func_enum_t func_id, void* cmd_data, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options); /// See async_request_schedule() for documentation. static inline int gpe_request_schedule(GpeRequest* request) { return async_request_schedule((AsyncRequest*)request); } //////////////////////////////////////////////////////////////////////////// // GpeQueue //////////////////////////////////////////////////////////////////////////// /// A GPE engine queue /// /// A GPE queue consists of a generic AsyncQueue to manage jobs on the /// engine. typedef struct GpeQueue { /// The generic request queue - the "base class" AsyncQueue queue; /// The IPC target_id uint8_t ipc_target_id; /// Pointer to an IPC command message ipc_async_cmd_t* ipc_cmd; } GpeQueue; int gpe_queue_create(GpeQueue* queue, int engine); #endif /* ASSEMBLER */ //////////////////////////////////////////////////////////////////////////// // PBA FFDC Structures //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ /// Common FFDC collected for each PBA subunit in the event that a particular /// subunit is implicated in an error. This structure contains generic /// data that may be useful in diagnosing any PBA error. Instances of this /// structure are embedded in higher-level structures for the PBA bridge, BCE /// engines, and PBAX mechanism. typedef struct { /// FFDC from the PLB (OCI) arbiter OciFfdc oci_ffdc; /// The PBA MODE register pba_mode_t mode; /// The PBA FIR pba_fir_t fir; /// PBA Error Report 0 pba_errrpt0_t errrpt0; /// PBA Error Report 1 pba_errrpt1_t errrpt1; /// PBA Error Report 2 pba_errrpt2_t errrpt2; /// PBA Read Buffer Valid Status pba_rbufvaln_t rbufval[PBA_READ_BUFFERS]; /// PBA Write Buffer Valid Status pba_wbufvaln_t wbufval[PBA_WRITE_BUFFERS]; /// PBA BARs pba_barn_t bar[PBA_BARS]; /// PBA BAR masks pba_barmskn_t barmsk[PBA_BARS]; /// Error status - non-0 if this structure contains error data int error; } PbaCommonFfdc; /// FFDC collected for generic PBA bridge errors /// /// These types of errors will almost certainly be attributable to the /// PORE-SLW or PORE-GPE, since the OCC is normally not allowed to perform /// direct bridge operations after OCC initialization. This structure extends /// the common PBA FFDC with information on how the slaves were programmed. typedef struct { /// Common FFDC PbaCommonFfdc common; /// PBA Slave reset register pba_slvrst_t slvrst; /// PBA Slave control registers pba_slvctln_t slvctl[PBA_SLAVES]; } PbaBridgeFfdc; /// FFDC collected for the PBA BCUE/BCDE /// /// The BCDE/BCUE control and status registers have identical layouts. /// Similar to the way the drivers are coded, the BCDE register forms are used /// to declare the structures. typedef struct { /// Common FFDC PbaCommonFfdc common; /// BCE control register pba_bcde_ctl_t ctl; /// BCE setup register pba_bcde_set_t set; /// BCE PowerBus setup register pba_bcde_pbadr_t pbadr; /// BCE status register pba_bcde_stat_t stat; } BceFfdc; /// FFDC collected for PBAX send errors typedef struct { /// Common FFDC PbaCommonFfdc common; /// PBAX configuration register pba_xcfg_t xcfg; /// PBAX send transaction register pba_xsndtx_t xsndtx; /// PBAX send status register pba_xsndstat_t xsndstat; } PbaxSendFfdc; /// FFDC collected for PBAX receive errors typedef struct { /// Common FFDC PbaCommonFfdc common; /// PBAX configuration register pba_xcfg_t xcfg; /// PBAX receive status register pba_xrcvstat_t xrcvstat; /// PBAX push base registers pba_xshbrn_t xshbrn[PBAX_QUEUES]; /// PBAX push control/status registers pba_xshcsn_t xshcsn[PBAX_QUEUES]; } PbaxReceiveFfdc; /// A single global structure containing FFDC for all PBA functions typedef struct { /// FFDC for the generic bridge PbaBridgeFfdc bridge; /// FFDC for the BCDE BceFfdc bcde; /// FFDC for the BCUE BceFfdc bcue; /// FFDC for PBAX send PbaxSendFfdc pbax_send; /// FFDC for PBAX receive PbaxReceiveFfdc pbax_receive; } PbaUnitFfdc; #endif // __ASSEMBLER__ //////////////////////////////////////////////////////////////////////////// // BceRequest //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ struct BceQueue; /// A request to move data through the PBA BCUE or BCDE /// /// From a programming and control perspective the Block Copy Download Engine /// (BCDE) and Upload Engine (BCUE) are identical - they simply move a given /// number of 128-byte cache lines from/to system memory to/from SRAM. /// /// Although the PBA BCE hardware can only move a maximum of 4KB at a time /// through the channel, the software layer allows any amount of data to be /// moved as a single request. typedef struct { /// The generic request AsyncRequest request; /// FFDC collected in the event of an error in the request BceFfdc ffdc; /// Initial bridge address for read (BCDE) or write (BCUE) data. This /// field is not modified by the drivers. uint32_t bridge_address; /// Initial OCI address for read (BCUE) or write (BCDE) data. This /// field is not modified by the drivers. uint32_t oci_address; /// Number of bytes to move. This field is not modified by the drivers. /// /// Note that the PBA moves data in sets of 128 bytes (the PowerBus /// cache line size). This field will always be a multiple of 128. size_t bytes; /// The next bridge address for read (BCDE) or write (BCUE) data. This /// field is modified by the drivers as each maximum 4K block is copied. uint32_t next_bridge_address; /// Initial OCI address for read (BCUE) or write (BCDE) data. This /// field is modified by the drivers as each maximum 4K block is copied. uint32_t next_oci_address; /// The number of bytes remaining to be moved. size_t remaining; /// The extended address, as a 64-bit PowerBus address /// /// Bits 23:36 of the field define bits 23:36 of the final PowerBus /// address, subject to the final mask selection. This field is cleared by /// the default constructor, and must be explicitly set if an extended /// address is needed. pba_extended_address_t extended_address; } BceRequest; int bce_request_create(BceRequest* request, struct BceQueue* queue, uint32_t bridge_address, uint32_t oci_address, size_t bytes, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // BceQueue //////////////////////////////////////////////////////////////////////////// // NB: This assignment ordering is assumed by static initialization code. // These constants are used as array indices. #define BCE_ENGINE_BCDE 0 #define BCE_ENGINE_BCUE 1 #define BCE_ENGINES 2 #ifndef __ASSEMBLER__ /// A PBA Block Copy Engine queue /// /// A PBA block copy request queue consists of a generic AsyncQueue to manage /// jobs on the engine and the PBA engine id. The BCDE and BCUE can use the /// same driver because their control interfaces are identical. typedef struct BceQueue { /// The generic request queue AsyncQueue queue; /// The engine id of the BCE engine for control register address lookup int engine; } BceQueue; int bce_queue_create(BceQueue* queue, int engine); int bce_request_schedule(BceRequest* request); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // PbaxRequest //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ struct PbaxQueue; /// A request to move data through a PBAX circular queue /// /// The PBAX circular queues are modeled after the OCB circular queues. The /// queues are named and documented in the hardware specifications from the /// perspective of the PowerBus as "PUSH" queues. Here we name and document /// the queues from the perspective of OCC firmware as "READ" queues. Note /// that there are no PBAX "WRITE" queues. The PBAX write mechanism handles /// only a single datum at a time and has no interrupt. PBAX writes are /// handled by the pbax_send() and _pbax_send() APIs. /// /// The PBAX queues support data buffers of from 8 to 256 bytes with an 8-byte /// granularity. The PBAX hardware requires that the data buffers be aligned /// to a power-of-2 boundary greater than or equal to the buffer size. /// The async drivers allow specification of any multiple of 8 bytes to read /// and handle all of the queue and split-request management. /// /// Note : As long as the PbaxRequest is idle, the application is free to /// directly change the \a data and \a bytes fields to read/write different /// numbers of bytes to/from different locations the next time the request is /// scheduled. /// /// The PBAX queues support both 'lazy' and 'aggressive' interrupt protocols. /// The aggressive protocols generate interrupts whenever read data is /// available. The lazy protocols require a full read buffer to trigger an /// interrupt. A lazy read protocol with a buffer size > 1 demands that /// communcations always consist of a known number of doublewords equal to the /// buffer size. For free-form communications an aggressive read protocol must /// be used. typedef struct { /// The generic request AsyncRequest request; /// Initial pointer to the data area to hold read data. /// /// This field is not modified by the drivers. The application may modify /// this field any time the PbaxRequest is idle. uint64_t* data; /// Number of bytes to move, which must be a multiple of 8. /// /// This field is not modified by the drivers. The application may modify /// this field any time the PbaxRequest is idle. size_t bytes; /// Pointer to where to put the next read data. /// /// The application should never modify this field. void* current; /// Number of bytes remaining to be moved. /// /// The application should never modify this field. size_t remaining; } PbaxRequest; int pbax_request_create(PbaxRequest* request, struct PbaxQueue* queue, uint64_t* data, size_t bytes, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options); int pbax_request_schedule(PbaxRequest* request); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // PbaxQueue //////////////////////////////////////////////////////////////////////////// // NB: This assignment ordering is assumed by static initialization code in // occhw_async.c - these constants are used as array indices. #define PBAX_ENGINE_PUSH0 0 #define PBAX_ENGINE_PUSH1 1 #define PBAX_ENGINES 2 #ifndef __ASSEMBLER__ extern const SsxAddress pba_xshcsn[]; extern const SsxAddress pba_xshbrn[]; extern const SsxAddress pba_xshincn[]; /// A PBAX Circular buffer queue /// /// A PBAX circular buffer queue consists of a generic AsyncQueue to manage /// jobs on the engine, a pointer to the data area and the PBAX engine id. typedef struct PbaxQueue { /// The generic request queue AsyncQueue queue; /// The base of the circular queue data area /// /// This data area must satisfy stringent alignment constraints; See the /// documentation for PbaxRequest. uint64_t* cq_base; /// The number of 8-byte entries in the queue. /// /// This is included here to simplify APIs; The length is also encoded in /// the PBAXSHCSn register for the queue. size_t cq_entries; /// The interrupt protocol implemented by the queue. /// /// This will either be PBAX_INTERRUPT_PROTOCOL_LAZY or /// PBAX_INTERRUPT_PROTOCOL_AGGRESSIVE. int protocol; /// The engine id for lookup of OCI control register addresses. int engine; /// The IRQ associated with normal completion on the engine /// /// \todo Due to header reference ordering we can't define this as SsxIrqId uint8_t irq; } PbaxQueue; int pbax_queue_create(PbaxQueue* queue, int engine, uint64_t* cq_base, size_t cq_entries, int protocol); int pbax_queue_disable(PbaxQueue* queue); int pbax_queue_enable(PbaxQueue* queue); int pbax_read(PbaxQueue* queue, void* buf, size_t bytes, size_t* read); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // OcbRequest //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ /// OCB FFDC /// /// This structure is used to store FFDC in two cases. 1) When an error can be /// reasonably attributed to an OCB channel under the control of OCC, and 2) /// general errors signalled by the OCB direct bridge. Due to the myriad ways /// that OCB channels can be used the FFDC for OCB direct bridge errors is /// stored globally rather than with particular requests or queues. /// /// The OcbFfdc includes the PLB arbiter PEARL and PESR register state. /// This state is only collected if the error status indicates an OCI timeout /// for this channel. /// /// Any error reasonably attributable to a channel will capture the FFDC and /// then disable the channel since any further communication through the /// channel must be considered compromised. typedef struct { /// FFDC from the OCI (PLB) arbiter OciFfdc oci_ffdc; /// A copy of the OCB OCC_LFIR register at the time of the error ocb_occlfir_t fir; /// A copy of the OCB Control/Status register for the channel at the time /// of the error. /// /// This field will be set to 0 for generic OCB bridge errors ocb_ocbcsrn_t csr; /// A copy of the OCB Stream Push Base [n] Register at the time of the /// failure /// /// This field will be set to 0 for generic OCB bridge errors ocb_ocbshbrn_t shbr; /// A copy of the OCB Stream Push Control/Status [n] Register at the time /// of the failure /// /// This field will be set to 0 for generic OCB bridge errors ocb_ocbshcsn_t shcs; /// A copy of the OCB Stream Pull Base [n] Register at the time of the /// failure /// /// This field will be set to 0 for generic OCB bridge errors ocb_ocbslbrn_t slbr; /// A copy of the OCB Stream Pull Control/Status [n] Register at the time /// of the failure /// /// This field will be set to 0 for generic OCB bridge errors ocb_ocbslcsn_t slcs; /// Is this record valid (does it contain captured error information)? int error; } OcbFfdc; /// OCB Unit FFDC /// /// Contains FFDC structures for each channel and the direct bridge typedef struct { OcbFfdc channel[OCB_INDIRECT_CHANNELS]; OcbFfdc bridge; } OcbUnitFfdc; /// Global FFDC for OCB extern OcbUnitFfdc G_ocb_ffdc; struct OcbQueue; /// A request to move data through an OCB circular queue /// /// The OCB circular queues are named and documented in the hardware specs /// from the perspective of the PIB - "PUSH" and "PULL" queues. Here we name /// and document the queues from the perspective of OCC firmware - "READ" and /// "WRITE" queues. The request is generic and becomes either a read or write /// request simply by which queue it is scheduled on. /// /// The circular queues only support 8-byte granularity, require that the data /// areas be 8- or 32-byte aligned, and only support up to 256 byte /// queues. However the async drivers allow specification of any multiple of 8 /// bytes to read or write, and handle all of the queue and split-request /// management. /// /// Note : As long as the OcbRequest is idle, the application is free to /// directly change the \a data and \a bytes fields to read/write different /// numbers of bytes to/from different locations the next time the request is /// scheduled. /// /// OCB requests always complete in an interrupt context. The OCB queues /// support both 'lazy' and 'aggressive' interrupt protocols. The aggressive /// protocols generate interrupts whenever read data is available or write /// space is available. The lazy protocols require a full read buffer or /// empty write buffer to trigger an interrupt. A lazy read protocol with a /// buffer size > 1 demands that communcations always consist of a known /// number of doublewords. For free-form communications an aggressive read /// protocol must be used. On average, an aggressive write protocol will /// shorten blocking periods of writers, and can guarantee that data is in the /// queue whenever data is avilable. Lazy write protocols will be preferred /// when reducing interrupt overhead is more important than reducing blocking /// time. /// /// Completion of write requests does not guarantee that the communication /// partner has received the data, but simply that the data has been queued /// for reception and the caller may reuse/refill the data buffer if required. typedef struct { /// The generic request AsyncRequest request; /// Initial pointer to the data to be moved for write data, or the /// data area to hold read data. This field is not modified by the drivers. uint64_t* data; /// Number of bytes to move. This field is not modified by the drivers. size_t bytes; /// Pointer to data yet to be moved for write, or where to put the next /// read data. uint64_t* current; /// Number of bytes remaining to be moved. size_t remaining; } OcbRequest; int ocb_request_create(OcbRequest* request, struct OcbQueue* queue, uint64_t* data, size_t bytes, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options); int ocb_request_schedule(OcbRequest* request); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // OcbQueue //////////////////////////////////////////////////////////////////////////// // NB: This assignment ordering is assumed by static initialization code in // occhw_async.c - these constants are used as array indices. The code also // assumes this ordering for the access of G_ocb_ocbsesn[], and for // determining whether the engine is a PUSH or PULL queue. // Note: push/pull queues for channel 3 have been deleted #define OCB_ENGINE_PUSH0 0 #define OCB_ENGINE_PULL0 1 #define OCB_ENGINE_PUSH1 2 #define OCB_ENGINE_PULL1 3 #define OCB_ENGINE_PUSH2 4 #define OCB_ENGINE_PULL2 5 #define OCB_ENGINE_PUSH3 6 #define OCB_ENGINE_PULL3 7 #define OCB_ENGINES 8 #ifndef __ASSEMBLER__ /// An OCB Circular buffer queue /// /// A OCB circular buffer queue consists of a generic AsyncQueue to manage /// jobs on the engine, a pointer to the data area and the OCB engine id. typedef struct OcbQueue { /// The generic request queue AsyncQueue queue; /// The base of the circular queue data area - must be 8-byte aligned uint64_t* cq_base; /// The length of the queue in terms of the number of 8-byte entries in /// the queue. /// /// This is for informational purposes only. The length is also encoded /// in the OCBSxCSn register for the queue. size_t cq_length; /// The engine id for lookup of OCI control register addresses. int engine; /// The IRQ associated with normal completion on the engine /// /// \todo Due to header reference ordering we can't define this as SsxIrqId uint8_t irq; } OcbQueue; int ocb_queue_create(OcbQueue* queue, int engine, uint64_t* cq_base, size_t cq_length, int protocol); #endif /* __ASSEMBLER__ */ //////////////////////////////////////////////////////////////////////////// // Miscellaneous/Initialization //////////////////////////////////////////////////////////////////////////// // Error codes #define ASYNC_INVALID_OBJECT_REQUEST 0x00279600 #define ASYNC_INVALID_OBJECT_SCHEDULE 0x00279601 #define ASYNC_INVALID_OBJECT_OCB_REQUEST 0x00279602 #define ASYNC_INVALID_OBJECT_OCB_QUEUE 0x00279603 #define ASYNC_INVALID_OBJECT_PBAX_REQUEST 0x00279604 #define ASYNC_INVALID_OBJECT_PBAX_DISABLE 0x00279605 #define ASYNC_INVALID_OBJECT_PBAX_QUEUE 0x00279606 #define ASYNC_INVALID_OBJECT_BCE_REQUEST 0x00279607 #define ASYNC_INVALID_OBJECT_BCE_QUEUE 0x00279608 #define ASYNC_INVALID_OBJECT_GPE_REQUEST 0x00279609 #define ASYNC_INVALID_OBJECT_GPE_QUEUE 0x0027960a #define ASYNC_INVALID_ARGUMENT 0x00279610 #define ASYNC_INVALID_ARGUMENT_OCB_READ 0x00279611 #define ASYNC_INVALID_ARGUMENT_OCB_WRITE 0x00279612 #define ASYNC_INVALID_ARGUMENT_OCB_QUEUE 0x00279613 #define ASYNC_INVALID_ARGUMENT_OCB_QUEUE2 0x00279614 #define ASYNC_INVALID_ARGUMENT_OCB_REQUEST 0x00279615 #define ASYNC_INVALID_ARGUMENT_OCB_SCHEDULE 0x00279616 #define ASYNC_INVALID_ARGUMENT_BCE_SCHEDULE 0x00279617 #define ASYNC_INVALID_ARGUMENT_PBAX_READ 0x00279618 #define ASYNC_INVALID_ARGUMENT_PBAX_REQUEST 0x00279619 #define ASYNC_INVALID_ARGUMENT_PBAX_SCHEDULE 0x0027961a #define ASYNC_INVALID_ARGUMENT_PBAX_QUEUE 0x0027961b #define ASYNC_INVALID_ARGUMENT_GPE_REQUEST 0x0027961c #define ASYNC_INVALID_ENGINE_OCB 0x0027961f #define ASYNC_INVALID_ENGINE_PBAX 0x00279620 #define ASYNC_INVALID_ENGINE_BCE 0x00279621 #define ASYNC_INVALID_ENGINE_GPE 0x00279622 #define ASYNC_INVALID_OPTIONS 0x00279624 #define ASYNC_INVALID_ASSIGNMENT 0x00279625 #define ASYNC_CALLBACK_PROTOCOL_UNSPECIFIED 0x00279626 #define ASYNC_REQUEST_NOT_IDLE 0x00279627 #define ASYNC_REQUEST_COMPLETE 0x00279629 #define ASYNC_INVALID_TIMESTAMPS 0x0027962a #define ASYNC_OCB_ERROR_READ_OLD 0x0027962b #define ASYNC_OCB_ERROR_READ_NEW 0x0027962c #define ASYNC_OCB_ERROR_WRITE_OLD 0x0027962d #define ASYNC_OCB_ERROR_WRITE_NEW 0x0027962e #define ASYNC_PBAX_ERROR_OLD 0x0027962f #define ASYNC_PBAX_ERROR_NEW 0x00279630 #define ASYNC_REQUEST_NOT_COMPLETE 0x00279631 // Panic codes #define ASYNC_GPE_FIXED_INVARIANT 0x00279633 #define ASYNC_PHANTOM_INTERRUPT 0x00279634 #define ASYNC_PHANTOM_INTERRUPT_OCB 0x00279635 #define ASYNC_PHANTOM_INTERRUPT_BCE 0x00279636 #define ASYNC_PHANTOM_INTERRUPT_PBAX 0x00279637 #define ASYNC_SCOM_ERROR 0x00279638 #define ASYNC_TIMEOUT_BUG 0x00279639 #define ASYNC_INVALID_STATE 0x0027963a #define ASYNC_PHANTOM_ERROR 0x0027963b #define ASYNC_BUG_GPE_AT_CREATE 0x0027963c //////////////////////////////////////////////////////////////////////////// // Global Data and Constants //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ // GPE Queues extern GpeQueue G_async_gpe_queue0; extern GpeQueue G_async_gpe_queue1; extern GpeQueue G_async_gpe_queue2; extern GpeQueue G_async_gpe_queue3; // OCB Queues and FFDC // OCB circular queue naming is confusing, because PUSH/PULL are defined from // the perspective of the PIB. This driver uses the terms read/write // respectively and represents the hardware from the perspective of code // running on OCC. // OCB read/write queue lengths are defined in terms of doublewords, and must // be in a small defined range. Two meaningful interrupt protocols are // possible for a queue: 'LAZY' allows read/write queues to fill/empty // respectively before an interrupt is signalled. 'AGRESSIVE' signals an // interrupt whenever there is data to be read or a free slot to put write // data. // In a production system the lengths and protocols will likely vary based on // the particular application and the characteristics of the communication // partner. By default the queues take on their maximum lengths. Read queues // use the aggressive protocol which allows free-form communication. Write // queues use lazy protoclols which reduces interrupt overhead. Different // effective lengths and the interrupt protocols can be changed later if // desired - assuming the queues are idle when the changes are made. #define OCB_PUSH_PULL_LENGTH_MIN 1 #define OCB_PUSH_PULL_LENGTH_MAX 32 #define OCB_INTERRUPT_PROTOCOL_LAZY 0 #define OCB_INTERRUPT_PROTOCOL_AGGRESSIVE 1 #define OCB_READ0_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_READ1_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_READ2_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_READ3_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_WRITE0_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_WRITE1_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_WRITE2_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_WRITE3_LENGTH OCB_PUSH_PULL_LENGTH_MAX #define OCB_READ0_PROTOCOL OCB_INTERRUPT_PROTOCOL_AGGRESSIVE #define OCB_READ1_PROTOCOL OCB_INTERRUPT_PROTOCOL_AGGRESSIVE #define OCB_READ2_PROTOCOL OCB_INTERRUPT_PROTOCOL_AGGRESSIVE #define OCB_READ3_PROTOCOL OCB_INTERRUPT_PROTOCOL_AGGRESSIVE #define OCB_WRITE0_PROTOCOL OCB_INTERRUPT_PROTOCOL_LAZY #define OCB_WRITE1_PROTOCOL OCB_INTERRUPT_PROTOCOL_LAZY #define OCB_WRITE2_PROTOCOL OCB_INTERRUPT_PROTOCOL_LAZY #define OCB_WRITE3_PROTOCOL OCB_INTERRUPT_PROTOCOL_LAZY extern OcbUnitFfdc G_ocb_ffdc; extern OcbQueue G_ocb_read_queue[]; extern OcbQueue G_ocb_write_queue[]; extern uint64_t G_ocb_read0_buffer[]; extern uint64_t G_ocb_read1_buffer[]; extern uint64_t G_ocb_read2_buffer[]; extern uint64_t G_ocb_read3_buffer[]; extern uint64_t G_ocb_write0_buffer[]; extern uint64_t G_ocb_write1_buffer[]; extern uint64_t G_ocb_write2_buffer[]; extern uint64_t G_ocb_write3_buffer[]; // PBA Queues /// Block Copy Upload (OCI -> PowerBus) Engine job queue; extern BceQueue G_pba_bcue_queue; /// Block Copy Download Engine (PowerBus -> OCI) job queue; extern BceQueue G_pba_bcde_queue; // PBAX Queues // PBAX circular queue naming is confusing, because "PUSH" is defined from the // perspective of the PowerBus. This driver uses the term "READ" and // represents the hardware from the perspective of code running on OCC. // PBAX read queue lengths are defined in terms of 8-byte doublewords, and // must be in a small defined range. Two meaningful interrupt protocols are // possible for a queue: 'LAZY' allows read queues to fill before an interrupt // is signalled. 'AGRESSIVE' signals an interrupt whenever there is data to // be read. // In a production system the lengths and protocols will likely vary based on // the particular application and the characteristics of the communication // partner. By default the queues take on their maximum lengths. Read queues // use the aggressive protocol which allows free-form communication. Different // effective lengths and the interrupt protocols can be changed later if // desired - assuming the queues are idle when the changes are made. #define PBAX_PUSH_LENGTH_MIN 1 #define PBAX_PUSH_LENGTH_MAX 32 #define PBAX_INTERRUPT_PROTOCOL_LAZY 0 #define PBAX_INTERRUPT_PROTOCOL_AGGRESSIVE 1 #define PBAX_READ0_LENGTH PBAX_PUSH_LENGTH_MAX #define PBAX_READ1_LENGTH PBAX_PUSH_LENGTH_MAX #define PBAX_READ0_PROTOCOL PBAX_INTERRUPT_PROTOCOL_AGGRESSIVE #define PBAX_READ1_PROTOCOL PBAX_INTERRUPT_PROTOCOL_AGGRESSIVE /// Job queues for the PBAX circular buffers extern PbaxQueue G_pbax_read_queue[]; // PBAX read buffers must be cache-line aligned since they are invalidated, // and furthermore must be aligned to the next higher power-of-two of their // lengths. Some minor efficiencies could probably be obtained by a policy // that buffers be held in non-cacheable storage (and subsequent modifications // to the device driver code). // // Due to linker restrictions, only initialized data areas can be aligned. #define _PBAX_ALIGN_(length) \ (((length) <= 4) ? 32 : \ (((length) <= 8) ? 64 : \ (((length) <= 16) ? 128 : 256))) #define PBAX_CQ_READ_BUFFER(buffer, length) \ uint64_t buffer[length] \ __attribute__ ((aligned (_PBAX_ALIGN_(length)))) = {0} extern uint64_t G_pbax_read0_buffer[]; extern uint64_t G_pbax_read1_buffer[]; // Initialization APIs void async_gpe_initialize(GpeQueue* queue, int engine); void async_bce_initialize(BceQueue* queue, int engine, SsxIrqId irq); void async_ocb_initialize(OcbQueue* queue, int engine, uint64_t* buffer, size_t length, int protocol); void async_pbax_initialize(PbaxQueue* queue, int engine, SsxIrqId irq, uint64_t* buffer, size_t length, int protocol); void async_initialize(); #endif /* __ASSEMBLER__ */ #endif /* __OCCHW_ASYNC_H__ */ <|start_filename|>src/lib/ppc405lib/simics_stdio.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/simics_stdio.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file simics_stdio.c /// \brief SSX I/O drivers for Simics stdio streams /// /// The Simics 'stdio' component is a pseudo serial port for I/O to stdio, /// stdout and stderr, as well as to other configurable streams. Each virtual /// file potentially has a read port, write port and flush port. /// /// The write ports accept 1, 2 and 4-byte transactions on a 32-bit OCI /// address and write the data to the associated stream. Writing any value to /// the flush port flushes the output stream. The input ports are not yet /// implemented. #include "ssx.h" #include "simics_stdio.h" SimicsStdio simics_stdin; SimicsStdio simics_stdout; SimicsStdio simics_stderr; int simics_stdio_sread(FILE *stream, void *buf, size_t count, size_t *read) { SSX_PANIC(ENXIO); return -ENXIO; } int simics_stdio_swrite(FILE *stream, const void *buf, size_t count, size_t *written) { SimicsStdio *simics = (SimicsStdio *)stream; size_t n; n = count; while (n) { if (n >= 4) { out32(simics->write_address, *((uint32_t *)buf)); buf += 4; n -= 4; } else if (n >= 2) { out16(simics->write_address, *((uint16_t *)buf)); buf += 2; n -= 2; } else { out8(simics->write_address, *((uint8_t *)buf)); buf++; n--; } } *written = count; return 0; } ssize_t simics_stdio_fflush(FILE *stream) { SimicsStdio *simics = (SimicsStdio *)stream; out8(simics->flush_address, 0); return 0; } /// Create a SimicsStdio stream /// /// Any of the \a read_address, \a write_address or \a flush_address which are /// non-0 specify that the stream supports the associated method. The Simics /// I/O drivers do not require locking. int simics_stdio_create(SimicsStdio* stream, SsxAddress read_address, SsxAddress write_address, SsxAddress flush_address) { FILE *base = (FILE *)stream; int rc; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(stream == 0, EBADF); } rc = FILE_create((FILE*)stream, 0); if (!rc) { stream->read_address = read_address; if (read_address != 0) { base->sread = simics_stdio_sread; } stream->write_address = write_address; if (write_address != 0) { base->swrite = simics_stdio_swrite; } stream->flush_address = flush_address; if (flush_address != 0) { base->fflush = simics_stdio_fflush; } } return rc; } int simics_stdin_create(SimicsStdio *stream) { return simics_stdio_create(stream, SIMICS_STDIN, 0, 0); } int simics_stdout_create(SimicsStdio *stream) { return simics_stdio_create(stream, 0, SIMICS_STDOUT, SIMICS_STDOUT_FLUSH); } int simics_stderr_create(SimicsStdio *stream) { return simics_stdio_create(stream, 0, SIMICS_STDERR, SIMICS_STDERR_FLUSH); } int simics_stdfile_create(SimicsStdio *stream, int fn) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((fn < 0) > (fn >= SIMICS_STDFILE_STREAMS), EBADF); } return simics_stdio_create(stream, SIMICS_STDFILE_READ(fn), SIMICS_STDFILE_WRITE(fn), SIMICS_STDFILE_FLUSH(fn)); } <|start_filename|>src/ppe/pk/kernel/pk_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/kernel/pk_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file pk_init.c /// \brief PK initialization /// /// The entry points in this file are initialization routines - they are never /// needed after PK initialization and their code space could be reclaimed by /// the application after initialization if required. #include "pk.h" #include "pk_trace.h" uint32_t __pk_timebase_frequency_hz; /// The timebase frequency is passed into PK during initialization. It cannot /// be set statically because there is a requirement to support a frequency /// that can change from one IPL to the next. On the 405, scaling of time /// intervals is accomplished by doing a 32x32 bit multiplication which is /// supported by the ppc405 instruction set. PPE42 does not support 32x32 bit /// multiplication directly and some applications can not afford to use a /// function call to emulate the operation. Instead we scale the time /// interval by shifting the value X bits to the right and adding it to itself. /// This can scale the value by 2, 1.5, 1.25, 1.125, etc. /// /// This is the right shift value. /// NOTE: shifting by 0 gives a 2x scale factor, shifting by 32 gives a 1x /// scale factor. uint8_t __pk_timebase_rshift = 32; void pk_set_timebase_rshift(uint32_t timebase_freq_hz) { //Use 1.0 scale if less than or equal to 1.0625 * base frequency if(timebase_freq_hz <= (PK_BASE_FREQ_HZ + (PK_BASE_FREQ_HZ >> 4))) { __pk_timebase_rshift = 32; } //use 1.125 scale if between 1.0625 and 1.1875 * base frequency else if(timebase_freq_hz <= (PK_BASE_FREQ_HZ + (PK_BASE_FREQ_HZ >> 4) + (PK_BASE_FREQ_HZ >> 3))) { __pk_timebase_rshift = 3; } //use 1.25 scale if between 1,1875 and 1.375 * base frequency else if(timebase_freq_hz <= (PK_BASE_FREQ_HZ + (PK_BASE_FREQ_HZ >> 3) + (PK_BASE_FREQ_HZ >> 2))) { __pk_timebase_rshift = 2; } //use 1.5 scale if between 1.375 and 1.75 * base frequency else if(timebase_freq_hz <= (PK_BASE_FREQ_HZ + (PK_BASE_FREQ_HZ >> 2) + (PK_BASE_FREQ_HZ >> 1))) { __pk_timebase_rshift = 1; } //use 2.0 scale if greater than 1.75 * base frequency else { __pk_timebase_rshift = 0; } } /// Initialize PK. /// /// \param kernel_stack A stack area for interrupt and bottom-half handlers. /// /// \param kernel_stack_size The size (in bytes) of the stack area for /// interrupt and bottom-half handlers. /// /// \param initial_timebase The initial value of the PK timebase. /// If the argument is given as the special value \c PK_TIMEBASE_CONTINUES, then the /// timebase is not reset. /// /// \param timebase_frequency_hz The frequency of the PK timebase in Hz. /// /// This routine \e must be called before any other PK / routines, and \e /// should be called before any interrupts are enabled. /// /// Return values other than PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_ARGUMENT_INIT A stack pointer is 0 or is given /// a 0 size. /// /// \retval -PK_STACK_OVERFLOW One or both stacks are not large enough to /// support a minimum context save in the event of an interrupt. // Note that PK does not rely on any static initialization of dynamic // variables. In debugging sessions using RAM-resident PK images it is // assumed that the processor may be reset at any time, so we always need to // reset everything at initialization. #if PK_TRACE_SUPPORT extern PkTimer g_pk_trace_timer __attribute__((section (".sdata"))); #endif int pk_initialize(PkAddress kernel_stack, size_t kernel_stack_size, PkTimebase initial_timebase, uint32_t timebase_frequency_hz) { int rc; if (PK_ERROR_CHECK_API) { PK_ERROR_IF((kernel_stack == 0) || (kernel_stack_size == 0), PK_INVALID_ARGUMENT_INIT); } __pk_timebase_frequency_hz = timebase_frequency_hz; __pk_thread_machine_context_default = PK_THREAD_MACHINE_CONTEXT_DEFAULT; //set the shift adjustment to get us closer to the true //timebase frequency (versus what was hardcoded) pk_set_timebase_rshift(timebase_frequency_hz); __pk_kernel_stack_limit = kernel_stack; rc = __pk_stack_init(&kernel_stack, &kernel_stack_size); if (rc) { return rc; } __pk_kernel_stack = kernel_stack; __pk_kernel_stack_size = kernel_stack_size; #if PK_TIMER_SUPPORT // Initialize the time queue sentinel as a circular queue, set the next // timeout and clear the cursor. pk_deque_sentinel_create((PkDeque*)&__pk_time_queue); __pk_time_queue.cursor = 0; __pk_time_queue.next_timeout = PK_TIMEBASE_MAX; #if PK_TRACE_SUPPORT //set the trace timebase HZ g_pk_trace_buf.hz = timebase_frequency_hz; if(initial_timebase != PK_TIMEBASE_CONTINUES) { //set the timebase ajdustment for trace synchronization pk_trace_set_timebase(initial_timebase); } // Schedule the timer that puts a 64bit timestamp in the trace buffer // periodically. This allows us to use 32bit timestamps. pk_timer_schedule(&g_pk_trace_timer, PK_TRACE_TIMER_PERIOD); #endif /* PK_TRACE_SUPPORT */ #endif /* PK_TIMER_SUPPORT */ #if PK_THREAD_SUPPORT // Clear the priority map. The final entry [PK_THREADS] is for the idle // thread. int i; for (i = 0; i <= PK_THREADS; i++) { __pk_priority_map[i] = 0; } // Initialize the thread scheduler __pk_thread_queue_clear(&__pk_run_queue); __pk_current_thread = 0; __pk_next_thread = 0; __pk_delayed_switch = 0; #endif /* PK_THREAD_SUPPORT */ return PK_OK; } // Set the timebase frequency. int pk_timebase_freq_set(uint32_t timebase_frequency_hz) { __pk_timebase_frequency_hz = timebase_frequency_hz; pk_set_timebase_rshift(timebase_frequency_hz); #if PK_TRACE_SUPPORT g_pk_trace_buf.hz = timebase_frequency_hz; #endif // Does the initial_timebase need to be reset? return PK_OK; } /// Call the application main() /// /// __pk_main() is called from the bootloader. It's only purpose is to /// provide a place for the PK_MAIN_HOOK to be called before main() is /// called. void __pk_main(int argc, char** argv) { PK_MAIN_HOOK; int main(int argc, char** argv); main(argc, argv); } <|start_filename|>src/ssx/ppc405/ssxppc405files.mk<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/ssx/ppc405/ssxppc405files.mk $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2014,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG # @file ssxppc405files.mk # # @brief mk for including ppc405 object files ########################################################################## # Include Files ########################################################################## ########################################################################## # Object Files ########################################################################## PPC405-C-SOURCES = ppc405_core.c \ ppc405_lib_core.c \ ppc405_cache_core.c \ ppc405_init.c \ ppc405_irq_core.c \ ppc405_irq_init.c PPC405-S-SOURCES = ppc405_boot.S \ ppc405_exceptions.S \ ppc405_cache_init.S \ ppc405_mmu_asm.S \ ppc405_breakpoint.S PPC405-TIMER-C-SOURCES = PPC405-TIMER-S-SOURCES = PPC405-THREAD-C-SOURCES += PPC405-THREAD-S-SOURCES += ppc405_thread_init.S PPC405-MMU-C-SOURCES += ppc405_mmu.c PPC405-MMU-S-SOURCES += PPC405_OBJECTS += $(PPC405-C-SOURCES:.c=.o) $(PPC405-S-SOURCES:.S=.o) <|start_filename|>src/lib/occlib/occhw_xir_dump.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/occlib/occhw_xir_dump.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_XIR_DUMP_H__ #define __OCCHW_XIR_DUMP_H__ /// \file occhw_xir_dump.h /// \brief header for the occhw_xir_dump function /// #ifndef __ASSEMBLER__ #include "stdint.h" /// Structure for dumping XIR data for a GPE typedef struct { uint32_t xsr; uint32_t sprg0; uint32_t edr; uint32_t ir; uint32_t iar; uint32_t sib_upper; uint32_t sib_lower; } occhw_xir_dump_t; /////////////////////////////////////////////////////////////////////////////// /// Dump the XIR registers for a GPE engine /// /// \param inst_id The instance ID of the target GPE. /// /// \param xir_dump Pointer to a occhw_xir_dump_t structure. /// /// Possible return codes are: /// /// \retval 0 XIR registers were successfully dumped /// /// \retval OCCHW_XIR_INVALID_GPE \a inst_id is not for a valid GPE instance. /// /// \retval OCCHW_XIR_INVALID_POINTER \a xir_dump is NULL /// int32_t occhw_xir_dump(uint32_t inst_id, occhw_xir_dump_t* xir_dump); #endif /*__ASSEMBLER__*/ #endif /*__OCCHW_XIR_DUMP_H__*/ <|start_filename|>src/occ_gpe0/firdata/pnorData_common.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/pnorData_common.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __pnorData_common_h #define __pnorData_common_h /** NOTE: This file is common between OCC and Hosboot. Any change to this file * must be mirrored to both repositories. Also, this must be C, not C++, * because OCC strictly uses C. */ #include <firDataConst_common.h> #include <string.h> /** This file is used to define the format of the register data captured by the * OCC and stored in PNOR. The data will be stored in the following format: * * - PNOR_Data_t struct - This has all of the information characterizing how * many targets that have register data. * - For each target with register data, the following format will be used: * - PNOR_Trgt_t struct - Contains the target type, position, and how many * registers are in the register list. * - A list of all regular registers (PNOR_Reg_t). * - A list of all indirect-SCOM registers (PNOR_IdReg_t). * * IMPORTANT NOTE: All of the structs used here are packed. Therefore, we must * ensure the variables within the struct are byte aligned. Meaning each * uint32_t within the struct must be 4-byte aligned and each uint16_t must * be 2-byte aligned. This also means the structs must always start on a * 4-bye word boundary to maintain alignment. This is required due to the * limitations of the PPE42/SRAM hardware. * * The PNOR has limited data space. So the following rules will apply: * - Any registers with the value of zero will not be captured. * - Registers with SCOM errors will not be captured, however, the number * of SCOM errors detected should be stored in each PNOR_Trgt_t struct. * - If the value of a FIR (or ID FIR) is zero, do not capture the * associated ACT0 and ACT1 registers. Note that the associated MASK * register is still needed for FFDC. * - Each target type may have associated global registers. If none exist, * simply capture all registers for that type. However, if they do exist * and the values of ALL the global registers are zero, skip capturing * the associated registers of the target and any subsequent targets on * the affinity path. Example, * - For a MCBIST, skip this MCBIST and all associated MCSs, and MCAs. * - If for some reason we run out of space in the PNOR, do not SCOM any * more registers, set the 'full' bit in the PNOR_Data_t struct, and * write all data successfully captured to PNOR. */ typedef enum { PNOR_FIR1 = 0x46495231, /** FIR data version 1 ("FIR1" in ascii) P8 */ PNOR_FIR2 = 0x46495232, /** FIR data version 2 ("FIR2" in ascii) P9 */ } PNOR_Version_t; /** PNOR data header information. */ /* NOTE: This structure is 4-byte word aligned. */ typedef struct __attribute__((packed)) { uint32_t header; /** Magic number to indicate valid data and version */ uint32_t trgts : 12; /** Number of targets with register data */ uint32_t full : 1; /** 1 if PNOR data is full and data incomplete */ uint32_t iplState : 1; /** See enum IplState_t */ uint32_t reserved : 18; } PNOR_Data_t; /** @return An initialized PNOR_Data_t struct. */ static inline PNOR_Data_t PNOR_getData() { PNOR_Data_t d; memset( &d, 0x00, sizeof(d) ); /* init to zero */ d.header = PNOR_FIR2; return d; }; /** These values will match the corresponding bit fields in PNOR_Trgt_t. */ typedef enum { PNOR_Trgt_MAX_REGS_PER_TRGT = 511, /* Currently expect 266 on the PROC */ PNOR_Trgt_MAX_ID_REGS_PER_TRGT = 15, /* Currently expect 9 on the MBA */ PNOR_Trgt_MAX_SCOM_ERRORS = 255, /* Should be plenty */ } PNOR_Trgt_RegLimits_t; /** Information for each target with SCOM data. */ /* NOTE: This structure is 4-byte word aligned. */ typedef struct __attribute__((packed)) { uint32_t chipPos : 6; /** Parent chip position relative to the node */ uint32_t unitPos : 5; /** Unit position relative to the parent chip */ uint32_t regs : 9; /** Number of normal registers */ uint32_t idRegs : 4; /** Number of indirect-SCOM registers */ uint32_t scomErrs : 8; /** Number of SCOM errors detected */ uint32_t trgtType : 6; /** Target type. See enum TrgtType_t */ uint32_t reserved : 26; } PNOR_Trgt_t; /** @param i_trgtType Target type. See enum TrgtType_t. * @param i_chipPos Parent chip position relative to the node. * @param i_unitPos Unit position relative to the parent chip. * @return An initialized PNOR_Data_t struct. */ static inline PNOR_Trgt_t PNOR_getTrgt( uint32_t i_trgtType, uint32_t i_chipPos, uint32_t i_unitPos ) { PNOR_Trgt_t t; memset( &t, 0x00, sizeof(t) ); /* init to zero */ t.trgtType = i_trgtType; t.chipPos = i_chipPos; t.unitPos = i_unitPos; return t; }; /** Information for a normal register. */ /* NOTE: This structure is 4-byte word aligned. */ //The order matters here due to hardware limitations on the GPE typedef struct __attribute__((packed)) { uint64_t val; /** 64-bit value */ uint32_t addr; /** 32-bit address */ } PNOR_Reg_t; /** Information for an indirect-SCOM register. */ /* NOTE: This structure is 4-byte word aligned. */ typedef struct __attribute__((packed)) { uint64_t addr; /** 64-bit address */ uint32_t val; /** 32-bit value */ } PNOR_IdReg_t; #endif // __pnorData_common_h <|start_filename|>src/occBootLoader/linkboot.cmd<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occBootLoader/linkboot.cmd $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // Linker script for the OCC Firmware boot loader. // // The image is 4 byte aligned. #define BOOT_IMAGE_START_ADDR 0x80000000 #define BOOT_VECTORS 0x80000000 #define BOOT_VECTORS_SIZE 0x00000740 #define BOOT_BUILDNAME_ADDR (BOOT_IMAGE_START_ADDR + BOOT_VECTORS_SIZE) #define WRITE_DATA_SEC_ADDR 0x00000000 #define BYTE_ALIGN 128 #define pack_0000 *(imageHeader) MEMORY { writeableMem : ORIGIN = WRITE_DATA_SEC_ADDR, LENGTH = 0x4000 } SECTIONS { . = BOOT_IMAGE_START_ADDR; . = BOOT_VECTORS; __START_ADDR__ = .; //////////////////////////////// // start read-only section //////////////////////////////// //////////////////////////////// // exception/vector section //////////////////////////////// .exceptions . : { ___vectors = .; bootInit.o(.vectors_0000) pack_0000 . = ___vectors + 0x0100; *(.vectors_0100) . = ___vectors + 0x0200; *(.vectors_0200) . = ___vectors + 0x0300; *(.vectors_0300) . = ___vectors + 0x0400; *(.vectors_0400) . = ___vectors + 0x0500; *(.vectors_0500) . = ___vectors + 0x0600; *(.vectors_0600) . = ___vectors + 0x0700; *(.vectors_0700) } //////////////////////////////// // buildname section 4 byte aligned //////////////////////////////// . = BOOT_BUILDNAME_ADDR; .buildname . : { *(.buildname) } //////////////////////////////// // text section 4 byte aligned, follows buildname section //////////////////////////////// .text . : { *(.text) *(.text.*) . = ALIGN(BYTE_ALIGN); } //////////////////////////////// // SDA2 section 4 byte aligned //////////////////////////////// _SDA2_BASE_ = .; .sdata2 . : { *(.sdata2) . = ALIGN(BYTE_ALIGN); } .sbss2 . : { *(.sbss2) . = ALIGN(BYTE_ALIGN); } .rodata . : { *(.rodata*) *(.got2) . = ALIGN(BYTE_ALIGN); } __READ_ONLY_DATA_LEN__ = . - BOOT_IMAGE_START_ADDR; __WRITEABLE_ADDR__ = .; //////////////////////////////// // start writeable section, has different virtual and loadable memory addresses //////////////////////////////// __WRITEABLE_DATA_ADDR__ = WRITE_DATA_SEC_ADDR; __CURADDR__ = WRITE_DATA_SEC_ADDR; //////////////////////////////// // read-write section //////////////////////////////// .rela __CURADDR__ : AT(__WRITEABLE_ADDR__) { *(.rela*) . = ALIGN(BYTE_ALIGN); } > writeableMem __CURADDR__ = __CURADDR__ + SIZEOF(.rela); .rwdata __CURADDR__ : AT(__WRITEABLE_ADDR__ + SIZEOF(.rela)) { *(.data) *(.bss) *(COMMON) . = ALIGN(BYTE_ALIGN); } > writeableMem __CURADDR__ = __CURADDR__ + SIZEOF(.rwdata); //////////////////////////////// // SDA section //////////////////////////////// _SDA_BASE_ = __CURADDR__; .sdata __CURADDR__ : AT(__WRITEABLE_ADDR__ + SIZEOF(.rela) + SIZEOF(.rwdata)) { *(.sdata) . = ALIGN(BYTE_ALIGN); } > writeableMem __CURADDR__ = __CURADDR__ + SIZEOF(.sdata); .sbss (__CURADDR__) : AT(__WRITEABLE_ADDR__ + SIZEOF(.rela) + SIZEOF(.rwdata) + SIZEOF(.sdata)) { *(.sbss) . = ALIGN(BYTE_ALIGN); } > writeableMem __CURADDR__ = __CURADDR__ + SIZEOF(.sbss); //////////////////////////////// // writeable section length //////////////////////////////// __WRITEABLE_DATA_LEN__ = (__WRITEABLE_ADDR__ + SIZEOF(.sdata) + SIZEOF(.rela) + SIZEOF(.rwdata)) - __WRITEABLE_ADDR__; } <|start_filename|>src/ssx/occhw/occhw_scom.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_scom.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_SCOM_H__ #define __OCCHW_SCOM_H__ /// \file occhw_scom.h /// \brief procedures and support for SCOM operations #include "ssx.h" #include "occhw_common.h" //////////////////////////////////////////////////////////////////////////// // SCOM //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ int _getscom(uint32_t address, uint64_t* data, SsxInterval timeout); int getscom(uint32_t address, uint64_t* data); int _putscom(uint32_t address, uint64_t data, SsxInterval timeout); int putscom(uint32_t address, uint64_t data); #endif /* __ASSEMBLER__ */ // Error/Panic Codes #define SCOM_PCB_ERROR_1_GETSCOM 0x00726601 #define SCOM_PCB_ERROR_2_GETSCOM 0x00726602 #define SCOM_PCB_ERROR_3_GETSCOM 0x00726603 #define SCOM_PCB_ERROR_4_GETSCOM 0x00726604 #define SCOM_PCB_ERROR_5_GETSCOM 0x00726605 #define SCOM_PCB_ERROR_6_GETSCOM 0x00726606 #define SCOM_PCB_ERROR_7_GETSCOM 0x00726607 #define SCOM_PCB_ERROR_1_PUTSCOM 0x00726608 #define SCOM_PCB_ERROR_2_PUTSCOM 0x00726609 #define SCOM_PCB_ERROR_3_PUTSCOM 0x0072660a #define SCOM_PCB_ERROR_4_PUTSCOM 0x0072660b #define SCOM_PCB_ERROR_5_PUTSCOM 0x0072660c #define SCOM_PCB_ERROR_6_PUTSCOM 0x0072660d #define SCOM_PCB_ERROR_7_PUTSCOM 0x0072660e #define SCOM_TIMEOUT_ERROR 0x00726610 #define SCOM_TIMEOUT_ERROR_GETSCOM 0x00726611 #define SCOM_TIMEOUT_ERROR_PUTSCOM 0x00726612 #define SCOM_PROTOCOL_ERROR_GETSCOM 0x00726613 #define SCOM_PROTOCOL_ERROR_PUTSCOM 0x00726614 #define SCOM_PROTOCOL_ERROR_GETSCOM_BUSY 0x00726615 #define SCOM_PROTOCOL_ERROR_PUTSCOM_BUSY 0x00726616 #define SCOM_PROTOCOL_ERROR_PUTSCOM_RST 0x00726617 #define SCOM_PROTOCOL_ERROR_GETSCOM_RST 0x00726618 #define SCOM_INVALID_ADDRESS 0x00726619 /// The default timeout for getscom()/putscom() /// /// This timeout is enforced by the firmware to guarantee a timeout regardless /// of the hardware setup. /// /// The expectation is that the hardware will be set up to enforce a PCB /// timeout of 8K cycles, or 16.384us @ 500 MHz. A timeout only occurs if /// someone erroneously issues a SCOM for a chiplet that does not exist. If /// this happens, then all other SCOMS waiting for the timed-out SCOM to /// finish will have to wait as well. Aside from the timeout error, the /// hardware arbitration and hard latency calculations guarantee that a SCOM /// from any master will complete in under 1us, regardless of PCB utilization. /// /// Assuming that the PCB timeout is a rare event that will only happen when a /// console user types an illegal address for getscom/putscom, then we should /// be able to use 17us as a hard upper bound for a soft timeout. In practice /// this software timeout should never be observed - if it is, then something /// (either the setup, hardware or firmware) must be broken. #ifndef SCOM_TIMEOUT #define SCOM_TIMEOUT SSX_MICROSECONDS(17) #endif /// The default getscom()/putscom() error limit. /// /// This defines the maximum PCB error return code which will not cause /// getscom()/putscom() to panic. The choice of this error limit is /// application dependent. For lab applications we should never try to SCOM a /// partial-good chiplet, so the limit is set at PCB_ERROR_CHIPLET_OFFLINE. /// For production applications it may be that notification of garded cores is /// late, so production code may need to handle PCB_ERROR_PARTIAL_GOOD as /// well. #ifndef SCOM_ERROR_LIMIT #define SCOM_ERROR_LIMIT PCB_ERROR_CHIPLET_OFFLINE #endif #endif // __OCCHW_SCOM_H__ <|start_filename|>src/occ_405/cmdh/cmdh_tunable_parms.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_tunable_parms.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef CMDH_TUNABLE_PARMS_H #define CMDH_TUNABLE_PARMS_H #include "cmdh_fsp_cmds.h" typedef enum { TUNABLE_PARMS_QUERY = 0x00, TUNABLE_PARMS_WRITE = 0x01, TUNABLE_PARMS_RESTORE = 0x02, } TUNABLE_PARMS_CMD; // Used by OCC to get tunable parms query command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; }tunable_parms_query_cmd_t; #define TUNABLE_PARMS_MAX_PARMS 29 #define TUNABLE_PARMS_QUERY_VERSION 0 #define TUNABLE_PARMS_WRITE_VERSION 0 typedef struct __attribute__ ((packed)) { uint8_t id; uint8_t value[2]; }tunable_parm_write_entry_t; // Used by OCC to get tunable parms write command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; uint8_t sub_cmd; uint8_t version; uint8_t numParms; tunable_parm_write_entry_t data[TUNABLE_PARMS_MAX_PARMS]; }tunable_parms_write_cmd_t; // Used by OCC to get tunable parms query response typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint8_t version; uint8_t numParms; cmdh_tunable_param_table_t data[TUNABLE_PARMS_MAX_PARMS]; }tunable_parms_query_rsp_t; errlHndl_t cmdh_tunable_parms( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_tunable_parms_query( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_tunable_parms_write( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); uint8_t cmdh_tunable_parms_restore( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr); #endif <|start_filename|>src/include/registers/ppm_register_addresses.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/ppm_register_addresses.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPM_REGISTER_ADDRESSES_H__ #define __PPM_REGISTER_ADDRESSES_H__ /// \file ppm_register_addresses.h /// \brief Symbolic addresses for the PPM unit // *** WARNING *** - This file is generated automatically, do not edit. #define PPM_PIB_BASE 0x000F0000 #define PPM_GPMMR 0x000f0100 #define PPM_GPMMR_CLR 0x000f0101 #define PPM_GPMMR_OR 0x000f0102 #define PPM_SPWKUP_OTR 0x000f010a #define PPM_SPWKUP_FSP 0x000f010b #define PPM_SPWKUP_OCC 0x000f010c #define PPM_SPWKUP_HYP 0x000f010d #define PPM_SSHSRC 0x000f0110 #define PPM_SSHFSP 0x000f0111 #define PPM_SSHOCC 0x000f0112 #define PPM_SSHOTR 0x000f0113 #define PPM_SSHHYP 0x000f0114 #define PPM_PFCS 0x000f0118 #define PPM_PFCS_CLR 0x000f0119 #define PPM_PFCS_OR 0x000f011a #define PPM_PFDLY 0x000f011b #define PPM_PFSNS 0x000f011c #define PPM_PFOFF 0x000f011d #define PPM_SCRATCH0 0x000f011e #define PPM_SCRATCH1 0x000f011f #define PPM_CGCR 0x000f0165 #define PPM_CGCR_CLR 0x000f0166 #define PPM_CGCR_OR 0x000f0167 #define PPM_PIG 0x000f0180 #define PPM_IVRMCR 0x000f01b0 #define PPM_IVRMCR_CLR 0x000f01b1 #define PPM_IVRMCR_OR 0x000f01b2 #define PPM_IVRMST 0x000f01b3 #define PPM_IVRMDVR 0x000f01b4 #define PPM_IVRMAVR 0x000f01b5 #define PPM_VDMCR 0x000f01b8 #define PPM_VDMCR_CLR 0x000f01b9 #define PPM_VDMCR_OR 0x000f01ba #endif // __PPM_REGISTER_ADDRESSES_H__ <|start_filename|>src/ssx/trace/ssx_trace_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/trace/ssx_trace_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_trace_core.c /// \brief SSX Trace core data and code. /// /// This file includes the minimal code/data required to do minimal tracing. /// This includes the periodic timer initialization and the ssx_trace_tiny /// function. The ssx_trace_tiny function is called by the SSX_TRACE() macro /// when there is one or less parameters (not including the format string) /// and the parameter size is 16 bits or smaller. /// #include "ssx.h" #include "ssx_trace.h" void ssx_trace_timer_callback(void* arg); #if (SSX_TRACE_SUPPORT && SSX_TIMER_SUPPORT) //Static initialization of the trace timer SsxTimer g_ssx_trace_timer = { .deque = SSX_DEQUE_ELEMENT_INIT(), .timeout = 0, .callback = ssx_trace_timer_callback, .arg = 0, .options = SSX_TIMER_CALLBACK_PREEMPTIBLE, }; //Static initialization of the ssx trace buffer SsxTraceBuffer g_ssx_trace_buf = { .version = SSX_TRACE_VERSION, .image_str = PPC_IMG_STRING, .hash_prefix = SSX_TRACE_HASH_PREFIX, .partial_trace_hash = trace_ppe_hash("PARTIAL TRACE ENTRY. HASH_ID = %d", SSX_TRACE_HASH_PREFIX), .size = SSX_TRACE_SZ, .max_time_change = SSX_TRACE_MTBT, .hz = 500000000, //default value. Actual value is set in ssx_init.c .time_adj64 = 0, .state.word64 = 0, .cb = {0} }; //Needed for buffer extraction in simics for now SsxTraceBuffer* g_ssx_trace_buf_ptr = &g_ssx_trace_buf; // Creates an 8 byte entry in the trace buffer that includes a timestamp, // a format string hash value and a 16 bit parameter. // // i_parm has the hash value combined with the 16 bit parameter void ssx_trace_tiny(uint32_t i_parm) { SsxTraceTiny footer; SsxTraceState state; uint64_t* ptr64; uint64_t tb64; SsxMachineContext ctx; //fill in the footer data footer.parms.word32 = i_parm; tb64 = ssx_ext_timebase_get(); state.tbu32 = tb64 >> 32; footer.time_format.word32 = tb64 & 0x00000000ffffffffull; footer.time_format.format = SSX_TRACE_FORMAT_TINY; //The following operations must be done atomically ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); //load the current byte count and calculate the address for this //entry in the cb ptr64 = (uint64_t*)&g_ssx_trace_buf.cb[g_ssx_trace_buf.state.offset & SSX_TRACE_CB_MASK]; //calculate the offset for the next entry in the cb state.offset = g_ssx_trace_buf.state.offset + sizeof(SsxTraceTiny); //update the cb state (tbu and offset) g_ssx_trace_buf.state.word64 = state.word64; //write the data to the circular buffer including the //timesamp, string hash, and 16bit parameter *ptr64 = footer.word64; //exit the critical section ssx_critical_section_exit(&ctx); } // This function is called periodically in order to ensure that the max ticks // between trace entries is no more than what will fit inside a 32bit value. void ssx_trace_timer_callback(void* arg) { // guarantee at least one trace before the lower 32bit timebase flips SSX_TRACE("PERIODIC TIMESTAMPING TRACE"); // restart the timer ssx_timer_schedule(&g_ssx_trace_timer, SSX_TRACE_TIMER_PERIOD, 0); } // Use this function to synchronize the timebase between multiple Processors. // proc A can send proc B it's current timebase and then proc B can set that // as the current timebase for tracing purposes. It can also be used // to set the current time to 0. This function changes the timebase for // all entries that are currently in the trace buffer. Setting the current // timebase to 0 will cause previous traces to have very large timestamps. void ssx_trace_set_timebase(SsxTimebase timebase) { g_ssx_trace_buf.time_adj64 = timebase - ssx_ext_timebase_get(); } void ssx_trace_init(uint32_t timebase_frequency_hz, SsxTimebase initial_timebase) { //set the trace timebase HZ (used by parsing tools) g_ssx_trace_buf.hz = timebase_frequency_hz; if(initial_timebase != SSX_TIMEBASE_CONTINUES) { //Set the timebase adjustment. The external timebase //is not adjustable so we use a software adjustment instead. //Typically, this should only be used by the first processor to come //up in order to set the timebase to 0. Other processors //will want to synchronize with the first processor's timebase. ssx_trace_set_timebase(initial_timebase); } // Schedule the timer that puts a timestamp in the trace buffer // periodically. This allows us to use 32bit timestamps. ssx_timer_schedule(&g_ssx_trace_timer, SSX_TRACE_TIMER_PERIOD, 0); } ////Needed for easy cache flush of trace buffer size_t g_ssx_trace_buf_size = sizeof(g_ssx_trace_buf); #endif <|start_filename|>src/lib/ppc405lib/strtox.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/strtox.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __STRTOX_H__ #define __STRTOX_H__ /// \file strtox.h /// \brief Underlying and extended APIs that support strtoX macros /// /// See the Doxygen comments of the file strtox.c for descriptions of the /// facilities provided by this header. #ifndef __ASSEMBLER__ #include <limits.h> // Error codes #define STRTOX_NO_CONVERSION_EMPTY 0x00787901 #define STRTOX_NO_CONVERSION_PARSE 0x00787902 #define STRTOX_INVALID_ARGUMENT 0x00787903 #define STRTOX_INVALID_ARGUMENT_STRTOL 0x00787904 #define STRTOX_UNDERFLOW_STRTOL1 0x00787905 #define STRTOX_UNDERFLOW_STRTOL2 0x00787906 #define STRTOX_UNDERFLOW_STRTOLL1 0x00787907 #define STRTOX_UNDERFLOW_STRTOLL2 0x00787908 #define STRTOX_OVERFLOW_STRTOL1 0x00787909 #define STRTOX_OVERFLOW_STRTOL2 0x0078790a #define STRTOX_OVERFLOW_STRTOLL1 0x0078790b #define STRTOX_OVERFLOW_STRTOLL2 0x0078790c #define STRTOX_OVERFLOW_STRTOUL 0x0078790d #define STRTOX_OVERFLOW_STRTOULL 0x0078790e // Earlier GCC configurations (ppcnf-mcp5-gcc) are not configured to define // these standard constants, which exist in the include tree under various // switches and configuration settings (from <limits.h>). They are defined by // default in later standard cross builds however (GCC 4.5, 4.6). However we // always assume that (long long) is a 64-bit type. It's likely that this is // the only place these constant will be used (as they are defined as the // values for under/overflow of strtoX() conversions), however it may be // necessary in the future to move these #defines somewhere else. #ifndef LLONG_MIN # define LLONG_MIN (0x8000000000000000ll) #endif #ifndef LLONG_MAX # define LLONG_MAX (0x7fffffffffffffffll) #endif #ifndef ULLONG_MAX # define ULLONG_MAX (0xffffffffffffffffull) #endif int _strtol(const char* str, char** endptr, int base, long* value); int _strtoul(const char* str, char** endptr, int base, unsigned long* value); int _strtoll(const char* str, char** endptr, int base, long long* value); int _strtoull(const char* str, char** endptr, int base, unsigned long long* value); // The way the sizeof(long) is discovered by default depends on which version // of gcc/cpp we're using as these macros are predefined by cpp. #if (__SIZEOF_LONG__ == 4) || (__LONG_MAX__ == 2147483647L) /// See documentation for the file strtox.c static inline int strtoi32(const char* str, char** endptr, int base, int32_t* value) { long int value_l; int rc; rc = _strtol(str, endptr, base, &value_l); *value = value_l; return rc; } /// See documentation for the file strtox.c static inline int strtou32(const char* str, char** endptr, int base, uint32_t* value) { unsigned long int value_ul; int rc; rc = _strtoul(str, endptr, base, &value_ul); *value = value_ul; return rc; } #else #error "No port of strtox.h yet for systems with sizeof(long) != 4" #endif // It is assumed that long long is always 64 bits; There is no standard macro // for this size constant /// See documentation for the file strtox.c static inline int strtoi64(const char* str, char** endptr, int base, int64_t* value) { return _strtoll(str, endptr, base, value); } /// See documentation for the file strtox.c static inline int strtou64(const char* str, char** endptr, int base, uint64_t* value) { return _strtoull(str, endptr, base, value); } #endif // __ASSEMBLER__ #endif // __STRTOX_H__ <|start_filename|>src/common/occ_util.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_util.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* This header file is used by both occ_405 and occ_gpe1. */ /* Contains common structures and globals. */ #ifndef _OCC_UTIL_H #define _OCC_UTIL_H #define WORD_HIGH(data) ((uint32_t)(((uint64_t)data)>>32)) #define WORD_LOW(data) ((uint32_t)(((uint64_t)data)&0xFFFFFFFF)) #endif // _OCC_UTIL_H <|start_filename|>src/occ_405/timer/timer_service_codes.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/timer/timer_service_codes.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _TIMER_SERVICE_CODES_H_ #define _TIMER_SERVICE_CODES_H_ //************************************************************************* // Includes //************************************************************************* #include <comp_ids.h> //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* enum occTimerModuleId { INIT_WD_TIMERS = TMER_COMP_ID | 0x00, POKE_WD_TIMERS = TMER_COMP_ID | 0x01, }; //************************************************************************* // Structures //************************************************************************* //************************************************************************* // Globals //************************************************************************* //************************************************************************* // Function Prototypes //************************************************************************* //************************************************************************* // Functions //************************************************************************* #endif /* #ifndef _TIMER_SERVICE_CODES_H_ */ <|start_filename|>src/lib/occlib/ipc_macros.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/occlib/ipc_macros.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __IPC_MACROS_H__ #define __IPC_MACROS_H__ /// \file ipc_macros.h /// \brief Contains macros related to the Interprocessor Communications (IPC) /// API. /// /////////////////////////////////////////////////////////////////////////////// /// Retrieves the IRQ number for the specified OCC processor instance /// #define IPC_GET_IRQ(instance_id) (OCCHW_IRQ_IPI0_HI_PRIORITY + instance_id) /////////////////////////////////////////////////////////////////////////////// /// Marks the start of the IPC function ID table /// #define IPC_FUNCIDS_TABLE_START \ typedef enum \ { /////////////////////////////////////////////////////////////////////////////// /// Marks the end of the IPC function ID table /// #define IPC_FUNCIDS_TABLE_END \ } ipc_func_enum_t; /////////////////////////////////////////////////////////////////////////////// /// Marks the start of the IPC multi-target function IDs within the IPC /// function ID table. /// #define IPC_FUNCIDS_MT_START \ IPC_MT_START = (int)((IPC_TARGET_MASK | IPC_FLAG_MT | IPC_FLAG_VALID | (((uint32_t)((uint8_t)OCCHW_INST_ID_SELF)) << 16)) - 1), /////////////////////////////////////////////////////////////////////////////// /// Marks the end of the IPC multi-target function IDs within the IPC function /// ID table. /// #define IPC_FUNCIDS_MT_END \ IPC_MT_END, #define IPC_CONCAT_INST(name, inst) name ## inst /////////////////////////////////////////////////////////////////////////////// /// Marks the start of the IPC single-target function IDs within the IPC /// ID table. /// /// \param target_id The instance ID of the processor that the following /// function IDs will target. /// /// Each processor has it's own set of single-target function IDs. Messages /// that are initialized with these function ID's can only be sent to the /// processor specified by \a target_id. /// #define IPC_FUNCIDS_ST_START(target_id) \ IPC_CONCAT_INST(IPC_ST_START_, target_id) = \ (int)(((((uint32_t)target_id) << 24) | IPC_FLAG_VALID ) - 1), /////////////////////////////////////////////////////////////////////////////// /// Marks the end of the IPC single-target function IDs for the specified /// target ID, \a target_id. /// #define IPC_FUNCIDS_ST_END(target_id) \ IPC_CONCAT_INST(IPC_ST_END_, target_id), /////////////////////////////////////////////////////////////////////////////// /// Create an IPC function ID. /// /// \param The name of the IPC function ID /// /// This macro should only be used inside the IPC function ID table. Under /// the covers, an enum with a name of \a name is created. /// #define IPC_FUNC_ID(name) \ name, /////////////////////////////////////////////////////////////////////////////// #define IPC_MT_NUM_FUNCIDS \ ((IPC_MT_END - IPC_MT_START) - 1) /////////////////////////////////////////////////////////////////////////////// #define IPC_ST_TARGET_NUM_FUNCIDS(target_id) \ ((IPC_CONCAT_INST(IPC_ST_END_, target_id) - IPC_CONCAT_INST(IPC_ST_START_, target_id)) - 1) /////////////////////////////////////////////////////////////////////////////// #define IPC_ST_NUM_FUNCIDS IPC_ST_TARGET_NUM_FUNCIDS(OCCHW_INST_ID_SELF) /////////////////////////////////////////////////////////////////////////////// /// Macros for statically initializing the IPC function tables #ifdef STATIC_IPC_TABLES #define IPC_MT_FUNC_TABLE_START \ ipc_func_table_entry_t G_ipc_mt_handlers[IPC_MT_MAX_FUNCTIONS] = \ { #define IPC_ST_FUNC_TABLE_START \ ipc_func_table_entry_t G_ipc_st_handlers[IPC_ST_MAX_FUNCTIONS] = \ { #define IPC_HANDLER(func, arg) \ {func, arg}, #define IPC_HANDLER_DEFAULT \ {ipc_default_handler, 0}, #define IPC_MSGQ_HANDLER(msgq_ptr) \ {ipc_msgq_handler, msgq_ptr}, #define IPC_MT_FUNC_TABLE_END \ }; #define IPC_ST_FUNC_TABLE_END \ }; #else #define IPC_MT_FUNC_TABLE_START #define IPC_ST_FUNC_TABLE_START #define IPC_HANDLER(func, arg) #define IPC_HANDLER_DEFAULT #define IPC_MSGQ_HANDLER(msgq_ptr) #define IPC_MT_FUNC_TABLE_END #define IPC_ST_FUNC_TABLE_END #endif /*STATIC_IPC_TABLES*/ /////////////////////////////////////////////////////////////////////////////// /// Convenience macro for defering handling of a command or /// response in a noncritical interrupt context. This was /// specifically added for ipc functions that need to call /// ssx functions on the 405. (ssx functions can not be called /// inside a critical interrupt context). #ifdef __SSX__ #define IPC_DEFER_TO_NONCRITICAL(ipc_msg) \ { \ ssx_deque_push_back(&G_ipc_deferred_queue, &ipc_msg->node); \ ssx_irq_status_set(OCCHW_IRQ_ASYNC_IPI, 1); \ } #else #define IPC_DEFER_TO_NONCRITICAL(ipc_msg) #endif /////////////////////////////////////////////////////////////////////////////// /// Determine if an IPC function ID is a multi-target ID /////////////////////////////////////////////////////////////////////////////// #define IPC_FUNCID_IS_MT(funcid) (IPC_FLAG_MT & (funcid)) /////////////////////////////////////////////////////////////////////////////// /// Set the target ID of a multi-target function ID /// Sets the target to be invalid if it's not a multi-target function id /////////////////////////////////////////////////////////////////////////////// #define IPC_SET_MT_TARGET(funcid, targetid) \ (((funcid) & IPC_FLAG_MT)? \ (((targetid) << IPC_TARGET_SHIFT) | ((funcid) & ~(IPC_TARGET_MASK))): \ (IPC_TARGET_MASK | (funcid))) /////////////////////////////////////////////////////////////////////////////// /// Retrieve the target ID from an IPC function id /////////////////////////////////////////////////////////////////////////////// #define IPC_GET_TARGET_ID(funcid) (((uint32_t)(funcid)) >> IPC_TARGET_SHIFT) #endif /*__IPC_MACROS_H__*/ <|start_filename|>src/occ_405/cmdh/cmdh_tunable_parms.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_tunable_parms.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "cmdh_tunable_parms.h" #include "cmdh_service_codes.h" #include "cmdh_fsp_cmds.h" #include "dcom.h" // Function Specification // // Name: cmdh_tunable_parms_query // // Description: This function returns all supported tuanble parameters from the // Tunable Parameters List that this system type supports. // // End Function Specification uint8_t cmdh_tunable_parms_query( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; uint16_t l_numParms = 0; tunable_parms_query_cmd_t *l_cmd_ptr = (tunable_parms_query_cmd_t*) i_cmd_ptr; tunable_parms_query_rsp_t *l_rsp_ptr = (tunable_parms_query_rsp_t*) o_rsp_ptr; do { // Check version if ( l_cmd_ptr->version != TUNABLE_PARMS_QUERY_VERSION ) { TRAC_ERR("cmdh_tunable_parms_query: Tunable Parms invalid version: %x", l_cmd_ptr->version ); l_rc = ERRL_RC_INVALID_DATA; break; } // Start setting up response :: // Version l_rsp_ptr->version = TUNABLE_PARMS_QUERY_VERSION; // Number of parameters l_numParms = sizeof(G_mst_tunable_parameter_table) / sizeof (cmdh_tunable_param_table_t); l_rsp_ptr->numParms = l_numParms; TRAC_INFO("cmdh_tunable_parms_query: Found %d entries", l_numParms ); // Copy complete global array data into response memcpy( l_rsp_ptr->data, G_mst_tunable_parameter_table, sizeof(G_mst_tunable_parameter_table) ); }while(0); // Setup the response data packet info uint16_t l_size = 2 + sizeof(G_mst_tunable_parameter_table); G_rsp_status = l_rc; o_rsp_ptr->data_length[0] = ((uint8_t *)&l_size)[0]; o_rsp_ptr->data_length[1] = ((uint8_t *)&l_size)[1]; return l_rc; } // Function Specification // // Name: cmdh_tunable_parms_write // // Description: This function is used to set the values for tunable parameters // // End Function Specification uint8_t cmdh_tunable_parms_write( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; tunable_parms_write_cmd_t *l_cmd_ptr = (tunable_parms_write_cmd_t*) i_cmd_ptr; do { // Check version if ( l_cmd_ptr->version != TUNABLE_PARMS_WRITE_VERSION ) { TRAC_ERR("cmdh_tunable_parms_write: Tunable Parms invalid version: %x", l_cmd_ptr->version ); l_rc = ERRL_RC_INVALID_DATA; break; } // Loop through each parameter entry sent uint8_t i = 0; for (i=0; i < l_cmd_ptr->numParms; i++) { // Check if id is valid uint8_t l_id = l_cmd_ptr->data[i].id; if ( (l_id>0) && (l_id<=CMDH_DEFAULT_TUNABLE_PARAM_NUM) ) { // Save off value G_mst_tunable_parameter_table[l_id-1].value = CONVERT_UINT8_ARRAY_UINT16(l_cmd_ptr->data[i].value[0], l_cmd_ptr->data[i].value[1]); G_mst_tunable_parameter_table_ext[l_id-1].adj_value = G_mst_tunable_parameter_table[l_id-1].value*G_mst_tunable_parameter_table_ext[l_id-1].multiplier; TRAC_INFO("New tunable parameter value received: id[%u] value[%u] adj_value[%u]", l_id, G_mst_tunable_parameter_table[l_id-1].value, G_mst_tunable_parameter_table_ext[l_id-1].adj_value); } else { TRAC_INFO("cmdh_tunable_parms_write: Tunable Parms invalid data found id=%x, value=%x", l_id, CONVERT_UINT8_ARRAY_UINT16(l_cmd_ptr->data[i].value[0], l_cmd_ptr->data[i].value[1]) ); l_rc = ERRL_RC_INVALID_DATA; } } }while(0); // Populate the response data packet G_rsp_status = l_rc; // Set global var G_mst_tunable_parameter_overwrite = 1; return l_rc; } // Function Specification // // Name: cmdh_tunable_parms_restore // // Description: This is used to tell OCC to use default value for all supported // tunable parameters defined in the Tunable Parameters list. // // End Function Specification uint8_t cmdh_tunable_parms_restore(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = ERRL_RC_SUCCESS; do { // Loop through global array uint8_t i = 0; for (i=0; i<CMDH_DEFAULT_TUNABLE_PARAM_NUM; i++) { // Update value using default value G_mst_tunable_parameter_table[i].value = G_mst_tunable_parameter_table_ext[i].def_value; G_mst_tunable_parameter_table_ext[i].adj_value = G_mst_tunable_parameter_table_ext[i].def_value*G_mst_tunable_parameter_table_ext[i].multiplier; } }while(0); // Populate the response data header G_rsp_status = l_rc; // Set global var G_mst_tunable_parameter_overwrite = 2; return l_rc; } // Function Specification // // Name: cmdh_tunable_parms // // Description: This function parses the tunable parms commands sent via TMGT. // // End Function Specification errlHndl_t cmdh_tunable_parms ( const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { uint8_t l_rc = 0; uint8_t l_sub_cmd = 0; errlHndl_t l_errl = NULL; do { // Command is only supported on Master OCC if (G_occ_role == OCC_SLAVE) { TRAC_ERR("cmdh_tunable_parms: Tunable Parameters command not supported on Slave OCCs!"); l_rc = ERRL_RC_INVALID_CMD; break; } // Sub-command is always first byte of data l_sub_cmd = i_cmd_ptr->data[0]; TRAC_INFO("cmdh_tunable_parms: Tunable Parms sub-command [%d]", l_sub_cmd ); switch (l_sub_cmd) { case TUNABLE_PARMS_QUERY: l_rc = cmdh_tunable_parms_query(i_cmd_ptr, o_rsp_ptr); break; case TUNABLE_PARMS_WRITE: l_rc = cmdh_tunable_parms_write(i_cmd_ptr, o_rsp_ptr); break; case TUNABLE_PARMS_RESTORE: l_rc = cmdh_tunable_parms_restore(i_cmd_ptr, o_rsp_ptr); break; default: // Should never get here... l_rc = ERRL_RC_INVALID_DATA; break; } } while (0); // All errors in TUNABLE PARMS logged internally if (l_rc) { TRAC_ERR("Tunable Parms command 0x%02x failed with rc = %d", l_sub_cmd, l_rc); // Build Error Response packet cmdh_build_errl_rsp(i_cmd_ptr, o_rsp_ptr, l_rc, &l_errl); } return l_errl; } <|start_filename|>src/ssx/ppc405/ppc405_mmu.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_mmu.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppc405_mmu.c /// \brief Functions related to the PPC405 MMU and its use in SSX. /// /// SSX currently only supports using the PPC405 MMU for instruction and data /// area translation and protection for the global SSX application and kernel. /// No support for demand paging, user vs. kernel protection or /// thread-specific protection is provided. /// /// Instead, the ppc405_mmu_map() API is provided. This API sets up TLB /// entries that provide address translation and protection for a region of /// memory. TLB entries are "locked", that is, once a TLB entry is defined it /// is permanently defined. SSX makes use of the variable page sizes provided /// by the PPC405 to protect regions using the minimum number of TLB entries. /// The minimum page size is 1K, and all regions to be protected must be 1K /// aligned and have sizes that are multiples of 1K. /// /// The ppc405_mmu_map() API optionally returns a Ppc405MmuMap descriptor. /// This descriptor can be later used as the argument to ppc405_mmu_unmap() to /// unmap the region. /// /// The overall SSX configuration option is PPC405_MMU_SUPPORT, with /// suboptions PPC405_IR_SUPPORT and PPC405_DR_SUPPORT. The IR (instruction /// relocate) and DR (data relocate) bits of the MSR must be set to enable /// instruction and data translation/protection respectively. In SSX this is /// handled by the definition of a macro PPC405_RELOCATION_MODE that contains /// the IR and/or DR bits as configured. This macro is OR'ed with the default /// PPC405 SSX_THREAD_MACHINE_CONTEXT_DEFAULT. If the application defines its /// own SSX_THREAD_MACHINE_CONTEXT_DEFAULT then the application will have to /// take care of ensuring that the correct IR/DR settings go into the default. /// /// During interrupts and context switches the relocation mode is /// re-established before any loads or stores take place which provides /// complete protection for interrupt handlers. Note the /// assumption/requirement that all kernel, interrupt and thread code will be /// run under the PPC405_RELOCATION_MODE. #include "ssx.h" #include "ppc405_mmu.h" // A map of free TLB entries. // // It's handy that the PPC405 TLB has 64 entries. Thus we can use a 64-bit // bit mask to represent free entries. The next free entry is quickly found // using cntlz64(). uint64_t __ppc405_tlb_free = 0; /// Reset the PPC405 simple MMU translation/protection scheme /// /// This API invalidates the TLB, clears the zone protection register, and /// otherwise resets the SSX simple translation/protcetion scheme for the /// PPC405. The application must not be running in a translated mode when /// this API is invoked. /// /// \retval 0 Success /// /// \retval -PPC405_MMU_ILLEGAL_CONTEXT The API was called with translation /// enabled. int ppc405_mmu_reset() { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(mfmsr() & (MSR_IR | MSR_DR), PPC405_MMU_ILLEGAL_CONTEXT); } tlbia(); mtspr(SPRN_PID, 0); mtspr(SPRN_ZPR, 0); __ppc405_tlb_free = 0xffffffffffffffffull; isync(); return 0; } /// Define a memory region for MMU protection purposes /// /// \param effective_address The effective (virtual) base address of the /// region. This address must be at least 1KB aligned. /// /// \param real_address The real base address of the region. This address /// must be at least 1KB aligned. /// /// \param size The size of the region in bytes. The size must be a multiple /// of 1KB. A \a size of 0 is legal and creates no entries. /// /// \param tlbhi_flags An OR combination of PPC405_TLBHI_* bits (excluding the /// V-bit). This parameter is unlikely to be non-0 as it contains only the /// little-endian (E) and U0 flags. /// /// - TLBHI_E : Little Endian /// - TLBHI_U0 : U0 mode access /// /// \param tlblo_flags An OR combination of PPC405_TLBLO_* bits. This /// parameter defines WR and EX protection, as well as the 'WIMG' bits. /// /// - TLBLO_EX : Executable code /// - TLBLO_WR : Writable data /// - TLBLO_W : Write-through mode /// - TLBLO_I : Cache-inhibited /// - TLBLO_M : Memory Coherent (Implemented but Ignored) /// - TLBLO_G : Guarded /// /// \param map If non-0, then a Ppc405TlbMap for the region is returned. /// This map can be later used as an argument to ppc405_mmu_unmap() to unmap /// the region. /// /// This API creates fixed TLB entries that provide virtual-to-real address /// translation and protection using a minimum number of TLB entries. The /// number of TLB entries is fixed, so there is no guarantee in general that /// any particular memory map is feasible. In general it is helpful to make /// sure that the effective and real memory ranges have similar alignment, /// otherwise the algorithm will be forced to use small page sizes. /// /// The caller is responsible for cache-correctness of this API. If necessary /// the caller should flush or invalidate memory areas whose protection /// attributes have changed prior to and/or after invoking this API. /// /// Note the the simple translation/protection protocol supported by this SSX /// API does not support the "zone selection" field of the PPC405 TLB /// entry. In SSX the PID is always 0. /// /// If SSX_ERROR_CHECK_API is configured, the API checks each new TLB entry to /// ensure that it does not duplicate an existing entry. The check only /// covers duplicated effective addresses (which are not supported by the /// hardware), not the real addresses. /// /// \retval 0 Success /// /// \retval -PPC405_MMU_INVALID_ARGUMENT Can be signalled by numerous errors /// including improperly aigned memory regions, region size not a multiple of /// 1KB, and illegal flags. /// /// \retval -PPC405_TOO_MANY_TLB_ENTRIES There are not enough TLB entries left /// to completely map the region. The state of the TLB at this point may be /// inconsistent. /// /// \retval -PPC405_DUPLICATE_TLB_ENTRY The requested mapping would duplicate /// all or part of a currently existing TLB entry. Duplicate entries are not /// supported in the 405 core and will cause a TLB miss if an address in a /// duplicated range is accessed. int ppc405_mmu_map(SsxAddress effective_address, SsxAddress real_address, size_t size, int tlbhi_flags, int tlblo_flags, Ppc405MmuMap* map) { size_t log_page_size; size_t page_size = 0; Ppc405Tlbhi tlbhi; Ppc405Tlblo tlblo; Ppc405MmuMap local_map = 0; int tlb_entry; uint64_t bit; SsxMachineContext ctx; if (SSX_ERROR_CHECK_API) { uint64_t allocated; SsxAddress this_effective_address; int entry, overlap; // Check alignment, wrapping and legal flags. SSX_ERROR_IF((effective_address % PPC405_PAGE_SIZE_MIN) || (real_address % PPC405_PAGE_SIZE_MIN) || (size % PPC405_PAGE_SIZE_MIN) || ((effective_address + size - 1) < effective_address) || (tlbhi_flags & ~TLBHI_LEGAL_FLAGS) || (tlblo_flags & ~TLBLO_LEGAL_FLAGS), PPC405_MMU_INVALID_ARGUMENT); // The check for duplicate entries needs to be done iteratively since // we don't use a fixed page size. Since this API will probably only // be called during initialization or from thread contexts, and since // the TLB size is small, this overhead is not considered too onerous. // For complete correctness this check would need to be done in its // entirity in an SSX_CRITICAL critical section. In order to reduce // SSX_CRITICAL interrupt latency we simply check against the TLB // entries that were allocated at the time of the API call. This code // may not protect against multiple threads simultaneously creating // mappings that duplicate each other (a super-bug), but it should // protect against bugs in a single thread's updating of the TLB. if (size != 0) { // See if the requested effective address is already mapped in the // TLB overlap = tlbsx(effective_address, &entry); // Iteratively check the other overlap condition, which is the // case that the effective address of any TLB entry is in the // range of the new request. allocated = ~__ppc405_tlb_free; while (!overlap && (allocated != 0)) { entry = cntlz64(allocated); allocated &= ~((uint64_t)1 << (63 - entry)); tlbhi.value = tlbrehi(entry); if (tlbhi.fields.v) { this_effective_address = tlbhi.fields.epn << PPC405_LOG_PAGE_SIZE_MIN; // See if the first byte of this entry is inside the // requested effective address range. NB: use actual // address ranges (addr + size - 1) to compute overlap to // avoid overflow. overlap |= (this_effective_address >= effective_address) && (this_effective_address <= (effective_address + size - 1)); } } SSX_ERROR_IF(overlap, PPC405_DUPLICATE_TLB_ENTRY); } } // NB: PPC405 page sizes go from 1K to 16M by factors of 4. This is a // 'greedy' algorithm that packs the region into the fewest number of // pages, by using the largest possible (aligned) page size for the // remaining memory area. while (size != 0) { ssx_critical_section_enter(SSX_CRITICAL, &ctx); if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL(__ppc405_tlb_free == 0, PPC405_TOO_MANY_TLB_ENTRIES, &ctx); } tlb_entry = cntlz64(__ppc405_tlb_free); bit = 0x8000000000000000ull >> tlb_entry; __ppc405_tlb_free &= ~bit; local_map |= bit; ssx_critical_section_exit(&ctx); log_page_size = PPC405_LOG_PAGE_SIZE_MAX; do { page_size = POW2_32(log_page_size); if ((size >= page_size) && ((effective_address & (page_size - 1)) == 0) && ((real_address & (page_size - 1)) == 0)) { break; } else { log_page_size -= 2; } } while (1); size -= page_size; // Create and install the TLB entries. The installation is done in a // critical section to avoid any chance of another entity seeing an // inconsistent TLB. tlbhi.value = tlbhi_flags; tlbhi.fields.epn = effective_address >> PPC405_LOG_PAGE_SIZE_MIN; tlbhi.fields.size = (log_page_size - PPC405_LOG_PAGE_SIZE_MIN) / 2; tlbhi.fields.v = 1; tlblo.value = tlblo_flags; tlblo.fields.rpn = real_address >> PPC405_LOG_PAGE_SIZE_MIN; ssx_critical_section_enter(SSX_CRITICAL, &ctx); tlbwelo(tlb_entry, tlblo.value); tlbwehi(tlb_entry, tlbhi.value); isync(); ssx_critical_section_exit(&ctx); effective_address += page_size; real_address += page_size; } if (map) { *map = local_map; } return 0; } /// Un-define a memory region for MMU protection purposes /// /// \param map A pointer to a Ppc405MmuMap object created by ppc405_mmu_map() /// when the memory region was mapped. This map is used to invalidate the TLB /// entries associated with the map, then the map itself is invalidated. /// /// The caller is responsible for cache-correctness of this API. If necessary /// the caller should flush or invalidate memory areas whose protection /// attributes have changed prior to and/or after invoking this API. /// /// \retval 0 Success /// /// \retval -PPC405_MMU_INVALID_ARGUMENT The \a map pointer is null (0). int ppc405_mmu_unmap(Ppc405MmuMap* map) { int tlb_entry; uint64_t bit; SsxMachineContext ctx; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(map == 0, PPC405_MMU_INVALID_ARGUMENT); } while ((tlb_entry = cntlz64(*map)) != 64) { bit = 0x8000000000000000ull >> tlb_entry; *map &= ~bit; tlbwehi(tlb_entry, 0); isync(); ssx_critical_section_enter(SSX_CRITICAL, &ctx); __ppc405_tlb_free |= bit; ssx_critical_section_exit(&ctx); } return 0; } /// Produce a dump of the TLB /// /// \param[in] i_stream The output stream for the dump /// /// \param[in] i_map An optional pointer. If NULL (0) then a full report is /// printed. If non-null then only the entries recorded in the \a i_map are /// printed. #if 0 void ppc405_mmu_report(FILE* i_stream, Ppc405MmuMap* i_map) { size_t i; Ppc405Tlbhi tlbhi; Ppc405Tlblo tlblo; uint32_t size, eff_lo, eff_hi, real_lo, real_hi; const char* size_string[] = { " 1K", " 4K", " 16K", " 64K", "256K", " 1M", " 4M", " 16M" }; Ppc405MmuMap map; fprintf(i_stream, "------------------------------------------------------------------------------\n"); if (i_map == 0) { fprintf(i_stream, "-- PPC405 MMU : Full Report --\n"); } else { fprintf(i_stream, "-- PPC405 MMU : Partial Report --\n"); } fprintf(i_stream, "------------------------------------------------------------------------------\n"); fprintf(i_stream, "-- # Effective Real Size EX/WR WIMG Other --\n"); fprintf(i_stream, "------------------------------------------------------------------------------\n"); if (i_map == 0) { map = __ppc405_tlb_free; } else { map = ~*i_map; } for (i = 0; i < PPC405_TLB_ENTRIES; i++, map <<= 1) { if (map & 0x8000000000000000ull) { continue; } tlbhi.value = tlbrehi(i); tlblo.value = tlbrelo(i); if (tlbhi.fields.v) { size = POW2_32(PPC405_LOG_PAGE_SIZE_MIN) << (2 * tlbhi.fields.size); eff_lo = tlbhi.fields.epn << PPC405_LOG_PAGE_SIZE_MIN; eff_hi = eff_lo + size - 1; real_lo = tlblo.fields.rpn << PPC405_LOG_PAGE_SIZE_MIN; real_hi = real_lo + size - 1; fprintf(i_stream, "-- %2d : %08x:%08x -> %08x:%08x : %s : %s %s : %s%s%s%s : %s%s --\n", i, eff_lo, eff_hi, real_lo, real_hi, size_string[tlbhi.fields.size], tlblo.fields.ex ? "EX" : " ", tlblo.fields.wr ? "WR" : " ", tlblo.fields.w ? "W" : " ", tlblo.fields.i ? "I" : " ", tlblo.fields.m ? "M" : " ", tlblo.fields.g ? "G" : " ", tlbhi.fields.e ? "E" : " ", tlbhi.fields.u0 ? "U0" : " "); } else { fprintf(i_stream, "-- %2d : ENTRY NOT VALID\n", i); } } fprintf(i_stream, "------------------------------------------------------------------------------\n"); } #endif /// Perform a memcpy() without address translation (protection) /// /// It sometimes arises that "read-only" data needs to be initialized at /// run-time. This can be accomplished in general by temporarily disabling /// translation (protection) while the "read-only" data is altered. Another /// option is to use the memcpy_real() API to copy an image of the data from /// writable memory to memory marked read-only by the MMU. /// /// The memcpy_real() function copies \a n bytes from memory area \a src to /// memory area \a dest, with translation disabled. The memory areas should /// not overlap. The memcpy_real() function returns a pointer to dest. /// /// This is a general-purpose API that makes no assumption about the /// cacheability of the data, and can also be used to move code from data /// areas to text areas as the I-cache is always invalidated after the copy. /// The algorithm is as follows: /// /// - Flush the \a dest data from the D-cache /// - Disable translation /// - memcpy() the \a src to the \a dest /// - Flush the \a dest data from the D-cache /// - Invalidate the I-cache /// - Re-enable translation (if it had been previously enabled) /// /// \note Any synchronization access required for \a dest or \a src is the /// responsibility of the caller. void* memcpy_real(void* dest, const void* src, size_t n) { uint32_t msr; dcache_flush(dest, n); msr = mfmsr(); mtmsr(msr & ~(MSR_IR | MSR_DR)); sync(); /* HW239446! */ memcpy(dest, src, n); dcache_flush(dest, n); icache_invalidate_all(); mtmsr(msr); sync(); /* HW239446! */ return dest; } <|start_filename|>src/occ_405/thread/test/threadtest.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/thread/test/threadtest.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "ssx_io.h" #include "simics_stdio.h" #include <errl.h> #include <rand.h> #include <thread.h> #include <threadSch.h> #include <appletId.h> extern void __ssx_boot; IMAGE_HEADER (G_mainAppImageHdr,__ssx_boot,MAIN_APP_ID,OCC_APLT_TEST); // Period in which to run timer_routine #define TIMER_INTERVAL (SsxInterval) SSX_MICROSECONDS(5000) SsxSemaphore prcd_sem; int g_j = 0; int g_k = 0; /*----------------------------------------------------------------------------*/ /* noncrtical/critical stack */ /*----------------------------------------------------------------------------*/ uint8_t noncritical_stack[NONCRITICAL_STACK_SIZE]; uint8_t critical_stack[CRITICAL_STACK_SIZE]; SimicsStdio simics_stdout; SimicsStdio simics_stderr; SsxTimer G_test_timer; extern void timer_routine(void *private); extern void rtloop_ocb_init(void); // Function Specification // // Name: pgp_validation_ssx_main_hook // // Description: Pgp validation test // // End Function Specification void pgp_validation_ssx_main_hook(void) { } // Function Specification // // Name: Cmd_Hndl_thread_routine // // Description: Pseudo-command handler thread test // // End Function Specification void Cmd_Hndl_thread_routine(void *arg) { do { int x=0; for(x=0; x < 1000; x++) { } }while(1); } // Function Specification // // Name: App_thread_routine // // Description: Pseudo-applet thread routine test // // End Function Specification void App_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } }while(1); } // Function Specification // // Name: Thermal_Monitor_thread_routine // // Description: Pseudo-thermal monitoring thread routine test // // End Function Specification void Thermal_Monitor_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } }while(1); } // Function Specification // // Name: Hlth_Monitor_thread_routine // // Description: Pseudo-health monitoring thread test // // End Function Specification void Hlth_Monitor_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } }while(1); } // Function Specification // // Name: FFDC_thread_routine // // Description: Pseudo-ffdc thread routine test // // End Function Specification void FFDC_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } }while(1); } // Function Specification // // Name: main_thread_routine // // Description: This thread currently just looks as the lowest priority thread, // handling the lowest priority tasks. // // End Function Specification void main_thread_routine(void *private) { // Start the critical 250uS timer ssx_timer_schedule(&timer, 1, TIMER_INTERVAL); while(1) { // Only trace the first XX times that this function loops if(g_k < 3) { g_k++; // TRACE: Main Thread } // Sleep for 1000 before we run the loop again ssx_sleep_absolute(1000); } } // Function Specification // // Name: timer_routine // // Description: timer routine test // // End Function Specification void timer_routine (void *arg) { } // Function Specification // // Name: dump_thread_info // // Description: Dumps information related to all scheduled threads // // End Function Specification void dump_thread_info(void *arg) { printf("dumping thread info--------------------------\n"); int l_rc = 0; SsxThreadState l_state = 0; SsxThreadPriority l_pri = 0; int l_runnable=0; int x=0; for(x=0; x < THREADS_TO_SCHEDULE; x++) { l_rc = ssx_thread_info_get(G_scheduledThreads[x], &l_state, &l_pri, &l_runnable); printf("Thread %p: State %x priority %x runnable %x rc %x Global index %x\n",G_scheduledThreads[x], l_state, l_pri, l_runnable, l_rc, G_threadSchedulerIndex); } } // Function Specification // // Name: main // // Description: Initializes the trace buffer, along with creating threads and timers // for execution. Note that once main runs with ssx_start_threads, we // never return as the SSX kernel takes over. // // End Function Specification int main(int argc, char **argv) { // Locals errlHndl_t l_errl = INVALID_ERR_HNDL; // Initialize Trace Buffers immediately, so they can be used // from this point on. // Initialize stdout so we can do printf from within simics env simics_stdout_create(&simics_stdout); simics_stderr_create(&simics_stderr); stdout = (FILE *)(&simics_stdout); stderr = (FILE *)(&simics_stderr); // Initialize SSX Stacks (note that this also reinitializes the time base to 0) ssx_initialize((SsxAddress)noncritical_stack, NONCRITICAL_STACK_SIZE, (SsxAddress)critical_stack, CRITICAL_STACK_SIZE, 0); // Create Global Semaphores ssx_semaphore_create(&prcd_sem, 0, 13); ssx_timer_create(&timer, timer_routine, 0); // Create thread with already mapped priority // Create Threads ssx_thread_create(&main_thread, main_thread_routine, (void *)0, (SsxAddress)main_thread_stack, THREAD_STACK_SIZE, 0); // Make Threads runnable ssx_thread_resume(&main_thread); //Initialize the thread scheduler initThreadScheduler(); // Kick off timer ssx_timer_create(&G_test_timer, dump_thread_info, 0); ssx_timer_schedule(&G_test_timer, 1, 500000000); // Enter SSX Kernel ssx_start_threads(); return 0; } <|start_filename|>src/occ_gpe1/gpe1_24x7.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/gpe1_24x7.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" #include "pk_app_cfg.h" #include "ppe42_scom.h" #include "ipc_api.h" #include "ipc_async_cmd.h" #include "gpe_util.h" #include "gpe_24x7_structs.h" #include "gpe_pba_cntl.h" #include "gpe1_24x7.h" #include "string.h" /* * Function Specifications: * * Name: gpe_24x7 * Description: 24x7 code on the GPE. Owned by the performance team * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void gpe_24x7(ipc_msg_t* cmd, void* arg) { // Note: arg was set to 0 in ipc func table (ipc_func_tables.c), so don't use it. // the ipc arguments passed through the ipc_msg_t structure, has a pointer // to the gpe_24x7_args_t struct. int rc = 0; int iter = 0; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; gpe_24x7_args_t *args = (gpe_24x7_args_t*)async_cmd->cmd_data; uint8_t ticks = args->numTicksPassed; // number of 500us ticks since last call static uint8_t L_current_state = 1; // 24x7 collection "state" to execute when called static uint8_t L_DELAY_1 = 0; static uint8_t L_DELAY_2 = 0; static uint8_t L_DELAY_3 = 0; static uint8_t L_DELAY_4 = 0; static uint8_t L_DELAY_5 = 0; static uint8_t L_DELAY_6 = 0; static uint8_t L_DELAY_7 = 0; static uint8_t L_CUR_DELAY = 0; static uint64_t L_cur_speed = 0; static uint64_t L_prev_status = 0; static bool L_configure = false; static bool L_DONT_RUN = false; static bool L_INIT = false; static bool L_PART_INIT = false; // //control block memory area. // static volatile uint64_t* L_status = (uint64_t*) (CNTL_STATUS_OFFSET | PBA_ENABLE); static volatile uint64_t* L_cmd = (uint64_t*) (CNTL_CMD_OFFSET | PBA_ENABLE); static volatile uint64_t* L_speed = (uint64_t*) (CNTL_SPEED_OFFSET | PBA_ENABLE); static volatile uint64_t* L_uav = (uint64_t*) (CNTL_UAV_OFFSET | PBA_ENABLE); static volatile uint64_t* L_mode = (uint64_t*) (CNTL_MODE_OFFSET | PBA_ENABLE); static volatile uint64_t* L_mode_state = (uint64_t*) (CNTL_MODE_STATE_OFFSET | PBA_ENABLE); static volatile uint64_t* L_version = (uint64_t*) (DBG_VER_OFFSET | PBA_ENABLE); static volatile uint64_t* L_tics_exceded = (uint64_t*) (DBG_TICS_OFFSET | PBA_ENABLE); static volatile uint64_t* L_marker = (uint64_t*) (DBG_MARK | PBA_ENABLE); static volatile uint64_t* L_DBG_ITER = (uint64_t*) (DBG_ITER | PBA_ENABLE); volatile uint8_t* L_DBG_STATE = (uint8_t*) (DBG_STATE | PBA_ENABLE); //uint64_t temp; args->error.error = 0; // default success args->error.ffdc = 0; //Populate version details //------------------------ /** * 24x7 Version * [00:03] - Major revision * [04:11] - Minor revision * [12:15] - Bug fix release number * [16:23] - Day * [24:31] - Month * [32:47] - Year * [48:63] - Reserved **/ uint64_t VERSION = 0; static uint64_t ver_major = 0x2; static uint64_t ver_minor = 0x0; static uint64_t ver_bugfix = 0x0; static uint64_t ver_day = 0x31; // Day: 27 static uint64_t ver_month = 0x05; // Month: 04 static uint64_t ver_year = 0x2018; // Year:2018 VERSION |= (ver_major << 60); VERSION |= (ver_minor << 52); VERSION |= (ver_bugfix << 48); VERSION |= (ver_day << 40); VERSION |= (ver_month << 32); VERSION |= (ver_year << 16); //PBA Slave setup. Do this each time you enter this loop to be safe. gpe_pba_reset(); if(ticks == 0) // First time 24x7 called since OCC started? { //1. read and update the control block //------------------------------------ PK_TRACE("gpe_24x7: First call since OCC started. ticks = 0"); //set configure to true L_configure = true; L_INIT = true; //initialize posting area initialize_postings(); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); //set code version *L_version = VERSION; //set status as initializing *L_status = CNTL_STATUS_INIT; //initialize cmd to NOP *L_cmd = CNTL_CMD_NOP; //UAV - currently filled with system dependent static value. Need to be replaced with value from reading HDAT. if (*L_uav == 0) *L_uav = CNTL_UAV_TEMP; //get speed of collection and set delays accordingly. L_cur_speed = *L_speed; set_speed(&L_cur_speed,&L_CUR_DELAY,L_status); //check if mode is set to monitor //support for debug modes (flexible IMA) not present currently. if((*L_mode != CNTL_MODE_MONITOR)&&(*L_mode != CNTL_MODE_DEBUG1)) *L_status = CNTL_STATUS_ERR2; //set Dont run if the speed and mode info is not set to legal values. if( (*L_status == CNTL_STATUS_ERR1)||(*L_status == CNTL_STATUS_ERR2) ) L_DONT_RUN = true; } else if(ticks > 1) // longer than 500us since last call? { // It has been ticks*500us since last call PK_TRACE("gpe_24x7: It has been 0x%02X ticks since last call", ticks); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_tics_exceded ++; } //2. get any new command //---------------------- if (*L_cmd != CNTL_CMD_NOP) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); switch(*L_cmd) { case CNTL_CMD_PAUSE: L_DONT_RUN = true; *L_status = CNTL_STATUS_PAUSE; *L_cmd = CNTL_CMD_NOP; PK_TRACE("gpe_24x7: in CNTL_CMD_PAUSE"); for(iter = 0;iter < 24;iter++) { G_PHB_pmulets[iter] = 0; G_MBA_pmulets[iter] = 0; } break; case CNTL_CMD_RESUME: L_DONT_RUN = false; *L_status = CNTL_STATUS_RUN; *L_cmd = CNTL_CMD_NOP; PK_TRACE("gpe_24x7: in CNTL_CMD_RESUME"); break; case CNTL_CMD_CLEAR: L_DONT_RUN = false; L_INIT = true; PK_TRACE("gpe_24x7: in CNTL_CMD_CLEAR, L_INIT set to true"); *L_cmd = CNTL_CMD_NOP; break; } } //3.get any new speed setting //--------------------------- if (*L_speed != L_cur_speed) { L_INIT = true; PK_TRACE("gpe_24x7: speed change, L_INIT set to true"); set_speed(&L_cur_speed,&L_CUR_DELAY,L_status); } //4.check for any system config changes via uav //--------------------------------------------- if (*L_uav != G_CUR_UAV) { L_INIT = true; L_PART_INIT = true; } //5.check for mode change //----------------------- if (*L_mode != G_CUR_MODE) { L_INIT = true; L_prev_status = *L_status; L_PART_INIT = true; L_DONT_RUN = false; PK_TRACE("gpe_24x7: mode change, L_INIT set to true"); } //if(*L_mode != CNTL_MODE_MONITOR)//&&(*L_mode != CNTL_MODE_DEBUG1)) if((*L_mode != CNTL_MODE_MONITOR)&&(*L_mode != CNTL_MODE_DEBUG1)) *L_status = CNTL_STATUS_ERR2; //set Dont run if the speed and mode info is not set to legal values. if( (*L_status == CNTL_STATUS_ERR1)||(*L_status == CNTL_STATUS_ERR2) ) L_DONT_RUN = true; //initialize postings if required from new cmd or change of speed or UAV change. if (L_INIT) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_status = CNTL_STATUS_INIT; //need not initialize postings for UAV change. if (L_PART_INIT) L_PART_INIT = false; else initialize_postings(); L_configure = true; L_cur_speed = *L_speed; G_CUR_UAV = *L_uav; G_CUR_MODE = *L_mode; //SW399904 patch until HWP output for UAV is debugged. //G_CUR_UAV = CNTL_UAV_TEMP; *L_marker = MARKER1; set_speed(&L_cur_speed,&L_CUR_DELAY,L_status); //set the state to 1 if reconfig is required. config scoms are split across multiple states starting from 1. L_current_state = 1; PK_TRACE("gpe_24x7: in L_INIT L_current_state set to 1"); L_INIT = false; } //5. Based on the current entry state number, appropriate group posting is done. //G1,G2(states 1,3,5,7), //G3(states 2,4,6,8) G4(state 2), G5(state 4), G6(state 6), G7(state 8). //during first time entry or a re-init is trigered, the current run is used for pmu configuration. //configuration will continue across multiple re-entry slots till all configuration scoms are done. //scoms are generally kept at 16 per slot, to prevent from exceeding 50us runtime buget. if (L_DONT_RUN == false) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); //PK_TRACE("gpe_24x7: begin state = %d",(int)L_current_state); *L_DBG_STATE = L_current_state; switch(L_current_state) { case 1: if(L_configure) { configure_pmu(L_current_state, L_cur_speed); } else { if(L_DELAY_1 == 0) { post_pmu_events(G1); L_DELAY_1 = L_CUR_DELAY; } else L_DELAY_1--; if(L_DELAY_2 == 0) { post_pmu_events(G2); L_DELAY_2 = L_CUR_DELAY; } else L_DELAY_2--; } break; case 2: if(L_configure) { configure_pmu(L_current_state, L_cur_speed); } else { if(L_DELAY_3 == 0) { post_pmu_events(G3); L_DELAY_3 = L_CUR_DELAY; } else L_DELAY_3--; if(L_DELAY_4 == 0) { post_pmu_events(G4); //for groups 4,5,6,7 8ms is the fastest possible collection speed. L_DELAY_4 = L_CUR_DELAY/8; } else L_DELAY_4--; } break; case 3: if(L_configure) { configure_pmu(L_current_state, L_cur_speed); } else { if(L_DELAY_1 == 0) { post_pmu_events(G1); L_DELAY_1 = L_CUR_DELAY; } else L_DELAY_1--; if(L_DELAY_2 == 0) { post_pmu_events(G2); L_DELAY_2 = L_CUR_DELAY; } else L_DELAY_2--; } break; case 4: if(L_configure) { configure_pmu(L_current_state, L_cur_speed); L_configure = false; *L_status = CNTL_STATUS_RUN; //*L_status = L_prev_status; if(L_prev_status == CNTL_STATUS_PAUSE) { L_DONT_RUN = true; *L_status = L_prev_status; } *L_mode_state = G_CUR_MODE; //*L_mode = 0; L_prev_status = 0; } else { if(L_DELAY_3 == 0) { post_pmu_events(G3); L_DELAY_3 = L_CUR_DELAY; } else L_DELAY_3--; if(L_DELAY_5 == 0) { post_pmu_events(G5); //for groups 4,5,6,7 8ms is the fastest possible collection speed. L_DELAY_5 = L_CUR_DELAY/8; } else L_DELAY_5--; } break; case 5: if(L_DELAY_1 == 0) { post_pmu_events(G1); L_DELAY_1 = L_CUR_DELAY; } else L_DELAY_1--; if(L_DELAY_2 == 0) { post_pmu_events(G2); L_DELAY_2 = L_CUR_DELAY; } else L_DELAY_2--; break; case 6: if(L_DELAY_3 == 0) { post_pmu_events(G3); L_DELAY_3 = L_CUR_DELAY; } else L_DELAY_3--; if(L_DELAY_6 == 0) { post_pmu_events(G6); //for groups 4,5,6,7 8ms is the fastest possible collection speed. L_DELAY_6 = L_CUR_DELAY/8; } else L_DELAY_6--; break; case 7: if(L_DELAY_1 == 0) { post_pmu_events(G1); L_DELAY_1 = L_CUR_DELAY; } else L_DELAY_1--; if(L_DELAY_2 == 0) { post_pmu_events(G2); L_DELAY_2 = L_CUR_DELAY; } else L_DELAY_2--; break; case 8: if(L_DELAY_3 == 0) { post_pmu_events(G3); L_DELAY_3 = L_CUR_DELAY; } else L_DELAY_3--; if(L_DELAY_7 == 0) { post_pmu_events(G7); //for groups 4,5,6,7 8ms is the fastest possible collection speed. L_DELAY_7 = L_CUR_DELAY/8; } else L_DELAY_7--; break; default: PK_TRACE("gpe_24x7: Invalid collection state: 0x%02X", L_current_state); break; } } // Setup state to run on next call if(L_current_state == MAX_24x7_STATES) L_current_state = 1; else L_current_state++; //PK_TRACE("gpe_24x7: end state = %d",(int)L_current_state); // send back a response, IPC success even if ffdc/rc are non zeros rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); //PK_TRACE("gpe_24x7: SRN exiting thread with rc =%d", rc); if(rc) { *L_DBG_ITER = MARKER2; PK_TRACE("gpe_24x7: Failed to send response back. Halting GPE1"); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } } /** * Function: configure_pmu **/ void configure_pmu(uint8_t state, uint64_t speed) {//write the configuration SCOMs for all pmus. uint64_t temp; int i,start = (state - 1) * 16,end = state * 16; static volatile uint64_t* L_conf_last = (uint64_t*) (DBG_CONF_OFFSET | PBA_ENABLE); static volatile uint64_t* L_DBG_0 = (uint64_t*) (DBG_0 | PBA_ENABLE); static volatile uint64_t* L_DBG_1 = (uint64_t*) (DBG_1 | PBA_ENABLE); static volatile uint64_t* L_DBG_2 = (uint64_t*) (DBG_2 | PBA_ENABLE); static volatile uint64_t* L_DBG_3 = (uint64_t*) (DBG_3 | PBA_ENABLE); static volatile uint64_t* L_DBG_UAV = (uint64_t*) (DBG_UAV | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UAV = G_CUR_UAV; *L_DBG_3 = MARKER3; *L_DBG_0 = (!(G_CUR_UAV & MASK_XLNK0)); *L_DBG_1 = (!(G_CUR_UAV & MASK_XLNK1)); *L_DBG_2 = (!(G_CUR_UAV & MASK_XLNK2)); if(end > TOTAL_CONFIGS) end = TOTAL_CONFIGS; for(i = start; i < end; i++) { //check the availability of unit before writing the configurations to the config scoms. //use the unit wise masks to acertain availability of a unit. //in Nimbus, MCA is present instead of MBAs and they are updated at the location for MBAs. //MBAs need to be checked to see which MC poerts are configured. if( (i==4) && !(G_CUR_UAV & MASK_MBA4) ) continue; else if( (i==5) && !(G_CUR_UAV & MASK_MBA5) ) continue; else if( (i==6) && !(G_CUR_UAV & MASK_MBA6) ) continue; else if( (i==7) && !(G_CUR_UAV & MASK_MBA7) ) continue; else if( ((i==8)||(i==9)||(i==10)||(i==11)) && (!(G_CUR_UAV & MASK_MBA4)) && (!(G_CUR_UAV & MASK_MBA5)) ) continue; else if( ((i==12)||(i==13)||(i==14)||(i==15)) && (!(G_CUR_UAV & MASK_MBA6)) && (!(G_CUR_UAV & MASK_MBA7)) ) continue; else if( (i==16) && !(G_CUR_UAV & MASK_MBA0) ) continue; else if( (i==17) && !(G_CUR_UAV & MASK_MBA1) ) continue; else if( (i==18) && !(G_CUR_UAV & MASK_MBA2) ) continue; else if( (i==19) && !(G_CUR_UAV & MASK_MBA3) ) continue; else if( ((i==20)||(i==21)||(i==22)||(i==23)) && (!(G_CUR_UAV & MASK_MBA0)) && (!(G_CUR_UAV & MASK_MBA1)) ) continue; else if( ((i==24)||(i==25)||(i==26)||(i==27)) && (!(G_CUR_UAV & MASK_MBA2)) && (!(G_CUR_UAV & MASK_MBA3)) ) continue; else if( (i==28) && ((!(G_CUR_UAV & MASK_XLNK0)) && (!(G_CUR_UAV & MASK_XLNK1)) && (!(G_CUR_UAV & MASK_XLNK2))) ) continue; else if( ((i==29)||(i==30)||(i==31)||(i==32)) && !(G_CUR_UAV & MASK_NX) ) continue; else if( (i==33) && !(G_CUR_UAV & MASK_NVLNK0) ) continue; else if( (i==34) && !(G_CUR_UAV & MASK_NVLNK1) ) continue; else if( (i==35) && !(G_CUR_UAV & MASK_NVLNK2) ) continue; else if( (i==36) && !(G_CUR_UAV & MASK_NVLNK3) ) continue; else if( (i==37) && !(G_CUR_UAV & MASK_NVLNK4) ) continue; else if( (i==38) && !(G_CUR_UAV & MASK_NVLNK5) ) continue; else if( ((i==39)||(i==40)) && (!(G_CUR_UAV & MASK_NVLNK5)) && (!(G_CUR_UAV & MASK_NVLNK4)) && (!(G_CUR_UAV & MASK_NVLNK3)) && (!(G_CUR_UAV & MASK_NVLNK2)) && (!(G_CUR_UAV & MASK_NVLNK1)) && (!(G_CUR_UAV & MASK_NVLNK0)) ) continue; else if( (i==41) && !(G_CUR_UAV & MASK_PHB0) ) continue; else if( (i==42) && !(G_CUR_UAV & MASK_PHB1) ) continue; else if( (i==43) && !(G_CUR_UAV & MASK_PHB2) ) continue; else if( (i==44) && !(G_CUR_UAV & MASK_PHB3) ) continue; else if( (i==45) && !(G_CUR_UAV & MASK_PHB4) ) continue; else if( (i==46) && !(G_CUR_UAV & MASK_PHB5) ) continue; else if( (i==47) && (!(G_CUR_UAV & MASK_NVLNK1)) && (!(G_CUR_UAV & MASK_NVLNK0)) ) continue; else if( (i==48) && (!(G_CUR_UAV & MASK_NVLNK3)) && (!(G_CUR_UAV & MASK_NVLNK2)) ) continue; else if( (i==49) && (!(G_CUR_UAV & MASK_NVLNK5)) && (!(G_CUR_UAV & MASK_NVLNK4)) ) continue; else if( ((i==50)||(i==51)||(i==52)||(i==53)) && !(G_CUR_UAV & MASK_CAPP0) ) continue; else if( ((i==54)||(i==55)||(i==56)||(i==57)) && !(G_CUR_UAV & MASK_CAPP1) ) continue; else { //Two sets of configurations. //1.for speeds till 8ms- 8 bit prescale if((speed == CNTL_SPEED_1MS)||(speed == CNTL_SPEED_2MS)||(speed == CNTL_SPEED_4MS)||(speed == CNTL_SPEED_8MS)) { // Fix for defect SW430218 - 24x7 to touch only XTS Config2 bits [0:47] if ( G_PMU_CONFIGS_8[i][0] == 0x5011645 ) { getscom_abs(G_PMU_CONFIGS_8[i][0], &temp); temp &= (0xFFFF); temp |= G_PMU_CONFIGS_8[i][1]; putscom_abs(G_PMU_CONFIGS_8[i][0], temp); } else { putscom_abs(G_PMU_CONFIGS_8[i][0], G_PMU_CONFIGS_8[i][1]); } *L_conf_last = (uint64_t)i; } //2.for all speeds above 8 ms till 2s - 16bit prescale else { // Fix for defect SW430218 - 24x7 to touch only XTS Config2 bits [0:47] if ( G_PMU_CONFIGS_16[i][0] == 0x5011645 ) { getscom_abs(G_PMU_CONFIGS_16[i][0], &temp); temp &= (0xFFFF); temp |= G_PMU_CONFIGS_16[i][1]; putscom_abs(G_PMU_CONFIGS_16[i][0], temp); } else { putscom_abs(G_PMU_CONFIGS_16[i][0], G_PMU_CONFIGS_16[i][1]); } *L_conf_last = (uint64_t)i; } } } } /** * function: post_pmu_events **/ void post_pmu_events(int grp) {//read the scom pmulets. split/extract the counters.accumulate to main memory. volatile uint64_t* post_addr; static int L_phb_events =0; static volatile uint64_t* L_DBG_GRP = (uint64_t*) (DBG_GRP_OFFSET | PBA_ENABLE); static volatile uint64_t* L_DBG_UNIT = (uint64_t*) (DBG_UNIT_OFFSET | PBA_ENABLE); static bool L_X_A_LINKS_flag = false; //static volatile uint64_t* L_DBG_4 = (uint64_t*) (DBG_4 | PBA_ENABLE); //static volatile uint64_t* L_DBG_5 = (uint64_t*) (DBG_5 | PBA_ENABLE); //static volatile uint64_t* L_DBG_6 = (uint64_t*) (DBG_6 | PBA_ENABLE); //static volatile uint64_t* L_DBG_7 = (uint64_t*) (DBG_7 | PBA_ENABLE); //static uint64_t L_PHB_pmulets[24]; //static uint64_t L_MBA_pmulets[24]; uint64_t temp; volatile uint64_t temp1; //union to split a pmulet containg 4 counters into its constituents. union u1 { struct event { uint16_t e[4]; } ev; uint64_t pmulet; } u3; union u_mba { struct event_mba { uint32_t e[2]; } ev; uint64_t pmulet; } u3_mba; int i=0,j=0,phb_epoch=0; uint64_t TOD; int iter=0, ev_count=0; post_addr = (uint64_t*) (POSTING_START | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); //FIXME:restricting groups for test on witherspoon //remove once done. //int test_grp = G1; // switch(grp) //switch(test_grp) { case G1://cnpm group - always written if(G_CUR_MODE == CNTL_MODE_MONITOR) post_addr = (uint64_t*) (POST_OFFSET_G1H | PBA_ENABLE); else if(G_CUR_MODE == CNTL_MODE_DEBUG1) post_addr = (uint64_t*) (POST_OFFSET_DBG1H | PBA_ENABLE); *L_DBG_GRP = 1; *L_DBG_UNIT = 1; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; for(i=0; i<8; i++) { getscom_abs(G_PMULETS_1[i], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if(G_CUR_MODE == CNTL_MODE_MONITOR) post_addr = (uint64_t*) (POST_OFFSET_G1T | PBA_ENABLE); else if(G_CUR_MODE == CNTL_MODE_DEBUG1) post_addr = (uint64_t*) (POST_OFFSET_DBG1T | PBA_ENABLE); *post_addr = INC_UPD_COUNT; break; case G2://XLINKS,NX and ALINKS. Read scoms based on availability. if (L_X_A_LINKS_flag) //Here do xlink-[0:2] and nx { L_X_A_LINKS_flag = false; *L_DBG_GRP = 2; post_addr = (uint64_t*) (POST_OFFSET_G2H | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; if ((G_CUR_UAV & MASK_XLNK0) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G2_1 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2[0], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2[1], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_XLNK1) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 2; post_addr = (uint64_t*) (POST_OFFSET_G2_2 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2[2], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2[3], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_XLNK2) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 3; post_addr = (uint64_t*) (POST_OFFSET_G2_3 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2[4], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2[5], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_NX) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 4; post_addr = (uint64_t*) (POST_OFFSET_G2_4 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2[6], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2[7], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } post_addr = (uint64_t*) (POST_OFFSET_G2T | PBA_ENABLE); *post_addr = INC_UPD_COUNT; } else //Here do alink [0:3] { L_X_A_LINKS_flag = true; if ((G_CUR_UAV & MASK_ALNK0) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G2_A0 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2_2a[0], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2_2a[1], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_ALNK1) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G2_A1 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2_2b[0], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2_2b[1], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_ALNK2) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G2_A2 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2_2c[0], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2_2c[1], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_ALNK3) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G2_A3 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_2_2d[0], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_2_2d[1], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } } break; case G3://NVLINKS -NTL,ATS,XTS *L_DBG_GRP = 3; post_addr = (uint64_t*) (POST_OFFSET_G3H | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; if ((G_CUR_UAV & MASK_NVLNK0) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; getscom_abs(G_PMULETS_3[0], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_1 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_NVLNK1) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 2; getscom_abs(G_PMULETS_3[1], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_2 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_NVLNK2) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 3; getscom_abs(G_PMULETS_3[2], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_3 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_NVLNK3) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 4; getscom_abs(G_PMULETS_3[3], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_4 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_NVLNK4) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 5; getscom_abs(G_PMULETS_3[4], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_5 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_NVLNK5) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 6; getscom_abs(G_PMULETS_3[5], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_6 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ( ((G_CUR_UAV & MASK_NVLNK0) > 0) || ((G_CUR_UAV & MASK_NVLNK1) > 0) || ((G_CUR_UAV & MASK_NVLNK2) > 0)|| ((G_CUR_UAV & MASK_NVLNK3) > 0) || ((G_CUR_UAV & MASK_NVLNK4) > 0) || ((G_CUR_UAV & MASK_NVLNK5) > 0) ) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 7; getscom_abs(G_PMULETS_3[6], &u3.pmulet); post_addr = (uint64_t*) (POST_OFFSET_G3_7 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } *L_DBG_UNIT = 8; getscom_abs(G_PMULETS_3[7], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } post_addr = (uint64_t*) (POST_OFFSET_G3T | PBA_ENABLE); *post_addr = INC_UPD_COUNT; break; case G4: //PHB events are present on separate 48-bit SCOM registers. They dont clear on read. //But wrap around. After each read, the value is subtracted from the prvious value to //get current increment which is then atomically added to the main memory. //Totally 24 scoms of the PHB are split across 3 epochs for the same group. // Only 8 scoms are read and updated to memory in an epoch to abide the 25us run time restriction. *L_DBG_GRP = 4; post_addr = (uint64_t*) (POST_OFFSET_G4H | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; if(L_phb_events > 23) L_phb_events = 0; phb_epoch = L_phb_events/8; switch(phb_epoch) { case 0: if ((G_CUR_UAV & MASK_PHB0) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); post_addr = (uint64_t*) (POST_OFFSET_G4a | PBA_ENABLE); for(i=0; i<4; i++) { getscom_abs(G_PMULETS_4a[i], &temp); temp >>=16; temp1 = temp; temp = get_phb_event(temp, G_PHB_pmulets[L_phb_events] ); if(G_PHB_pmulets[L_phb_events] != 0) *post_addr = temp; G_PHB_pmulets[L_phb_events] = temp1; post_addr++; L_phb_events++; } } else L_phb_events += 4; if ((G_CUR_UAV & MASK_PHB1) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 2; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); post_addr = (uint64_t*) (POST_OFFSET_G4b | PBA_ENABLE); for(i=0; i<4; i++) { getscom_abs(G_PMULETS_4b[i], &temp); temp >>=16; temp1 = temp; temp = get_phb_event(temp, G_PHB_pmulets[L_phb_events] ); if(G_PHB_pmulets[L_phb_events] != 0) *post_addr = temp; G_PHB_pmulets[L_phb_events] = temp1; post_addr++; L_phb_events++; } } else L_phb_events += 4; break; case 1: if ((G_CUR_UAV & MASK_PHB2) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 3; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); post_addr = (uint64_t*) (POST_OFFSET_G4c | PBA_ENABLE); for(i=0; i<4; i++) { getscom_abs(G_PMULETS_4c[i], &temp); temp >>=16; temp1 = temp; temp = get_phb_event(temp, G_PHB_pmulets[L_phb_events] ); if(G_PHB_pmulets[L_phb_events] != 0) *post_addr = temp; G_PHB_pmulets[L_phb_events] = temp1; post_addr++; L_phb_events++; } } else L_phb_events += 4; if ((G_CUR_UAV & MASK_PHB3) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 4; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); post_addr = (uint64_t*) (POST_OFFSET_G4d | PBA_ENABLE); for(i=0; i<4; i++) { getscom_abs(G_PMULETS_4d[i], &temp); temp >>=16; temp1 = temp; temp = get_phb_event(temp, G_PHB_pmulets[L_phb_events] ); if(G_PHB_pmulets[L_phb_events] != 0) *post_addr = temp; G_PHB_pmulets[L_phb_events] = temp1; post_addr++; L_phb_events++; } } else L_phb_events += 4; break; case 2: if ((G_CUR_UAV & MASK_PHB4) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 5; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); post_addr = (uint64_t*) (POST_OFFSET_G4e | PBA_ENABLE); for(i=0; i<4; i++) { getscom_abs(G_PMULETS_4e[i], &temp); temp >>=16; temp1 = temp; temp = get_phb_event(temp, G_PHB_pmulets[L_phb_events] ); if(G_PHB_pmulets[L_phb_events] != 0) *post_addr = temp; G_PHB_pmulets[L_phb_events] = temp1; post_addr++; L_phb_events++; } } else L_phb_events += 4; if ((G_CUR_UAV & MASK_PHB5) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 6; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); post_addr = (uint64_t*) (POST_OFFSET_G4f | PBA_ENABLE); for(i=0; i<4; i++) { getscom_abs(G_PMULETS_4f[i], &temp); temp >>=16; temp1 = temp; temp = get_phb_event(temp, G_PHB_pmulets[L_phb_events] ); if(G_PHB_pmulets[L_phb_events] != 0) *post_addr = temp; G_PHB_pmulets[L_phb_events] = temp1; post_addr++; L_phb_events++; } } else L_phb_events += 4; break; } post_addr = (uint64_t*) (POST_OFFSET_G4T | PBA_ENABLE); *post_addr = INC_UPD_COUNT; break; case G5://MBAs - 8 fixed counters for MBA0-3 that dont clear on read but wraparound on overflow. *L_DBG_GRP = 5; post_addr = (uint64_t*) (POST_OFFSET_G5H | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; if ((G_CUR_UAV & MASK_MBA0) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G5_1 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_5[0], &u3_mba.pmulet); ev_count = 0; for(iter=0;iter<2;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_5[1], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[2]); if(G_MBA_pmulets[2] != 0) *post_addr = temp<<1;//needs scaling by 2; G_MBA_pmulets[2] = temp1; } if ((G_CUR_UAV & MASK_MBA1) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 2; post_addr = (uint64_t*) (POST_OFFSET_G5_2 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_5[2], &u3_mba.pmulet); ev_count = 0; for(iter=3;iter<5;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_5[3], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[5]); if(G_MBA_pmulets[5] != 0) *post_addr = temp<<1;//needs scaling by 2; G_MBA_pmulets[5] = temp1; } if ((G_CUR_UAV & MASK_MBA2) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 3; post_addr = (uint64_t*) (POST_OFFSET_G5_3 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_5[4], &u3_mba.pmulet); ev_count = 0; for(iter=6;iter<8;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_5[5], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[8]); if(G_MBA_pmulets[8] != 0) *post_addr = temp<<1;//needs scaling by 2; G_MBA_pmulets[8] = temp1; } if ((G_CUR_UAV & MASK_MBA3) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 4; post_addr = (uint64_t*) (POST_OFFSET_G5_4 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_5[6], &u3_mba.pmulet); ev_count = 0; for(iter=9;iter<11;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_5[7], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[11]); if(G_MBA_pmulets[11] != 0) *post_addr = temp<<1;//needs scaling by 2; G_MBA_pmulets[11] = temp1; } post_addr = (uint64_t*) (POST_OFFSET_G5T | PBA_ENABLE); *post_addr = INC_UPD_COUNT; break; case G6://8 more fixed scoms for MBA4-7. no clear on read.wraparound. *L_DBG_GRP = 6; post_addr = (uint64_t*) (POST_OFFSET_G6H | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; if ((G_CUR_UAV & MASK_MBA4) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G6_1 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_6[0], &u3_mba.pmulet); ev_count = 0; for(iter=12;iter<14;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_6[1], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[14]); if(G_MBA_pmulets[14] != 0) *post_addr = temp<<1;//needs scaling by 2; G_MBA_pmulets[14] = temp1; } if ((G_CUR_UAV & MASK_MBA5) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 2; post_addr = (uint64_t*) (POST_OFFSET_G6_2 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_6[2], &u3_mba.pmulet); ev_count = 0; for(iter=15;iter<17;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_6[3], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[17]); if(G_MBA_pmulets[17] != 0) *post_addr = temp<<1;//needs scaling by 2 G_MBA_pmulets[17] = temp1; } if ((G_CUR_UAV & MASK_MBA6) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 3; post_addr = (uint64_t*) (POST_OFFSET_G6_3 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_6[4], &u3_mba.pmulet); ev_count = 0; for(iter=18;iter<20;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_6[5], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[20]); if(G_MBA_pmulets[20] != 0) *post_addr = temp<<1;//needs scaling by 2 G_MBA_pmulets[20] = temp1; } if ((G_CUR_UAV & MASK_MBA7) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 4; post_addr = (uint64_t*) (POST_OFFSET_G6_4 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_6[6], &u3_mba.pmulet); ev_count = 0; for(iter=21;iter<23;iter++) { temp = u3_mba.ev.e[ev_count]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[iter]); if(G_MBA_pmulets[iter] != 0) *post_addr = temp; G_MBA_pmulets[iter] = temp1; post_addr++; ev_count++; } //only first 32-bit counter is used to get cycles. getscom_abs(G_PMULETS_6[7], &u3_mba.pmulet); temp = u3_mba.ev.e[0]; temp1 = temp; temp = get_mba_event(temp, G_MBA_pmulets[23]); if(G_MBA_pmulets[23] != 0) *post_addr = temp<<1;//needs scaling by 2 G_MBA_pmulets[23] = temp1; } post_addr = (uint64_t*) (POST_OFFSET_G6T | PBA_ENABLE); *post_addr = INC_UPD_COUNT; break; case G7://3 NVLINK-NPCQ's and 2 CAPP pmulets each with 4 counters.TOD present here. *L_DBG_GRP = 7; post_addr = (uint64_t*) (POST_OFFSET_G6H | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; post_addr++; if ( ((G_CUR_UAV & MASK_NVLNK0) > 0) || ((G_CUR_UAV & MASK_NVLNK1) > 0) ) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 1; post_addr = (uint64_t*) (POST_OFFSET_G7_1 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_7[0], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ( ((G_CUR_UAV & MASK_NVLNK2) > 0) || ((G_CUR_UAV & MASK_NVLNK3) > 0) ) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 2; post_addr = (uint64_t*) (POST_OFFSET_G7_2 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_7[1], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ( ((G_CUR_UAV & MASK_NVLNK4) > 0) || ((G_CUR_UAV & MASK_NVLNK5) > 0) ) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 3; post_addr = (uint64_t*) (POST_OFFSET_G7_3 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_7[2], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_CAPP0) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 4; post_addr = (uint64_t*) (POST_OFFSET_G7_4 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_7[3], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_7[4], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } if ((G_CUR_UAV & MASK_CAPP1) > 0) { putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *L_DBG_UNIT = 5; post_addr = (uint64_t*) (POST_OFFSET_G7_5 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); getscom_abs(G_PMULETS_7[5], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } getscom_abs(G_PMULETS_7[6], &u3.pmulet); for(j=0; j<4; j++) { *post_addr = (uint64_t)u3.ev.e[j]; post_addr++; } } getscom_abs(TOD_VALUE_REG,&TOD); post_addr = (uint64_t*) (POST_OFFSET_G7_6 | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); *post_addr = TOD; post_addr = (uint64_t*) (POST_OFFSET_G7T | PBA_ENABLE); putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_ATOMIC); *post_addr = INC_UPD_COUNT; break; default: PK_TRACE("gpe_24x7: Invalid Group:%d",grp); break; } } /** * function: initialize_postings **/ void initialize_postings() {//initialize posting area. volatile uint64_t* post_addr; int i; putscom_abs(PBASLVCTL3_C0040030, PBASLV_SET_DMA); post_addr = (uint64_t*) (POSTING_START | PBA_ENABLE); for(i=0; i<TOTAL_POSTINGS; i++) { *post_addr = (uint64_t)0x0; post_addr++; } } /** * function: set_speed **/ void set_speed(uint64_t* speed, uint8_t* delay, volatile uint64_t* status) {//set counter-scom read delay according to speed setting. switch(*speed) { case CNTL_SPEED_1MS: *delay = 0; break; case CNTL_SPEED_2MS: *delay = 1; break; case CNTL_SPEED_4MS: *delay = 2; break; case CNTL_SPEED_8MS: *delay = 3; break; case CNTL_SPEED_16MS: *delay = 4; break; case CNTL_SPEED_32MS: *delay = 5; break; case CNTL_SPEED_64MS: *delay = 6; break; case CNTL_SPEED_128MS: *delay = 7; break; case CNTL_SPEED_256MS: *delay = 8; break; case CNTL_SPEED_512MS: *delay = 9; break; case CNTL_SPEED_1024MS: *delay = 10; break; case CNTL_SPEED_2048MS: *delay = 11; break; default: *status = CNTL_STATUS_ERR1; break; } } /** * function: get_mba_event **/ uint64_t get_mba_event(uint64_t cur, uint64_t prev) { if(cur >= prev) prev = cur - prev; else prev = (MAX_32 - prev) + cur; return prev; } /** * function: get_phb_event **/ uint64_t get_phb_event(uint64_t cur, uint64_t prev) { if(cur >= prev) prev = cur - prev; else prev = (MAX_48 - prev) + cur; return prev; } <|start_filename|>src/ssx/ppc405/ppc405.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_H__ #define __PPC405_H__ /// \file ppc405.h /// \brief PowerPC 405 port header for SSX // The 405 has a 32-byte line and 2-way set associative caches. The cache // configuration varies by chip/ASIC. // // Regarding the DCACHE_TAG_MASK, used by dcache_flush_all: The IBM // documentation on the D-cache tag sizes doesn't make any sense to me - it // claims the tag size is constant regardless of the size of the cache. // However the Xilinx documentation for their 405 core (which has the same // 16KB cache as OCCHW) is consistent with the way the DCACHE_TAG_MASK is // defined here. #define CACHE_LINE_SIZE 32 #define LOG_CACHE_LINE_SIZE 5 #define ICACHE_WAYS 2 #define DCACHE_WAYS 2 #define LOG_ICACHE_WAYS 1 #define LOG_DCACHE_WAYS 1 #define ICACHE_LINES (ICACHE_SIZE / CACHE_LINE_SIZE) #define DCACHE_LINES (DCACHE_SIZE / CACHE_LINE_SIZE) #define DCACHE_TAG_MASK \ ((0xffffffff << (LOG_DCACHE_SIZE - LOG_DCACHE_WAYS)) & 0xffffffff) #ifdef HWMACRO_OCC #define ICACHE_SIZE (16 * 1024) #define DCACHE_SIZE (16 * 1024) #define LOG_ICACHE_SIZE 14 #define LOG_DCACHE_SIZE 14 #else #error "Please define the cache configuration of the processor" #endif // Macros to define where declared code is actually compiled #ifdef __PPC405_C__ #define IF__PPC405_CORE_C__(x) x #define UNLESS__PPC405_CORE_C__(x) #else #define IF__PPC405_CORE_C__(x) #define UNLESS__PPC405_CORE_C__(x) x #endif #ifdef __PPC405_IRQ_CORE_C__ #define IF__PPC405_IRQ_CORE_C__(x) x #define UNLESS__PPC405_IRQ_CORE_C__(x) #else #define IF__PPC405_IRQ_CORE_C__(x) #define UNLESS__PPC405_IRQ_CORE_C__(x) x #endif #ifdef HWMACRO_OCC #include "occhw.h" #endif #include "ppc32.h" #include "ppc405_dcr.h" #include "ppc405_spr.h" #include "ppc405_msr.h" #include "ppc405_irq.h" #include "ppc405_cache.h" #if PPC405_MMU_SUPPORT #include "ppc405_mmu.h" #ifndef PPC405_IR_SUPPORT #define PPC405_IR_SUPPORT 1 #endif #ifndef PPC405_DR_SUPPORT #define PPC405_DR_SUPPORT 1 #endif #define PPC405_RELOCATION_MODE \ ((PPC405_IR_SUPPORT * MSR_IR) | (PPC405_DR_SUPPORT * MSR_DR)) #ifndef __ASSEMBLER__ void* memcpy_real(void* dest, const void* src, size_t n); #endif #else /* PPC405_MMU_SUPPORT */ #define PPC405_RELOCATION_MODE 0 #ifndef __ASSEMBLER__ static inline void* memcpy_real(void* dest, const void* src, size_t n) { memcpy(dest, src, n); icache_invalidate_all(); return dest; } #endif #endif /* PPC405_MMU_SUPPORT */ /// By default, in MMU mode free space is read/write only, just like normal /// data. Saome applications may need to execute from free space however, and /// can override this default. #ifndef EXECUTABLE_FREE_SPACE #define EXECUTABLE_FREE_SPACE 0 #endif #include "ppc405_context.h" // PPC405 stack characteristics for SSX. The pre-pattern pattern is selected // to be easily recognizable yet be an illegal instruction. #define SSX_STACK_DIRECTION -1 #define SSX_STACK_PRE_DECREMENT 1 #define SSX_STACK_ALIGNMENT 8 #define SSX_STACK_TYPE unsigned int #define SSX_STACK_PATTERN 0x03abcdef // Kernel data structure offsets for assembler code #define SSX_THREAD_OFFSET_SAVED_STACK_POINTER 0 #define SSX_THREAD_OFFSET_STACK_LIMIT 4 #define SSX_THREAD_OFFSET_STACK_BASE 8 // SSX boot loader panic codes #define PPC405_BOOT_CCR0_MODIFY_FAILED 0x00405000 #define PPC405_BOOT_VECTORS_NOT_ALIGNED 0x00405001 // Interrupt handler panic codes #define PPC405_DEFAULT_IRQ_HANDLER 0x00405010 #define PPC405_DEFAULT_SPECIAL_HANDLER 0x00405011 #define PPC405_PHANTOM_INTERRUPT 0x00405012 #define PPC405_PROGRAM_HALT 0x00405013 // Exception handling invariant panic codes #define PPC405_IRQ_FULL_EXIT_INVARIANT 0x00405020 #define PPC405_IRQ_FAST2FULL_INVARIANT 0x00405021 // API error panic codes #define PPC405_CACHE_ALIGNMENT 0x00405030 // Application-overrideable definitions /// The default thread machine context has MSR[CE], MSR[EE] and MSR[ME] set, /// and all other MSR bits cleared. /// /// The default definition allows critical, non-critical and machine check /// exceptions. Debug interrupts are not enabled by default. This definition /// can be overriden by the application. If MMU protection is enabled then /// the IR/DR bits are also modeably set. #ifndef SSX_THREAD_MACHINE_CONTEXT_DEFAULT #define SSX_THREAD_MACHINE_CONTEXT_DEFAULT \ (MSR_CE | MSR_EE | MSR_ME | PPC405_RELOCATION_MODE) #endif #ifndef __ASSEMBLER__ /// The SSX kernel default panic sequence for C code /// /// By default a kernel panic from C code forces external debug mode then /// generates a \c trap instruction followed by the error code. The \a code /// argument must be a compile-time integer immediate. This definition can be /// overriden by the application. /// /// The OCC may be running in internal debug mode for various reasons, and /// TRAP-ing in internal debug mode would lead to an infinite loop in the /// default Program Interrupt handler - which itself would be a TRAP (since /// that's the default implementation of SSX_PANIC(). Therefore by default /// the panic is implemented as a special code sequence that forces the core /// into external debug mode before issuing a TRAP which will halt the core. /// To preserve the state we use the special global variables /// __ssx_panic_save_dbcr0 and __ssx_panic_save_r3 defined in ppc405_core.c. /// The original value of DBCR0 is destroyed, but can be recovered from the /// global. In the end %r3 is reloaded from temporary storage and will be /// unchanged at the halt. /// /// Note that there is a small chance that an interrupt will fire and /// interrupt this code before the halt - in general there is no way around /// this. /// /// The Simics environment does not model Debug events correctly. It executes /// the TRAP as an illegal instruction and branches to the Program Interrupt /// handler, destroying the contents of SRR0 and SRR1. Therefore we always /// insert a special Simics magic breakpoint (which is an effective NOP) /// before the hardware trap. The special-form magic instruction is /// recognized by our Simics support scripts which decode the kernel state and /// try to help the user interpret what happened based on the TRAP code. #ifndef SSX_PANIC #define SSX_PANIC(code) \ do { \ barrier(); \ asm volatile ("stw %r3, __ssx_panic_save_r3@sda21(0)"); \ asm volatile ("mfdbcr0 %r3"); \ asm volatile ("stw %r3, __ssx_panic_save_dbcr0@sda21(0)"); \ asm volatile ("lwz %r3, __ssx_panic_dbcr0@sda21(0)"); \ asm volatile ("mtdbcr0 %r3"); \ asm volatile ("isync"); \ asm volatile ("lwz %r3, __ssx_panic_save_r3@sda21(0)"); \ asm volatile ("rlwimi 1,1,0,0,0"); \ asm volatile ("trap"); \ asm volatile (".long %0" : : "i" (code)); \ } while (0) // These variables are used by the SSX_PANIC() definition above to save and // restore state. __ssx_panic_dbcr0 is the value loaded into DBCR0 to force // traps to halt the OCC and freeze the timers. #ifdef __PPC405_CORE_C__ uint32_t __ssx_panic_save_r3; uint32_t __ssx_panic_save_dbcr0; uint32_t __ssx_panic_dbcr0 = DBCR0_EDM | DBCR0_TDE | DBCR0_FT; #endif #endif // SSX_PANIC /// This is the Simics 'magic breakpoint' instruction. /// /// Note that this form does not include a memory barrier, as doing so might /// change the semantics of the program. There is an alternative form /// SIMICS_MAGIC_BREAKPOINT_BARRIER that does include a barrier. #define SIMICS_MAGIC_BREAKPOINT asm volatile ("rlwimi 0,0,0,0,0") /// This is the Simics 'magic breakpoint' instruction including a memory /// barrier. /// /// Note that the memory barrier guarantees that all variables held in /// registers are flushed to memory before the breakpoint, however this might /// change the semantics of the program. There is an alternative form of /// SIMICS_MAGIC_BREAKPOINT that does not include a barrier. If the idea is /// to use the breakpoint for tracing code execution in Simics, the barrier /// form may be preferred so that variable values will be visible in memory. #define SIMICS_MAGIC_BREAKPOINT_BARRIER \ asm volatile ("rlwimi 0,0,0,0,0" : : : "memory") #else // __ASSEMBLER__ // *INDENT-OFF* /// This is the Simics 'magic breakpoint' instruction. An assembler macro /// form is also provided for use within macros. #define SIMICS_MAGIC_BREAKPOINT rlwimi 0,0,0,0,0 .macro _simics_magic_breakpoint rlwimi 0,0,0,0,0 .endm /// The SSX kernel panic default panic sequence for assembler code /// /// By default a kernel panic from assembler forces external debug mode then /// generates a \c trap instruction followed by the error code. The \a code /// argument must be a compile-time integer immediate. This definition can be /// overriden by the application. /// /// See the comments for the non-ASSEMBLER version for further details. Note /// that the code space reserved for exception handlers is only 8 /// instructions, so in the assembler context we don't save DBCR0 as doing so /// would require 10. #ifndef SSX_PANIC #define SSX_PANIC(code) _ssx_panic code .macro _ssx_panic, code _stwsd %r3, __ssx_panic_save_r3 _lwzsd %r3, __ssx_panic_dbcr0 mtdbcr0 %r3 isync _lwzsd %r3, __ssx_panic_save_r3 rlwimi 1,1,0,0,0 trap .long \code .endm #endif // SSX_PANIC // *INDENT-ON* #endif // __ASSEMBLER__ // Application-overridible definitions for the SSX boot loader /// In order to enable the default kernel panic (a trap) to halt the machine, /// the Debug Control Register 0 (DBCR0) is initialized in externel debug /// mode, with the Trap Debug Event enabled so that the trap will not cause a /// program exception, and the FT bit set so that the timers will freeze. /// This definition can be overridden by the application. /// /// NB: It is expected that a reliable production system will redefine all of /// the 'panic' macros and the default DBCR0 setup. #ifndef PPC405_DBCR0_INITIAL #define PPC405_DBCR0_INITIAL (DBCR0_EDM | DBCR0_TDE | DBCR0_FT) #endif /// This is the value of the MSR used during initialization. Once SSX threads /// are started (with \c ssx_start_threads()), all machine contexts derive /// from the default thread context \c /// SSX_THREAD_MACHINE_CONTEXT_DEFAULT. This definition can be overriden by /// the application. /// /// The default is to enable machine checks only. #ifndef PPC405_MSR_INITIAL #define PPC405_MSR_INITIAL MSR_ME #endif /// This is the initial value of Cache Control Register 0 (CCR0). This /// definition can be overridden by the application. /// /// The default sets the CCR0 to give priority to DCU and ICU operations. The /// user should consider setting other options in this register that affect /// performance, e.g., ICU prefetching. Other options can be set at run time /// with the API \c ppc405_ccr0_modify(). #ifndef PPC405_CCR0_INITIAL #define PPC405_CCR0_INITIAL (CCR0_DPP1 | CCR0_IPP0 | CCR0_IPP1) #endif /// The \a argc argument passed to \c main(). This definition can be overriden /// by the application. #ifndef PPC405_ARGC_INITIAL #define PPC405_ARGC_INITIAL 0 #endif /// The \a argv argument passed to \c main(). This definition can be overriden /// by the application. #ifndef PPC405_ARGV_INITIAL #define PPC405_ARGV_INITIAL 0 #endif /// Optionally trap the reset for the debugger, which means that the PPC405 /// will simply spin at the symbol \c __reset_trap after a chip reset. Set R0 /// to a non-zero value in the debugger to continue execution. This definition /// can be overriden by the application. #ifndef PPC405_RESET_TRAP #define PPC405_RESET_TRAP 0 #endif #ifndef __ASSEMBLER__ /// The PPC405 SSX machine context is simply the MSR, a 32-bit integer. typedef uint32_t SsxMachineContext; /// Disable interrupts at the given priority level, and return the current /// context. /// /// \param priority The interrupt priority level to disable, either \c /// SSX_NONCRITICAL, \c SSX_CRITICAL or \c SSX_SUPERCRITICAL. For best /// efficiency, the \a priority parameter should be a manifest constant. /// /// \param context A pointer to an SsxMachineContext, this is the context that /// existed before interrupts were disabled. Typically this /// context is restored at the end of a critical section. /// /// The PPC405 supports a 'super-critical' context in which every possible /// maskable exception is disabled. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_INTERRUPT An illegal priority was specified. UNLESS__PPC405_CORE_C__(extern) inline int ssx_interrupt_disable(int priority, SsxMachineContext* context) { *context = mfmsr(); if (priority == SSX_NONCRITICAL) { wrteei(0); } else if (priority == SSX_CRITICAL) { mtmsr(*context & ~(MSR_EE | MSR_CE)); } else if (priority == SSX_SUPERCRITICAL) { mtmsr(*context & ~(MSR_APE | MSR_WE | MSR_CE | MSR_EE | MSR_ME | MSR_DWE | MSR_DE)); } else if (SSX_ERROR_CHECK_API) { SSX_ERROR(SSX_INVALID_ARGUMENT_INTERRUPT); } return SSX_OK; } /// Set the machine context. /// /// \param context A pointer to an SsxMachineContext /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_CONTEXT_SET A null pointer was provided as /// the \a context argument or an illegal machine context was specified. UNLESS__PPC405_CORE_C__(extern) inline int ssx_machine_context_set(SsxMachineContext* context) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(context == 0, SSX_INVALID_ARGUMENT_CONTEXT_SET); } mtmsr(*context); return SSX_OK; } /// Get the machine context. /// /// \param context A pointer to an SsxMachineContext. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_CONTEXT_GET A null pointer was provided as /// the \a context argument. UNLESS__PPC405_CORE_C__(extern) inline int ssx_machine_context_get(SsxMachineContext* context) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(context == 0, SSX_INVALID_ARGUMENT_CONTEXT_GET); } *context = mfmsr(); return SSX_OK; } /// The SSX kernel thread context switch - PPC405 uses the system call /// exception. #define __ssx_switch() asm volatile ("sc") /// In the PowerPC EABI all initial stack frames require 8 bytes - the 4 bytes /// at the SP are zeroed to indicate the end of the stack, and the 4 bytes /// behind the SP are for the initial subroutine's LR. static inline void __ssx_stack_create_initial_frame(SsxAddress* stack, size_t* size) \ { *stack -= 8; * size -= 8; * ((SSX_STACK_TYPE*)(*stack)) = 0; } /// The SSX Kernel Context for PPC405 /// /// The SSX portable kernel does not define how the kernel keeps track of /// whether SSX is running, interrupt levels, and other debug /// information. Instead it defines an API that the port must provide to the /// portable kernel. /// /// In the PPC405 port, the kernel context is maintained in USPRG0. This /// 32-bit value is treated as 5 distinct fields as indicated in the structure /// definition. For certain tests it's also helpful to look at the two /// interrupt counters as a single 0/non-0 field. typedef union { uint32_t value; struct { /// The critical interrupt nesting level. If this field is non-zero, /// then interrupt priority and preemption rules guarantee that a /// critical interrupt handler is running, and the \c irq field will /// contain the SsxIrqId of the currently active critical interrupt. unsigned critical_interrupts : 8; /// The non-critical interrupt nesting level. If this field is /// non-zero and the \c critical_interrupts field is 0, then interrupt /// priority and preemption rules guarantee that a noncritical /// interrupt handler is running, and the \c irq field will contain /// the SsxIrqId of the currently active noncritical interrupt. unsigned noncritical_interrupts : 8; /// The SsxIrqId of the currently running (or last run) handler. If /// either of the interrupt nesting levels are non-0, then this is the /// SsxIrqId of the IRQ that is currently executing. unsigned irq : 8; /// A flag indicating that SSX is in thread mode after a call of /// ssx_start_threads(). unsigned thread_mode : 1; /// The priority of the currently running thread. In an interrupt /// context, this is the priority of the thread that was interrupted. unsigned thread_priority : 7; } fields; struct { /// Used as a 0/non-0 flag for interrupt context. unsigned interrupt_context : 16; /// Ignore unsigned ignore : 16; } merged_fields; } __SsxKernelContext; // These APIs are provided to the SSX portable kernel by the port. /// SSX threads have been started by a call of ssx_start_threads(). #define __ssx_kernel_mode_thread() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.fields.thread_mode;}) /// SSX is executing in a thread context (not an interrupt handler). #define __ssx_kernel_context_thread() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.fields.thread_mode && !__ctx.merged_fields.interrupt_context;}) /// SSX is executing an interrupt handler of any priority. #define __ssx_kernel_context_any_interrupt() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.merged_fields.interrupt_context;}) /// SSX is executing a critical interrupt handler. #define __ssx_kernel_context_critical_interrupt() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.fields.critical_interrupts;}) /// SSX is executing a non-critical interrupt handler. #define __ssx_kernel_context_noncritical_interrupt() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.fields.noncritical_interrupts && \ !__ctx.fields.critical_interrupts;}) /// Return the noncritical interrupt nesting level #define __ssx_noncritical_level() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.fields.noncritical_interrupts; }) /// Return the critical interrupt nesting level #define __ssx_critical_level() \ ({ \ __SsxKernelContext __ctx; \ __ctx.value = mfspr(SPRN_USPRG0); \ __ctx.fields.critical_interrupts; }) // SSX requires the port to define the type SsxThreadQueue, which is a // priority queue (where 0 is the highest priority). This queue must be able // to handle SSX_THREADS + 1 priorities (the last for the idle thread) The // port must also define methods for clearing, insertion, deletion and min // (with assumed legal priorities). The min operation returns SSX_THREADS if // the queue is empty (or a queue could be initialized with that entry always // present - SSX code never tries to delete the idle thread from a thread // queue). // // These queues are used both for the run queue and the pending queue // associated with every semaphore. // // On PPC405 with 32 threads (implied), this is a job for a uint32_t and // cntlzw(). static inline void __ssx_thread_queue_clear(volatile SsxThreadQueue* queue) { *queue = 0; } static inline void __ssx_thread_queue_insert(volatile SsxThreadQueue* queue, SsxThreadPriority priority) { *queue |= (0x80000000u >> priority); } static inline void __ssx_thread_queue_delete(volatile SsxThreadQueue* queue, SsxThreadPriority priority) { *queue &= ~(0x80000000u >> priority); } static inline SsxThreadPriority __ssx_thread_queue_min(volatile SsxThreadQueue* queue) { return cntlzw(*queue); } static inline int __ssx_thread_queue_member(volatile SsxThreadQueue* queue, SsxThreadPriority priority) { return ((*queue >> (31 - priority)) & 1); } static inline void __ssx_thread_queue_union(volatile SsxThreadQueue* queue0, volatile SsxThreadQueue* queue1) { *queue0 |= *queue1; } static inline int __ssx_thread_queue_count(volatile SsxThreadQueue* queue) { return __builtin_popcount(*queue); } /// This macro is used to call __ssx_start_threads() using the kernel stack, /// in a SSX_NONCRITICAL critical section. #define __ssx_call_ssx_start_threads() \ do { \ SsxMachineContext ctx; \ ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); \ asm volatile ("mr 1, %0; mtlr %1; blrl" : : \ "r" (__ssx_noncritical_stack), \ "r" (__ssx_start_threads)); \ SSX_PANIC(SSX_START_THREADS_RETURNED); \ } while (0) #endif /* __ASSEMBLER__ */ /// The __SsxKernelContext 'thread_mode' bit as a flag #define PPC405_THREAD_MODE 0x80 #ifndef __ASSEMBLER__ /// Code breakpoints for PPC405 /// /// This macro inserts a special PPC405-only breakpoint into the object code /// at the place the macro invocation appears. This facility is designed for /// VBU/VPO procedure debugging. This type of breakpoint may not be required /// on real hardware as we will then have the full power of RISCWatch, gdb, /// etc. Once inserted into the code, code breakpoints can be enabled or /// disabled by manipulating the global variable _code_breakpoint_enable, /// which defaults to 1. /// /// The code breakpoint is implemented as a setup routine and a teardown /// routine, executed in an SSX_CRITICAL critical section. The actual break /// will occur at the address of the call of the teardown routine, in the /// context of the calling code. The setup routine saves the state of DBCR0/1 /// and IAC4, then programs the DBCR for an external debug mode, IAC4 /// breakpoint. The IAC4 breakpoint is set for the address of the call of the /// teardown routine. The teardown routine simply restores the state of the /// debug registers that existed before the code breakpoint. /// /// Once hit, restarting from the break requires clearing IAC4 and restarting /// instructions: /// /// \code /// /// putspr pu.occ iac4 0 /// cipinstruct pu.occ start /// /// \endcode /// /// The above restart processes is also encapsulated as the p8_tclEcmd /// procedure 'unbreakOcc'. /// /// In code built for the Simics environment (i.e., with the preprocessor /// macro SIMICS_ENVIRONMENT=1) this macro simply expands into /// SIMICS_MAGIC_BREAKPOINT, and simulation can be continued from the break as /// normal. This Simics magic breakpoint is also under the control of /// _code_breakpoint_enable. In code not built with SIMICS_ENVIROMENT=1, note /// that the CODE_BREAKPOINT is ignored by the Simics PPC405 model as it does /// not model debug events. #if defined(SIMICS_ENVIRONMENT) && (SIMICS_ENVIRONMENT != 0) #define CODE_BREAKPOINT \ do { \ if (_code_breakpoint_enable) { \ SIMICS_MAGIC_BREAKPOINT; \ } \ } while (0) #else #define CODE_BREAKPOINT \ do { \ if (_code_breakpoint_enable) { \ SsxMachineContext __ctx; \ ssx_critical_section_enter(SSX_CRITICAL, &__ctx); \ _code_breakpoint_prologue(); \ _code_breakpoint_epilogue(); \ ssx_critical_section_exit(&__ctx); \ } \ } while (0) #endif void _code_breakpoint_prologue(void); void _code_breakpoint_epilogue(void); extern uint32_t _code_breakpoint_enable; #endif // __ASSEMBLER__ #endif /* __PPC405_H__ */ <|start_filename|>src/occ_405/pss/test/apsstest.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pss/test/apsstest.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "ssx_io.h" #include "simics_stdio.h" #include <thread.h> #include <threadSch.h> #include <errl.h> #include <apss.h> // Period in which to run #timer_routine #define TIMER_INTERVAL (SsxInterval) SSX_MICROSECONDS(5000) SsxSemaphore prcd_sem; int g_j = 0; int g_k = 0; SimicsStdio simics_stdout; SimicsStdio simics_stderr; uint8_t noncritical_stack[NONCRITICAL_STACK_SIZE]; uint8_t critical_stack[CRITICAL_STACK_SIZE]; SsxTimer G_test_timer; extern void timer_routine(void *private); extern void rtloop_ocb_init(void); // Function Specification // // Name: pgp_validation_ssx_main_hook // // Description: // // End Function Specification void pgp_validation_ssx_main_hook(void) { } // Function Specification // // Name: Cmd_Hndl_thread_routine // // Description: // // End Function Specification //TODO placeholder void Cmd_Hndl_thread_routine(void *arg) { do { int x=0; for(x=0; x < 1000; x++) { } //printf("Thread A running"); }while(1); } // Function Specification // // Name: App_thread_routine // // Description: // // End Function Specification void App_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } }while(1); } // Function Specification // // Name: Thermal_Monitor_thread_routine // // Description: // // End Function Specification void Thermal_Monitor_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } //printf("Thread A running"); }while(1); } // Function Specification // // Name: Hlth_Monitor_thread_routine // // Description: // // End Function Specification void Hlth_Monitor_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } //printf("Thread A running"); }while(1); } // Function Specification // // Name: FFDC_thread_routine // // Description: // // End Function Specification void FFDC_thread_routine(void *arg) { int z=0; do { int x=0; for(x=0; x < 10000; x++) { z++; } //printf("Thread A running"); }while(1); } /** PRCD Thread * * This thread loops as the highest priority thread, where it currently * just * */ // Function Specification // // Name: prcd_thread_routine // // Description: // // End Function Specification void prcd_thread_routine(void *private) { while(1) { // Just sit here until this semaphore is posted, which will never happen. ssx_semaphore_pend(&prcd_sem, SSX_WAIT_FOREVER); // Only trace the first XX times that this function loops if(g_j < 20) { g_k = 0; g_j++; } } } // Function Specification // // Name: apss_test_pwr_meas // // Description: Request the full power measurement data in a single function call for TESTING ONLY // // End Function Specification extern PoreEntryPoint pore_test; // Sleep for specified amount of time... void apss_test_pwr_meas(void) { task_apss_start_pwr_meas(); // Schedule GPE program to delay to ensure the data is available... (BLOCKING) // bad: 48, good: 56 PoreFlex test_request; DEBUG_PRINTF(("apss_test_pwr_meas: delay...\n")); pore_flex_create(&test_request, &pore_gpe0_queue, (void*)pore_test, // entry_point (uint32_t)56, // entry_point argument NULL, // callback, NULL, // callback arg ASYNC_REQUEST_BLOCKING); // options pore_flex_schedule(&test_request); DEBUG_PRINTF(("apss_test_pwr_meas: delay complete\n")); task_apss_continue_pwr_meas(); task_apss_complete_pwr_meas(); } // end apss_test_pwr_meas() /** Main Thread * * This thread currently just loops as the lowest priority thread, handling * the lowest priority tasks. * */ // Function Specification // // Name: main_thread_routine // // Description: // // End Function Specification void main_thread_routine(void *private) { // Start the critical 250uS timer ssx_timer_schedule(&timer, 1, TIMER_INTERVAL); // Initialize APSS errlHndl_t l_errl = apss_initialize(); if (l_errl) { // init failed, attempt one more time before giving up printf("ERROR: apss_initialize failed! (retrying)\n"); setErrlSevToInfo(l_errl); commitErrl(&l_errl); l_errl = apss_initialize(); if (l_errl) { printf("ERROR: apss_initialize failed again! (OCC will be reset)"); commitErrl(&l_errl); // $TODO - Request Reset } } // Attempt to retrieve 3 sets of measurements printf("Attempting to gather power measurements\n"); apss_test_pwr_meas(); apss_test_pwr_meas(); apss_test_pwr_meas(); while(1) { // Only trace the first XX times that this function loops if(g_k < 3) { g_k++; // TRACE: Main Thread } // Sleep for 1000 before we run the loop again ssx_sleep_absolute(1000); } } // Function Specification // // Name: dump_thread_info // // Description: // // End Function Specification void dump_thread_info(void *arg) { printf("dumping thread info--------------------------\n"); int l_rc = 0; SsxThreadState l_state = 0; SsxThreadPriority l_pri = 0; int l_runnable=0; int x=0; for(x=0; x < THREADS_TO_SCHEDULE; x++) { l_rc = ssx_thread_info_get(G_scheduledThreads[x], &l_state, &l_pri, &l_runnable); printf("Thread %p: State %x priority %x runnable %x rc %x Global index %x\n",G_scheduledThreads[x], l_state, l_pri, l_runnable, l_rc, G_threadSchedulerIndex); } } /** Entry point for OCC execution * * main() currently initalizes our trace buffer along with creating threads * and timers for execution. Note that once main runs ssx_start_threads, we * never return as the SSX kernel takes over. * */ // Function Specification // // Name: main // // Description: // // End Function Specification int main(int argc, char **argv) { //locals errlHndl_t l_errl = NULL; // Initialize Trace Buffers immediately, so they can be used // from this point on. //TRAC_init_buffers(); // Initialize stdout so we can do printf from within simics env simics_stdout_create(&simics_stdout); simics_stderr_create(&simics_stderr); stdout = (FILE *)(&simics_stdout); stderr = (FILE *)(&simics_stderr); printf("Inside apsstest main\n"); // Initialize SSX Stacks (note that this also reinitializes the time base to 0) ssx_initialize((SsxAddress)noncritical_stack, NONCRITICAL_STACK_SIZE, (SsxAddress)critical_stack, CRITICAL_STACK_SIZE, 0); // Create Global Semaphores ssx_semaphore_create(&prcd_sem, 0, 13); // Create Threads ssx_thread_create(&main_thread, main_thread_routine, (void *)0, (SsxAddress)main_thread_stack, THREAD_STACK_SIZE, 1); // Create Threads ssx_thread_create(&prcd_thread, prcd_thread_routine, (void *)0, (SsxAddress)prcd_thread_stack, THREAD_STACK_SIZE, 0); // Make Threads runnable ssx_thread_resume(&main_thread); ssx_thread_resume(&prcd_thread); //Initialize the thread scheduler l_errl = initThreadScheduler(); if( l_errl ) { // Trace and commit error // TODO add trace // commit log // NOTE: log should be deleted by reader mechanism commitErrl( &l_errl ); } //kick off timer ssx_timer_create(&G_test_timer, dump_thread_info, 0); ssx_timer_schedule(&G_test_timer, 1, 500000000); // Enter SSX Kernel ssx_start_threads(); return 0; } <|start_filename|>src/ssx/occhw/occhw_async.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_async.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_async.c /// \brief Support for asynchronous request queuing and callback mechanisms /// /// This file implements device drivers for asynchronous requests. The model /// for devices like the PORE engines and the PBA block copy engines is that /// the application creates self-contained requests for jobs to run on the /// engine. The application then schedules the request and continues normal /// processing, or threads can request to simply block in place until the /// request finishes. Queue management is handled in the interrupt handler /// for the engine. As each queued job finishes, the next request (if any) is /// started on the engine and the optional callback is invoked or scheduled. /// /// The application can either use a polling protocol or the asynchronous /// callback mechanism to determine the state of the request. A timeout /// mechanism is also provided that cancels or kills a job that does not /// complete within a fixed time. Error handling in the event that the request /// does not complete in time or has failed is standardized by the /// implementation, but can be overridden by the application. /// /// Asynchronous request interrupt handlers can run either as critical or /// noncritical handlers. Some engines may support queuing requests that /// complete immediately; therefore the kernel context of the callback may be /// either a thread or interupt context, and in general, callbacks should not /// make assumptions about the kernel context when they run. /// /// If the callback is non-NULL and the request was created with \c /// ASYNC_CALLBACK_IMMEDIATE, the callback is then immediately invoked in the /// current context. In general, immediate callbacks should be short and sweet /// (to reduce interrupt latency) and should not make SSX kernel calls. /// /// If the request has a non-NULL callback and was created with \c /// ASYNC_CALLBACK_DEFERRED then the callback will be deferred to a /// noncritical interrupt context. Deferred callbacks are queued, then run /// later in response to a reserved IPI. Deferred callbacks always run as /// noncritical interrupt handlers with noncritical interrupts \e enabled, /// similar to SSX timer callbacks. /// /// If the request has a non-null callback and was created with \c /// ASYNC_CALLBACK_NONCRITICAL, then the callback will be run immediately from /// a noncritical handler or thread environment, or deferred from a critical /// interrupt context. Similar to immediate callbacks, callbacks marked /// noncritical should be short and sweet (to reduce interrupt latency), but /// may make SSX kernel calls. /// /// Regardless of whether the callback is critical or noncritical, the /// callback is coded as a normal C or assembler subroutine with a single /// void* argument. /// /// As a programming shortcut, the AsyncRequest includes a semaphore object. /// A special AsyncRequest option ASYNC_REQUEST_BLOCKING indicates that the /// thread scheduling the request should block on the semaphore of the /// AsyncRequest (with SSX_WAIT_FOREVER) until the request is complete. Note /// that a separate callback can be specified even if ASYNC_REQUEST_BLOCKING /// is specified. /// /// Requests are always timestamped. The \a start_time field of the request is /// set from the SSX timebase when the request is first 'run' on the device. /// Request types that may require multiple back-to-back 'runs' (like PBA /// block copies with more than 4K data) only record the initial 'run'. The \a /// end_time field of the request is set from the SSX timebase when the job /// finishes on the hardware, but before any callback is run. These /// timestamps cover time intervals not visible to the application; The /// application is responsible for timestamping the period between request /// queing and the \a start_time, and between the \a end_time and callback /// completion if required. The timestamps can be robustly recovered from the /// request using the API async_request_timestamps_get(). /// /// This is largely a generic implementation, designed to reduce code space by /// allowing the GPE, PBA and OCB drivers to use the same generic data /// structures and code. This is supported by the 'single-inheritence class /// hierarchy' described in the comments for occhw_async.h. /// /// <b> Request Completion and Callback States </b> /// /// The application can determine what happend to the job by observing the /// request state and callback return code when the request becomes idle. /// A request is not considered idle until the job has run to completion or /// been aborted, any callback has been run, any timeout has been cancelled, /// and any thread pending on request completion has been maxde runnable. /// /// Normally the application should see the request state (\a request->state) /// ASYNC_REQUEST_STATE_COMPLETE and a callback return code /// (\a request=->callback_rc) of 0 which indicates that the job and callback /// both completed normally. If the request did not complete normally it /// could be due to one of several reasons. For further analysis the request /// also includes a field \a abort_state that records the state the job was in /// when it was aborted (i.e., cancelled, killed, timed out or error-out). /// /// <b> Timeout Semantics </b> /// /// Any timeout other than SSX_WAIT_FOREVER specifies a timeout covering the /// interval spanning the time a job is scheduled until the time the job /// completes on the hardware. If the job is still wating to execute when it /// times out then the job is simply removed from the queue and marked as /// having timed out. If the job is running when it times out then the job is /// forceably removed from the hardware, which may have unintended or /// indeterminate consequences. The application may need to consider whether /// it is safe to continue after a forced timeout. /// /// Specifying a timeout involves quite a bit of overhead, since a timer needs /// to be scheduled and cancelled each time a job is run. If the interrupt /// handler for a device is a critical handler then the timeout cancellation /// will need to be deferred to the callback queue, potentially increasing /// overhead even further. /// /// <b> Implementation Notes </b> /// /// - The \e queue objects will normally be global data structures that /// persist throughout the life of the application. /// /// - The \e request objects may be either global or local data /// structures. However, since \e request objects are not copied, and pointers /// to them are stored in the \e queue objects, \a request objects should not /// be allocated on the stack if the stack frame could become invalid before /// the request completes. /// /// \todo Once all function is developed and tested, convert interrupt /// handling to fast-mode assembler routines. #include "ssx.h" #include "occhw_async.h" //////////////////////////////////////////////////////////////////////////// // Global Data //////////////////////////////////////////////////////////////////////////// /// Queue of deferred async callbacks static SsxDeque G_async_callback_queue; /// Queue of deferred IPC callbacks SsxDeque G_ipc_deferred_queue; //////////////////////////////////////////////////////////////////////////// // FFDC //////////////////////////////////////////////////////////////////////////// /// Collect FFDC for the PLB (OCI) arbiter /// /// \param ffdc A pointer to an OciFfdc structure to be filled in. /// /// \param master_id The PLB (OCI) master Id of the master of interest. /// /// Note: The PEAR and PESR hold error information for all OCI masters /// _except_ the OCC ICU and DCU. ICU and DCU errors are in the STO_PESR and /// STO_PEAR. Currently there is no need to collect those DCRs for 'async' /// errors. void oci_ffdc(OciFfdc* ffdc, int master_id) { // \todo, fix new pib access to dcr registers // uint32_t oesr_lock_mask; // ffdc->oear.value = mfdcr(OCB_OEAR); // ffdc->oesr.value = mfdcr(OCB_OESR); // oesr_lock_mask = 0x30000000 >> (4 * master_id); // if (ffdc->oesr.value & oesr_lock_mask) { // ffdc->mine = 1; // mtdcr(OCB_OESR, oesr_lock_mask); // } else { // ffdc->mine = 0; // } } //////////////////////////////////////////////////////////////////////////// // AsyncQueue //////////////////////////////////////////////////////////////////////////// // Start an asynchronous request on the device with timestamping. This will // always be called from a critical section, and any timestamp is collected // immediately before the request is kicked off on the device. Devices like // the BCE engines and the OCB queue drivers may run the same request multiple // times to get all of the data moved. Therefore the initial timestamp is only // captured the first time the request is run on the device. static inline int async_request_run(AsyncRequest* request) { if (request->state != ASYNC_REQUEST_STATE_RUNNING) { request->start_time = ssx_timebase_get(); } request->state = ASYNC_REQUEST_STATE_RUNNING; return request->run_method(request); } // Create (initialize) a generic AsyncQueue // // This is an internal API used to initialize generic request queues. The // caller is assumed to have done all error checking on the parameters. // // This is a simple initialization that resets the queues and sets the state // to QUEUE_STATE_IDLE. This routine should only be called on uninitialized // AsyncQueue objects. int async_queue_create(AsyncQueue* queue, AsyncEngine engine) { ssx_deque_sentinel_create(&(queue->deque)); queue->current = 0; queue->engine = engine; queue->state = ASYNC_QUEUE_STATE_IDLE; return 0; } // Generic completion of a request. This is called both by async_handler() // and async_request_deque(). static void async_request_complete(AsyncRequest* request) { SsxMachineContext ctx; AsyncRequestCallback callback; int completed; // Handle callbacks and deferred processing of the job that just // finished. No callback is easy. If the job does have a callback // that we can execute immediately then that is done immediately. // Note that 'completed' here means only that the callback is complete. callback = request->callback; if (!callback) { completed = 1; } else if ((request->options & ASYNC_CALLBACK_IMMEDIATE) || ((request->options & ASYNC_CALLBACK_NONCRITICAL) && !__ssx_kernel_context_critical_interrupt())) { request->state = ASYNC_REQUEST_STATE_CALLBACK_RUNNING; request->callback_rc = callback(request->arg); completed = 1; } else { request->state = ASYNC_REQUEST_STATE_CALLBACK_QUEUED; completed = 0; } // If the callback completed then we go ahead and cancel any timeout // and/or wake the thread if possible. In critical interrupt contexts // we always have to defer these operations, so we may lose 'complete' // status. if (completed && ((request->timeout != SSX_WAIT_FOREVER) || (request->options & ASYNC_REQUEST_BLOCKING))) { if (__ssx_kernel_context_critical_interrupt()) { request->state = ASYNC_REQUEST_STATE_POSTPROCESSING; completed = 0; } else { if (request->timeout != SSX_WAIT_FOREVER) { ssx_timer_cancel(&(request->timer)); } if (request->options & ASYNC_REQUEST_BLOCKING) { ssx_semaphore_post(&(request->sem)); } } } // A truly completed job gets its completion state here. Otherwise we // have to schedule the deferred postprocessing. if (completed) { request->state = request->completion_state; } else { ssx_critical_section_enter(SSX_CRITICAL, &ctx); if (request->options & ASYNC_CALLBACK_PRIORITY) { ssx_deque_push_front(&G_async_callback_queue, &(request->deque)); } else { ssx_deque_push_back(&G_async_callback_queue, &(request->deque)); } ssx_critical_section_exit(&ctx); ssx_irq_status_set(OCCHW_IRQ_ASYNC_IPI, 1); } } // The generic handler for asynchonous device completion. // // This handler processes completions of generic device requests, as well as // the initial running of jobs when the queue is idle. Error completions are // initially handled by async_error_handler() which then calls async_handler() // to finish the failed job and start the next job if possible. The initial // device handler must manage interrupts and provide a method to run the // 'current' job in the queue. The engine-specific handler may also iterate // the current job until it is complete - this handler should only be called // when the current job is complete. // // Some engines may have jobs that can complete immediately. This handler // iterates over jobs in the queue as long as the run method of the current // job returns the code -ASYNC_REQUEST_COMPLETE. // // NB : Normally this call is made from an interrupt handler, however it may // be called from job scheduling code if the engine is idle. Regardless, the // caller must insure that any call for a queue is protected against // interrupts for that queue. void async_handler(AsyncQueue* queue) { AsyncRequest* finished, *current; int rc; // This loop is repeated as long as any job started in a loop completes // immediately. do { // This API may be called on an idle queue, which indicates that we // should simply start the job on the head of the queue. Otherwise // save a pointer to the job that just finished and update its // end_time. if (queue->state == ASYNC_QUEUE_STATE_IDLE) { finished = 0; } else { finished = (AsyncRequest*)(queue->current); if (SSX_ERROR_CHECK_KERNEL && (finished == 0)) { SSX_PANIC(ASYNC_PHANTOM_INTERRUPT); } finished->end_time = ssx_timebase_get(); } // If the queue is in an error state we will not schedule any further // jobs on this queue. Otherwise we start the next job running on the // engine. if (queue->state == ASYNC_QUEUE_STATE_ERROR) { queue->current = 0; rc = 0; } else { current = (AsyncRequest*)ssx_deque_pop_front(&(queue->deque)); queue->current = current; if (current) { queue->state = ASYNC_QUEUE_STATE_RUNNING; rc = async_request_run(current); } else { queue->state = ASYNC_QUEUE_STATE_IDLE; rc = 0; } } // If no job just finished, continue with the loop. If the job we // just enqueued finished immediately it will be 'finished' on the // next loop (it would have given an rc == // -ASYNC_REQUEST_COMPLETE). Otherwise complete the request. if (finished != 0) { async_request_complete(finished); } } while (rc == -ASYNC_REQUEST_COMPLETE); } /// Schedule (queue for execution) a generic asynchronous request. /// /// \param request An initialized and idle AsyncRequest /// /// /// The request is queued for execution with all of the parameters provided /// when the request was created. It is considered an error to (re)schedule a /// request that is currently scheduled, running, or has the callback queued or /// in execution. Requests either need to be idle, or must be explicitly /// cancelled or killed before thay can be (re)scheduled. Because engine queue /// interrupt handlers may run as critical interrupts, this routine operates in /// a short \c SSX_CRITICAL critical section. /// /// If the request is made to an otherwise empty queue then the async_handler() /// must also be called immediately to begin the job. This will extend the /// critical section slightly. This routine will not start a request on a /// queue that has halted due to an error. The request will simply be enqueued /// in that case. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_SCHEDULE The \a request is NULL (0). /// /// \retval -ASYNC_REQUEST_NOT_IDLE The \a request is (still) active in some /// way at entry. /// /// \retval -ASYNC_REQUEST_NOT_COMPLETE This code is returned for requests that /// do not complete successfully, but only if ASYNC_REQUEST_BLOCKING is /// specified. The caller will need to examine the request state if necessary /// to determine whether the request failed, was cancelled or timed out. /// /// \todo Consider making the critical section priority depend on the device /// queue priority here, by adding a priority field to the queue. Without this /// we always have to run the async_handler() in an SSX_CRITICAL critical /// section. int async_request_schedule(AsyncRequest* request) { SsxMachineContext ctx = SSX_THREAD_MACHINE_CONTEXT_DEFAULT; // For GCC AsyncQueue* queue; int rc; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(request == 0, ASYNC_INVALID_OBJECT_SCHEDULE); } rc = 0; ssx_critical_section_enter(SSX_CRITICAL, &ctx); do { // Check to insure the request is idle (which check must be done in // the critical section), then start any required timeout. if (SSX_ERROR_CHECK_API) { if (!async_request_is_idle(request)) { rc = -ASYNC_REQUEST_NOT_IDLE; break; } } if (request->timeout != SSX_WAIT_FOREVER) { rc = ssx_timer_schedule(&(request->timer), request->timeout, 0); if (rc) { break; } } // Enqueue the request and initialize the request state. queue = request->queue; if (request->options & ASYNC_REQUEST_PRIORITY) { ssx_deque_push_front(&(queue->deque), &(request->deque)); } else { ssx_deque_push_back(&(queue->deque), &(request->deque)); } request->state = ASYNC_REQUEST_STATE_QUEUED; request->completion_state = ASYNC_REQUEST_STATE_COMPLETE; request->callback_rc = 0; // If the queue is idle, call the async_handler() to start the job. // Then block the calling thread if required. if (queue->state == ASYNC_QUEUE_STATE_IDLE) { async_handler(queue); } if (request->options & ASYNC_REQUEST_BLOCKING) { rc = ssx_semaphore_pend(&(request->sem), SSX_WAIT_FOREVER); if (rc) { break; } if (!async_request_completed(request)) { rc = -ASYNC_REQUEST_NOT_COMPLETE; break; } } } while (0); ssx_critical_section_exit(&ctx); return rc; } // The generic error handler // // This is a generic handler called in response to an error interrupt or // timeout. This handler calls a request-specific error method to stop the // hardware device, collect FFDC and make the hardware device runnable again // if possible. Then the current request is marked as having failed, and the // generic async_handler() is called which will start the next job (if any) // and take care of the callbacks for the failed request. If the error // method returns a non-0 return code then the error is non-recoverable and // the queue is marked with the error state. void async_error_handler(AsyncQueue* queue, uint8_t completion_state) { AsyncRequest* finished; finished = (AsyncRequest*)(queue->current); if (SSX_ERROR_CHECK_KERNEL && (finished == 0)) { SSX_PANIC(ASYNC_PHANTOM_ERROR); } if (finished->error_method) { if (finished->error_method(finished)) { queue->state = ASYNC_QUEUE_STATE_ERROR; } } finished->abort_state = finished->state; finished->completion_state = completion_state; async_handler(queue); } //////////////////////////////////////////////////////////////////////////// // AsyncRequest //////////////////////////////////////////////////////////////////////////// // Dequeue a queued AsyncRequest // // This is an internal API, always called from an SSX_CRITICAL critical // section. The request is known to be queued in one of the async queues. It // is removed from the queue and its state is updated. static void async_request_dequeue(AsyncRequest* request, uint8_t completion_state) { ssx_deque_delete((SsxDeque*)request); request->abort_state = request->state; request->completion_state = completion_state; async_request_complete(request); } // Time out an AsyncRequest // // This is an internal API, the timer callback used to time out long-running // AsyncRequest. // // This timer callback must run in an SSX_CRITICAL critical section to // guarantee atomic access to the AsyncRequest object. static void async_timeout(void* arg) { AsyncRequest* request = (AsyncRequest*)arg; SsxMachineContext ctx; ssx_critical_section_enter(SSX_CRITICAL, &ctx); // The behavior at timeout depends on the mode. We'll handle the cases // from easiest to hardest. if (request->state & ASYNC_REQUEST_CALLBACK_GROUP) { // If the request has already queued or is running the callback (which // could happen due to interrupt interleaving) then the request is // already finished, and it will eventually make a (redundant) call to // ssx_timer_cancel() to cancel the timer. So there's nothing to do. } else if (request->state & ASYNC_REQUEST_IDLE_GROUP) { // If the request is idle we panic - This can't happen as it would // indicate that the timer was not cancelled when the request // finished. SSX_PANIC(ASYNC_TIMEOUT_BUG); } else if (request->state & ASYNC_REQUEST_QUEUED_GROUP) { // If the request is still in the queue then we can simply cancel it, // which includes running the callback. async_request_dequeue(request, ASYNC_REQUEST_STATE_TIMED_OUT); } else if (request->state & ASYNC_REQUEST_RUNNING_GROUP) { // If the request is running on the hardware, then we need to call // the async_error_handler() to remove the job and restart the // hardware, which includes running the callback. async_error_handler(request->queue, ASYNC_REQUEST_STATE_TIMED_OUT); } else { SSX_PANIC(ASYNC_INVALID_STATE); } ssx_critical_section_exit(&ctx); } // Create (initialize) a generic AsyncRequest // // This is an internal API used to initialize generic requests. However this // API does some error checking, and any errors will be returned by the // higher-level call. // // \retval -ASYNC_INVALID_OBJECT_REQUEST The \a request or \a queue was /// null (0). // // \retval -ASYNC_INVALID_OPTIONS The \a options argument contains invalid // options, or more than one callback protocol was selected. // // \retval -ASYNC_INVALID_ARGUMENT The \a run_method was null. // // \retval -ASYNC_CALLBACK_PROTOCOL_UNSPECIFIED The request includes a // non-NULL callback, but no protocol for running the callback was specified. int async_request_create(AsyncRequest* request, AsyncQueue* queue, AsyncRunMethod run_method, AsyncErrorMethod error_method, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request == 0) || (queue == 0), ASYNC_INVALID_OBJECT_REQUEST); SSX_ERROR_IF((options & ~ASYNC_GENERIC_OPTIONS) || (__builtin_popcount(options & ASYNC_CALLBACK_OPTIONS) > 1), ASYNC_INVALID_OPTIONS); SSX_ERROR_IF(run_method == 0, ASYNC_INVALID_ARGUMENT); SSX_ERROR_IF((callback != 0) && ((options & ASYNC_CALLBACK_OPTIONS) == 0), ASYNC_CALLBACK_PROTOCOL_UNSPECIFIED); } ssx_deque_element_create(&(request->deque)); request->queue = queue; request->run_method = run_method; request->error_method = error_method; request->timeout = timeout; request->state = ASYNC_REQUEST_STATE_INITIALIZED; request->callback = callback; request->arg = arg; request->options = options; if (request->timeout != SSX_WAIT_FOREVER) { ssx_timer_create(&(request->timer), async_timeout, (void*)request); } if (options & ASYNC_REQUEST_BLOCKING) { ssx_semaphore_create(&(request->sem), 0, 1); } return 0; } /// Get timestamps from an AsyncRequest object /// /// \param request A pointer to an AsyncRequest /// /// \param start_time A pointer to a location to get the \a start_time of the /// request, or NULL (0) if this data is not required. /// /// \param end_time A pointer to a location to get the \a end_time of the /// request, or NULL (0) is this data is not required. /// /// \retval 0 The request contains valid timestamps and they have been /// returned. /// /// \retval -ASYNC_INVALID_TIMESTAMPS The caller's timestamps have been /// updated, but the timestamps are fully or partially invalid. This could be /// due to several reasons: /// /// - The request has never been scheduled /// - The request has been scheduled but has not completed on the device /// - For space/time reasons, timestamps are not supported int async_request_timestamps_get(AsyncRequest* request, SsxTimebase* start_time, SsxTimebase* end_time) { int rc; SsxMachineContext ctx; ssx_critical_section_enter(SSX_CRITICAL, &ctx); if (start_time) { *start_time = request->start_time; } if (end_time) { *end_time = request->end_time; } if ((request->state & ASYNC_REQUEST_IDLE_GROUP) && (request->state != ASYNC_REQUEST_STATE_INITIALIZED)) { rc = 0; } else { rc = -ASYNC_INVALID_TIMESTAMPS; } ssx_critical_section_exit(&ctx); return rc; } /// Compute the latency of an AsyncRequest /// /// \param request A pointer to an AsyncRequest /// /// \param latency A pointer to a location to receive the latency (end time - /// start time) computed from the timestamps of \a request. /// /// \retval 0 The request contains valid timestamps and they have been /// returned. /// /// \retval -ASYNC_INVALID_TIMESTAMPS The latancy has been computed but may be /// invalid. This could be due to several reasons: /// /// - The request has never been scheduled /// - The request has been scheduled but has not completed on the device /// - For space/time reasons, timestamps are not supported int async_request_latency(AsyncRequest* request, SsxTimebase* latency) { int rc; SsxTimebase start, end; rc = async_request_timestamps_get(request, &start, &end); *latency = end - start; return rc; } // Dump an AsyncRequest #if 0 void async_request_printk(AsyncRequest* request) { printk("----------------------------------------\n"); printk("-- AsyncRequest @ %p\n", request); printk("-- deque = %p\n", &(request->deque)); printk("-- start_time = 0x%016llx\n", request->start_time); printk("-- end_time = 0x%016llx\n", request->end_time); printk("-- sem = %p\n", &(request->sem)); printk("-- queue = %p\n", request->queue); printk("-- run_method = %p\n", request->run_method); printk("-- error_method = %p\n", request->error_method); printk("-- callback = %p\n", request->callback); printk("-- arg = %p\n", request->arg); printk("-- state = 0x%02x\n", request->state); printk("-- completion_state = 0x%02x\n", request->completion_state); printk("-- options = 0x%04x\n", request->options); printk("----------------------------------------\n"); } #endif //////////////////////////////////////////////////////////////////////////// // Callback Queue //////////////////////////////////////////////////////////////////////////// SSX_IRQ_FAST2FULL(async_callback_handler, async_callback_handler_full); // The handler for the asynchronous callback queue // // This is a full-mode noncritical interrupt handler. It is activated to run // 1) all deferred callbacks, and 2) noncritical callbacks invoked from // critical interrupt handlers, and 3) Thread-unblock and/or timeout-cancel // requests that needed to be deferred to a noncritical context. The callback // is enqueued in the SsxDeque passed as the private argument, and an IPI is // used to activate this handler. // // This handler runs each callback in order. Since the callback queue may be // managed by critical interrupt handlers we need to disable critical // interrupts when popping the next element from the queue. // // Deferred callbacks are run with noncritical interrupts \e enabled, similar // to how timer callbacks are run. // // Noncritical callbacks that were deferred here (by being invoked from a // critical handler) run with interrupts \e disabled, to be consistent with // the expected environment. Interrupts are then renabled briefly for // interrupt latency mitigation. // // Note that NULL callbacks may be enqueued here but only in the state // ASYNC_REQUEST_STATE_POSTPROCESSING. // The handler runs with its own IRQ disabled to avoid infinite interrupt // loops caused by enabling interrupt preemption. The IRQ status can only be // cleared inside an SSX_CRITICAL critical section. For efficiency we only do // this when we know that no more callbacks are queued. // Final request completion has been broken out into a generic routine, // async_request_finalize(). This routine is also called by the PTS // completion queue handler, which handles its requests ion a slightly // different way from the other async handlers. void async_request_finalize(AsyncRequest* request) { if (request->state == ASYNC_REQUEST_STATE_CALLBACK_QUEUED) { request->state = ASYNC_REQUEST_STATE_CALLBACK_RUNNING; if (request->options & ASYNC_CALLBACK_DEFERRED) { ssx_interrupt_preemption_enable(); request->callback_rc = request->callback(request->arg); } else { request->callback_rc = request->callback(request->arg); ssx_interrupt_preemption_enable(); } ssx_interrupt_preemption_disable(); } request->state = request->completion_state; if (request->timeout != SSX_WAIT_FOREVER) { ssx_timer_cancel(&(request->timer)); } if (request->options & ASYNC_REQUEST_BLOCKING) { ssx_semaphore_post(&(request->sem)); } } void async_callback_handler_full(void* arg, SsxIrqId irq, int priority) { SsxMachineContext ctx; AsyncRequest* request; ipc_msg_t* msg; ssx_irq_disable(irq); //Check for any async callbacks first do { ssx_critical_section_enter(SSX_CRITICAL, &ctx); request = (AsyncRequest*)ssx_deque_pop_front(&G_async_callback_queue); if (!request) { break; } ssx_critical_section_exit(&ctx); async_request_finalize(request); } while (1); ssx_critical_section_exit(&ctx); //Next, check for any deferred IPC messages do { ssx_critical_section_enter(SSX_CRITICAL, &ctx); msg = (ipc_msg_t*)ssx_deque_pop_front(&G_ipc_deferred_queue); if (!msg) { ssx_irq_status_clear(irq); break; } ssx_critical_section_exit(&ctx); void ipc_process_msg(ipc_msg_t* msg); //handle the command or response message in a noncritical context ipc_process_msg(msg); } while (1); ssx_critical_section_exit(&ctx); ssx_irq_enable(irq); } //////////////////////////////////////////////////////////////////////////// // Initialization //////////////////////////////////////////////////////////////////////////// // These initialization routines are for boot-time initialization, or // test-mode reinitialization of interface parameters when the interface is // known to be idle. They are not robust enough for mid-application // reset/reprogramming of the asynchronous interfaces in the event of errors. // For the interrupt setup, whether or not the interrupt is enabled at the // exit of setup depends on the particular driver being initialized. void async_edge_handler_setup(SsxIrqHandler handler, void* arg, SsxIrqId irq, int priority) { ssx_irq_disable(irq); ssx_irq_setup(irq, SSX_IRQ_POLARITY_ACTIVE_HIGH, SSX_IRQ_TRIGGER_EDGE_SENSITIVE); ssx_irq_handler_set(irq, handler, arg, priority); ssx_irq_status_clear(irq); } void async_level_handler_setup(SsxIrqHandler handler, void* arg, SsxIrqId irq, int priority, int polarity) { ssx_irq_disable(irq); ssx_irq_setup(irq, polarity, SSX_IRQ_TRIGGER_LEVEL_SENSITIVE); ssx_irq_handler_set(irq, handler, arg, priority); } void async_callbacks_initialize(SsxIrqId irq) { ssx_deque_sentinel_create(&G_async_callback_queue); ssx_deque_sentinel_create(&G_ipc_deferred_queue); async_edge_handler_setup(async_callback_handler, 0, irq, SSX_NONCRITICAL); ssx_irq_enable(irq); } /// Create all of the asynchronous request structures and install and /// activate the interrupt handlers. void async_initialize() { // This is the callback queue used e.g. when critical interrupts need to // run non-critical callbacks. async_callbacks_initialize(OCCHW_IRQ_ASYNC_IPI); async_gpe_initialize(&G_async_gpe_queue0, ASYNC_ENGINE_GPE0); async_gpe_initialize(&G_async_gpe_queue1, ASYNC_ENGINE_GPE1); async_gpe_initialize(&G_async_gpe_queue2, ASYNC_ENGINE_GPE2); async_gpe_initialize(&G_async_gpe_queue3, ASYNC_ENGINE_GPE3); // BCE async_bce_initialize(&G_pba_bcde_queue, ASYNC_ENGINE_BCDE, OCCHW_IRQ_PBA_BCDE_ATTN); async_bce_initialize(&G_pba_bcue_queue, ASYNC_ENGINE_BCUE, OCCHW_IRQ_PBA_BCUE_ATTN); // OCB async_ocb_initialize(&(G_ocb_read_queue[0]), ASYNC_ENGINE_OCB_PUSH0, G_ocb_read0_buffer, OCB_READ0_LENGTH, OCB_READ0_PROTOCOL); async_ocb_initialize(&(G_ocb_read_queue[1]), ASYNC_ENGINE_OCB_PUSH1, G_ocb_read1_buffer, OCB_READ1_LENGTH, OCB_READ1_PROTOCOL); async_ocb_initialize(&(G_ocb_read_queue[2]), ASYNC_ENGINE_OCB_PUSH2, G_ocb_read2_buffer, OCB_READ2_LENGTH, OCB_READ2_PROTOCOL); async_ocb_initialize(&(G_ocb_read_queue[3]), ASYNC_ENGINE_OCB_PUSH3, G_ocb_read3_buffer, OCB_READ3_LENGTH, OCB_READ3_PROTOCOL); async_ocb_initialize(&(G_ocb_write_queue[0]), ASYNC_ENGINE_OCB_PULL0, G_ocb_write0_buffer, OCB_WRITE0_LENGTH, OCB_WRITE0_PROTOCOL); async_ocb_initialize(&(G_ocb_write_queue[1]), ASYNC_ENGINE_OCB_PULL1, G_ocb_write1_buffer, OCB_WRITE1_LENGTH, OCB_WRITE1_PROTOCOL); async_ocb_initialize(&(G_ocb_write_queue[2]), ASYNC_ENGINE_OCB_PULL2, G_ocb_write2_buffer, OCB_WRITE2_LENGTH, OCB_WRITE2_PROTOCOL); async_ocb_initialize(&(G_ocb_write_queue[3]), ASYNC_ENGINE_OCB_PULL3, G_ocb_write3_buffer, OCB_WRITE3_LENGTH, OCB_WRITE3_PROTOCOL); // PBAX async_pbax_initialize(&G_pbax_read_queue[0], ASYNC_ENGINE_PBAX_PUSH0, OCCHW_IRQ_PBAX_OCC_PUSH0, G_pbax_read0_buffer, PBAX_READ0_LENGTH, PBAX_READ0_PROTOCOL); async_pbax_initialize(&G_pbax_read_queue[1], ASYNC_ENGINE_PBAX_PUSH1, OCCHW_IRQ_PBAX_OCC_PUSH1, G_pbax_read1_buffer, PBAX_READ1_LENGTH, PBAX_READ1_PROTOCOL); } <|start_filename|>src/occ_405/trac/trac.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ/trac/trac.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _trac_h #define _trac_h //*************************************************************************/ // Includes //*************************************************************************/ #include <trac_interface.h> //*************************************************************************/ // Externs //*************************************************************************/ //*************************************************************************/ // Macros //*************************************************************************/ //*************************************************************************/ // Defines/Enums //*************************************************************************/ #ifndef NO_TRAC_STRINGS #define ERR_MRK "ERR: " #define INFO_MRK "INF: " #define IMP_MRK "IMP: " #define DBG_MRK "DBG: " #define MAIN_MRK "MAIN: " #define CMDH_MRK "CMDH: " #define DCOM_MRK "DCOM: " #define INTR_MRK "INTR: " #define SNPS_MRK "SNPS: " //NOTE: TRAC_ERR must be used for tracing error related information only // TRAC_IMP must be used for tracing important OCC state/status that // changes once or twice OCC lifetime. It must NOT be used // for tracing anything that seems important to particular // developer. This trace buffer must not wrap so use it with // caution. // TRAC_INFO must be used for anything that does not fall under // TRAC_ERR or TRAC_IMP. Any debug or informational traces. // TRAC_DBG must be used for debug purpose only. This traces will be // turned OFF with product code. #if TRAC_TO_SIMICS #define TRAC_ERR(frmt,args...) \ printf(ERR_MRK "%s: "frmt "\n",__FUNCTION__,##args); \ TRACE(&g_des_array[ERR_TRACE_DESCRIPTOR],frmt,##args) #define TRAC_INFO(frmt,args...) \ printf(INFO_MRK "%s: "frmt "\n",__FUNCTION__,##args); \ TRACE(&g_des_array[INF_TRACE_DESCRIPTOR],frmt,##args) #define TRAC_IMP(frmt,args...) \ printf(IMP_MRK "%s: "frmt "\n",__FUNCTION__,##args); \ TRACE(&g_des_array[IMP_TRACE_DESCRIPTOR],frmt,##args) #define DBG_PRINT(fmt,args...) \ printf(DBG_MRK "%s: "fmt "\n",__FUNCTION__,##args); \ TRACEBIN(&g_des_array[INF_TRACE_DESCRIPTOR], string, data,len) extern void dumpHexString(const void *i_data, const unsigned int len, const char *string); #define DEBUG_HEXDUMP(data, len, string) \ dumpHexString(data, len, string) #else //TRAC_TO_SIMICS #define TRAC_ERR(frmt,args...) \ TRACE(&g_des_array[ERR_TRACE_DESCRIPTOR],frmt,##args) #define TRAC_INFO(frmt,args...) \ TRACE(&g_des_array[INF_TRACE_DESCRIPTOR],frmt,##args) #define TRAC_IMP(frmt,args...) \ TRACE(&g_des_array[IMP_TRACE_DESCRIPTOR],frmt,##args) #define DBG_PRINT(fmt,args...) \ TRACE(&g_des_array[INF_TRACE_DESCRIPTOR],DBG_MRK fmt,##args) #define DEBUG_HEXDUMP(data, len, string) \ TRACEBIN(&g_des_array[INF_TRACE_DESCRIPTOR], string, data,len) #endif //TRAC_TO_SIMICS // Tracing for main thread (call home, health monitor, fir data, thermal) #define MAIN_TRAC_ERR(frmt,args...) \ TRAC_ERR(MAIN_MRK frmt, ##args) #define MAIN_TRAC_INFO(frmt,args...) \ TRAC_INFO(MAIN_MRK frmt, ##args) #define MAIN_TRAC_IMP(frmt,args...) \ TRAC_IMP(MAIN_MRK frmt, ##args) // Tracing for command handler thread #define CMDH_TRAC_ERR(frmt,args...) \ TRAC_ERR(CMDH_MRK frmt, ##args) #define CMDH_TRAC_INFO(frmt,args...) \ TRAC_INFO(CMDH_MRK frmt, ##args) #define CMDH_TRAC_IMP(frmt,args...) \ TRAC_IMP(CMDH_MRK frmt, ##args) // Tracing for dcom thread #define DCOM_TRAC_ERR(frmt,args...) \ TRAC_ERR(DCOM_MRK frmt, ##args) #define DCOM_TRAC_INFO(frmt,args...) \ TRAC_INFO(DCOM_MRK frmt, ##args) #define DCOM_TRAC_IMP(frmt,args...) \ TRAC_IMP(DCOM_MRK frmt, ##args) // Tracing for the snapshot thread #define SNPS_TRAC_ERR(frmt,args...) \ TRAC_ERR(SNPS_MRK frmt, ##args) #define SNPS_TRAC_INFO(frmt,args...) \ TRAC_INFO(SNPS_MRK frmt, ##args) #define SNPS_TRAC_IMP(frmt,args...) \ TRAC_IMP(SNPS_MRK frmt, ##args) // Tracing for interrupts (RTL, oversubscription, etc) #define INTR_TRAC_ERR(frmt,args...) \ TRAC_ERR(INTR_MRK frmt, ##args) #define INTR_TRAC_INFO(frmt,args...) \ TRAC_INFO(INTR_MRK frmt, ##args) #define INTR_TRAC_IMP(frmt,args...) \ TRAC_IMP(INTR_MRK frmt, ##args) #ifdef MAIN_DEBUG #define MAIN_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define MAIN_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define MAIN_DBG(frmt,args...) #define MAIN_DBG_HEXDUMP(data, len, string) #endif #ifdef RTLS_DEBUG #define RTLS_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define RTLS_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define RTLS_DBG(frmt,args...) #define RTLS_DBG_HEXDUMP(data, len, string) #endif #ifdef PROC_DEBUG #define PROC_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define PROC_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define PROC_DBG(frmt,args...) #define PROC_DBG_HEXDUMP(data, len, string) #endif #ifdef CENT_DEBUG #define CENT_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define CENT_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define CENT_DBG(frmt,args...) #define CENT_DBG_HEXDUMP(data, len, string) #endif #ifdef THRD_DEBUG #define THRD_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define THRD_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define THRD_DBG(frmt,args...) #define THRD_DBG_HEXDUMP(data, len, string) #endif #ifdef AMEC_DEBUG #define AMEC_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define AMEC_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define AMEC_DBG(frmt,args...) #define AMEC_DBG_HEXDUMP(data, len, string) #endif #ifdef DCOM_DEBUG #define DCOM_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define DCOM_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define DCOM_DBG(frmt,args...) #define DCOM_DBG_HEXDUMP(data, len, string) #endif #ifdef ERRL_DEBUG #define ERRL_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define ERRL_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define ERRL_DBG(frmt,args...) #define ERRL_DBG_HEXDUMP(data, len, string) #endif #ifdef APSS_DEBUG #define APSS_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define APSS_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define APSS_DBG(frmt,args...) #define APSS_DBG_HEXDUMP(data, len, string) #endif #ifdef DPSS_DEBUG #define DPSS_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define DPSS_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define DPSS_DBG(frmt,args...) #define DPSS_DBG_HEXDUMP(data, len, string) #endif #ifdef CMDH_DEBUG #define CMDH_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define CMDH_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define CMDH_DBG(frmt,args...) #define CMDH_DBG_HEXDUMP(data, len, string) #endif #ifdef SNSR_DEBUG #define SNSR_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define SNSR_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define SNSR_DBG(frmt,args...) #define SNSR_DBG_HEXDUMP(data, len, string) #endif #ifdef TMER_DEBUG #define TMER_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define TMER_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define TMER_DBG(frmt,args...) #define TMER_DBG_HEXDUMP(data, len, string) #endif #ifdef CNFG_DEBUG #define CNFG_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define CNFG_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define CNFG_DBG(frmt,args...) #define CNFG_DBG_HEXDUMP(data, len, string) #endif #ifdef DIMM_DEBUG #define DIMM_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define DIMM_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define DIMM_DBG(frmt,args...) #define DIMM_DBG_HEXDUMP(data, len, string) #endif #ifdef MEM_DEBUG #define MEM_DBG(frmt,args...) \ DBG_PRINT(frmt,##args) #define MEM_DBG_HEXDUMP(data, len, string) \ DEBUG_HEXDUMP(data, len, string) #else #define MEM_DBG(frmt,args...) #define MEM_DBG_HEXDUMP(data, len, string) #endif #else // NO_TRAC_STRINGS #define TRAC_ERR(frmt,args...) #define TRAC_INFO(frmt,args...) #define TRAC_IMP(frmt,args...) #define MAIN_DBG(frmt,args...) #define RTLS_DBG(frmt,args...) #define PROC_DBG(frmt,args...) #define THRD_DBG(frmt,args...) #define AMEC_DBG(frmt,args...) #define DCOM_DBG(frmt,args...) #define ERRL_DBG(frmt,args...) #define CENT_DBG(frmt,args...) #define CMDH_DBG(frmt,args...) #define APSS_DBG(frmt,args...) #define DPSS_DBG(frmt,args...) #define SNSR_DBG(frmt,args...) #define TMER_DBG(frmt,args...) #define CNFG_DBG(frmt,args...) #define DIMM_DBG(frmt,args...) #define MAIN_DBG_HEXDUMP(frmt,args...) #define RTLS_DBG_HEXDUMP(frmt,args...) #define PROC_DBG_HEXDUMP(frmt,args...) #define THRD_DBG_HEXDUMP(frmt,args...) #define AMEC_DBG_HEXDUMP(frmt,args...) #define DCOM_DBG_HEXDUMP(frmt,args...) #define ERRL_DBG_HEXDUMP(frmt,args...) #define CENT_DBG_HEXDUMP(frmt,args...) #define CMDH_DBG_HEXDUMP(frmt,args...) #define APSS_DBG_HEXDUMP(frmt,args...) #define DPSS_DBG_HEXDUMP(frmt,args...) #define SNSR_DBG_HEXDUMP(frmt,args...) #define TMER_DBG_HEXDUMP(frmt,args...) #define CNFG_DBG_HEXDUMP(frmt,args...) #define DIMM_DBG_HEXDUMP(frmt,args...) #endif //************************************************************************* // Structures //************************************************************************* //************************************************************************* // Globals //************************************************************************* //************************************************************************* // Function Prototypes //************************************************************************* //************************************************************************* // Functions //************************************************************************* #endif // _trac_h <|start_filename|>src/occ_405/rtls/rtls_tables.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/rtls/rtls_tables.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "rtls.h" #include <timer.h> // timer reset task #include "apss.h" #include "dcom.h" #include "state.h" #include "proc_data.h" #include "proc_data_control.h" #include <centaur_data.h> #include <centaur_control.h> #include "memory.h" #include "amec_master_smh.h" #include "amec_sensors_fw.h" #include "dimm.h" #include <common.h> #include "sensor_get_tod_task.h" // For task_get_tod() #include "gpu.h" //flags for task table #define APSS_TASK_FLAGS RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_RUN #define FLAGS_DCOM_RX_SLV_INBX RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_RST_REQ | RTL_FLAG_APSS_NOT_INITD #define FLAGS_DCOM_TX_SLV_INBX RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_RST_REQ | RTL_FLAG_APSS_NOT_INITD #define FLAGS_DCOM_WAIT_4_MSTR RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_RST_REQ | RTL_FLAG_APSS_NOT_INITD #define FLAGS_DCOM_RX_SLV_OUTBOX RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_RST_REQ | RTL_FLAG_APSS_NOT_INITD #define FLAGS_DCOM_TX_SLV_OUTBOX RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_APSS_NOT_INITD #define FLAGS_LOW_CORES_DATA RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_HIGH_CORES_DATA RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_NEST_DTS RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD // Start out with memory tasks not running, then start during transition to observation in memory_init() #define FLAGS_MEMORY_DATA RTL_FLAG_NONE #define FLAGS_MEMORY_CONTROL RTL_FLAG_NONE #define FLAGS_FAST_CORES_DATA RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_AMEC_SLAVE RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_AMEC_MASTER RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_24X7 RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_GPU_SM RTL_FLAG_NONE #define FLAGS_GET_TOD RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD #define FLAGS_APSS_START_MEAS APSS_TASK_FLAGS #define FLAGS_APSS_CONT_MEAS APSS_TASK_FLAGS #define FLAGS_APSS_DONE_MEAS APSS_TASK_FLAGS #define FLAGS_APSS_RESET RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY #define FLAGS_DCOM_PARSE_OCC_FW_MSG RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_RST_REQ | RTL_FLAG_APSS_NOT_INITD #define FLAGS_MISC_405_CHECKS RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_STANDBY | RTL_FLAG_RST_REQ | RTL_FLAG_APSS_NOT_INITD #define FLAGS_CORE_DATA_CONTROL RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD // Don't run watchdog poke in all cases, expecially if a reset request is pending #define FLAGS_POKE_WDT RTL_FLAG_RUN | RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_STANDBY | \ RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_APSS_NOT_INITD #define FLAGS_GPE_TIMINGS RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD // Global tick sequences // The number and size of these will vary as the real tick sequences are developed over time. //NOTE: Currently this is the only way the complete apss works in simics // the future. /* The Global Task Table Use task_id_t values to index into this table and find a specific task. Add rows to this table as TASK_END grows. Example use: #define TASK_0_FLAGS RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE void task_0_func(struct task *i_self); uint32_t task_0_data = 0x00000000; // Use whatever data type makes sense // flags, func_ptr, data_ptr, // task_id_t { TASK_0_FLAGS, task_0_func, (void *)&task_0_data }, // TASK_ID_0 */ task_t G_task_table[TASK_END] = { // flags, func_ptr, data_ptr,// task_id_t { FLAGS_APSS_START_MEAS, task_apss_start_pwr_meas, NULL }, // TASK_ID_APSS_START { FLAGS_LOW_CORES_DATA, task_core_data, (void *) &G_low_cores}, { FLAGS_APSS_CONT_MEAS, task_apss_continue_pwr_meas, NULL }, // TASK_ID_APSS_CONT { FLAGS_HIGH_CORES_DATA, task_core_data, (void *) &G_high_cores}, { FLAGS_APSS_DONE_MEAS, task_apss_complete_pwr_meas, NULL }, // TASK_ID_APSS_DONE { FLAGS_DCOM_RX_SLV_INBX, task_dcom_rx_slv_inbox, NULL }, // TASK_ID_DCOM_RX_INBX { FLAGS_DCOM_TX_SLV_INBX, task_dcom_tx_slv_inbox, NULL }, // TASK_ID_DCOM_TX_INBX { FLAGS_POKE_WDT, task_poke_watchdogs, NULL }, // TASK_ID_POKE_WDT { FLAGS_DCOM_WAIT_4_MSTR, task_dcom_wait_for_master, NULL }, // TASK_ID_DCOM_WAIT_4_MSTR { FLAGS_DCOM_RX_SLV_OUTBOX, task_dcom_rx_slv_outboxes, NULL }, // TASK_ID_DCOM_RX_OUTBX { FLAGS_DCOM_TX_SLV_OUTBOX, task_dcom_tx_slv_outbox, NULL }, // TASK_ID_DCOM_TX_OUTBX { FLAGS_MISC_405_CHECKS, task_misc_405_checks, NULL }, // TASK_ID_MISC_405_CHECKS { FLAGS_DCOM_PARSE_OCC_FW_MSG, task_dcom_parse_occfwmsg, NULL }, // TASK_ID_DCOM_PARSE_FW_MSG { FLAGS_AMEC_SLAVE, task_amec_slave, NULL }, // TASK_ID_AMEC_SLAVE { FLAGS_AMEC_MASTER, task_amec_master, NULL }, // TASK_ID_AMEC_MASTER { FLAGS_CORE_DATA_CONTROL, task_core_data_control, NULL }, // TASK_ID_CORE_DATA_CONTROL { FLAGS_GPU_SM, task_gpu_sm, NULL }, // TASK_ID_GPU_SM { FLAGS_MEMORY_DATA, task_dimm_sm, NULL }, // TASK_ID_DIMM_SM { FLAGS_MEMORY_CONTROL, task_memory_control, (void *) &G_memory_control_task }, // TASK_ID_MEMORY_CONTROL { FLAGS_NEST_DTS, task_nest_dts, NULL }, { FLAGS_24X7, task_24x7, NULL }, // TASK_ID_24X7 { FLAGS_GPE_TIMINGS, task_gpe_timings, NULL }, // TASK_ID_GPE_TIMINGS { FLAGS_GET_TOD, task_get_tod, NULL }, // TASK_ID_GET_TOD { FLAGS_APSS_RESET, task_apss_reset, NULL }, // TASK_APSS_RESET }; const uint8_t G_tick0_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick1_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick2_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick3_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_NEST_DTS, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick4_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick5_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick6_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick7_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick8_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick9_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick10_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick11_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick12_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick13_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick14_seq[] = { TASK_ID_APSS_RESET, TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_CORE_DATA_LOW, TASK_ID_DIMM_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; const uint8_t G_tick15_seq[] = { TASK_ID_APSS_START, TASK_ID_GET_TOD, TASK_ID_GPU_SM, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_MEMORY_CONTROL, TASK_ID_CORE_DATA_CONTROL, TASK_ID_24X7, TASK_ID_POKE_WDT, TASK_ID_GPE_TIMINGS, TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_DCOM_TX_INBX, TASK_ID_AMEC_SLAVE, TASK_ID_AMEC_MASTER, TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_MISC_405_CHECKS, TASK_END }; // The Global Tick Table // This will change as the real tick sequences are developed. const uint8_t *G_tick_table[MAX_NUM_TICKS] = { G_tick0_seq, G_tick1_seq, G_tick2_seq, G_tick3_seq, G_tick4_seq, G_tick5_seq, G_tick6_seq, G_tick7_seq, G_tick8_seq, G_tick9_seq, G_tick10_seq, G_tick11_seq, G_tick12_seq, G_tick13_seq, G_tick14_seq, G_tick15_seq, }; <|start_filename|>src/occ_405/cent/centaur_control.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cent/centaur_control.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _CENTAUR_CONTROL_H #define _CENTAUR_CONTROL_H //************************************************************************* // Includes //************************************************************************* #include <occ_common.h> #include <ssx.h> #include "rtls.h" //#include "gpe_data.h" #include "occ_sys_config.h" #include "memory.h" //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Globals //************************************************************************* //Global memory structures used for centaur task data pointers extern memory_control_task_t G_memory_control_task; //************************************************************************* // Function Prototypes //************************************************************************* //Collect centaur data for all centaur in specified range //void centaur_control( task_t* i_task ); bool centaur_control( memory_control_task_t * i_memControlTask ); //Initialize structures for collecting centaur data. //void centaur_control_init( void ) INIT_SECTION; void centaur_control_init( void ); #endif //_CENTAUR_CONTROL_H <|start_filename|>src/lib/ppc405lib/polling.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/polling.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __POLLING_H__ #define __POLLING_H__ /// \file polling.c /// \brief Library APIs for polling and busy-waiting #include "ssx.h" // Return/Panic codes #define POLLING_TIMEOUT 0x00765501 #define POLLING_ERROR 0x00765502 #define POLLING_CONDITION 0x00765503 #ifndef __ASSEMBLER__ /// Poll for a condition or a timeout with optional sleep /// /// \param[out] o_rc The last return code from calling \a i_condition. This /// will only be valid if the return code from polling() is /// POLLING_CONDITION. This argument may be passed as NULL (0) if the caller /// does not require this information. /// /// \param[in] i_condition A function of two arguments, returning an integer /// return code - 0 for success, non-0 for failure. The first argument is a /// private state or parameter variable. The second argument is used to /// return the truth value of the \a i_condition predicate (0 for false, non-0 /// for true), and is only considered if the return value of \a i_condition is /// 0. /// /// \param[in,out] io_arg The private argument of the \a condition function. /// /// \param[in] i_timeout The maximum amount of time to poll the \a condition /// before declaring a timeout. The special value SSX_WAIT_FOREVER can be /// used to specify polling without timeout. /// /// \param[in] i_sleep If non-0 at entry, then the thread will sleep for this /// interval between polls of the condition. Otherwise the polling is /// continuous. polling() can only be called with i_sleep non-0 from a /// thread context (since interrupt contexts can not block). /// /// polling() implements a generic polling protocol for conditions that can /// not be recognized as interrupt events. polling() polls the \a i_condition /// until either an error is encountered, the condition is true, or the /// polling times out as measured by the SSX timebase. Whenever a timeout is /// detected the condition is polled once more to exclude false timeouts that /// may have been caused by thread preemption. /// /// The \a i_sleep A non-0 value of \a i_sleep specifies that the thread /// should sleep for the given interval between polling tries instead of /// polling continuously. A non-0 \a i_sleep argument is only legal in thread /// contexts. /// /// \retval 0 Success; The condition was satisfied prior to the timeout. /// /// \retval POLLING_TIMEOUT A timeout was detected before the condition became /// valid. /// /// \retval POLLING_ERROR This code is returned if any of the arguments of /// polling() are invalid. /// /// \retval POLLING_CONDITION This code is returned if the \a i_condition /// function returns a non-0 return code. /// /// If the embedded call of ssx_sleep() fails for some reason then the return /// code will be the code returned by ssx_sleep(). int polling(int* o_rc, int (*i_condition)(void* io_arg, int* o_satisfied), void* io_arg, SsxInterval i_timeout, SsxInterval i_sleep); /// A busy-wait loop /// /// \param[in] i_interval The interval of time to busy-wait. The actual /// interval may be more than this if the thread is interrupted. If called /// from a context with interrupts disabled the timing should be very precise. void busy_wait(SsxInterval i_interval); #endif // __ASSEMBLER__ #endif // __POLLING_H__ <|start_filename|>src/lib/ppc405lib/printf.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/printf.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file printf.c /// \brief Clean-room implementation of printf() functions for SSX I/O /// /// For licensing reasons we are required to create our own version of the /// printf() family of functions. This implementation was created without /// reference to or inclusion of any licensed or copyrighted code. /// /// The functions defined in this file have prototypes, behavior and return /// values as defined by C language standards. In the event of an error a /// negative value is returned, generally corresponding to a standard Unix /// 'errno' code. Note that SSX does not support either an application- or /// per-thread 'errno', so the only record of any error is the \a error field /// of the stream. Also note that SSX may be configured to cause a panic if an /// error is detected rather than returning an error code. /// /// This implementation defines a limited but useful subset of the C standard /// for format control. This implementation includes the following: /// /// - \b c, \b d, \b i, \b n, \b p, \b s, \b u, \b x, and \b X conversion /// specifiers, as well as '%%' to output a single '%' /// /// - \b #, \b 0, \b ' ' and \b + flag characters /// /// - Decimal field width specifiers including * (but indirect field widths /// must be positive as left-justification is not supported) /// /// - Decimal precision specifiers (currently only apply to %s formats, may be /// indirect using *) /// /// - \b l, \b ll and \b z length modifiers /// /// \b Notes: /// /// \a If a \c p conversion specifier is used without any flags (\c '%p'), the /// \c p conversion is interptered as if it were \c 0x%08lx for 32-bit address /// machines and \c 0x%016llx for 64-bit address machines. The GCC builtin /// format checker gives warnings about '0' flag characters for \c p /// conversion specifiers, so there is otherwise no 'un-warned' way to get /// this preferred (by some) format of pointer values. If you do include /// explicit flags (e.g., \c %30p) they will be processed as expected. /// /// Similar to how printf() behaves on an X86-Linux machine, a null pointer /// will print as "(null)" with the %s format (unless the precision specifier /// precludes it) and "(nil)" with the %p format. /// /// Note that calling formatted I/O functions on non-blocking streams may fail /// with the -EAGAIN error, and there is no clean way to restart these /// calls. Calling formatted (or any) I/O functions on blocking streams from /// interrupt contexts in SSX is also likely to fail intermittently since /// interrupt contexts can not block in SSX. /// /// \todo I'd really like to implement the '-' flag for /// left-justification. Implementing the precision specifer for integers /// should be done for completeness. #include "ssx.h" #include "ssx_io.h" // Formatting options #define OPTION_ALTERNATE 0x0001 #define OPTION_PAD_ZERO 0x0002 #define OPTION_PLUS_SIGN 0x0004 #define OPTION_FIELD_WIDTH 0x0008 #define OPTION_PRECISION 0x0010 #define OPTION_LONG 0x0020 #define OPTION_LONG_LONG 0x0040 #define OPTION_SIZE_T 0x0080 #define OPTION_UPPERCASE 0x0100 #define OPTION_HEX 0x0200 #define OPTION_SPACE 0x0400 // Generate padding if required, returning the total number of pad characters // output or a negative error code. The 'nchars' argument is the number of // non-pad characters to be output by the caller. #define PAD_SIZE 8 static const char zeros[PAD_SIZE] = {'0', '0', '0', '0', '0', '0', '0', '0'}; static const char blanks[PAD_SIZE] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; static ssize_t pad(FILE *stream, size_t nchars, int options, size_t width) { const char *padchars; size_t chars, written; int rc; if (!(options & OPTION_FIELD_WIDTH) || (nchars >= width)) { return 0; } chars = width - nchars; if (options & OPTION_PAD_ZERO) { padchars = zeros; } else { padchars = blanks; } while (chars) { rc = swrite(stream, (void *)padchars, MIN(chars, PAD_SIZE), &written); if (rc < 0) return rc; chars -= written; } return width - nchars; } // Format a character static ssize_t format_char(FILE *stream, unsigned char c, int options, size_t width) { ssize_t padchars, nchars; int rc; padchars = pad(stream, 1, options, width); if (padchars < 0) return padchars; nchars = padchars + 1; rc = swrite(stream, (void *)(&c), 1, 0); if (rc < 0) return rc; return nchars; } // Format a string // // If the string is the NULL pointer then normally "(null)" is printed // unless the precision is < 6, in which case the empty string is printed. // The specification leaves it as undefined what happens if a string requests // 0 padding; Here we always pad with blanks (although GCC/PowerPC catches // this as an error). static ssize_t format_string(FILE *stream, const char *s, int options, size_t width, size_t precision) { size_t len; ssize_t padchars, nchars; int rc; if (s == 0) { if ((options & OPTION_PRECISION) && (precision < 6)) { s = ""; } else { s = "(null)"; } } len = strlen(s); if (options & OPTION_PRECISION) { len = MIN(len, precision); } options &= ~OPTION_PAD_ZERO; padchars = pad(stream, len, options, width); if (padchars < 0) return padchars; nchars = padchars + len; rc = swrite(stream, (void *)s, len, 0); if (rc < 0) return rc; return nchars; } // Format an integer - signed and unsigned. A 64-bit integer (assumed to be // the longest we'll see) has 20 decimal digits. An extra space is reserved // for the sign. If zero-padding is specified, the sign will be output // separately. static const char lower[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const char upper[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; static ssize_t format_int(FILE *stream, long long int lli, int options, size_t width) { char digits[21]; int rc, k, ndigits, negative, positive, i; ssize_t output; negative = (lli < 0); positive = (lli > 0); // Unpack the integer to characters. The code is optimized for 32-bit // machines where 64-bit division is not built in. The first part of the // loop handles integers requiring a 64-bit divide, the second loop // handles 32-bit integers. if (lli == 0) { digits[20] = '0'; k = 20; } else if (negative) { for (k = 21; lli != (int)lli; digits[--k] = lower[-(lli % 10)], lli = lli / 10); for (i = (int)lli; i != 0; digits[--k] = lower[-(i % 10)], i = i / 10); } else { for (k = 21; lli != (int)lli; digits[--k] = lower[lli % 10], lli = lli / 10); for (i = (int)lli; i != 0; digits[--k] = lower[i % 10], i = i / 10); } ndigits = 21 - k; // Handle other options and output output = 0; if (options & OPTION_PAD_ZERO) { if (negative) { rc = swrite(stream, "-", 1, 0); if (rc < 0) return rc; output++; } else if (positive) { if (options & OPTION_PLUS_SIGN) { rc = swrite(stream, "+", 1, 0); if (rc < 0) return rc; output++; } else if (options & OPTION_SPACE) { rc = swrite(stream, " ", 1, 0); if (rc < 0) return rc; output++; } } rc = pad(stream, ndigits + output, options, width); if (rc < 0) return rc; output += rc; rc = swrite(stream, &(digits[k]), ndigits, 0); if (rc < 0) return rc; output += ndigits; } else { if (negative) { digits[--k] = '-'; ndigits++; } else if (positive) { if (options & OPTION_PLUS_SIGN) { digits[--k] = '+'; ndigits++; } else if (options & OPTION_SPACE) { digits[--k] = ' '; ndigits++; } } rc = pad(stream, ndigits, options, width); if (rc < 0) return rc; output += rc; rc = swrite(stream, &(digits[k]), ndigits, 0); if (rc < 0) return rc; output += ndigits; } return output; } static ssize_t format_unsigned(FILE *stream, unsigned long long ull, int options, size_t width) { char digits[21], *alternate; const char *xchars; int rc, k, ndigits, zero; unsigned u; ssize_t output; zero = (ull == 0); // Determine hex case and alternate string alternate = 0; if (options & OPTION_HEX) { if (options & OPTION_UPPERCASE) { xchars = upper; if (options & OPTION_ALTERNATE) { alternate = "0X"; } } else { xchars = lower; if (options & OPTION_ALTERNATE) { alternate = "0x"; } } } else { xchars = lower; } // Unpack the unsigned integer to characters. The Hex conversions are // easier since they can be done with shift and mask rather than // divison. The code is optimized for a 32-bit machine where 64-bit // division is not built-in. if (zero) { digits[20] = '0'; k = 20; } else if (options & OPTION_HEX) { for (k = 21; ull != (unsigned)ull; digits[--k] = xchars[ull & 0xf], ull = ull >> 4); for (u = (unsigned)ull; u != 0; digits[--k] = xchars[u & 0xf], u = u >> 4); } else { for (k = 21; ull != (unsigned)ull; digits[--k] = xchars[ull % 10], ull = ull / 10); for (u = (unsigned)ull; u != 0; digits[--k] = xchars[u % 10], u = u / 10); } ndigits = 21 - k; // Handle other options and output output = 0; if (options & OPTION_PAD_ZERO) { if (!zero && alternate) { rc = swrite(stream, (void *)alternate, 2, 0); if (rc < 0) return rc; output += 2; } rc = pad(stream, ndigits + output, options, width); if (rc < 0) return rc; output += rc; rc = swrite(stream, &(digits[k]), ndigits, 0); if (rc < 0) return rc; output += ndigits; } else { if (!zero && alternate) { output += 2; } rc = pad(stream, ndigits + output, options, width); if (rc < 0) return rc; output += rc; if (!zero && alternate) { rc = swrite(stream, alternate, 2, 0); if (rc < 0) return rc; output += 2; } rc = swrite(stream, &(digits[k]), ndigits, 0); if (rc < 0) return rc; output += ndigits; } return output; } int vfprintf(FILE *stream, const char *format, va_list argp) { const char *fmt, *scan; int rc, total_chars, options, done; size_t width, precision; int arg_i, *arg_pi; long int arg_li; long long int arg_lli; ssize_t arg_zi; unsigned arg_u; unsigned long arg_lu; unsigned long long arg_llu; size_t arg_zu; char *arg_s; total_chars = 0; fmt = format; while (*fmt) { // Scan until '%' or the end of the format, then output the text. scan = fmt; while (*scan && (*scan != '%')) { scan++; } if (scan != fmt) { rc = swrite(stream, fmt, scan - fmt, 0); if (rc < 0) return rc; total_chars += scan - fmt; } fmt = scan; if (!*fmt) { return total_chars; } fmt++; // We got a '%'. Check for %% and %n. switch (*fmt) { case '\0': SSX_IO_ERROR(stream, EINVAL); break; case '%': rc = swrite(stream, "%", 1, 0); if (rc < 0) return rc; total_chars++; fmt++; continue; case 'n': arg_pi = va_arg(argp, int *); *arg_pi = total_chars; fmt++; continue; } // Collect padding options, if any. Left justification is not // implemeted. options = 0; done = 0; do { switch (*fmt) { case '\0': SSX_IO_ERROR(stream, EINVAL); break; case '#': options |= OPTION_ALTERNATE; break; case '0': options |= OPTION_PAD_ZERO; break; case '+': options |= OPTION_PLUS_SIGN; break; case ' ': options |= OPTION_SPACE; break; case '-': SSX_IO_ERROR(stream, EINVAL); // Left just. not impl. break; default: done = 1; break; } if (!done) { fmt++; } } while (!done); // Collect the field width, if specified. A negative precision // specified as an argument indicates left justification (not // implemented). width = 0; if (isdigit(*fmt)) { options |= OPTION_FIELD_WIDTH; for (; isdigit(*fmt); fmt++) { width = (width * 10) + (*fmt - '0'); } } else if (*fmt == '*') { fmt++; options |= OPTION_FIELD_WIDTH; arg_i = va_arg(argp, int); if (arg_i < 0) { SSX_IO_ERROR(stream, EINVAL); // Left just. not impl. } width = arg_i; } // Collect the precision, if specified. By standard specification an // empty or negative precision is interpreted as 0. precision = 0; if (*fmt == '.') { fmt++; options |= OPTION_PRECISION; if (isdigit(*fmt)) { for(; isdigit(*fmt); fmt++) { precision = (precision * 10) + (*fmt - '0'); } } else if (*fmt == '*') { fmt++; arg_i = va_arg(argp, int); if (arg_i < 0) { arg_i = 0; } precision = arg_i; } } // Collect length modifiers. done = 0; do { switch (*fmt) { case '\0': SSX_IO_ERROR(stream, EINVAL); break; case 'l': if (options & OPTION_LONG) { options &= ~OPTION_LONG; options |= OPTION_LONG_LONG; } else if (options & OPTION_LONG_LONG) { SSX_IO_ERROR(stream, EINVAL); } else { options |= OPTION_LONG; } if (options & OPTION_SIZE_T) { SSX_IO_ERROR(stream, EINVAL); } break; case 'z': if ((options & OPTION_LONG) || (options & OPTION_LONG_LONG)) { SSX_IO_ERROR(stream, EINVAL); } options |= OPTION_SIZE_T; break; default: done = 1; break; } if (!done) { fmt++; } } while (!done); // Use the conversion specifier to format the next argument switch (*fmt) { case 'c': arg_i = va_arg(argp, int); rc = format_char(stream, (unsigned char)arg_i, options, width); if (rc < 0) return rc; total_chars++; break; case 'd': case 'i': if (options & OPTION_LONG) { arg_li = va_arg(argp, long int); rc = format_int(stream, (long long int)arg_li, options, width); } else if (options & OPTION_LONG_LONG) { arg_lli = va_arg(argp, long long int); rc = format_int(stream, (long long int)arg_lli, options, width); } else if (options & OPTION_SIZE_T) { arg_zi = va_arg(argp, ssize_t); rc = format_int(stream, (long long int)arg_zi, options, width); } else { arg_i = va_arg(argp, int); rc = format_int(stream, (long long int)arg_i, options, width); } if (rc < 0) return rc; total_chars += rc; break; case 'p': arg_lu = va_arg(argp, unsigned long); options |= (OPTION_ALTERNATE | OPTION_HEX); if (!(options & OPTION_PAD_ZERO) && !(options & OPTION_FIELD_WIDTH)) { options |= (OPTION_PAD_ZERO | OPTION_FIELD_WIDTH); width = (2 * sizeof(unsigned long)) + 2; /* 0x........ */ } if (arg_lu == 0) { options &= ~OPTION_PRECISION; rc = format_string(stream, "(nil)", options, width, precision); } else { rc = format_unsigned(stream, (unsigned long long)arg_lu, options, width); } if (rc < 0) return rc; total_chars += rc; break; case 's': arg_s = va_arg(argp, char *); rc = format_string(stream, arg_s, options, width, precision); if (rc < 0) return rc; total_chars += rc; break; case 'X': options |= OPTION_UPPERCASE; case 'x': options |= OPTION_HEX; case 'u': if (options & OPTION_LONG) { arg_lu = va_arg(argp, unsigned long); rc = format_unsigned(stream, (unsigned long long)arg_lu, options, width); } else if (options & OPTION_LONG_LONG) { arg_llu = va_arg(argp, unsigned long long); rc = format_unsigned(stream, (unsigned long long)arg_llu, options, width); } else if (options & OPTION_SIZE_T) { arg_zu = va_arg(argp, size_t); rc = format_unsigned(stream, (unsigned long long)arg_zu, options, width); } else { arg_u = va_arg(argp, unsigned); rc = format_unsigned(stream, (unsigned long long )arg_u, options, width); } if (rc < 0) return rc; total_chars += rc; break; default: SSX_IO_ERROR(stream, EINVAL); break; } fmt++; } return total_chars; } int vprintf(const char *format, va_list argp) { return vfprintf(stdout, format, argp); } int fprintf(FILE *stream, const char *format, ...) { va_list argp; int rc; va_start(argp, format); rc = vfprintf(stream, format, argp); va_end(argp); return rc; } int printf(const char *format, ...) { va_list argp; int rc; va_start(argp, format); rc = vfprintf(stdout, format, argp); va_end(argp); return rc; } int printk(const char *format, ...) { va_list argp; int rc; va_start(argp, format); rc = vfprintf(ssxout, format, argp); va_end(argp); return rc; } <|start_filename|>src/occ_gpe1/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occ_gpe1/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2015,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG #Pull in the definitions that affect all makefiles for this image include img_defs.mk #Pull in object file names for the top directory include topfiles.mk ifdef P2P_ENABLE include $(P2P_SRCDIR)/p2pfiles.mk endif PK_MAKE_DIR := $(PK_SRCDIR)/$(PPE_TYPE) OBJS := $(addprefix $(OBJDIR)/, $(TOP_OBJECTS)) PKLIB := $(OBJDIR)/pk/libpk.a COMMONLIB := $(OBJDIR)/commonlib/libcommon.a OCCLIB := $(OBJDIR)/occlib/libocc.a LIB_DIRS += -L$(OBJDIR)/pk -L$(OBJDIR)/commonlib -L$(OBJDIR)/occlib LINK_OBJS = $(OBJS) $(PKLIB) $(COMMONLIB) $(OCCLIB) LINK_SCRIPT = $(addprefix $(OBJDIR)/, linkscript) ifdef P2P_ENABLE P2PLIB := $(OBJDIR)/p2p/libp2p.a LIB_DIRS += -L$(OBJDIR)/p2p LINK_OBJS += $(P2PLIB) endif #default target is to make a binary application image all: $(PPETOOLS_OBJDIR)/ppetracepp $(OBJDIR)/$(IMAGE_NAME).bin $(OBJDIR)/$(IMAGE_NAME).dis #This removes all unecessary headers from the ELF executable $(OBJDIR)/$(IMAGE_NAME).bin $(OBJDIR)/$(IMAGE_NAME).dis: $(OBJDIR)/$(IMAGE_NAME).out $(OBJCOPY) -O binary $< $(OBJDIR)/$(IMAGE_NAME).bin $(OBJDUMP) -S $< > $(OBJDIR)/$(IMAGE_NAME).dis #create a linked ELF executable $(OBJDIR)/$(IMAGE_NAME).out: $(LINK_OBJS) $(LINK_SCRIPT) $(LD) -e __system_reset -N -T$(LINK_SCRIPT) -Map $(OBJDIR)/$(IMAGE_NAME).map \ -Bstatic -o $(OBJDIR)/$(IMAGE_NAME).out $(LIB_DIRS) $(OBJS) \ -locc -lcommon -lpk #pass the link command file through the C preprocessor to evaluate macros and remove comments $(LINK_SCRIPT): link.cmd $(CPP) -E -x c -P $(DEFS) link.cmd -o $(LINK_SCRIPT) #Create an obj directory if needed $(LINK_OBJS) $(OBJS) $(OBJS:.o=.d): | $(OBJDIR) $(OBJDIR): mkdir -p $(OBJDIR) $(PPETOOLS_OBJDIR)/ppetracepp: $(PPETOOLS_OBJDIR) g++ -O3 -w -g -I$(PPETRACEPP_DIR)/ $(PPETRACEPP_DIR)/ppetracepp.C -o $(PPETOOLS_OBJDIR)/ppetracepp $(PPETOOLS_OBJDIR): mkdir -p $(PPETOOLS_OBJDIR) .PHONY: clean $(PKLIB) $(P2PLIB) #Build macro-specific kernel code $(PKLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(PK_MAKE_DIR) #Build the code that is common for all processors (PPEs and 405) $(COMMONLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(COMMONLIB_SRCDIR) #Build the code that is common for all OCC processors (GPEs and 405) $(OCCLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(OCCLIB_SRCDIR) ifdef P2P_ENABLE $(P2PLIB): $(MAKE) -I $(IMAGE_SRCDIR) -C $(P2P_SRCDIR) endif # collect all of the trace hash files for this image into a single trexStringFile .PHONY : tracehash tracehash: mkdir -p $(OBJDIR) $(THASH) -c -d $(OBJDIR) -s $(OBJDIR)/trexStringFile #clean the kernel directory first, then the application level clean clean: rm -fr $(OBJDIR) #Add dependencies to header files ifneq ($(MAKECMDGOALS),clean) -include $(OBJS:.o=.d) endif <|start_filename|>src/occ_gpe0/gpe_get_tod.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/gpe_get_tod.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file gpe_get_tod.c * * This file defines the functions for getting the current value of the Time Of * Day (TOD) register. */ //****************************************************************************** // Includes //****************************************************************************** #include <stdint.h> // For uint*_t #include "pk.h" // For PK_TRACE() and pk_halt() #include "ipc_api.h" // For ipc_msg_t #include "ipc_async_cmd.h" // For ipc_async_cmd_t #include "ppe42_scom.h" // For getscom_abs() #include "gpe_util.h" // For gpe_set_ffdc() #include "get_tod_structs.h" // For gpe_get_tod_args_t #include "gpe_err.h" // For GPE_RC_* #include "pss_constants.h" // For TOD_STATUS_REG and TOD_VALUE_REG //****************************************************************************** // Defines //****************************************************************************** /** * Returns the IS_RUNNING bit within the TOD_STATUS_REG register. * * IS_RUNNING is bit 20 in the register value. Note that bit 0 is the most * significant bit. * * @param reg_value value of TOD_STATUS_REG register * @return IS_RUNNING bit. If 1, the TOD is running. */ #define TOD_IS_RUNNING(reg_value) \ (((uint8_t) (((uint64_t) (reg_value)) >> 43)) & 0x01u) /** * Returns the TOD_VALUE field within the TOD_VALUE_REG register. * * The TOD_VALUE field is located in bits 0:59 of the register value. Note that * bit 0 is the most significant bit. In the returned value we must set the low * order 4 bits (60:63) to 0 rather than right shifting 4 bits. * * @param reg_value value of TOD_VALUE_REG register * @return TOD_VALUE field */ #define TOD_VALUE(reg_value) (((uint64_t) (reg_value)) & 0xFFFFFFFFFFFFFFF0ull) //****************************************************************************** // Functions //****************************************************************************** /** * Reads the value of the TOD_STATUS_REG and TOD_VALUE_REG registers. If the * TOD is running, the current Time Of Day value is stored in the tod field of * the args parameter. * * @param args Arguments passed from the OCC 405 via the IPC framework */ void gpe_read_tod_registers(gpe_get_tod_args_t * args) { // Initialize output arguments to default values args->error.rc = GPE_RC_SUCCESS; args->error.addr = 0; args->error.ffdc = 0; args->tod = TOD_VALUE_UNKNOWN; // Read value of TOD_STATUS_REG register uint64_t l_reg_val; uint32_t rc = getscom_abs(TOD_STATUS_REG, &l_reg_val); if (rc != 0) { gpe_set_ffdc(&(args->error), TOD_STATUS_REG, GPE_RC_SCOM_GET_FAILED, rc); return; } // Check if TOD is running based on TOD_STATUS_REG value. if (!TOD_IS_RUNNING(l_reg_val)) { // TOD is not running. Operating system is likely fixing it. Not an error. return; } // Read value of TOD_VALUE_REG register rc = getscom_abs(TOD_VALUE_REG, &l_reg_val); if (rc != 0) { gpe_set_ffdc(&(args->error), TOD_VALUE_REG, GPE_RC_SCOM_GET_FAILED, rc); return; } // The TOD_VALUE_REG register contains two fields. Get the TOD_VALUE field // and store that as the Time Of Day value. args->tod = TOD_VALUE(l_reg_val); } /** * IPC function that gets the current Time Of Day (TOD) value. * * First reads the TOD_STATUS_REG register to make sure the TOD is running. * Then reads the TOD_VALUE_REG register to get the TOD value. * * @param cmd A pointer to the IPC command message * @param arg IPC function argument. Currently not used. */ void gpe_get_tod(ipc_msg_t * cmd, void * arg) { // Cast command message pointer to more specific type to access cmd_data field ipc_async_cmd_t * async_cmd = (ipc_async_cmd_t *) cmd; // Cast cmd_data field to specific type of arguments for this IPC function gpe_get_tod_args_t * args = (gpe_get_tod_args_t *) async_cmd->cmd_data; // Read the TOD registers to get the TOD value. Store the result in args. gpe_read_tod_registers(args); // Send back a response with IPC success even if ffdc/rc fields are non-zero int rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if (rc != 0) { PK_TRACE("gpe_get_tod: Failed to send response back. Halting GPE0. rc=0x%08X", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } } <|start_filename|>src/occ_405/amec/amec_slave_smh.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ/amec/amec_slave_smh.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_SLAVE_SMH_H #define _AMEC_SLAVE_SMH_H //************************************************************************* // Includes //************************************************************************* #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include <amec_smh.h> #include <amec_amester.h> //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* #define AMEC_SLV_STATE() AMEC_STATE(&G_amec_slv_state); #define AMEC_SLV_SUBSTATE() AMEC_SUBSTATE(&G_amec_slv_state); #define AMEC_SLV_SUB_SUBSTATE() AMEC_SUB_SUBSTATE(&G_amec_slv_state); #define AMEC_SLV_STATE_NEXT() AMEC_STATE_NEXT(&G_amec_slv_state); #define AMEC_SLV_SUBSTATE_NEXT() AMEC_SUBSTATE_NEXT(&G_amec_slv_state); #define AMEC_SLV_SUB_SUBSTATE_NEXT() AMEC_SUB_SUBSTATE_NEXT(&G_amec_slv_state); //************************************************************************* // Structures //************************************************************************* //************************************************************************* // Globals //************************************************************************* extern const smh_tbl_t amec_slv_state_table[AMEC_SMH_STATES_PER_LVL]; extern smh_state_t G_amec_slv_state; extern smh_state_timing_t G_amec_slv_state_timings; extern bool G_apss_lower_pmax_rail; //************************************************************************* // Function Prototypes //************************************************************************* void amec_slv_check_apss_fail(void); void amec_slv_update_main_mem_sensors(void); void amec_update_proc_core_group(uint8_t); // PRE: slave common tasks void amec_slv_common_tasks_pre(void); // POST: slave common tasks void amec_slv_common_tasks_post(void); // Slave States void amec_slv_state_0(void); void amec_slv_state_1(void); void amec_slv_state_2(void); void amec_slv_state_3(void); void amec_slv_state_4(void); void amec_slv_state_5(void); void amec_slv_state_6(void); void amec_slv_state_7(void); // Slave SubState 1 void amec_slv_substate_1_0(void); void amec_slv_substate_1_1(void); void amec_slv_substate_1_2(void); void amec_slv_substate_1_3(void); void amec_slv_substate_1_4(void); void amec_slv_substate_1_5(void); void amec_slv_substate_1_6(void); void amec_slv_substate_1_7(void); // Slave SubState 2 (odd SubStates currently unused) void amec_slv_substate_2_even(void); // Slave SubState 3 void amec_slv_substate_3_0(void); void amec_slv_substate_3_1(void); void amec_slv_substate_3_2(void); void amec_slv_substate_3_3(void); void amec_slv_substate_3_4(void); void amec_slv_substate_3_5(void); void amec_slv_substate_3_6(void); void amec_slv_substate_3_7(void); // Slave SubState 5 void amec_slv_substate_5_0(void); void amec_slv_substate_5_1(void); void amec_slv_substate_5_2(void); void amec_slv_substate_5_3(void); void amec_slv_substate_5_4(void); void amec_slv_substate_5_5(void); void amec_slv_substate_5_6(void); void amec_slv_substate_5_7(void); // Slave SubState 6 called every SubState - check for inband cmd every 4ms void amec_slv_substate_6_all(void); // Slave SubState 7 void amec_slv_substate_7_0(void); void amec_slv_substate_7_1(void); void amec_slv_substate_7_2(void); void amec_slv_substate_7_3(void); void amec_slv_substate_7_4(void); void amec_slv_substate_7_5(void); void amec_slv_substate_7_6(void); void amec_slv_substate_7_7(void); #endif <|start_filename|>src/ppe/pk/kernel/pk_thread_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/kernel/pk_thread_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file pk_thread_init.c /// \brief PK thread API initialization routines /// /// The entry points in this file are routines that are typically used during /// initialization, and their code space could be deallocated and recovered if /// no longer needed by the application after initialization. #include "pk.h" /// Create (initialize) a thread /// /// \param thread A pointer to an PkThread structure to initialize /// /// \param thread_routine The subroutine that implements the thread /// /// \param arg Private data to be passed as the argument to the thread /// routine when it begins execution /// /// \param stack The stack space of the thread /// /// \param stack_size The size of the stack in bytes /// /// \param priority The initial priority of the thread /// /// The \a thread argument must be a pointer to an uninitialized or completed /// or deleted thread. This \c PkThread structure \em is the thread, so this /// memory area must not be modified by the application until the thread /// completes or is deleted. PK can not tell if an PkThread structure is /// currently in use as a thread control block.pk_thread_create() will /// silently overwrite an PkThread structure that is currently in use. /// /// The stack area must be large enough to hold the dynamic stack requirements /// of the entry point routine, and all subroutines and functions that might /// be invoked on any path from the entry point. The stack must also always /// be able to hold the thread context in the event the thread is preempted, /// plus other critical context. PK aligns stack areas in machine-specific /// ways, so that the actual stack area may reduced in size slightly if it is /// not already aligned. /// /// Threads are created runnable but unmapped. A newly created thread will /// not be eligible to run until a call of pk_thread_resume() targets the /// thread. /// /// Return values other than PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_THREAD_AT_CREATE The \a thread is a null (0) pointer. /// /// \retval -PK_INVALID_ARGUMENT_THREAD1 the \a thread_routine is null (0) /// /// \retval -PK_INVALID_ARGUMENT_THREAD2 the \a priority is invalid, /// /// \retval -PK_INVALID_ARGUMENT_THREAD3 the stack area wraps around /// the end of memory. /// /// \retval -PK_STACK_OVERFLOW The stack area at thread creation is smaller /// than the minimum safe size. int pk_thread_create(PkThread *thread, PkThreadRoutine thread_routine, void *arg, PkAddress stack, size_t stack_size, PkThreadPriority priority) { int rc; if (PK_ERROR_CHECK_API) { PK_ERROR_IF(thread == 0, PK_INVALID_THREAD_AT_CREATE); PK_ERROR_IF((thread_routine == 0) || (priority >= PK_THREADS), PK_INVALID_ARGUMENT_THREAD1); } rc = __pk_stack_init(&stack, &stack_size); if (rc) { return rc; } thread->saved_stack_pointer = stack; thread->stack_base = stack; if (PK_STACK_DIRECTION < 0) { thread->stack_limit = stack - stack_size; if (PK_ERROR_CHECK_API) { PK_ERROR_IF(thread->stack_limit > thread->stack_base, PK_INVALID_ARGUMENT_THREAD2); } } else { thread->stack_limit = stack + stack_size; if (PK_ERROR_CHECK_API) { PK_ERROR_IF(thread->stack_limit < thread->stack_base, PK_INVALID_ARGUMENT_THREAD3); } } thread->semaphore = 0; thread->priority = priority; thread->state = PK_THREAD_STATE_SUSPENDED_RUNNABLE; thread->flags = 0; pk_timer_create(&(thread->timer), __pk_thread_timeout, (void *)thread); __pk_thread_context_initialize(thread, thread_routine, arg); return rc; } <|start_filename|>src/occBootLoader/bootMain.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occBootLoader/bootMain.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //************************************************************************* // Includes //************************************************************************* #include <bootMain.h> // boot loader defines #include <occhw_common.h> // Nest frequency constant #include <stddef.h> // offsetof //************************************************************************* // Externs //************************************************************************* extern void __boot_low_level_init; //************************************************************************* // Image header //************************************************************************* IMAGE_HEADER(G_bootImageHdr,__boot_low_level_init,BOOT_LOADER_ID, ID_NUM_INVALID); //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* //************************************************************************* // Structures //************************************************************************* //************************************************************************* // Globals //************************************************************************* //************************************************************************* // Function Prototypes //************************************************************************* //Forward declaration uint32_t boot_test_sram(uint32_t i_start, uint32_t i_end); uint32_t boot_load_405(const imageHdr_t *i_hdrAddr); uint32_t boot_load_gpe0(uint32_t i_startAddr, uint32_t i_size, uint8_t * i_srcPtr); uint32_t boot_load_gpe1(uint32_t i_startAddr, uint32_t i_size, uint8_t * i_srcPtr); uint32_t calChecksum(const uint32_t i_startAddr ,const uint32_t i_sz, bool i_gpeFile); //************************************************************************* // Functions //************************************************************************* // Function Specification // // Name: boot_main // // Description: boot main will test SRAM, copy main application image from // main memory to SRAM, validate checksum and call ssx_boot. // // End Function Specification void main() { uint32_t l_rc = 0; uint32_t l_gpe0_start_addr = 0; uint32_t l_gpe1_start_addr = 0; uint8_t* l_gpe0_src_ptr = 0; uint8_t* l_gpe1_src_ptr = 0; // set checkpoint to boot test SRAM WRITE_TO_SPRG0(BOOT_TEST_SRAM_CHKPOINT); #ifndef VPO // This is ifdef'd out b/c it takes too long to run in VPO // Only test GPE0/GPE1/405 SRAM because SGPE and PGPE are // loaded before us. // If failed to test SRAM, write failed return code to SPRG1 and halt l_rc = boot_test_sram(SRAM_START_ADDRESS_GPE0, SRAM_END_ADDRESS_GPE1); if(0 != l_rc) { WRITE_TO_SPRG1_AND_HALT(l_rc); } l_rc = boot_test_sram(SRAM_START_ADDRESS_405, SRAM_END_ADDRESS_405); if(0 != l_rc) { WRITE_TO_SPRG1_AND_HALT(l_rc); } #endif // set imageHdr_t pointer to point to boot image header to get to boot // image size. This way we can get to main application image header. imageHdr_t *l_hdrPtr = (imageHdr_t *)(G_bootImageHdr.start_addr + G_bootImageHdr.image_size); // set checkpoint to boot load main application image to SRAM WRITE_TO_SPRG0(BOOT_LOAD_IMAGE_CHKPOINT); // Load main application image to SRAM including main application header l_rc = boot_load_405(l_hdrPtr); // If failed to load image, write failed return code to SPRG1 and halt if(0 != l_rc) { WRITE_TO_SPRG1_AND_HALT(l_rc); } // set checkpoint to load gpe0 into SRAM WRITE_TO_SPRG0(BOOT_LOAD_GPE0_CHKPOINT); // Load GPE0 l_gpe0_start_addr = (uint32_t) (((uint32_t) l_hdrPtr) + l_hdrPtr->image_size); l_gpe0_src_ptr = (uint8_t*) (((uint32_t)l_hdrPtr) + l_hdrPtr->image_size); l_rc = boot_load_gpe0(l_gpe0_start_addr, l_hdrPtr->gpe0_size, l_gpe0_src_ptr); if(0 != l_rc) { WRITE_TO_SPRG1_AND_HALT(l_rc); } WRITE_TO_SPRG0(BOOT_LOAD_GPE1_CHKPOINT); // Load GPE1 l_gpe1_start_addr = l_gpe0_start_addr + l_hdrPtr->gpe0_size; l_gpe1_src_ptr = (uint8_t*) (((uint32_t)l_gpe0_src_ptr) + l_hdrPtr->gpe0_size); l_rc = boot_load_gpe1(l_gpe1_start_addr, l_hdrPtr->gpe1_size, l_gpe1_src_ptr); if(0 != l_rc) { WRITE_TO_SPRG1_AND_HALT(l_rc); } //========================================== // Calculate checksums and verify they match //========================================== // set checkpoint to calculate checksum WRITE_TO_SPRG0(BOOT_CALCULTE_CHKSUM_CHKPOINT_405); // Calculate checksum for 405 SRAM uint32_t l_checksum = calChecksum(l_hdrPtr->start_addr, l_hdrPtr->image_size, false); // If checksum does not match, store bad checksum into SPRG1 and halt if(l_checksum != l_hdrPtr->checksum) { WRITE_TO_SPRG1_AND_HALT(l_checksum); } WRITE_TO_SPRG0(BOOT_CALCULTE_CHKSUM_CHKPOINT_GPE0); // Calculate checksum for GPE0 SRAM l_checksum = calChecksum(SRAM_START_ADDRESS_GPE0, l_hdrPtr->gpe0_size, true); // If checksum does not match, store bad checksum into SPRG1 and halt if(l_checksum != l_hdrPtr->gpe0_checksum) { WRITE_TO_SPRG1_AND_HALT(l_checksum); } WRITE_TO_SPRG0(BOOT_CALCULTE_CHKSUM_CHKPOINT_GPE1); // Calculate checksum for GPE1 SRAM l_checksum = calChecksum(SRAM_START_ADDRESS_GPE1, l_hdrPtr->gpe1_size, true); // If checksum does not match, store bad checksum into SPRG1 and halt if(l_checksum != l_hdrPtr->gpe1_checksum) { WRITE_TO_SPRG1_AND_HALT(l_checksum); } // set checkpoint to get nest frequency WRITE_TO_SPRG0(BOOT_GET_NEST_FREQ_CHKPOINT); // set checkpoint to call to SSX_BOOT WRITE_TO_SPRG0(BOOT_SSX_BOOT_CALL_CHKPOINT); // create function pointer pointing to main application header entry point // address. void (*execute_ssx_boot)(void) = (void (*)(void))l_hdrPtr->ep_addr; (*execute_ssx_boot)(); // set checkpoint to return from ssx_boot. This should never happen so // halt at this point. WRITE_TO_SPRG0(BOOT_SSX_RETURNED_CHKPOINT); WRITE_TO_SPRG1_AND_HALT(l_hdrPtr->ep_addr); } // Function Specification // // Name: calChecksum // // Description: Calculate checksum starting at given address and given size // bytes. Skip checksum field in the imageHdr_t while calculating // checksum // // End Function Specification uint32_t calChecksum(const uint32_t i_startAddr, const uint32_t i_sz, bool i_gpeFile) { uint32_t l_checksum = 0; uint32_t l_counter = 0; uint8_t *l_srcPtr = (uint8_t *)(i_startAddr); while(l_counter < i_sz) { if( (l_counter == (uint32_t)(offsetof(imageHdr_t,checksum))) && !i_gpeFile ) { l_counter = ((uint32_t)(offsetof(imageHdr_t,checksum)) + sizeof(G_bootImageHdr.checksum)); } else if ( (l_counter == (uint32_t)(offsetof(imageHdr_t,gpe0_checksum))) && !i_gpeFile ) { l_counter = ((uint32_t)(offsetof(imageHdr_t,gpe0_checksum)) + sizeof(G_bootImageHdr.gpe0_checksum)); } else if ( (l_counter == (uint32_t)(offsetof(imageHdr_t,gpe1_checksum))) && !i_gpeFile ) { l_counter = ((uint32_t)(offsetof(imageHdr_t,gpe1_checksum)) + sizeof(G_bootImageHdr.gpe1_checksum)); } else { l_checksum += (*(l_srcPtr + l_counter)); l_counter = l_counter + 1; } } return l_checksum; } // Function Specification // // Name: boot_load_image // // Description: This function copies main application (405) // image from main memory to SRAM // // End Function Specification uint32_t boot_load_405(const imageHdr_t* i_hdrAddr) { uint32_t l_rc = 0x0; uint32_t l_mainAppDestRange = (i_hdrAddr->start_addr) + (i_hdrAddr->image_size-1); // Make sure main application destination rang address falls within SRAM // range. if((l_mainAppDestRange < SRAM_START_ADDRESS_405) || (l_mainAppDestRange > SRAM_END_ADDRESS_405)) { // Return destination range address if address is out of range and // address is not zero. If address is zero, then return eye-catcher // address. if(l_mainAppDestRange != 0) { l_rc = l_mainAppDestRange; } else { l_rc = EYE_CATCHER_ADDRESS; } } // Make sure main application start address falls within SRAM range else if((i_hdrAddr->start_addr < SRAM_START_ADDRESS_405) || (i_hdrAddr->start_addr > SRAM_END_ADDRESS_405)) { // Return start address if address is out of range and // address is not zero. If address is zero, then return eye-catcher // address. if(i_hdrAddr->start_addr != 0) { l_rc = i_hdrAddr->start_addr; } else { l_rc = EYE_CATCHER_ADDRESS; } } else { // At this point we know that main application destination address // is within SRAM range. // Now copy main application (405) from main memory to SRAM. uint8_t *l_srcPtr = (uint8_t *)(i_hdrAddr); uint8_t *l_destPtr = (uint8_t *)(i_hdrAddr->start_addr); uint32_t l_numWords = i_hdrAddr->image_size; while(l_numWords != 0) { *l_destPtr = *l_srcPtr; l_destPtr++; l_srcPtr++; l_numWords--; } } return l_rc; } uint32_t boot_load_gpe0(uint32_t i_startAddr, uint32_t i_size, uint8_t * i_srcPtr) { uint8_t* l_srcPtr = i_srcPtr; uint32_t l_rc = 0x0; uint32_t l_gpe0DestRange = SRAM_START_ADDRESS_GPE0 + i_size - 1; // Make sure GPE0 destination range address falls within its SRAM range. if(l_gpe0DestRange > SRAM_END_ADDRESS_GPE0) { // Return destination range address if address is out of range and // address is not zero. If address is zero, then return eye-catcher // address. if(l_gpe0DestRange != 0) { l_rc = l_gpe0DestRange; } else { l_rc = EYE_CATCHER_ADDRESS; } } else { // At this point we know that the destination address of GPE0 // is within SRAM range. Now copy GPE0 from main memory to SRAM. uint8_t *l_destPtr = (uint8_t *)(SRAM_START_ADDRESS_GPE0); uint32_t l_numWords = i_size; while(l_numWords != 0) { *l_destPtr = *l_srcPtr; l_destPtr++; l_srcPtr++; l_numWords--; } } return l_rc; } uint32_t boot_load_gpe1(uint32_t i_startAddr, uint32_t i_size, uint8_t * i_srcPtr) { uint8_t* l_srcPtr = i_srcPtr; uint32_t l_rc = 0x0; uint32_t l_gpe1DestRange = SRAM_START_ADDRESS_GPE1 + i_size - 1; // Make sure GPE1 destination range address falls within its SRAM range. if (l_gpe1DestRange > SRAM_END_ADDRESS_GPE1) { // Return destination range address if address is out of range and // address is not zero. If address is zero, then return eye-catcher // address. if(l_gpe1DestRange != 0) { l_rc = l_gpe1DestRange; } else { l_rc = EYE_CATCHER_ADDRESS; } } else { // At this point we know that the destination address of GPE1 // is within SRAM range. Now copy GPE1 from main memory to SRAM. uint8_t *l_destPtr = (uint8_t *)(SRAM_START_ADDRESS_GPE1); uint32_t l_numWords = i_size; while(l_numWords != 0) { *l_destPtr = *l_srcPtr; l_destPtr++; l_srcPtr++; l_numWords--; } } return l_rc; } // Function Specification // // Name: boot_test_sram // // Description: This function tests SRAM by writing some bit pattern and // verifying it back through read // // // End Function Specification uint32_t boot_test_sram(uint32_t i_start, uint32_t i_end) { uint32_t l_rc = 0; // Point start to SRAM start address uint32_t *l_startPtr = (uint32_t *) i_start; // Copy bit pattern from start until SRAM end address while((uint32_t)l_startPtr < i_end) { *l_startPtr = SRAM_TEST_BIT_PATTERN; l_startPtr++; } // Reset start pointer to point to SRAM start Address l_startPtr = (uint32_t *) i_start; //Read and verify bit pattern that was written. If pattern does not match, // return address that failed to match the pattern. while((uint32_t)l_startPtr < i_end) { if((*l_startPtr) != SRAM_TEST_BIT_PATTERN) { l_rc = (uint32_t)l_startPtr; break; } l_startPtr++; } return l_rc; } <|start_filename|>src/ppe/pk/ppe42/eabi.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/eabi.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // assuming link script instructs the c++ compiler to put // ctor_start_address and ctor_end_address in .rodata //extern void (*ctor_start_address)() __attribute__ ((section (".rodata"))); //extern void (*ctor_end_address)() __attribute__((section(".rodata"))); #ifdef __cplusplus extern "C" #endif __attribute__((weak)) void __eabi() { // This is the default eabi and can be overridden. // eabi environment is already set up by the PK kernel // Call static C++ constructors if you use C++ global/static objects //void(**ctors)() = &ctor_start_address; //while(ctors != &ctor_end_address) //{ // (*ctors)(); // ctors++; //} } <|start_filename|>src/occ_gpe1/pk_app_cfg.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/pk_app_cfg.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PK_APP_CFG_H__ #define __PK_APP_CFG_H__ /// \file pk_app_cfg.h /// \brief Application specific overrides go here. /// #include "global_app_cfg.h" #ifndef SIMICS_ENVIRONMENT #define SIMICS_ENVIRONMENT 0 #endif #if SIMICS_ENVIRONMENT #pragma message "Building for Simics!" #endif /// Static configuration data for external interrupts: /// /// IRQ#, TYPE, POLARITY, ENABLE /// #define APPCFG_EXT_IRQS_CONFIG \ OCCHW_IRQ_CHECK_STOP_GPE1 OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_IPI_SCOM OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_IPI1_HI_PRIORITY OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_IPI1_LO_PRIORITY OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ /// The Instance ID of the occ processor that this application is intended to run on /// 0-3 -> GPE, 4 -> 405 #define APPCFG_OCC_INSTANCE_ID 1 // This application will statically initialize it's external interrupt table #define STATIC_IRQ_TABLE #define STATIC_IPC_TABLES // PBA Slave allocated to Gpe 1 is PBA_SLAVE 2. SET PBASLVCTLN to 2 here. #define PBASLVCTLN 2 #define PPE42_MACHINE_CHECK_HANDLER \ b __gpe1_machine_check_handler #endif /*__PK_APP_CFG_H__*/ <|start_filename|>src/occ_405/sensor/sensor.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <sensor.h> // sensor structure and other defines #include <occ_common.h> // For size_t needed by memset #include <string.h> // For memset #include "ssx_io.h" // For sprintf #include <occ_service_codes.h> // OCC reason codes #include <sensor_service_codes.h> // sensor module ids #include <trac.h> // Trace macros #include <get_tod_structs.h> // For TOD_VALUE_UNKNOWN #define UINT16_MIN 0 // Global sensor counter uint32_t G_amec_sensor_count = 0; // See header file for description volatile uint64_t G_tod = TOD_VALUE_UNKNOWN; void sensor_init(sensor_t * io_sensor_ptr, const uint16_t i_gsid, const uint16_t * i_miniSnsrPtr ) INIT_SECTION; void sensor_init_all(void) INIT_SECTION; // Function Specification // // Name: sensor_init // // Description: Initialize global sensor list. // // End Function Specification void sensor_init(sensor_t * io_sensor_ptr, const uint16_t i_gsid, const uint16_t * i_miniSnsrPtr ) { // check if input pointers are valid and global sensor count is // within range. // Note: Don't need to check i_miniSnsrPtr here as it can be NULL if(( io_sensor_ptr != NULL) && (G_amec_sensor_count < MAX_AMEC_SENSORS)) { // zero out sensor pointer memset(io_sensor_ptr,0x0,sizeof(sensor_t)); io_sensor_ptr->gsid = i_gsid; io_sensor_ptr->status.reset = 1; // set mini sensor pointer to point to i_miniSnsrPtr. i_miniSnsrPtr can // be NULL io_sensor_ptr->mini_sensor = (uint16_t*)i_miniSnsrPtr; G_amec_sensor_count++; } // end valid input and max sensor count check else { TRAC_ERR("Invalid input parameters OR Number of " "sensor is out of range. Current sensor count: 0x%x, " "max allowed: 0x%x",G_amec_sensor_count,MAX_AMEC_SENSORS); } } // Function Specification // // Name: sensor_clear_minmax // // Description: Clears minimum and maximum fields in the sensor structure. // i_clear_type contains one or more values OR'd together from the // AMEC_SENSOR_CLEAR_TYPE enumeration. // // End Function Specification void sensor_clear_minmax(sensor_t * io_sensor_ptr, AMEC_SENSOR_CLEAR_TYPE i_clear_type) { if (io_sensor_ptr != NULL) { if (i_clear_type & AMEC_SENSOR_CLEAR_SAMPLE_MINMAX) { io_sensor_ptr->sample_min = UINT16_MAX; io_sensor_ptr->sample_max = UINT16_MIN; // If it has vector sensor, clear max and min position if (io_sensor_ptr->vector != NULL) { io_sensor_ptr->vector->max_pos = VECTOR_SENSOR_DEFAULT_VAL; io_sensor_ptr->vector->min_pos = VECTOR_SENSOR_DEFAULT_VAL; } } if (i_clear_type & AMEC_SENSOR_CLEAR_CSM_SAMPLE_MINMAX) { io_sensor_ptr->csm_sample_min = UINT16_MAX; io_sensor_ptr->csm_sample_max = UINT16_MIN; } if (i_clear_type & AMEC_SENSOR_CLEAR_PROFILER_SAMPLE_MINMAX) { io_sensor_ptr->profiler_sample_min = UINT16_MAX; io_sensor_ptr->profiler_sample_max = UINT16_MIN; } if (i_clear_type & AMEC_SENSOR_CLEAR_JOB_S_SAMPLE_MINMAX) { io_sensor_ptr->job_s_sample_min = UINT16_MAX; io_sensor_ptr->job_s_sample_max = UINT16_MIN; } } else { TRAC_ERR("Invalid input parameters "); } } // Function Specification // // Name: sensor_reset // // Description: Reset sensor fields // // End Function Specification void sensor_reset( sensor_t * io_sensor_ptr) { if( io_sensor_ptr != NULL) { io_sensor_ptr->timestamp = 0x0; io_sensor_ptr->accumulator = 0x0; io_sensor_ptr->sample = 0x0; // clear mini sensor value if( io_sensor_ptr->mini_sensor != NULL) { *(io_sensor_ptr->mini_sensor) = 0x0; } sensor_clear_minmax(io_sensor_ptr, AMEC_SENSOR_CLEAR_ALL_MINMAX); io_sensor_ptr->status.reset = 0; } else { TRAC_ERR("Invalid input parameters "); } } // Function Specification // // Name: sensor_vectorize // // Description: vectorize sensor // // End Function Specification void sensor_vectorize( sensor_t * io_sensor_ptr, vectorSensor_t * io_vec_sensor_ptr, const VECTOR_SENSOR_OP i_op) { if( (io_vec_sensor_ptr != NULL) && (io_sensor_ptr != NULL)) { // assign to sensor vector pointer io_sensor_ptr->vector = io_vec_sensor_ptr; // zero out vector sensor and set operation memset(io_vec_sensor_ptr,0x0,sizeof(vectorSensor_t)); io_vec_sensor_ptr->operation = i_op; } else { TRAC_ERR("Invalid input sensor pointer"); } } // Function Specification // // Name: sensor_update_minmax // // Description: Updates minimum and maximum fields in the sensor structure. // // Implementation Notes: // * This is an internal function so we don't validate parameters // // End Function Specification void sensor_update_minmax(sensor_t * io_sensor_ptr, uint16_t i_sensor_value) { // Update sample min/max fields if needed if (i_sensor_value < io_sensor_ptr->sample_min) { io_sensor_ptr->sample_min = i_sensor_value; } if (i_sensor_value > io_sensor_ptr->sample_max) { io_sensor_ptr->sample_max = i_sensor_value; } // Update CSM sample min/max fields if needed if (i_sensor_value < io_sensor_ptr->csm_sample_min) { io_sensor_ptr->csm_sample_min = i_sensor_value; } if (i_sensor_value > io_sensor_ptr->csm_sample_max) { io_sensor_ptr->csm_sample_max = i_sensor_value; } // Update profiler sample min/max fields if needed if (i_sensor_value < io_sensor_ptr->profiler_sample_min) { io_sensor_ptr->profiler_sample_min = i_sensor_value; } if (i_sensor_value > io_sensor_ptr->profiler_sample_max) { io_sensor_ptr->profiler_sample_max = i_sensor_value; } // Update job scheduler sample min/max fields if needed if (i_sensor_value < io_sensor_ptr->job_s_sample_min) { io_sensor_ptr->job_s_sample_min = i_sensor_value; } if (i_sensor_value > io_sensor_ptr->job_s_sample_max) { io_sensor_ptr->job_s_sample_max = i_sensor_value; } } // Function Specification // // Name: sensor_update // // Description: Update sensor // // End Function Specification void sensor_update( sensor_t * io_sensor_ptr, const uint16_t i_sensor_value) { if( io_sensor_ptr != NULL) { // reset sensors if requested if( io_sensor_ptr->status.reset == 1) { sensor_reset(io_sensor_ptr); } // set timestamp to current time of day io_sensor_ptr->timestamp = G_tod; // update sample value io_sensor_ptr->sample = i_sensor_value; // update min/max values if needed sensor_update_minmax(io_sensor_ptr, i_sensor_value); // If this sensor has mini sensor, update it's value if( io_sensor_ptr->mini_sensor != NULL) { *(io_sensor_ptr->mini_sensor) = i_sensor_value; } // add sample value to accumulator io_sensor_ptr->accumulator += i_sensor_value; // increment update tag io_sensor_ptr->update_tag += 1; } else { TRAC_ERR("Invalid sensor pointer"); } } // Function Specification // // Name: sensor_op_min // // Description: Perform min operation on vector sensor // // End Function Specification uint16_t sensor_op_min(const vectorSensor_t * i_vecSensorPtr, uint8_t * o_position) { uint16_t l_value = UINT16_MAX; uint16_t i = 0; // Internal function so not checking for input NULL pointers // traverse through enabled vector sensors to find the minimum value for(; i < i_vecSensorPtr->size; i++) { // check if sensor is enabled if( i_vecSensorPtr->elem_enabled[i] == 1) { if( i_vecSensorPtr->source_ptr[i]->sample < l_value) { l_value = i_vecSensorPtr->source_ptr[i]->sample; *o_position = i; } } // end element enabled check } // end for loop return l_value; } // Function Specification // // Name: sensor_op_max // // Description: Perform max operation for vector sensor // // End Function Specification uint16_t sensor_op_max(const vectorSensor_t * i_vecSensorPtr, uint8_t * o_position) { uint16_t l_value = UINT16_MIN; uint16_t i = 0; // Internal function so not checking for input NULL pointers // traverse through enabled vector sensors to find the maximum value for(; i < i_vecSensorPtr->size; i++) { // Check if element is enabled if( i_vecSensorPtr->elem_enabled[i] == 1) { if( i_vecSensorPtr->source_ptr[i]->sample > l_value) { l_value = i_vecSensorPtr->source_ptr[i]->sample; *o_position = i; } }// end element enabled check } // end for loop return l_value; } // Function Specification // // Name: sensor_op_avg // // Description: Perform average operation for vector sensor // // End Function Specification uint16_t sensor_op_avg(const vectorSensor_t * i_vecSensorPtr, const uint16_t i_threshold) { uint32_t l_sum = 0; uint16_t i = 0; uint16_t l_number = 0; // Internal function so not checking for input NULL pointers // traverse through enabled vector sensors to get sum of sensor sample for(; i < i_vecSensorPtr->size; i++) { // check if element is enabled if( i_vecSensorPtr->elem_enabled[i] == 1) { // Include sample only if it is higher than threshold if( i_vecSensorPtr->source_ptr[i]->sample > i_threshold) { l_number++; l_sum += i_vecSensorPtr->source_ptr[i]->sample; } } // end element enabled check } // end for loop // Calculate average if( l_number != 0) { l_sum = l_sum / l_number; } return l_sum; } // Function Specification // // Name: sensor_vector_update // // Description: Update Vector Sensor // // End Function Specification void sensor_vector_update( sensor_t * io_sensor_ptr,const uint32_t i_threshold) { if( io_sensor_ptr != NULL) { // Reset sensor if requested if( io_sensor_ptr->status.reset == 1) { sensor_reset(io_sensor_ptr); } // Perform vector sensor operation and update sensor if( io_sensor_ptr->vector != NULL) { uint16_t l_value = 0; uint8_t l_position = 0; // Min operation if( VECTOR_OP_MIN == io_sensor_ptr->vector->operation) { // calculate min value and get sensor position holding min value l_value = sensor_op_min(io_sensor_ptr->vector, &l_position); // set min position in vector sensor io_sensor_ptr->vector->min_pos = l_position; // Update only if needed if( l_value != UINT16_MAX) { // update sensor with new min value sensor_update(io_sensor_ptr,l_value); } } // Max operation else if( VECTOR_OP_MAX == io_sensor_ptr->vector->operation) { // calculate max value and get sensor position holding max value l_value = sensor_op_max(io_sensor_ptr->vector, &l_position); // set max position in vector sensor io_sensor_ptr->vector->max_pos = l_position; // Update only if needed if( l_value != UINT16_MIN) { // update sensor with new max value sensor_update(io_sensor_ptr,l_value); } } // Average operation else if( VECTOR_OP_AVG == io_sensor_ptr->vector->operation) { // Calculate average of the sensor sample l_value = sensor_op_avg(io_sensor_ptr->vector,i_threshold); // Update only if needed if( l_value != 0) { // update sensor with new average value sensor_update(io_sensor_ptr,l_value); } } // Unsupported operation else { TRAC_ERR("Unsupported vector sensor operation: 0x%x", io_sensor_ptr->vector->operation); } } // end valid vector sensor check else { TRAC_ERR("This sensor does not have vector sensor"); } } else { TRAC_ERR("Invalid input sensor pointer"); } } // Function Specification // // Name: getSensorByGsid // // Description: Get sensor data using GSID (Global Sensor ID) // // End Function Specification sensor_t * getSensorByGsid( const uint16_t i_gsid) { sensor_t * l_sensorPtr = NULL; // check if input gsid is within range. Return sensor pointer if within // range. Else return NULL if( i_gsid < G_amec_sensor_count) { l_sensorPtr = G_amec_sensor_list[i_gsid]; } return l_sensorPtr; } // Function Specification // // Name: sensor_vector_elem_enable // // Description: Enable/disable vector sensor element. This interface can be // used at runtime // // End Function Specification void sensor_vector_elem_enable( vectorSensor_t* io_sensor_vector_ptr, const uint8_t i_loc, const uint8_t i_enable) { if( io_sensor_vector_ptr != NULL) { // check if location of the vector sensor is within range if( i_loc < io_sensor_vector_ptr->size) { // set element enabled io_sensor_vector_ptr->elem_enabled[i_loc] = i_enable; } else { TRAC_ERR("Invalid input location: 0x%x, max size: 0x%x", i_loc,io_sensor_vector_ptr->size); } } else { TRAC_ERR("NULL input vector sensor pointer"); } } // Function Specification // // Name: sensor_vector_elem_add // // Description: Add element to the vector sensor. If element at the given // location is already present, it will be overwritten. // // End Function Specification void sensor_vector_elem_add( vectorSensor_t* io_sensor_vector_ptr, const uint8_t i_loc, const sensor_t * i_elemPtr) { if( (io_sensor_vector_ptr == NULL) || (i_elemPtr == NULL ) || (i_loc >= MAX_VECTOR_SENSORS)) { TRAC_ERR("Invalid input parameters. Either pointers are NULL or " "location is out of range i_loc: 0x%x,max allowed: 0x%x", i_loc,MAX_VECTOR_SENSORS); } else if( (i_loc > io_sensor_vector_ptr->size)) { TRAC_ERR("Invalid location. Location does not make element contiguous " "i_loc: 0x%x,current vector size: 0x%x",i_loc, io_sensor_vector_ptr->size); } else { // Increase size if spot is empty. Else we are overwriting existing // slot so no need to increment vector size if(io_sensor_vector_ptr->source_ptr[i_loc] == NULL) { io_sensor_vector_ptr->size++; } // set element and enable it. io_sensor_vector_ptr->source_ptr[i_loc] = (sensor_t*)i_elemPtr; io_sensor_vector_ptr->elem_enabled[i_loc] = 1; } } // Function Specification // // Name: sensor_init_all // // Description: Initialize all sensors in the global sensor list. // // End Function Specification void sensor_init_all(void) { int i; int l_num_entries = NUMBER_OF_SENSORS_IN_LIST; const sensor_ptr_t * l_argPtrSensor = &G_amec_sensor_list[0]; const minisensor_ptr_t * l_argPtrMiniSensor = &G_amec_mini_sensor_list[0]; for(i=0; i < l_num_entries; i++) { sensor_init(l_argPtrSensor[i], i, l_argPtrMiniSensor[i]); } // If G_amec_sensor_count doesn't match the number of sensors, we must have // failed to initialize one or more sensors. if(NUMBER_OF_SENSORS_IN_LIST != G_amec_sensor_count) { TRAC_ERR("Sensor Initialization Failed to initialize all sensors"); /* @ * @errortype * @moduleid SENSOR_INITIALIZE * @reasoncode INTERNAL_FAILURE * @userdata1 G_amec_sensor_count - number of sensors initialized * @userdata2 NUMBER_OF_SENSORS_IN_LIST - total number of OCC sensors * @userdata4 OCC_NO_EXTENDED_RC * @devdesc Firmware internal failure initializing sensors */ errlHndl_t l_err = createErrl( SENSOR_INITIALIZE, // Module ID INTERNAL_FAILURE, // Reason Code // @wb003 OCC_NO_EXTENDED_RC, // Extended reason code ERRL_SEV_PREDICTIVE, // Severity NULL, // Trace 0, // Trace Size G_amec_sensor_count, // UserData 1 NUMBER_OF_SENSORS_IN_LIST // UserData 2 ); commitErrl(&l_err); } TRAC_IMP("Sensor Initialization Complete"); } <|start_filename|>src/ppe/pk/ppe42/ppe42_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppe42_init.c /// \brief PPE42 initialization routines /// /// The entry points in this file are routines that are typically used during /// initialization, and their code space could be deallocated and recovered if /// no longer needed by the application after initialization. #include "pk.h" #include "pk_trace.h" // Note that __ppe42_system_setup() is called from the PK bootloader early // in the initialization, at a point before the aplication has enabled // interrupts. // This function is expected to be defined by the macro specific code (GPE, CME, SBE) void __hwmacro_setup(void); void __ppe42_system_setup() { //Only do this if the application hasn't provided a static table definition #ifndef STATIC_IRQ_TABLE PkIrqId irq; // Initialize the interrupt vectors. for (irq = 0; irq < EXTERNAL_IRQS; irq++) { __ppe42_irq_handlers[irq].handler = __ppe42_default_irq_handler; } //NOTE: EXTERNAL_IRQS is the phantom interrupt assigned irq __ppe42_irq_handlers[irq].handler = __ppe42_phantom_irq_handler; #endif /*STATIC_IRQ_TABLE*/ // Initialize special interrupt handlers __ppe42_fit_routine = __ppe42_default_irq_handler; __ppe42_fit_arg = 0; __ppe42_watchdog_routine = __ppe42_default_irq_handler; __ppe42_watchdog_arg = 0; //Clear all status bits in the TSR mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS); #ifdef APPCFG_USE_EXT_TIMEBASE //Enable the DEC interrupt and configure it to use the external dec_timer signal mtspr(SPRN_TCR, TCR_DIE | TCR_DS); #else //Enable the DEC interrupt and configure it to use the internal clock signal mtspr(SPRN_TCR, TCR_DIE); #endif /* APPCFG_USE_EXT_TIMEBASE */ #if PK_TIMER_SUPPORT #if PK_TRACE_SUPPORT extern PkTraceBuffer g_pk_trace_buf; //set the ppe instance id g_pk_trace_buf.instance_id = (uint16_t)(mfspr(SPRN_PIR) & PIR_PPE_INSTANCE_MASK); #endif /* PK_TRACE_SUPPORT */ #endif /* PK_TIMER_SUPPORT */ //call macro-specific setup __hwmacro_setup(); } <|start_filename|>src/occ_405/linkocc.cmd<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/linkocc.cmd $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // Description // This linker script creates SRAM images of SSX applications for PgP. This // script is processed through the C proprocessor to create // configuration-dependent images. // // All sections with different MMU protection properties are 1KB-aligned, even // when linked in real-addressing mode. // // NB: According to *info* manual for ld, it should not be necessary to specify // the '.' in the section commands, e.g., // // .data.startup . : { *(.data.startup) } > sram // // However without these the sections are not aligned properly, as the linker // seems to ignore the LC and move the section 'backwards' until it abuts // (aligned) with the previous one. // // Info on PPC binaries: // http://devpit.org/wiki/Debugging_PowerPC_ELF_Binaries // Need to do this so that elf32-powerpc is not modified! #undef powerpc #ifndef INITIAL_STACK_SIZE #define INITIAL_STACK_SIZE 2000 #endif // Always include occLinkInputFile for GNU builds //#ifdef OCCMK INCLUDE occLinkInputFile //#endif OUTPUT_FORMAT(elf32-powerpc); // Define the beginning of SRAM, the location of the PowerPC exception // vectors (must be 64K-aligned) and the location of the boot branch. // 512 KB SRAM at the top of the 768K SRAM. SRAM starts at 0xfff00000 // Here we start at 0xfff40000 because the bottom 256K is reserved for // -- IPC Common space (0xfff00000 - 0xfff01000) // -- GPE0 (0xfff01000 - 0xfff10000) // -- GPE1 (0xfff10000 - 0xfff20000) // -- GPE2 (0xfff20000 - 0xfff30000) // -- GPE3 (0xfff30000 - 0xfff40000) #define origin 0xfff40000 #define vectors 0xfff40000 #define reset 0xffffffec #define sram_size 0x00080000 #define sram_available sram_size // The SRAM controller aliases the SRAM at 8 x 128MB boundaries to support // real-mode memory attributes using DCCR, ICCR etc. Noncacheable access is // the next-to-last 128MB PPC405 region. Write-though access is the // next-to-next-to-last 128MB PPC405 region. For our purposes, this means that: // -- 0xF7F00000 - 0xF7FC0000 is our noncacheable SRAM address space // -- 0xEFF00000 - 0xEFFC0000 is our writethrough SRAM address space // -- 0xFFF00000 - 0xFFFC0000 is cached for both reads and writes #define noncacheable_offset 0x08000000 #define noncacheable_origin (origin - 0x08000000) #define writethrough_offset 0x10000000 #define writethrough_origin (origin - 0x10000000) // This is the offset from the ppc405 EVPR where the debug pointers can be // found. #define SSX_DEBUG_PTRS_OFFSET 0x820 // Define SSX kernel text sections to be packed into nooks and crannies of // the exception vector area. An option is provided _not_ to pack, to help // better judge the best way to pack. Note that any code eligible for packing // is considered 'core' code that will be needed by the application at // runtime. Any header data is _always_ packed into .vectors_0000 however. // // Note that in order to support MMU protection, we can't pack data along // with the text. All of the packed data sections are thus left empty. // .vectors_0000 #define text_0000 \ *(.vectors_0000) #define data_0000 main.o(imageHeader) // .vectors_0100 #define text_0100 \ ppc405_core.o(.text) \ ppc405_irq_core.o(.text) #define data_0100 // .vectors_0c00 #if SSX_TIMER_SUPPORT #define text_0c00_conditional #else #define text_0c00_conditional #endif #define text_0c00 \ text_0c00_conditional \ ppc405_cache_core.o(.text) #define data_0c00 // .vectors_0f00 #if SSX_TIMER_SUPPORT #if SSX_THREAD_SUPPORT #define text_0f00_conditional \ ssx_timer_init.o(.text) \ ssx_timer_core.o(.text) \ ssx_semaphore_core.o(.text) #endif /* SSX_THREAD_SUPPORT */ #if !SSX_THREAD_SUPPORT #define text_0f00_conditional \ ssx_timer_init.o(.text) \ ssx_timer_core.o(.text) #endif /* !SSX_THREAD_SUPPORT */ #else /* SSX_TIMER_SUPPORT */ #define text_0f00_conditional #endif /* SSX_TIMER_SUPPORT */ #define text_0f00 \ text_0f00_conditional #define data_0f00 // .vectors_2000 #if SSX_THREAD_SUPPORT #define thread_text \ ssx_thread_init.o(.text) \ ssx_thread_core.o(.text) \ ppc405_irq_init.o(.text) \ ppc405_thread_init.o(.text) \ ssx_semaphore_init.o(.text) #else #define thread_text #endif #if PPC405_MMU_SUPPORT #define mmu_text \ ppc405_mmu.o(.text)\ ppc405_mmu_asm.o(.text) #else #define mmu_text #endif #define text_2000 \ occhw_irq_init.o(.text) \ ppc405_cache_init.o(.text) \ ppc405_breakpoint.o(.text) \ occhw_cache.o(.text) \ ssx_stack_init.o(.text) \ thread_text \ mmu_text \ occhw_async.o(.text) \ occhw_async_ocb.o(.text) \ occhw_async_pba.o(.text) \ occhw_scom.o(.text) \ occhw_ocb.o(.text) \ occhw_pba.o(.text) \ occhw_id.o(.text) \ //occhw_centaur.o(.text) \ ppc405_lib_core.o(.text) \ ssx_core.o(.text) #define data_2000 // .vectors_0000 is always packed with header information #define pack_0000 text_0000 data_0000 #define nopack_0000 #ifndef NO_PACK_SSX #define pack_0100 text_0100 data_0100 #define nopack_0100 #define pack_0c00 text_0c00 data_0c00 #define nopack_0c00 #define pack_0f00 text_0f00 data_0f00 #define nopack_0f00 #define pack_2000 text_2000 data_2000 #define nopack_2000 #else #define pack_0100 #define nopack_0100 text_0100 data_0100 #define pack_0c00 #define nopack_0c00 text_0c00 data_0c00 #define pack_0f00 #define nopack_0f00 text_0f00 data_0f00 #define pack_2000 #define nopack_2000 text_2000 data_2000 #endif #define init_text \ ssx_init.o(.text) \ ppc405_boot.o(.text) \ ppc405_init.o(.text) \ occhw_init.o(.text) #ifndef PPC405_MMU_SUPPORT ASSERT((0), "OCC Application Firmware can not be compiled without \ PPC405_MMU_SUPPORT compile flag") #endif // Define memory areas. MEMORY { sram : ORIGIN = origin, LENGTH = sram_available noncacheable : ORIGIN = noncacheable_origin, LENGTH = sram_available writethrough : ORIGIN = writethrough_origin, LENGTH = sram_available boot : ORIGIN = reset, LENGTH = 20 } // This symbol is only needed by external debug tools, so add this command // to ensure that table is pulled in by the linker even if ppc405 code // never references it. EXTERN(ssx_debug_ptrs); // NB: The code that sets up the MMU assumes that the linker script provides a // standard set of symbols that define the base address and size of each // expected section. Any section with a non-0 size will be mapped in the MMU // using protection attributes appropriate for the section. All sections // requiring different MMU attributes must be 1KB-aligned. // NOTE: __START_ADDR__, __READ_ONLY_DATA_LEN__, __WRITEABLE_DATA_ADDR__, // __WRITEABLE_DATA_LEN__ are used for the common image header macro SECTIONS { . = origin; . = vectors; _MEMORY_ORIGIN = .; _MEMORY_SIZE = sram_size; __START_ADDR__ = .; //////////////////////////////// // Text0 //////////////////////////////// // Low-memory kernel code and any other code that would benefit from being // resident in lower-latency SRAM _TEXT0_SECTION_BASE = .; _PPC405_VECTORS_BASE = .; .exceptions . : { ___vectors = .; ppc405_exceptions.o(.vectors_0000) pack_0000 . = ___vectors + 0x0100; ppc405_exceptions.o(.vectors_0100) . = ___vectors + SSX_DEBUG_PTRS_OFFSET; *(.debug_ptrs) ppc405_exceptions.o(.irq_exit_traces) pack_0100 . = ___vectors + 0x0c00; ppc405_exceptions.o(.vectors_0c00) pack_0c00 . = ___vectors + 0x0f00; ppc405_exceptions.o(.vectors_0f00) pack_0f00 . = ___vectors + 0x2000; ppc405_exceptions.o(.vectors_2000) pack_2000 } > sram // If we're not packing, then place 'core' code immediately after the // exception vectors. .nopack . : { nopack_0000 nopack_0100 nopack_0c00 nopack_0f00 nopack_2000 } > sram . = ALIGN(1024); _TEXT0_SECTION_SIZE = . - _TEXT0_SECTION_BASE; //////////////////////////////// // Noncacheable and Write-through Data //////////////////////////////// // When running without the MMU we need to carefully arrange things such // that the noncacheable and writethrough data is linked at the correct // aliased VMA while remaining loaded in contiguous LMA addresses. #if PPC405_MMU_SUPPORT #define ALIASED_SECTION(s) s . : {*(s)} > sram #else #define ALIASED_SECTION(s) \ _LMA = . + _lma_offset; \ s . : AT (_LMA) {*(s)} #endif #if !PPC405_MMU_SUPPORT . = . - noncacheable_offset; _lma_offset = noncacheable_offset; #endif _NONCACHEABLE_RO_SECTION_BASE = .; ALIASED_SECTION(.noncacheable_ro) . = ALIGN(1024); _NONCACHEABLE_RO_SECTION_SIZE = . - _NONCACHEABLE_RO_SECTION_BASE; _NONCACHEABLE_SECTION_BASE = .; ALIASED_SECTION(.noncacheable) . = ALIGN(1024); _NONCACHEABLE_SECTION_SIZE = . - _NONCACHEABLE_SECTION_BASE; #if !PPC405_MMU_SUPPORT . = . + noncacheable_offset - writethrough_offset; _lma_offset = writethrough_offset; #endif _WRITETHROUGH_SECTION_BASE = .; ALIASED_SECTION(.writethrough) . = ALIGN(1024); _WRITETHROUGH_SECTION_SIZE = . - _WRITETHROUGH_SECTION_BASE; #if !PPC405_MMU_SUPPORT . = . + writethrough_offset; #endif //////////////////////////////// // Read-only Data //////////////////////////////// _RODATA_SECTION_BASE = .; // SDA2 constant sections .sdata2 and .sbss2 must be adjacent to each // other. Our SDATA sections are small so we'll use strictly positive // offsets. _SDA2_BASE_ = .; .sdata2 . : { *(.sdata2) } > sram .sbss2 . : { *(.sbss2) } > sram // The .rodata.vclcommand section contains read-only VclCommandRecord for // the benefit of the vcl_console() command interpreter. _VCL_COMMAND_SECTION_BASE = .; .rodata.vclcommand . : { *(.rodata.vclcommand) } > sram _VCL_COMMAND_SECTION_SIZE = . - _VCL_COMMAND_SECTION_BASE; // The .rodata.vclthread section contains read-only VclThreadRecord for the // benefit of the thread command. _VCL_THREAD_SECTION_BASE = .; .rodata.vclthread . : { *(.rodata.vclthread) } > sram _VCL_THREAD_SECTION_SIZE = . - _VCL_THREAD_SECTION_BASE; // The .rodata.vclpackage section contains read-only char* pointers for the // benefit of the package command. _VCL_PACKAGE_SECTION_BASE = .; .rodata.vclpackage . : { *(.rodata.vclpackage) } > sram _VCL_PACKAGE_SECTION_SIZE = . - _VCL_PACKAGE_SECTION_BASE; // Other read-only data. .buildname . : { *(.buildname) } > sram .rodata . : { *(.rodata*) *(.got2) } > sram . = ALIGN(1024); _RODATA_SECTION_SIZE = . - _RODATA_SECTION_BASE; __READ_ONLY_DATA_LEN__ = . - __START_ADDR__; //////////////////////////////// // Text1 //////////////////////////////// // The default text section _TEXT1_SECTION_BASE = .; // Initialization text. If we ever do a scheme to get rid of // initialization text then this will have to be moved if we're also doing // MMU protection. .itext . : { init_text } > sram // Other text // It's not clear why boot.S is generating empty .glink,.iplt .glink . : { *(.glink) } > sram .otext . : { *(.text) *(.text.startup)} > sram __CTOR_LIST__ = .; .ctors . : { *(.ctors) } > sram __CTOR_END__ = .; . = ALIGN(1024); _TEXT1_SECTION_SIZE = . - _TEXT1_SECTION_BASE; //////////////////////////////// // Read-write Data //////////////////////////////// _DATA_SECTION_BASE = .; __WRITEABLE_DATA_ADDR__ = .; // SDA sections .sdata and .sbss must be adjacent to each // other. Our SDATA sections are small so we'll use strictly positive // offsets. _SDA_BASE_ = .; .sdata . : { *(.sdata) } > sram // Make sbss section 128 bytes aligned as linker is complaining while // compiling product applets that use global variables from the occ // application. OCC application is compiled with SDA data enabled and // applets are compiled with SDA sections not enabled. .sbss . : { *(.sbss) . = ALIGN(128); } > sram // Other read-write data // It's not clear why boot.S is generating empty .glink,.iplt .rela . : { *(.rela*) *(.glink*) *(.iplt*) } > sram .rwdata . : { *(.data) *(.bss) *(COMMON) . = ALIGN(128); } > sram // Initialization-only data. This includes the stack of main, the data // structures declared by INITCALL, and any other data areas that can be // reclaimed to the heap after initialization. // // NB: If we ever do reclaim this space, we need to modify the concept of // executable free space. _INIT_ONLY_DATA_BASE = .; // Put the stack right after the 405 main application and before the trace buffers _SSX_INITIAL_STACK_LIMIT = .; . = . + INITIAL_STACK_SIZE; _SSX_INITIAL_STACK = . - 1; _INITCALL_SECTION_BASE = .; .data.initcall . : { *(.data.initcall) } > sram _INITCALL_SECTION_SIZE = . - _INITCALL_SECTION_BASE; .data.startup . : { *(.data.startup) } > sram _INIT_ONLY_DATA_SIZE = . - _INIT_ONLY_DATA_BASE; //////////////////////////////// // Free Space //////////////////////////////// // If the configuration allows executing from free space - i.e., // malloc()-ing a buffer and loading and executing code from it - then the // free space is separated and aligned so that it can be marked executable. // Otherwise it is simply read/write like the normal data sections. #ifndef EXECUTABLE_FREE_SPACE #define EXECUTABLE_FREE_SPACE 0 #endif #if PPC405_MMU_SUPPORT && EXECUTABLE_FREE_SPACE . = ALIGN(1024); #endif // The free space available to the program starts here. This space does // not include the initial stack used by the boot loader and main(). The // initial stack space is considered part of the free 'section' for MMU // purposes. Free space is always 8-byte aligned. // // Note that there is no data after _SSX_FREE_START. When binary images // are created they can be padded to _SSX_FREE_START to guarantee // that .bss and COMMON data are zeroed, and that the images contain an // even multiple of 8 bytes (required for HW loaders). . = ALIGN(8); _EX_FREE_SECTION_BASE = .; _SSX_FREE_START = .; #if EXECUTABLE_FREE_SPACE _DATA_SECTION_SIZE = . - _DATA_SECTION_BASE; __WRITEABLE_DATA_LEN__ = . - __WRITEABLE_DATA_ADDR__ ; _EX_FREE_SECTION_SIZE = _GPE_SHARED_DATA_BASE - _EX_FREE_SECTION_BASE; #else _DATA_SECTION_SIZE = _GPE_SHARED_DATA_BASE - _DATA_SECTION_BASE; __WRITEABLE_DATA_LEN__ = _GPE_SHARED_DATA_BASE - __WRITEABLE_DATA_ADDR__ ; _EX_FREE_SECTION_SIZE = 0; #endif _SSX_FREE_END = _GPE_SHARED_DATA_BASE - 1; //////////////////////////////// // Shared GPE data // // Section for sharing data with GPEs before IPC commands can be used // NOTE: If this location is changed, the #define for the address // needs to be changed in gpe0_main.c and gpe1_main.c. //////////////////////////////// __CUR_COUNTER__ = .; _GPE_SHARED_DATA_BASE = 0xfffb3c00; _GPE_SHARED_DATA_SIZE = 0x100; . = _GPE_SHARED_DATA_BASE; #if !PPC405_MMU_SUPPORT . = . - writethrough_offset; _LMA = . + writethrough_offset; .gpe_shared . : AT(_LMA) {*(gpe_shared) . = ALIGN(_GPE_SHARED_DATA_SIZE);} . = . + writethrough_offset; #else .gpe_shared . : {*(gpe_shared) . = ALIGN(_GPE_SHARED_DATA_SIZE);} > sram #endif . = __CUR_COUNTER__; //////////////////////////////// // Ping/Pong Buffer Section // // Contains two 256-byte buffers used to tell the PGPE which vfrt to use // //////////////////////////////// __CUR_COUNTER__ = .; _PING_PONG_BUFFER_BASE = 0xfffb3d00; _PING_BUFFER_BASE = 0xfffb3d00; _PING_BUFFER_SIZE = 0x100; _PONG_BUFFER_BASE = 0xfffb3e00; _PONG_BUFFER_SIZE = 0x100; . = _PING_BUFFER_BASE; #if !PPC405_MMU_SUPPORT . = . - writethrough_offset; _LMA = . + writethrough_offset; .vfrt_ping_buffer . : AT(_LMA) {*(vfrt_ping_buffer) . = ALIGN(_PING_BUFFER_SIZE);} _LMA = . + writethrough_offset; .vfrt_pong_buffer . : AT(_LMA) {*(vfrt_pong_buffer) . = ALIGN(_PONG_BUFFER_SIZE);} . = . + writethrough_offset; #else .vfrt_ping_buffer . : {*(vfrt_ping_buffer) . = ALIGN(_PING_BUFFER_SIZE);} > sram .vfrt_pong_buffer . : {*(vfrt_pong_buffer) . = ALIGN(_PONG_BUFFER_SIZE);} > sram #endif . = __CUR_COUNTER__; //////////////////////////////// // Global Data Section // // Contains pointers to important Global variables // //////////////////////////////// __CUR_COUNTER__ = .; _GLOBAL_DATA_BASE = 0xfffb3f00; _GLOBAL_DATA_SIZE = 0x100; . = _GLOBAL_DATA_BASE; #if !PPC405_MMU_SUPPORT . = . - writethrough_offset; _LMA = . + writethrough_offset; .global_data . : AT(_LMA) {*(global_data) . = ALIGN(_GLOBAL_DATA_SIZE);} . = . + writethrough_offset; #else .global_data . : {*(global_data) . = ALIGN(_GLOBAL_DATA_SIZE);} > sram #endif . = __CUR_COUNTER__; //////////////////////////////// // Trace Buffers // // NOTE: If these addresses change, TMGT/HTMGT will require // changes as well, to collect trace data in the event // the OCC/405 dies unexpectedly. //////////////////////////////// __CUR_COUNTER__ = .; _ERR_TRACE_BUFFER_BASE = 0xfffb4000; _TRACE_BUFFERS_START_BASE = 0xfffb4000; _ERR_TRACE_BUFFER_SIZE = 0x2000; _INF_TRACE_BUFFER_BASE = 0xfffb6000; _INF_TRACE_BUFFER_SIZE = 0x2000; _IMP_TRACE_BUFFER_BASE = 0xfffb8000; _IMP_TRACE_BUFFER_SIZE = 0x2000; . = _ERR_TRACE_BUFFER_BASE; #if !PPC405_MMU_SUPPORT . = . - writethrough_offset; _LMA = . + writethrough_offset; .err_trac . : AT (_LMA) {*(err_trac) . = ALIGN(_ERR_TRACE_BUFFER_SIZE);} _LMA = . + writethrough_offset; .inf_trac . : AT (_LMA) {*(inf_trac) . = ALIGN(_INF_TRACE_BUFFER_SIZE);} _LMA = . + writethrough_offset; .imp_trac . : AT (_LMA) {*(imp_trac) . = ALIGN(_IMP_TRACE_BUFFER_SIZE);} . = . + writethrough_offset; #else .err_trac . : {*(err_trac) . = ALIGN(_ERR_TRACE_BUFFER_SIZE);} > sram .inf_trac . : {*(inf_trac) . = ALIGN(_INF_TRACE_BUFFER_SIZE);} > sram .imp_trac . : {*(imp_trac) . = ALIGN(_IMP_TRACE_BUFFER_SIZE);} > sram #endif . = __CUR_COUNTER__; //////////////////////////////// // FIR data heap section //////////////////////////////// __CUR_COUNTER__ = .; _FIR_HEAP_SECTION_BASE = 0xfffba000; _FIR_HEAP_SECTION_SIZE = 0x3000; . = _FIR_HEAP_SECTION_BASE; #if !PPC405_MMU_SUPPORT . = . - writethrough_offset; _LMA = . + writethrough_offset; .firHeap . : AT (_LMA) {*(firHeap) . = ALIGN(1024);} . = . + writethrough_offset; #else .firHeap . : {*(firHeap) . = ALIGN(1024);} > sram #endif . = __CUR_COUNTER__; //////////////////////////////// // FIR data parms section //////////////////////////////// __CUR_COUNTER__ = .; _FIR_PARMS_SECTION_BASE = 0xfffbd000; _FIR_PARMS_SECTION_SIZE = 0x1000; . = _FIR_PARMS_SECTION_BASE; #if !PPC405_MMU_SUPPORT . = . - noncacheable_offset; _LMA = . + noncacheable_offset; .firParms . : AT (_LMA) {*(firParms) . = ALIGN(1024);} . = . + noncacheable_offset; #else .firParms . : {*(firParms) . = ALIGN(1024);} > sram #endif . = __CUR_COUNTER__; //////////////////////////////// // FSP Command Buffer //////////////////////////////// __CUR_COUNTER__ = .; _LINEAR_WR_WINDOW_SECTION_BASE = 0xfffbe000; _LINEAR_WR_WINDOW_SECTION_SIZE = 0x1000; _LINEAR_RD_WINDOW_SECTION_BASE = 0xfffbf000; // Update FFDC_BUFFER_ADDR if changed _LINEAR_RD_WINDOW_SECTION_SIZE = 0x1000; . = _LINEAR_WR_WINDOW_SECTION_BASE; #if !PPC405_MMU_SUPPORT . = . - noncacheable_offset; _LMA = . + noncacheable_offset; .linear_wr . : AT (_LMA) {*(linear_wr) . = ALIGN(_LINEAR_WR_WINDOW_SECTION_SIZE);} #else .linear_wr . : {*(linear_wr) . = ALIGN(_LINEAR_WR_WINDOW_SECTION_SIZE);} > sram #endif #if !PPC405_MMU_SUPPORT . = . + noncacheable_offset - writethrough_offset; _LMA = . + writethrough_offset; .linear_rd . : AT (_LMA) {*(linear_rd) . = ALIGN(_LINEAR_RD_WINDOW_SECTION_SIZE);} #else .linear_rd . : {*(linear_rd) . = ALIGN(_LINEAR_RD_WINDOW_SECTION_SIZE);} > sram #endif #if !PPC405_MMU_SUPPORT . = . + writethrough_offset; #endif . = __CUR_COUNTER__; //////////////////////////////// // The init data, // takes up around 6K. //////////////////////////////// //__CUR_COUNTER__ = .; //INIT_SECTION_BASE = 0xfffbf000; //. = INIT_SECTION_BASE; // Section aligned to 128 to make occ main application image 128 bytes // aligned which is requirement for applet manager when traversing through // all the image headers //initSection . : { *(initSection) init_text . = ALIGN(128);} > sram //. = __CUR_COUNTER__; ////////////////////////////// // End Of Memory ////////////////////////////// _PPC405_END_OF_MEMORY = 0; } <|start_filename|>src/include/core_data.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/core_data.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file core_data.h /// \brief Data structures for the GPE programs that collect raw data defined /// in core_data.C. The data structure layouts are also documented in the /// spreadsheet \todo (RTC 137031) location. #ifndef __GPE_CORE_DATA_H__ #define __GPE_CORE_DATA_H__ #include <stdint.h> #include <p9_config.h> #define PC_OCC_SPRC 0x00010A82 #define PC_OCC_SPRD 0x00010A83 #define TOD_VALUE_REG 0x00040020 #define STOP_STATE_HIST_OCC_REG 0x000F0112 #define SELECT_ODD_CORE 0x100 #define CORE_RAW_CYCLES 0x200 #define CORE_RUN_CYCLES 0x208 #define CORE_WORKRATE_BUSY 0x210 #define CORE_WORKRATE_FINISH 0x218 #define CORE_MEM_HIER_A_LATENCY 0x220 #define CORE_MEM_HIER_B_LATENCY 0x228 #define CORE_MEM_HIER_C_ACCESS 0x230 #define THREAD0_RUN_CYCLES 0x238 #define THREAD0_INST_DISP_UTIL 0x240 #define THREAD0_INST_COMP_UTIL 0x248 #define THREAD0_MEM_HIER_C_ACCESS 0x250 #define THREAD1_RUN_CYCLES 0x258 #define THREAD1_INST_DISP_UTIL 0x260 #define THREAD1_INST_COMP_UTIL 0x268 #define THREAD1_MEM_HEIR_C_ACCESS 0x270 #define THREAD2_RUN_CYCLES 0x278 #define THREAD2_INST_DISP_UTIL 0x280 #define THREAD2_INST_COMP_UTIL 0x288 #define THREAD2_MEM_HEIR_C_ACCESS 0x290 #define THREAD3_RUN_CYCLES 0x298 #define THREAD3_INST_DISP_UTIL 0x2A0 #define THREAD3_INST_COMP_UTIL 0x2A8 #define THREAD3_MEM_HEIR_C_ACCESS 0x2B0 #define IFU_THROTTLE_BLOCK_FETCH 0x2B8 #define IFU_THROTTLE_ACTIVE 0x2C0 #define VOLT_DROOP_THROTTLE_ACTIVE 0x2C8 #define EMPATH_CORE_THREADS 4 // Droop events cache=bit37, cores = bits 42,46,50,54 #define CACHE_VDM_LARGE_DROOP 0x0000000004000000ull #define CORE0_VDM_SMALL_DROOP 0x0000000000200000ull #define CORE1_VDM_SMALL_DROOP 0x0000000000020000ull #define CORE2_VDM_SMALL_DROOP 0x0000000000002000ull #define CORE3_VDM_SMALL_DROOP 0x0000000000000200ull // return codes: #define SIBRC_RESOURCE_OCCUPIED (1) #define SIBRC_CORE_FENCED (2) #define SIBRC_PARTIAL_GOOD (3) #define SIBRC_ADDRESS_ERROR (4) #define SIBRC_CLOCK_ERROR (5) #define SIBRC_PACKET_ERROR (6) #define SIBRC_TIMEOUT (7) #define EMPATH_VALID (1) #define WORKAROUND_SCOM_ADDRESS 0x10800 typedef enum { FUSED_UNKNOWN, FUSED_FALSE, FUSED_TRUE } FusedCore; typedef struct { uint32_t tod_2mhz; uint32_t raw_cycles; // 0x200 uint32_t run_cycles; // 0x208 uint32_t freq_sens_busy; // 0x210 Core workrate busy counter uint32_t freq_sens_finish; // 0x218 Core workrate finish counter uint32_t mem_latency_a; uint32_t mem_latency_b; uint32_t mem_access_c; } CoreDataEmpath; typedef struct { uint32_t ifu_throttle; uint32_t ifu_active; uint32_t undefined; uint32_t v_droop; // new for p9 } CoreDataThrottle; typedef struct { uint32_t run_cycles; uint32_t dispatch; // new for p9 uint32_t completion; uint32_t mem_c; // was mem_a // uint32_t mem_b; // No longer exists in p9 } CoreDataPerThread; typedef struct { sensor_result_t core[2]; sensor_result_t cache[2]; } CoreDataDts; typedef struct { uint32_t cache_large_event; uint32_t core_small_event; } DroopEvents; // // The instance of this data object must be 8 byte aligned and // size must be muliple of 8 // typedef struct // 136 bytes { CoreDataEmpath empath; //32 CoreDataThrottle throttle; //16 CoreDataPerThread per_thread[EMPATH_CORE_THREADS]; // 64 CoreDataDts dts; // 8 uint64_t stop_state_hist; // 8 DroopEvents droop; // 8 uint32_t reserved; // 4 uint32_t empathValid; // 4 } CoreData; #ifdef __cplusplus extern "C" { #endif /** * Get core data * @param[in] The system core number [0-23] * @param[out] Data pointer for the result * @return result of scom operation */ uint32_t get_core_data(uint32_t i_core, CoreData* o_data); #ifdef __cplusplus }; #endif #endif /* __GPE_CORE_DATA_H__ */ <|start_filename|>src/include/registers/qppm_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/qppm_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __QPPM_FIRMWARE_REGISTERS_H__ #define __QPPM_FIRMWARE_REGISTERS_H__ /// \file qppm_firmware_registers.h /// \brief C register structs for the QPPM unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union qppm_qpmmr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t fsafe : 11; uint64_t enable_fsafe_upon_heartbeat_loss : 1; uint64_t reserved13_15 : 3; uint64_t reserved2 : 4; uint64_t cme_interppm_ivrm_enable : 1; uint64_t cme_interppm_ivrm_sel : 1; uint64_t cme_interppm_aclk_enable : 1; uint64_t cme_interppm_aclk_sel : 1; uint64_t cme_interppm_vdm_enable : 1; uint64_t cme_interppm_vdm_sel : 1; uint64_t cme_interppm_dpll_enable : 1; uint64_t cme_interppm_dpll_sel : 1; uint64_t reserved28_293 : 2; uint64_t pb_purge_pls : 1; uint64_t pb_purge_done_lvl : 1; uint64_t reserved4 : 32; #else uint64_t reserved4 : 32; uint64_t pb_purge_done_lvl : 1; uint64_t pb_purge_pls : 1; uint64_t reserved28_293 : 2; uint64_t cme_interppm_dpll_sel : 1; uint64_t cme_interppm_dpll_enable : 1; uint64_t cme_interppm_vdm_sel : 1; uint64_t cme_interppm_vdm_enable : 1; uint64_t cme_interppm_aclk_sel : 1; uint64_t cme_interppm_aclk_enable : 1; uint64_t cme_interppm_ivrm_sel : 1; uint64_t cme_interppm_ivrm_enable : 1; uint64_t reserved2 : 4; uint64_t reserved13_15 : 3; uint64_t enable_fsafe_upon_heartbeat_loss : 1; uint64_t fsafe : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_qpmmr_t; typedef union qppm_qpmmr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t fsafe : 11; uint64_t enable_fsafe_upon_heartbeat_loss : 1; uint64_t reserved13_15 : 3; uint64_t reserved2 : 4; uint64_t cme_interppm_ivrm_enable : 1; uint64_t cme_interppm_ivrm_sel : 1; uint64_t cme_interppm_aclk_enable : 1; uint64_t cme_interppm_aclk_sel : 1; uint64_t cme_interppm_vdm_enable : 1; uint64_t cme_interppm_vdm_sel : 1; uint64_t cme_interppm_dpll_enable : 1; uint64_t cme_interppm_dpll_sel : 1; uint64_t reserved28_293 : 2; uint64_t pb_purge_pls : 1; uint64_t pb_purge_done_lvl : 1; uint64_t reserved4 : 32; #else uint64_t reserved4 : 32; uint64_t pb_purge_done_lvl : 1; uint64_t pb_purge_pls : 1; uint64_t reserved28_293 : 2; uint64_t cme_interppm_dpll_sel : 1; uint64_t cme_interppm_dpll_enable : 1; uint64_t cme_interppm_vdm_sel : 1; uint64_t cme_interppm_vdm_enable : 1; uint64_t cme_interppm_aclk_sel : 1; uint64_t cme_interppm_aclk_enable : 1; uint64_t cme_interppm_ivrm_sel : 1; uint64_t cme_interppm_ivrm_enable : 1; uint64_t reserved2 : 4; uint64_t reserved13_15 : 3; uint64_t enable_fsafe_upon_heartbeat_loss : 1; uint64_t fsafe : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_qpmmr_clr_t; typedef union qppm_qpmmr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t fsafe : 11; uint64_t enable_fsafe_upon_heartbeat_loss : 1; uint64_t reserved13_15 : 3; uint64_t reserved2 : 4; uint64_t cme_interppm_ivrm_enable : 1; uint64_t cme_interppm_ivrm_sel : 1; uint64_t cme_interppm_aclk_enable : 1; uint64_t cme_interppm_aclk_sel : 1; uint64_t cme_interppm_vdm_enable : 1; uint64_t cme_interppm_vdm_sel : 1; uint64_t cme_interppm_dpll_enable : 1; uint64_t cme_interppm_dpll_sel : 1; uint64_t reserved28_293 : 2; uint64_t pb_purge_pls : 1; uint64_t pb_purge_done_lvl : 1; uint64_t reserved4 : 32; #else uint64_t reserved4 : 32; uint64_t pb_purge_done_lvl : 1; uint64_t pb_purge_pls : 1; uint64_t reserved28_293 : 2; uint64_t cme_interppm_dpll_sel : 1; uint64_t cme_interppm_dpll_enable : 1; uint64_t cme_interppm_vdm_sel : 1; uint64_t cme_interppm_vdm_enable : 1; uint64_t cme_interppm_aclk_sel : 1; uint64_t cme_interppm_aclk_enable : 1; uint64_t cme_interppm_ivrm_sel : 1; uint64_t cme_interppm_ivrm_enable : 1; uint64_t reserved2 : 4; uint64_t reserved13_15 : 3; uint64_t enable_fsafe_upon_heartbeat_loss : 1; uint64_t fsafe : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_qpmmr_or_t; typedef union qppm_errsum { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pm_error : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t pm_error : 1; #endif // _BIG_ENDIAN } fields; } qppm_errsum_t; typedef union qppm_err { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcb_interrupt_protocol_err : 1; uint64_t special_wkup_protocol_err : 1; uint64_t l2_ex0_clk_sync_err : 1; uint64_t l2_ex1_clk_sync_err : 1; uint64_t dpll_dyn_fmin_err : 1; uint64_t dpll_dco_full_err : 1; uint64_t dpll_dco_empty_err : 1; uint64_t dpll_int_err : 1; uint64_t occ_heartbeat_loss : 1; uint64_t spare_8_11 : 3; uint64_t reserved1 : 52; #else uint64_t reserved1 : 52; uint64_t spare_8_11 : 3; uint64_t occ_heartbeat_loss : 1; uint64_t dpll_int_err : 1; uint64_t dpll_dco_empty_err : 1; uint64_t dpll_dco_full_err : 1; uint64_t dpll_dyn_fmin_err : 1; uint64_t l2_ex1_clk_sync_err : 1; uint64_t l2_ex0_clk_sync_err : 1; uint64_t special_wkup_protocol_err : 1; uint64_t pcb_interrupt_protocol_err : 1; #endif // _BIG_ENDIAN } fields; } qppm_err_t; typedef union qppm_errmsk { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 12; uint64_t reserved2 : 52; #else uint64_t reserved2 : 52; uint64_t reserved1 : 12; #endif // _BIG_ENDIAN } fields; } qppm_errmsk_t; typedef union qppm_dpll_freq { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t fmax : 11; uint64_t hires_fmax : 4; uint64_t reserved2 : 1; uint64_t freq_mult : 11; uint64_t hires_freq_mult : 4; uint64_t reserved3 : 1; uint64_t fmin : 11; uint64_t hires_fmin : 4; uint64_t reserved4 : 16; #else uint64_t reserved4 : 16; uint64_t hires_fmin : 4; uint64_t fmin : 11; uint64_t reserved3 : 1; uint64_t hires_freq_mult : 4; uint64_t freq_mult : 11; uint64_t reserved2 : 1; uint64_t hires_fmax : 4; uint64_t fmax : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_freq_t; typedef union qppm_dpll_ctrl { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dpll_lock_sel : 1; uint64_t dynamic_filter_enable : 1; uint64_t ff_bypass : 1; uint64_t dco_override : 1; uint64_t dco_incr : 1; uint64_t dco_decr : 1; uint64_t ff_slewrate : 10; uint64_t ss_enable : 1; uint64_t reserved_17_19 : 3; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t reserved_17_19 : 3; uint64_t ss_enable : 1; uint64_t ff_slewrate : 10; uint64_t dco_decr : 1; uint64_t dco_incr : 1; uint64_t dco_override : 1; uint64_t ff_bypass : 1; uint64_t dynamic_filter_enable : 1; uint64_t dpll_lock_sel : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_ctrl_t; typedef union qppm_dpll_ctrl_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dpll_lock_sel : 1; uint64_t dynamic_filter_enable : 1; uint64_t ff_bypass : 1; uint64_t dco_override : 1; uint64_t dco_incr : 1; uint64_t dco_decr : 1; uint64_t ff_slewrate : 10; uint64_t ss_enable : 1; uint64_t reserved_17_19 : 3; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t reserved_17_19 : 3; uint64_t ss_enable : 1; uint64_t ff_slewrate : 10; uint64_t dco_decr : 1; uint64_t dco_incr : 1; uint64_t dco_override : 1; uint64_t ff_bypass : 1; uint64_t dynamic_filter_enable : 1; uint64_t dpll_lock_sel : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_ctrl_clr_t; typedef union qppm_dpll_ctrl_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dpll_lock_sel : 1; uint64_t dynamic_filter_enable : 1; uint64_t ff_bypass : 1; uint64_t dco_override : 1; uint64_t dco_incr : 1; uint64_t dco_decr : 1; uint64_t ff_slewrate : 10; uint64_t ss_enable : 1; uint64_t reserved_17_19 : 3; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t reserved_17_19 : 3; uint64_t ss_enable : 1; uint64_t ff_slewrate : 10; uint64_t dco_decr : 1; uint64_t dco_incr : 1; uint64_t dco_override : 1; uint64_t ff_bypass : 1; uint64_t dynamic_filter_enable : 1; uint64_t dpll_lock_sel : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_ctrl_or_t; typedef union qppm_dpll_stat { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t freqout : 11; uint64_t hires_freqout : 5; uint64_t reserved2 : 40; uint64_t reserved_57_60 : 4; uint64_t fsafe_active : 1; uint64_t freq_change : 1; uint64_t lock : 1; #else uint64_t lock : 1; uint64_t freq_change : 1; uint64_t fsafe_active : 1; uint64_t reserved_57_60 : 4; uint64_t reserved2 : 40; uint64_t hires_freqout : 5; uint64_t freqout : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_stat_t; typedef union qppm_dpll_ochar { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t freqout_max : 11; uint64_t hires_freqout_max : 5; uint64_t reserved2 : 4; uint64_t freqout_avg : 11; uint64_t hires_freqout_avg : 5; uint64_t reserved3 : 4; uint64_t freqout_min : 11; uint64_t hires_freqout_min : 5; uint64_t reserved4 : 7; #else uint64_t reserved4 : 7; uint64_t hires_freqout_min : 5; uint64_t freqout_min : 11; uint64_t reserved3 : 4; uint64_t hires_freqout_avg : 5; uint64_t freqout_avg : 11; uint64_t reserved2 : 4; uint64_t hires_freqout_max : 5; uint64_t freqout_max : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_ochar_t; typedef union qppm_dpll_ichar { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t freqin_avg : 11; uint64_t hires_freqin_avg : 5; uint64_t reserved2 : 4; uint64_t freqin_max : 11; uint64_t hires_freqin_max : 5; uint64_t reserved3 : 4; uint64_t freqin_min : 11; uint64_t hires_freqin_min : 5; uint64_t reserved4 : 7; #else uint64_t reserved4 : 7; uint64_t hires_freqin_min : 5; uint64_t freqin_min : 11; uint64_t reserved3 : 4; uint64_t hires_freqin_max : 5; uint64_t freqin_max : 11; uint64_t reserved2 : 4; uint64_t hires_freqin_avg : 5; uint64_t freqin_avg : 11; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } qppm_dpll_ichar_t; typedef union qppm_occhb { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_heartbeat_count : 16; uint64_t occ_heartbeat_enable : 1; uint64_t reserved1 : 47; #else uint64_t reserved1 : 47; uint64_t occ_heartbeat_enable : 1; uint64_t occ_heartbeat_count : 16; #endif // _BIG_ENDIAN } fields; } qppm_occhb_t; typedef union qppm_qaccr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t core_clk_sb_strength : 4; uint64_t core_clk_sb_spare : 1; uint64_t core_clk_sb_pulse_mode_en : 1; uint64_t core_clk_sb_pulse_mode : 2; uint64_t core_clk_sw_resclk : 4; uint64_t core_clk_sw_spare : 1; uint64_t l2_ex0_clk_sync_enable : 1; uint64_t reserved_14_151 : 2; uint64_t l2_ex0_clkglm_async_reset : 1; uint64_t reserved_17_182 : 2; uint64_t l2_ex0_clkglm_sel : 1; uint64_t l2_ex0_clk_sb_strength : 4; uint64_t l2_ex0_clk_sb_spare0 : 1; uint64_t l2_ex0_clk_sb_pulse_mode_en : 1; uint64_t l2_ex0_clk_sb_pulse_mode : 2; uint64_t l2_ex0_clk_sw_resclk : 4; uint64_t l2_ex0_clk_sw_spare1 : 1; uint64_t l2_ex1_clk_sync_enable : 1; uint64_t reserved_34_353 : 2; uint64_t l2_ex1_clkglm_async_reset : 1; uint64_t reserved_37_384 : 2; uint64_t l2_ex1_clkglm_sel : 1; uint64_t l2_ex1_clk_sb_strength : 4; uint64_t l2_ex1_clk_sb_spare0 : 1; uint64_t l2_ex1_clk_sb_pulse_mode_en : 1; uint64_t l2_ex1_clk_sb_pulse_mode : 2; uint64_t l2_ex1_clk_sw_resclk : 4; uint64_t l2_ex1_clk_sw_spare1 : 1; uint64_t reserved_53_55 : 3; uint64_t l3_clk_sb_strength : 4; uint64_t l3_clk_sb_spare0 : 1; uint64_t l3_clk_sb_pulse_mode_en : 1; uint64_t l3_clk_sb_pulse_mode : 2; #else uint64_t l3_clk_sb_pulse_mode : 2; uint64_t l3_clk_sb_pulse_mode_en : 1; uint64_t l3_clk_sb_spare0 : 1; uint64_t l3_clk_sb_strength : 4; uint64_t reserved_53_55 : 3; uint64_t l2_ex1_clk_sw_spare1 : 1; uint64_t l2_ex1_clk_sw_resclk : 4; uint64_t l2_ex1_clk_sb_pulse_mode : 2; uint64_t l2_ex1_clk_sb_pulse_mode_en : 1; uint64_t l2_ex1_clk_sb_spare0 : 1; uint64_t l2_ex1_clk_sb_strength : 4; uint64_t l2_ex1_clkglm_sel : 1; uint64_t reserved_37_384 : 2; uint64_t l2_ex1_clkglm_async_reset : 1; uint64_t reserved_34_353 : 2; uint64_t l2_ex1_clk_sync_enable : 1; uint64_t l2_ex0_clk_sw_spare1 : 1; uint64_t l2_ex0_clk_sw_resclk : 4; uint64_t l2_ex0_clk_sb_pulse_mode : 2; uint64_t l2_ex0_clk_sb_pulse_mode_en : 1; uint64_t l2_ex0_clk_sb_spare0 : 1; uint64_t l2_ex0_clk_sb_strength : 4; uint64_t l2_ex0_clkglm_sel : 1; uint64_t reserved_17_182 : 2; uint64_t l2_ex0_clkglm_async_reset : 1; uint64_t reserved_14_151 : 2; uint64_t l2_ex0_clk_sync_enable : 1; uint64_t core_clk_sw_spare : 1; uint64_t core_clk_sw_resclk : 4; uint64_t core_clk_sb_pulse_mode : 2; uint64_t core_clk_sb_pulse_mode_en : 1; uint64_t core_clk_sb_spare : 1; uint64_t core_clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } qppm_qaccr_t; typedef union qppm_qaccr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t core_clk_sb_strength : 4; uint64_t core_clk_sb_spare : 1; uint64_t core_clk_sb_pulse_mode_en : 1; uint64_t core_clk_sb_pulse_mode : 2; uint64_t core_clk_sw_resclk : 4; uint64_t core_clk_sw_spare : 1; uint64_t l2_ex0_clk_sync_enable : 1; uint64_t reserved_14_151 : 2; uint64_t l2_ex0_clkglm_async_reset : 1; uint64_t reserved_17_182 : 2; uint64_t l2_ex0_clkglm_sel : 1; uint64_t l2_ex0_clk_sb_strength : 4; uint64_t l2_ex0_clk_sb_spare0 : 1; uint64_t l2_ex0_clk_sb_pulse_mode_en : 1; uint64_t l2_ex0_clk_sb_pulse_mode : 2; uint64_t l2_ex0_clk_sw_resclk : 4; uint64_t l2_ex0_clk_sw_spare1 : 1; uint64_t l2_ex1_clk_sync_enable : 1; uint64_t reserved_34_353 : 2; uint64_t l2_ex1_clkglm_async_reset : 1; uint64_t reserved_37_384 : 2; uint64_t l2_ex1_clkglm_sel : 1; uint64_t l2_ex1_clk_sb_strength : 4; uint64_t l2_ex1_clk_sb_spare0 : 1; uint64_t l2_ex1_clk_sb_pulse_mode_en : 1; uint64_t l2_ex1_clk_sb_pulse_mode : 2; uint64_t l2_ex1_clk_sw_resclk : 4; uint64_t l2_ex1_clk_sw_spare1 : 1; uint64_t reserved_53_55 : 3; uint64_t l3_clk_sb_strength : 4; uint64_t l3_clk_sb_spare0 : 1; uint64_t l3_clk_sb_pulse_mode_en : 1; uint64_t l3_clk_sb_pulse_mode : 2; #else uint64_t l3_clk_sb_pulse_mode : 2; uint64_t l3_clk_sb_pulse_mode_en : 1; uint64_t l3_clk_sb_spare0 : 1; uint64_t l3_clk_sb_strength : 4; uint64_t reserved_53_55 : 3; uint64_t l2_ex1_clk_sw_spare1 : 1; uint64_t l2_ex1_clk_sw_resclk : 4; uint64_t l2_ex1_clk_sb_pulse_mode : 2; uint64_t l2_ex1_clk_sb_pulse_mode_en : 1; uint64_t l2_ex1_clk_sb_spare0 : 1; uint64_t l2_ex1_clk_sb_strength : 4; uint64_t l2_ex1_clkglm_sel : 1; uint64_t reserved_37_384 : 2; uint64_t l2_ex1_clkglm_async_reset : 1; uint64_t reserved_34_353 : 2; uint64_t l2_ex1_clk_sync_enable : 1; uint64_t l2_ex0_clk_sw_spare1 : 1; uint64_t l2_ex0_clk_sw_resclk : 4; uint64_t l2_ex0_clk_sb_pulse_mode : 2; uint64_t l2_ex0_clk_sb_pulse_mode_en : 1; uint64_t l2_ex0_clk_sb_spare0 : 1; uint64_t l2_ex0_clk_sb_strength : 4; uint64_t l2_ex0_clkglm_sel : 1; uint64_t reserved_17_182 : 2; uint64_t l2_ex0_clkglm_async_reset : 1; uint64_t reserved_14_151 : 2; uint64_t l2_ex0_clk_sync_enable : 1; uint64_t core_clk_sw_spare : 1; uint64_t core_clk_sw_resclk : 4; uint64_t core_clk_sb_pulse_mode : 2; uint64_t core_clk_sb_pulse_mode_en : 1; uint64_t core_clk_sb_spare : 1; uint64_t core_clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } qppm_qaccr_clr_t; typedef union qppm_qaccr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t core_clk_sb_strength : 4; uint64_t core_clk_sb_spare : 1; uint64_t core_clk_sb_pulse_mode_en : 1; uint64_t core_clk_sb_pulse_mode : 2; uint64_t core_clk_sw_resclk : 4; uint64_t core_clk_sw_spare : 1; uint64_t l2_ex0_clk_sync_enable : 1; uint64_t reserved_14_151 : 2; uint64_t l2_ex0_clkglm_async_reset : 1; uint64_t reserved_17_182 : 2; uint64_t l2_ex0_clkglm_sel : 1; uint64_t l2_ex0_clk_sb_strength : 4; uint64_t l2_ex0_clk_sb_spare0 : 1; uint64_t l2_ex0_clk_sb_pulse_mode_en : 1; uint64_t l2_ex0_clk_sb_pulse_mode : 2; uint64_t l2_ex0_clk_sw_resclk : 4; uint64_t l2_ex0_clk_sw_spare1 : 1; uint64_t l2_ex1_clk_sync_enable : 1; uint64_t reserved_34_353 : 2; uint64_t l2_ex1_clkglm_async_reset : 1; uint64_t reserved_37_384 : 2; uint64_t l2_ex1_clkglm_sel : 1; uint64_t l2_ex1_clk_sb_strength : 4; uint64_t l2_ex1_clk_sb_spare0 : 1; uint64_t l2_ex1_clk_sb_pulse_mode_en : 1; uint64_t l2_ex1_clk_sb_pulse_mode : 2; uint64_t l2_ex1_clk_sw_resclk : 4; uint64_t l2_ex1_clk_sw_spare1 : 1; uint64_t reserved_53_55 : 3; uint64_t l3_clk_sb_strength : 4; uint64_t l3_clk_sb_spare0 : 1; uint64_t l3_clk_sb_pulse_mode_en : 1; uint64_t l3_clk_sb_pulse_mode : 2; #else uint64_t l3_clk_sb_pulse_mode : 2; uint64_t l3_clk_sb_pulse_mode_en : 1; uint64_t l3_clk_sb_spare0 : 1; uint64_t l3_clk_sb_strength : 4; uint64_t reserved_53_55 : 3; uint64_t l2_ex1_clk_sw_spare1 : 1; uint64_t l2_ex1_clk_sw_resclk : 4; uint64_t l2_ex1_clk_sb_pulse_mode : 2; uint64_t l2_ex1_clk_sb_pulse_mode_en : 1; uint64_t l2_ex1_clk_sb_spare0 : 1; uint64_t l2_ex1_clk_sb_strength : 4; uint64_t l2_ex1_clkglm_sel : 1; uint64_t reserved_37_384 : 2; uint64_t l2_ex1_clkglm_async_reset : 1; uint64_t reserved_34_353 : 2; uint64_t l2_ex1_clk_sync_enable : 1; uint64_t l2_ex0_clk_sw_spare1 : 1; uint64_t l2_ex0_clk_sw_resclk : 4; uint64_t l2_ex0_clk_sb_pulse_mode : 2; uint64_t l2_ex0_clk_sb_pulse_mode_en : 1; uint64_t l2_ex0_clk_sb_spare0 : 1; uint64_t l2_ex0_clk_sb_strength : 4; uint64_t l2_ex0_clkglm_sel : 1; uint64_t reserved_17_182 : 2; uint64_t l2_ex0_clkglm_async_reset : 1; uint64_t reserved_14_151 : 2; uint64_t l2_ex0_clk_sync_enable : 1; uint64_t core_clk_sw_spare : 1; uint64_t core_clk_sw_resclk : 4; uint64_t core_clk_sb_pulse_mode : 2; uint64_t core_clk_sb_pulse_mode_en : 1; uint64_t core_clk_sb_spare : 1; uint64_t core_clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } qppm_qaccr_or_t; typedef union qppm_qacsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 62; uint64_t l2_ex0_clk_sync_done : 1; uint64_t l2_ex1_clk_sync_done : 1; #else uint64_t l2_ex1_clk_sync_done : 1; uint64_t l2_ex0_clk_sync_done : 1; uint64_t reserved1 : 62; #endif // _BIG_ENDIAN } fields; } qppm_qacsr_t; typedef union qppm_vdmcfgr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_vid_compare : 8; uint64_t vdm_overvolt : 4; uint64_t vdm_droop_small : 4; uint64_t vdm_droop_large : 4; uint64_t vdm_droop_xtreme : 4; uint64_t reserved1 : 8; uint64_t vid_compare_max : 8; uint64_t vid_compare_min : 8; uint64_t reserved2 : 16; #else uint64_t reserved2 : 16; uint64_t vid_compare_min : 8; uint64_t vid_compare_max : 8; uint64_t reserved1 : 8; uint64_t vdm_droop_xtreme : 4; uint64_t vdm_droop_large : 4; uint64_t vdm_droop_small : 4; uint64_t vdm_overvolt : 4; uint64_t vdm_vid_compare : 8; #endif // _BIG_ENDIAN } fields; } qppm_vdmcfgr_t; typedef union qppm_edram_ctrl { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t l3_ex0_edram_enable : 1; uint64_t l3_ex0_edram_vwl_enable : 1; uint64_t l3_ex0_edram_vrow_vblh_enable : 1; uint64_t l3_ex0_edram_vpp_enable : 1; uint64_t l3_ex1_edram_enable : 1; uint64_t l3_ex1_edram_vwl_enable : 1; uint64_t l3_ex1_edram_vrow_vblh_enable : 1; uint64_t l3_ex1_edram_vpp_enable : 1; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t l3_ex1_edram_vpp_enable : 1; uint64_t l3_ex1_edram_vrow_vblh_enable : 1; uint64_t l3_ex1_edram_vwl_enable : 1; uint64_t l3_ex1_edram_enable : 1; uint64_t l3_ex0_edram_vpp_enable : 1; uint64_t l3_ex0_edram_vrow_vblh_enable : 1; uint64_t l3_ex0_edram_vwl_enable : 1; uint64_t l3_ex0_edram_enable : 1; #endif // _BIG_ENDIAN } fields; } qppm_edram_ctrl_t; typedef union qppm_edram_ctrl_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t l3_ex0_edram_enable : 1; uint64_t l3_ex0_edram_vwl_enable : 1; uint64_t l3_ex0_edram_vrow_vblh_enable : 1; uint64_t l3_ex0_edram_vpp_enable : 1; uint64_t l3_ex1_edram_enable : 1; uint64_t l3_ex1_edram_vwl_enable : 1; uint64_t l3_ex1_edram_vrow_vblh_enable : 1; uint64_t l3_ex1_edram_vpp_enable : 1; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t l3_ex1_edram_vpp_enable : 1; uint64_t l3_ex1_edram_vrow_vblh_enable : 1; uint64_t l3_ex1_edram_vwl_enable : 1; uint64_t l3_ex1_edram_enable : 1; uint64_t l3_ex0_edram_vpp_enable : 1; uint64_t l3_ex0_edram_vrow_vblh_enable : 1; uint64_t l3_ex0_edram_vwl_enable : 1; uint64_t l3_ex0_edram_enable : 1; #endif // _BIG_ENDIAN } fields; } qppm_edram_ctrl_clr_t; typedef union qppm_edram_ctrl_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t l3_ex0_edram_enable : 1; uint64_t l3_ex0_edram_vwl_enable : 1; uint64_t l3_ex0_edram_vrow_vblh_enable : 1; uint64_t l3_ex0_edram_vpp_enable : 1; uint64_t l3_ex1_edram_enable : 1; uint64_t l3_ex1_edram_vwl_enable : 1; uint64_t l3_ex1_edram_vrow_vblh_enable : 1; uint64_t l3_ex1_edram_vpp_enable : 1; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t l3_ex1_edram_vpp_enable : 1; uint64_t l3_ex1_edram_vrow_vblh_enable : 1; uint64_t l3_ex1_edram_vwl_enable : 1; uint64_t l3_ex1_edram_enable : 1; uint64_t l3_ex0_edram_vpp_enable : 1; uint64_t l3_ex0_edram_vrow_vblh_enable : 1; uint64_t l3_ex0_edram_vwl_enable : 1; uint64_t l3_ex0_edram_enable : 1; #endif // _BIG_ENDIAN } fields; } qppm_edram_ctrl_or_t; #endif // __ASSEMBLER__ #endif // __QPPM_FIRMWARE_REGISTERS_H__ <|start_filename|>src/occ_405/lock/lock.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/lock/lock.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // Debug trace //#define LOCK_DEBUG #ifdef LOCK_DEBUG #define LOCK_DBG(frmt,args...) \ TRAC_INFO(frmt,##args) #else #define LOCK_DBG(frmt,args...) #endif #include <ssx.h> #include <occhw_async.h> #include <gpe_export.h> #include <trac_interface.h> #include <trac.h> #include <occ_common.h> #include <comp_ids.h> #include <occ_service_codes.h> #include "dimm.h" #include "dimm_service_codes.h" #include "lock.h" #include "common.h" #include "state.h" #include "i2c.h" #include <amec_sys.h> extern bool G_mem_monitoring_allowed; typedef enum { LOCK_RELEASE = 0x00, LOCK_ACQUIRE = 0x01 } lockOperation_e; #ifdef DEBUG_LOCK_TESTING // DEBUG: Simulate I2C lock request from the host void host_i2c_lock_request() { ocb_occflg_t occ_flags = {0}; TRAC_INFO("host_i2c_lock_request called (tick %d / %d)", CURRENT_TICK, DIMM_TICK); occ_flags.fields.i2c_engine3_lock_host = 1; TRAC_INFO("host_i2c_lock_request - writing %04X to _OR(0x%08X)", occ_flags.value, OCB_OCCFLG_OR); out32(OCB_OCCFLG_OR, occ_flags.value); occ_flags.value = in32(OCB_OCCFLG); //TRAC_INFO("host_i2c_lock_request - 0x%08X returned value=0x%04X", OCB_OCCFLG, occ_flags.value); if (occ_flags.fields.i2c_engine3_lock_host != 1) { TRAC_INFO("ERROR: host_i2c_lock_request - host not locked! (0x%08X value=0x%04X)", OCB_OCCFLG, occ_flags.value); occ_flags.fields.i2c_engine3_lock_host = 1; occ_flags.fields.i2c_engine3_lock_occ = 1; out32(OCB_OCCFLG, occ_flags.value); occ_flags.value = in32(OCB_OCCFLG); TRAC_INFO("host_i2c_lock_request - write+read 0x%08X returned value=0x%04X", OCB_OCCFLG, occ_flags.value); } } // DEBUG: Simulate I2C lock release from host void host_i2c_lock_release() { TRAC_INFO("host_i2c_lock_release called (tick %d / %d)", CURRENT_TICK, DIMM_TICK); ocb_occmisc_t occmiscreg = {0}; ocb_occflg_t occ_flags = {0}; // clear external interrupt (so OCC can notify host when lock released) occmiscreg.fields.core_ext_intr = 1; out32(OCB_OCCMISC_CLR, occmiscreg.value); // Clear the host request occ_flags.fields.i2c_engine3_lock_host = 1; TRAC_INFO("host_i2c_lock_release - writing %04X to _CLR(0x%08X)", occ_flags.value, OCB_OCCFLG_CLR); out32(OCB_OCCFLG_CLR, occ_flags.value); occ_flags.value = in32(OCB_OCCFLG); //TRAC_INFO("host_i2c_lock_release - 0x%08X returned value=0x%04X", OCB_OCCFLG, occ_flags.value); if (occ_flags.fields.i2c_engine3_lock_host != 0) { TRAC_INFO("ERROR: host_i2c_lock_release - host not released! (0x%08X value=0x%04X)", OCB_OCCFLG, occ_flags.value); occ_flags.fields.i2c_engine3_lock_host = 0; occ_flags.fields.i2c_engine3_lock_occ = 1; out32(OCB_OCCFLG, occ_flags.value); occ_flags.value = in32(OCB_OCCFLG); TRAC_INFO("host_i2c_lock_release - write+read 0x%08X returned value=0x%04X", OCB_OCCFLG, occ_flags.value); } } #endif // Update I2C log information for specified engine // i_op values: // LOC_ACQUIRE = OCC should take ownership of lock // LOC_RELEASE = OCC should release ownership of lock and notify host void update_i2c_lock(const lockOperation_e i_op, const uint8_t i_engine) { ocb_occflg_t occ_flags = {0}; #ifdef DEBUG_LOCK_TESTING ocb_occflg_t flag; flag.value = in32(OCB_OCCFLG); if (LOCK_RELEASE == i_op) { LOCK_DBG("update_i2c_lock: I2C engine %d RELEASE - host=%d, occ=%d, dimmTick=%d", i_engine, flag.fields.i2c_engine3_lock_host, flag.fields.i2c_engine3_lock_occ, DIMM_TICK); } else { LOCK_DBG("update_i2c_lock: I2C engine %d LOCK - host=%d, occ=%d, dimmTick=%d", i_engine, flag.fields.i2c_engine3_lock_host, flag.fields.i2c_engine3_lock_occ, DIMM_TICK); } #endif if (PIB_I2C_ENGINE_E == i_engine) { occ_flags.fields.i2c_engine3_lock_occ = 1; } else if (PIB_I2C_ENGINE_D == i_engine) { occ_flags.fields.i2c_engine2_lock_occ = 1; } else if (PIB_I2C_ENGINE_C == i_engine) { occ_flags.fields.i2c_engine1_lock_occ = 1; } if (LOCK_RELEASE == i_op) { out32(OCB_OCCFLG_CLR, occ_flags.value); // OCC had the lock and host wants it, so send interrupt to host notify_host(INTR_REASON_I2C_OWNERSHIP_CHANGE); TRAC_IMP("update_i2c_lock: OCC has released lock for I2C engine %d", i_engine); } else // LOCK_ACQUIRE { out32(OCB_OCCFLG_OR, occ_flags.value); TRAC_IMP("update_i2c_lock: OCC has acquired lock for I2C engine %d", i_engine); } } // end update_i2c_lock() // Release the OCC lock indefinitely // This should be called when OCC goes into safe mode or will be reset // to allow the host to use the specified I2C engines. // If no engine is specified, locks for all I2C engines will be released void occ_i2c_lock_release(const uint8_t i_engine) { TRAC_INFO("occ_i2c_lock_release(engine %d) called", i_engine); if ((PIB_I2C_ENGINE_ALL == i_engine) || (PIB_I2C_ENGINE_E == i_engine) || (PIB_I2C_ENGINE_D == i_engine) || (PIB_I2C_ENGINE_C == i_engine)) { if ((PIB_I2C_ENGINE_E == i_engine) || (PIB_I2C_ENGINE_ALL == i_engine)) { update_i2c_lock(LOCK_RELEASE, PIB_I2C_ENGINE_E); } if ((PIB_I2C_ENGINE_D == i_engine) || (PIB_I2C_ENGINE_ALL == i_engine)) { update_i2c_lock(LOCK_RELEASE, PIB_I2C_ENGINE_D); } if ((PIB_I2C_ENGINE_C == i_engine) || (PIB_I2C_ENGINE_ALL == i_engine)) { update_i2c_lock(LOCK_RELEASE, PIB_I2C_ENGINE_C); } } else { INTR_TRAC_ERR("occ_i2c_lock_release: Invalid engine specified: 0x%02X", i_engine); } } // end occ_i2c_lock_release() // Determine if the OCC currently owns the lock // Returns true if OCC owns the lock, else false bool occ_owns_i2c_lock(const ocb_occflg_t i_flags, const uint8_t i_engine) { bool ownsLock = false; if (PIB_I2C_ENGINE_E == i_engine) { ownsLock = i_flags.fields.i2c_engine3_lock_occ; } else if (PIB_I2C_ENGINE_D == i_engine) { ownsLock = i_flags.fields.i2c_engine2_lock_occ; } else if (PIB_I2C_ENGINE_C == i_engine) { ownsLock = i_flags.fields.i2c_engine1_lock_occ; } return ownsLock; } // Determine if the Host wants the i2c lock // Returns true if Host wants the lock, else false bool host_wants_i2c_lock(const ocb_occflg_t i_flags, const uint8_t i_engine) { bool wantsLock = false; if (PIB_I2C_ENGINE_E == i_engine) { wantsLock = i_flags.fields.i2c_engine3_lock_host; } else if (PIB_I2C_ENGINE_D == i_engine) { wantsLock = i_flags.fields.i2c_engine2_lock_host; } else if (PIB_I2C_ENGINE_C == i_engine) { wantsLock = i_flags.fields.i2c_engine1_lock_host; } return wantsLock; } // Check and update lock ownership for the specified i2c engine. // Returns true if OCC owns the lock, or false if host owns lock // // If host has requesed the i2c lock, it will be released and an external interrupt // will be generated/queued and function will return false. // If the host has not released the lock, function will return false. // If the host cleared its lock bit, OCC will take back ownership and return true. // bool check_and_update_i2c_lock(const uint8_t i_engine) { bool occ_owns_lock = true; if ((PIB_I2C_ENGINE_E == i_engine) || (PIB_I2C_ENGINE_D == i_engine) || (PIB_I2C_ENGINE_C == i_engine)) { bool needRetry = false; do { ocb_occflg_t original_occflags; original_occflags.value = in32(OCB_OCCFLG); LOCK_DBG("check_and_update_i2c_lock: I2C engine %d - host=%d, occ=%d (dimmTick=%d)", i_engine, original_occflags.fields.i2c_engine3_lock_host, original_occflags.fields.i2c_engine3_lock_occ, DIMM_TICK); if (occ_owns_i2c_lock(original_occflags, i_engine)) { if (host_wants_i2c_lock(original_occflags, i_engine)) { // Host requested lock, clear the OCC lock and notify host update_i2c_lock(LOCK_RELEASE, i_engine); occ_owns_lock = false; } // else OCC already owns the lock } else { // OCC does not own the lock occ_owns_lock = false; if (false == host_wants_i2c_lock(original_occflags, i_engine)) { // Host is not requesting the lock, acquire lock for OCC update_i2c_lock(LOCK_ACQUIRE, i_engine); occ_owns_lock = true; } // else Host still holds the lock } if ((occ_owns_lock) && (original_occflags.fields.i2c_engine1_lock_host == 0) && (original_occflags.fields.i2c_engine1_lock_occ == 0)) { // If neither lock bit is set, we must read back the register to make // sure the host did not set at same time (lock conflict) ocb_occflg_t verify_occflags; verify_occflags.value = in32(OCB_OCCFLG); if (host_wants_i2c_lock(verify_occflags, i_engine)) { // Host wrote their lock bit at same time, clear OCC lock and notify host update_i2c_lock(LOCK_RELEASE, i_engine); occ_owns_lock = false; } else { if (false == occ_owns_i2c_lock(verify_occflags, i_engine)) { // ERROR - OCC OWNERSHIP BIT DID NOT GET SET INTR_TRAC_ERR("check_and_update_i2c_lock: I2C lock bit did not get set (OCCFLAGS reg: 0x%08X)", verify_occflags.value); if (needRetry) { // After one retry, log error and goto safe /* * @errortype * @moduleid I2C_LOCK_UPDATE * @reasoncode OCI_WRITE_FAILURE * @userdata1 I2C engine number * @userdata2 OCC Flags register * @devdesc OCI write failure setting I2C ownership bit */ errlHndl_t err = createErrl(I2C_LOCK_UPDATE, OCI_WRITE_FAILURE, OCC_NO_EXTENDED_RC, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, i_engine, verify_occflags.value); //Callout firmware addCalloutToErrl(err, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_FIRMWARE, ERRL_CALLOUT_PRIORITY_MED); //Callout processor addCalloutToErrl(err, ERRL_CALLOUT_TYPE_HUID, G_sysConfigData.proc_huid, ERRL_CALLOUT_PRIORITY_LOW); REQUEST_RESET(err); occ_owns_lock = false; break; } needRetry = true; } // else verify succeeded (OCC owns lock) } } } while (needRetry); } else { // Invalid engine INTR_TRAC_ERR("check_and_update_i2c_lock: Invalid engine specified: 0x%02X", i_engine); } return occ_owns_lock; } // end check_and_update_i2c_lock() <|start_filename|>src/occ_405/thread/threadSch.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/thread/threadSch.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _THREADSCH_H #define _THREADSCH_H #include <occ_common.h> #include <thread.h> #include "ssx.h" #include <errl.h> // Function to reprioritize the threads in the array void threadSwapcallback(void * arg); // Function to initilize the threads and the thread schedule timer void initThreadScheduler(void) INIT_SECTION; // Function to create and resume thread. Externalizing as it is used to // create main thread int createAndResumeThreadHelper(SsxThread *io_thread, SsxThreadRoutine i_thread_routine, void *io_arg, SsxAddress i_stack, size_t i_stack_size, THREAD_PRIORITY i_priority); #endif //_THREADSCH_H <|start_filename|>src/ssx/occhw/occhw_id.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_id.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_id.h /// \brief processor chip and EC-level identification + chip configuration #include "ssx.h" #include "chip_config.h" // Note: These cached variables are all declared as 64 bits, noncacheable so // that that they are also available as-is to PORE programs. uint64_t G_node_id SECTION_ATTRIBUTE(".noncacheable") = 0; uint64_t G_chip_id SECTION_ATTRIBUTE(".noncacheable") = 0; uint64_t G_cfam_id SECTION_ATTRIBUTE(".noncacheable") = 0; uint64_t G_cfam_chip_type SECTION_ATTRIBUTE(".noncacheable") = 0; uint64_t G_cfam_ec_level SECTION_ATTRIBUTE(".noncacheable") = 0; void _occhw_get_ids(void) { tpc_gp0_t gp0; tpc_device_id_t deviceId; cfam_id_t cfamId; getscom(TPC_GP0, &(gp0.value)); G_node_id = gp0.fields.tc_node_id_dc; G_chip_id = gp0.fields.tc_chip_id_dc; getscom(TPC_DEVICE_ID, &(deviceId.value)); G_cfam_id = cfamId.value = deviceId.fields.cfam_id; G_cfam_chip_type = cfamId.chipType; G_cfam_ec_level = (cfamId.majorEc << 4) | cfamId.minorEc; } uint8_t node_id(void) { return G_node_id; } uint8_t chip_id(void) { return G_chip_id; } uint32_t cfam_id(void) { return G_cfam_id; } uint8_t cfam_chip_type(void) { return G_cfam_chip_type; } uint8_t cfam_ec_level(void) { return G_cfam_ec_level; } // The chiplet configuration is computed by doing a "select-mode" multicast to // the all-functional-chiplets-core group. Correctness here depends on the // convention that the "select" bit number will always be 0. We check just to // be sure. Since this is called from initialization code there is no recourse // here except to panic in the event of error. // Note: Ex-chiplets start at chiplet 16 and are left-justified in the // ChipConfig. ChipConfig G_chip_configuration SECTION_ATTRIBUTE(".noncacheable") = 0; uint64_t G_core_configuration SECTION_ATTRIBUTE(".noncacheable") = 0; /// \bug This API currently only computes the core configuration. It needs to /// be extended to also compute the MC and Centaur configuration. /// /// \bug in Simics we're doing this based on the PMC_CORE_DECONFIGURATION_REG /// pending Simics support for the base pervasive functionality #if 0 void _occhw_get_chip_configuration(void) { if (SIMICS_ENVIRONMENT) { pmc_core_deconfiguration_reg_t pcdr; pcdr.value = in32(PMC_CORE_DECONFIGURATION_REG); G_chip_configuration = ~((uint64_t)(pcdr.fields.core_chiplet_deconf_vector) << 48); } else { uint64_t select, configuration; int rc; rc = getscom(0x000f0008, &select); /* TP CHIPLET SELECT */ if (rc) { SSX_PANIC(OCCHW_ID_SCOM_ERROR_SELECT); } if (select != 0) { SSX_PANIC(OCCHW_ID_SELECT_ERROR); } rc = getscom(MC_ADDRESS(0x000f0012, MC_GROUP_EX_CORE, PCB_MULTICAST_SELECT), &configuration); if (rc) { SSX_PANIC(OCCHW_ID_SCOM_ERROR_CONFIG); } G_chip_configuration = (configuration << 16) & 0xffff000000000000ull; } G_core_configuration = G_chip_configuration & 0xffff000000000000ull; } #endif uint32_t core_configuration(void) { return G_core_configuration >> 32; } <|start_filename|>src/occ_405/proc/proc_data.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/proc/proc_data.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _PROC_DATA_H #define _PROC_DATA_H #include <occ_common.h> #include <ssx.h> #include "rtls.h" #include "proc_shared.h" //Returns 0 if the specified core is not present. Otherwise, returns none-zero. #define CORE_PRESENT(occ_core_id) \ ((CORE0_PRESENT_MASK >> occ_core_id) & G_present_cores) #define ALL_CORES_MASK 0xffffff00 #define CORE0_PRESENT_MASK 0x80000000ul #define CORE0_PRESENT_MASK_GPE 0x8000000000000000ull #define MAX_NUM_HW_CORES 24 #define MAX_NUM_FW_CORES 24 #define CORE_MID_POINT (MAX_NUM_FW_CORES / 2) #define THREADS_PER_CORE 4 // A dts should be considered invalid if it is returning a negative reading the dts reading is // actually only 8 bits (not 12 as the structure has) the signed bit is msb of the 8 bit reading #define DTS_INVALID_MASK 0x80 #define NUM_CORE_DATA_BUFF 7 #define NUM_CORE_DATA_DOUBLE_BUF 2 #define NUM_CORE_DATA_EMPTY_BUF 1 #define LO_CORES_MASK 0xfff00000 #define HI_CORES_MASK 0x000fff00 #define HW_CORES_MASK 0xffffff00 #define QUAD0_CORES_PRESENT_MASK 0xf0000000 enum eOccProcCores { CORE_0 = 0, CORE_1 = 1, CORE_2 = 2, CORE_3 = 3, CORE_4 = 4, CORE_5 = 5, CORE_6 = 6, CORE_7 = 7, CORE_8 = 8, CORE_9 = 9, CORE_10 = 10, CORE_11 = 11, CORE_12 = 12, CORE_13 = 13, CORE_14 = 14, CORE_15 = 15, CORE_16 = 16, CORE_17 = 17, CORE_18 = 18, CORE_19 = 19, CORE_20 = 20, CORE_21 = 21, CORE_22 = 22, CORE_23 = 23, }; //Processor data collect structures used for task data pointers //gpe_req.cmd_data points to ipc_core_data_parms_t struct bulk_core_data_task { uint8_t start_core; uint8_t current_core; uint8_t end_core; CoreData * core_data_ptr; GpeRequest gpe_req; } __attribute__ ((__packed__)); typedef struct bulk_core_data_task bulk_core_data_task_t; //Global low and high cores structures used for task data pointers extern bulk_core_data_task_t G_low_cores; extern bulk_core_data_task_t G_high_cores; //Global G_present_cores is bitmask of all OCC core numbering extern uint32_t G_present_cores; //AMEC needs to know when data for a core has been collected. extern uint32_t G_updated_core_mask; //AMEC needs to know when a core is offline extern uint32_t G_core_offline_mask; // External reference to empath error mask extern uint32_t G_empath_error_core_mask; extern bool G_nest_dts_data_valid; //Returns 0 if the specified core is not updated. Otherwise, returns none-zero. #define CORE_UPDATED(occ_core_id) \ ((CORE0_PRESENT_MASK >> occ_core_id) & G_updated_core_mask) //Returns 0 if the specified core is not updated. Otherwise, returns none-zero. #define CLEAR_CORE_UPDATED(occ_core_id) \ G_updated_core_mask &= ~(CORE0_PRESENT_MASK >> occ_core_id) // Evaluates to true if an empath collection error has occurred on a core #define CORE_EMPATH_ERROR(occ_core_id) \ ((CORE0_PRESENT_MASK >> occ_core_id) & G_empath_error_core_mask) // Evaluates to true if the specified core is offline #define CORE_OFFLINE(occ_core_id) \ ((CORE0_PRESENT_MASK >> occ_core_id) & G_core_offline_mask) #define CLEAR_CORE_OFFLINE(occ_core_id) \ G_core_offline_mask &= ~(CORE0_PRESENT_MASK >> occ_core_id) // Evaluates to true if the specified quad has at least 1 active present core #define QUAD_ONLINE(occ_quad_id) \ ( (QUAD0_CORES_PRESENT_MASK >> (occ_quad_id*4)) & ((~G_core_offline_mask) & G_present_cores) ) //Collect bulk core data for all cores in specified range void task_core_data( task_t * i_task ); //Initialize structures for collecting core data. void proc_core_init( void ) INIT_SECTION; // Collect nest dts temperature sensors void task_nest_dts( task_t * i_task ); // Initialize structures for collecting nest dts temps void nest_dts_init( void ) INIT_SECTION; //Returns a pointer to the most up-to-date bulk core data for the core //associated with the specified OCC core id. CoreData * proc_get_bulk_core_data_ptr( const uint8_t i_occ_core_id ); // 24x7 data collection void task_24x7( task_t * i_task ); #endif //_PROC_DATA_H <|start_filename|>src/occ_gpe1/gpe1_dimm_read.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/gpe1_dimm_read.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file gpe1_dimm_read.c /// \brief Functions to handle reading the DIMM temperatures /// //#define GPE1_DEBUG #include "pk.h" #include "ipc_api.h" #include "ppe42_scom.h" #include "ipc_async_cmd.h" #include "gpe1.h" #include "gpe1_dimm.h" #include "dimm_structs.h" #include "i2c.h" void dimm_write_int_mask(ipc_msg_t* cmd, void* arg); void dimm_write_mode(ipc_msg_t* cmd, void* arg); void dimm_write_ts_addr(ipc_msg_t* cmd, void* arg); void dimm_initiate_read(ipc_msg_t* cmd, void* arg); void dimm_read_temp(ipc_msg_t* cmd, void* arg); // from gpe1_dimm_reset.c void dimm_reset_master(ipc_msg_t* cmd, void* arg); void dimm_reset_slave(ipc_msg_t* cmd, void* arg); void dimm_reset_slave_status(ipc_msg_t* cmd, void* arg); /* * Function Specification * * Name: gpe_set_ffdc * * Description: Fills up the error struct with the given data. * * End Function Specification */ void gpe_set_ffdc(GpeErrorStruct *o_error, uint32_t i_addr, uint32_t i_rc, uint64_t i_ffdc) { o_error->addr = i_addr; //Return codes defined in gpe_err.h o_error->rc = i_rc; o_error->ffdc = i_ffdc; } /* * Function Specifications: * * Name: gpe_dimm_sm * * Description: DIMM I2C State Machine handler in the GPE * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void gpe_dimm_sm(ipc_msg_t* cmd, void* arg) { // Note: arg was set to 0 in ipc func table (ipc_func_tables.c), so don't use it. // the ipc arguments passed through the ipc_msg_t structure, has a pointer // to the G_gpe_start_pwr_meas_read_args struct. int rc; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // clear error args->error.error = 0; args->error.ffdc = 0; // Need to mask machine checks for I2C master: // // Turn off MCR bit will prevent machine check on error on scom readings (MSR bits 1:7) // rc == 1 resource occupied (see ppe42_scom.h) Action: return with rc // rc == 2 Core is fenced, offline Action: return with rc // rc == 3 partial good // rc == 4 address error // rc == 5 clock error // rc == 6 packet error // rc == 7 timeout // // Clear: last SIB rc (SIBRC) and rc accumulator (SIMBRCA) // Set: SIB Error Mask to prevent machine checks for any rcs const uint32_t orig_msr = mfmsr(); const uint32_t msr = (orig_msr & ~(MSR_SIBRC | MSR_SIBRCA)) | MSR_SEM; mtmsr(msr); switch(args->state) { case DIMM_STATE_INIT: dimm_write_int_mask(cmd, arg); break; // Read DIMM Temperature States case DIMM_STATE_WRITE_MODE: dimm_write_mode(cmd, arg); break; case DIMM_STATE_WRITE_ADDR: dimm_write_ts_addr(cmd, arg); break; case DIMM_STATE_INITIATE_READ: dimm_initiate_read(cmd, arg); break; case DIMM_STATE_READ_TEMP: dimm_read_temp(cmd, arg); break; // I2C Reset States case DIMM_STATE_RESET_MASTER: dimm_reset_master(cmd, arg); break; case DIMM_STATE_RESET_SLAVE_P0: case DIMM_STATE_RESET_SLAVE_P1: dimm_reset_slave(cmd, arg); break; case DIMM_STATE_RESET_SLAVE_P0_COMPLETE: case DIMM_STATE_RESET_SLAVE_P1_COMPLETE: dimm_reset_slave_status(cmd, arg); break; default: PK_TRACE("gpe_dimm_sm: Invalid state (0x%02X) received!", args->state); args->error.rc = 0; gpe_set_ffdc(&(args->error), 0, GPE_RC_INVALID_STATE, args->state); break; } // Send back IPC response of success (IPC operation itself succeeded) // (if any operation failed, the error (rc/ffdc) will be non-zero // and can be handled by the 405) rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("gpe_dimm_sm: Failed to send response back. Halting GPE1", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } // Restore original MSR and clear SIBRC and SIBRCA mtmsr(orig_msr & ~(MSR_SIBRC | MSR_SIBRCA)); } // end gpe_dimm_sm() /* * Function Specifications: * * Name: dimm_write_int_mask * * Description: Write the I2C interrupt mask and read I2C status register * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_write_int_mask(ipc_msg_t* cmd, void* arg) { int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; scomAddr = I2C_INTERRUPT_MASK_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); // Enable the following bit in the interrupt mask: // invalid command, LBUS parity, back end overrun, back end access, // arbitration lost, nack received, data request, command complete, // stop, i2c busy regValue = 0x0000FFC000000000; rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_write_int_mask: I2C_INTERRUPT_MASK_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_write_int_mask: putscom(0x%08X,0x%08X%08X) SUCCESS - INT MASK", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); } // READ I2C STATUS REGISTER scomAddr = I2C_STATUS_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); rc = getscom_abs(scomAddr, &regValue); if(rc) { PK_TRACE("dimm_write_int_mask: I2C_STATUS_REG getscom 0x%08X FAILED. rc = 0x%08x - STATUS", scomAddr, rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_GET_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_write_int_mask: getscom(0x%08X) returned 0x%08X%08X) - STATUS #1", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); // max_num_of_ports (bits 9:15) args->maxPorts = (regValue >> 48) & 0x7F; GPE1_DIMM_DBG("dimm_write_int_mask: maxPorts = %d", args->maxPorts); } } // end dimm_write_int_mask() /* * Function Specifications: * * Name: dimm_write_mode * * Description: Write the I2C mode register (set speed and port) * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_write_mode(ipc_msg_t* cmd, void* arg) { // Note: arg was set to 0 in ipc func table (ipc_func_tables.c), so don't use it. // the ipc arguments passed through the ipc_msg_t structure, has a pointer // to the G_gpe_start_pwr_meas_read_args struct. int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // MODE_REGISTER scomAddr = I2C_MODE_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); // 0-15: Bit Rate Divisor - 0x0049 gives approx 391kHz (and allows margin for clock variation) // 16-21: Port Number (0-5) // 22-26: reserved (0s) regValue = I2C_MODE_REG_DIVISOR; if ((args->i2cPort > 0) && (args->i2cPort < 6)) { regValue |= ((uint64_t)args->i2cPort << 42); } rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_write_mode: I2C_MODE_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_write_mode: putscom(0x%08X,0x%08X%08X) SUCCESS - MODE", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); } } // end dimm_write_mode() /* * Function Specifications: * * Name: dimm_write_ts_addr * * Description: Write the Temperature Sensor address to I2C * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_write_ts_addr(ipc_msg_t* cmd, void* arg) { int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // Write I2C command register with a 1 byte write scomAddr = I2C_COMMAND_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); // start+address + slave_address, rw=0=write, length=1, i2c address regValue = 0xC000000100000000 | ((uint64_t)args->i2cAddr << 48); rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_write_ts_addr: I2C_COMMAND_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_write_ts_addr: putscom(0x%08X,0x%08X%08X) SUCCESS - COMMAND (write)", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); // Write the Temperature Sensor address to the FIFO register scomAddr = I2C_FIFO1_REG_READ | SCOM_ENGINE_OFFSET(args->i2cEngine); // 0x05 = temperature value regValue = 0x0500000000000000; rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_write_ts_addr: I2C_FIFO_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_write_ts_addr: putscom(0x%08X,0x%08X%08X) SUCCESS - FIFO", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); } } } // end dimm_write_ts_addr() /* * Function Specifications: * * Name: dimm_initiate_read * * Description: Initiate the read of the temperature sensor * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_initiate_read(ipc_msg_t* cmd, void* arg) { int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // Default the rc to NOT_COMPLETE (meaning the read was not initiated) args->error.rc = GPE_RC_NOT_COMPLETE; // Read the I2c Status Register to ensure the TS address was written successfully scomAddr = I2C_STATUS_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); rc = getscom_abs(scomAddr, &regValue); if(rc) { PK_TRACE("dimm_initiate_read: I2C_STATUS_REG getscom 0x%08X FAILED. rc = 0x%08x", scomAddr, rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_GET_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_initiate_read: getscom(0x%08X) returned 0x%08X%08X - STATUS", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); if ((regValue & STATUS_ERROR_OR_COMPLETE_MASK) == STATUS_COMPLETE_MASK) { // Status register indicates no errors and last command completed. // Write the I2C command register with a 2 byte read request. // Since FIFO4 can read 4 bytes in one operation, we will do a read of 4 bytes // and only look at first 2 bytes. (FIFO4 will hang if only try to read 2 bytes) scomAddr = I2C_COMMAND_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); // start+address+stop + slave_address, rw=1=read, length=4 regValue = 0xD001000400000000; regValue |= ((uint64_t)args->i2cAddr << 48); rc = putscom_abs(scomAddr, regValue); if(rc) { PK_TRACE("dimm_initiate_read: I2C_COMMAND_REG putscom 0x%08X->0x%08X%08X FAILED. rc = 0x%08x", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue), rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_PUT_FAILED, rc); } else { // The read command has been started, return success GPE1_DIMM_DBG("dimm_initiate_read: putscom(0x%08X,0x%08X%08X) SUCCESS - COMMAND (read)", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); args->error.error = 0; args->error.rc = GPE_RC_SUCCESS; args->error.ffdc = 0; } } else { if ((regValue & STATUS_ERROR_OR_COMPLETE_MASK) != 0) { // I2C error was found PK_TRACE("dimm_initiate_read: Error in status register: 0x%08X%08X", WORD_HIGH(regValue), WORD_LOW(regValue)); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_I2C_ERROR, regValue); } else { // Last command (write TS address) has not completed yet PK_TRACE("dimm_initiate_read: last command not complete yet..."); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_NOT_COMPLETE, regValue); } // else, not complete yet } } } // end dimm_initiate_read() /* * Function Specifications: * * Name: dimm_read_temp * * Description: Read the temperature sensor value * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void dimm_read_temp(ipc_msg_t* cmd, void* arg) { int rc; uint32_t scomAddr; uint64_t regValue; // a pointer to hold the putscom_abs register value ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; dimm_sm_args_t *args = (dimm_sm_args_t*)async_cmd->cmd_data; // Default the rc to NOT_COMPLETE (meaning the read has not completed) args->error.rc = GPE_RC_NOT_COMPLETE; // Read the I2C status register scomAddr = I2C_STATUS_REG | SCOM_ENGINE_OFFSET(args->i2cEngine); rc = getscom_abs(scomAddr, &regValue); if(rc) { PK_TRACE("dimm_read_temp: I2C_STATUS_REG getscom 0x%08X FAILED. rc = 0x%08x - STATUS #1", scomAddr, rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_GET_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_read_temp: getscom(0x%08X) returned 0x%08X%08X) - STATUS #1", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); uint8_t fifoLength = (regValue >> 32) & 0xFF; if ((regValue & STATUS_ERROR_MASK) != 0) { // I2C error was found PK_TRACE("dimm_read_temp: Error in status register: 0x%08X%08X", WORD_HIGH(regValue), WORD_LOW(regValue)); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_I2C_ERROR, regValue); } else { // Need to wait until both bytes are available if (fifoLength >= 2) { // Read the sensor value from the FIFO4 register scomAddr = I2C_FIFO4_REG_READ | SCOM_ENGINE_OFFSET(args->i2cEngine); rc = getscom_abs(scomAddr, &regValue); if(rc) { PK_TRACE("dimm_read_temp: I2C_FIFO4_REG getscom 0x%08X FAILED. rc = 0x%08x", scomAddr, rc); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_SCOM_GET_FAILED, rc); } else { GPE1_DIMM_DBG("dimm_read_temp: getscom(0x%08X) returned 0x%08X%08X) - FIFO4", scomAddr, WORD_HIGH(regValue), WORD_LOW(regValue)); // Temperature is in bits 4-11 args->temp = (regValue >> 52) & 0xFF; args->error.error = 0; args->error.rc = GPE_RC_SUCCESS; args->error.ffdc = 0; GPE1_DIMM_DBG("dimm_read_temp: DIMM%04X temperature=%dC", (args->i2cPort<<8)|args->dimm, args->temp); // Check for operation complete bit // (operation complete bit will not get set until all // data has been read from the FIFO.) if (regValue & PEEK_ERROR_MASK) { // I2C error was found PK_TRACE("dimm_read_temp: Error in FIFO4 peek data: 0x%08X%08X", WORD_HIGH(regValue), WORD_LOW(regValue)); gpe_set_ffdc(&(args->error), scomAddr, GPE_RC_I2C_ERROR, regValue); } // PEEK_MORE_DATA will be set because we only read 2 of the 4 bytes (ignore this bit) } } // else, all data not available yet (NOT_COMPLETE) } } } // end dimm_read_temp() <|start_filename|>src/include/registers/sramctl_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/sramctl_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SRAMCTL_FIRMWARE_REGISTERS_H__ #define __SRAMCTL_FIRMWARE_REGISTERS_H__ /// \file sramctl_firmware_registers.h /// \brief C register structs for the SRAMCTL unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union sramctl_srbar { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t sram_region_qualifier : 2; uint32_t reserved : 3; uint32_t sram_bar_region : 8; uint32_t _reserved0 : 19; #else uint32_t _reserved0 : 19; uint32_t sram_bar_region : 8; uint32_t reserved : 3; uint32_t sram_region_qualifier : 2; #endif // _BIG_ENDIAN } fields; } sramctl_srbar_t; typedef union sramctl_srmr { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t sram_enable_remap : 1; uint32_t sram_arb_en_send_all_writes : 1; uint32_t sram_disable_lfsr : 1; uint32_t sram_lfsr_fairness_mask : 5; uint32_t sram_error_inject_enable : 1; uint32_t sram_ctl_trace_en : 1; uint32_t sram_ctl_trace_sel : 1; uint32_t reserved : 5; uint32_t _reserved0 : 16; #else uint32_t _reserved0 : 16; uint32_t reserved : 5; uint32_t sram_ctl_trace_sel : 1; uint32_t sram_ctl_trace_en : 1; uint32_t sram_error_inject_enable : 1; uint32_t sram_lfsr_fairness_mask : 5; uint32_t sram_disable_lfsr : 1; uint32_t sram_arb_en_send_all_writes : 1; uint32_t sram_enable_remap : 1; #endif // _BIG_ENDIAN } fields; } sramctl_srmr_t; typedef union sramctl_srmap { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t reserved : 1; uint32_t sram_remap_source : 12; uint32_t _reserved0 : 1; uint32_t reserved1 : 3; uint32_t sram_remap_dest : 13; uint32_t reserved2 : 2; #else uint32_t reserved2 : 2; uint32_t sram_remap_dest : 13; uint32_t reserved1 : 3; uint32_t _reserved0 : 1; uint32_t sram_remap_source : 12; uint32_t reserved : 1; #endif // _BIG_ENDIAN } fields; } sramctl_srmap_t; typedef union sramctl_srear { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t sram_error_address : 16; uint32_t _reserved0 : 16; #else uint32_t _reserved0 : 16; uint32_t sram_error_address : 16; #endif // _BIG_ENDIAN } fields; } sramctl_srear_t; typedef union sramctl_srbv0 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t boot_vector_word0 : 32; #else uint32_t boot_vector_word0 : 32; #endif // _BIG_ENDIAN } fields; } sramctl_srbv0_t; typedef union sramctl_srbv1 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t boot_vector_word1 : 32; #else uint32_t boot_vector_word1 : 32; #endif // _BIG_ENDIAN } fields; } sramctl_srbv1_t; typedef union sramctl_srbv2 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t boot_vector_word2 : 32; #else uint32_t boot_vector_word2 : 32; #endif // _BIG_ENDIAN } fields; } sramctl_srbv2_t; typedef union sramctl_srbv3 { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t boot_vector_word3 : 32; #else uint32_t boot_vector_word3 : 32; #endif // _BIG_ENDIAN } fields; } sramctl_srbv3_t; typedef union sramctl_srchsw { uint32_t value; struct { #ifdef _BIG_ENDIAN uint32_t chksw_wrfsm_dly_dis : 1; uint32_t chksw_allow1_rd : 1; uint32_t chksw_allow1_wr : 1; uint32_t chksw_allow1_rdwr : 1; uint32_t chksw_oci_parchk_dis : 1; uint32_t chksw_tank_rddata_parchk_dis : 1; uint32_t chksw_tank_sr_rderr_dis : 1; uint32_t chksw_val_be_addr_chk_dis : 1; uint32_t chksw_so_spare : 2; uint32_t _reserved0 : 22; #else uint32_t _reserved0 : 22; uint32_t chksw_so_spare : 2; uint32_t chksw_val_be_addr_chk_dis : 1; uint32_t chksw_tank_sr_rderr_dis : 1; uint32_t chksw_tank_rddata_parchk_dis : 1; uint32_t chksw_oci_parchk_dis : 1; uint32_t chksw_allow1_rdwr : 1; uint32_t chksw_allow1_wr : 1; uint32_t chksw_allow1_rd : 1; uint32_t chksw_wrfsm_dly_dis : 1; #endif // _BIG_ENDIAN } fields; } sramctl_srchsw_t; #endif // __ASSEMBLER__ #endif // __SRAMCTL_FIRMWARE_REGISTERS_H__ <|start_filename|>src/occ_405/arl_test.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/arl_test.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "ssx_io.h" #include "simics_stdio.h" #include "arl_test_data.h" #ifdef AMEC_ARL_TEST_COMPILE sOCCData_t gOCC = {0}; sRTLData_t gRTL = {0}; sOCCData_t * gpOCC = &gOCC; sRTLData_t * gpRTL = &gRTL; #endif /////////////////////////////////////////////////////////////////////////////// // Function Specification // // Name: arl_test // // Description: Perform any needed mode changes void arl_test(void) { #ifdef AMEC_ARL_TEST_COMPILE UINT8 i = 0; UINT32 temp32 = 0; UINT32 temp32a = 0; UINT16 temp16 = 0; UINT16 temp16a = 0; //gpRTL->cycles250usincrement = CYCLES_INC; // hard coded to correspond to 4GHz and the # of cycles every 250usec gpRTL->cycles250us = gpRTL->cycles250us + gpRTL->cycles250usincrement; // Inject raw cycle counter (currently based on 4GHz core frequency) gpOCC->SCOM_ARRAY[INDEX_PC_RAW]=gpRTL->cycles250us; // Compute differential in raw PC cycles temp32 = gpOCC->SCOM_ARRAY[INDEX_PC_RAW]; temp32a = gpRTL->scom_prev_PC_RAW_250us; temp32 = temp32 - temp32a; // Convert to frequency for this core temp32 = temp32 << 8; // Shift left 8 bits (raw value is < 2^24) temp32a = 64000; // Divide by 64000 to convert to frequency sensor in 1MHz increments temp32 = temp32 / temp32a; gpRTL->FREQREQC0=(UINT16)temp32; // Write to frequency sensor // Debug code to inject data into SCOMs for per thread information for (i=0; i<MAX_THREADS; i++) { temp32 = gpRTL->utilcounter[i]+gpRTL->utilincrement[i]; gpRTL->utilcounter[i]=temp32; gpOCC->SCOM_ARRAY[INDEX_PC_RUN_T0+i]=temp32; } ////////////////////// // 2ms state machine switch (gpOCC->AME_sm_cnt) { ///////////////////////////////////////////////////////////// // STATE 0 of EMPATH 2msec State Machine // This state processes core 0's per thread utilization SCOMs ///////////////////////////////////////////////////////////// case 0x00: // Code to read SCOM_ARRAY and convert into actual per thread utilization sensors // First step is to calculate how many raw cycles went by in the core during the last 2msec temp32 = gpOCC->SCOM_ARRAY[INDEX_PC_RAW]; temp32a = gpRTL->scom_prev_PC_RAW_2ms; // Compute 32 bit differential between SCOM reads now and previous 2msec gpRTL->cycles2ms = temp32 - temp32a; for (i=0; i<MAX_THREADS; i++) { temp32 = gpOCC->SCOM_ARRAY[INDEX_PC_RUN_T0+i]; // Read 32 bit SCOM value for this thread (free running) temp32a = gpRTL->scom_prev_thread[i]; // Read previous 32 bit SCOM value from 32msec ago temp32 = temp32 - temp32a; // Compute 32 bit differential between SCOM reads now and previous 2msec temp32 = temp32 >> 8; // Limit to 16 bits (highest count is < 2^24) temp16 = (UINT16)temp32; temp16a = 10000; // 10000 = 100.00% temp32 = ((UINT32)temp16a)*((UINT32)temp16); // scale by 10000 temp32a = gpRTL->cycles2ms; temp32a = temp32a >> 8; // Limit to 16 bits temp32 = temp32 / temp32a; gpRTL->util2ms_thread[i]=(UINT16)temp32; } // Last step is to remember current SCOMs in scom_prev_thread array for next time for (i=0; i<MAX_THREADS; i++) { gpRTL->scom_prev_thread[i] = gpOCC->SCOM_ARRAY[INDEX_PC_RUN_T0+i]; } gpRTL->scom_prev_PC_RAW_2ms = gpOCC->SCOM_ARRAY[INDEX_PC_RAW]; // Capture raw cycle count for usage in the next 2msec break; ///////////////////////////////////////////////////////////// // STATE 1 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x01: break; ///////////////////////////////////////////////////////////// // STATE 2 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x02: break; ///////////////////////////////////////////////////////////// // STATE 3 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x03: break; ///////////////////////////////////////////////////////////// // STATE 4 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x04: break; ///////////////////////////////////////////////////////////// // STATE 5 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x05: break; ///////////////////////////////////////////////////////////// // STATE 6 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x06: break; ///////////////////////////////////////////////////////////// // STATE 7 of EMPATH 2msec State Machine ///////////////////////////////////////////////////////////// case 0x07: break; } // Capture raw cycle count to use in next 250us gpRTL->scom_prev_PC_RAW_250us = gpOCC->SCOM_ARRAY[INDEX_PC_RAW]; // Increment AME state machine counter using modulo AME_SM_TICK gpOCC->AME_sm_cnt = (UINT8) ((gpOCC->AME_sm_cnt + 1) & (AME_SM_TICKS - 1)); // Always increment AME time on every call to ISR gpOCC->r_cnt++; // Insert ARL Test Code Here //printf("ARL Test Code\n"); #endif } <|start_filename|>src/include/registers/ppm_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/ppm_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPM_FIRMWARE_REGISTERS_H__ #define __PPM_FIRMWARE_REGISTERS_H__ /// \file ppm_firmware_registers.h /// \brief C register structs for the PPM unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union ppm_gpmmr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t special_wkup_done : 1; uint64_t special_wkup_active : 1; uint64_t regular_wkup_active : 1; uint64_t special_wkup_requested : 1; uint64_t regular_wkup_requested : 1; uint64_t regular_wkup_present : 1; uint64_t block_reg_wkup_events : 1; uint64_t block_all_wkup_events : 1; uint64_t wkup_override_en : 1; uint64_t spc_wkup_override : 1; uint64_t reg_wkup_override : 1; uint64_t chiplet_enable : 1; uint64_t reserved_12_141 : 3; uint64_t reset_state_indicator : 1; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t reset_state_indicator : 1; uint64_t reserved_12_141 : 3; uint64_t chiplet_enable : 1; uint64_t reg_wkup_override : 1; uint64_t spc_wkup_override : 1; uint64_t wkup_override_en : 1; uint64_t block_all_wkup_events : 1; uint64_t block_reg_wkup_events : 1; uint64_t regular_wkup_present : 1; uint64_t regular_wkup_requested : 1; uint64_t special_wkup_requested : 1; uint64_t regular_wkup_active : 1; uint64_t special_wkup_active : 1; uint64_t special_wkup_done : 1; #endif // _BIG_ENDIAN } fields; } ppm_gpmmr_t; typedef union ppm_gpmmr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t special_wkup_done : 1; uint64_t special_wkup_active : 1; uint64_t regular_wkup_active : 1; uint64_t special_wkup_requested : 1; uint64_t regular_wkup_requested : 1; uint64_t regular_wkup_present : 1; uint64_t block_reg_wkup_events : 1; uint64_t block_all_wkup_events : 1; uint64_t wkup_override_en : 1; uint64_t spc_wkup_override : 1; uint64_t reg_wkup_override : 1; uint64_t chiplet_enable : 1; uint64_t reserved_12_141 : 3; uint64_t reset_state_indicator : 1; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t reset_state_indicator : 1; uint64_t reserved_12_141 : 3; uint64_t chiplet_enable : 1; uint64_t reg_wkup_override : 1; uint64_t spc_wkup_override : 1; uint64_t wkup_override_en : 1; uint64_t block_all_wkup_events : 1; uint64_t block_reg_wkup_events : 1; uint64_t regular_wkup_present : 1; uint64_t regular_wkup_requested : 1; uint64_t special_wkup_requested : 1; uint64_t regular_wkup_active : 1; uint64_t special_wkup_active : 1; uint64_t special_wkup_done : 1; #endif // _BIG_ENDIAN } fields; } ppm_gpmmr_clr_t; typedef union ppm_gpmmr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t special_wkup_done : 1; uint64_t special_wkup_active : 1; uint64_t regular_wkup_active : 1; uint64_t special_wkup_requested : 1; uint64_t regular_wkup_requested : 1; uint64_t regular_wkup_present : 1; uint64_t block_reg_wkup_events : 1; uint64_t block_all_wkup_events : 1; uint64_t wkup_override_en : 1; uint64_t spc_wkup_override : 1; uint64_t reg_wkup_override : 1; uint64_t chiplet_enable : 1; uint64_t reserved_12_141 : 3; uint64_t reset_state_indicator : 1; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t reset_state_indicator : 1; uint64_t reserved_12_141 : 3; uint64_t chiplet_enable : 1; uint64_t reg_wkup_override : 1; uint64_t spc_wkup_override : 1; uint64_t wkup_override_en : 1; uint64_t block_all_wkup_events : 1; uint64_t block_reg_wkup_events : 1; uint64_t regular_wkup_present : 1; uint64_t regular_wkup_requested : 1; uint64_t special_wkup_requested : 1; uint64_t regular_wkup_active : 1; uint64_t special_wkup_active : 1; uint64_t special_wkup_done : 1; #endif // _BIG_ENDIAN } fields; } ppm_gpmmr_or_t; typedef union ppm_spwkup_otr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t otr_special_wkup : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t otr_special_wkup : 1; #endif // _BIG_ENDIAN } fields; } ppm_spwkup_otr_t; typedef union ppm_spwkup_fsp { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fsp_special_wkup : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t fsp_special_wkup : 1; #endif // _BIG_ENDIAN } fields; } ppm_spwkup_fsp_t; typedef union ppm_spwkup_occ { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t occ_special_wkup : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t occ_special_wkup : 1; #endif // _BIG_ENDIAN } fields; } ppm_spwkup_occ_t; typedef union ppm_spwkup_hyp { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t hyp_special_wkup : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t hyp_special_wkup : 1; #endif // _BIG_ENDIAN } fields; } ppm_spwkup_hyp_t; typedef union ppm_sshsrc { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t stop_gated : 1; uint64_t stop_transition : 2; uint64_t special_wkup_done : 1; uint64_t req_stop_level : 4; uint64_t act_stop_level : 4; uint64_t reserved1 : 52; #else uint64_t reserved1 : 52; uint64_t act_stop_level : 4; uint64_t req_stop_level : 4; uint64_t special_wkup_done : 1; uint64_t stop_transition : 2; uint64_t stop_gated : 1; #endif // _BIG_ENDIAN } fields; } ppm_sshsrc_t; typedef union ppm_sshfsp { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t stop_gated_fsp : 1; uint64_t special_wkup_active_fsp : 1; uint64_t stop_transition__fsp : 2; uint64_t req_stop_level_fsp : 4; uint64_t act_stop_level_fsp : 4; uint64_t deepest_req_stop_level_fsp : 4; uint64_t deepest_act_stop_level_fsp : 4; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t deepest_act_stop_level_fsp : 4; uint64_t deepest_req_stop_level_fsp : 4; uint64_t act_stop_level_fsp : 4; uint64_t req_stop_level_fsp : 4; uint64_t stop_transition__fsp : 2; uint64_t special_wkup_active_fsp : 1; uint64_t stop_gated_fsp : 1; #endif // _BIG_ENDIAN } fields; } ppm_sshfsp_t; typedef union ppm_sshocc { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t run_stop_occ : 1; uint64_t special_wkup_active_occ : 1; uint64_t stop_transition_occ : 2; uint64_t req_stop_level_occ : 4; uint64_t act_stop_level_occ : 4; uint64_t deepest_req_stop_level_occ : 4; uint64_t deepest_act_stop_level_occ : 4; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t deepest_act_stop_level_occ : 4; uint64_t deepest_req_stop_level_occ : 4; uint64_t act_stop_level_occ : 4; uint64_t req_stop_level_occ : 4; uint64_t stop_transition_occ : 2; uint64_t special_wkup_active_occ : 1; uint64_t run_stop_occ : 1; #endif // _BIG_ENDIAN } fields; } ppm_sshocc_t; typedef union ppm_sshotr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t run_stop_otr : 1; uint64_t special_wkup_active_otr : 1; uint64_t stop_transition_otr : 2; uint64_t req_stop_level_otr : 4; uint64_t act_stop_level_otr : 4; uint64_t deepest_req_stop_level_otr : 4; uint64_t deepest_act_stop_level_otr : 4; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t deepest_act_stop_level_otr : 4; uint64_t deepest_req_stop_level_otr : 4; uint64_t act_stop_level_otr : 4; uint64_t req_stop_level_otr : 4; uint64_t stop_transition_otr : 2; uint64_t special_wkup_active_otr : 1; uint64_t run_stop_otr : 1; #endif // _BIG_ENDIAN } fields; } ppm_sshotr_t; typedef union ppm_sshhyp { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t run_stop_hyp : 1; uint64_t special_wkup_active_hyp : 1; uint64_t stop_transition_hyp : 2; uint64_t req_stop_level_hyp : 4; uint64_t act_stop_level_hyp : 4; uint64_t deepest_req_stop_level_hyp : 4; uint64_t deepest_act_stop_level_hyp : 4; uint64_t reserved1 : 44; #else uint64_t reserved1 : 44; uint64_t deepest_act_stop_level_hyp : 4; uint64_t deepest_req_stop_level_hyp : 4; uint64_t act_stop_level_hyp : 4; uint64_t req_stop_level_hyp : 4; uint64_t stop_transition_hyp : 2; uint64_t special_wkup_active_hyp : 1; uint64_t run_stop_hyp : 1; #endif // _BIG_ENDIAN } fields; } ppm_sshhyp_t; typedef union ppm_pfcs { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdd_pfet_force_state : 2; uint64_t vcs_pfet_force_state : 2; uint64_t vdd_pfet_val_override : 1; uint64_t vdd_pfet_sel_override : 1; uint64_t vcs_pfet_val_override : 1; uint64_t vcs_pfet_sel_override : 1; uint64_t vdd_pfet_regulation_finger_en : 1; uint64_t vdd_pfet_regulation_finger_value : 1; uint64_t reserved1 : 2; uint64_t vdd_pfet_enable_value : 8; uint64_t vdd_pfet_sel_value : 4; uint64_t vcs_pfet_enable_value : 8; uint64_t vcs_pfet_sel_value : 4; uint64_t reserved2 : 6; uint64_t vdd_pg_state : 4; uint64_t vdd_pg_sel : 4; uint64_t vcs_pg_state : 4; uint64_t vcs_pg_sel : 4; uint64_t reserved3 : 6; #else uint64_t reserved3 : 6; uint64_t vcs_pg_sel : 4; uint64_t vcs_pg_state : 4; uint64_t vdd_pg_sel : 4; uint64_t vdd_pg_state : 4; uint64_t reserved2 : 6; uint64_t vcs_pfet_sel_value : 4; uint64_t vcs_pfet_enable_value : 8; uint64_t vdd_pfet_sel_value : 4; uint64_t vdd_pfet_enable_value : 8; uint64_t reserved1 : 2; uint64_t vdd_pfet_regulation_finger_value : 1; uint64_t vdd_pfet_regulation_finger_en : 1; uint64_t vcs_pfet_sel_override : 1; uint64_t vcs_pfet_val_override : 1; uint64_t vdd_pfet_sel_override : 1; uint64_t vdd_pfet_val_override : 1; uint64_t vcs_pfet_force_state : 2; uint64_t vdd_pfet_force_state : 2; #endif // _BIG_ENDIAN } fields; } ppm_pfcs_t; typedef union ppm_pfcs_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdd_pfet_force_state : 2; uint64_t vcs_pfet_force_state : 2; uint64_t vdd_pfet_val_override : 1; uint64_t vdd_pfet_sel_override : 1; uint64_t vcs_pfet_val_override : 1; uint64_t vcs_pfet_sel_override : 1; uint64_t vdd_pfet_regulation_finger_en : 1; uint64_t vdd_pfet_regulation_finger_value : 1; uint64_t reserved1 : 2; uint64_t vdd_pfet_enable_value : 8; uint64_t vdd_pfet_sel_value : 4; uint64_t vcs_pfet_enable_value : 8; uint64_t vcs_pfet_sel_value : 4; uint64_t reserved2 : 6; uint64_t vdd_pg_state : 4; uint64_t vdd_pg_sel : 4; uint64_t vcs_pg_state : 4; uint64_t vcs_pg_sel : 4; uint64_t reserved3 : 6; #else uint64_t reserved3 : 6; uint64_t vcs_pg_sel : 4; uint64_t vcs_pg_state : 4; uint64_t vdd_pg_sel : 4; uint64_t vdd_pg_state : 4; uint64_t reserved2 : 6; uint64_t vcs_pfet_sel_value : 4; uint64_t vcs_pfet_enable_value : 8; uint64_t vdd_pfet_sel_value : 4; uint64_t vdd_pfet_enable_value : 8; uint64_t reserved1 : 2; uint64_t vdd_pfet_regulation_finger_value : 1; uint64_t vdd_pfet_regulation_finger_en : 1; uint64_t vcs_pfet_sel_override : 1; uint64_t vcs_pfet_val_override : 1; uint64_t vdd_pfet_sel_override : 1; uint64_t vdd_pfet_val_override : 1; uint64_t vcs_pfet_force_state : 2; uint64_t vdd_pfet_force_state : 2; #endif // _BIG_ENDIAN } fields; } ppm_pfcs_clr_t; typedef union ppm_pfcs_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdd_pfet_force_state : 2; uint64_t vcs_pfet_force_state : 2; uint64_t vdd_pfet_val_override : 1; uint64_t vdd_pfet_sel_override : 1; uint64_t vcs_pfet_val_override : 1; uint64_t vcs_pfet_sel_override : 1; uint64_t vdd_pfet_regulation_finger_en : 1; uint64_t vdd_pfet_regulation_finger_value : 1; uint64_t reserved1 : 2; uint64_t vdd_pfet_enable_value : 8; uint64_t vdd_pfet_sel_value : 4; uint64_t vcs_pfet_enable_value : 8; uint64_t vcs_pfet_sel_value : 4; uint64_t reserved2 : 6; uint64_t vdd_pg_state : 4; uint64_t vdd_pg_sel : 4; uint64_t vcs_pg_state : 4; uint64_t vcs_pg_sel : 4; uint64_t reserved3 : 6; #else uint64_t reserved3 : 6; uint64_t vcs_pg_sel : 4; uint64_t vcs_pg_state : 4; uint64_t vdd_pg_sel : 4; uint64_t vdd_pg_state : 4; uint64_t reserved2 : 6; uint64_t vcs_pfet_sel_value : 4; uint64_t vcs_pfet_enable_value : 8; uint64_t vdd_pfet_sel_value : 4; uint64_t vdd_pfet_enable_value : 8; uint64_t reserved1 : 2; uint64_t vdd_pfet_regulation_finger_value : 1; uint64_t vdd_pfet_regulation_finger_en : 1; uint64_t vcs_pfet_sel_override : 1; uint64_t vcs_pfet_val_override : 1; uint64_t vdd_pfet_sel_override : 1; uint64_t vdd_pfet_val_override : 1; uint64_t vcs_pfet_force_state : 2; uint64_t vdd_pfet_force_state : 2; #endif // _BIG_ENDIAN } fields; } ppm_pfcs_or_t; typedef union ppm_pfdly { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t powdn_dly : 4; uint64_t powup_dly : 4; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t powup_dly : 4; uint64_t powdn_dly : 4; #endif // _BIG_ENDIAN } fields; } ppm_pfdly_t; typedef union ppm_pfsns { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdd_pfets_enabled_sense : 1; uint64_t vdd_pfets_disabled_sense : 1; uint64_t vcs_pfets_enabled_sense : 1; uint64_t vcs_pfets_disabled_sense : 1; uint64_t reserved1 : 12; uint64_t tp_vdd_pfet_enable_actual : 8; uint64_t tp_vcs_pfet_enable_actual : 8; uint64_t reserved2 : 32; #else uint64_t reserved2 : 32; uint64_t tp_vcs_pfet_enable_actual : 8; uint64_t tp_vdd_pfet_enable_actual : 8; uint64_t reserved1 : 12; uint64_t vcs_pfets_disabled_sense : 1; uint64_t vcs_pfets_enabled_sense : 1; uint64_t vdd_pfets_disabled_sense : 1; uint64_t vdd_pfets_enabled_sense : 1; #endif // _BIG_ENDIAN } fields; } ppm_pfsns_t; typedef union ppm_pfoff { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdd_voff_sel : 4; uint64_t vcs_voff_sel : 4; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t vcs_voff_sel : 4; uint64_t vdd_voff_sel : 4; #endif // _BIG_ENDIAN } fields; } ppm_pfoff_t; typedef union ppm_scratch0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } ppm_scratch0_t; typedef union ppm_scratch1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 64; #else uint64_t data : 64; #endif // _BIG_ENDIAN } fields; } ppm_scratch1_t; typedef union ppm_cgcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t clkglm_async_reset : 1; uint64_t reserved_1_21 : 2; uint64_t clkglm_sel : 1; uint64_t reserved2 : 60; #else uint64_t reserved2 : 60; uint64_t clkglm_sel : 1; uint64_t reserved_1_21 : 2; uint64_t clkglm_async_reset : 1; #endif // _BIG_ENDIAN } fields; } ppm_cgcr_t; typedef union ppm_cgcr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t clkglm_async_reset : 1; uint64_t reserved_1_21 : 2; uint64_t clkglm_sel : 1; uint64_t reserved2 : 60; #else uint64_t reserved2 : 60; uint64_t clkglm_sel : 1; uint64_t reserved_1_21 : 2; uint64_t clkglm_async_reset : 1; #endif // _BIG_ENDIAN } fields; } ppm_cgcr_clr_t; typedef union ppm_cgcr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t clkglm_async_reset : 1; uint64_t reserved_1_21 : 2; uint64_t clkglm_sel : 1; uint64_t reserved2 : 60; #else uint64_t reserved2 : 60; uint64_t clkglm_sel : 1; uint64_t reserved_1_21 : 2; uint64_t clkglm_async_reset : 1; #endif // _BIG_ENDIAN } fields; } ppm_cgcr_or_t; typedef union ppm_pig { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 1; uint64_t req_intr_type : 3; uint64_t req_intr_payload : 12; uint64_t granted_packet : 16; uint64_t intr_granted : 1; uint64_t reserved2 : 1; uint64_t granted__source : 2; uint64_t reserved3 : 1; uint64_t pending_source : 3; uint64_t reserved4 : 24; #else uint64_t reserved4 : 24; uint64_t pending_source : 3; uint64_t reserved3 : 1; uint64_t granted__source : 2; uint64_t reserved2 : 1; uint64_t intr_granted : 1; uint64_t granted_packet : 16; uint64_t req_intr_payload : 12; uint64_t req_intr_type : 3; uint64_t reserved1 : 1; #endif // _BIG_ENDIAN } fields; } ppm_pig_t; typedef union ppm_ivrmcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_vid_valid : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_vreg_slow_dc : 1; uint64_t reserved1 : 4; uint64_t reserved2 : 56; #else uint64_t reserved2 : 56; uint64_t reserved1 : 4; uint64_t ivrm_vreg_slow_dc : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_vid_valid : 1; #endif // _BIG_ENDIAN } fields; } ppm_ivrmcr_t; typedef union ppm_ivrmcr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_vid_valid : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_vreg_slow_dc : 1; uint64_t reserved1 : 4; uint64_t reserved2 : 56; #else uint64_t reserved2 : 56; uint64_t reserved1 : 4; uint64_t ivrm_vreg_slow_dc : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_vid_valid : 1; #endif // _BIG_ENDIAN } fields; } ppm_ivrmcr_clr_t; typedef union ppm_ivrmcr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_vid_valid : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_vreg_slow_dc : 1; uint64_t reserved1 : 4; uint64_t reserved2 : 56; #else uint64_t reserved2 : 56; uint64_t reserved1 : 4; uint64_t ivrm_vreg_slow_dc : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_vid_valid : 1; #endif // _BIG_ENDIAN } fields; } ppm_ivrmcr_or_t; typedef union ppm_ivrmst { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_vid_done : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t ivrm_vid_done : 1; #endif // _BIG_ENDIAN } fields; } ppm_ivrmst_t; typedef union ppm_ivrmdvr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_ivid : 8; uint64_t reserved_8_10 : 3; uint64_t ivrm_pfet_strength_core : 5; uint64_t reserved_16_18 : 3; uint64_t ivrm_pfet_strength_cache : 5; uint64_t reserved1 : 40; #else uint64_t reserved1 : 40; uint64_t ivrm_pfet_strength_cache : 5; uint64_t reserved_16_18 : 3; uint64_t ivrm_pfet_strength_core : 5; uint64_t reserved_8_10 : 3; uint64_t ivrm_ivid : 8; #endif // _BIG_ENDIAN } fields; } ppm_ivrmdvr_t; typedef union ppm_ivrmavr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_ivid : 8; uint64_t reserved1 : 3; uint64_t ivrm_pfet_strength : 5; uint64_t reserved2 : 3; uint64_t ivrm_enabled_history : 1; uint64_t reserved3 : 4; uint64_t ivrm_vid_valid : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_vreg_slow_dc : 1; uint64_t reserved4 : 36; #else uint64_t reserved4 : 36; uint64_t ivrm_vreg_slow_dc : 1; uint64_t ivrm_poweron : 1; uint64_t ivrm_bypass_b : 1; uint64_t ivrm_vid_valid : 1; uint64_t reserved3 : 4; uint64_t ivrm_enabled_history : 1; uint64_t reserved2 : 3; uint64_t ivrm_pfet_strength : 5; uint64_t reserved1 : 3; uint64_t ivrm_ivid : 8; #endif // _BIG_ENDIAN } fields; } ppm_ivrmavr_t; typedef union ppm_vdmcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_poweron : 1; uint64_t vdm_disable : 1; uint64_t reserved1 : 62; #else uint64_t reserved1 : 62; uint64_t vdm_disable : 1; uint64_t vdm_poweron : 1; #endif // _BIG_ENDIAN } fields; } ppm_vdmcr_t; typedef union ppm_vdmcr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_poweron : 1; uint64_t vdm_disable : 1; uint64_t reserved1 : 62; #else uint64_t reserved1 : 62; uint64_t vdm_disable : 1; uint64_t vdm_poweron : 1; #endif // _BIG_ENDIAN } fields; } ppm_vdmcr_clr_t; typedef union ppm_vdmcr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t vdm_poweron : 1; uint64_t vdm_disable : 1; uint64_t reserved1 : 62; #else uint64_t reserved1 : 62; uint64_t vdm_disable : 1; uint64_t vdm_poweron : 1; #endif // _BIG_ENDIAN } fields; } ppm_vdmcr_or_t; #endif // __ASSEMBLER__ #endif // __PPM_FIRMWARE_REGISTERS_H__ <|start_filename|>src/ppe/pk/ppe/ppe_common.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe/ppe_common.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPE_COMMON_H__ #define __PPE_COMMON_H__ /// \file ppe_common.h /// \brief Common header for PPE /// /// This header is maintained as part of the PK port for PPE, but needs to be /// physically present in the PMX area to allow dropping PMX code as a whole /// to other teams. // -*- WARNING: This file is maintained as part of PK. Do not edit in -*- // -*- the PMX area as your edits will be lost. -*- #ifndef __ASSEMBLER__ #include <stdint.h> #endif /// This constant is used to define the size of the table of interrupt handler /// structures as well as a limit for error checking. /// NOTE: This can be specific to each PPE type (SBE, PPE, GPE) #define EXTERNAL_IRQS 64 #ifdef __ASSEMBLER__ /// This macro contains PPE specific code. /// Since standalone models of the PPE do not support external interrupts /// we just set the code to 64 (phantom interrupt) .macro hwmacro_get_ext_irq li %r4, 64 .endm /// Redirect the .hwmacro_irq_cfg_bitmaps macro to call our ppe specific implementation /// This is called from the ppe42_exceptions.S file. /// NOTE: The standalone version of PPE doesn't support external interrupts so this /// does nothing. .macro .hwmacro_irq_cfg_bitmaps .endm #endif /* __ASSEMBLER__ */ #endif /* __PPE_COMMON_H__ */ <|start_filename|>src/common/global_app_cfg.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/common/global_app_cfg.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #define GLOBAL_CFG_USE_IPC // have lib/occlib/ipc_structs.h use "ipc_func_ids.h" #define OCCHW_IRQ_ROUTE_OWNER 3 /// All GPE's will use the external timebase register #define APPCFG_USE_EXT_TIMEBASE #define DEFAULT_NEST_FREQ_HZ 600000000 #define DEFAULT_EXT_CLK_FREQ_HZ 37500000 // Turn off periodic GPE traces #define PK_TRACE_TIMER_OUTPUT 0 // Increase size of GPE trace buffers #define PK_TRACE_SZ 1024 // Redefine the default MSR to mask off SIB errors and avoid data machine checks // These SIB errors probably occur due to contention on the PIB #define PK_THREAD_MACHINE_CONTEXT_DEFAULT (MSR_SEM | MSR_UIE | MSR_EE | MSR_ME) #define PPE42_MSR_INITIAL (MSR_SEM | MSR_ME | MSR_UIE ) // Enable GPE IPC Timers #define GPE_IPC_TIMERS // If we are using the OCB timebase then assume // a frequency of 37.5Mhz. Otherwise, the default is to use // the decrementer as a timebase and assume a frequency of // 600MHz // In product code, this value will be IPL-time configurable. #ifdef APPCFG_USE_EXT_TIMEBASE #define PPE_TIMEBASE_HZ DEFAULT_EXT_CLK_FREQ_HZ #else #define PPE_TIMEBASE_HZ DEFAULT_NEST_FREQ_HZ #endif /* APPCFG_USE_EXT_TIMEBASE */ <|start_filename|>src/occ_405/pss/dpss.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pss/dpss.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include <dpss.h> #include <trac.h> #include <occ_common.h> #include <comp_ids.h> #include <occ_sys_config.h> #include <trac_interface.h> #include <occ_service_codes.h> #include <pss_service_codes.h> #include <state.h> #include <amec_oversub.h> #include <ppc405_irq.h> // Macro creates a 'bridge' handler that converts the initial fast-mode to full- // mode interrupt handler SSX_IRQ_FAST2FULL(isr_dpss_oversubscription_handler, isr_dpss_oversubscription_handler_full); // Increment a counter each time we see a phantom interrupt (used by health monitor thread) uint32_t G_occ_phantom_critical_count = 0; uint32_t G_occ_phantom_noncritical_count = 0; // Function Specification // // Name: isr_dpss_oversubscription_handler_full // // Description: From the flow diagram: // Will eventually be doing something to set the Pstates & Memory // Throttles when this interrupt occurs, but for now just put in this // comment and no code besides clearing the irq and tracing the fact that // we got an interrupt. // // End Function Specification void isr_dpss_oversubscription_handler_full(void *private, SsxIrqId irq, int priority) { SsxMachineContext ctx; // disable further interrupts at this level ssx_irq_disable(irq); // enter the protected context ssx_critical_section_enter( SSX_CRITICAL, &ctx ); // clear this irq ssx_irq_status_clear(irq); // exit the protected context ssx_critical_section_exit( &ctx ); // call oversub isr amec_oversub_isr(); // re-enable interrupts at this level ssx_irq_enable(irq); } // end isr_dpss_oversubscription_handler_full // Function Specification // // Name: occ_phantom_irq_handler // // Description: // handler for an interrupt that fired and then went away before // we could read what it was. // // End Function Specification void occ_phantom_irq_handler(void* i_arg, SsxIrqId i_irq, int i_critical) { if(i_critical == SSX_CRITICAL) { G_occ_phantom_critical_count++; } else { G_occ_phantom_noncritical_count++; } } // Function Specification // // Name: dpss_oversubscription_irq_initialize // // Description: // Installs the power oversubscription IRQ handler for the DPSS // // End Function Specification errlHndl_t dpss_oversubscription_irq_initialize() { int rc = 0; errlHndl_t l_err = NULL; // NOTE: It is believed that the oversubscription interrupt bounces // on and off as power supplies are re-inserted. If it happens quickly enough // it will clear the interrupt before the code has a chance to see the cause // of the interrupt. The default phantom handler would then be invoked and // cause occ to panic. Instead, we just increment a counter and log an info // error. __ppc405_phantom_irq.handler = occ_phantom_irq_handler; // Disable the IRQ while we work on it ssx_irq_disable(OCCHW_IRQ_EXTERNAL_TRAP); // Setup the IRQ rc = ssx_irq_setup(OCCHW_IRQ_EXTERNAL_TRAP, SSX_IRQ_POLARITY_ACTIVE_HIGH, SSX_IRQ_TRIGGER_LEVEL_SENSITIVE); if( rc ) { TRAC_ERR("%s: Failed IRQ setup.", __FUNCTION__); /*@ * @moduleid PSS_MID_DPSS_OVS_IRQ_INIT * @reasonCode SSX_GENERIC_FAILURE * @severity ERRL_SEV_PREDICTIVE * @userdata1 ssx_irq_setup return code * @userdata4 ERC_SSX_IRQ_SETUP_FAILURE * @devdesc Firmware failure initializing DPSS IRQ */ l_err = createErrl( PSS_MID_DPSS_OVS_IRQ_INIT, // i_modId SSX_GENERIC_FAILURE, // i_reasonCode ERC_SSX_IRQ_SETUP_FAILURE, ERRL_SEV_PREDICTIVE, NULL, // tracDesc_t i_trace 0, // i_traceSz rc, // i_userData1 0); // i_userData2 } else { // Set the IRQ handler rc = ssx_irq_handler_set(OCCHW_IRQ_EXTERNAL_TRAP, isr_dpss_oversubscription_handler, NULL, SSX_NONCRITICAL); if( rc ) { TRAC_ERR("%s: Failed to set the IRQ handler.", __FUNCTION__); /*@ * @moduleid PSS_MID_DPSS_OVS_IRQ_INIT * @reasonCode SSX_GENERIC_FAILURE * @severity ERRL_SEV_PREDICTIVE * @userdata1 ssx_irq_handler_set return code * @userdata4 ERC_SSX_IRQ_HANDLER_SET_FAILURE * @devdesc Firmware failure setting up DPSS routine */ l_err = createErrl( PSS_MID_DPSS_OVS_IRQ_INIT, // i_modId SSX_GENERIC_FAILURE, // i_reasonCode ERC_SSX_IRQ_HANDLER_SET_FAILURE, ERRL_SEV_PREDICTIVE, NULL, // tracDesc_t i_trace 0, // i_traceSz rc, // i_userData1 0); // i_userData2 } else { // Enable the IRQ ssx_irq_status_clear(OCCHW_IRQ_EXTERNAL_TRAP); ssx_irq_enable(OCCHW_IRQ_EXTERNAL_TRAP); } } return l_err; } // end dpss_oversubscription_irq_initialize <|start_filename|>src/ssx/ssx/ssx_timer_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_timer_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_timer_core.c /// \brief SSX portable kernel timer handler /// /// This file contains core routines that would be needed by any application /// that requires SSX timer support at runtime. /// /// SSX implements a 'tickless' kernel - all events are scheduled at absolute /// times of the SSX timebase. This approach gives the application full /// control over granularity of event scheduling. Scheduling in absolute time /// opens up the possibility of scheduling events "in the past". SSX /// uniformly handles this case by scheduling "past" events to occur 1 /// timebase tick in the future, so that timer callbacks are always run in the /// expected noncritical interrupt context. /// /// SSX implements the time queue as a simple unordered list of events, plus a /// dedicated variable that holds the earliest timeout of any event in the /// list. This is thought to be an appropriate data structure for the /// following reasons: /// /// - SSX applications will be small and will not schedule a large number of /// events. Therefore the cost of scanning the list each time an event times /// out is balanced against the cost of maintaining the list as a sorted data /// structure each time an event is added or removed from the event queue. /// /// - SSX applications may schedule and cancel many, many more events (safety /// timeouts) than are ever allowed to expire. Events can be added and deleted /// from the simple DEQUE very quickly since there is no sorting /// overhead. /// /// Events are added to the queue simply by placing them at the end of the /// queue. If the new event times out earlier than the previous earliest /// event, the hardware timeout is rescheduled for the new event time. Events /// are deleted from the queue (cancelled) simply by deleting them. Deletion /// does not affect the hardware timeout, even if the deleted event would have /// been the next to time out. It is not an error for the timer handler to /// take a timer interrupt and find no events pending. Pending events can /// also be rescheduled in place. /// /// When a timeout occurs the event list is scanned from the beginning, and /// any event that has timed out is rescheduled if necessary (periodic events) /// and its callback is processed. Since event and callback processing take /// time, the list is potentially scanned multiple times until there are no /// more timed-out events in the list. /// /// Note that callbacks are not necessarily processed in time-order. In this /// sense the SSX time queue is like a traditional tick-based time queue in /// that events are effectively lumped into groups of events that time out /// together. In a tick-based kernel the 'lump' is the tick interval; here /// the 'lump' is a variable interval that corresponds to the time it takes to /// process the entire event list. /// /// Timer callbacks are typically run with interrupt preemption enabled. /// Special callbacks may run without preemption. This is the only part of /// the SSX kernel where data structures of indeterminate size are processed. /// During processing of the event list by the timer interrupt handler, the /// consideration of each event always includes a window of preemptability. #define __SSX_TIMER_CORE_C__ #include "ssx.h" // This routine is only used in this file, and will always be called in // critical section. static inline int timer_active(SsxTimer* timer) { return ssx_deque_is_queued((SsxDeque*)timer); } // This is the kernel version of ssx_timer_cancel(). // // This routine is used here and by thread and semaphore routines. // Noncritical interrupts must be disabled at entry. // // If the timer is active, then there is a special case if we are going to // delete the 'cursor' - that is the timer that __ssx_timer_handler() is going // to handle next. In this case we need to move the cursor to the next timer // in the queue. // // Note that cancelling a timer does not cause a re-evaluation of the next // timeout. This will happen naturally when the current timeout expires. int __ssx_timer_cancel(SsxTimer* timer) { int rc; SsxDeque* timer_deque = (SsxDeque*)timer; SsxTimeQueue* tq = &__ssx_time_queue; if (!timer_active(timer)) { rc = -SSX_TIMER_NOT_ACTIVE; } else { if (timer_deque == tq->cursor) { tq->cursor = tq->cursor->next; } ssx_deque_delete(timer_deque); rc = 0; } return rc; } // This is the kernel version of ssx_timer_schedule(). // // This routine is used here and by thread and semaphore routines. // Noncritical interrupts must be disabled at entry. // // Unless the timer is already active it is enqueued in the doubly-linked // timer list by inserting the timer at the end of the queue. Then the // hardware timeout is scheduled if necessary. If the time queue 'cursor' != 0 // we are in the midst of processing the time queue, and the end of time queue // processing will schedule the next hardware timemout. void __ssx_timer_schedule(SsxTimer* timer) { SsxTimeQueue* tq = &__ssx_time_queue; if (!timer_active(timer)) { ssx_deque_push_back((SsxDeque*)tq, (SsxDeque*)timer); } if (timer->timeout < tq->next_timeout) { tq->next_timeout = timer->timeout; if (tq->cursor == 0) { __ssx_schedule_hardware_timeout(tq->next_timeout); } } } // The tickless timer mechanism has timed out. Note that due to timer // deletions and other factors, there may not actually be a timer in the queue // that has timed out - but it doesn't matter (other than for efficiency). // // Noncritical interrupts are (must be) disabled at entry, and this invariant // is checked. This routine must not be entered reentrantly. // // First, time out any timers that have expired. Timers in the queue are // unordered, so we have to check every one. Since passing through the // loop takes time, we may have to make multiple passes until we know // that there are no timers in the queue that have already timed // out. Note that it would also work to only go through the loop once and // let the hardware scheduler take care of looping, but that would imply // more overhead than the current implementation. // // On each pass through the loop tq->next_timeout computes the minimum timeout // of events remaining in the queue. This is the only part of the kernel that // searches a list of indefinite length. Kernel interrupt latency is mitigated // by running callbacks with interrupts disabled either during or after the // call for timed out events, and also after every check for events that have // not timed out. // // Because interrupt preemption is enabled during processing, and preempting // handlers may invoke time queue operations, we need to establish a pointer // to the next entry to be examined (tq->cursor) before enabling interupts. // It's possible that this pointer will be changed by other interrupt handlers // that cancel the timer pointed to by tq->cursor. // // The main loop iterates on the SsxDeque form of the time queue, casting each // element back up to the SsxTimer as it is processed. void __ssx_timer_handler() { SsxTimeQueue* tq; SsxTimebase now; SsxTimer* timer; SsxDeque* timer_deque; SsxTimerCallback callback; tq = &__ssx_time_queue; if (SSX_ERROR_CHECK_KERNEL) { if (tq->cursor != 0) { SSX_PANIC(SSX_TIMER_HANDLER_INVARIANT); } } while ((now = ssx_timebase_get()) >= tq->next_timeout) { tq->next_timeout = SSX_TIMEBASE_MAX; timer_deque = ((SsxDeque*)tq)->next; while (timer_deque != (SsxDeque*)tq) { timer = (SsxTimer*)timer_deque; tq->cursor = timer_deque->next; if (timer->timeout <= now) { // The timer timed out. It is removed from the queue unless // it is a peridic timer that needs to be rescheduled. We do // rescheduling here in the critical section to correctly // handle timers whose callbacks may cancel the timer. The // timer is rescheduled in absolute time. // // The callback may be made with interrupt preemption enabled // or disabled. However to mitigate kernel interrupt latency // we go ahead and open up to interrupts after the callback if // the callback itself was not preemptible. if (timer->period == 0) { ssx_deque_delete(timer_deque); } else { timer->timeout += timer->period; tq->next_timeout = MIN(timer->timeout, tq->next_timeout); } callback = timer->callback; if (callback) { if (timer->options & SSX_TIMER_CALLBACK_PREEMPTIBLE) { ssx_interrupt_preemption_enable(); callback(timer->arg); } else { callback(timer->arg); ssx_interrupt_preemption_enable(); } } ssx_interrupt_preemption_disable(); } else { // This timer has not timed out. Its timeout will simply // participate in the computation of the next timeout. For // interrupt latency reasons we always allow a period of // interrupt preemption. tq->next_timeout = MIN(timer->timeout, tq->next_timeout); ssx_interrupt_preemption_enable(); ssx_interrupt_preemption_disable(); } timer_deque = tq->cursor; } } tq->cursor = 0; // Finally, reschedule the next timeout __ssx_schedule_hardware_timeout(tq->next_timeout); } /// Schedule a timer in absolute time. /// /// \param timer The SsxTimer to schedule. /// /// \param timeout The timer will be scheduled to time out at this absolute /// time. Note that if the \a timeout is less than the current time then the /// timer will be scheduled at a minimum timeout in the future and the /// callback will be executed in an interrupt context. /// /// \param period If non-0, then when the timer times out it will rescheduled /// to time out again at the absolute time equal to the last timeout time plus /// the \a period. By convention a \a period of 0 indicates a one-shot /// timer that is not rescheduled. /// /// Once created with ssx_timer_create() a timer can be \e scheduled, which /// queues the timer in the kernel time queue. It is not an error to call /// ssx_timer_schedule() on a timer that is already scheduled in the time /// queue - the timer is simply rescheduled with the new characteristics. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_TIMER_AT_SCHEDULE A a null (0) pointer was provided as /// the \a timer argument. /// /// \retval -SSX_ILLEGAL_CONTEXT_TIMER The call was made from a critical /// interrupt context. int ssx_timer_schedule_absolute(SsxTimer* timer, SsxTimebase timeout, SsxInterval period) { SsxMachineContext ctx; ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(timer == 0, SSX_INVALID_TIMER_AT_SCHEDULE); SSX_ERROR_IF(__ssx_kernel_context_critical_interrupt(), SSX_ILLEGAL_CONTEXT_TIMER); } timer->timeout = timeout; timer->period = period; __ssx_timer_schedule(timer); ssx_critical_section_exit(&ctx); return SSX_OK; } /// Schedule a timer for an interval relative to the current time. /// /// \param timer The SsxTimer to schedule. /// /// \param interval The timer will be scheduled to time out at the current /// time (ssx_timebase_get()) plus this \a interval. /// /// \param period If non-0, then when the timer times out it will rescheduled /// to time out again at the absolute time equal to the last timeout time plus /// the \a period. By convention a \a period of 0 indicates a one-shot /// timer that is not rescheduled. /// /// Once created with ssx_timer_create() a timer can be \e scheduled, which /// queues the timer in the kernel time queue. It is not an error to call \c /// ssx_timer_schedule() on a timer that is already scheduled in the time /// queue - the timer is simply rescheduled with the new characteristics. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_TIMER_AT_SCHEDULE A a null (0) pointer was provided as /// the \a timer argument. /// /// \retval -SSX_ILLEGAL_CONTEXT_TIMER The call was made from a critical /// interrupt context. int ssx_timer_schedule(SsxTimer* timer, SsxInterval interval, SsxInterval period) { return ssx_timer_schedule_absolute(timer, ssx_timebase_get() + interval, period); } /// Cancel (dequeue) a timer. /// /// \param timer The SsxTimer to cancel. /// /// Timers can be canceled at any time. It is never an error to call /// ssx_timer_cancel() on an SsxTimer object after it is created. Memory used /// by an SsxTimer can be safely reused for another purpose after a successful /// call ofssx_timer_cancel(). /// /// Return values other than SSX_OK (0) are not necessarily errors; see \ref /// ssx_errors /// /// The following return codes are non-error codes: /// /// \retval 0 Successful completion /// /// \retval -SSX_TIMER_NOT_ACTIVE The \a timer is not currently scheduled, /// i.e. it was never scheduled or has timed out. This code is returned for /// information only and is not considered an error. /// /// The following return codes are error codes: /// /// \retval -SSX_INVALID_TIMER_AT_CANCEL The \a timer is a null (0) pointer. /// /// \retval -SSX_ILLEGAL_CONTEXT_TIMER The call was made from a critical /// interrupt context. /// int ssx_timer_cancel(SsxTimer* timer) { SsxMachineContext ctx; int rc = SSX_OK; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF_CRITICAL_INTERRUPT_CONTEXT(); SSX_ERROR_IF(timer == 0, SSX_INVALID_TIMER_AT_CANCEL); } ssx_critical_section_enter(SSX_NONCRITICAL, &ctx); rc = __ssx_timer_cancel(timer); ssx_critical_section_exit(&ctx); return rc; } /// Get information about a timer. /// /// \param timer The SsxTimer to query /// /// \param timeout The API returns the absolute timeout of the timer through /// this pointer. If the timer is active, this is the current timeout. If /// the timer has timed out then this is the previous absolute timeout. If /// the timer was never scheduled this will be 0. The caller can set this /// parameter to the null pointer (0) if this information is not required. /// /// \param active If the value returned through this pointer is 1 then the /// timer is active (currently scheduled), otherwise the value will be 0 /// indicating an inactive timer. The caller can set this parameter to the /// null pointer (0) if this information is not required. /// /// The information returned by this API can only be guaranteed consistent if /// the API is called from an SSX_NONCRITICAL critical section. Since the /// implementation of this API does not require a critical section, it is not /// an error to call this API from a critical interrupt context. /// /// Return values other than SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_TIMER_AT_INFO The \a timer is a null (0) pointer. int ssx_timer_info_get(SsxTimer* timer, SsxTimebase* timeout, int* active) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(timer == 0, SSX_INVALID_TIMER_AT_INFO); } if (timeout) { *timeout = timer->timeout; } if (active) { *active = timer_active(timer); } return SSX_OK; } #undef __SSX_TIMER_CORE_C__ <|start_filename|>src/ssx/ssx/ssx_stack_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_stack_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_stack_init.c /// \brief SSX stack initialization /// /// The entry points in this file are initialization routines - they are never /// needed after SSX initialization and their code space could be reclaimed by /// the application after initialization if required. /// /// This code was split out from "ssx_init.c" because it may be needed in a /// thread configuration if threads are being created dynamically. in an /// interrupt-only configuration it is not needed after \c ssx_initialize(). #include "ssx.h" /// Initialize a stack area. /// /// \param stack A pointer to the smallest legal address of the stack. The /// stack address is modified as the stack is aligned and initialized. /// /// \param size A pointer to the size of the stack (in bytes). The size is /// modified as the stack is aligned and initialized. At exit this is the /// final usable stack area size aligned to the size of the SSX_STACK_TYPE. /// /// SSX makes no assumptions about size or alignment of the area provided as a /// stack, and carefully aligns and initializes the stack. Regardless of how /// the stack grows, the \a stack parameter is considered to be the lowest /// legal address of the stack. int __ssx_stack_init(SsxAddress* stack, size_t* size) { SsxAddress mask; size_t excess, i, count; SSX_STACK_TYPE* p; if (SSX_STACK_DIRECTION < 0) { // Stacks grow down. The initial stack pointer is set to just above // the last allocated stack address. This is legal for pre-decrement // stacks, otherwise the initial address is first brought into range // before alignment. The stack is aligned downward, then the size is // adjusted to a multiple of the stack type. Stacks are optionally // prepatterned. Alignment is assumed to be a power of 2. *stack += *size; if (!SSX_STACK_PRE_DECREMENT) { *stack -= sizeof(SSX_STACK_TYPE); *size -= sizeof(SSX_STACK_TYPE); } mask = SSX_STACK_ALIGNMENT - 1; excess = *stack & mask; *stack -= excess; *size -= excess; *size = (*size / sizeof(SSX_STACK_TYPE)) * sizeof(SSX_STACK_TYPE); if (SSX_STACK_CHECK) { p = (SSX_STACK_TYPE*)(*stack); count = *size / sizeof(SSX_STACK_TYPE); for (i = 0; i < count; i++) { if (SSX_STACK_PRE_DECREMENT) { *(--p) = SSX_STACK_PATTERN; } else { *(p--) = SSX_STACK_PATTERN; } } } __ssx_stack_create_initial_frame(stack, size); } else { SSX_PANIC(SSX_UNIMPLEMENTED); } return SSX_OK; } <|start_filename|>src/occ_405/pss/test/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occ_405/pss/test/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2011,2015 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG apsstest_CFILES = \ ../../common.c \ ../../errl/errl.c \ ../../thread/threadSch.c \ ../apss.c \ apsstest.c all_cfiles = ${apsstest_CFILES} occ_GPEFILES = ../../gpe/apss_init.S \ ../../gpe/apss_composite.S \ ../../gpe/apss_meas_read_start.S \ ../../gpe/apss_meas_read_cont.S \ ../../gpe/apss_meas_read_complete.S \ ../../gpe/pore_test.S all_gpefiles = ${occ_GPEFILES} APP = apsstest APP_INCLUDES += -I../../../ssx APP_INCLUDES += -I../../../lib APP_INCLUDES += -I../../incl APP_INCLUDES += -I../../trac APP_INCLUDES += -I../../async APP_INCLUDES += -I../../errl APP_INCLUDES += -I../../gpe APP_INCLUDES += -I../../thread #APP_INCLUDES += -I../../aplt #APP_INCLUDES += -I../../rtls #APP_INCLUDES += -I../../sensor APP_INCLUDES += -I../../pss APP_INCLUDES += -I. D = -DSIMICS_MAGIC_PANIC=1 #D = -DVERIFICATION=1 \ -DSSX_STACK_CHECK=0 \ -DINITIALIZE_PMC=0 \ -DINITIALIZE_SIMICS_IO=0 \ -DINITIALIZE_RTX_IO=1 \ -DINITIALIZE_PBA=1 \ -DSIMICS_MAGIC_PANIC=1 \ -DSSX_KERNEL_TRACE_ENABLE=1 SOURCES = ${all_cfiles} ${all_gpefiles} MODE = validation PGP_ASYNC_SUPPORT = 1 include ./app.mk pgas: $(CC) $(CFLAGS) -c -Wa,-al -Wa,--listing-cont-lines='10' ${all_gpefiles} <|start_filename|>src/ssx/occhw/occhw_ocb.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_ocb.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_ocb.c /// \brief OCB-related drivers for OCCHW #include "ssx.h" //use compile-time default in case the OCB timer is never used -- grm unsigned int g_ocb_timer_divider = OCB_TIMER_DIVIDER_DEFAULT; /// Reset an OCB timer /// /// \param timer A valid OCB timer index /// /// \param auto_reload A non-0 value indicates to run the timer in auto-reload /// mode. /// /// \param timeout_ns The timeout specified in nanoseconds. The actual timeout /// will be rounded down to the underlying timer tick, with a minimum 1 tick /// timeout. However if the \a timeout_ns argument is explicity 0, then the /// timer wil be initialized with a 0 timeout, effectively disabling the /// timer. /// /// Reseting an OCB timer means rewriting the timer control register with a /// potentially new auto-reload enable and new timeout value. This API also /// clears any pending timer interrupt status. /// /// \retval 0 Success /// /// \retval -OCB_INVALID_ARGUMENT_TIMER Causes include illegal timer /// numbers and illegal or unrepresntable timeouts. // Note that OCB_TIMER_FREQUENCY_HZ is in the range of 1-2 MHz. int ocb_timer_reset(int timer, int auto_reload, int timeout_ns) { ocb_otrn_t otr; int ticks; //printk("ocb_timer_reset(%d, %d, %d)\n", // timer, auto_reload, timeout_ns); if (timeout_ns != 0) { ticks = MAX(1, timeout_ns / (1000000000 / OCB_TIMER_FREQUENCY_HZ)); } else { ticks = 0; } if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((timer < 0) || (timer >= OCB_TIMERS) || (timeout_ns < 0) || (ticks != ((uint16_t)ticks)), OCB_INVALID_ARGUMENT_TIMER); } otr.value = 0; otr.fields.timeout = 1; otr.fields.control = 1; otr.fields.auto_reload = (auto_reload != 0); otr.fields.timer = ticks; out32(OCB_OTRN(timer), otr.value); return 0; } /// Set up an OCB timer and interrupt handler /// /// \param timer A valid OCB timer index /// /// \param auto_reload A non-0 value indicates to run the timer in auto-reload /// mode. /// /// \param timeout_ns The timeout specified in nanoseconds. The actual timeout /// will rounded down to the underlying timer tick, with a minimum 1 tick /// timeout. However if the \a timeout_ns argument is explicity 0, then the /// timer wil be initialized with a 0 timeout, effectively disabling the /// timer. /// /// \param handler The interrupt handler for the timer interrupt /// /// \param arg The private argument of the interrupt handler /// /// \param priority The SSX/PPC405 interrupt priority to assign to the /// interrupt. /// /// This API sets up and starts the timer and unmasks the timer /// interrupt. Once set up, the timer can be reset using ocb_timer_reset(). As /// a fine point of the specification, if a timer interrupt is already pending /// when this API is invoked then that interrupt will be cleared. Only the /// next interrupt (corresponding to the new programming) will be serviced by /// the newly installed handler. /// /// Note that the interrupt handler is responsible for clearing the timer /// interrupt status. An API ocb_timer_status_clear() is available for this. /// /// \retval 0 Success /// /// \retval -OCB_INVALID_ARGUMENT_TIMER Causes include illegal timer /// numbers and illegal or unrepresntable timeouts. /// /// Other errors may be returned by the underlying calls to SSX routines that /// set up interrupts. int ocb_timer_setup(int timer, int auto_reload, int timeout_ns, SsxIrqHandler handler, void* arg, int priority) { int rc; //printk("ocb_timer_setup(%d, %d, %d, %p, %p, %d)\n", // timer, auto_reload, timeout_ns, // handler, arg, priority); ssx_irq_disable(OCCHW_IRQ_OCC_TIMER0 + timer); ssx_irq_setup(OCCHW_IRQ_OCC_TIMER0 + timer, SSX_IRQ_POLARITY_ACTIVE_HIGH, SSX_IRQ_TRIGGER_LEVEL_SENSITIVE); ssx_irq_handler_set(OCCHW_IRQ_OCC_TIMER0 + timer, handler, arg, priority); rc = ocb_timer_reset(timer, auto_reload, timeout_ns); ssx_irq_enable(OCCHW_IRQ_OCC_TIMER0 + timer); return rc; } /// Generate an core interrupt via the PSI Host Bridge /// /// Setting OCB_OCCMISC.core_ext_int to 1 causes a wire to pulse to the PSI /// Host Bridge to allow the presentation of an external interrupt to a core /// thread. The core thread to be interrupted is controlled by the XIVR - OCC /// register, SCOM 02010916. Normally the hypervisor will set up the PSI Host /// Bridge. This procedure allows OCC to send an interrupt to the hypervisor. /// /// \retval 0 Success // The interrupt is generated by causing a 0->1 transation on // OCB_OCCMISC.core_ext_intr. This is implemented here using the WAND/WOR // forms of the register. int ocb_core_interrupt() { ocb_occmisc_t oo; oo.value = 0; oo.fields.core_ext_intr = 1; out32(OCB_OCCMISC_CLR, oo.value); out32(OCB_OCCMISC_OR, oo.value); return 0; } /// Procedure to setup a linear window on an indirect channel /// /// /// Since the linear window access is restricted to the SRAM region of /// OCI space, Bits 0:4 of the base parameter are don't care and will be /// overwritten with b'11000' /// /// /// \todo double check SRAM region restriction /// /// \param channel The indirect channel to use, in the range 0..2. /// /// \param base The 32-bit PowerBus base address where the block starts. This /// address must be aligned to the \a log_size. /// /// \param log_size The base 2 logarithm of the block size, in bytes. The /// minimum size is 8B (2**3), the maximum size is 32KB (2**15) /// /// /// \retval 0 Success /// /// \retval OCB_INVALID_ARGUMENT_LW_INIT One or more of the parameter /// restrictions were violated. /// /// \retval OCB_SCOM_ERROR An attempt to write a PBA SCOM register to set up /// the BARs produced a non-zero return code. int ocb_linear_window_initialize(int channel, uint32_t base, int log_size) { uint32_t mask ; ocb_ocblwcrn_t ocblwcrn; ocb_ocblwsbrn_t ocblwsbrn; // create mask for checking mask = (0x1ull << log_size) - 1; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((channel < 0) || (channel > 3) || (log_size < OCB_LW_LOG_SIZE_MIN) || (log_size > OCB_LW_LOG_SIZE_MAX) || ((base & mask) != 0), OCB_INVALID_ARGUMENT_LW_INIT); } // now invert mask for use in ocb linear window setup mask = ~mask; // Enable LW mode ocblwcrn.fields.linear_window_enable = 1; // Select bits(12:28) of OCI addr for the LW bar ocblwcrn.fields.linear_window_bar = (base >> 3) & 0x1FFFF; ocblwcrn.fields.linear_window_mask = (mask >> 3) & 0xFFF; out32(OCB_OCBLWCRN(channel), ocblwcrn.value); // Configure LW region for SRAM access ocblwsbrn.fields.linear_window_region = 7; // Select bits(5:11) of OCI addr for the LW base ocblwsbrn.fields.linear_window_base = (base >> 20) & 0x7F; out32(OCB_OCBLWSBRN(channel), ocblwsbrn.value); return 0 ; } /// Procedure to disable a linear window on an indirect channel /// /// This procedure will disable the linear window while maintaining /// the linear_window_bar and linear_window_mask settings /// /// \param channel The indirect channel to disable, in the range 0..2. /// /// \retval 0 Success /// /// \retval OCB_INVALID_ARGUMENT_LW_DISABLE One or more of the parameter /// restrictions were violated. /// int ocb_linear_window_disable(int channel) { ocb_ocblwcrn_t ocblwcrn; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((channel < 0) || (channel > 3), OCB_INVALID_ARGUMENT_LW_DISABLE); } ocblwcrn.value = in32(OCB_OCBLWCRN(channel)); // Disable LW mode ocblwcrn.fields.linear_window_enable = 0; out32(OCB_OCBLWCRN(channel), ocblwcrn.value); return 0 ; } /// Procedure for setting up untrusted mode for an indirect channel /// /// Note that the OCC FW is expected to enable the channel for FSP /// access. As an untrusted master, the FSP cannot configure this /// in a chip running in trusted mode. The SBE is considered a trusted /// master. /// /// /// \param channel The indirect channel to use, in the range 0..2 /// Note that this bit is not used for indirect channel 3. /// /// /// \param allow_untrusted Enable untrusted PIB masters /// access to the indirect channel being configured. If allow_untrusted is /// not enabled and the chip is running in trusted mode, then any untrusted /// PIB master will get an offline return code when attempting to write /// the indirect channel. 0 = Disable, 1 = Enable /// /// \retval 0 Success /// /// \retval OCB_INVALID_ARGUMENT_UNTRUST One or more of the parameter /// restrictions were violated. /// //NOTE: The OCBICR register seems to have gone away in P9 and we didn't ever // call this function in P8 so I'm removing this function for now. (grm) #if 0 int ocb_allow_untrusted_initialize(int channel, int allow_untrusted) { ocb_ocbicrn_t ocbicrn; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((channel < 0) || (channel > 2) || (allow_untrusted < 0) || (allow_untrusted > 1), OCB_INVALID_ARGUMENT_UNTRUST); } // Configure allow_unsecure_pib_masters bit ocbicrn.fields.allow_unsecure_pib_masters = allow_untrusted; out32(OCB_OCBICRN(channel), ocbicrn.value); return 0 ; } #endif <|start_filename|>src/occ_405/cmdh/cmdh_thread.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_thread.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "ssx_io.h" #include "simics_stdio.h" #include "errl.h" #include "trac.h" #include <thread.h> #include <threadSch.h> #include "state.h" #include <cmdh_fsp.h> extern uint8_t G_occ_interrupt_type; eCmdhWakeupThreadMask G_cmdh_thread_wakeup_mask; // Function Specification // // Name: Cmd_Hndl_thread_routine // // Description: This needs to be moved to separate file after we add cmd handler // thread support // // End Function Specification void Cmd_Hndl_thread_routine(void *arg) { #define OCC_RESP_READY_ALERT_TIMEOUT_ATTEMPTS 5 int l_rc = 0; errlHndl_t l_errlHndl = NULL; CHECKPOINT(CMDH_THREAD_STARTED); CMDH_TRAC_INFO("Command Handler Thread Started ... " ); // ------------------------------------------------ // Initialize HW for FSP Comm // ------------------------------------------------ cmdh_comm_init(); CHECKPOINT(COMM_INIT_COMPLETED); // Read/trace push queue register const uint32_t l_data = in32(OCB_OCBSHCS1); CMDH_TRAC_INFO("Cmd_Hndl_thread_routine: OCB_OCBSHCS1=0x%08X", l_data); // write data after checkpoint and update checkpoint length G_fsp_msg.rsp->fields.data[3] = (l_data >> 24); G_fsp_msg.rsp->fields.data[4] = (l_data >> 16) & 0xFF; G_fsp_msg.rsp->fields.data[5] = (l_data >> 8) & 0xFF; G_fsp_msg.rsp->fields.data[6] = (l_data ) & 0xFF; G_fsp_msg.rsp->fields.data[7] = 0x11; G_fsp_msg.rsp->fields.data_length[1] = 8; // 8 bytes vs 3 dcache_flush_line((void *)CMDH_OCC_RESPONSE_BASE_ADDRESS); // ------------------------------------------------ // Loop forever, handling FSP commands // ------------------------------------------------ while(1) { // ------------------------------------------------ // Block, Waiting on sem for a doorbell from FSP // ------------------------------------------------ l_rc = cmdh_thread_wait_for_wakeup(); // Blocking Call // ------------------------------------------------ // Handle the command // ------------------------------------------------ if(SSX_OK == l_rc) { // Handle the command that TMGT just sent to OCC if( CMDH_WAKEUP_FSP_COMMAND & G_cmdh_thread_wakeup_mask ) { clearCmdhWakeupCondition(CMDH_WAKEUP_FSP_COMMAND); l_errlHndl = cmdh_fsp_cmd_hndler(); // Commit an error if we get one passed back, do it before // we tell the FSP we have a response ready if(NULL != l_errlHndl) { commitErrl(&l_errlHndl); } } } } } <|start_filename|>src/ssx/occhw/occhw_async_pba.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_async_pba.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_async_pba.c /// \brief Async device drivers for the PBA block copy engines and PBAX #include "ssx.h" #include "occhw_async.h" //////////////////////////////////////////////////////////////////////////// // Global Data //////////////////////////////////////////////////////////////////////////// BceQueue G_pba_bcue_queue; BceQueue G_pba_bcde_queue; PbaxQueue G_pbax_read_queue[PBAX_QUEUES]; //////////////////////////////////////////////////////////////////////////// // Local Data //////////////////////////////////////////////////////////////////////////// /// Combined FFDC for all PBA subunits static PbaUnitFfdc G_pba_ffdc = {{{{{0}}}}}; PBAX_CQ_READ_BUFFER(G_pbax_read0_buffer, PBAX_READ0_LENGTH); PBAX_CQ_READ_BUFFER(G_pbax_read1_buffer, PBAX_READ1_LENGTH); // The generic driver code stores an engine-specfic engine ID in the // queue. Here arrays are set up that contain the OCI control register // addresses for an engine indexed by the queue-specific value. // /// \todo Once the designers actually define register addresses, see about /// modifying these tables to be macros instead. /// /// \todo Actually, why don't we just store this data directly in the queue? /// PBA BCDE/BCUE PowerBus BAR[0..31] static const SsxAddress G_bce_pbadr[BCE_ENGINES] = {PBA_BCDE_PBADR, PBA_BCUE_PBADR}; /// PBA BCDE/BCUE OCI BAR static const SsxAddress G_bce_ocibar[BCE_ENGINES] = {PBA_BCDE_OCIBAR, PBA_BCUE_OCIBAR}; /// PBA BCDE/BCUE SET register static const SsxAddress G_bce_set[BCE_ENGINES] = {PBA_BCDE_SET, PBA_BCUE_SET}; /// PBA BCDE/BCUE Control register static const SsxAddress G_bce_ctl[BCE_ENGINES] = {PBA_BCDE_CTL, PBA_BCUE_CTL}; /// PBA BCDE/BCUE Status register static const SsxAddress G_bce_stat[BCE_ENGINES] = {PBA_BCDE_STAT, PBA_BCUE_STAT}; /// PBAX Push Queue Control/Status Register addresses static const SsxAddress G_pba_xshcsn[PBAX_ENGINES] = {PBA_XSHCS0, PBA_XSHCS1}; /// PBAX Push Queue Base Register addresses static const SsxAddress G_pba_xshbrn[PBAX_ENGINES] = {PBA_XSHBR0, PBA_XSHBR1}; /// PBAX Push Queue Increment Register addresses static const SsxAddress G_pba_xshincn[PBAX_ENGINES] = {PBA_XSHINC0, PBA_XSHINC1}; //////////////////////////////////////////////////////////////////////////// // PBA FFDC Structures //////////////////////////////////////////////////////////////////////////// // NB: Collection of FFDC for PBA will be very time consuming due to the large // amount of information required to fully diagnose any problem. This will be // done in a critical interrupt so it may have some impact on micro-timescale // realtime operations. // Collect PBA common FFDC // // Most of this is just collection of all of the setup registers required to // diagnose problems with the bridge and block copy engines. Not all of this // data is required for PBAX errors but we collect it anyway. // // FFDC is only collected for the first error, until the error flag is reset. static void pba_common_ffdc(PbaCommonFfdc* ffdc) { int i; if (ffdc->error == 0) { oci_ffdc(&(ffdc->oci_ffdc), OCI_MASTER_ID_PBA); ffdc->mode.value = in64(PBA_MODE); for (i = 0; i < PBA_READ_BUFFERS; i++) { getscom(PBA_RBUFVALN(i), &(ffdc->rbufval[i].value)); } for (i = 0; i < PBA_WRITE_BUFFERS; i++) { getscom(PBA_WBUFVALN(i), &(ffdc->wbufval[i].value)); } for (i = 0; i < PBA_BARS; i++) { getscom(PBA_BARN(i), &(ffdc->bar[i].value)); getscom(PBA_BARMSKN(i), &(ffdc->barmsk[i].value)); } getscom(PBA_FIR, &(ffdc->fir.value)); getscom(PBA_ERRRPT0, &(ffdc->errrpt0.value)); getscom(PBA_ERRRPT1, &(ffdc->errrpt1.value)); getscom(PBA_ERRRPT2, &(ffdc->errrpt2.value)); ffdc->error = 1; } } // Collect FFDC for generic PBA bridge errors // // This extends the common collection with PBA slave control/status // information. static void pba_bridge_ffdc(PbaBridgeFfdc* ffdc) { int i; if (ffdc->common.error == 0) { //TODO: Cannot get this information through scoms //pba_common_ffdc(&(ffdc->common)); ffdc->slvrst.value = in64(PBA_SLVRST); for (i = 0; i > PBA_SLAVES; i++) { ffdc->slvctl[i].value = in64(PBA_SLVCTLN(i)); } } } // Collect FFDC for a particular Block Copy Engine // // The engine ID here is either 0 (BCDE) or 1 (BCUE) static void bce_ffdc(BceFfdc* ffdc, int engine) { if (ffdc->common.error == 0) { //TODO: Cannot get this information through scoms //pba_common_ffdc(&(ffdc->common)); ffdc->ctl.value = in64(G_bce_ctl[engine]); ffdc->set.value = in64(G_bce_set[engine]); ffdc->pbadr.value = in64(G_bce_pbadr[engine]); ffdc->stat.value = in64(G_bce_stat[engine]); } } // Collect FFDC for PBAX send static void pbax_send_ffdc(PbaxSendFfdc* ffdc) { if (ffdc->common.error == 0) { //TODO: Cannot get this information through scoms //pba_common_ffdc(&(ffdc->common)); ffdc->xcfg.value = in64(PBA_XCFG); ffdc->xsndtx.value = in64(PBA_XSNDTX); ffdc->xsndstat.value = in64(PBA_XSNDSTAT); } } // Collect FFDC for PBAX receive // // The drivers currently do not distinguish errors between the two receive // queues as the hardware design does not provide a clean separation. static void pbax_receive_ffdc(PbaxReceiveFfdc* ffdc) { int i; if (ffdc->common.error == 0) { //TODO: Cannot get this information through scoms //pba_common_ffdc(&(ffdc->common)); ffdc->xcfg.value = in64(PBA_XCFG); ffdc->xrcvstat.value = in64(PBA_XRCVSTAT); for (i = 0; i < PBAX_ENGINES; i++) { ffdc->xshbrn[i].value = in64(PBA_XSHBRN(i)); ffdc->xshcsn[i].value = in64(PBA_XSHCSN(i)); } } } //////////////////////////////////////////////////////////////////////////// // BceRequest //////////////////////////////////////////////////////////////////////////// // Start a request running on a PBA Block Copy Engine // // \param queue A BceQueue upcast to an AsyncQueue // // \param request A BceRequest upcast to an AsyncRequest // // This routine takes a Bce objects cast to Async objects so that it can be // called from the generic Async interrupt handler. // // This is an internal API. This routine must be called from a context where // critical interrupts are disabled. Prior to this call, scheduling code will // have installed the new request as the \a current request of the queue, and // marked both the queue and the request as running. // // The PBA driver handles requests that require multiple runs of the PBA to // complete the request. Starting a PBA job requires setting up 3 registers, // hitting the "go" bit, and computing the amount of work remaining. // // Note that PBA will signal an error and lock up the system if the START bit // is written while a BC-engine is running. // Recall that the engines have identical control structures with identical // relative offsets between registers. So we use BCDE offsets and BCDE // register layout structures, but they work for BCUE as well. static int bce_async_run_method(AsyncRequest* async_request) { BceQueue* queue = (BceQueue*)(async_request->queue); BceRequest* request = (BceRequest*)async_request; int rc, engine; pba_bcde_pbadr_t pbadr; pba_bcde_set_t set; pba_bcde_ctl_t ctl; size_t to_write; if (request->remaining == 0) { rc = -ASYNC_REQUEST_COMPLETE; } else { to_write = MIN(request->remaining, PBA_BCE_SIZE_MAX); // Create the address offset register. The PowerBus offset is the // cache-line address of the stored offset (ex the OCI region bits). pbadr.value = 0; pbadr.fields.pb_offset = (request->next_bridge_address & 0x3FFFFFFF) / POWERBUS_CACHE_LINE_SIZE; pbadr.fields.extaddr = request->extended_address.fields.extended_address; // Create the setup register set.value = 0; set.fields.copy_length = to_write / POWERBUS_CACHE_LINE_SIZE; // Set the START bit ctl.value = PBA_BCDE_CTL_START; // Start the BCE engine = queue->engine; out64(G_bce_pbadr[engine], pbadr.value); out32(G_bce_ocibar[engine], request->next_oci_address); out32(G_bce_set[engine], set.words.high_order); out32(G_bce_ctl[engine], ctl.words.high_order); // Update the work remaining to be done. request->remaining -= to_write; if (request->remaining != 0) { request->next_bridge_address += to_write; request->next_oci_address += to_write; } rc = 0; } return rc; } // The async error method for Block Copy Engines // // Collect FFDC and stop the engine. The return of -1 will disable the // channel associated with the request. The application will need to decide // whether to restart the queue. static int bce_async_error_method(AsyncRequest* request) { BceQueue* queue = (BceQueue*)(request->queue); int engine = queue->engine; if (engine == BCE_ENGINE_BCDE) { bce_ffdc(&(G_pba_ffdc.bcde), engine); out32(PBA_BCDE_CTL, PBA_BCDE_CTL_STOP >> 32); } else { bce_ffdc(&(G_pba_ffdc.bcue), engine); out32(PBA_BCUE_CTL, PBA_BCUE_CTL_STOP >> 32); } return -1; } /// Create a request for a PBA Block Copy engine /// /// \param request An uninitialized or otherwise idle BceRequest. /// /// \param queue An initialized BceQueue. /// /// \param bridge_address The 32-bit bridge address that is translated to /// a PowerBus address associated with the copy. This address must be a /// PowerBus cache (128-byte) aligned address. /// /// \param oci_address The 32-bit OCI address associated with the copy. This /// address must be 128-byte aligned. /// /// \param bytes The number of bytes to move. This must be a multiple of 128, /// and the size must not obviously overflow the OCI address or the bridge /// address. /// /// \param timeout If not specified as SSX_WAIT_FOREVER, then this request /// will be governed by a private watchdog timer that will cancel a queued job /// or kill a running job if the hardware operation does not complete before /// it times out. /// /// \param callback The callback to execute when the PBA copy completes, or /// NULL (0) to indicate no callback. /// /// \param arg The parameter to the callback routine; ignored if the \a /// callback is NULL. /// /// \param options Options to control request priority and callback context. /// /// Note that the setup for the BC engines includes an extended address and a /// PowerBus maximum priority. This API sets these to /// the default values in the request. If non-default values are required, /// they will need to be installed in the structure explicitly before /// scheduling. /// /// This routine has no way to know if the BceRequest structure is currently /// in use, so this API should only be called on uninitialized or otherwise /// idle GpeRequest structures. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_BCE_REQUEST The \a request was NULL (0), /// or the \a queue was NULL (0) or not a BceQueue. /// /// See async_request_create() for other errors that may be returned by this /// call. int bce_request_create(BceRequest* request, BceQueue* queue, uint32_t bridge_address, uint32_t oci_address, size_t bytes, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options) { int rc; AsyncQueue* async_queue = (AsyncQueue*)queue; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request == 0) || (queue == 0) || !(async_queue->engine & ASYNC_ENGINE_BCE), ASYNC_INVALID_OBJECT_BCE_REQUEST); } rc = async_request_create(&(request->request), async_queue, bce_async_run_method, bce_async_error_method, timeout, callback, arg, options); request->bridge_address = bridge_address; request->oci_address = oci_address; request->bytes = bytes; request->extended_address.value = 0; return rc; } //////////////////////////////////////////////////////////////////////////// // BceQueue //////////////////////////////////////////////////////////////////////////// /// Create (initialize) a BceQueue /// /// \param queue An uninitialized of otherwise idle BceQueue /// /// \param engine Either ASYNC_ENGINE_PBA_BCDE or ASYNC_ENGINE_PBA_BCUE /// /// This API initializes the BceQueue structure based on the engine /// provided. There is really no special hardware initialization required as /// the BC-engines are pretty simple data movers. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_BCE_QUEUE The \a queue was NULL (0). /// /// \retval -ASYNC_INVALID_ENGINE_BCE The \a engine is not a PBA engine. int bce_queue_create(BceQueue* queue, int engine) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(queue == 0, ASYNC_INVALID_OBJECT_BCE_QUEUE); } switch (engine) { case ASYNC_ENGINE_BCDE: async_queue_create(&(queue->queue), engine); queue->engine = BCE_ENGINE_BCDE; break; case ASYNC_ENGINE_BCUE: async_queue_create(&(queue->queue), engine); queue->engine = BCE_ENGINE_BCUE; break; default: if (SSX_ERROR_CHECK_API) { SSX_ERROR(ASYNC_INVALID_ENGINE_BCE); } break; } return 0; } /// Schedule a request on a PBA block-copy engine /// /// Note : As long as the BceRequest is idle, the application is free to /// directly change the \a bridge_address, \a oci_address and \a bytes fields to /// read/write different numbers of bytes to/from different locations the next /// time the request is scheduled. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_ARGUMENT_BCE_SCHEDULE Either the \a bridge_address /// is not 128-byte aligned, or the OCI address is not 128-byte aligned, or the /// number of bytes is not a multiple of 128. /// /// See async_request_schedule() for documentation of other errors int bce_request_schedule(BceRequest* request) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request->bridge_address % POWERBUS_CACHE_LINE_SIZE) || (request->oci_address % POWERBUS_CACHE_LINE_SIZE) || (request->bytes % POWERBUS_CACHE_LINE_SIZE), ASYNC_INVALID_ARGUMENT_BCE_SCHEDULE); } request->next_bridge_address = request->bridge_address; request->next_oci_address = request->oci_address; request->remaining = request->bytes; return async_request_schedule((AsyncRequest*)request); } // The interrupt handler for asynchronous PBA Block Copy requests // // BC-engine 'done' interrupts are level-sensitive active high, so they need // to be cleared in the PBA by writing a 0 to the CTL register. We also get // the PBA 'done' even when jobs are killed, but the cancel/kill code is // responsible for setting the \a completion_state of the request. // // We only go to the generic handler once all data has been transferred. SSX_IRQ_FAST2FULL(bce_async_handler, bce_async_handler_full); void bce_async_handler_full(void* arg, SsxIrqId irq, int priority) { AsyncQueue* async_queue = (AsyncQueue*)arg; AsyncRequest* async_current = (AsyncRequest*)async_queue->current; BceQueue* queue = (BceQueue*)async_queue; out32(G_bce_ctl[queue->engine], 0); if (SSX_ERROR_CHECK_KERNEL && (async_current == 0)) { SSX_PANIC(ASYNC_PHANTOM_INTERRUPT_BCE); } if (async_current->run_method(async_current) == -ASYNC_REQUEST_COMPLETE) { async_handler(async_queue); } } //////////////////////////////////////////////////////////////////////////// // PbaxRequest //////////////////////////////////////////////////////////////////////////// /// Non-blocking read from a PBAX PUSH (read) queue /// /// \param queue The target PbaxQueue /// /// \param buf The caller's data buffer to receive the read data /// /// \param bytes The maximum number of bytes to read. This value should be an /// even multiple of 8, as this API always reads multiples of 8 bytes. /// /// \param read The number of bytes actually copied from the device buffer to /// the caller's buffer. This may be returned as any value from 0 to \a /// bytes in multiples of 8 bytes. /// /// pbax_read() implements a non-blocking copy of data from a PBAX read (PUSH) /// queue data area to the caller's data area, with the side effect of /// advancing the hardware queue pointers. pbax_read() does not implement /// locking, critical sections or any other type of synchronization for access /// to the PBAX queue data. /// /// pbax_read() returns the error code -ASYNC_PBAX_ERROR_OLD or /// -ASYNC_PBAX_ERROR_NEW if PBAX receive error status is asserted. /// The error return code may be disjoint from the actual /// read: If data is available it may be copied to the caller's buffer, but /// this data should always be considered corrupted in the event of an error /// return code. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_ARGUMENT_PBAX_READ The number of \a bytes is not /// an even multiple of 8. /// /// \retval -ASYNC_PBAX_ERROR_OLD The PBA shows pre-existing error status /// /// \retval -ASYNC_PBAX_ERROR_NEW The PBA shows current error status /// /// \todo Once the HW design is finalized, we might consider modifying the /// error behavior to only return an error status if the receive error was /// associated with this particular queue. int pbax_read(PbaxQueue* queue, void* buf, size_t bytes, size_t* read) { pba_xshcsn_t csr; pba_xrcvstat_t rsr; unsigned qlen, read_ptr, write_ptr, to_read; uint64_t* pcq, *pbuf; int rc; do { rc = 0; *read = 0; // If pre-existing errors exist then immediately abort the read. rsr.words.high_order = in32(PBA_XRCVSTAT); if (rsr.fields.rcv_error) { pbax_receive_ffdc(&(G_pba_ffdc.pbax_receive)); rc = -ASYNC_PBAX_ERROR_OLD; break; } if (bytes % 8) { rc = -ASYNC_INVALID_ARGUMENT_PBAX_READ; break; } // Determine the number of doubleword entries remaining to be read in // the queue. The driver does not keep state, but instead reinterprets // the control/status register each time the read method is called. // This may be confusing - remember that 'push' is from the PowerBus // perspective - here we use 'read' from OCC's perspective. csr.words.high_order = in32(G_pba_xshcsn[queue->engine]); qlen = csr.fields.push_length + 1; read_ptr = csr.fields.push_read_ptr; if (csr.fields.push_empty) { break; } else if (csr.fields.push_full) { to_read = qlen; } else { write_ptr = csr.fields.push_write_ptr; if (read_ptr > write_ptr) { to_read = qlen - (read_ptr - write_ptr); } else { to_read = write_ptr - read_ptr; } } // Copy the data from the CQ memory area. For simplicty of dealing with // cache management each doubleword invokes a line invalidate before // refetching the fresh data from memory. Alignment requirements enforced // on the data buffer guarantee the buffers are cache-line aligned and // each doubleword is fully contained in a single D-cache line. // // Here the code models the evolution of the read_ptr as each datum is // copied from the queue. pbuf = (uint64_t*) buf; while (bytes && to_read--) { read_ptr++; if (read_ptr == qlen) { read_ptr = 0; } pcq = queue->cq_base + read_ptr; dcache_invalidate_line(pcq); *pbuf++ = *pcq; out32(G_pba_xshincn[queue->engine], 0); bytes -= 8; *read += 8; } } while(0); // Check for errors that occurred during the read rsr.words.high_order = in32(PBA_XRCVSTAT); if (rsr.fields.rcv_error) { pbax_receive_ffdc(&(G_pba_ffdc.pbax_receive)); rc = -ASYNC_PBAX_ERROR_NEW; } return rc; } // This is the internal 'run method' for reading through a PBAX circular // queue. The run method simply enables the IRQ. The interrupt handler reads // data from the queue and leaves the interrupt enabled until the read is // satisfied. int pbax_read_method(AsyncRequest* async_request) { PbaxRequest* request = (PbaxRequest*)async_request; PbaxQueue* queue = (PbaxQueue*)(async_request->queue); int rc; if (request->bytes == 0) { rc = -ASYNC_REQUEST_COMPLETE; } else { ssx_irq_enable(queue->irq); rc = 0; } return rc; } // The async error method for PBAX // // Collect FFDC. static int pbax_async_error_method(AsyncRequest* request) { pbax_receive_ffdc(&(G_pba_ffdc.pbax_receive)); return -1; } /// Create a request for a PBAX read queue /// /// \param request An uninitialized or otherwise idle PbaxRequest. /// /// \param queue An async queue for a PBAX read buffer. /// /// \param data A pointer to the data to where the data should be placed. /// /// \param bytes The (maximum) number of bytes of data to move. The PBAX read /// queues always move multiples of 8 bytes, and the number of bytes must be a /// multiple of 8. Higher-level abstractions will have to take care of cases /// where the "actual" numbers of bytes are not multiples of 8. /// /// \param timeout If not specified as SSX_WAIT_FOREVER, then this request /// will be governed by a private watchdog timer that will cancel a queued job /// or kill a running job if the hardware operation does not complete before /// it times out. /// /// \param callback The callback to execute when the read completes, or /// NULL (0) to indicate no callback. /// /// \param arg The parameter to the callback routine; ignored if the \a /// callback is NULL. /// /// \param options Options to control request priority, callback context and /// blocking. See the documentation for the PbaxRequest object for information /// on the special ASYNC_NONBLOCKING_READ option. /// /// This routine has no way to know if the PbaxRequest structure is currently /// in use, so this API should only be called on uninitialized or otherwise /// idle PbaxRequest structures. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_PBAX_REQUEST The \a request or \a queue /// were NULL (0), or the \a queue is not an initialized PbaxQueue. /// /// \retval -ASYNC_INVALID_ARGUMENT_PBAX_REQUEST The \a data pointer is /// NULL (0), or the number of bytes is not a multiple of 8. /// /// See async_request_create() for other errors that may be returned by this /// call. int pbax_request_create(PbaxRequest* request, PbaxQueue* queue, uint64_t* data, size_t bytes, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options) { int rc; AsyncQueue* async_queue = (AsyncQueue*)queue; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request == 0) || (queue == 0) || !(async_queue->engine & ASYNC_ENGINE_PBAX), ASYNC_INVALID_OBJECT_PBAX_REQUEST); SSX_ERROR_IF((data == 0) || (bytes % 8), ASYNC_INVALID_ARGUMENT_PBAX_REQUEST); } rc = async_request_create(&(request->request), async_queue, pbax_read_method, pbax_async_error_method, timeout, callback, arg, options); request->data = data; request->bytes = bytes; return rc; } /// Schedule a request on a PBAX read queue /// /// Note : As long as the PbaxRequest is idle, the application is free to /// directly change the \a data and \a bytes fields to read different numbers of /// bytes into different locations the next time the request is scheduled. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_ARGUMENT_PBAX_SCHEDULE The number of \a bytes /// currently requested is not a multiple of 8. /// /// See async_request_schedule() for documentation of other errors int pbax_request_schedule(PbaxRequest* request) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request->bytes % 8), ASYNC_INVALID_ARGUMENT_PBAX_SCHEDULE); } request->current = request->data; request->remaining = request->bytes; return async_request_schedule((AsyncRequest*)request); } //////////////////////////////////////////////////////////////////////////// // PbaxQueue //////////////////////////////////////////////////////////////////////////// /// Disable a PBAX circular PUSH (read) queue /// /// \param queue An initialized PbaxQueue object. /// /// Disable the PBAX recieve mechanism for a particular PBAX receive queue. /// Interrupts are disabled, and any data managed by the queue is effectively /// lost. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_PBAX_DISABLE The \a queue is NULL (0) /// or otherwise invalid. int pbax_queue_disable(PbaxQueue* queue) { pba_xshcsn_t cs; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(queue == 0, ASYNC_INVALID_OBJECT_PBAX_DISABLE); } ssx_irq_disable(queue->irq); cs.value = 0; out32(G_pba_xshcsn[queue->engine], cs.value); return 0; } /// Enable a PBAX circular PUSH (read) queue /// /// \param queue An initialized PbaxQueue object. /// /// This API reprograms the queue hardware in accordance with the values /// present in the \a queue structure, and enables the queue to accept data. /// Any previous record of data present in the queue will be lost. The queue /// interrupt is also disabled by this API. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_PBAX_DISABLE The \a queue is NULL (0) /// or otherwise invalid. int pbax_queue_enable(PbaxQueue* queue) { int rc; pba_xshcsn_t cs; rc = pbax_queue_disable(queue); if (!rc) { // Reinitialize the data buffer base address register and // reprogram/re-enable the queue. out32(G_pba_xshbrn[queue->engine], (uint32_t)(queue->cq_base)); cs.value = 0; if (queue->protocol == PBAX_INTERRUPT_PROTOCOL_LAZY) { cs.fields.push_intr_action = PBAX_INTR_ACTION_FULL; } else { cs.fields.push_intr_action = PBAX_INTR_ACTION_NOT_EMPTY; } cs.fields.push_length = queue->cq_entries - 1; cs.fields.push_enable = 1; out32(G_pba_xshcsn[queue->engine], cs.words.high_order); } return 0; } /// Create (initialize) a PbaxQueue abstraction /// /// \param queue An uninitialized or otherwise idle PbaxQueue /// /// \param engine A valid PBAX engine id /// /// \param cq_base The base address of the circular queue data area for the /// queue. This address must be aligned to the next higher power-of-two of the /// buffer size, with a minimum alignment of a cache line. /// /// \param cq_entries The number of 8-byte entries in the queue /// /// \param protocol The interrupt protocol, either PBAX_PUSH_PROTOCOL_LAZY or /// PBAX_PUSH_PROTOCOL_AGGRESSIVE. Lazy means that read queues only interrupt /// when full, and agressive means that read queues interrupt whenever they /// are not empty. In general the lazy read protocol will only work for 1) /// queues of length 1, where lazy == aggressive, and 2) protocols where a /// known fixed number of 8-byte entries is always expected to be received. /// /// This API simply creates the PbaxQueue abstraction in the software space; /// The API does not modify any harwdare state. To enable/disable the PBAX /// hardware read queue use pbax_queue_enable(). /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_PBAX_QUEUE The \a queue was NULL (0). /// /// \retval -ASYNC_INVALID_ARGUMENT_PBAX_QUEUE The \a cq_base is not properly /// aligned, or the \a cq_length is invalid, or the \a protocol is invalid. /// /// \retval -ASYNC_INVALID_ENGINE_PBAX The \a engine is not an PBAX engine. /// /// Other errors may be returned by async_queue_create(). int pbax_queue_create(PbaxQueue* queue, int engine, uint64_t* cq_base, size_t cq_entries, int protocol) { AsyncQueue* async_queue = (AsyncQueue*)queue; if (SSX_ERROR_CHECK_API) { uint32_t align_mask = POW2_32(MAX(CEILING_LOG2(cq_entries * 8), LOG_CACHE_LINE_SIZE)) - 1; SSX_ERROR_IF(queue == 0, ASYNC_INVALID_OBJECT_PBAX_QUEUE); SSX_ERROR_IF((((uint32_t)(cq_base) & align_mask) != 0) || (cq_entries < PBAX_PUSH_LENGTH_MIN) || (cq_entries > PBAX_PUSH_LENGTH_MAX) || ((protocol != PBAX_INTERRUPT_PROTOCOL_LAZY) && (protocol != PBAX_INTERRUPT_PROTOCOL_AGGRESSIVE)), ASYNC_INVALID_ARGUMENT_PBAX_QUEUE); } queue->cq_base = cq_base; queue->cq_entries = cq_entries; queue->protocol = protocol; switch (engine) { case ASYNC_ENGINE_PBAX_PUSH0: queue->irq = OCCHW_IRQ_PBAX_OCC_PUSH0; queue->engine = PBAX_ENGINE_PUSH0; break; case ASYNC_ENGINE_PBAX_PUSH1: queue->irq = OCCHW_IRQ_PBAX_OCC_PUSH1; queue->engine = PBAX_ENGINE_PUSH1; break; default: if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(1, ASYNC_INVALID_ENGINE_PBAX); } } async_queue_create(async_queue, engine); return 0; } // The interrupt handler for asynchronous PBAX requests // // The circular buffer interupts are level sensitive, active high. There is // really no way to 'clear' them as they indicate a permanent status - so // instead they need to be enabled and disabled. This is done by the read // method. (Note that one could make them edge-triggered, but in general // device drivers [including this one] would not work correctly if they were // programmed that way.) // // This interrupt handler can process up to 256 bytes at once, plus the // overhead of scheduling the next job when this one completes. If interrupt // latency becomes a problem then this process could be run with interrupt // preemption enabled. SSX_IRQ_FAST2FULL(pbax_async_handler, pbax_async_handler_full); void pbax_async_handler_full(void* arg, SsxIrqId irq, int priority) { AsyncQueue* async_queue = (AsyncQueue*)arg; PbaxQueue* queue = (PbaxQueue*)async_queue; PbaxRequest* request = (PbaxRequest*)(async_queue->current); size_t read; int rc; if (SSX_ERROR_CHECK_KERNEL && (request == 0)) { SSX_PANIC(ASYNC_PHANTOM_INTERRUPT_PBAX); } rc = pbax_read(queue, request->current, request->remaining, &read); if (rc) { ssx_irq_disable(queue->irq); async_error_handler(async_queue, ASYNC_REQUEST_STATE_FAILED); } else if (read == request->remaining) { ssx_irq_disable(queue->irq); async_handler(async_queue); } else { request->current += (read / 8); request->remaining -= read; } } // The interrupt handler for the PBA error interrupt. // // There is one error interrupt that covers all PBA function - the generic // bridge, block copy engines and PBAX buffers. The PBA error pulses whenever // new error bits are logged in the PBA FIR, so it is possible for OCC to log // errors independently for the bridge, BCE and PBAX. // // When the PBA error interrupt fires we try to determine which unit is // responsible for the error and take appropriate action. The analysis is // currently not very deep, however it is not clear whether it is worth the // time and code space required to do more than this. // // - If the error appears to be associated with either a BCDE or BCUE job // running as part of the async mechanism then we let the // async_error_handler() mechanism operate. As a side effect the indicated // queue will be disabled. Note that further analysis (and storage space) // might allow jobs to be restarted on that engine, but this is currently not // done. // // - If the error appears to be associated with a PBAX send then the PBAX send // mechanism is already effectively disabled by the fact that the send status // register shows an error. FFDC is simply collected in this case. // // - If the error appears to be associated with a PBAX receive mechanism then // both receive queues are stopped. The receive may or may not be using the // job queues (the application may be polling using pbax_read()). // // If the error is due to the direct bridge we collect FFDC, but can't really // do anything else. Since OCC will not use the PBA bridge at run time // (except for lab-mode applications) this error is due either to a PORE // engine or FSP using the dedicated trusted channel to mainstore. // // This code is assumed to be activated as a critical interrupt. /// \todo What to do for generic PBA errors? SSX_IRQ_FAST2FULL(pba_error_handler, pba_error_handler_full); void pba_error_handler_full(void* arg, SsxIrqId irq, int priority) { pba_fir_t fir = {0}; pba_bcde_stat_t bcde_stat; pba_bcue_stat_t bcue_stat; pba_xsndstat_t xsndstat; pba_xrcvstat_t xrcvstat; int channel; AsyncQueue* queue; ssx_irq_status_clear(irq); //getscom(PBA_FIR, &(fir.value)); bcde_stat.words.high_order = in32(PBA_BCDE_STAT); bcue_stat.words.high_order = in32(PBA_BCUE_STAT); xsndstat.words.high_order = in32(PBA_XSNDSTAT); xrcvstat.words.high_order = in32(PBA_XRCVSTAT); queue = (AsyncQueue*)(&G_pba_bcde_queue); if (bcde_stat.fields.error && (queue->state == ASYNC_QUEUE_STATE_RUNNING)) { async_error_handler(queue, ASYNC_REQUEST_STATE_FAILED); } queue = (AsyncQueue*)(&G_pba_bcue_queue); if (bcue_stat.fields.error && (queue->state == ASYNC_QUEUE_STATE_RUNNING)) { async_error_handler(queue, ASYNC_REQUEST_STATE_FAILED); } if (xsndstat.fields.snd_error) { pbax_send_ffdc(&G_pba_ffdc.pbax_send); } if (xrcvstat.fields.rcv_error) { for (channel = 0; channel < PBAX_CHANNELS; channel++) { queue = (AsyncQueue*)(&G_pbax_read_queue[channel]); if (queue->state == ASYNC_REQUEST_STATE_RUNNING) { async_error_handler(queue, ASYNC_REQUEST_STATE_FAILED); } else { pbax_receive_ffdc(&G_pba_ffdc.pbax_receive); } } } // Any FIR bits not already attributable to previously handled errors are // assumed to be due to the generic bridge. // TODO: These should be bitwise OR'd not logic OR'd? if (fir.value & ( PBA_FIR_OCI_APAR_ERR || PBA_FIR_PB_RDADRERR_FW || PBA_FIR_PB_RDDATATO_FW || PBA_FIR_PB_SUE_FW || PBA_FIR_PB_UE_FW || PBA_FIR_PB_CE_FW || PBA_FIR_OCI_SLAVE_INIT || PBA_FIR_OCI_WRPAR_ERR || PBA_FIR_OCI_REREQTO || PBA_FIR_PB_UNEXPCRESP || PBA_FIR_PB_UNEXPDATA || PBA_FIR_PB_PARITY_ERR || PBA_FIR_PB_WRADRERR_FW || PBA_FIR_PB_BADCRESP || PBA_FIR_PB_ACKDEAD_FW || PBA_FIR_PB_CRESPTO || // PBA_FIR_BCUE_SETUP_ERR || // PBA_FIR_BCUE_PB_ACK_DEAD || // PBA_FIR_BCUE_PB_ADRERR || // PBA_FIR_BCUE_OCI_DATAERR || // PBA_FIR_BCDE_SETUP_ERR || // PBA_FIR_BCDE_PB_ACK_DEAD || // PBA_FIR_BCDE_PB_ADRERR || // PBA_FIR_BCDE_RDDATATO_ERR || // PBA_FIR_BCDE_SUE_ERR || // PBA_FIR_BCDE_UE_ERR || // PBA_FIR_BCDE_CE || // PBA_FIR_BCDE_OCI_DATAERR || PBA_FIR_INTERNAL_ERR || PBA_FIR_ILLEGAL_CACHE_OP || PBA_FIR_OCI_BAD_REG_ADDR || // PBA_FIR_AXPUSH_WRERR || // PBA_FIR_AXRCV_DLO_ERR || // PBA_FIR_AXRCV_DLO_TO || // PBA_FIR_AXRCV_RSVDATA_TO || // PBA_FIR_AXFLOW_ERR || // PBA_FIR_AXSND_DHI_RTYTO || // PBA_FIR_AXSND_DLO_RTYTO || // PBA_FIR_AXSND_RSVTO || // PBA_FIR_AXSND_RSVERR || PBA_FIR_FIR_PARITY_ERR || PBA_FIR_FIR_PARITY_ERR2 ) ) { pba_bridge_ffdc(&(G_pba_ffdc.bridge)); } } //////////////////////////////////////////////////////////////////////////// // Initialization //////////////////////////////////////////////////////////////////////////// void async_bce_initialize(BceQueue* queue, int engine, SsxIrqId irq) { bce_queue_create(queue, engine); async_level_handler_setup(bce_async_handler, (void*)queue, irq, SSX_CRITICAL, SSX_IRQ_POLARITY_ACTIVE_HIGH); ssx_irq_enable(irq); } void async_pbax_initialize(PbaxQueue* queue, int engine, SsxIrqId irq, uint64_t* buffer, size_t length, int protocol) { pbax_queue_create(queue, engine, buffer, length, protocol); pbax_queue_enable(queue); async_level_handler_setup(pbax_async_handler, (void*)queue, irq, SSX_NONCRITICAL, SSX_IRQ_POLARITY_ACTIVE_HIGH); // Driver or application manages IRQ enable/disable } <|start_filename|>src/include/proc_shared.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/proc_shared.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _PROC_SHARED_H #define _PROC_SHARED_H #include "core_data.h" #include "nest_dts.h" #include "gpe_export.h" // Paramaters for gpe_get_core_data() typedef struct ipc_core_data_parms { GpeErrorStruct error; CoreData* data; uint32_t core_num; } ipc_core_data_parms_t; typedef struct ipc_nest_dts_parms { GpeErrorStruct error; NestDts_t data; } ipc_nest_dts_parms_t; #endif // _PROC_SHARED_H <|start_filename|>src/occ_405/cmdh/ffdc.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/ffdc.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ffdc.h" // Function Specification ////////////////////////////////////////////////////// // // Name: ffdc_thread_dumper // // Description: Dump the state of the thread provided // // End Function Specification ////////////////////////////////////////////////// void ffdc_thread_dumper(SsxThread *i_thread, void *o_ffdc_buffer) { // Format of data dumped into FFDC buffer. The buffer space allocated must // match the size of the dump. The dumped structure must agree with the // structure of the FFDC defined in ll_ffdc.S. // // Offset Length Contents // 0x00 1 Length of thread dump // 0x01 1 Priority // 0x02 1 State // 0x03 1 Flags // 0x04 4 Thread timer // 0x08 4 Semaphore // 0x0c 4 SRR0 // 0x10 4 SRR1 // 0x14 4 SRR2 // 0x18 4 SRR3 // 0x1c 4 LR // 0x20 32 Thread stack unwind // // Total length = 64 bytes uint8_t *l_byte_ptr = (uint8_t *)o_ffdc_buffer; // Store length, priority, state and flags to buffer l_byte_ptr[0] = 64; l_byte_ptr[1] = (uint8_t)(i_thread->priority); l_byte_ptr[2] = (uint8_t)(i_thread->state); l_byte_ptr[3] = (uint8_t)(i_thread->flags); // Store Timer, Semaphore uint32_t *l_word_ptr = (uint32_t *)(l_byte_ptr + 4); l_word_ptr[0] = (uint32_t)&(i_thread->timer); l_word_ptr[1] = (uint32_t)(i_thread->semaphore); // Store SRR0-3 and LR from saved context SsxThreadContext *l_threadCtx = (SsxThreadContext *)(i_thread->saved_stack_pointer); l_word_ptr[2] = (uint32_t)(l_threadCtx->srr0); l_word_ptr[3] = (uint32_t)(l_threadCtx->srr1); l_word_ptr[4] = (uint32_t)(l_threadCtx->srr2); l_word_ptr[5] = (uint32_t)(l_threadCtx->srr3); l_word_ptr[6] = (uint32_t)(l_threadCtx->lr); // Store up to 8 LRs from stack chain, set stack frame pointer to caller's // frame. uint32_t *l_sptr = (uint32_t *)(((uint32_t*)l_threadCtx->r1)[0]); // Reset the ffdc pointer l_word_ptr = &l_word_ptr[7]; ffdc_stack_unwind(l_sptr, l_word_ptr, 8); } // End of ffdc_thread_dumper // Function Specification ////////////////////////////////////////////////////// // // Name: ffdc_stack_unwind // // Description: Unwind the link registers from the provided stack pointer. // // End Function Specification ////////////////////////////////////////////////// void ffdc_stack_unwind(uint32_t *i_sptr, uint32_t *o_buffer, uint32_t i_frameCount) { // Format of the data dumped to the output buffer. // The caller must provide at least one 32 bit word per frame requested by // frame count parameter. // // Offset Length Contents // 0x00 4 Link register for frame n // 0x04 4 Link register for frame n+1 // ... do as many as frames as requested uint32_t *l_sptr = i_sptr; int i = 0; // Loop through the frames storing the LR words for (i = 0; i < i_frameCount; i++) { // Stop storing if we get to the last frame if (l_sptr == NULL) { // Zero out the remaining words in the buffer and break for (; i < i_frameCount; i++) { o_buffer[i] = 0x00000000; } break; } else { o_buffer[i] = (uint32_t)(l_sptr[1]); l_sptr = (uint32_t *)l_sptr[0]; } } } // End of ffdc_stack_unwind <|start_filename|>src/ssx/ppc405/ppc405_msr.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_msr.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_MSR_H__ #define __PPC405_MSR_H__ /// \file ppc405_msr.h /// \brief Everything related to the PPC405 Machine State Register /// /// All of the macros defined here that \e modify the MSR create a compiler /// memory barrier that will cause GCC to flush/invalidate all memory data /// held in registers before the macro. This is consistent with other systems, /// e.g., the PowerPC Linux kernel, and is the safest way to define these /// macros as it guarantess for example that kernel data structure updates /// have completed before exiting a critical section. #define MSR_AP 0x02000000 /* APU Available */ #define MSR_APE 0x00080000 /* APU Exception Enable */ #define MSR_WE 0x00040000 /* Wait State Enable */ #define MSR_CE 0x00020000 /* Critical Interrupt Enable */ #define MSR_EE 0x00008000 /* External Interrupt Enable */ #define MSR_PR 0x00004000 /* Problem State */ #define MSR_ME 0x00001000 /* Machine Check Exception Enable */ #define MSR_FE0 0x00000800 /* Floating-Point Exception Mode 0 */ #define MSR_DWE 0x00000400 /* Debug Wait Enable */ #define MSR_DE 0x00000200 /* Debug Interrupt Enable */ #define MSR_IR 0x00000020 /* Instruction Relocation */ #define MSR_DR 0x00000010 /* Data Relocation */ #define MSR_CE_BIT 14 #define MSR_EE_BIT 16 #define MSR_IR_BIT 26 #define MSR_DR_BIT 27 #ifndef __ASSEMBLER__ /// Move From MSR #define mfmsr() \ ({uint32_t __msr; \ asm volatile ("mfmsr %0" : "=r" (__msr)); \ __msr;}) /// Move to MSR #define mtmsr(value) \ asm volatile ("mtmsr %0; isync" : : "r" (value) : "memory") /// Read-Modify-Write the MSR with OR (Set MSR bits). This operation is only /// guaranteed atomic in a critical section. #define or_msr(x) \ mtmsr(mfmsr() | (x)) /// Read-Modify-Write the MSR with AND complement (Clear MSR bits). This /// operation is only guaranteed atomic in a critical section. #define andc_msr(x) \ mtmsr(mfmsr() & ~(x)) /// Write MSR[EE] with an immediate value (0/1) /// /// Note that the immediate value \a i must be a compile-time constant. #define wrteei(i) \ asm volatile ("wrteei %0; isync" : : "i" (i) : "memory") /// Write MSR[EE] from the EE bit of another MSR #define wrtee(other_msr) \ asm volatile ("wrtee %0; isync" : : "r" (other_msr) : "memory") #endif /* __ASSEMBLER__ */ #endif /* __PPC405_MSR_H__ */ <|start_filename|>src/lib/common/string.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/common/string.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __STRING_H__ #define __STRING_H__ /// \file string.h /// \brief Replacement for <string.h> /// /// The SSX library does not implement the entire <string.h> function. /// However the real reason for this header was the finding that under certain /// optimization modes, we were geting errors from the default <string.h> /// supplied with the MPC environment. So we created this replacement that /// only calls out what is implemented, exactly as it is implemented for SSX. #ifndef __ASSEMBLER__ #include <stddef.h> #if !defined(__size_t) #include <stdint.h> typedef size_t uint32_t; #endif // APIs inmplemented by string.c size_t strlen(const char *s); int strcmp(const char* s1, const char* s2); int strncmp(const char* s1, const char* s2, size_t n); int strcasecmp(const char* s1, const char* s2); int strncasecmp(const char* s1, const char* s2, size_t n); char * strcpy(char *dest, const char *src); char * strncpy(char *dest, const char *src, size_t n); void * memcpy(void *dest, const void *src, size_t n); void * memset(void *s, int c, size_t n); int memcmp(const void* s1, const void* s2, size_t n); // APIs implemented by strdup.c char * strdup(const char* s); #endif /* __ASSEMBLER__ */ #endif /* __STRING_H__ */ <|start_filename|>src/include/registers/cppm_register_addresses.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/cppm_register_addresses.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CPPM_REGISTER_ADDRESSES_H__ #define __CPPM_REGISTER_ADDRESSES_H__ /// \file cppm_register_addresses.h /// \brief Symbolic addresses for the CPPM unit // *** WARNING *** - This file is generated automatically, do not edit. #define CPPM_PIB_BASE 0x000F0000 #define CPPM_CPMMR 0x000f0106 #define CPPM_CPMMR_CLR 0x000f0107 #define CPPM_CPMMR_OR 0x000f0108 #define CPPM_PERRSUM 0x000f0120 #define CPPM_ERR 0x000f0121 #define CPPM_ERRMSK 0x000f0122 #define CPPM_NC0INDIR 0x000f0130 #define CPPM_NC0INDIR_CLR 0x000f0131 #define CPPM_NC0INDIR_OR 0x000f0132 #define CPPM_NC1INDIR 0x000f0133 #define CPPM_NC1INDIR_CLR 0x000f0134 #define CPPM_NC1INDIR_OR 0x000f0135 #define CPPM_CSAR 0x000f0138 #define CPPM_CSAR_CLR 0x000f0139 #define CPPM_CSAR_OR 0x000f013a #define CPPM_CACCR 0x000f0168 #define CPPM_CACCR_CLR 0x000f0169 #define CPPM_CACCR_OR 0x000f016a #define CPPM_CACSR 0x000f016b #define CPPM_CMEDB0 0x000f0190 #define CPPM_CMEDB0_CLR 0x000f0191 #define CPPM_CMEDB0_OR 0x000f0192 #define CPPM_CMEDB1 0x000f0194 #define CPPM_CMEDB1_CLR 0x000f0195 #define CPPM_CMEDB1_OR 0x000f0196 #define CPPM_CMEDB2 0x000f0198 #define CPPM_CMEDB2_CLR 0x000f0199 #define CPPM_CMEDB2_OR 0x000f019a #define CPPM_CMEDB3 0x000f019c #define CPPM_CMEDB3_CLR 0x000f019d #define CPPM_CMEDB3_OR 0x000f019e #define CPPM_CMEDATA 0x000f01a8 #define CPPM_CMEDATA_CLR 0x000f01a9 #define CPPM_CMEDATA_OR 0x000f01aa #define CPPM_CMEMSG 0x000f01ab #define CPPM_CISR 0x000f01ae #define CPPM_PECES 0x000f01af #define CPPM_CIVRMLCR 0x000f01b7 #define CPPM_IPPMCMD 0x000f01c0 #define CPPM_IPPMSTAT 0x000f01c1 #define CPPM_IPPMWDATA 0x000f01c2 #define CPPM_IPPMRDATA 0x000f01c3 #endif // __CPPM_REGISTER_ADDRESSES_H__ <|start_filename|>src/occ_gpe0/firdata/ecc.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/firdata/ecc.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <native.h> #include <ecc.h> /** Matrix used for ECC calculation. * * Each row of this is the set of data word bits that are used for * the calculation of the corresponding ECC bit. The parity of the * bitset is the value of the ECC bit. * * ie. ECC[n] = eccMatrix[n] & data * * Note: To make the math easier (and less shifts in resulting code), * row0 = ECC7. HW numbering is MSB, order here is LSB. * * These values come from the HW design of the ECC algorithm. */ static uint64_t eccMatrix[] = { /*0000000000000000111010000100001000111100000011111001100111111111 */ 0x0000e8423c0f99ff, /*0000000011101000010000100011110000001111100110011111111100000000 */ 0x00e8423c0f99ff00, /*1110100001000010001111000000111110011001111111110000000000000000 */ 0xe8423c0f99ff0000, /*0100001000111100000011111001100111111111000000000000000011101000 */ 0x423c0f99ff0000e8, /*0011110000001111100110011111111100000000000000001110100001000010 */ 0x3c0f99ff0000e842, /*0000111110011001111111110000000000000000111010000100001000111100 */ 0x0f99ff0000e8423c, /*1001100111111111000000000000000011101000010000100011110000001111 */ 0x99ff0000e8423c0f, /*1111111100000000000000001110100001000010001111000000111110011001 */ 0xff0000e8423c0f99 }; /** Syndrome calculation matrix. * * Maps syndrome to flipped bit. * * To perform ECC correction, this matrix is a look-up of the bit * that is bad based on the binary difference of the good and bad * ECC. This difference is called the "syndrome". * * When a particular bit is on in the data, it cause a column from * eccMatrix being XOR'd into the ECC field. This column is the * "effect" of each bit. If a bit is flipped in the data then its * "effect" is missing from the ECC. You can calculate ECC on unknown * quality data and compare the ECC field between the calculated * value and the stored value. If the difference is zero, then the * data is clean. If the difference is non-zero, you look up the * difference in the syndrome table to identify the "effect" that * is missing, which is the bit that is flipped. * * Notice that ECC bit flips are recorded by a single "effect" * bit (ie. 0x1, 0x2, 0x4, 0x8 ...) and double bit flips are identified * by the UE status in the table. * * Bits are in MSB order. */ static uint8_t syndromeMatrix[] = { ECC_GD, ECC_E7, ECC_E6, ECC_UE, ECC_E5, ECC_UE, ECC_UE, 47, ECC_E4, ECC_UE, ECC_UE, 37, ECC_UE, 35, 39, ECC_UE, ECC_E3, ECC_UE, ECC_UE, 48, ECC_UE, 30, 29, ECC_UE, ECC_UE, 57, 27, ECC_UE, 31, ECC_UE, ECC_UE, ECC_UE, ECC_E2, ECC_UE, ECC_UE, 17, ECC_UE, 18, 40, ECC_UE, ECC_UE, 58, 22, ECC_UE, 21, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 16, 49, ECC_UE, 19, ECC_UE, ECC_UE, ECC_UE, 23, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 20, ECC_UE, ECC_UE, ECC_E1, ECC_UE, ECC_UE, 51, ECC_UE, 46, 9, ECC_UE, ECC_UE, 34, 10, ECC_UE, 32, ECC_UE, ECC_UE, 36, ECC_UE, 62, 50, ECC_UE, 14, ECC_UE, ECC_UE, ECC_UE, 13, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 61, 8, ECC_UE, 41, ECC_UE, ECC_UE, ECC_UE, 11, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 15, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 12, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_E0, ECC_UE, ECC_UE, 55, ECC_UE, 45, 43, ECC_UE, ECC_UE, 56, 38, ECC_UE, 1, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 25, 26, ECC_UE, 2, ECC_UE, ECC_UE, ECC_UE, 24, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 28, ECC_UE, ECC_UE, 59, 54, ECC_UE, 42, ECC_UE, ECC_UE, 44, 6, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 5, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 63, 53, ECC_UE, 0, ECC_UE, ECC_UE, ECC_UE, 33, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 3, ECC_UE, ECC_UE, 52, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 7, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 60, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, 4, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, ECC_UE, }; /** Returns the parity of x, i.e. the number of 1-bits in x modulo 2. * Replacement for __builtin_parityl */ uint8_t parity_check( uint64_t i_data ) { int ones = 0; uint32_t x; for( x=0; x<(sizeof(i_data)*8); x++ ) { if( i_data & (0x8000000000000000ull >> x) ) { ones++; } } return ones%2; } /** Create the ECC field corresponding to a 8-byte data field * * @param[in] i_data - The 8 byte data to generate ECC for. * @return The 1 byte ECC corresponding to the data. */ uint8_t generateECC(uint64_t i_data) { uint8_t result = 0; int i = 0; for (i = 0; i < 8; i++) { result |= (parity_check(eccMatrix[i] & i_data) << i); } return result; } /** Verify the data and ECC match or indicate how they are wrong. * * @param[in] i_data - The data to check ECC on. * @param[in] i_ecc - The [supposed] ECC for the data. * * @return eccBitfield or 0-64. * * @retval GD - Indicates the data is good (matches ECC). * @retval UE - Indicates the data is uncorrectable. * @retval all others - Indication of which bit is incorrect. */ uint8_t verifyECC(uint64_t i_data, uint8_t i_ecc) { return syndromeMatrix[generateECC(i_data) ^ i_ecc]; } /** Correct the data and/or ECC. * * @param[in,out] io_data - Data to check / correct. * @param[in,out] io_ecc - ECC to check / correct. * * @return eccBitfield or 0-64. * * @retval GD - Data is good. * @retval UE - Data is uncorrectable. * @retval all others - which bit was corrected. */ uint8_t correctECC(uint64_t* io_data, uint8_t* io_ecc) { uint8_t badBit = verifyECC(*io_data, *io_ecc); if ((badBit != ECC_GD) && (badBit != ECC_UE)) /* Good is done, UE is hopeless. */ { /* Determine if the ECC or data part is bad, do bit flip. */ if (badBit >= ECC_E7) { *io_ecc ^= (1 << (badBit - ECC_E7)); } else { *io_data ^= (1ul << (63 - badBit)); } } return badBit; } void injectECC(const uint8_t* i_src, uint32_t i_srcSz, uint8_t* o_dst) { if (0 != (i_srcSz % sizeof(uint64_t))) { return; } uint32_t i = 0; uint32_t o = 0; for(i = 0, o = 0; i < i_srcSz; i += sizeof(uint64_t), o += sizeof(uint64_t) + sizeof(uint8_t)) { /* Read data word, copy to destination. */ uint64_t data = *((const uint64_t*)(&i_src[i])); *((uint64_t*)(&o_dst[o])) = data; data = be64toh(data); /* Calculate ECC, copy to destination. */ uint8_t ecc = generateECC(data); o_dst[o + sizeof(uint64_t)] = ecc; } } eccStatus removeECC(uint8_t* io_src, uint8_t* o_dst, uint32_t i_dstSz) { if (0 != (i_dstSz % sizeof(uint64_t))) { return -1; } eccStatus rc = ECC_CLEAN; uint32_t i = 0, o = 0; for(i = 0, o = 0; o < i_dstSz; i += sizeof(uint64_t) + sizeof(uint8_t), o += sizeof(uint64_t)) { /* Read data and ECC parts. */ uint64_t data = *((uint64_t*)(&io_src[i])); data = be64toh(data); uint8_t ecc = io_src[i + sizeof(uint64_t)]; /* Calculate failing bit and fix data. */ uint8_t badBit = correctECC(&data, &ecc); /* Return data to big endian. */ data = htobe64(data); /* Perform correction and status update. */ if (badBit == ECC_UE) { rc = ECC_UNCORRECTABLE; } else if (badBit != ECC_GD) { if (rc != ECC_UNCORRECTABLE) { rc = ECC_CORRECTED; } *((uint64_t*)(&io_src[i])) = data; io_src[i + sizeof(uint64_t)] = ecc; } /* Copy fixed data to destination buffer. */ *((uint64_t*)(&o_dst[o])) = data; } return rc; } <|start_filename|>src/ssx/occhw/occhw_irq.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_irq.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_IRQ_H__ #define __OCCHW_IRQ_H__ /// \file occhw_irq.h /// \brief PPC405-OCCHW Interrupt handling for SSX /// /// The OCCHW interrupt controller supports a maximum of 64 interrupts, split /// into 2 x 32-bit non-cascaded interrupt controllers with simple OR /// combining of the interrupt signals. /// /// The OCB interrupt controller allows interrupt status to be set directly by /// software, as well as providing a mode that causes an enabled pending /// interrupt to trigger an Unconditional Debug Event. The OCB interrupt /// controller contains a 'mask' register, unlike other 405 interrupt /// controllers that have an 'enable' register. The OCCHW mask and status /// registers also have atomic CLR/OR function so that it is never necessary /// to enter a critical section to enable/disable/clear interrupts and /// interrupt status. #include "occhw_common.h" #include "ocb_register_addresses.h" #ifndef __ASSEMBLER__ /// Enable an interrupt by clearing the mask bit. UNLESS__PPC405_IRQ_CORE_C__(extern) inline void ssx_irq_enable(SsxIrqId irq) { out32(OCCHW_OIMR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } /// Disable an interrupt by setting the mask bit. UNLESS__PPC405_IRQ_CORE_C__(extern) inline void ssx_irq_disable(SsxIrqId irq) { out32(OCCHW_OIMR_OR(irq), OCCHW_IRQ_MASK32(irq)); } /// Clear interrupt status with an CLR mask. Only meaningful for /// edge-triggered interrupts. UNLESS__PPC405_IRQ_CORE_C__(extern) inline void ssx_irq_status_clear(SsxIrqId irq) { out32(OCCHW_OISR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } /// Get IRQ status as a 0 or non-0 integer UNLESS__PPC405_IRQ_CORE_C__(extern) inline int ssx_irq_status_get(SsxIrqId irq) { return (in32(OCCHW_OISR(irq)) & OCCHW_IRQ_MASK32(irq)) != 0; } /// Set or clear interrupt status explicitly. UNLESS__PPC405_IRQ_CORE_C__(extern) inline void ssx_irq_status_set(SsxIrqId irq, int value) { if (value) { out32(OCCHW_OISR_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OISR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } } void ssx_irq_debug_set(SsxIrqId irq, int value); #endif /* __ASSEMBLER__ */ /// \page occhw_irq_macros OCCHW IRQ API Assembler Macros /// /// These macros encapsulate the SSX API for the OCCHW interrupt /// controller. These macros require 2 scratch registers in addition to the \c /// irq parameter register passed into the handler from SSX interrupt /// dispatch. These macros also modift CR0. /// /// \arg \c rirq A register that holds the \c irq parameter passed to /// the handler from SSX interrupt dispatch. This register is not /// modified. /// \arg \c rmask A scratch register - At the end of macro execution this /// register contains the 32-bit mask form of the irq. /// /// \arg \c raddr A scratch register - At the end of macro execution this /// register holds the address of the interrupt /// controller facility that implements the action. /// /// \arg \c imm An immediate (0/non-0) value for certain macros. /// /// Forms: /// /// \b _ssx_irq_enable \a rirq, \a rmask, \a raddr - Enable an \c irq. \n /// \b _ssx_irq_disable \a rirq, \a rmask, \a raddr - Disable an \c irq. \n /// \b _ssx_irq_status_clear \a rirq, \a rmask, \a raddr - Clear \c irq /// interrupt status. \n /// \b _ssx_irq_status_set \a rirq, \a rmask, \a raddr, \a imm - Set \c irq status /// with an immediate (0/non-0) value. \n /// /// \todo Once the logic design is locked down, revisit whether these macros /// (and C-code versions) can be implemented without branching. This could be /// done in theory by converting bit 26 into the byte offset between addresses /// in interupt controller 0 and interrupt controller 1 - assuming the /// distances are all the same power-of-two. /// /// \cond // IRQ numbers are in the range 0..63. IRQs are converted to the 32-bit // residue used to compute the mask. CR0 is set as a test of IRQ > 32 - the // register \c raddr is used as scratch for these computations. Hopefully the // local labels 888 and 999 are unique enough. // Register names must be compared as strings - e.g., %r0 is not // a symbol, it is converted to "0" by the assembler. #ifdef __ASSEMBLER__ // *INDENT-OFF* .macro .two_unique, ra, rb .ifnc \ra, \rb .exitm .endif .error "Both register arguments must be unique" .endm .macro .three_unique, ra, rb, rc .ifnc \ra, \rb .ifnc \rb, \rc .ifnc \ra, \rc .exitm .endif .endif .endif .error "All three register arguments must be unique" .endm .macro _occhw_irq_or_mask, rirq:req, rmask:req .two_unique \rirq, \rmask lis \rmask, 0x8000 srw \rmask, \rmask, \rirq .endm .macro _occhw_irq_clr_mask, rirq:req, rmask:req .two_unique \rirq, \rmask _occhw_irq_or_mask \rirq, \rmask .endm .macro _ssx_irq_enable, rirq:req, rmask:req, raddr:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 _occhw_irq_clr_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OIMR0_CLR b 999f 888: _stwi \rmask, \raddr, OCB_OIMR1_CLR 999: eieio .endm .macro _ssx_irq_disable, rirq:req, rmask:req, raddr:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 _occhw_irq_or_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OIMR0_OR b 999f 888: _stwi \rmask, \raddr, OCB_OIMR1_OR 999: eieio .endm .macro _ssx_irq_status_clear, rirq:req, rmask:req, raddr:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 _occhw_irq_clr_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OISR0_CLR b 999f 888: _stwi \rmask, \raddr, OCB_OISR1_CLR 999: eieio .endm .macro _ssx_irq_status_set, rirq:req, rmask:req, raddr:req, imm:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 .if \imm _occhw_irq_or_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OISR0_OR b 999f 888: _stwi \rmask, \raddr, OCB_OISR1_OR .else _occhw_irq_clr_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OISR0_CLR b 999f 888: _stwi \rmask, \raddr, OCB_OISR1_CLR .endif 999: eieio .endm // *INDENT-ON* #endif /* __ASSEMBLER__ */ /// \endcond #endif /* __OCCHW_IRQ_H__ */ <|start_filename|>src/common/get_tod_structs.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/common/get_tod_structs.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* This header file is used by both occ_405 and occ_gpe0. */ /* Contains common structures and defines. */ #ifndef _GET_TOD_STRUCTS_H #define _GET_TOD_STRUCTS_H #include <stdint.h> // For uint*_t #include <gpe_export.h> // For GpeErrorStruct /** * Struct containing the error state and arguments for the IPC function * IPC_ST_GET_TOD_FUNCID. */ typedef struct __attribute__ ((packed)) { GpeErrorStruct error; uint64_t tod; } gpe_get_tod_args_t; /** * Value used when the actual TOD value is unknown. */ #define TOD_VALUE_UNKNOWN 0xFFFFFFFFFFFFFFFFull #endif // _GET_TOD_STRUCTS_H <|start_filename|>src/occ_gpe0/firdata/scom_addr_util.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/scom_addr_util.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __scom_addr_util_h #define __scom_addr_util_h #include <stdint.h> //This file is a result of de-classing the p9_scom_addr that currently //lives in EKB: chips/p9/common/scominfo/p9_scom_addr.H // @brief Modify SCOM address, update satellite ID field // @param[in] i_sat_id Satellite ID value to write // @retval none // void set_sat_id(const uint8_t i_sat_id, uint64_t * o_addr); // @brief Modify SCOM address, update pervasive chiplet ID // @param[in] i_chiplet_id Chiplet ID value to write // @retval none // void set_chiplet_id(const uint8_t i_chiplet_id, uint64_t * o_addr); // @brief Modify SCOM address, update ring field value // @param[in] i_ring Ring field value to write // @retval none void set_ring(const uint8_t i_ring, uint64_t * o_addr); // @brief Modify SCOM address, update satellite offset field // @param[in] i_sat_offset Satellite offset value to write // @retval none void set_sat_offset(const uint8_t i_sat_offset, uint64_t * o_addr); // @brief Modify SCOM address, update the RX or TX Group ID // @param[in] i_grp_id Group id to set // @retval none void set_rxtx_group_id(const uint8_t i_grp_id, uint64_t * o_addr); // @brief Extract satellite ID field from SCOM address // @retval uint8_t Satellite ID field value uint8_t get_sat_id(const uint64_t i_addr); // @brief Extract pervasive chiplet ID from SCOM address // @retval uint8_t Pervasive chiplet ID value uint8_t get_chiplet_id(const uint64_t i_addr); // @brief Extract ring field from SCOM address // @retval uint8_t Ring field value uint8_t get_ring(const uint64_t i_addr); // @brief Extract satellite register offset field from SCOM address // @retval uint8_t Satellite register offset field value uint8_t get_sat_offset(const uint64_t i_addr); // @brief Extract the RX or TX Group ID of an indirect scom address // @retval uint8_t Satellite register offset field value uint8_t get_rxtx_group_id(const uint64_t i_addr); #endif <|start_filename|>src/ssx/occhw/occhw_id.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_id.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_ID_H__ #define __OCCHW_ID_H__ /// \file occhw_id.h /// \brief chip and EC-level identification + chip configuration /// /// During initialization the device identification SCOM registers are read /// and cached. /// /// The node and chip ids are read from TPC_GP0 and stored as global /// variables, accessible through the node_id() and chip_id() APIs. The /// global variables are available to PORE programs. /// /// The TPC_DEVICE_ID register is also read, deconstructed and stored in /// global variables. APIs defined here provide access to the fields of the /// device identification to support run-time behavior based on the chip type /// and EC level of the POWER8 chip containing the OCC. The global variables /// are available to PORE programs. /// /// - cfam_id() : Obtain the full chip identification as a 32-bit CFAM id /// - cfam_chip_type() : Obtain the 8-bit CFAM chip type /// - cfam_ec_level() : Obtain an 8-bit CFAM EC level /// /// For example, to identify a chip as Murano DD1.0, one could use either /// method shown below: /// /// \code /// /// if (cfam_id() == CFAM_CHIP_ID_MURANO_10) { ... } /// /// if ((cfam_chip_type() == CFAM_CHIP_TYPE_MURANO) && /// (cfam_ec_level() == 0x10)) { ... } /// /// \encode // Error/Panic Codes #define OCCHW_ID_SCOM_ERROR_SELECT 0x00747401 #define OCCHW_ID_SCOM_ERROR_CONFIG 0x00747402 #define OCCHW_ID_SELECT_ERROR 0x00747403 #ifndef __ASSEMBLER__ #include <stdint.h> #include "tpc_firmware_registers.h" /// Get TPC device identification (internal API, called once from __occhw_setup(). void _occhw_get_ids(void); /// Get the TPC Node Id uint8_t node_id(void); /// Get the TPC Chip Id uint8_t chip_id(void); /// Get the CFAM Chip Id /// /// \returns A 32-bit value to be compared against the enumeration of known /// CFAM ids. See \ref cfam_chip_ids. uint32_t cfam_id(void); /// Get the CFAM Chip Type /// /// \returns An 8-bit value to be compared against the enumeration of known /// CFAM chip types. See \ref cfam_chip_types. uint8_t cfam_chip_type(void); /// Get the CFAM Chip EC Level /// /// \returns An 8-bit value; The high-order nibble is the major EC level and /// the low-order nibble is the minor EC level. Fore example a value of 0x21 /// indicates DD 2.1. uint8_t cfam_ec_level(void); /// Compute the chip configuration (internal API, called once from __occhw_setup(). void _occhw_get_chip_configuration(void); /// Get the core configuration /// /// The return value is a 32 bit integer with big-endian bits set to indicate /// valid cores. uint32_t core_configuration(void); #endif // __ASSEMBLER__ /// \defgroup cfam_chip_types CFAM Chip Types (Including Centaur) /// /// The CFAM Chip Type is an 8-bit value that uniquely identfies a chip /// architecture. /// /// @{ #define CFAM_CHIP_TYPE_CENTAUR 0xe9 #define CFAM_CHIP_TYPE_VENICE 0xea #define CFAM_CHIP_TYPE_MURANO 0xef /// @} /// \defgroup cfam_chip_ids CFAM Chip Ids (Including Centaur) /// /// The CFAM Chip ID is a 32-bit value that uniquely identfies a chip and its /// EC level. /// /// The reference: /// /// - https://eclipz.pok.ibm.com/sys/ras/docs/cfam_ids.txt /// /// The interpretation: /// /// MlmCC049 /// /// M - Major EC (RIT-A) level /// l - 2:Austin, 6:Poughkeepsie /// m - Minor EC (RIT-B) level /// CC - 0xE9:Centaur, 0xEA:Venice, 0xEF:Murano /// 049 - IBM (Except for buggy 0x001 in Murano DD1.X) /// /// @{ #define CFAM_CHIP_ID_VENICE_10 0x120ea049 #define CFAM_CHIP_ID_VENICE_20 0x220ea049 #define CFAM_CHIP_ID_VENICE_21 0x221ea049 #define CFAM_CHIP_ID_MURANO_10 0x120ef001 #define CFAM_CHIP_ID_MURANO_11 0x121ef001 #define CFAM_CHIP_ID_MURANO_12 0x122ef001 #define CFAM_CHIP_ID_MURANO_13 0x123ef001 #define CFAM_CHIP_ID_MURANO_20 0x220ef049 #define CFAM_CHIP_ID_MURANO_21 0x221ef049 #define CFAM_CHIP_ID_CENTAUR_10 0x160e9049 #define CFAM_CHIP_ID_CENTAUR_20 0x260e9049 #ifndef __ASSEMBLER__ /// The CFAM ID as a set of fields typedef union { #ifdef _BIG_ENDIAN struct { uint32_t majorEc : 4; uint32_t location : 4; uint32_t minorEc : 4; uint32_t chipType : 8; uint32_t vendor : 12; }; #else struct { uint32_t vendor : 12; uint32_t chipType : 8; uint32_t minorEc : 4; uint32_t location : 4; uint32_t majorEc : 4; }; #endif // _BIG_ENDIAN uint32_t value; } cfam_id_t; #endif // __ASSEMBLER__ /// @} #endif // __OCCHW_ID_H__ <|start_filename|>src/ssx/ppc405/ppc405_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppc405_init.c /// \brief PPC405 initialization routines /// /// The entry points in this file are routines that are typically used during /// initialization, and their code space could be deallocated and recovered if /// no longer needed by the application after initialization. #include "ssx.h" #include "ssx_trace.h" // Note that __ppc405_system_setup() is called from the SSX bootloader early // in the initialization, at a point before the aplication has enabled // critical or external interruts. void __ppc405_system_setup() { SsxIrqId irq; // Initialize the interrupt vectors. for (irq = 0; irq < EXTERNAL_IRQS; irq++) { __ppc405_irq_handlers[irq].handler = __ppc405_default_irq_handler; __ppc405_irq_handlers[irq].arg = 0; } __ppc405_phantom_irq.handler = __ppc405_phantom_irq_handler; __ppc405_phantom_irq.arg = 0; // Initialize special interrupt handlers __ppc405_fit_routine = __ppc405_default_irq_handler; __ppc405_fit_arg = 0; __ppc405_watchdog_routine = __ppc405_default_irq_handler; __ppc405_watchdog_arg = 0; __ppc405_debug_routine = __ppc405_default_irq_handler; __ppc405_debug_arg = 0; // Enable the PIT interrupt, but not auto-reload mode. Clear the status // of all timers for good measure. andc_spr(SPRN_TCR, TCR_ARE); or_spr(SPRN_TCR, TCR_PIE); or_spr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_PIS | TSR_FIS); #if SSX_TIMER_SUPPORT #if SSX_TRACE_SUPPORT extern SsxTraceBuffer g_ssx_trace_buf; //set the instance id g_ssx_trace_buf.instance_id = OCCHW_INST_ID_PPC; #endif /* SSX_TRACE_SUPPORT */ #endif /* SSX_TIMER_SUPPORT */ #ifdef HWMACRO_OCC // Call system-specific setup void __occhw_setup(); __occhw_setup(); #endif } // Set the timebase using the PowerPC protocol. void __ssx_timebase_set(SsxTimebase t) { Uint64 tb; tb.value = t; mttbl(0); mttbu(tb.word[0]); mttbl(tb.word[1]); } <|start_filename|>src/ssx/ppc405/ppc405_cache_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_cache_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppc405_cache_core.c /// \brief Core cache management routines required of any PPC405 configuration /// of SSX that interacts with DMA devices using cacheable memory. /// /// The entry points in this file are considered 'core' routines that will /// always be present at runtime in any SSX application. /// /// \todo The compiler generates wierd assembly language for these cache /// management APIs - probably due to the "volatile" asm - it may be best to /// recode them directly in assembler. #include "ssx.h" /// Invalidate a range of addresses from the D-cache /// /// \param p A pointer to the memory area to be invalidated. /// /// \param bytes The size (in bytes) of the area to invalidate. /// /// The dcache_invalidate() API is used to invalidate an arbitrary range of /// memory in the cache. Note that invalidation is a destructive operation /// that may cause the loss of information. This API will invalidate all /// cache lines from the line containing the address \a p, to the line /// containing the address \a p + \a size - 1. (If \a size == 0 this call is /// a NOP.) It is the caller's responsibility to insure that no useful data is /// inadverdently invalidated. D-cache invalidation is more-or-less a no-op /// for data either not in the cache or marked as non-cacheable. /// /// This API always issues a sync() after the invalidation, even in the event /// of \a size == 0. /// /// \note For invalidating small blocks of data where some alignmment /// constraints are known it may be more efficient to use /// dcache_invalidate_line() rather than this API. void dcache_invalidate(void* p, size_t bytes) { size_t lines; if (bytes != 0) { lines = 1; bytes -= MIN((CACHE_LINE_SIZE - ((unsigned long)p % CACHE_LINE_SIZE)), bytes); lines += bytes / CACHE_LINE_SIZE; if (!cache_aligned(bytes)) { lines++; } while (lines--) { dcbi(p); p += CACHE_LINE_SIZE; } } sync(); } /// Flush and invalidate a range of addresses from the D-cache /// /// \param p A pointer to a memory area to be invalidated. /// /// \param bytes The size (in bytes) of the area to invalidate. /// /// The dcache_flush() API is used to flush and invalidate an arbitrary range /// of memory from the D-cache. Note that flushing is not a destructive /// operation in the sense that no information is lost. This API will flush /// and invalidate all cache lines from the line containing the address \a p, /// to the line containing the address \a p + \a size - 1. (If \a size == 0 /// this call is a NOP.) D-cache flush is more-or-less a no-op for data /// either not in the cache or marked as non-cacheable. /// /// This API always issues a sync() after the flush, even in the event of \a /// size == 0. /// /// \note For flushing small blocks of data where some alignmment constraints /// are known it may be more efficient to use dcache_flush_line() rather than /// this API. void dcache_flush(void* p, size_t bytes) { size_t lines; if (bytes != 0) { lines = 1; bytes -= MIN((CACHE_LINE_SIZE - ((unsigned long)p % CACHE_LINE_SIZE)), bytes); lines += bytes / CACHE_LINE_SIZE; if (!cache_aligned(bytes)) { lines++; } while (lines--) { dcbf(p); p += CACHE_LINE_SIZE; } } sync(); } <|start_filename|>src/occ_gpe0/gpe_core_data.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/gpe_core_data.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "core_data.h" #include "ipc_async_cmd.h" #include "gpe_err.h" #include "gpe_util.h" #include "proc_shared.h" #include "nest_dts.h" /* * Function Specifications: * * Name: gpe_get_core_data * * Description: extract core number, call get_core data with the * proper core id and pointer to CoreData * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void gpe_get_core_data(ipc_msg_t* cmd, void* arg) { uint32_t rc; // return code ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; ipc_core_data_parms_t *args = (ipc_core_data_parms_t*) async_cmd->cmd_data; static uint32_t L_trace = 0; rc = get_core_data(args->core_num, // core ID args->data); // CoreData* if(rc) { // trace non-offline error once per core. // offline errors are normal with stop states and ignored by the 405 if( (!(L_trace & (1 << args->core_num))) && (rc != PCB_ERROR_CHIPLET_OFFLINE) ) { PK_TRACE("gpe_get_core_data: get_core_data failed, rc = 0x%08x, core = 0x%08x", rc, args->core_num); L_trace |= (1 << args->core_num); } gpe_set_ffdc(&(args->error), args->core_num, GPE_RC_GET_CORE_DATA_FAILED, rc); } // send back a response, IPC success even if ffdc/rc are non zeros rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("gpe_get_core_data: Failed to send response back. Halting GPE0", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } } /* * Function Specifications: * * Name: gpe_get_nest_dts * * Description: Get the 3 NEST DTS sensor readings * * Inputs: cmd is a pointer to IPC msg's cmd and cmd_data struct * * Outputs: error: sets rc, address, and ffdc in the cmd_data's * GpeErrorStruct * * End Function Specification */ void gpe_get_nest_dts(ipc_msg_t* cmd, void* arg) { uint32_t rc; // return code ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; ipc_nest_dts_parms_t *args = (ipc_nest_dts_parms_t*) async_cmd->cmd_data; args->error.error = 0; args->error.ffdc = 0; rc = get_nest_dts(&args->data); // NestDts_t* if(rc) { PK_TRACE("gpe_get_nest_dts: get_nest_dts failed, rc = 0x%08x", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_GET_NEST_DTS_FAILED, rc); } // send back a response, IPC success even if ffdc/rc are non zeros rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("gpe_get_nest_dts: Failed to send response back. Halting GPE0", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } } <|start_filename|>src/ppe/pk/gpe/gpe_pba_cntl.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/gpe/gpe_pba_cntl.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // PBA slave control for PK // PBA slave 0,1,2,3 (disable 3 for now) // Write TTypes: // PBA_WRITE_TTYPE_DMA_PR_WR (DMA Partial Write) (default if don't care) // PBA_WRITE_TTYPE_LCO_M (L3 LCO for IPL, Tsize denotes chiplet) // PBA_WRITE_TTYPE_ATOMIC_RMW (Atomic) // PBA_WRITE_TTYPE_CACHE_INJECT(Cache inject after IPL) // PBA_WRITE_TTYPE_CI_PR_W (Cache-inhibited partial write) // // Read TTypes // PBA_READ_TTYPE_CL_RD_NC (Cache line read) (default if don't care) // PBA_READ_TTYPE_CI_PR_R (Cache-inhibitited parital read) // // @see ssx/occhw/occhw_pba.h // // See 6.10.3.4 of the P9_Power_Managemente_Spec. // 1. Stop write requests on Master(s), // (Read requests can continue if not changing read ttype) // 2. Write PBASLVRST(SLV Reset) on the desired slave // 3. Poll for PBASLVRST(Busy SLV Status) = 0 // 4. Change PBASLVCTL // 5. Resume requests from Master(s) // #include "pba_register_addresses.h" #include "pba_firmware_registers.h" #include "gpe_pba_cntl.h" #define PPE_LVD(_m_address, _m_data) \ asm volatile \ ( \ "lvd %[data], 0(%[address]) \n" \ : [data]"=r"(_m_data) \ : [address]"b"(_m_address) \ ); // PPE Store Virtual Double operation #define PPE_STVD(_m_address, _m_data) \ asm volatile \ ( \ "stvd %[data], 0(%[address]) \n" \ : [data]"=&r"(_m_data) \ : "[data]"(_m_data), \ [address]"b"(_m_address) \ : "memory" \ ); // See gpe_pba_cntl.h for contract void gpe_pba_reset() { uint32_t slave = PBASLVCTLN; uint64_t value64 = 0; uint64_t val = 0; pba_slvrst_t slvrst; slvrst.value = 0; slvrst.fields.set = PBA_SLVRST_SET(slave); pba_slvrst_t rst_in_progress; rst_in_progress.value = 0; rst_in_progress.fields.in_prog = PBA_SLVRST_IN_PROG(slave); do { value64 = slvrst.value; PPE_STVD(PBA_SLVRST, value64); val = rst_in_progress.value; PPE_LVD(PBA_SLVRST, value64); val &= value64; } while(val != 0); } // See gpe_pba_cntl.h for contract. void gpe_pba_slave_setup(uint32_t i_gpeInstanceId, uint32_t i_write_ttype, uint32_t i_write_tsize, uint32_t i_read_ttype, uint32_t i_buf_alloc) { uint32_t slave = PBASLVCTLN; // gpe PBA_SLVCTL uint64_t current = 0; pba_slvctln_t slvctln; slvctln.value = 0; slvctln.fields.enable = 1; slvctln.fields.mid_match_value = i_gpeInstanceId; slvctln.fields.mid_care_mask = 0x7; slvctln.fields.write_ttype = i_write_ttype; slvctln.fields.read_ttype = i_read_ttype; // read prefetch - default 0, does it need param? slvctln.fields.read_prefetch_ctl = PBA_READ_PREFETCH_NONE; // slvctln.fields.buf_invalidate_ctl - leave 0 slvctln.fields.buf_alloc_w = (i_buf_alloc & PBA_BUF_W) != 0; slvctln.fields.buf_alloc_a = (i_buf_alloc & PBA_BUF_A) != 0; slvctln.fields.buf_alloc_b = (i_buf_alloc & PBA_BUF_B) != 0; slvctln.fields.buf_alloc_c = (i_buf_alloc & PBA_BUF_C) != 0; slvctln.fields.dis_write_gather = 1; slvctln.fields.wr_gather_timeout = PBA_WRITE_GATHER_TIMEOUT_2_PULSES; slvctln.fields.write_tsize = i_write_tsize; // slvctln.fields.extaddr = 0; PowerBus address bits (23:36) // Only write PBA_SLVCTL if it needs to change PPE_LVD(PBA_SLVCTLN(slave), current); if(slvctln.value != current) { gpe_pba_reset(); PPE_STVD(PBA_SLVCTLN(slave), slvctln.value); } } <|start_filename|>src/include/gpe_pba_parms.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/common/pmlib/include/gpe_pba_parms.h $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ #if !defined(__GPE_PBA_PARMS_H__) #define __GPE_PBA_PARMS_H__ #include <stdint.h> #include "pba_register_addresses.h" #include "pba_firmware_registers.h" typedef struct { /// The 32-bit OCI address of the PBA_SLVCTLn register to set up uint32_t slvctl_address; /// The slave id (0 - 3) uint32_t slave_id; /// An image of the relevant parts of the PBA_SLVCTLn register in effect /// for this procedure //pba_slvctln_t slvctl; pba_slvctln_t slvctl; /// The mask in effect for this update of the PBA_SLVCTL //pba_slvctln_t mask; pba_slvctln_t mask; /// The value to write to the PBA_SLVRST register to reset the slave //pba_slvrst_t slvrst; pba_slvrst_t slvrst; /// The bit to AND-poll to check for slave reset in progress //pba_slvrst_t slvrst_in_progress; pba_slvrst_t slvrst_in_progress; } GpePbaParms; #endif <|start_filename|>src/lib/common/libcommonfiles.mk<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/lib/common/libcommonfiles.mk $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2015,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG # @file libcommonfiles.mk # # @brief mk for libcommon.a object files ########################################################################## # INCLUDES ########################################################################## C-SOURCES = \ memcpy.c \ memset.c \ string.c \ S-SOURCES = LIBCOMMON_OBJECTS = $(C-SOURCES:.c=.o) $(S-SOURCES:.S=.o) <|start_filename|>src/ssx/occhw/occhw.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_H__ #define __OCCHW_H__ /// \file occhw.h /// \brief The OCCHW environment for SSX. // This is a 'circular' reference in SSX, but included here to simplify PGAS // programming. #ifndef HWMACRO_OCC #define HWMACRO_OCC #include "ppc405.h" #endif // Can't include this here due to ordering issues. It's included in // ppc405_irq.h. // #include "occhw_irq.h" // Required for MMU Map declarations #include "ppc405_mmu.h" #include "occhw_common.h" #include "occhw_core.h" #include "occhw_ocb.h" #include "occhw_pba.h" #include "occhw_scom.h" #include "occhw_sramctl.h" //#include "occhw_vrm.h" #include "occhw_id.h" //#include "occhw_centaur.h" //#include "pcbs_register_addresses.h" //#include "pcbs_firmware_registers.h" //#include "tod_register_addresses.h" //#include "tod_firmware_registers.h" //#include "mcs_register_addresses.h" //#include "mcs_firmware_registers.h" //#include "centaur_firmware_registers.h" //#include "centaur_register_addresses.h" #include "tpc_register_addresses.h" #include "tpc_firmware_registers.h" /// \defgroup memory_map Real-mode memory map setup for SRAM-resident applications /// /// Below are the interpretations of the default settings of the real-mode /// memory control registers. All of the settings can be overridden as /// compile switches for special test purposes. /// /// The final 128MB of memory (the SRAM) is mapped both I- and /// D-cacheable. The other 7 high-memory regions aliased by the SRAM remain /// uncacheable, however SRAM alias region 29 is marked write-through. /// /// Low memory addresses (direct-map Mainstore via PBA) are I-cacheable /// but not D-cacheable to improve predicatability of execution times. /// However, we should not execute from mainstore after initialization. /// /// OCI register space (Segment '0b01') is marked guarded and non-cacheable. /// /// All memory is big-endian. /// /// @{ #ifndef PPC405_ICCR_INITIAL #define PPC405_ICCR_INITIAL 0xff000001 #endif #ifndef PPC405_DCCR_INITIAL #define PPC405_DCCR_INITIAL 0x00000001 #endif #ifndef PPC405_DCWR_INITIAL #define PPC405_DCWR_INITIAL 0x00000004 #endif #ifndef PPC405_SGR_INITIAL #define PPC405_SGR_INITIAL 0x00ff0000 #endif #ifndef PPC405_SU0R_INITIAL #define PPC405_SU0R_INITIAL 0x00000000 #endif #ifndef PPC405_SLER_INITIAL #define PPC405_SLER_INITIAL 0x00000000 #endif /// @} /// OCCHW always runs from a memory image #define SSX_RUN_FROM_MEMORY 1 /// This is the initial value of Cache Control Register 0 (CCR0) for OCCHW. /// This definition can be overridden by the application. /// /// The default setting: /// /// - Enables parity checking in the caches and TLBs. The parity mode is not /// modified and defaults to 'imprecise'. /// /// - Enables ICU prefetching for cacheable regions (Subject to final /// performance evaluation). Non-cacheable regions are not prefetched. /// /// - Gives highest PLB priority to ICU fetches. This setting can be /// overriden by scan-only dials in the OCCHW design which force a fixed /// priority on the ICU. /// /// - Sets priority bit 1 to '1' for DCU operations. The DCU sets priority /// bit 0 automatically. This setting can also be overridden by scan-only /// dials that force a fixed priority on the DCU /// /// Other options can be set at run time with the API \c ppc405_ccr0_modify(). #ifndef PPC405_CCR0_INITIAL #define PPC405_CCR0_INITIAL \ (CCR0_DPE | CCR0_IPE | CCR0_TPE | \ CCR0_PFC | \ CCR0_IPP0 | CCR0_IPP1 | \ CCR0_DPP1) #endif #ifndef __ASSEMBLER__ /// \page noncacheable_support Non-cacheable modes for OCCHW /// /// In order to support evaluation of cache management strategies on /// performance, DMA buffers read/written by DMA devices can be declared as /// NONCACHEABLE or NONCACHEABLE_RO, and DMA buffers read by DMA devices can /// be declared as WRITETHROUGH. However the code still does an explicit /// FLUSH of these buffers before activating DMA devices. The configuration /// option NONCACHEABLE_SUPPORT determines how NONCACHEABLE, NONCACAHEABLE_RO, /// WRITETHROUGH and FLUSH are defined. /// /// When noncacheable support is configured, the linker will link the /// noncacheable and writethrough sections at a fixed offset from cacheable /// address, depending on where SSX is loaded. Non-cacheable read-only /// sections are enforced only if PPC405_MMU_SUPPORT is also configured. /// Writethrogh sections are assumed to be read-write. /// /// OCCHW_HIGH_MEMORY_LOAD /// /// cacheable : 0xfff8000 - 0xffffffff /// noncacheable : 0xf7f8000 - 0xf7ffffff [cacheable - 128MB] /// writethrough : 0xeff8000 - 0xefffffff [cacheable - 256MB] #ifndef NONCACHEABLE_SUPPORT #define NONCACHEABLE_SUPPORT 0 #endif /// Declare an aligned data structure in a noncacheable RO section /// /// This macro declares an aligned data structure in a noncacheable read-only /// section. The linker requires that data allocated in non-default sections /// be initialized - so an initialization declaration for at least one element /// of the data structure is required. Use a value of 8 as the default /// alignment. /// /// See \ref noncacheable_support #if NONCACHEABLE_SUPPORT #define NONCACHEABLE_RO(declaration, alignment, initialization) \ declaration __attribute__ \ ((section (".noncacheable_ro"), aligned (alignment))) = initialization #else #define NONCACHEABLE_RO(declaration, alignment, initialization) \ declaration __attribute__ \ ((aligned (alignment))) = initialization #endif /* NONCACHEABLE_SUPPORT */ /// Declare an aligned data structure in a noncacheable RW section /// /// This macro declares an aligned data structure in a noncacheable read-write /// section. The linker requires that data allocated in non-default sections /// be initialized - so an initialization declaration for at least one element /// of the data structure is required. Use a value of 8 as the default /// alignment. /// /// See \ref noncacheable_support #if NONCACHEABLE_SUPPORT #define NONCACHEABLE(declaration, alignment, initialization) \ declaration __attribute__ \ ((section (".noncacheable"), aligned (alignment))) = initialization #else #define NONCACHEABLE(declaration, alignment, initialization) \ declaration __attribute__ \ ((aligned (alignment))) = initialization #endif /* NONCACHEABLE_SUPPORT */ /// Declare an aligned data structure in a write-through section /// /// This macro declares an aligned data structure in a write-throgh section. /// The linker requires that data allocated in non-default sections be /// initialized - so an initialization declaration for at least one element of /// the data structure is required. Use a value of 8 as the default /// alignment. /// /// See \ref noncacheable_support #if NONCACHEABLE_SUPPORT #define WRITETHROUGH(declaration, alignment, initialization) \ declaration __attribute__ \ ((section (".writethrough"), aligned (alignment))) = initialization #else #define WRITETHROUGH(declaration, alignment, initialization) \ declaration __attribute__ \ ((aligned (alignment))) = initialization #endif /* NONCACHEABLE_SUPPORT */ /// Flush/invalidate a region of memory #if NONCACHEABLE_SUPPORT #define FLUSH(p, n) do {} while (0) #define INVALIDATE(p, n) do {} while (0) #else #define FLUSH(p, n) do {dcache_flush((p), (n));} while (0) #define INVALIDATE(p, n) do {dcache_invalidate((p), (n));} while (0) #endif /* NONCACHEABLE_SUPPORT */ /// The type of linker symbols /// /// C++ and current GCC versions do not allow us to declare (C++) or take the /// address of (C) a symbol of type void, which was an acceptable way to /// declare linker symbols in earlier versions of GCC. However if we declare /// them of type 'char' or another integral type, the compiler will try to /// make references to this 'data' appear to be in the small data areas (since /// we're compiling with the PPC EABI), which causes the link to fail since /// the symbols are actually defined in many different sections. The solution /// is to declare them to be external references of a bogus type, /// SsxLinkerSymbol, which is too large (9 bytes) to be stored in the small /// data area. /// /// This type definition is considered a required definition for a port of /// SSX. typedef struct { char bogus[9]; } SsxLinkerSymbol; // Symbols defined by linkssx.cmd, used during MMU setup, byte-pool setup, and // other purposes. extern SsxLinkerSymbol _MEMORY_ORIGIN; extern SsxLinkerSymbol _MEMORY_SIZE; extern SsxLinkerSymbol _TEXT0_SECTION_BASE; extern SsxLinkerSymbol _TEXT0_SECTION_SIZE; extern SsxLinkerSymbol _TEXT1_SECTION_BASE; extern SsxLinkerSymbol _TEXT1_SECTION_SIZE; extern SsxLinkerSymbol _RODATA_SECTION_BASE; extern SsxLinkerSymbol _RODATA_SECTION_SIZE; extern SsxLinkerSymbol _NONCACHEABLE_RO_SECTION_BASE; extern SsxLinkerSymbol _NONCACHEABLE_RO_SECTION_SIZE; extern SsxLinkerSymbol _NONCACHEABLE_SECTION_BASE; extern SsxLinkerSymbol _NONCACHEABLE_SECTION_SIZE; extern SsxLinkerSymbol _WRITETHROUGH_SECTION_BASE; extern SsxLinkerSymbol _WRITETHROUGH_SECTION_SIZE; extern SsxLinkerSymbol _DATA_SECTION_BASE; extern SsxLinkerSymbol _DATA_SECTION_SIZE; extern SsxLinkerSymbol _EX_FREE_SECTION_BASE; extern SsxLinkerSymbol _EX_FREE_SECTION_SIZE; extern SsxLinkerSymbol _APPLET0_SECTION_BASE; extern SsxLinkerSymbol _APPLET0_SECTION_SIZE; extern SsxLinkerSymbol _APPLET1_SECTION_BASE; extern SsxLinkerSymbol _APPLET1_SECTION_SIZE; extern SsxLinkerSymbol _SSX_FREE_START; extern SsxLinkerSymbol _SSX_FREE_END; // Global MMU maps to allow remapping certain regions extern Ppc405MmuMap G_ex_free_mmu_map; extern Ppc405MmuMap G_applet0_mmu_map; extern Ppc405MmuMap G_applet1_mmu_map; #endif /* __ASSEMBLER__ */ // OCCHW defines a private version of dcache_flush_all() that uses undefined // OCI space defined by OCCHW_FLUSH_ZERO_ADDRESS. // See dcache_flush_all() in occhw_cache.S. // // DCCR bit | OCCHW_FLUSH_ZERO_ADDRESS ( see 405 spec for full table) // ---------|------------------------------------------ // 0 | 0x00000000 - 0x07ffffff // 1 | 0x08000000 - 0x0fffffff // 4 | 0x20000000 - 0x27ffffff // 8 | 0x40000000 - 0x47ffffff (undefined range - use for dcache flush) // 16 | 0x80000000 - 0x87ffffff (overlaps PBA defined space) // 31 | 0xF8000000 - 0xffffffff (overlaps SRAM) #define USE_GENERIC_DCACHE_FLUSH_ALL 0 #define OCCHW_FLUSH_ZERO_ADDRESS 0x40000000 #define OCCHW_FLUSH_ZERO_DCCR 0x00800000 #endif /* __OCCHW_H__ */ <|start_filename|>src/occ_405/amec/amec_perfcount.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_perfcount.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include <string.h> #include <common_types.h> #include <sensor.h> #include <amec_sys.h> #include <amec_part.h> #include <amec_perfcount.h> /*----------------------------------------------------------------------------*/ /* Constants */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Globals */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Typedef / Enum */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Code */ /*----------------------------------------------------------------------------*/ // Function Specification // // Name: amec_calc_dps_util_counters // // Description: Calculate the performance counter for a core. // // End Function Specification void amec_calc_dps_util_counters(const uint8_t i_core_id) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ amec_part_t *l_part = NULL; amec_core_perf_counter_t *l_perf = NULL; sensor_ptr_t l_sensor = NULL; uint16_t l_utilization = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ l_perf = &g_amec->proc[0].core[i_core_id].core_perf; // Read sensor for this core l_sensor = AMECSENSOR_ARRAY_PTR(UTILC0, i_core_id); l_utilization = l_sensor->sample; l_part = amec_part_find_by_core(&g_amec->part_config, i_core_id); // Type 41 input: Check if core's utilization is within // epsilon of the slack threshold: if yes declare the core // active if (l_part != NULL) { if (l_utilization > (l_part->dpsalg.tlutil - l_part->dpsalg.epsilon_perc)) { // indicate core is active l_perf->util_active_core_counter++; if (l_utilization < l_part->dpsalg.tlutil) { // indicate core has some slack l_perf->util_slack_core_counter++; } } } } // Function Specification // // Name: amec_core_perf_counter_ctor // // Description: Build the performance counter for a core. // // End Function Specification amec_core_perf_counter_t* amec_core_perf_counter_ctor(amec_core_perf_counter_t* i_this_ptr, const uint8_t i_proc_id, const uint8_t i_core_id) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ //zero everything out, regardless of when we were called memset(i_this_ptr, 0x00, sizeof(amec_core_perf_counter_t)); // Create space for per-core active and slack counts (for DPS #41 algorithm) memset(i_this_ptr->ptr_util_slack_avg_buffer, 0, (uint32_t)(2*MAX_UTIL_SLACK_AVG_LEN)); memset(i_this_ptr->ptr_util_active_avg_buffer, 0, (uint32_t)(2*MAX_UTIL_SLACK_AVG_LEN)); // DPS frequency request. Choose highest performance by default. i_this_ptr->dps_freq_request = UINT16_MAX; // input to core freq voting box //pass out i_this_ptr in case we're allocating this dynamically return i_this_ptr; } /*----------------------------------------------------------------------------*/ /* End */ /*----------------------------------------------------------------------------*/ <|start_filename|>src/ssx/ppc32/ppc32.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc32/ppc32.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC32_H__ #define __PPC32_H__ /// \file ppc32.h /// \brief Generic 32-bit PowerPC header for SSX /// /// The synchronization macros defined here all create a compiler /// memory barrier that will cause GCC to flush/invalidate all memory data /// held in registers before the macro. This is consistent with other systems, /// e.g., the PowerPC Linux kernel, and is the safest way to define these /// macros. #include "ppc32_asm.h" #include "ppc32_gcc.h" // Condition register fields #define CR_LT(n) (0x80000000u >> (4 * (n))) #define CR_GT(n) (0x40000000u >> (4 * (n))) #define CR_EQ(n) (0x20000000u >> (4 * (n))) #define CR_SO(n) (0x10000000u >> (4 * (n))) #ifndef __ASSEMBLER__ #include "stdint.h" /// ssize_t is defined explictly rather than bringing in all of <unistd.h> #ifndef __ssize_t_defined #define __ssize_t_defined typedef int ssize_t; #endif /// A memory barrier #define barrier() asm volatile ("" : : : "memory") /// Ensure In-order Execution of Input/Output #define eieio() asm volatile ("eieio" : : : "memory") /// Memory barrier #define sync() asm volatile ("sync" : : : "memory") /// Instruction barrier #define isync() asm volatile ("isync" : : : "memory") /// CouNT Leading Zeros Word #define cntlzw(x) \ ({uint32_t __x = (x); \ uint32_t __lzw; \ asm volatile ("cntlzw %0, %1" : "=r" (__lzw) : "r" (__x)); \ __lzw;}) /// CouNT Leading Zeros : uint32_t static inline int cntlz32(uint32_t x) { return cntlzw(x); } /// CouNT Leading Zeros : uint64_t static inline int cntlz64(uint64_t x) { if (x > 0xffffffff) { return cntlz32(x >> 32); } else { return 32 + cntlz32(x); } } /// 32-bit population count static inline int popcount32(uint32_t x) { return __builtin_popcount(x); } /// 64-bit population count static inline int popcount64(uint64_t x) { return __builtin_popcountll(x); } // NB: Normally we wouldn't like to force coercion inside a macro because it // can mask programming errors, but for the MMIO macros the addresses are // typically manifest constants or 32-bit unsigned integer expressions so we // embed the coercion to avoid warnings. /// 8-bit MMIO Write #define out8(addr, data) \ do {*(volatile uint8_t *)(addr) = (data); eieio();} while(0) /// 8-bit MMIO Read #define in8(addr) \ ({uint8_t __data = *(volatile uint8_t *)(addr); eieio(); __data;}) /// 16-bit MMIO Write #define out16(addr, data) \ do {*(volatile uint16_t *)(addr) = (data); eieio();} while(0) /// 16-bit MMIO Read #define in16(addr) \ ({uint16_t __data = *(volatile uint16_t *)(addr); eieio(); __data;}) /// 32-bit MMIO Write #define out32(addr, data) \ do {*(volatile uint32_t *)(addr) = (data); eieio();} while(0) /// 32-bit MMIO Read #define in32(addr) \ ({uint32_t __data = *(volatile uint32_t *)(addr); eieio(); __data;}) /// 64-bit MMIO Write #define out64(addr, data) \ do { \ uint64_t __data = (data); \ volatile uint32_t *__addr_hi = (uint32_t *)(addr); \ volatile uint32_t *__addr_lo = __addr_hi + 1; \ *__addr_hi = (__data >> 32); \ eieio(); \ *__addr_lo = (__data & 0xffffffff); \ eieio(); \ } while(0) /// 64-bit MMIO Read #define in64(addr) \ ({ \ uint64_t __data; \ volatile uint32_t *__addr_hi = (uint32_t *)(addr); \ volatile uint32_t *__addr_lo = __addr_hi + 1; \ __data = *__addr_hi; \ eieio(); \ __data = (__data << 32) | *__addr_lo; \ eieio(); \ __data;}) #endif /* __ASSEMBLER__ */ #ifndef __ASSEMBLER__ /// Store revision information as a (global) string constant #define REVISION_STRING(symbol, rev) const char* symbol = rev; #else // __ASSEMBLER__ /// Store revision information as a global string constant // *INDENT-OFF* .macro .revision_string, symbol:req, rev:req .pushsection .rodata .balign 4 .global \symbol \symbol\(): .asciz "\rev" .balign 4 .popsection .endm // *INDENT-ON* #endif // __ASSEMBLER__ #endif /* __PPC32_H__ */ <|start_filename|>src/occ_405/arl_test_data.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/arl_test_data.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _arl_test_data_h #define _arl_test_data_h // Uncomment this to enable the ARL Test Code compile flag. //#define AMEC_ARL_TEST_COMPILE 1 #ifdef AMEC_ARL_TEST_COMPILE typedef uint32_t UINT32; typedef uint16_t UINT16; typedef uint8_t UINT8; #define MAX_THREADS 8 // Definitions of SCOM_ARRAY offsets // The following is an offset into a 32 bit array that contains the SCOM values read by the OCC // Later, the order will likely change to reflect the order in which the SCOMs are written into local OCC memory // by the GUPI program that is reading them from the physical SCOM registers and depositing them into OCC memory. #define INDEX_PC_RUN_T0 0 #define INDEX_PC_RUN_T1 1 #define INDEX_PC_RUN_T2 2 #define INDEX_PC_RUN_T3 3 #define INDEX_PC_RUN_T4 4 #define INDEX_PC_RUN_T5 5 #define INDEX_PC_RUN_T6 6 #define INDEX_PC_RUN_T7 7 #define INDEX_PC_RAW 8 #define MAX_INDICES 9 // equal to the total number of SCOM_ARRAY entries #define CYCLES_INC 1000000 // cycles increment: corresponds to the # of core cycles every 250usec (currently set to correspond to 4GHz core) #define AME_SM_TICKS 8 // Basic state machine modulo 8 (8*250usec = 2msec) typedef struct { UINT32 r_cnt; // 32 bit time stamp counting interrupt ticks UINT32 SCOM_ARRAY[MAX_INDICES]; // Array of SCOM values (32 bits each) read by the GUPI program and placed into OCC SRAM UINT8 AME_sm_cnt; // Underlying AME state machine counter (modulo 8) } sOCCData_t; typedef struct { UINT32 cycles250us; // base cycle counter counting each tick of the core's clock UINT32 cycles250usincrement; // amount to increment base cycles by every 250usec UINT32 cycles2ms; // computes cycles every 2msec using PC_RAW SCOM register UINT32 scom_prev_PC_RAW_250us; // Remembers previous SCOM value for PC_RAW SCOM register 250us ago UINT32 scom_prev_PC_RAW_2ms; // Remembers previous SCOM value for PC_RAW SCOM register 2msec ago UINT32 scom_prev_thread[MAX_THREADS];// Remembers previous SCOM value for each thread UINT32 utilcounter[MAX_THREADS]; // base counter for synthesizing per thread utilization (value written to SCOMs every 250usec) UINT32 utilincrement[MAX_THREADS]; // increment for synthesizing per thread utilization (cycles per 250usec with run latch on) UINT16 util2ms_thread[MAX_THREADS]; // array of utilization sensors for P0 Core 0 (0.01% increments) UINT16 FREQREQC0; // requested actual frequency sensor for P0 Core 0 (1MHz increments) } sRTLData_t; extern sOCCData_t gOCC; extern sRTLData_t gRTL; extern sOCCData_t * gpOCC; extern sRTLData_t * gpRTL; #endif #endif //_arl_test_data_h <|start_filename|>src/ssx/occhw/occhw_irq_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_irq_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_irq_init.c /// \brief OCCHW IRQ initialization code for SSX /// /// The entry points in this file are initialization rotines that could be /// eliminated/deallocated by the application to free up storage if they are /// no longer needed after initialization. #include "ssx.h" /// Define the polarity and trigger condition for an interrupt. /// /// It is up to the application to take care of any side effects that may /// occur from programming or reprogramming the interrupt controller. For /// example, changing edge/level sensitivity or active level may set or clear /// interrupt status in the controller. /// /// Note that SSX allows this API to be called from any context, and changes /// to the interrupt controller are made from an SSX_CRITICAL critical /// section. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_IRQ_SETUP One or more arguments are invalid, /// including an invalid \a irq, or invalid \a polarity or \a trigger parameters. int ssx_irq_setup(SsxIrqId irq, int polarity, int trigger) { SsxMachineContext ctx; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(!OCCHW_IRQ_VALID(irq) || !OCCHW_IRQ_OWNED(irq) || !((polarity == SSX_IRQ_POLARITY_ACTIVE_HIGH) || (polarity == SSX_IRQ_POLARITY_ACTIVE_LOW)) || !((trigger == SSX_IRQ_TRIGGER_LEVEL_SENSITIVE) || (trigger == SSX_IRQ_TRIGGER_EDGE_SENSITIVE)), SSX_INVALID_ARGUMENT_IRQ_SETUP); } ssx_critical_section_enter(SSX_CRITICAL, &ctx); if (polarity == SSX_IRQ_POLARITY_ACTIVE_HIGH) { out32(OCCHW_OIEPR_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OIEPR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } if (trigger == SSX_IRQ_TRIGGER_EDGE_SENSITIVE) { out32(OCCHW_OITR_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OITR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } ssx_critical_section_exit(&ctx); return SSX_OK; } /// (Re)define the IRQ handler and priority for an interrupt. /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// Note that SSX allows this API to be called from any context, and changes /// to the interrupt controller are made from an SSX_CRITICAL critical /// section. /// /// \retval 0 Successful completion /// /// \retval -SSX_INVALID_ARGUMENT_IRQ_HANDLER One or more arguments are /// invalid, including an invalid \a irq, a null (0) \a handler, /// or invalid \a priority. int ssx_irq_handler_set(SsxIrqId irq, SsxIrqHandler handler, void* arg, int priority) { SsxMachineContext ctx; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(!OCCHW_IRQ_VALID(irq) || !OCCHW_IRQ_OWNED(irq) || (handler == 0) || !((priority == SSX_NONCRITICAL) || (priority == SSX_CRITICAL)), SSX_INVALID_ARGUMENT_IRQ_HANDLER); } ssx_critical_section_enter(SSX_CRITICAL, &ctx); //Regardless of priority, OIRRA & OIRRB will be cleared out32(OCCHW_OIRRA_CLR(irq), OCCHW_IRQ_MASK32(irq)); out32(OCCHW_OIRRB_CLR(irq), OCCHW_IRQ_MASK32(irq)); //Critical priority needs a 1 in OIRRC if (priority == SSX_CRITICAL) { out32(OCCHW_OIRRC_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OIRRC_CLR(irq), OCCHW_IRQ_MASK32(irq)); } __ppc405_irq_handlers[irq].handler = handler; __ppc405_irq_handlers[irq].arg = arg; ssx_critical_section_exit(&ctx); return SSX_OK; } /// Set or clear interrupt debug mode explicitly. void ssx_irq_debug_set(SsxIrqId irq, int value) { SsxMachineContext ctx; //uint32_t ouder; ssx_critical_section_enter(SSX_CRITICAL, &ctx); //TODO: port this over to using the OIRR instead of the OUDER //ouder = in32(OCCHW_OUDER(irq)); if (value) { //out32(OCCHW_OUDER(irq), ouder | OCCHW_IRQ_MASK32(irq)); } else { //out32(OCCHW_OUDER(irq), ouder & ~OCCHW_IRQ_MASK32(irq)); } ssx_critical_section_exit(&ctx); } <|start_filename|>src/lib/ppc405lib/stdlib.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/stdlib.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file stdlib.c /// \brief Functions from <stdlib.h> /// /// \note The strtoX() APIs are defined in strtox.[ch] #include "ssx.h" #include "ctype.h" #include "libssx.h" #include <stdlib.h> /// Convert a string to a long integer - base 10 only /// /// atol(str) is defined here as strtol(str, 0, 10) in sympathy with the POSIX /// standard. Note that by specification "atol() does not detect /// errors", however here it will behave the same as the strtol() call just /// mentioned. long atol(const char *str) { return strtol(str, 0, 10); } /// Convert a string to an integer - base 10 only /// /// atoi(str) is defined here as strtol(str, 0, 10) in sympathy with the POSIX /// standard. Note that by specification "atoi() does not detect errors", /// however in this implementation the long integer returned by the strtol() /// call just mentioned is simply converted to an int. int atoi(const char *str) { return strtol(str, 0, 10); } /// 'Exit' an application /// /// An SSX application can not really 'exit'. By convention, exit(0) is the /// same as ssx_halt(). Calling exit() with a non-zero code causes a kernel /// panic - the exit code will be found in R3 on PowerPC. /// /// Note that to exit a thread, the thread can either return from the thread /// entry routine or explicitly call ssx_complete(). exit() was implemented /// to allow porting of the EEMBC benchmarks. void exit(int status) { if (status) { SSX_PANIC(ERROR_EXIT); } ssx_halt(); } /// Compute the absolute value of the integer argument int abs(int i) { return ((i < 0) ? -i : i); } /// Compute the absolute value of the long integer argument long int labs(long int i) { return ((i < 0) ? -i : i); } /// Compute the absolute value of the long long integer argument long long int llabs(long long int i) { return ((i < 0) ? -i : i); } <|start_filename|>src/occ_405/ssx_app_cfg.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/ssx_app_cfg.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SSX_APP_CFG_H__ #define __SSX_APP_CFG_H__ /// \file ssx_app_cfg.h /// \brief Application specific overrides go here. /// #include "global_app_cfg.h" // These versions of SSX_PANIC are being changed so that they exactly // mirror each other and are exactly structured at 8 instructions only and // make only one branch to outside code. #ifndef __ASSEMBLER__ #ifndef SSX_PANIC #define SSX_PANIC(code) \ do { \ barrier(); \ asm volatile ("stw %r3, __occ_panic_save_r3@sda21(0)"); \ asm volatile ("mflr %r3"); \ asm volatile ("stw %r4, __occ_panic_save_r4@sda21(0)"); \ asm volatile ("lis %%r4, %0"::"i" (code >> 16)); \ asm volatile ("ori %%r4, %%r4, %0"::"i" (code & 0xffff)); \ asm volatile ("bl __ssx_checkpoint_panic_and_save_ffdc"); \ asm volatile ("trap"); \ asm volatile (".long %0" : : "i" (code)); \ } while (0) #endif // SSX_PANIC #else /* __ASSEMBLER__ */ #ifndef SSX_PANIC // This macro cannot be more than 8 instructions long, but it can be less than // 8. #define SSX_PANIC(code) _ssx_panic code .macro _ssx_panic, code stw %r3, __occ_panic_save_r3@sda21(0) mflr %r3 stw %r4, __occ_panic_save_r4@sda21(0) lis %r4, \code@h ori %r4, %r4, \code@l bl __ssx_checkpoint_panic_and_save_ffdc trap .long \code .endm #endif // SSX_PANIC #endif /* __ASSEMBLER__ */ /// Static configuration data for external interrupts: /// /// IRQ#, TYPE, POLARITY, ENABLE /// #define APPCFG_EXT_IRQS_CONFIG \ OCCHW_IRQ_GPE0_HALT OCCHW_IRQ_TYPE_LEVEL OCCHW_IRQ_POLARITY_HI OCCHW_IRQ_MASKED \ OCCHW_IRQ_GPE1_HALT OCCHW_IRQ_TYPE_LEVEL OCCHW_IRQ_POLARITY_HI OCCHW_IRQ_MASKED \ OCCHW_IRQ_PPC405_HALT OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_CHECK_STOP_PPC405 OCCHW_IRQ_TYPE_LEVEL OCCHW_IRQ_POLARITY_HI OCCHW_IRQ_MASKED \ OCCHW_IRQ_OCB_ERROR OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_SPIPSS_ERROR OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_EXTERNAL_TRAP OCCHW_IRQ_TYPE_LEVEL OCCHW_IRQ_POLARITY_HI OCCHW_IRQ_MASKED \ OCCHW_IRQ_OCC_TIMER0 OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_OCC_TIMER1 OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_IPI4_HI_PRIORITY OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_PBAX_OCC_SEND OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_PBAX_OCC_PUSH0 OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_PBAX_OCC_PUSH1 OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_PBA_BCDE_ATTN OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_PBA_BCUE_ATTN OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM0_PULL OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM0_PUSH OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM1_PULL OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM1_PUSH OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM2_PULL OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM2_PUSH OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM3_PULL OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_STRM3_PUSH OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ OCCHW_IRQ_IPI4_LO_PRIORITY OCCHW_IRQ_TYPE_EDGE OCCHW_IRQ_POLARITY_RISING OCCHW_IRQ_MASKED \ /// The Instance ID of the occ processor that this application is intended to run on /// 0-3 -> GPE, 4 -> 405 #define APPCFG_OCC_INSTANCE_ID 4 // Common configuration groups for verification. Bypass time-consuming setup // or setup done by procedures for simulation environments, and set up special // I/O configurations for simulation environments. #ifndef VERIFICATION #define VERIFICATION 0 #endif #ifndef OCC_UNIT_VERIFICATION #define OCC_UNIT_VERIFICATION 0 #endif #ifndef EPM_VERIFICATION #define EPM_VERIFICATION 0 #endif #ifndef VBU_VERIFICATION #define VBU_VERIFICATION 0 #endif #ifndef LAB_VALIDATION #define LAB_VALIDATION 0 #endif #if VERIFICATION || LAB_VALIDATION #if !LAB_VALIDATION #define SSX_STACK_CHECK 0 #endif #define SIMICS_ENVIRONMENT 0 #else #define INITIALIZE_PBA_SLAVES 1 #define INITIALIZE_PBA_BARS 1 #endif /* VERIFICATION */ #if OCC_UNIT_VERIFICATION #define USE_RTX_IO 1 #endif #if EPM_VERIFICATION #define USE_EPM_IO 1 #endif // VBU and the lab use trace buffer I/O. The DBCR0 is left untouched so VBU // can use instruction/data breakpoints. #if VBU_VERIFICATION || LAB_VALIDATION #define USE_TRACE_IO 1 #define NO_INIT_DBCR0 1 #endif // Default initializations for validation that affect SSX and library code #define PROCESSOR_EC_LEVEL #ifndef SIMICS_ENVIRONMENT #define SIMICS_ENVIRONMENT 0 #endif #if SIMICS_ENVIRONMENT #pragma message "Building for Simics!" #ifndef USE_SIMICS_IO #define USE_SIMICS_IO 1 #endif #endif #ifndef USE_SIMICS_IO #define USE_SIMICS_IO 0 #endif #ifndef USE_RTX_IO #define USE_RTX_IO 0 #endif #ifndef USE_TRACE_IO #define USE_TRACE_IO 0 #endif #ifndef USE_EPM_IO #define USE_EPM_IO 0 #endif /// The buffer used for 'ssxout' in VBU and lab applications /// /// The buffer is defined to be quite large in order to accomodate full kernel /// and application dumps in the event of problems. #ifndef SSXOUT_TRACE_BUFFER_SIZE #define SSXOUT_TRACE_BUFFER_SIZE (8 * 1024) #endif #ifndef APPCFG_USE_EXT_TIMEBASE_FOR_TRACE #define APPCFG_USE_EXT_TIMEBASE_FOR_TRACE 1 #endif #ifndef PPC405_TIMEBASE_HZ #define PPC405_TIMEBASE_HZ DEFAULT_NEST_FREQ_HZ #endif //If we are using the external timebase for traces, assume it is 37500000 Hz. //Otherwise, it will use the PPC405 timebase. #if APPCFG_USE_EXT_TIMEBASE_FOR_TRACE #define SSX_TRACE_TIMEBASE_HZ DEFAULT_EXT_CLK_FREQ_HZ #else #define SSX_TRACE_TIMEBASE_HZ __ssx_timebase_frequency_hz #endif /* APPCFG_USE_EXT_TIMEBASE_FOR_TRACE */ #if SSX_USE_INIT_SECTION #define INIT_SEC_NM_STR "initSection" #define INIT_SECTION __attribute__ ((section (INIT_SEC_NM_STR))) #else #define INIT_SECTION #endif #endif /*__SSX_APP_CFG_H__*/ <|start_filename|>src/ssx/ppc405/ppc405_irq_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_irq_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppc405_irq_core.c /// \brief Core IRQ routines required of any PPC405 configuration of SSX /// /// This file is mostly only a placeholder - where 'extern inline' API /// functions and 'extern' variables are realized. A couple of default /// handlers are also installed here. The entry points in this file are /// considered 'core' routines that will always be present at runtime in any /// SSX application. #define __PPC405_IRQ_CORE_C__ #include "ssx.h" /// This function is installed by default for interrupts not explicitly set up /// by the application. These interrupts should never fire. void __ppc405_default_irq_handler(void* arg, SsxIrqId irq, int critical) { SSX_PANIC(PPC405_DEFAULT_IRQ_HANDLER); } /// This function is installed by default to handle the case that the /// interrupt dispatch code is entered in response to an external critical or /// non-critical interrupt, but no interrupt is found pending in the interrupt /// controller. This should never happen, as it would indicate that a /// 'glitch' occurred on the external noncritical or critical interrupt input /// to the PPC405 core. void __ppc405_phantom_irq_handler(void* arg, SsxIrqId irq, int critical) { SSX_PANIC(PPC405_PHANTOM_INTERRUPT); } #undef __PPC405_IRQ_CORE_C__ <|start_filename|>src/occ_405/rtls/test/rtls_tables.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/rtls/test/rtls_tables.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "rtls.h" // Default task data buffers uint32_t task_0_data = 0x00000000; uint32_t task_1_data = 0x00000000; uint32_t task_2_data = 0x00000000; uint32_t task_3_data = 0x00000000; // Alternate task data buffers uint32_t task_0_alt_data = 0x00000000; uint32_t task_1_alt_data = 0x00000000; uint32_t task_2_alt_data = 0x00000000; uint32_t task_3_alt_data = 0x00000000; #define TASK_ID_0 0 #define TASK_ID_1 1 #define TASK_ID_2 2 #define TASK_ID_3 3 #define TASK_ID_END 4 // Test tick sequences // For testing, run every task on every tick, but vary the order. uint8_t G_tick0_seq[TASK_END + 1] = { TASK_ID_0, TASK_ID_1, TASK_ID_2, TASK_ID_3, TASK_END }; uint8_t G_tick1_seq[TASK_END + 1] = { TASK_ID_1, TASK_ID_2, TASK_ID_3, TASK_ID_0, TASK_END }; uint8_t G_tick2_seq[TASK_END + 1] = { TASK_ID_2, TASK_ID_3, TASK_ID_0, TASK_ID_1, TASK_END }; uint8_t G_tick3_seq[TASK_END + 1] = { TASK_ID_3, TASK_ID_0, TASK_ID_1, TASK_ID_2, TASK_END }; uint8_t G_tick4_seq[TASK_END + 1] = { TASK_ID_3, TASK_ID_2, TASK_ID_1, TASK_ID_0, TASK_END }; uint8_t G_tick5_seq[TASK_END + 1] = { TASK_ID_2, TASK_ID_1, TASK_ID_0, TASK_ID_3, TASK_END }; uint8_t G_tick6_seq[TASK_END + 1] = { TASK_ID_1, TASK_ID_0, TASK_ID_3, TASK_ID_2, TASK_END }; uint8_t G_tick7_seq[TASK_END + 1] = { TASK_ID_0, TASK_ID_3, TASK_ID_2, TASK_ID_1, TASK_END }; /* Tick Table */ uint8_t *G_tick_table[MAX_NUM_TICKS] = { G_tick0_seq, G_tick1_seq, G_tick2_seq, G_tick3_seq, G_tick4_seq, G_tick5_seq, G_tick6_seq, G_tick7_seq }; // Example Task Table // Use task_id_t values to index into this table and find a specific task. task_t G_task_table[TASK_END] = { // flags, func_ptr, data_ptr, task_id_t { 0x00000000, task_0_func, (void *)&task_0_data }, // TASK_ID_0 { 0x00000000, task_1_func, (void *)&task_1_data }, // TASK_ID_1 { 0x00000000, task_2_func, (void *)&task_2_data }, // TASK_ID_2 { 0x00000000, task_3_func, (void *)&task_3_data } // TASK_ID_3 }; void task_0_func(struct task *); void task_1_func(struct task *); void task_2_func(struct task *); void task_3_func(struct task *); // Function Specification // // Name: task_0_func // // Description: Example task 0 // // End Function Specification void task_0_func(struct task *i_self) { uint8_t curr_tick = (uint8_t)((MAX_NUM_TICKS - 1) & CURRENT_TICK); // If our task pointer & it's data pointer are valid, set a bit // in the data area indicating which tick this function ran during. if ( i_self && i_self -> data_ptr ) { *((uint32_t *)(i_self -> data_ptr)) |= (0x00000001 << curr_tick); } return; } // Function Specification // // Name: task_1_func // // Description: Example task 1 // // End Function Specification void task_1_func(struct task *i_self) { uint8_t curr_tick = (uint8_t)((MAX_NUM_TICKS - 1) & CURRENT_TICK); // If our task pointer & it's data pointer are valid, set a bit // in the data area indicating which tick this function ran during. if ( i_self && i_self -> data_ptr ) { *((uint32_t *)(i_self -> data_ptr)) |= (0x00000001 << curr_tick); } return; } // Function Specification // // Name: task_2_func // // Description: Example task 2 // // End Function Specification void task_2_func(struct task *i_self) { uint8_t curr_tick = (uint8_t)((MAX_NUM_TICKS - 1) & CURRENT_TICK); // If our task pointer & it's data pointer are valid, set a bit // in the data area indicating which tick this function ran during. if ( i_self && i_self -> data_ptr ) { *((uint32_t *)(i_self -> data_ptr)) |= (0x00000001 << curr_tick); } return; } // Function Specification // // Name: task_3_func // // Description: Example task 3 // // End Function Specification void task_3_func(struct task *i_self) { uint8_t curr_tick = (uint8_t)((MAX_NUM_TICKS - 1) & CURRENT_TICK); // If our task pointer & it's data pointer are valid, set a bit // in the data area indicating which tick this function ran during. if ( i_self && i_self -> data_ptr ) { *((uint32_t *)(i_self -> data_ptr)) |= (0x00000001 << curr_tick); } return; } <|start_filename|>src/occ_gpe1/nop.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/nop.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" #include "ppe42_scom.h" #include "gpe_export.h" #include "ipc_api.h" #include "ipc_async_cmd.h" #include "gpe_util.h" /* * Function Specification: * * Name: gpe1_nop * * Description: a function that does nothing. Called to measure IPC timing * * Inputs: none * * return: none * * End Function Specification */ void gpe1_nop(ipc_msg_t* cmd, void* arg) { int rc; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; nop_t *args = (nop_t*)async_cmd->cmd_data; // send back a response, IPC success even if ffdc/rc are non zeros rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("gpe1_nop: Failed to send response back. Halting GPE1", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } } <|start_filename|>src/occBootLoader/bootMain.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occBootLoader/bootMain.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _bootMain_h #define _bootMain_h //*************************************************************************/ // Includes //*************************************************************************/ #ifndef __ASSEMBLER__ #include <common_types.h> // defines imageHdr_t and other types #endif /* __ASSEMBLER__ */ //*************************************************************************/ // Externs //*************************************************************************/ //*************************************************************************/ // Macros //*************************************************************************/ //*************************************************************************/ // Defines/Enums //*************************************************************************/ #define MACHINE_CHECK_ENABLE 0x00001000 #define DATA_CACHE_BLOCK_ENABLE 0x80000000 #define DATA_CACHE_BLOCK_ADDR 0x00000000 #define DATA_CACHE_SIZE (16 * 1024) #define CACHE_LINE_SIZE 32 #define DATA_CACHE_LINES (DATA_CACHE_SIZE/CACHE_LINE_SIZE) // Data cache address + 8K #define STACK_POINTER_ADDR (DATA_CACHE_BLOCK_ADDR + 0x2000) #ifndef __ASSEMBLER__ typedef enum CHKPOINT { BOOT_TEST_SRAM_CHKPOINT = 0x00000001, BOOT_LOAD_IMAGE_CHKPOINT = 0x00000002, BOOT_LOAD_GPE0_CHKPOINT = 0x00000003, BOOT_LOAD_GPE1_CHKPOINT = 0x00000004, BOOT_CALCULTE_CHKSUM_CHKPOINT_405 = 0x00000005, BOOT_CALCULTE_CHKSUM_CHKPOINT_GPE0 = 0x00000006, BOOT_CALCULTE_CHKSUM_CHKPOINT_GPE1 = 0x00000007, BOOT_GET_NEST_FREQ_CHKPOINT = 0x00000008, BOOT_SSX_BOOT_CALL_CHKPOINT = 0x00000009, BOOT_SSX_RETURNED_CHKPOINT = 0x0000000A }CHKPOINT; #endif /* __ASSEMBLER__ */ #define SRAM_TEST_START_ADDRESS 0xFFF00000 #define SRAM_START_ADDRESS_FULL 0xFFF00000 #define SRAM_START_ADDRESS_405 0xFFF40000 #define SRAM_START_ADDRESS_GPE0 0xFFF01000 #define SRAM_START_ADDRESS_GPE1 0xFFF10000 #define SRAM_TEST_END_ADDRESS 0xFFFBFFFF #define SRAM_END_ADDRESS_405 0xFFFBFFFF #define SRAM_END_ADDRESS_GPE0 0xFFF0FFFF #define SRAM_END_ADDRESS_GPE1 0xFFF1FFFF #define SRAM_TEST_BIT_PATTERN 0xA5A5A5A5 #define EYE_CATCHER_ADDRESS 0x1234ABCD #define BOOT_LOADER_ID "OCC Boot Image\0" // Define to write val to SPRG0 register #define WRITE_TO_SPRG0(val) \ ({__asm__ __volatile__ ("mtsprg0 %0;" ::"r"(val));}) #define WRITE_TO_SPRG1_AND_HALT(rc) \ ({__asm__ __volatile__ ("mtsprg1 %0;" "tw 31,0,0;": : "r" (rc));}) //*************************************************************************/ // Structures //*************************************************************************/ //*************************************************************************/ // Globals //*************************************************************************/ //*************************************************************************/ // Function Prototypes //*************************************************************************/ //*************************************************************************/ // Functions //*************************************************************************/ #endif // _bootMain_h <|start_filename|>src/ppe/pk/std/std_irq.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/std/std_irq.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __STD_IRQ_H__ #define __STD_IRQ_H__ /// \file occhw_irq.h /// \brief Standard PPE Externnal Interrupt handling for PK /// /// The standard PPE interrupt controller supports a maximum of 64 interrupts with /// simple OR combining of the interrupt signals. /// /// The standard PPE interrupt controller allows interrupt status to be set directly by /// software. It contains a 'mask' register, unlike most 405 interrupt /// controllers that have an 'enable' register. The standard PPE mask and status /// registers also have atomic CLR/OR function so that it is never necessary /// to enter a critical section to enable/disable/clear interrupts and /// interrupt status. #include "std_common.h" #include "std_register_addresses.h" #include "ppe42.h" #ifndef __ASSEMBLER__ /// Enable an interrupt by clearing the mask bit. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_enable(PkIrqId irq) { out64(STD_LCL_EIMR_CLR, STD_IRQ_MASK64(irq)); } /// Enable a vector of interrupts by clearing the mask bits. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_enable(uint64_t irq_vec_mask) { out64(STD_LCL_EIMR_CLR, irq_vec_mask); } /// Disable an interrupt by setting the mask bit. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_disable(PkIrqId irq) { out64(STD_LCL_EIMR_OR, STD_IRQ_MASK64(irq)); } /// Disable a vector of interrupts by setting the mask bits. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_disable(uint64_t irq_vec_mask) { out64(STD_LCL_EIMR_OR, irq_vec_mask); } /// Clear interrupt status with an CLR mask. Only meaningful for /// edge-triggered interrupts. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_status_clear(PkIrqId irq) { out64(STD_LCL_EISR_CLR, STD_IRQ_MASK64(irq)); } /// Clear a vector of interrupts status with an CLR mask. Only meaningful for /// edge-triggered interrupts. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_status_clear(uint64_t irq_vec_mask) { out64(STD_LCL_EISR_CLR, irq_vec_mask); } /// Get IRQ status as a 0 or non-0 integer UNLESS__PPE42_IRQ_CORE_C__(extern) inline int pk_irq_status_get(PkIrqId irq) { return (in64(STD_LCL_EISR) & STD_IRQ_MASK64(irq)) != 0; } /// Set or clear interrupt status explicitly. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_status_set(PkIrqId irq, int value) { if (value) { out64(STD_LCL_EISR_OR, STD_IRQ_MASK64(irq)); } else { out64(STD_LCL_EISR_CLR, STD_IRQ_MASK64(irq)); } } #endif /* __ASSEMBLER__ */ #endif /* __STD_IRQ_H__ */ <|start_filename|>src/occ_gpe1/gpe1_memory_power_control.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe1/gpe1_memory_power_control.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _GPE1_MEMORY_POWER_CONTROL_H #define _GPE1_MEMORY_POWER_CONTROL_H #define PCR0_MASTER_ENABLE_BIT 2 #define PCR0_POWERDOWN_ENABLE_BIT 22 #define STR0_STR_ENABLE_BIT 0 #define STR0_DISABLE_MEMORY_CLOCKS_BIT 1 // Big Endian set/clear bit MACROS #define SET_BIT(var, bit) (var | (0x8000000000000000 >> bit) ) #define CLR_BIT(var, bit) (var & ~(0x8000000000000000 >> bit) ) // Big Endian set/clear 2 different bits MACROS #define SET_2BITS(var, bit1, bit2) SET_BIT(SET_BIT(var, bit1), bit2) #define CLR_2BITS(var, bit1, bit2) CLR_BIT(CLR_BIT(var, bit1), bit2) #endif // _GPE1_MEMORY_POWER_CONTROL_H <|start_filename|>src/occ_405/amec/amec_sensors_core.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_sensors_core.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_SENSORS_CORE_H #define _AMEC_SENSORS_CORE_H /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include "amec_external.h" #include <occ_sys_config.h> /*----------------------------------------------------------------------------*/ /* Defines/Constants */ /*----------------------------------------------------------------------------*/ // See bit definition of OCC Stop State History Register #define OCC_CORE_STOP_GATED 0x80000000 // Set upon entry stop entry transition (or initial power on) // Not cleared until core is fully accessible #define OCC_CORE_SWUP_DONE 0x40000000 // Special wake-up done #define OCC_CORE_ACT_STOP_LVL 0x00F00000 // Actual stop level (probably changes too fast to be useful) // The following clear upon reading #define OCC_DEEPEST_REQ_STOP_LVL 0x000F0000 // Deepest requested stop level #define OCC_DEEPEST_ACT_STOP_LVL 0x0000F000 // Deepest stop state fully entered #define OCC_IVRM_ENABLED_HIST 0x00000800 // Bit indicating if IVRM has been enabled /*----------------------------------------------------------------------------*/ /* Structures */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Function Declarations */ /*----------------------------------------------------------------------------*/ void amec_update_proc_core_sensors(uint8_t i_core); #endif // _AMEC_SENSORS_CORE_H <|start_filename|>src/occ_405/cmdh/cmdh_snapshot.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_snapshot.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef CMDH_SNAPSHOT_H #define CMDH_SNAPSHOT_H #include "cmdh_fsp_cmds.h" /* snapshot buffer timer */ extern SsxTimer G_snapshotTimer; // Struct used to parse get snapshot buffer request Command typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; // Standard TMGT uint8_t version; // Get snapshot request Version uint8_t reserved; // Reserved. uint8_t requested_id; // ID of snapshot buffer to be returned. uint8_t getnewest; // 0x01 => return newest snapshot, 0x00 => return snapshot of ID given. }cmdh_get_snapshot_query_t; #define CMDH_GET_SNAPSHOT_NONITE_VERSION 0 #define CMDH_GET_SNAPSHOT_ITE_VERSION 1 #define CMDH_GET_SNAPSHOT_QUERY_DATALEN sizeof(cmdh_get_snapshot_query_t) - sizeof(cmdh_fsp_cmd_header_t) #define CMDH_SNAPSHOT_MAX 6 #define CMDH_CIMP_MAX 20 #define CMDH_SNAPSHOT_DEFAULT_CUR_INDEX 0xFF //Default value of g_cmdh_snapshot_cur_index #define CMDH_SNAPSHOT_MAX_INDEX (CMDH_SNAPSHOT_MAX - 1) #define CMDH_SNAPSHOT_SYNC_VERSION 0 // Used by OCC to store sequenced snapshot entries. 16 bytes each typedef struct __attribute__ ((packed)) { uint8_t seq_number; //Snapshot Sequence number; 30 second time slice. uint8_t avg_dc[4]; //Average total node DC power in milliwatts. uint8_t max_dc[4]; //Maximum total node DC power in milliwatts. uint8_t min_dc[4]; //Minimum total node DC power in milliwatts. uint8_t avg_cpu_freq[2]; //Average Node CPU Frequency in MHz. uint8_t reserved; //reserved. }cmdh_snapshot_cimp_entry_t; // Contains all entries in a snapshot. typedef struct __attribute__ ((packed)) { uint8_t current_id; // Snapshot buffer ID number of buffer data to follow, typically this // should match id in request data, unless it's not available. cmdh_snapshot_cimp_entry_t cim[CMDH_CIMP_MAX]; // Data collected for cimp }cmdh_snapshot_buffer_t; // Used by OCC to respond to "GET_SNAPSHOT_BUFFER" nonite(version 0) cmd. 323 bytes typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; uint8_t oldest_id; // Oldest available snapshot buffer ID number uint8_t newest_id; // Newest available snapshot buffer ID number cmdh_snapshot_buffer_t snapshot; // Snapshot. uint8_t checksum[2]; // Checksum }cmdh_get_snapshot_resp_v0_t; // Used by OCC to respond to "SNAPSHOT_SYNC" cmd. typedef struct __attribute__ ((packed)) { struct cmdh_fsp_rsp_header; UINT8 checksum[2]; }cmdh_snapshot_sync_resp_t; // Structure of cmd packet received from tmgt. typedef struct __attribute__ ((packed)) { struct cmdh_fsp_cmd_header; // Standard TMGT UINT8 version; } cmdh_snapshot_sync_query_t; // Structure of data that need to be maintained between snapshots. typedef struct __attribute__ ((packed)) { uint32_t count; //Count of number of samples taken. uint16_t max; //Max value of pwr250us uint16_t min; //Min value of pwr250us uint32_t freqaAccum;//Accumulated AvgFreq over the past 30seconds. } pwr250us_over30sec_t; extern pwr250us_over30sec_t g_pwr250us_over30sec; errlHndl_t cmdh_get_snapshot_buffer(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * i_rsp_ptr); errlHndl_t cmdh_snapshot_sync(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * i_rsp_ptr); //Called by a timer that is triggered every 30seconds. void cmdh_snapshot_callback(void * arg); #endif <|start_filename|>src/occ_405/thread/test/Makefile<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/occ_405/thread/test/Makefile $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2011,2015 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG threadtest_CFILES = \ ../../common.c \ ../../errl/errl.c \ ../threadSch.c \ threadtest.c all_cfiles = ${threadtest_CFILES} APP = threadtest APP_INCLUDES += -I../../../ssx APP_INCLUDES += -I../../../lib APP_INCLUDES += -I../../incl APP_INCLUDES += -I../../trac APP_INCLUDES += -I../../errl APP_INCLUDES += -I../../thread APP_INCLUDES += -I../../aplt/incl APP_INCLUDES += -I. #D = -DVERIFICATION=1 \ -DSSX_STACK_CHECK=0 \ -DINITIALIZE_PMC=0 \ -DINITIALIZE_SIMICS_IO=0 \ -DINITIALIZE_RTX_IO=1 \ -DINITIALIZE_PBA=1 \ -DSIMICS_MAGIC_PANIC=1 \ -DSSX_KERNEL_TRACE_ENABLE=1 SOURCES = ${all_cfiles} MODE = validation PGP_ASYNC_SUPPORT = 1 include ./app.mk pgas: $(CC) $(CFLAGS) -c -Wa,-al -Wa,--listing-cont-lines='10' <|start_filename|>src/occ_405/cmdh/cmdh_snapshot.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/cmdh/cmdh_snapshot.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "cmdh_snapshot.h" #include "cmdh_service_codes.h" #include "cmdh_fsp_cmds.h" #include "dcom.h" #include "threadSch.h" // Array of snapshot buffers to return to TMGT cmdh_snapshot_buffer_t g_cmdh_snapshot_array[CMDH_SNAPSHOT_MAX]; // Current snapshot id. uint8_t g_cmdh_snapshot_cur_id = 0; // Current index into array for newest entry uint8_t g_cmdh_snapshot_cur_index = CMDH_SNAPSHOT_DEFAULT_CUR_INDEX; // This global is set to TRUE by default to get a clean start, and is also // set to TRUE in case of a resync request. bool g_cmdh_snapshot_reset = TRUE; SsxTimer G_snapshotTimer; // Max, min power, and accumulated frequency average over 30seconds pwr250us_over30sec_t g_pwr250us_over30sec; // Function Specification // // Name: cmdh_snapshot_find_oldest_newest // // Description: Returns the index of the oldest and newest snapshot in the // g_cmdh_snapshot_array. // // End Function Specification VOID cmdh_snapshot_find_oldest_newest(uint8_t *o_oldest, uint8_t *o_newest) { uint8_t l_index = 0; do { // We wont be called if no snapshots are available so we know at least // one is available // If our current index is 0, it's id is 0, and the last entry has // an id of 0 then we know we haven't wrapped yet since 2 entries // can not have the same current_id and 0 was what's written in // as an initializer if((g_cmdh_snapshot_cur_index == 0) && (g_cmdh_snapshot_array[0].current_id == 0) && (g_cmdh_snapshot_array[CMDH_SNAPSHOT_MAX_INDEX].current_id == 0)) { *o_oldest = 0; *o_newest = 0; break; } // Newest will be g_cmdh_snapshot_cur_index *o_newest = g_cmdh_snapshot_cur_index; // n = newest, o=oldest, x=used, _=empty //________________________________________ //|x|x|x|x|x|x|x|x|x|x|x|n|o|x|x|x|x|x|x|x| // Start by assuming that the oldest snapshot is right after the newest. l_index = g_cmdh_snapshot_cur_index+1; //________________________________________ //|o|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|n| //Check on whether the newest was at the end of the array. That would //mean that the oldest entry is at index 0. if(l_index > CMDH_SNAPSHOT_MAX_INDEX) { l_index = 0; } //________________________________________ //|o|x|x|x|x|x|x|x|x|x|x|n|_|_|_|_|_|_|_|_| //Check on whether the last entry in the array is empty and so is the one //right after the newest entry. If so, that means oldest is at index 0 since //we haven't wrapped yet. else if((g_cmdh_snapshot_array[l_index].current_id == 0) && (g_cmdh_snapshot_array[CMDH_SNAPSHOT_MAX_INDEX].current_id == 0)) { l_index = 0; } // else oldest is just equal to l_index *o_oldest = l_index; }while(FALSE); return; } // Function Specification // // Name: cmdh_snapshot_buffer_nonite // // Description: Returns the requested snapshot buffer to tmgt. // // End Function Specification ERRL_RC cmdh_snapshot_buffer_nonite(const cmdh_fsp_cmd_t *i_cmd_ptr, cmdh_fsp_rsp_t *o_rsp_ptr) { cmdh_get_snapshot_query_t *l_cmd_ptr = (cmdh_get_snapshot_query_t *) i_cmd_ptr; ERRL_RC l_rc = ERRL_RC_SUCCESS; cmdh_get_snapshot_resp_v0_t *l_rsp_ptr = (cmdh_get_snapshot_resp_v0_t*) o_rsp_ptr; uint8_t l_newest = 0; uint8_t l_oldest = 0; uint8_t l_req_idx = 0; uint8_t i = 0; do { // Check case where there are no snapshot buffers available. if (g_cmdh_snapshot_cur_index == CMDH_SNAPSHOT_DEFAULT_CUR_INDEX) { break; } // Determine newest and oldest buffer. cmdh_snapshot_find_oldest_newest(&l_oldest, &l_newest); l_rsp_ptr->oldest_id = g_cmdh_snapshot_array[l_oldest].current_id; l_rsp_ptr->newest_id = g_cmdh_snapshot_array[l_newest].current_id; // Determine which snapshot buffer is requested by TMGT if (l_cmd_ptr->getnewest) { l_req_idx = l_newest; } else { // Find requested snapshot, or if not available grab latest. for (i =0; i< CMDH_SNAPSHOT_MAX; i++) { if (g_cmdh_snapshot_array[i].current_id == l_cmd_ptr->requested_id) { l_req_idx = i; break; } } if (i == CMDH_SNAPSHOT_MAX) { l_req_idx = l_newest; } } // Copy the requested snapshot buffer into the response buffer. memcpy(&(l_rsp_ptr->snapshot), &(g_cmdh_snapshot_array[l_req_idx]), sizeof(cmdh_snapshot_buffer_t)); // Calculate returned data size. uint16_t l_size = 2 + sizeof(cmdh_snapshot_buffer_t); // 2 bytes for newest and oldest + size of snapshots. o_rsp_ptr->data_length[0] = ((uint8_t *)&l_size)[0]; o_rsp_ptr->data_length[1] = ((uint8_t *)&l_size)[1]; } while (0); return(l_rc); } // Function Specification // // Name: cmdh_get_snapshot_buffer // // Description: Returns requested snapshot buffer to tmgt when requested. // // End Function Specification errlHndl_t cmdh_get_snapshot_buffer(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { cmdh_get_snapshot_query_t *l_cmd_ptr = (cmdh_get_snapshot_query_t *) i_cmd_ptr; ERRL_RC l_rc = ERRL_RC_SUCCESS; uint16_t l_query_sz = 0; errlHndl_t l_err = NULL; do { // Command is only supported on Master OCC if (G_occ_role == OCC_SLAVE) { TRAC_ERR("cmdh_get_snapshot_buffer: Get snapshot buffer command not supported on Slave OCCs!"); l_rc = ERRL_RC_INVALID_CMD; break; } // Function Inputs Sanity Check if( (NULL == i_cmd_ptr) || (NULL == o_rsp_ptr) ) { TRAC_ERR("cmdh_get_snapshot_buffer: Received invalid inputs."); l_rc = ERRL_RC_INTERNAL_FAIL; break; } l_query_sz = CMDH_DATALEN_FIELD_UINT16(i_cmd_ptr); // Command Length Check. Should have 4 bytes total if(l_query_sz != CMDH_GET_SNAPSHOT_QUERY_DATALEN) { TRAC_ERR("cmdh_get_snapshot_buffer: Received an invalid packet size. Expecting 4 bytes, received:%i", l_query_sz); l_rc = ERRL_RC_INVALID_CMD_LEN; break; } // Call appropriate function based on version. switch (l_cmd_ptr->version) { case CMDH_GET_SNAPSHOT_NONITE_VERSION: l_rc = cmdh_snapshot_buffer_nonite(i_cmd_ptr, o_rsp_ptr); break; case CMDH_GET_SNAPSHOT_ITE_VERSION: default: TRAC_ERR("cmdh_get_snapshot_buffer: Version %i cmd is not supported.", l_cmd_ptr->version); l_rc = ERRL_RC_INVALID_DATA; break; } } while(0); if (l_rc) { // Build Error Response packet cmdh_build_errl_rsp(i_cmd_ptr, o_rsp_ptr, l_rc, &l_err); } return l_err; } #define CMDH_SNAPSHOT_SYNC_DATA_SIZE 1 // Function Specification // // Name: cmdh_snapshot_sync // // Description: Resets the snapshot buffer array and starts a new snapshot buffer from time 0. // // End Function Specification errlHndl_t cmdh_snapshot_sync(const cmdh_fsp_cmd_t * i_cmd_ptr, cmdh_fsp_rsp_t * o_rsp_ptr) { cmdh_snapshot_sync_query_t *l_cmd_ptr = (cmdh_snapshot_sync_query_t *) i_cmd_ptr; cmdh_snapshot_sync_resp_t *l_resp_ptr = (cmdh_snapshot_sync_resp_t *) o_rsp_ptr; errlHndl_t l_err = NULL; uint8_t l_query_sz = 0; ERRL_RC l_rc = 0; do { l_query_sz = CMDH_DATALEN_FIELD_UINT16(i_cmd_ptr); // Verify query data size if(l_query_sz != CMDH_SNAPSHOT_SYNC_DATA_SIZE) { TRAC_ERR("cmdh_snapshot_sync: Received an invalid packet size. Expecting 1 byte, received:%i", l_query_sz); l_rc = ERRL_RC_INVALID_CMD_LEN; break; } l_cmd_ptr = (cmdh_snapshot_sync_query_t *)i_cmd_ptr; // Check received packet version if (CMDH_SNAPSHOT_SYNC_VERSION != l_cmd_ptr->version) { TRAC_ERR("cmdh_snapshot_sync: Version %i cmd is not supported.", l_cmd_ptr->version); l_rc = ERRL_RC_INVALID_DATA; break; } // Set the global reset flag, that will cause all saved data to be cleared in the // next callback that is done every 30 seconds via a timer. g_cmdh_snapshot_reset = TRUE; // Reset current index to stop any possible calls from tmgt to get snapshot buffers. g_cmdh_snapshot_cur_index = CMDH_SNAPSHOT_DEFAULT_CUR_INDEX; // Reset timer and start counting from now. This will cause a call to the snapshot_callback // function below which will reset the other globals based on the fact that g_cmdh_snapshot_reset // is set to true. l_rc = ssx_timer_schedule(&G_snapshotTimer, 0, SSX_SECONDS(30)); if (l_rc != SSX_OK) { TRAC_ERR("cmdh_snapshot_sync: reseting the snapshot timer failed."); break; } l_resp_ptr->data_length[0] = 0; l_resp_ptr->data_length[1] = 0; G_rsp_status = 0; }while(FALSE); if (l_rc) { // Build Error Response packet cmdh_build_errl_rsp(i_cmd_ptr, o_rsp_ptr, l_rc, &l_err); } return(l_err); } // Function Specification // // Name: cmdh_snapshot_callback // // Description: Called from timer every 30seconds to store cimp data into // an array of 20 cimp snapshots. Then it triggers the generation // of a new snapshot in the g_cmdh_sna // // End Function Specification void cmdh_snapshot_callback(void * arg) { static cmdh_snapshot_cimp_entry_t L_cim_buf[CMDH_CIMP_MAX]; // Holds the earlier cim data snapshots. static uint8_t L_cim_seq_number = 0; // Holds the next cim seq number to be used. static uint32_t L_prev_pwr_accum = 0; // Holds the previous power sensor accumulator static uint32_t L_prev_pwr_update_tag = 0; // Holds the previous power sensor update tag. uint32_t l_pwr_accum = (uint32_t)AMECSENSOR_PTR(PWRSYS)->accumulator; uint32_t l_pwr_update_tag = AMECSENSOR_PTR(PWRSYS)->update_tag; uint32_t l_avg_pwr = 0; uint32_t l_min_pwr = g_pwr250us_over30sec.min; uint32_t l_max_pwr = g_pwr250us_over30sec.max; uint32_t l_freq_accum = g_pwr250us_over30sec.freqaAccum; uint32_t l_freq_cnt = g_pwr250us_over30sec.count; uint16_t l_avg_freq = 0; cmdh_snapshot_cimp_entry_t l_cim_buf_temp[CMDH_CIMP_MAX - 1]; cmdh_snapshot_buffer_t l_30s_snapshot; // Used to temporarily hold new snapshot data. // Clear data that is calculated every 250us to prep for next callback in 30seconds. // Reset max and min over 30 seconds. memset(&g_pwr250us_over30sec,0,sizeof(g_pwr250us_over30sec)); if (g_cmdh_snapshot_reset) { memset(g_cmdh_snapshot_array, 0, sizeof(g_cmdh_snapshot_array)); g_cmdh_snapshot_cur_id = 0; memset(L_cim_buf,0,sizeof(cmdh_snapshot_buffer_t)); L_cim_seq_number = 0; L_prev_pwr_accum = l_pwr_accum; L_prev_pwr_update_tag = l_pwr_update_tag; // Clear reset flag. - This should be the only place that clears it. g_cmdh_snapshot_reset = FALSE; g_cmdh_snapshot_cur_index = CMDH_SNAPSHOT_DEFAULT_CUR_INDEX; } else if (IS_OCC_STATE_OBSERVATION() || IS_OCC_STATE_ACTIVE() || IS_OCC_STATE_CHARACTERIZATION()) { uint32_t l_pwr_accum_diff = 0; uint32_t l_pwr_uptag_diff = 0; // Calculate the accumulator difference. if(l_pwr_accum >= L_prev_pwr_accum) { l_pwr_accum_diff = l_pwr_accum - L_prev_pwr_accum; } else { l_pwr_accum_diff = l_pwr_accum + (~L_prev_pwr_accum); } // Calculate the update tag difference. if(l_pwr_update_tag >= L_prev_pwr_update_tag) { l_pwr_uptag_diff = l_pwr_update_tag - L_prev_pwr_update_tag; } else if(l_pwr_update_tag < L_prev_pwr_update_tag) // accum must have wrapped. { l_pwr_uptag_diff = l_pwr_update_tag + (~L_prev_pwr_update_tag); } // Make sure we don't divide by 0 if(l_pwr_uptag_diff == 0) { // This should never happen. TRAC_INFO("cmdh_snapshot_callback: update tag difference should not be 0. current:%i, previous:%i.", l_pwr_update_tag, L_prev_pwr_update_tag); l_avg_pwr = 0; } else { // Calculate average power since previous callback. l_avg_pwr = l_pwr_accum_diff / l_pwr_uptag_diff; } if(l_freq_cnt == 0) { // This should never happen. TRAC_INFO("cmdh_snapshot_callback: No frequency data has been accumulated. Returning 0 for frequency. count:%i.", l_freq_cnt); l_avg_freq = 0; } else { // Calculate average frequency of all Cores for the whole Node (all OCCs) l_avg_freq = (uint16_t)(l_freq_accum / l_freq_cnt); } // Save power sensor accumulator and update tag values for next callback. L_prev_pwr_accum = l_pwr_accum; L_prev_pwr_update_tag = l_pwr_update_tag; // Append the new cim buffer entry to the front of the local static array of cim buffers. memcpy(l_cim_buf_temp, L_cim_buf, sizeof(cmdh_snapshot_cimp_entry_t) * (CMDH_CIMP_MAX - 1)); L_cim_buf[0].seq_number = L_cim_seq_number; memcpy(L_cim_buf[0].avg_dc, &l_avg_pwr,sizeof(L_cim_buf[0].avg_dc)); memcpy(L_cim_buf[0].min_dc, &l_min_pwr,sizeof(L_cim_buf[0].min_dc)); memcpy(L_cim_buf[0].max_dc, &l_max_pwr,sizeof(L_cim_buf[0].max_dc)); memcpy(L_cim_buf[0].avg_cpu_freq, &l_avg_freq,sizeof(L_cim_buf[0].avg_cpu_freq)); memcpy(&(L_cim_buf[1]), l_cim_buf_temp, sizeof(cmdh_snapshot_cimp_entry_t) * (CMDH_CIMP_MAX - 1)); // Populate the local 30s snapshot buffer before writing it out to the global array. Reason is // we don't want the buffer data to be read by tmgt cmd while we are filling it. // Copy cim data to snapshot buffer. memcpy(l_30s_snapshot.cim, L_cim_buf, sizeof(cmdh_snapshot_cimp_entry_t) * CMDH_CIMP_MAX); l_30s_snapshot.current_id = g_cmdh_snapshot_cur_id; // Increment current index to signify that we are going to add a new snapshot. g_cmdh_snapshot_cur_index++; if (g_cmdh_snapshot_cur_index > CMDH_SNAPSHOT_MAX_INDEX) { // Wrap back to start g_cmdh_snapshot_cur_index = 0; } // Write buffer to the current index in the global array g_cmdh_snapshot_array. memcpy(&(g_cmdh_snapshot_array[g_cmdh_snapshot_cur_index]),&l_30s_snapshot, sizeof(cmdh_snapshot_buffer_t)); // Increment snapshot id. g_cmdh_snapshot_cur_id++; // Increment sequence count. L_cim_seq_number ++; } } <|start_filename|>src/lib/occlib/occhw_scom_cmd.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/occlib/occhw_scom_cmd.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __OCCHW_SCOM_CMD_H__ #define __OCCHW_SCOM_CMD_H__ /// \file occhw_scom_cmd.h /// \brief Defines the shared scom command control block /// /// This file contains definitions that are used by both ppc405 and GPE /// instances inside the OCC. // The most significant bit of scom addresses is always 0, so we use this // bit to tell the SCOM proxy server (GPE) whether a getscom or putscom is // needed. #define OCCHW_SCOM_READ_MASK 0x80000000 // This is a status value that the ppc405 will write to the status // word prior to starting a new request. This value can be used to // detect that the GPE has not yet written status for the request. // Note: The GPE simply copies it's MSR value to the status field // when it completes. This value is not a valid MSR value. #define OCCHW_SCOM_PENDING 0x0000EF00 // Define the structure offsets for use in assembly code on the GPE #define OCCHW_SCOM_STATUS_OFFSET 0 #define OCCHW_SCOM_ADDR_OFFSET 4 #define OCCHW_SCOM_DATA_OFFSET 8 #ifndef __ASSEMBLER__ typedef union { uint32_t status32; struct { uint32_t rsvd0 : 1; uint32_t mask : 7; uint32_t is0 : 1; uint32_t sibrc : 3; uint32_t lp : 1; uint32_t we : 1; uint32_t is1 : 1; uint32_t uie : 1; uint32_t ee : 1; uint32_t rsvd1 : 2; uint32_t me : 1; uint32_t rsvd2 : 3; uint32_t ipe : 1; uint32_t sibrca : 8; }; } occhw_scom_status_t; typedef struct { //MSR is saved here volatile occhw_scom_status_t scom_status; //msg is used to communicate read/!write volatile uint32_t scom_addr; //data for putscom or from getscom volatile uint64_t scom_data; } occhw_scom_cmd_t; #endif /*__ASSEMBLER__*/ #endif /* __OCCHW_SCOM_CMD_H__ */ <|start_filename|>src/occ_405/pss/dpss_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pss/dpss_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //*************************************************************************/ // Includes //*************************************************************************/ #include <common_types.h> // imageHdr_t declaration and image header macro #include <errl.h> // For error handle #include <dpss.h> #include <trac.h> // For traces #include <occ_sys_config.h> #include <occ_service_codes.h> // for SSX_GENERIC_FAILURE #include <pss_service_codes.h> #include <state.h> //*************************************************************************/ // Externs //*************************************************************************/ extern PoreEntryPoint GPE_dpss_send_command_stream; extern PoreFlex G_dpss_read_status_request; extern gpeDpssCommandStream_t G_gpe_dpss_read_status; //*************************************************************************/ // Macros //*************************************************************************/ //*************************************************************************/ // Defines/Enums //*************************************************************************/ //*************************************************************************/ // Structures //*************************************************************************/ //*************************************************************************/ // Globals //*************************************************************************/ //*************************************************************************/ // Function Prototypes //*************************************************************************/ //*************************************************************************/ // Functions //*************************************************************************/ // Function Specification // // Name: dpss_initialize // // Description: Initializes DPSS fans and oversubscription interrupt // If errHndl is returned, caller should call this function again, // one time only, in the hopes that it will work on the retry. // // End Function Specification errlHndl_t dpss_initialize(void) { errlHndl_t l_err = NULL; PoreFlex request; uint8_t i, l_idx_limit; // index counter and limit value // Build command data // Structures from this array we will be passed into our GPE program one-by-one gpeDpssCommandStream_t l_gpe_dpss_stream_dpss_config[] = { { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_MIN_FANS | G_sysConfigData.dpss_fan.min_fans, .command[1] = DPSS_CMD_SET_PWM_DELAY | G_sysConfigData.dpss_fan.pwm_delay_reg, .command[2] = DPSS_CMD_SET_PWM_STEP | G_sysConfigData.dpss_fan.pwm_step_reg, .command[3] = 0x0000, .response = {0} }, }, { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_FAN_PPR_0 | G_sysConfigData.dpss_fan.fan_ppr[0], .command[1] = DPSS_CMD_SET_FAN_PPR_1 | G_sysConfigData.dpss_fan.fan_ppr[1], .command[2] = 0x0000, .command[3] = 0x0000, .response = {0} }, }, // Fan hysterisis: write low byte, then high byte { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_FAN_HYST_1_LO | G_sysConfigData.dpss_fan.fan_hysterisis[1], .command[1] = DPSS_CMD_SET_FAN_HYST_0_HI | G_sysConfigData.dpss_fan.fan_hysterisis[0], .command[2] = 0x0000, .command[3] = 0x0000, .response = {0} }, }, // Fan hysterisis: write low byte, then high byte { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_FAN_HYST_3_LO | G_sysConfigData.dpss_fan.fan_hysterisis[3], .command[1] = DPSS_CMD_SET_FAN_HYST_2_HI | G_sysConfigData.dpss_fan.fan_hysterisis[2], .command[2] = DPSS_CMD_SET_FAN_MODE | G_sysConfigData.dpss_fan.fan_mode, .command[3] = 0x0000, .response = {0} }, }, { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_FAN_MASK | G_sysConfigData.dpss_fan.fan_mask, .command[1] = DPSS_CMD_SET_FAN_HYST_MASK | G_sysConfigData.dpss_fan.fan_hyst_mask, .command[2] = DPSS_CMD_SET_MAX_FAN_PWM | G_sysConfigData.dpss_fan.max_fan_pwm, .command[3] = 0x0000, .response = {0} }, }, { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_MIN_PWM | G_sysConfigData.dpss_fan.min_pwm, .command[1] = DPSS_CMD_SET_SPI_FFS | G_sysConfigData.dpss_fan.spi_ffs, .command[2] = DPSS_CMD_SET_SPIS_INT_MASK | G_sysConfigData.dpss_spis_int_mask, .command[3] = 0x0000, .response = {0} }, }, { .dpss_msg_stream = { .command[0] = DPSS_CMD_SET_END_COUNT | G_sysConfigData.dpss_fan.end_count_reg, .command[1] = DPSS_CMD_SET_FAN_WARN_COUNT | G_sysConfigData.dpss_fan.fan_warning_cnt, .command[2] = 0x0000, .command[3] = 0x0000, .response = {0} }, }, }; // Calculate the array size dynamically so we don't have to update it if the array changes. l_idx_limit = sizeof(l_gpe_dpss_stream_dpss_config) / sizeof(gpeDpssCommandStream_t); for( i = 0; i < l_idx_limit; i++) { // Clear the error reporting parts of the argument structure. l_gpe_dpss_stream_dpss_config[i].gpe_error.error = 0; l_gpe_dpss_stream_dpss_config[i].gpe_error.ffdc = 0; // Create GPE program request DPSS_DEBUG_PRINTF(("%s: Calling GPE_dpss_send_command_stream for index %d\n", __FUNCTION__, i)); pore_flex_create(&request, // request &pore_gpe0_queue, // queue (void*)GPE_dpss_send_command_stream, // GPE entry_point (uint32_t)&l_gpe_dpss_stream_dpss_config[i], // GPE argument_ptr NULL, // callback NULL, // callback arg ASYNC_REQUEST_BLOCKING); // options // Schedule the request to be executed // Because our GPE structures are not in non-cacheable RAM (they are in the .init section instead), // we have to flush the dcache before making the pore flex request, then invalidate the dcache afterward. dcache_flush(&l_gpe_dpss_stream_dpss_config[i], sizeof(l_gpe_dpss_stream_dpss_config[i])); pore_flex_schedule(&request); dcache_invalidate((void *)(&l_gpe_dpss_stream_dpss_config[i]), sizeof(l_gpe_dpss_stream_dpss_config[i])); DPSS_DEBUG_PRINTF(("%s: GPE_dpss_send_command_stream for index %d returned: 0x%08X\n", __FUNCTION__, i, l_gpe_dpss_stream_dpss_config[i].gpe_error.rc)); DPSS_DEBUG_PRINTF(("\tcommand[0] = 0x%04x, response[0] = 0x%04x\n", l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[0], l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[0])); DPSS_DEBUG_PRINTF(("\tcommand[1] = 0x%04x, response[1] = 0x%04x\n", l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[1], l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[1])); DPSS_DEBUG_PRINTF(("\tcommand[2] = 0x%04x, response[2] = 0x%04x\n", l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[2], l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[2])); DPSS_DEBUG_PRINTF(("\tcommand[3] = 0x%04x, response[3] = 0x%04x\n", l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[3], l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[3])); // Check for errors and invalid DPSS responses. // (Valid DPSS responses should be an echo of the cmd & data passed in). if ( (l_gpe_dpss_stream_dpss_config[i].gpe_error.rc != 0) || (l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[0] != l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[0]) || (l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[1] != l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[1]) || (l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.response[2] != l_gpe_dpss_stream_dpss_config[i].dpss_msg_stream.command[2]) ) { DPSS_DEBUG_PRINTF(("%s: ...Failed with error.\n", __FUNCTION__)); /*@ * @moduleid PSS_MID_DPSS_INIT * @reasonCode INTERNAL_HW_FAILURE * @severity ERRL_SEV_UNRECOVERABLE * @userdata1 GPE error return code * @userdata2 GPE error ffdc * @userdata4 OCC_NO_EXTENDED_RC * @devdesc GPE command failed to initialize the DPSS */ l_err = createErrl(PSS_MID_DPSS_INIT, // i_modId, INTERNAL_HW_FAILURE, // i_reasonCode, OCC_NO_EXTENDED_RC, // extended reason code // @nh001a ERRL_SEV_UNRECOVERABLE, NULL, // tracDesc_t i_trace, 0x0000, // i_traceSz, l_gpe_dpss_stream_dpss_config[i].gpe_error.rc, // i_userData1, l_gpe_dpss_stream_dpss_config[i].gpe_error.ffdc >> 32); // i_userData2 // Put extra debug info into local data struct addUsrDtlsToErrl(l_err, (uint8_t*)&l_gpe_dpss_stream_dpss_config[i], sizeof(l_gpe_dpss_stream_dpss_config[i]), ERRL_STRUCT_VERSION_1, ERRL_USR_DTL_TRACE_DATA); break; } else { DPSS_DEBUG_PRINTF(("%s: ...Success!\n", __FUNCTION__)); } } return l_err; } // Function Specification // // Name: dpssInitApplet (old name is start_dpss) // // Description: // Entry-point for enabling DPSS functionality. // Initializes the DPSS chip. Starts the "DPSS Read Status" RTLS task. // // End Function Specification errlHndl_t dpssInitApplet(void * i_arg) { // Init DPSS TRAC_INFO("Initializing DPSS registers..."); errlHndl_t l_errl = dpss_initialize(); if (l_errl) { // init failed, attempt one more time before giving up TRAC_ERR("dpss_initialize failed! (retrying)..."); // Convert the error severity to info and log it. setErrlSevToInfo(l_errl); commitErrl( &l_errl ); l_errl = dpss_initialize(); if (l_errl) { TRAC_ERR("dpss_initialize failed again! OCC will be reset."); // Log the error with its original unrecoverable severity commitErrl( &l_errl ); REQUEST_RESET(); } } if (!l_errl) { TRAC_INFO("...DPSS initialized."); TRAC_INFO("Enabling DPSS Read Status RTLS task."); // Init the global DPSS read-status PORE flex request. // None of these values is expected to change. pore_flex_create(&G_dpss_read_status_request, // request &pore_gpe0_queue, // queue (void*)GPE_dpss_send_command_stream, // GPE entry_point (uint32_t)&G_gpe_dpss_read_status, // GPE argument_ptr NULL, // callback NULL, // callback arg 0); // options DO NOT set this to ASYNC_REQUEST_BLOCKING // Make this task runnable. rtl_start_task(TASK_ID_DPSS_RD_STATUS); } return l_errl; } <|start_filename|>src/ppe/pk/gpe/gpe_irq.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/gpe/gpe_irq.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __GPE_IRQ_H__ #define __GPE_IRQ_H__ /// \file occhw_irq.h /// \brief GPE-OCCHW Interrupt handling for PK /// /// The OCCHW interrupt controller supports a maximum of 64 interrupts, split /// into 2 x 32-bit non-cascaded interrupt controllers with simple OR /// combining of the interrupt signals. /// /// The OCB interrupt controller allows interrupt status to be set directly by /// software, as well as providing a mode that causes an enabled pending /// interrupt to trigger an Unconditional Debug Event. The OCB interrupt /// controller contains a 'mask' register, unlike other 405 interrupt /// controllers that have an 'enable' register. The OCCHW mask and status /// registers also have atomic CLR/OR function so that it is never necessary /// to enter a critical section to enable/disable/clear interrupts and /// interrupt status. #include "occhw_common.h" #include "ocb_register_addresses.h" #include "ppe42.h" #ifndef __ASSEMBLER__ /// Enable an interrupt by clearing the mask bit. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_enable(PkIrqId irq) { out32(OCCHW_OIMR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } /// Enable a vector of interrupts by clearing the mask bits. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_enable(uint64_t irq_vec_mask) { out32(OCB_OIMR0_CLR, (uint32_t)(irq_vec_mask >> 32)); out32(OCB_OIMR1_CLR, (uint32_t)irq_vec_mask); } /// Restore a vector of interrupts by overwriting OIMR. /* UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_restore( PkMachineContext *context, uint64_t irq_vec_mask) { pk_critical_section_enter(context); out64( OCB_OIMR, irq_vec_mask); pk_critical_section_exit(context); } */ /// Disable an interrupt by setting the mask bit. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_disable(PkIrqId irq) { out32(OCCHW_OIMR_OR(irq), OCCHW_IRQ_MASK32(irq)); } /// Disable a vector of interrupts by setting the mask bits. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_disable(uint64_t irq_vec_mask) { out32(OCB_OIMR0_OR, (uint32_t)(irq_vec_mask >> 32)); out32(OCB_OIMR1_OR, (uint32_t)irq_vec_mask); } /// Clear interrupt status with an CLR mask. Only meaningful for /// edge-triggered interrupts. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_status_clear(PkIrqId irq) { out32(OCCHW_OISR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } /// Clear a vector of interrupts status with an CLR mask. Only meaningful for /// edge-triggered interrupts. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_vec_status_clear(uint64_t irq_vec_mask) { out32(OCB_OISR0_CLR, (uint32_t)(irq_vec_mask >> 32)); out32(OCB_OISR1_CLR, (uint32_t)irq_vec_mask); } /// Get IRQ status as a 0 or non-0 integer UNLESS__PPE42_IRQ_CORE_C__(extern) inline int pk_irq_status_get(PkIrqId irq) { return (in32(OCCHW_OISR(irq)) & OCCHW_IRQ_MASK32(irq)) != 0; } /// Set or clear interrupt status explicitly. UNLESS__PPE42_IRQ_CORE_C__(extern) inline void pk_irq_status_set(PkIrqId irq, int value) { if (value) { out32(OCCHW_OISR_OR(irq), OCCHW_IRQ_MASK32(irq)); } else { out32(OCCHW_OISR_CLR(irq), OCCHW_IRQ_MASK32(irq)); } } #endif /* __ASSEMBLER__ */ /// \page occhw_irq_macros OCCHW IRQ API Assembler Macros /// /// These macros encapsulate the PK API for the OCCHW interrupt /// controller. These macros require 2 scratch registers in addition to the \c /// irq parameter register passed into the handler from PK interrupt /// dispatch. These macros also modify CR0. /// /// \arg \c rirq A register that holds the \c irq parameter passed to /// the handler from PK interrupt dispatch. This register is not /// modified. /// \arg \c rmask A scratch register - At the end of macro execution this /// register contains the 32-bit mask form of the irq. /// /// \arg \c raddr A scratch register - At the end of macro execution this /// register holds the address of the interrupt /// controller facility that implements the action. /// /// \arg \c imm An immediate (0/non-0) value for certain macros. /// /// Forms: /// /// \b _pk_irq_enable \a rirq, \a rmask, \a raddr - Enable an \c irq. \n /// \b _pk_irq_disable \a rirq, \a rmask, \a raddr - Disable an \c irq. \n /// \b _pk_irq_status_clear \a rirq, \a rmask, \a raddr - Clear \c irq /// interrupt status. \n /// \b _pk_irq_status_set \a rirq, \a rmask, \a raddr, \a imm - Set \c irq status /// with an immediate (0/non-0) value. \n /// /// \todo Once the logic design is locked down, revisit whether these macros /// (and C-code versions) can be implemented without branching. This could be /// done in theory by converting bit 26 into the byte offset between addresses /// in interupt controller 0 and interrupt controller 1 - assuming the /// distances are all the same power-of-two. /// /// \cond // IRQ numbers are in the range 0..63. IRQs are converted to the 32-bit // residue used to compute the mask. CR0 is set as a test of IRQ > 32 - the // register \c raddr is used as scratch for these computations. Hopefully the // local labels 888 and 999 are unique enough. // Register names must be compared as strings - e.g., %r0 is not // a symbol, it is converted to "0" by the assembler. #ifdef __ASSEMBLER__ // *INDENT-OFF* .macro .two_unique, ra, rb .ifnc \ra, \rb .exitm .endif .error "Both register arguments must be unique" .endm .macro .three_unique, ra, rb, rc .ifnc \ra, \rb .ifnc \rb, \rc .ifnc \ra, \rc .exitm .endif .endif .endif .error "All three register arguments must be unique" .endm .macro _occhw_irq_or_mask, rirq:req, rmask:req .two_unique \rirq, \rmask lis \rmask, 0x8000 srw \rmask, \rmask, \rirq .endm .macro _occhw_irq_clr_mask, rirq:req, rmask:req .two_unique \rirq, \rmask _occhw_irq_or_mask \rirq, \rmask .endm .macro _pk_irq_enable, rirq:req, rmask:req, raddr:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 _occhw_irq_clr_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OIMR0_CLR b 999f 888: _stwi \rmask, \raddr, OCB_OIMR1_CLR 999: eieio .endm .macro _pk_irq_disable, rirq:req, rmask:req, raddr:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 _occhw_irq_or_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OIMR0_OR b 999f 888: _stwi \rmask, \raddr, OCB_OIMR1_OR 999: eieio .endm .macro _pk_irq_status_clear, rirq:req, rmask:req, raddr:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 _occhw_irq_clr_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OISR0_CLR b 999f 888: _stwi \rmask, \raddr, OCB_OISR1_CLR 999: eieio .endm .macro _pk_irq_status_set, rirq:req, rmask:req, raddr:req, imm:req .three_unique \rirq, \rmask, \raddr andi. \raddr, \rirq, 0x20 clrlwi \raddr, \rirq, 27 .if \imm _occhw_irq_or_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OISR0_OR b 999f 888: _stwi \rmask, \raddr, OCB_OISR1_OR .else _occhw_irq_clr_mask \raddr, \rmask bne- 888f _stwi \rmask, \raddr, OCB_OISR0_CLR b 999f 888: _stwi \rmask, \raddr, OCB_OISR1_CLR .endif 999: eieio .endm // *INDENT-ON* #endif /* __ASSEMBLER__ */ /// \endcond #endif /* __GPE_IRQ_H__ */ <|start_filename|>src/occ_405/trac/trac_interface.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/trac/trac_interface.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //*************************************************************************/ // Includes //*************************************************************************/ #include "ssx.h" #include <trac_interface.h> #include <trac_service_codes.h> #include <occ_common.h> #include <comp_ids.h> //*************************************************************************/ // Externs //*************************************************************************/ //*************************************************************************/ // Macros //*************************************************************************/ //*************************************************************************/ // Defines/Enums //*************************************************************************/ #define TRAC_END_BUFFER "&" #define TRAC_INTF_MUTEX_TIMEOUT SSX_SECONDS(5) #define TRACE_BUF_VERSION 0x01; /*!< Trace buffer version */ #define TRACE_FIELDTRACE 0x4654; /*!< Field Trace - "FT" */ #define TRACE_FIELDBIN 0x4644 /*!< Binary Field Trace - "FD" */ #define TRAC_TIME_REAL 0 // upper 32 = seconds, lower 32 = microseconds #define TRAC_TIME_50MHZ 1 #define TRAC_TIME_200MHZ 2 #define TRAC_TIME_167MHZ 3 // 166666667Hz //*************************************************************************/ // Structures //*************************************************************************/ //*************************************************************************/ // Globals //*************************************************************************/ /// Instantiate the buffers for the traces. /// /// It may be beneficial to add the attribute: /// __attribute__ ((section (".noncacheable"))) /// when debugging on real HW, in case the OCC hangs and we can't access /// the cache to get coherent data. uint8_t g_trac_inf_buffer[TRACE_BUFFER_SIZE] __attribute__ ((section (".inf_trac"))); uint8_t g_trac_err_buffer[TRACE_BUFFER_SIZE] __attribute__ ((section (".err_trac"))); uint8_t g_trac_imp_buffer[TRACE_BUFFER_SIZE] __attribute__ ((section (".imp_trac"))); // Need to modify the addTraceToErrl() function in errl.c when new trace buffer is added/removed tracDesc_t g_trac_inf = (tracDesc_t) &g_trac_inf_buffer; tracDesc_t g_trac_err = (tracDesc_t) &g_trac_err_buffer; tracDesc_t g_trac_imp = (tracDesc_t) &g_trac_imp_buffer; SsxSemaphore g_trac_mutex_inf; SsxSemaphore g_trac_mutex_err; SsxSemaphore g_trac_mutex_imp; // There are #defines for the indicies of this array in the header file const trace_descriptor_array_t g_des_array[] = { {&g_trac_inf,"INF", &g_trac_mutex_inf}, {&g_trac_err,"ERR", &g_trac_mutex_err}, {&g_trac_imp,"IMP", &g_trac_mutex_imp} }; static bool circular_full_flag = FALSE; circular_buf_header_t g_isr_circular_header; circular_entire_data_t g_isr_circular_buf[CIRCULAR_BUFFER_SIZE]; //*************************************************************************/ // Function Prototypes //*************************************************************************/ /* * Initialize all header values of a trace buffer * * This function will initialize all of the values in the trace buffer * header so that it is ready for tracing. * * param o_buf Pointer to trace buffer which will be initialized. * param i_comp Component who is getting buffer initialized. * * return Non-zero return code on error. */ UINT trac_init_values_buffer(tracDesc_t *o_buf,const CHAR *i_comp); /* * Raw buffer write function * * This function assumes i_td has been initialized and it also assume * the critical region of the input trace descriptor has been locked. * * param io_td Initialized trace descriptor pointer to buffer to trace to. * param i_ptr Pointer to data to write to trace buffer * param i_size Size of i_ptr * * return Non-zero return code on error. */ UINT trac_write_data(const trace_descriptor_array_t *io_td, const void *i_ptr, const ULONG i_size); /* * Write data to circular buffer * * param i_ptr * * return Non-zero return code on error. */ uint16_t trac_write_data_to_circular(circular_entire_data_t *i_ptr); /** * Get data from circular buffer * * param o_ptr * * return Non-zero return code on error. */ uint16_t get_trac_entry_data_from_circular(circular_entire_data_t *o_ptr); //*************************************************************************/ // Functions //*************************************************************************/ // Function Specification // // Name: TRAC_init_buffers // // Description: // // End Function Specification UINT TRAC_init_buffers() { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ INT l_rc = 0; UINT l_num_des = sizeof(g_des_array) / sizeof(trace_descriptor_array_t); UINT i=0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // Initialize trace mutexes for(i = 0;i < l_num_des; i++) { l_rc = ssx_semaphore_create(g_des_array[i].sem, 1, 1); if(SSX_OK != l_rc) break; } if(SSX_OK != l_rc) { // Badness, don't continue FIELD("TRAC_init_buffers: Failed to create mutex"); } else { // Initialize trace buffers for(i=0;i<l_num_des;i++) { // Initialize the buffer l_rc = trac_init_values_buffer(g_des_array[i].entry, g_des_array[i].comp); if(l_rc) { FIELD1("TRAC_init_buffers: Failed to initialize buffer: ", (unsigned char)i); break; } } } // Initialize isr circular buffer it to all 0's g_isr_circular_header.head = 0; g_isr_circular_header.tail = 0; g_isr_circular_header.entryCount = 0; memset(g_isr_circular_buf, 0 , CIRCULAR_BUFFER_SIZE * sizeof(circular_entire_data_t)); return(l_rc); } // Function Specification // // Name: trac_init_values_buffer // // Description: // // End Function Specification UINT trac_init_values_buffer(tracDesc_t *o_buf,const CHAR *i_comp) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT16 l_rc = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // Initialize it to all 0's memset(*o_buf,0,(size_t)TRACE_BUFFER_SIZE); (*o_buf)->ver = TRACE_BUF_VERSION; (*o_buf)->hdr_len = sizeof(trace_buf_head_t); (*o_buf)->time_flg = TRAC_TIME_REAL; (*o_buf)->endian_flg = 'B'; // Big Endian memcpy((*o_buf)->comp,i_comp,(size_t)COMP_NAME_SIZE); (*o_buf)->size = TRACE_BUFFER_SIZE; (*o_buf)->times_wrap = 0; (*o_buf)->next_free = sizeof(trace_buf_head_t); return(l_rc); } // Function Specification // // Name: trace_adal_write_all // // Description: In order to leverage the tracepp, need to add this function. It will call // trac_write_int finally // // End Function Specification UINT trace_adal_write_all(const trace_descriptor_array_t *io_td,const trace_hash_val i_hash, const char *i_fmt,const ULONG i_line, const ULONG i_type,...) { UINT rc = 0, i = 0; UINT l_num_args = 0; ULONG l_i_param[TRACE_MAX_ARGS] = {0}; // Calculate the number of optional parameters by looking at the i_fmt. // i_fmt will store something like "%d,%f,%u" if(i_fmt != NULL) { l_num_args = 1; for(i=0;i_fmt[i] != 0;i++) { if( i_fmt[i] == ',') { l_num_args++; } } } // Get the optional parameters va_list l_argptr; //will hold optional parameters va_start(l_argptr,i_type); // Check the number of optional parameters if(TRACE_MAX_ARGS < l_num_args) { l_num_args = TRACE_MAX_ARGS; } for (i=0;i<l_num_args;i++) { l_i_param[i] = va_arg(l_argptr,ULONG); } va_end(l_argptr); rc = trac_write_int(io_td, i_hash, i_line, l_num_args, l_i_param[0], l_i_param[1], l_i_param[2], l_i_param[3], l_i_param[4] ); return rc; } // Function Specification // // Name: trac_write_int // // Description: // // End Function Specification UINT trac_write_int(const trace_descriptor_array_t *io_td,const trace_hash_val i_hash, const ULONG i_line, const UINT i_num_args, const ULONG i_1,const ULONG i_2,const ULONG i_3, const ULONG i_4,const ULONG i_5) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT l_rc = 0; ULONG l_entry_size = 0; trace_entire_entry_t l_entry; SsxMachineContext l_ctx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ if(io_td != NULL) { // Calculate total space needed l_entry_size = sizeof(trace_entry_stamp_t); l_entry_size += sizeof(trace_entry_head_t); // We always add the size of the entry at the end of the trace entry // so the parsing tool can easily walk the trace buffer stack so we // need to add that on to total size l_entry_size += sizeof(ULONG); // Now add on size for actual number of arguments we're tracing l_entry_size += (i_num_args * sizeof(ULONG)); // Word align the entry l_entry_size = (l_entry_size + 3) & ~3; // Fill in the entry structure //l_entry.stamp.tid = (ULONG)tx_thread_identify(); // What is response to this in AME code? l_entry.stamp.tid = (__ssx_kernel_context_thread() ? 1 : 0); //context thread or ISR // Capture the time. Note the time stamp is split into tbh (upper) and // tbl (lower), both of which are 32 bits each. The ssx_timebase_get // call returns a uint64_t uint64_t l_time = ssx_timebase_get(); l_entry.stamp.tbh = l_time / SSX_TIMEBASE_FREQUENCY_HZ; // seconds l_entry.stamp.tbl = ((l_time % SSX_TIMEBASE_FREQUENCY_HZ)*1000000000) // nanoseconds /SSX_TIMEBASE_FREQUENCY_HZ; // Length is equal to size of data l_entry.head.length = (i_num_args * sizeof(ULONG)); l_entry.head.tag = TRACE_FIELDTRACE; l_entry.head.hash = i_hash; l_entry.head.line = i_line; switch (i_num_args) { case 5: l_entry.args[4] = i_5; // Intentional Fall Through case 4: l_entry.args[3] = i_4; // Intentional Fall Through case 3: l_entry.args[2] = i_3; // Intentional Fall Through case 2: l_entry.args[1] = i_2; // Intentional Fall Through case 1: l_entry.args[0] = i_1; // Intentional Fall Through default: ; } // Now put total size at end of buffer l_entry.args[i_num_args] = l_entry_size; // Disable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_enter(SSX_NONCRITICAL, &l_ctx); // Check if context thread or ISR get semaphore or not // If ISR did not get semaphore, will add trace log into circular buffer. // Context thread will check circular buffer, and add log back into trace buffer. // Prevent ISR did not get semaphore, and lost trace log. l_rc = ssx_semaphore_pend(io_td->sem, __ssx_kernel_context_thread()? \ TRAC_INTF_MUTEX_TIMEOUT : SSX_NO_WAIT); if(l_rc == SSX_OK) { // Either this is thread context and mutex was locked within // timeout or this is interrupt context and mutex was immediately // available, regardless, mutex is now locked. l_rc = SUCCESS; // Update the entry count (*io_td->entry)->te_count++; l_rc = trac_write_data(io_td, (void *)&l_entry, l_entry_size); if(l_rc != SUCCESS) { // Badness - Not much we can do on trace failure. Can't log error // because of recursion concerns. Luckily a trace error is not critical. FIELD("trac_write_int: Failed in call to trac_write_data()"); } // Always try to release even if error above ssx_semaphore_post(io_td->sem); } else if(!__ssx_kernel_context_thread()) { // Tracing in interrupt context and mutex was locked, SSX // returned -SSX_SEMAPHORE_PEND_NO_WAIT // Failed to get semaphore in ISR // Create trace in ISR circular buffer circular_entire_data_t l_cir_data_in; l_cir_data_in.len = l_entry_size; memcpy(&l_cir_data_in.comp, io_td->comp, (size_t)COMP_NAME_SIZE); l_cir_data_in.entry = l_entry; if(g_isr_circular_header.entryCount >= CIRCULAR_BUFFER_SIZE) { FIELD("trac_write_int: Circular Buffer size insufficient!\n"); circular_full_flag = TRUE; l_rc = TRAC_CIRCULAR_BUFF_FULL; // Always try to release even if error above ssx_semaphore_post(io_td->sem); return(l_rc); } // Save to Circular Buffer l_rc = trac_write_data_to_circular(&l_cir_data_in); g_isr_circular_header.head = (g_isr_circular_header.head + 1) % CIRCULAR_BUFFER_SIZE; g_isr_circular_header.entryCount++; if(l_rc != SUCCESS) { // Badness - Not much we can do on trace failure. Can't log error // because of recursion concerns. Luckily a trace error is not critical. FIELD("trac_write_int: Failed in call to trac_write_data_to_circular()"); } } else { // Failed to get mutex in thread FIELD("trac_write_int: Failed to get mutex"); } // Re-enable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_exit(&l_ctx); //2nd. Check caller from thread? if(__ssx_kernel_context_thread() && (g_isr_circular_header.entryCount > 0)) { if(circular_full_flag) { // If ISR circular buffer is full, create a trace in IMP // Use existed trace structure to create new trace // re-calculate size of the new trace entry l_entry_size = l_entry_size + ((1 - i_num_args)*4); // fill trace field l_entry.head.hash = trace_adal_hash("IMP: ISR Circular Buffer is full, %d entries lost", -1); l_entry.head.line = __LINE__; // one argument for this trace l_entry.head.length = sizeof(ULONG); l_entry.args[0] = circular_full_flag; l_entry.args[1] = l_entry_size; // Disable non-critical interrupts in thread context ssx_critical_section_enter(SSX_NONCRITICAL, &l_ctx); // Get IMP trace buffer / mutex const trace_descriptor_array_t *imp_td = TRAC_get_td("IMP"); //Write to IMP trace buffer l_rc = ssx_semaphore_pend(imp_td->sem,TRAC_INTF_MUTEX_TIMEOUT); if(l_rc == SSX_OK) { // Update the entry count (*imp_td->entry)->te_count++; l_rc = trac_write_data(imp_td, (void *)&l_entry, l_entry_size); if(l_rc != SUCCESS) { // Badness - Not much we can do on trace failure. Can't log error // because of recursion concerns. Luckily a trace error is not critical. FIELD("trac_write_int: Failed in call to trac_write_data()"); } ssx_semaphore_post(imp_td->sem); } else { // Failed to get mutex in thread FIELD("trac_write_int: Failed to get mutex"); } // Re-enable non-critical interrupts ssx_critical_section_exit(&l_ctx); // Reset full flag circular_full_flag = FALSE; l_rc = TRAC_CIRCULAR_BUFF_FULL; } circular_entire_data_t l_cir_data_out; do { // Thread context here, disable non-critical // interrupts while unloading circular buffer ssx_critical_section_enter(SSX_NONCRITICAL, &l_ctx); // Get tail position g_isr_circular_header.tail = g_isr_circular_header.tail % CIRCULAR_BUFFER_SIZE; //Copy One trace entity from circular buffer get_trac_entry_data_from_circular(&l_cir_data_out); //Write to trace buffer const trace_descriptor_array_t *i_td = TRAC_get_td((const char *)l_cir_data_out.comp); l_rc = ssx_semaphore_pend(i_td->sem,TRAC_INTF_MUTEX_TIMEOUT); if(l_rc == SSX_OK) { // Update the entry count (*i_td->entry)->te_count++; l_rc = trac_write_data(i_td, (const void *)&l_cir_data_out.entry, (const ULONG)l_cir_data_out.len); if(l_rc == SUCCESS) { if(g_isr_circular_header.tail == g_isr_circular_header.head ) g_isr_circular_header.entryCount = 0; else { g_isr_circular_header.tail++; g_isr_circular_header.entryCount--; } } else { // Badness - Not much we can do on trace failure. Can't log error // because of recursion concerns. Luckily a trace error is not critical. FIELD("trac_write_int: Failed in call to trac_write_data()"); } ssx_semaphore_post(i_td->sem); } else { // Failed to get mutex in thread FIELD("trac_write_int: Failed to get mutex"); } // Re-enable non-critical interrupts ssx_critical_section_exit(&l_ctx); } while(g_isr_circular_header.entryCount > 0); } } else { l_rc = TRAC_INVALID_PARM; FIELD("trac_write_int: User passed invalid parameter"); } return(l_rc); } // NOTE: Removed trac_write_bin because it was unused and unsafe // Function Specification // // Name: trac_write_data // // Description: // // End Function Specification UINT trac_write_data(const trace_descriptor_array_t *io_td, const void *i_ptr, const ULONG i_size) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT l_rc = 0; ULONG l_total_size = i_size; void *l_buf_ptr = NULL; ULONG l_offset = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { if(i_size > TRACE_BUFFER_SIZE) { FIELD("trac_write_data: Input size too large!"); l_rc = TRAC_DATA_SIZE_TOO_LARGE; break; } if(((*io_td->entry)->next_free + l_total_size) > TRACE_BUFFER_SIZE) { // copy what we can to end l_buf_ptr = (char *)(*io_td->entry) + (*io_td->entry)->next_free; l_buf_ptr = (void *) ( ((ULONG) l_buf_ptr + 3) & ~3); l_offset = TRACE_BUFFER_SIZE - (*io_td->entry)->next_free; memcpy(l_buf_ptr,i_ptr,(size_t)l_offset); l_total_size -= l_offset; // Now adjust the main header of buffer (*io_td->entry)->times_wrap++; (*io_td->entry)->next_free = (*io_td->entry)->hdr_len; } l_buf_ptr = (char *)(*io_td->entry) + (*io_td->entry)->next_free; // Word align the write - total size includes this alignment l_buf_ptr = (void *) ( ((ULONG) l_buf_ptr + 3) & ~3); memcpy(l_buf_ptr,(char *)i_ptr + l_offset,l_total_size); // Make sure size is correct for word alignment // Note that this works with binary trace because only the binary data // has the potential to be un-word aligned. If two parts of the binary // trace had this problem then this code would not work. l_total_size = (l_total_size + 3) & ~3; (*io_td->entry)->next_free += l_total_size; }while(FALSE); return(l_rc); } // Function Specification // // Name: TRAC_get_td // // Description: // // End Function Specification const trace_descriptor_array_t* TRAC_get_td(const char *i_comp) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT l_num_des = 0; UINT i=0; const trace_descriptor_array_t* l_td = NULL; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ l_num_des = sizeof(g_des_array) / sizeof(trace_descriptor_array_t); for(i=0;i<l_num_des;i++) { if(memcmp(i_comp,(*(g_des_array[i].entry))->comp,(size_t)COMP_NAME_SIZE) == 0) { // Found the component l_td = &(g_des_array[i]); break; } } return(l_td); } // Function Specification // // Name: TRAC_get_buffer // // Description: // // End Function Specification UINT TRAC_get_buffer(const trace_descriptor_array_t *i_td_ptr, void *o_data) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT l_rc = 0; SsxMachineContext l_ctx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ if((i_td_ptr) && (o_data != NULL)) { // Disable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_enter(SSX_NONCRITICAL, &l_ctx); // Get the lock l_rc = ssx_semaphore_pend(i_td_ptr->sem,TRAC_INTF_MUTEX_TIMEOUT); if(l_rc != SSX_OK) { // Badness FIELD("TRAC_get_buffer: Failed to get mutex"); } else { l_rc = SUCCESS; // Copy it's buffer into temp one memcpy(o_data,*i_td_ptr->entry,(size_t)TRACE_BUFFER_SIZE); // Always try to release even if error above ssx_semaphore_post(i_td_ptr->sem); // Re-enable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_exit(&l_ctx); } } else { FIELD("TRAC_get_buffer: Invalid parameter passed by caller"); l_rc = TRAC_INVALID_PARM; } return(l_rc); } // Function Specification // // Name: TRAC_get_buffer_partial // // Description: // // End Function Specification UINT TRAC_get_buffer_partial(const trace_descriptor_array_t *i_td_ptr, void *io_data, UINT *io_size) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT l_rc = 0; char *l_full_buf = NULL; tracDesc_t l_head = NULL; UINT l_part_size = 0; bool l_lock_get = FALSE; SsxMachineContext l_ctx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { if((i_td_ptr == NULL) || (io_data == NULL) || (io_size == NULL)) { FIELD("TRAC_get_buffer_partial: Invalid parameter passed by caller"); l_rc = TRAC_INVALID_PARM; if(io_size != NULL) { *io_size = 0; } break; } // We can't even fit in first part of buffer // Make sure data size is larger than header length // Otherwise, we will be accessing beyond memory if(*io_size < sizeof(trace_buf_head_t)) { // Need to at least have enough space for the header FIELD("TRAC_get_buffer_partial: *io_size too small"); l_rc = TRAC_DATA_SIZE_LESS_THAN_HEADER_SIZE; *io_size = 0; break; } // CRITICAL REGION START // Disable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_enter(SSX_NONCRITICAL, &l_ctx); // Get the lock l_rc = ssx_semaphore_pend(i_td_ptr->sem,TRAC_INTF_MUTEX_TIMEOUT); if(l_rc != SSX_OK) { // Badness FIELD("TRAC_get_buffer_partial: Failed to get mutex"); } else { // Now that we have full buffer, adjust it to be requested size memset(io_data,0,(size_t)*io_size); l_lock_get = TRUE; l_full_buf = (char*)(*i_td_ptr->entry); if(*io_size >= TRACE_BUFFER_SIZE) { // It fits *io_size = TRACE_BUFFER_SIZE; memcpy(io_data,l_full_buf,(size_t)*io_size); break; } // copy the header of the trace buffer to io_data l_head = (tracDesc_t)l_full_buf; memcpy(io_data,l_full_buf,(size_t)(l_head->hdr_len)); // Reuse the l_head to point to the io_data and fill in the data l_head = (tracDesc_t)io_data; if((l_head->next_free == l_head->hdr_len) && (l_head->times_wrap == 0)) { // No data in buffer so just return what we have *io_size = 0; break; } if(l_head->next_free > *io_size) { l_part_size = *io_size - l_head->hdr_len; memcpy((UCHAR *)io_data+l_head->hdr_len, l_full_buf+l_head->next_free-l_part_size, (size_t)l_part_size); // We don't need to update *io_size, all data copied. l_head->size = *io_size; // Set pointer at beginning because this will be a // "just wrapped" buffer. l_head->next_free = l_head->hdr_len; // Buffer is now wrapped because we copied max data into it. if(!l_head->times_wrap) { l_head->times_wrap = 1; } } else { // First part of buffer fits fine memcpy((UCHAR *)io_data+l_head->hdr_len, l_full_buf+l_head->hdr_len, (size_t)(l_head->next_free - l_head->hdr_len)); // If it's wrapped then pick up some more data if(l_head->times_wrap) { // Figure out how much room we have left l_part_size = *io_size - l_head->next_free; memcpy((UCHAR *)io_data+l_head->next_free, l_full_buf+TRACE_BUFFER_SIZE-l_part_size, (size_t)l_part_size); // We don't need to update *io_size, all data copied. l_head->size = *io_size; } else { // Update copied length which is what we have in trace buffer l_head->size = l_head->next_free; *io_size = l_head->next_free; } } } // CRITICAL REGION END } while(FALSE); // Always try to release even if error above if(l_lock_get) { ssx_semaphore_post(i_td_ptr->sem); // Re-enable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_exit(&l_ctx); } return(l_rc); } // Function Specification // // Name: TRAC_reset_buf // // Description: // // End Function Specification UINT TRAC_reset_buf() { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ UINT l_rc = 0; UINT l_num_des = sizeof(g_des_array) / sizeof(trace_descriptor_array_t); UINT i=0; SsxMachineContext l_ctx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // Disable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_enter(SSX_NONCRITICAL, &l_ctx); for(i=0;i<l_num_des;i++) { // Get mutex so no one traces l_rc = ssx_semaphore_pend(g_des_array[i].sem,TRAC_INTF_MUTEX_TIMEOUT); if(l_rc != SSX_OK) { // Badness FIELD("TRAC_reset_buf: Failure trying to get mutex"); } else { // Initialize the buffer l_rc = trac_init_values_buffer(g_des_array[i].entry, g_des_array[i].comp); if(l_rc) { FIELD("TRAC_reset_buf: Failure in call to trac_init_values_buffer()"); break; } } // Always try to release even if fail above ssx_semaphore_post(g_des_array[i].sem); } // Re-enable non-critical interrupts if thread context if (__ssx_kernel_context_thread()) ssx_critical_section_exit(&l_ctx); return(l_rc); } // Function Specification // // Name: trac_write_data_to_circular // // Description: // // End Function Specification uint16_t trac_write_data_to_circular(circular_entire_data_t *i_ptr) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ uint16_t l_rc = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ memcpy((void *)&g_isr_circular_buf[g_isr_circular_header.head], (void *)i_ptr, sizeof(circular_entire_data_t)); return(l_rc); } // Function Specification // // Name: get_trac_entry_data_from_circular // // Description: // // End Function Specification uint16_t get_trac_entry_data_from_circular(circular_entire_data_t *o_ptr) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ uint16_t l_rc = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ memcpy((void *)o_ptr, (void *)&g_isr_circular_buf[g_isr_circular_header.tail], sizeof(circular_entire_data_t)); return(l_rc); } <|start_filename|>src/occ_405/mode.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/mode.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _mode_h #define _mode_h #include <occ_common.h> #include <common_types.h> #include "rtls.h" #include "errl.h" // Returns the current OCC Mode #define CURRENT_MODE() G_occ_internal_mode // Returns the 'OCC Requested' OCC Mode #define REQUESTED_MODE() G_occ_internal_req_mode // Returns the 'Requested' SMS Mode #define VALID_MODE(mode) ((mode < OCC_MODE_COUNT) ? 1 : 0) // Typedef of the various modes typedef enum { OCC_MODE_NOCHANGE = 0x00, OCC_MODE_NOMINAL = 0x01, OCC_MODE_OVERSUB = 0x02, // not a settable mode, just used to store oversubscription max freq OCC_MODE_TURBO = 0x03, OCC_MODE_SAFE = 0x04, OCC_MODE_PWRSAVE = 0x05, OCC_MODE_DYN_POWER_SAVE = 0x06, OCC_MODE_MIN_FREQUENCY = 0x07, // not a settable mode, just used to store system min freq OCC_MODE_NOM_PERFORMANCE = 0x08, OCC_MODE_MAX_PERFORMANCE = 0x09, OCC_MODE_DYN_POWER_SAVE_FP = 0x0A, OCC_MODE_FFO = 0x0B, OCC_MODE_FMF = 0x0C, OCC_MODE_UTURBO = 0x0D, // not a settable mode, just used to store UT freq OCC_MODE_VRM_N = 0x0E, // not a settable mode, just used to store VRM N mode max freq // Make sure this is after the last valid mode OCC_MODE_COUNT, // These are used for mode transition table, and are not // a valid mode in and of itself. OCC_MODE_ALL = 0xFE, OCC_MODE_INVALID = 0xFF, } OCC_MODE; // These are the only modes that TMGT/HTMGT can send #define OCC_MODE_IS_VALID(mode) ((mode == OCC_MODE_NOCHANGE) || \ (mode == OCC_MODE_NOMINAL) || \ (mode == OCC_MODE_TURBO) || \ (mode == OCC_MODE_PWRSAVE) || \ (mode == OCC_MODE_DYN_POWER_SAVE) || \ (mode == OCC_MODE_NOM_PERFORMANCE) || \ (mode == OCC_MODE_MAX_PERFORMANCE) || \ (mode == OCC_MODE_DYN_POWER_SAVE_FP) || \ (mode == OCC_MODE_FFO) || \ (mode == OCC_MODE_FMF)) // Typedef of the various internal modes that OCC can be in. typedef enum { OCC_INTERNAL_MODE_NOM = 0x00, OCC_INTERNAL_MODE_SPS = 0x01, OCC_INTERNAL_MODE_DPS = 0x02, OCC_INTERNAL_MODE_DPS_MP = 0x03, OCC_INTERNAL_MODE_FFO = 0x04, OCC_INTERNAL_MODE_NOM_PERF = 0x05, OCC_INTERNAL_MODE_MAX_PERF = 0x06, OCC_INTERNAL_MODE_FMF = 0x07, OCC_INTERNAL_MODE_MAX_NUM, OCC_INTERNAL_MODE_UNDEFINED = 0xFF } OCC_INTERNAL_MODE; extern OCC_MODE G_occ_internal_mode; extern OCC_MODE G_occ_internal_req_mode; extern OCC_MODE G_occ_external_req_mode; extern OCC_MODE G_occ_external_req_mode_kvm; extern OCC_MODE G_occ_master_mode; // Returns true if we are in the middle of a mode transition inline bool SMGR_is_mode_transitioning(void); // Used to get the OCC Mode inline OCC_MODE SMGR_get_mode(void); // Used to set OCC Mode errlHndl_t SMGR_set_mode(const OCC_MODE i_mode); #endif <|start_filename|>src/tools/ffdcparser/ffdcparser.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/tools/ffdcparser/ffdcparser.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <stdio.h> #include <stdint.h> #include <sys/stat.h> #include "parser_common.h" // NOTE: This tool is to be used when FFDC is dumped by the OCC, and currently // only accepts input files in binary format. void get_thread_data(FILE* i_fhndl, thread_dump_t * i_thrd) { uint32_t i = 0; i_thrd->len = fgetc(i_fhndl); i_thrd->pri = fgetc(i_fhndl); i_thrd->state = fgetc(i_fhndl); i_thrd->flags = fgetc(i_fhndl); i_thrd->timer = get_uint32(i_fhndl); i_thrd->sem = get_uint32(i_fhndl); i_thrd->srr0 = get_uint32(i_fhndl); i_thrd->srr1 = get_uint32(i_fhndl); i_thrd->srr2 = get_uint32(i_fhndl); i_thrd->srr3 = get_uint32(i_fhndl); i_thrd->lr = get_uint32(i_fhndl); for(i = 0; i < 8; i++) i_thrd->stack_trace[i] = get_uint32(i_fhndl); } void print_thread_data(thread_dump_t * i_thrd, char* i_name) { uint32_t i = 0; printf("%s Thread Dump\n", i_name); printf("\tPriority: 0x%02X\n", i_thrd->pri); printf("\tState: 0x%02X\n", i_thrd->state); printf("\tFlags: 0x%02X\n", i_thrd->flags); printf("\tTimer: 0x%08X\n", i_thrd->timer); printf("\tSemaphore: 0x%08X\n", i_thrd->sem); printf("\tSRR0: 0x%08X\n", i_thrd->srr0); printf("\tSRR1: 0x%08X\n", i_thrd->srr1); printf("\tSRR2: 0x%08X\n", i_thrd->srr2); printf("\tSRR3: 0x%08X\n", i_thrd->srr3); printf("\tStack Trace\n"); for(i = 0; i < 8; i++) printf("\t\t%d: 0x%08X\n", i+1, i_thrd->stack_trace[i]); } void dump_ffdc(ffdc_t * data) { uint32_t i = 0; printf("Exception Code: 0x%02X\n", data->excp); printf("Checkpoint: 0x%04X\n", data->ckpt); printf("SSX Panic Code: 0x%08X\n", data->ssx_panic); printf("Panic Address: 0x%08X\n", data->panic_addr); printf("LR: 0x%08X\n", data->lr); printf("MSR: 0x%08X\n", data->msr); printf("CR: 0x%08X\n", data->cr); printf("CTR: 0x%08X\n", data->ctr); for(i = 0; i < 32; i++) printf("GPR%02d: 0x%08X\n", i, data->gpr[i]); printf("EVPR: 0x%08X\n", data->evpr); printf("XER: 0x%08X\n", data->xer); printf("ESR: 0x%08X\n", data->esr); printf("DEAR: 0x%08X\n", data->dear); printf("SRR0: 0x%08X\n", data->srr0); printf("SRR1: 0x%08X\n", data->srr1); printf("SRR2: 0x%08X\n", data->srr2); printf("SRR3: 0x%08X\n", data->srr3); printf("MCSR: 0x%08X\n", data->mcsr); printf("PID:: 0x%08X\n", data->pid); printf("ZPR: 0x%08X\n", data->zpr); printf("USPRG0: 0x%08X\n", data->usprg0); for(i = 0; i < 8; i++) printf("SPRG%d: 0x%08X\n", i, data->sprg[i]); printf("TCR: 0x%08X\n", data->tcr); printf("TSR: 0x%08X\n", data->tsr); printf("DBCR0: 0x%08X\n", data->dbcr0); printf("DBCR1: 0x%08X\n", data->dbcr1); printf("DBSR: 0x%08X\n", data->dbsr); printf("OCB_OISR0: 0x%08X\n", data->ocb_oisr0); printf("OCB_OISR1: 0x%08X\n", data->ocb_oisr1); printf("OCB_OCCMISC: 0x%08X\n", data->ocb_occmisc); printf("OCB_OHTMCR: 0x%08X\n", data->ocb_ohtmcr); printf("OCB_OIMR0: 0x%08X\n", data->ocb_oimr0); printf("OCB_OIMR1: 0x%08X\n", data->ocb_oimr1); printf("OCB_OITR0: 0x%08X\n", data->ocb_oitr0); printf("OCB_OITR1: 0x%08X\n", data->ocb_oitr1); printf("OCB_OIEPR0: 0x%08X\n", data->ocb_oiepr0); printf("OCB_OIEPR1: 0x%08X\n", data->ocb_oiepr1); printf("OCB_OEHDR: 0x%08X\n", data->ocb_oehdr); printf("OCB_OCICFG: 0x%08X\n", data->ocb_ocicfg); printf("OCB_ONISR0: 0x%08X\n", data->ocb_onisr0); printf("OCB_ONISR1: 0x%08X\n", data->ocb_onisr1); printf("OCB_OCISR0: 0x%08X\n", data->ocb_ocisr0); printf("OCB_OCISR1: 0x%08X\n", data->ocb_ocisr1); printf("OCB_OCCFLG: 0x%08X\n", data->ocb_occflg); printf("OCB_OCCHBR: 0x%08X\n", data->ocb_occhbr); printf("SSX Timebase: 0x%08X\n", data->ssx_timebase); printf("OCC Buildname: %s\n", data->buildname); printf("OCC LFIR: 0x%016X\n", data->occlfir); printf("PBA FIR: 0x%016X\n", data->pbafir); printf("Cores Deconfigured: 0x%08X\n", data->cores_deconf); print_thread_data(&data->main, "MAIN"); print_thread_data(&data->cmdh, "CMDH"); print_thread_data(&data->dcom, "DCOM"); printf("Stack Trace:\n"); for(i = 0; i < 8; i++) printf("\t%d: 0x%08X\n", i+1, data->stack_trace[i]); } int main(int argc, char** argv) { FILE* ffdc_file = NULL; ffdc_t data = {0}; uint32_t i = 0; // Verify a file was passed as an argument if(argc < 2) { fprintf(stderr, "ERROR: Requires a file with the binary FFDC data\n"); return -1; } else { ffdc_file = fopen(argv[1], "rb"); if(ffdc_file == NULL) { fprintf(stderr, "ERROR: %s cannot be opened or does not exist\n", argv[1]); return -1; } } // Get file size fseek(ffdc_file, 0, SEEK_END); const unsigned int file_size = ftell(ffdc_file); fseek(ffdc_file, 0, SEEK_SET); // Binary file is open, parse it data.seq = fgetc(ffdc_file); data.cmd = fgetc(ffdc_file); data.excp = fgetc(ffdc_file); data.len = get_uint16(ffdc_file); if (file_size < data.len) { fprintf(stderr, "WARNING: FFDC file size (%d) is less than what was expected (%d)\n", file_size, data.len); // fgetc will continue to return 0xFF once the end of file is reached } if(fseek(ffdc_file, 5, SEEK_SET)) { fprintf(stderr, "ERROR: Something happened when changing offsets in ffdc file\n"); return -1; } data.reserved = fgetc(ffdc_file); data.ckpt = get_uint16(ffdc_file); data.ssx_panic = get_uint32(ffdc_file); data.panic_addr = get_uint32(ffdc_file); data.lr = get_uint32(ffdc_file); data.msr = get_uint32(ffdc_file); data.cr = get_uint32(ffdc_file); data.ctr = get_uint32(ffdc_file); for(i = 0; i < 32; i++) data.gpr[i] = get_uint32(ffdc_file); data.evpr = get_uint32(ffdc_file); data.xer = get_uint32(ffdc_file); data.esr = get_uint32(ffdc_file); data.dear = get_uint32(ffdc_file); data.srr0 = get_uint32(ffdc_file); data.srr1 = get_uint32(ffdc_file); data.srr2 = get_uint32(ffdc_file); data.srr3 = get_uint32(ffdc_file); data.mcsr = get_uint32(ffdc_file); data.pid = get_uint32(ffdc_file); data.zpr = get_uint32(ffdc_file); data.usprg0 = get_uint32(ffdc_file); for(i = 0; i < 8; i++) data.sprg[i] = get_uint32(ffdc_file); data.tcr = get_uint32(ffdc_file); data.tsr = get_uint32(ffdc_file); data.dbcr0 = get_uint32(ffdc_file); data.dbcr1 = get_uint32(ffdc_file); data.dbsr = get_uint32(ffdc_file); data.ocb_oisr0 = get_uint32(ffdc_file); data.ocb_oisr1 = get_uint32(ffdc_file); data.ocb_occmisc = get_uint32(ffdc_file); data.ocb_ohtmcr = get_uint32(ffdc_file); data.ocb_oimr0 = get_uint32(ffdc_file); data.ocb_oimr1 = get_uint32(ffdc_file); data.ocb_oitr0 = get_uint32(ffdc_file); data.ocb_oitr1 = get_uint32(ffdc_file); data.ocb_oiepr0 = get_uint32(ffdc_file); data.ocb_oiepr1 = get_uint32(ffdc_file); data.ocb_oehdr = get_uint32(ffdc_file); data.ocb_ocicfg = get_uint32(ffdc_file); data.ocb_onisr0 = get_uint32(ffdc_file); data.ocb_onisr1 = get_uint32(ffdc_file); data.ocb_ocisr0 = get_uint32(ffdc_file); data.ocb_ocisr1 = get_uint32(ffdc_file); data.ocb_occflg = get_uint32(ffdc_file); data.ocb_occhbr = get_uint32(ffdc_file); data.ssx_timebase = get_uint32(ffdc_file); fgets(data.buildname, 16, ffdc_file); fgetc(ffdc_file); data.occlfir = get_uint64(ffdc_file); data.pbafir = get_uint64(ffdc_file); data.cores_deconf = get_uint32(ffdc_file); get_thread_data(ffdc_file, &data.main); get_thread_data(ffdc_file, &data.cmdh); get_thread_data(ffdc_file, &data.dcom); for(i=0; i<8; i++) data.stack_trace[i] = get_uint32(ffdc_file); data.eye_catcher = get_uint32(ffdc_file); dump_ffdc(&data); if(data.eye_catcher != 0xFFDCFFDC) printf("WARNING: Eye catcher(0x%08X) was not 0xFFDCFFDC\n", data.eye_catcher); if(ffdc_file != NULL) fclose(ffdc_file); return 0; } <|start_filename|>src/occ_405/pss/avsbus.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/pss/avsbus.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AVSBUS_H #define _AVSBUS_H #include <errl.h> extern bool G_avsbus_vdd_monitoring; extern bool G_avsbus_vdn_monitoring; extern uint32_t G_check_vdd_current_10mA_for_rollover; #define AVSBUS_STATUS_OVER_CURRENT_MASK 0x4000 #define AVSBUS_STATUS_UNDER_VOLTAGE_MASK 0x2000 #define AVSBUS_STATUS_OVER_TEMPERATURE_MASK 0x1000 #define AVSBUS_STATUS_OVER_POWER_MASK 0x0800 #define AVSBUS_STATUS_ONGOING 0x80000000 // o2s_ongoing #define AVSBUS_STATUS_ERRORS 0x05000000 // write_while_bridge_busy_error | FSM error typedef enum { AVSBUS_VDD = 0x00, AVSBUS_VDN = 0x01, AVSBUS_TYPE_MAX = 2 // Number of bus types } avsbus_type_e; typedef enum { // This enum contains the AVS Bus CmdDataType that can be read AVSBUS_VOLTAGE = 0x00, AVSBUS_CURRENT = 0x02, AVSBUS_TEMPERATURE = 0x03, AVSBUS_STATUS = 0x0E, AVSBUS_CMDS_MAX = 4 // Number of supported AVS bus commands } avsbus_cmdtype_e; // Setup the AVS Bus for reading void avsbus_init(); // Initiate AVS Bus read for specified cmdtype (Voltage / Current) // (results can then be read on the next tick) void initiate_avsbus_reads(avsbus_cmdtype_e i_cmdType); // Initiate read for specified type (Vdd/Vdn) and cmd (Voltage/Current/Temperature) void avsbus_read_start(const avsbus_type_e i_type, const avsbus_cmdtype_e i_cmdtype); // Process AVS Bus read results (or errors) for specified bus/cmdtype. // Returns the data requested (voltage units are mV, current units are in 10mA) // Predictive error will be logged after MAX_READ_ATTEMPTS failures on the specific // bus/cmdtype and an OCC reset will be requested uint16_t avsbus_read(const avsbus_type_e i_type, const avsbus_cmdtype_e i_cmdtype); // Initiate read of AVS Bus Status // (results can then be read on the next tick) void initiate_avsbus_read_status(); // Read the status from AVS Bus // Error history counters will be incremented for any over-current condition. void process_avsbus_status(); // Calculate chip voltage and power from AVSbus readings and update sensors void update_avsbus_power_sensors(const avsbus_type_e i_type); // Error history counters will be incremented for any over-current condition. uint32_t clear_status_errors(const uint8_t i_bus, const uint32_t i_status_mask); #endif //_AVSBUS_H <|start_filename|>src/include/registers/tpc_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/tpc_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __TPC_FIRMWARE_REGISTERS_H__ #define __TPC_FIRMWARE_REGISTERS_H__ /// \file tpc_firmware_registers.h /// \brief C register structs for the TPC unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union tpc_perv_gp3 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t tp_chiplet_chiplet_en_dc : 1; uint64_t put_in_later0 : 25; uint64_t tp_chiplet_fence_pcb_dc : 1; uint64_t put_in_later1 : 37; #else uint64_t put_in_later1 : 37; uint64_t tp_chiplet_fence_pcb_dc : 1; uint64_t put_in_later0 : 25; uint64_t tp_chiplet_chiplet_en_dc : 1; #endif // _BIG_ENDIAN } fields; } tpc_perv_gp3_t; typedef union tpc_gp0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t put_in_later0 : 40; uint64_t tc_node_id_dc : 3; uint64_t tc_chip_id_dc : 3; uint64_t put_in_later1 : 18; #else uint64_t put_in_later1 : 18; uint64_t tc_chip_id_dc : 3; uint64_t tc_node_id_dc : 3; uint64_t put_in_later0 : 40; #endif // _BIG_ENDIAN } fields; } tpc_gp0_t; typedef union tpc_gp0_and { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t put_in_later0 : 40; uint64_t tc_node_id_dc : 3; uint64_t tc_chip_id_dc : 3; uint64_t put_in_later1 : 18; #else uint64_t put_in_later1 : 18; uint64_t tc_chip_id_dc : 3; uint64_t tc_node_id_dc : 3; uint64_t put_in_later0 : 40; #endif // _BIG_ENDIAN } fields; } tpc_gp0_and_t; typedef union tpc_gp0_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t put_in_later0 : 40; uint64_t tc_node_id_dc : 3; uint64_t tc_chip_id_dc : 3; uint64_t put_in_later1 : 18; #else uint64_t put_in_later1 : 18; uint64_t tc_chip_id_dc : 3; uint64_t tc_node_id_dc : 3; uint64_t put_in_later0 : 40; #endif // _BIG_ENDIAN } fields; } tpc_gp0_or_t; typedef union tpc_hpr2 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t hang_pulse_reg : 6; uint64_t suppress_hang : 1; uint64_t _reserved0 : 57; #else uint64_t _reserved0 : 57; uint64_t suppress_hang : 1; uint64_t hang_pulse_reg : 6; #endif // _BIG_ENDIAN } fields; } tpc_hpr2_t; typedef union tpc_device_id { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cfam_id : 32; uint64_t fuse_nx_allow_crypto : 1; uint64_t fuse_vmx_crypto_dis : 1; uint64_t fuse_fp_throttle_en : 1; uint64_t reserved32 : 1; uint64_t socket_id : 3; uint64_t chippos_id : 1; uint64_t _reserved0 : 24; #else uint64_t _reserved0 : 24; uint64_t chippos_id : 1; uint64_t socket_id : 3; uint64_t reserved32 : 1; uint64_t fuse_fp_throttle_en : 1; uint64_t fuse_vmx_crypto_dis : 1; uint64_t fuse_nx_allow_crypto : 1; uint64_t cfam_id : 32; #endif // _BIG_ENDIAN } fields; } tpc_device_id_t; #endif // __ASSEMBLER__ #endif // __TPC_FIRMWARE_REGISTERS_H__ <|start_filename|>src/occ_gpe0/gpe_util.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/gpe_util.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "pk.h" #include "ppe42_scom.h" #include "pss_constants.h" #include "gpe_util.h" #include "gpe_export.h" #include <fir_data_collect.h> #include <scom_util.h> #define SPIPSS_P2S_ONGOING_MASK 0x8000000000000000 extern gpe_shared_data_t * G_gpe_shared_data; /* * Function Specification * * Name: gpe_set_ffdc * * Description: Fills up the error struct with the given data. * * End Function Specification */ void gpe_set_ffdc(GpeErrorStruct *o_error, uint32_t i_addr, uint32_t i_rc, uint64_t i_ffdc) { o_error->addr = i_addr; //Return codes defined in apss_struct.h o_error->rc = i_rc; o_error->ffdc = i_ffdc; } /* * Function Specification: * * Name: wait_spi_completion * * Description: Read the specified register (SPIPSS_P2S_STATUS_REG * or SPIPSS_ADC_STATUS_REG), and check if it's p2s_ongoing * bit is 0 (operations done). If not, wait * up to the timeout usec (~1usec per retry). * If still not clear, continue looping, * If error/reserved bits are set, a return code will be sent back * * Inputs: error: a pointer to a GpeErrorStruct, to populate rc, ffdc, * and address, in case a scom get error happens * timeout: # usec to wait for ongoing bit to clear * Register: SPIPSS_P2S_STATUS_REG or SPIPSS_ADC_STATUS_REG * * return: 0 -> Success: spi transaction completed within timeout limit * not 0 -> timeout: spi transaction did not complete within timeout * bits 0:31 are masked, and returned back for potential * analysis of the reason that the transaction timed out * * End Function Specification */ int wait_spi_completion(GpeErrorStruct *error, uint32_t reg, uint32_t i_timeout) { int i = 0; int rc = 0; uint64_t status = 0; uint32_t wait_time = 0; uint32_t num_reads = 0; if((reg != SPIPSS_P2S_STATUS_REG) && (reg != SPIPSS_ADC_STATUS_REG)) { PK_TRACE("gpe0:wait_spi_completion failed: Invalid Register 0x%08x", reg); rc = GPE_RC_INVALID_REG; gpe_set_ffdc(error, reg, rc, 0x00); } else { // Read the P2S_ONGOING bits every 10us for i_timeout, if i_timeout is less than 10 // just wait i_timeout and check once if(i_timeout >= 10) { wait_time = 10; num_reads = i_timeout / 10; } else { wait_time = i_timeout; num_reads = 1; } for (i = 0; i< num_reads; i++) { busy_wait(wait_time); rc = getscom_abs(reg, &status); if(rc) { PK_TRACE("gpe0:wait_spi_completion failed with rc = 0x%08x", rc); gpe_set_ffdc(error, reg, GPE_RC_SCOM_GET_FAILED, rc); rc = GPE_RC_SCOM_GET_FAILED; break; } // bit zero is the P2s_ONGOING / HWCTRL_ONGOING // set to 1: means operation is in progress (ONGOING) // set to 0: means operation is complete, therefore exit for loop. if((status & SPIPSS_P2S_ONGOING_MASK) == 0) { rc = 0; break; } } } // Check if timed out waiting on P2S_ONGOING / HWCTRL_ONGOING bit if (i >= num_reads) { PK_TRACE("gpe0:wait_spi_completion Timed out waiting for p2s_ongoing to clear."); rc = GPE_RC_SPI_TIMEOUT; gpe_set_ffdc(error, reg, GPE_RC_SPI_TIMEOUT, rc); } return rc; } /* * Function Specification: * * Name: busy_wait * * Description: a counting loop to simulate sleep calls, and is ISR safe. * * Inputs: i_microseconds: time to sleep in microseconds * * Note: i_microseconds must be < (2^16)/nest_freq microseconds * about 114 seconds for the fastest nest_freq supported. * return: none * * End Function Specification */ void busy_wait(uint32_t i_microseconds) { uint32_t current_count = pk_timebase32_get(); uint32_t prev_count = current_count; uint32_t timebase_zero_adjust = -current_count; uint32_t change_timeout = 0; uint32_t end_count = PK_INTERVAL_SCALE((uint32_t)PK_MICROSECONDS(i_microseconds)); while((current_count + timebase_zero_adjust) < end_count) { prev_count = current_count; current_count = pk_timebase32_get(); if(prev_count == current_count) { ++change_timeout; if(change_timeout > 32) { PK_TRACE("TIMEBASE is not moving!"); // timebase is not moving break; } } else { change_timeout = 0; } } } /* * Function Specification * * Name: ipc_scom_operation * * Description: Does a getscom or putscom for the 405 * * End Function Specification */ void ipc_scom_operation(ipc_msg_t* cmd, void* arg) { int l_rc; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; ipc_scom_op_t *scom_op = (ipc_scom_op_t*) async_cmd->cmd_data; if (scom_op->read) { l_rc = getscom_abs(scom_op->addr, &scom_op->data); if( l_rc ) { PK_TRACE("ipc_scom_operation: Error doing getscom! rc: 0x%08X addr: 0x%08X", l_rc, scom_op->addr); gpe_set_ffdc(&(scom_op->error), scom_op->addr, GPE_RC_SCOM_GET_FAILED, l_rc); } } else { l_rc = putscom_abs(scom_op->addr, scom_op->data); if( l_rc ) { PK_TRACE("ipc_scom_operation: Error doing putscom! rc: 0x%08X addr: 0x%08X", l_rc, scom_op->addr); gpe_set_ffdc(&(scom_op->error), scom_op->addr, GPE_RC_SCOM_PUT_FAILED, l_rc); } } // send back a response, IPC success even if ffdc/rc are non zeros l_rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(l_rc) { PK_TRACE("ipc_scom_operation: Failed to send response back. Halting GPE0", l_rc); gpe_set_ffdc(&(scom_op->error), 0x00, GPE_RC_IPC_SEND_FAILED, l_rc); pk_halt(); } } /* * Function Specification * * Name: ipc_fir_collection * * Description: Does fir data collection in case of a checkstop * * End Function Specification */ void ipc_fir_collection(ipc_msg_t* cmd, void* arg) { int l_rc; PK_TRACE("ipc_fir_collection: starting fir_data_collect"); fir_data_collect(); // send back a response, IPC success even if ffdc/rc are non zeros l_rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(l_rc) { PK_TRACE("ipc_fir_collection: Failed to send response back. Halting GPE0", l_rc); pk_halt(); } PK_TRACE("ipc_fir_collection: fir_data_collect finished"); } /* * Function Specification: * * Name: gpe0_nop * * Description: a function that does nothing. Called to measure IPC timing * * Inputs: none * * return: none * * End Function Specification */ void gpe0_nop(ipc_msg_t* cmd, void* arg) { int rc; ipc_async_cmd_t *async_cmd = (ipc_async_cmd_t*)cmd; nop_t *args = (nop_t*)async_cmd->cmd_data; // send back a response, IPC success even if ffdc/rc are non zeros rc = ipc_send_rsp(cmd, IPC_RC_SUCCESS); if(rc) { PK_TRACE("gpe0_nop: Failed to send response back. Halting GPE0", rc); gpe_set_ffdc(&(args->error), 0x00, GPE_RC_IPC_SEND_FAILED, rc); pk_halt(); } } <|start_filename|>src/occ_gpe0/firdata/norflash.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/norflash.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PNOR_NORFLASH_H #define __PNOR_NORFLASH_H #include <native.h> #include <pnor_mboxdd.h> /** @file norflash.H * @brief Contains constants related to specific types of * of NOR flash chips */ /** * @brief Supported NOR Chip IDs */ enum NorChipIDs { UNKNOWN_NOR_ID = 0x12345600, /**< Initial value before read */ MICRON_MFG_ID = 0x20000000, /**< Micron Mfg ID */ MICRON_NOR_ID = 0x20ba2000, /**< Micron NOR */ MACRONIX_MFG_ID = 0xC2000000, /**< Macronix Mfg ID */ MACRONIX32_NOR_ID = 0xC2201A00, /**< Macronix NOR MXxxL51235F */ MACRONIX64_NOR_ID = 0xC2201900, /**< Macronix NOR MXxxL25635F */ /* Note: Simics currently models Micron NOR */ VPO_NOR_ID = 0x20201800, /**< VPO NOR chip ID */ FAKE_NOR_ID = 0xBADBAD00, /**< ID used during fake pnor */ ID_MASK = 0xFFFFFF00, /**< Only look at 3 bytes */ MFGID_MASK = 0xFF000000, /**< Manufacturer ID is the first byte */ }; /** * @brief SPI Config Info * OP Codes and other MISC info for configuring SFC */ typedef enum { SPI_NO_OPCODE = 0x00, /**< Undefined value */ /* * Micron Flash Commands */ SPI_MICRON_FLAG_STAT = 0x70, /**< Check write/erase complete */ SPI_MICRON_CLRFLAG_STAT = 0x50, /**< Clear write/erase Status reg */ /* * Macronix Flash Commands */ SPI_MACRONIX_EN4B = 0xB7, /**< Enable Macronix 4-Byte addressing */ /* SPI protocol commands */ SPI_JEDEC_WRITE_STATUS = 0x01, /*WRSR */ SPI_JEDEC_PAGE_PROGRAM = 0x02, /*PP */ SPI_JEDEC_READ = 0x03, /*READ */ SPI_JEDEC_WRITE_DISABLE = 0x04, /*WRDI */ SPI_JEDEC_READ_STATUS = 0x05, /*RDSR */ SPI_JEDEC_WRITE_ENABLE = 0x06, /*WREN */ SPI_JEDEC_FAST_READ = 0x0B, /*FAST_READ */ SPI_JEDEC_SECTOR_ERASE = 0x20, /*SE */ SPI_JEDEC_READ_SFDP = 0x5A, /*RDSFDP */ SPI_JEDEC_CHIPID = 0x9F, /*RDID */ SPI_JEDEC_BLOCK_ERASE = 0xD8, /*BE */ } SpiConfigInfo; /** * @brief General Constants related to flash */ enum { PAGE_PROGRAM_BYTES = 256, /***< 256 bytes per PP command */ }; /** * Common format of Status Register */ typedef union { uint8_t data8; struct { uint8_t writeProtect : 1; /*0 */ uint8_t rsvd : 5; /*1:5 */ uint8_t writeEnable : 1; /*6 */ uint8_t writeInProgress : 1; /*7 */ }; } NorStatusReg_t; /** * Flags used to trigger Hardware workarounds */ enum { /* No workarounds present */ HWWK_NO_WORKAROUNDS = 0x00000000, /* Must perform 'read flag status' commands after */ /* any write or erase */ HWWK_MICRON_WRT_ERASE = 0x00000001, /* Must do a read of a low flash address before issuing read */ /* commands that return more than 1 word of data */ HWWK_MICRON_EXT_READ = 0x00000002, }; /* * Vendor-specific interfaces */ /** * @brief Check flag status bit on Micron NOR chips * The current version of Micron parts require the Flag * Status register be read after a read or erase operation, * otherwise all future operations won't work.. * * @parm i_pnorMbox Pnor Mbox Struct to operate on * * @return Error from operation */ errorHndl_t micronFlagStatus( pnorMbox_t* i_pnorMbox ); #endif <|start_filename|>src/ssx/occhw/occhw_async_ocb.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_async_ocb.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_async_ocb.c /// \brief Async driver code for OCB #include "ssx.h" #include "occhw_async.h" //////////////////////////////////////////////////////////////////////////// // Global Data //////////////////////////////////////////////////////////////////////////// OcbUnitFfdc G_ocb_ffdc = {{{{{0}}}}}; OcbQueue G_ocb_read_queue[OCB_INDIRECT_CHANNELS]; OcbQueue G_ocb_write_queue[OCB_INDIRECT_CHANNELS]; #if OCB_READ0_LENGTH % CACHE_LINE_SIZE #error "OCB read buffer 0 alignment error" #endif #if OCB_READ1_LENGTH % CACHE_LINE_SIZE #error "OCB read buffer 1 alignment error" #endif #if OCB_READ2_LENGTH % CACHE_LINE_SIZE #error "OCB read buffer 2 alignment error" #endif #if OCB_READ3_LENGTH % CACHE_LINE_SIZE #error "OCB read buffer 3 alignment error" #endif // OCB circular queue write buffers must be 8-byte aligned per hardware // restrictions, whereas read buffers are cache-line aligned and must be an // even multiple of the cache line size since they must be invalidated. Some // minor efficiencies could probably be obtained by a policy that CQ buffers // be held in non-cacheable storage (and subsequent modifications to the // device driver code). // // Due to linker restrictions, only initialized data areas can be aligned. #define OCB_CQ_WRITE_BUFFER(buffer, length) \ uint64_t buffer[length] __attribute__ ((aligned (8))) = {0} #define OCB_CQ_READ_BUFFER(buffer, length) \ uint64_t buffer[length] __attribute__ ((aligned (CACHE_LINE_SIZE))) = {0} OCB_CQ_READ_BUFFER(G_ocb_read0_buffer, OCB_READ0_LENGTH); OCB_CQ_READ_BUFFER(G_ocb_read1_buffer, OCB_READ1_LENGTH); OCB_CQ_READ_BUFFER(G_ocb_read2_buffer, OCB_READ2_LENGTH); OCB_CQ_READ_BUFFER(G_ocb_read3_buffer, OCB_READ3_LENGTH); OCB_CQ_WRITE_BUFFER(G_ocb_write0_buffer, OCB_WRITE0_LENGTH); OCB_CQ_WRITE_BUFFER(G_ocb_write1_buffer, OCB_WRITE1_LENGTH); OCB_CQ_WRITE_BUFFER(G_ocb_write2_buffer, OCB_WRITE2_LENGTH); OCB_CQ_WRITE_BUFFER(G_ocb_write3_buffer, OCB_WRITE3_LENGTH); //////////////////////////////////////////////////////////////////////////// // Local Data //////////////////////////////////////////////////////////////////////////// /// \todo These addresses could/should simply be stored with the queue objects /// to avoid these static data declarations. /// OCB Stream Push/Pull Control/Status Register addresses static const SsxAddress G_ocb_ocbsxcsn[OCB_ENGINES] = { OCB_OCBSHCS0, OCB_OCBSLCS0, OCB_OCBSHCS1, OCB_OCBSLCS1, OCB_OCBSHCS2, OCB_OCBSLCS2, OCB_OCBSHCS3, OCB_OCBSLCS3 }; /// OCB Stream Push/Pull Base Register addresses static const SsxAddress G_ocb_ocbsxbrn[OCB_ENGINES] = { OCB_OCBSHBR0, OCB_OCBSLBR0, OCB_OCBSHBR1, OCB_OCBSLBR1, OCB_OCBSHBR2, OCB_OCBSLBR2, OCB_OCBSHBR3, OCB_OCBSLBR3 }; /// OCB Stream Push/Pull Increment Register addresses static const SsxAddress G_ocb_ocbsxin[OCB_ENGINES] = { OCB_OCBSHI0, OCB_OCBSLI0, OCB_OCBSHI1, OCB_OCBSLI1, OCB_OCBSHI2, OCB_OCBSLI2, OCB_OCBSHI3, OCB_OCBSLI3 }; /// OCB Stream Error Status; There is only one register per OCB channel const SsxAddress G_ocb_ocbsesn[OCB_ENGINES / 2] = {OCB_OCBSES0, OCB_OCBSES1, OCB_OCBSES2, OCB_OCBSES3}; //////////////////////////////////////////////////////////////////////////// // OcbRequest //////////////////////////////////////////////////////////////////////////// // Collect FFDC for an OCB channel // // This is an internal API, called either due to an OCB error interrupt or a // read/write error detected during the operation. See the comments for // OcbFfdc for a description of why this particular set of data is collected. // The special channel number -1 is used to denote the direct bridge. // // OCB FFDC collection procedure: // // - Collect the OCBSCR<n> for indirect channels // // - Collect PUSH/PULL queue setup for indirect channels and disable the queues. // // - Collect the OCB FIR // // - Collect FFDC from the PLB (OCI) arbiter // // FFDC is only collected for the first error, until the error flag is reset. static void ocb_ffdc(int channel) { OcbFfdc* ffdc; ocb_ocbshcsn_t ocbshcsn; ocb_ocbslcsn_t ocbslcsn; if (channel < 0) { ffdc = &(G_ocb_ffdc.bridge); } else { ffdc = &(G_ocb_ffdc.channel[channel]); } if (ffdc->error == 0) { if (channel < 0) { memset(ffdc, 0, sizeof(OcbFfdc)); } else { //TODO: Need to get OCBCSRN another way besides scom // getscom(OCB_OCBCSRN(channel), &(ffdc->csr.value)); ffdc->shbr.value = in32(OCB_OCBSHBRN(channel)); ffdc->shcs.value = in32(OCB_OCBSHCSN(channel)); ffdc->slbr.value = in32(OCB_OCBSLBRN(channel)); ffdc->slcs.value = in32(OCB_OCBSLCSN(channel)); ocbshcsn.value = ffdc->shcs.value; ocbshcsn.fields.push_enable = 0; out32(OCB_OCBSHCSN(channel), ocbshcsn.value); ocbslcsn.value = ffdc->slcs.value; ocbslcsn.fields.pull_enable = 0; out32(OCB_OCBSLCSN(channel), ocbslcsn.value); } //TODO: Need to get OCBLFIR another way // getscom(OCB_OCCLFIR, &(ffdc->fir.value)); oci_ffdc(&(ffdc->oci_ffdc), OCI_MASTER_ID_OCB); ffdc->error = 1; } } /// Non-blocking read from an OCB PUSH (read) queue /// /// \param queue The target OcbQueue /// /// \param buf The caller's data buffer to receive the read data /// /// \param bytes The maximum number of bytes to read. This value must be an /// even multiple of 8, as this API always reads multiples of 8 bytes. /// /// \param read The number of bytes actually copied from the device buffer to /// the caller's buffer. This may be returned as any value from 0 to \a /// bytes in multiples of 8 bytes. /// /// ocb_read() implements a non-blocking copy of data from an OCB read (PUSH) /// queue data area to the caller's data area, with the side effect of /// advancing the hardware queue pointers. ocb_read() does not implement /// locking, critical sections or any other type of synchronization for access /// to the OCB queue data - that is the responsibility of the caller. /// /// ocb_read() may return an error code. This may indicate a preexisting /// error in the queue, or may be an error resulting from the current read. /// In either event any read data should be considered corrupted. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_ARGUMENT_OCB_READ The number of \a bytes is not /// an even multiple of 8. /// /// \retval -ASYNC_OCB_ERROR_READ_OLD or -ASYNC_OCB_ERROR_READ_NEW This code /// indicates an error associated with the OCB channel represented by the queue. int ocb_read(OcbQueue* queue, void* buf, size_t bytes, size_t* read) { ocb_ocbshcsn_t csr; ocb_ocbsesn_t ses; unsigned qlen, read_ptr, write_ptr, to_read; uint64_t* pcq, *pbuf; int rc; do { rc = 0; *read = 0; // If pre-existing errors exist then immediately abort the read. if (G_ocb_ffdc.channel[queue->engine / 2].error) { rc = -ASYNC_OCB_ERROR_READ_OLD; break; } if (bytes % 8) { rc = -ASYNC_INVALID_ARGUMENT_OCB_READ; break; } // Determine the number of doubleword entries remaining to be read in // the queue. The driver does not keep state, but instead reinterprets // the control/status register each time ocb_read() is called. // This may be confusing - remember that 'push' and 'pull' are from // the PIB perspective - here we use 'read' and 'write' from OCC's // perspective. csr.value = in32(G_ocb_ocbsxcsn[queue->engine]); qlen = csr.fields.push_length + 1; read_ptr = csr.fields.push_read_ptr; if (csr.fields.push_empty) { break; } else if (csr.fields.push_full) { to_read = qlen; } else { write_ptr = csr.fields.push_write_ptr; if (read_ptr > write_ptr) { to_read = qlen - (read_ptr - write_ptr); } else { to_read = write_ptr - read_ptr; } } // Copy the data from the CQ memory area to the user's buffer. For // simplicty of dealing with cache management each doubleword invokes // a line invalidate before refetching the fresh data from // memory. Alignment requirements enforced on the data buffer // guarantee the buffers are cache-line aligned and each doubleword is // fully contained in a single D-cache line. // // Here the code models the evolution of the read_ptr as each datum is // copied from the queue. pbuf = (uint64_t*)buf; while (bytes && to_read--) { read_ptr++; if (read_ptr == qlen) { read_ptr = 0; } pcq = queue->cq_base + read_ptr; dcache_invalidate_line(pcq); *pbuf++ = *pcq; out32(G_ocb_ocbsxin[queue->engine], 0); bytes -= 8; *read += 8; } } while (0); // Check for underflow errors. If found, collect FFDC. ses.value = in32(G_ocb_ocbsesn[queue->engine / 2]); if (ses.fields.push_read_underflow) { ocb_ffdc(queue->engine / 2); rc = -ASYNC_OCB_ERROR_READ_NEW; } return rc; } /// Non-blocking write to an OCB PULL (write) queue /// /// \param queue The target OcbQueue /// /// \param buf The caller's data buffer containing the write data /// /// \param bytes The maximum number of bytes to write. This value must be an /// even multiple of 8, as this API always writes multiples of 8 bytes. /// /// \param written The number of bytes actually copied from the caller's buffer to /// the device buffer. This may be returned as any value from 0 to \a /// bytes in multiples of 8 bytes. /// /// ocb_write() implements a non-blocking copy of data to an OCB write (PULL) /// queue, with the side effect of advancing the hardware queue pointers. /// ocb_write() does not implement locking, critical sections or any other /// type of synchronization for access to the OCB queue data - that is the /// responsibility of the caller. /// /// ocb_write() may return an error code. This may indicate a preexisting /// error in the queue, or may be an error resulting from the current write. /// In either event any write data should be considered corrupted/nondelivered. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_ARGUMENT_OCB_WRITE The number of \a bytes is not /// an even multiple of 8. /// /// \retval -ASYNC_OCB_ERROR_WRITE_OLD or -ASYNC_OCB_ERROR_WRITE_NEW This code /// indicates an error associated with the OCB channel represented by the queue. int ocb_write(OcbQueue* queue, void* buf, size_t bytes, size_t* written) { ocb_ocbslcsn_t csr; ocb_ocbsesn_t ses; unsigned qlen, read_ptr, write_ptr, free; uint64_t* pcq, *pbuf; int rc; do { rc = 0; *written = 0; // Pre-existing errors immediately abort the read. if (G_ocb_ffdc.channel[queue->engine / 2].error) { rc = -ASYNC_OCB_ERROR_WRITE_OLD; break; } if (bytes % 8) { rc = -ASYNC_INVALID_ARGUMENT_OCB_WRITE; break; } // Determine the number of free doubleword entries remaining in the // queue. The driver does not keep state, but instead reinterprets the // control/status register each time the write method is called. // This is confusing - remember that 'push' and 'pull' are from the PIB // perspective - here we use 'read' and 'write' from OCC's perspective. csr.value = in32(G_ocb_ocbsxcsn[queue->engine]); qlen = csr.fields.pull_length + 1; write_ptr = csr.fields.pull_write_ptr; if (csr.fields.pull_full) { break; } if (csr.fields.pull_empty) { free = qlen; } else { read_ptr = csr.fields.pull_read_ptr; if (write_ptr > read_ptr) { free = qlen - (write_ptr - read_ptr); } else { free = read_ptr - write_ptr; } } // Copy the data into the CQ memory area. For simplicty of dealing // with cache management each doubleword invokes a line flush before // incrementing the hardware pointer. Alignment requirements enforced // on the data buffer guarantee each doubleword is fully contained in // a single D-cache line. // // Here the code models the evolution of the write_ptr as each datum is // copied into the queue. pbuf = (uint64_t*)buf; while (bytes && free--) { write_ptr++; if (write_ptr == qlen) { write_ptr = 0; } pcq = queue->cq_base + write_ptr; *pcq = *pbuf++; dcache_flush_line(pcq); in32(G_ocb_ocbsxin[queue->engine]); bytes -= 8; *written += 8; } } while (0); // Check for overflow. If found, collect FFDC. ses.value = in32(G_ocb_ocbsesn[queue->engine / 2]); if (ses.fields.pull_write_overflow) { ocb_ffdc(queue->engine / 2); rc = -ASYNC_OCB_ERROR_WRITE_NEW; } return rc; } // This is the internal 'run method' for reading through an OCB circular // queue. The run method simply enables the IRQ. The interrupt handler reads // data from the queue and leaves the interrupt enabled until the read is // satisfied. static int ocb_read_method(AsyncRequest* async_request) { OcbRequest* request = (OcbRequest*)async_request; OcbQueue* queue = (OcbQueue*)(async_request->queue); int rc; if (request->bytes == 0) { rc = -ASYNC_REQUEST_COMPLETE; } else { ssx_irq_enable(queue->irq); rc = 0; } return rc; } // This is the internal 'run method' for writing through an OCB circular // queue. The run method simply enables the IRQ. The interrupt handler writes // data from the queue and leaves the interrupt enabled until the write is // satisfied. static int ocb_write_method(AsyncRequest* async_request) { OcbRequest* request = (OcbRequest*)async_request; OcbQueue* queue = (OcbQueue*)(async_request->queue); int rc; if (request->bytes == 0) { rc = -ASYNC_REQUEST_COMPLETE; } else { ssx_irq_enable(queue->irq); rc = 0; } return rc; } // The async error method for OCB // // Collect FFDC. The return of -1 will disable the channel associated with // the request. static int ocb_async_error_method(AsyncRequest* request) { OcbQueue* queue = (OcbQueue*)(request->queue); ocb_ffdc(queue->engine / 2); return -1; } /// Create a request for an OCB circular queue /// /// \param request An uninitialized or otherwise idle OcbRequest. /// /// \param queue An async queue for an OCB circular buffer. The queue \a /// engine determines whether this is a read or write request. /// /// \param data A pointer to the data to be moved (for write) or where the /// data should be placed (for read). /// /// \param bytes The number of bytes of data to move. The OCB /// circular buffers always move multiples of 8 bytes, and the number of bytes /// must be a multiple of 8. Higher-level abstractions will have to take care /// of cases where the numbers of bytes are not multiples of 8. /// /// \param timeout If not specified as SSX_WAIT_FOREVER, then this request /// will be governed by a private watchdog timer that will cancel a queued job /// or kill a running job if the hardware operation does not complete before /// it times out. /// /// \param callback The callback to execute when the data move completes, or /// NULL (0) to indicate no callback. /// /// \param arg The parameter to the callback routine; ignored if the \a /// callback is NULL. /// /// \param options Options to control request priority, callback context and /// blocking. /// /// This routine has no way to know if the OcbRequest structure is currently /// in use, so this API should only be called on uninitialized or otherwise /// idle OcbRequest structures. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_OCB_REQUEST The \a request or \a queue were NULL (0), or /// the \a queue is not an initialized OcbQueue. /// /// \retval -ASYNC_INVALID_ARGUMENT_OCB_REQUEST The \a data pointer is /// NULL (0), or the number of bytes is not a multiple of 8. /// /// See async_request_create() for other errors that may be returned by this /// call. int ocb_request_create(OcbRequest* request, OcbQueue* queue, uint64_t* data, size_t bytes, SsxInterval timeout, AsyncRequestCallback callback, void* arg, int options) { int rc; AsyncRunMethod run_method = 0; // Make GCC Happy AsyncQueue* async_queue = (AsyncQueue*)queue; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request == 0) || (queue == 0) || !(async_queue->engine & ASYNC_ENGINE_OCB), ASYNC_INVALID_OBJECT_OCB_REQUEST); SSX_ERROR_IF((data == 0) || (bytes % 8), ASYNC_INVALID_ARGUMENT_OCB_REQUEST); } switch (async_queue->engine) { case ASYNC_ENGINE_OCB_PULL0: case ASYNC_ENGINE_OCB_PULL1: case ASYNC_ENGINE_OCB_PULL2: case ASYNC_ENGINE_OCB_PULL3: run_method = ocb_write_method; break; case ASYNC_ENGINE_OCB_PUSH0: case ASYNC_ENGINE_OCB_PUSH1: case ASYNC_ENGINE_OCB_PUSH2: case ASYNC_ENGINE_OCB_PUSH3: run_method = ocb_read_method; break; } rc = async_request_create(&(request->request), async_queue, run_method, ocb_async_error_method, timeout, callback, arg, options); request->data = data; request->bytes = bytes; return rc; } /// Schedule a request on an OCB circular queue. /// /// \param request An initialized OcbRequest /// /// Note : As long as the OcbRequest is idle, the application is free to /// directly change the \a data and \a bytes fields to read/write different /// numbers of bytes to/from different locations the next time the request is /// scheduled. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_ARGUMENT_OCB_SCHEDULE The number of \a bytes /// currently requested is not a multiple of 8. /// /// See async_request_schedule() for documentation of other errors int ocb_request_schedule(OcbRequest* request) { if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF((request->bytes % 8), ASYNC_INVALID_ARGUMENT_OCB_SCHEDULE); } request->current = request->data; request->remaining = request->bytes; return async_request_schedule((AsyncRequest*)request); } //////////////////////////////////////////////////////////////////////////// // OcbQueue //////////////////////////////////////////////////////////////////////////// /// Reset an OCB circular PUSH (read) queue /// /// This API is normally used during initialization, and assumes that all of /// the parameters are valid. It resets and reprograms the hardware /// associated with an OCB circular buffer to be consistent with the queue /// engine, base address, length and interrupt protocol. The queue is enabled /// and its interrupts are disabled. Any data in the queue will be silently /// lost. /// /// Note that this API \e does \e not put the OCB channel into circular mode - /// the communication method is controlled by the communication partner. /// /// The function of this routine is to write a new value into the OCB Stream /// Push Control/Status register, which as a side effect resets the circular /// buffer. The base register is also set up. void ocb_read_engine_reset(OcbQueue* queue, size_t cq_length, int protocol) { ocb_ocbshcsn_t cs; // Disable interrupts and disable and clear the queue. The queue length // field is updated (for informational purposes). Interrupts will be // re-enabled when requests are made for the queue. ssx_irq_disable(queue->irq); queue->cq_length = cq_length; cs.value = 0; out32(G_ocb_ocbsxcsn[queue->engine], cs.value); // Reinitialize the data buffer base address register out32(G_ocb_ocbsxbrn[queue->engine], (uint32_t)(queue->cq_base)); // Reprogram and reenable/reset the queue if (protocol == OCB_INTERRUPT_PROTOCOL_LAZY) { cs.fields.push_intr_action = OCB_INTR_ACTION_FULL; } else { cs.fields.push_intr_action = OCB_INTR_ACTION_NOT_EMPTY; } cs.fields.push_length = cq_length - 1; cs.fields.push_enable = 1; out32(G_ocb_ocbsxcsn[queue->engine], cs.value); } /// Reset an OCB circular PULL (write) queue /// /// This API is normally used during initialization, and assumes that all of /// the parameters are valid. It resets and reprograms the hardware /// associated with an OCB circular buffer to be consistent with the queue /// engine, base address, length and interrupt protocol. The queue is enabled /// and its interrupts are disabled. Any data in the queue will be silently /// lost. /// /// Note that this API \e does \e not put the OCB channel into circular mode - /// the communication method is controlled by the communication partner. /// /// The function of this routine is to write a new value into the OCB Stream /// Pull Control/Status register, which as a side effect resets the circular /// buffer. The base register is also set up. void ocb_write_engine_reset(OcbQueue* queue, size_t cq_length, int protocol) { ocb_ocbslcsn_t cs; // Disable interrupts and disable and clear the queue. The queue length // field is updated (for informational purposes). Interrupts will be // re-enabled when requests are made for the queue. ssx_irq_disable(queue->irq); queue->cq_length = cq_length; cs.value = 0; out32(G_ocb_ocbsxcsn[queue->engine], cs.value); // Reinitialize the data buffer base address register out32(G_ocb_ocbsxbrn[queue->engine], (uint32_t)(queue->cq_base)); // Reprogram and reenable/reset the queue if (protocol == OCB_INTERRUPT_PROTOCOL_LAZY) { cs.fields.pull_intr_action = OCB_INTR_ACTION_EMPTY; } else { cs.fields.pull_intr_action = OCB_INTR_ACTION_NOT_FULL; } cs.fields.pull_length = cq_length - 1; cs.fields.pull_enable = 1; out32(G_ocb_ocbsxcsn[queue->engine], cs.value); } /// Create (initialize) an OcbQueue /// /// \param queue An uninitialized or otherwise idle OcbQueue /// /// \param engine A valid OCB engine id /// /// \param cq_base The base address of the circular queue data area for the /// queue. This address must be 8-byte aligned for write queues. Read queues /// must be cache-line aligned and a multiple of the cache line in size. /// /// \param cq_length The length of the circular queue measured in 8-byte /// increments. /// /// \param protocol The interrupt protocol, either OCB_PUSH_PULL_PROTOCOL_LAZY /// or OCB_PUSH_PULL_PROTOCOL_AGGRESSIVE. Lazy means that read queues only /// interrupt when empty, and write queues only interrupt when full. /// Agressive means that read queues interrupt when not empty and write queues /// interrupt when not full. In general the lazy read protocol will only work /// for 1) queues of length 1, where lazy == aggressive, and 2) protocols /// where a known fixed number of 8-byte entries is always expected to be /// received. /// /// \retval 0 Success /// /// \retval -ASYNC_INVALID_OBJECT_OCB_QUEUE The \a queue was NULL (0). /// /// \retval -ASYNC_INVALID_ARGUMENT_OCB_QUEUE The \a cq_base is not properly /// aligned, or the \a cq_length is invalid, or the \a protocol is invalid. /// /// \retval -ASYNC_INVALID_ENGINE_OCB The \a engine is not an OCB engine. /// /// Other errors may be returned by async_queue_create(). int ocb_queue_create(OcbQueue* queue, int engine, uint64_t* cq_base, size_t cq_length, int protocol) { AsyncQueue* async_queue = (AsyncQueue*)queue; int align_mask = 0; if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(queue == 0, ASYNC_INVALID_OBJECT_OCB_QUEUE); SSX_ERROR_IF((cq_length < OCB_PUSH_PULL_LENGTH_MIN) || (cq_length > OCB_PUSH_PULL_LENGTH_MAX) || ((protocol != OCB_INTERRUPT_PROTOCOL_LAZY) && (protocol != OCB_INTERRUPT_PROTOCOL_AGGRESSIVE)), ASYNC_INVALID_ARGUMENT_OCB_QUEUE); } queue->cq_base = cq_base; queue->cq_length = cq_length; switch (engine) { // These are the read engines from OCC's perspective. case ASYNC_ENGINE_OCB_PUSH0: queue->irq = OCCHW_IRQ_STRM0_PUSH; queue->engine = OCB_ENGINE_PUSH0; goto read_engine; case ASYNC_ENGINE_OCB_PUSH1: queue->irq = OCCHW_IRQ_STRM1_PUSH; queue->engine = OCB_ENGINE_PUSH1; goto read_engine; case ASYNC_ENGINE_OCB_PUSH2: queue->irq = OCCHW_IRQ_STRM2_PUSH; queue->engine = OCB_ENGINE_PUSH2; goto read_engine; case ASYNC_ENGINE_OCB_PUSH3: queue->irq = OCCHW_IRQ_STRM3_PUSH; queue->engine = OCB_ENGINE_PUSH3; goto read_engine; read_engine: align_mask = CACHE_LINE_SIZE - 1; async_queue_create(async_queue, engine); ocb_read_engine_reset(queue, cq_length, protocol); break; // These are the write engines from OCC's perspective. case ASYNC_ENGINE_OCB_PULL0: queue->irq = OCCHW_IRQ_STRM0_PULL; queue->engine = OCB_ENGINE_PULL0; goto write_engine; case ASYNC_ENGINE_OCB_PULL1: queue->irq = OCCHW_IRQ_STRM1_PULL; queue->engine = OCB_ENGINE_PULL1; goto write_engine; case ASYNC_ENGINE_OCB_PULL2: queue->irq = OCCHW_IRQ_STRM2_PULL; queue->engine = OCB_ENGINE_PULL2; goto write_engine; case ASYNC_ENGINE_OCB_PULL3: queue->irq = OCCHW_IRQ_STRM3_PULL; queue->engine = OCB_ENGINE_PULL3; goto write_engine; write_engine: align_mask = 8 - 1; async_queue_create(async_queue, engine); ocb_write_engine_reset(queue, cq_length, protocol); break; default: if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(1, ASYNC_INVALID_ENGINE_OCB); } } if (SSX_ERROR_CHECK_API) { SSX_ERROR_IF(((uint32_t)cq_base & align_mask) != 0, ASYNC_INVALID_ARGUMENT_OCB_QUEUE2); } return 0; } // The interrupt handler for asynchronous OCB CQ requests // // The circular buffer interupts are level sensitive, active high. There is // really no way to 'clear' them as they indicate a permanent status - so // instead they need to be enabled and disabled. Interrupts are enabled by the // run methods and disabled by the interrupt handlers once all data has been // transferred (or in the event of an error). // // This interrupt handler can process up to 256 bytes at once, plus the // overhead of scheduling the next job when this one completes. If interrupt // latency becomes a problem then this process could be run with interrupt // preemption enabled. SSX_IRQ_FAST2FULL(ocb_async_handler, ocb_async_handler_full); void ocb_async_handler_full(void* arg, SsxIrqId irq, int priority) { AsyncQueue* async_queue = (AsyncQueue*)arg; OcbQueue* queue = (OcbQueue*)async_queue; OcbRequest* request = (OcbRequest*)(async_queue->current); size_t processed; int rc; if (SSX_ERROR_CHECK_KERNEL && (request == 0)) { SSX_PANIC(ASYNC_PHANTOM_INTERRUPT_OCB); } if (queue->engine % 2) { rc = ocb_write(queue, request->current, request->remaining, &processed); } else { rc = ocb_read(queue, request->current, request->remaining, &processed); } if (rc) { ssx_irq_disable(queue->irq); async_error_handler(async_queue, ASYNC_REQUEST_STATE_FAILED); } else if (processed == request->remaining) { ssx_irq_disable(queue->irq); async_handler(async_queue); } else { request->current += (processed / 8); request->remaining -= processed; } } // The interrupt handler for the OCB error interrupt. // // There is one interrupt that covers all OCB indirect channels as well as the // direct bridge. When this interrupt fires we try to determine which unit is // responsible. If the error appears to be associated with a job running as // part of the async mechanism then we let the async_error_handler() mechanism // operate, otherwise simply collect FFDC. The \a error field of the FFDC // structure stops non-queued read/write requests. Note that we kill both read // and write jobs without regard to the error. // // If the error is due to the direct bridge we collect FFDC, but can't really // do anything else. /// \todo What action to take for bridge errors? SSX_IRQ_FAST2FULL(ocb_error_handler, ocb_error_handler_full); void ocb_error_handler_full(void* arg, SsxIrqId irq, int priority) { ocb_occlfir_t fir = {0}; ocb_occlfir_t fir_temp; int channel; AsyncQueue* queue; ssx_irq_status_clear(irq); // TODO: Need to get OCCLFIR another way // getscom(OCB_OCCLFIR, &(fir.value)); fir_temp.value = 0; fir_temp.fields.ocb_idc0_error = 1; for (channel = 0; channel < OCB_INDIRECT_CHANNELS; channel++) { if (fir.value & (fir_temp.value >> channel)) { queue = (AsyncQueue*)(&(G_ocb_read_queue[channel])); if (queue->state == ASYNC_QUEUE_STATE_RUNNING) { async_error_handler(queue, ASYNC_REQUEST_STATE_FAILED); } else { ocb_ffdc(channel); } queue = (AsyncQueue*)(&(G_ocb_write_queue[channel])); if (queue->state == ASYNC_QUEUE_STATE_RUNNING) { async_error_handler(queue, ASYNC_REQUEST_STATE_FAILED); } else { ocb_ffdc(channel); } } } if (fir.fields.ocb_db_oci_timeout | fir.fields.ocb_db_oci_read_data_parity | fir.fields.ocb_db_oci_slave_error | fir.fields.ocb_pib_addr_parity_err | fir.fields.ocb_db_pib_data_parity_err) { ocb_ffdc(-1); } } //////////////////////////////////////////////////////////////////////////// // Initialization //////////////////////////////////////////////////////////////////////////// void async_ocb_initialize(OcbQueue* queue, int engine, uint64_t* buffer, size_t length, int protocol) { ocb_queue_create(queue, engine, buffer, length, protocol); async_level_handler_setup(ocb_async_handler, (void*)queue, queue->irq, SSX_NONCRITICAL, SSX_IRQ_POLARITY_ACTIVE_HIGH); // Driver manages IRQ enable/disable } <|start_filename|>src/occ_405/sensor/sensor_get_tod_task.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/sensor/sensor_get_tod_task.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file sensor_get_tod_task.c * * This file defines the functions and global variables for the task that gets * the current Time Of Day (TOD). * * The register holding the time of day value is read via a SCOM address, and * the OCC 405 cannot read from this address. To work around this, the IPC * framework is used to request GPE0 to read the register value. GPE0 returns * the current time of day value using a GPE_BUFFER. */ //****************************************************************************** // Includes //****************************************************************************** #include <sensor_get_tod_task.h> // Primary header #include <stdint.h> // For uint*_t #include <common_types.h> // For bool #include <sensor.h> // For G_tod #include <occ_common.h> // For GPE_BUFFER #include <occ_service_codes.h> // For OCC reason codes #include <sensor_service_codes.h> // For GET_TOD_*_MOD module ids #include <trac.h> // For trace macros #include <errl.h> // For error logging functions and types #include <occhw_async.h> // For gpe_request_*(), async_request_is_idle() #include <get_tod_structs.h> // For gpe_get_tod_args_t and TOD_VALUE_UNKNOWN #include <occ_sys_config.h> // For G_sysConfigData //****************************************************************************** // Defines //****************************************************************************** /** * Number of errors before we trace. */ #define GET_TOD_ERRORS_BEFORE_TRACE 1 /** * Number of errors before we set G_tod to TOD_VALUE_UNKNOWN. */ #define GET_TOD_ERRORS_BEFORE_UNKNOWN 4 /** * Number of errors before we log the error. */ #define GET_TOD_ERRORS_BEFORE_LOG 16 /** * Maximum number of errors to count. Must fit in a uint8_t. */ #define GET_TOD_MAX_ERRORS GET_TOD_ERRORS_BEFORE_LOG //****************************************************************************** // Structs and Enums //****************************************************************************** /** * Type of data to store in the user details section of an error log. */ typedef enum { GET_TOD_ERRL_USR_DTLS_NONE, ///< No data to store GET_TOD_ERRL_USR_DTLS_GPE_FFDC, ///< ffdc value from GPE0 in G_get_tod_args GET_TOD_ERRL_USR_DTLS_GPE_TRACE, ///< get GPE0 trace buffer } GET_TOD_ERRL_USR_DTLS_DATA; //****************************************************************************** // Globals //****************************************************************************** /** * Buffer holding arguments for the IPC function. Used to pass data to/from GPE0. */ GPE_BUFFER(gpe_get_tod_args_t G_get_tod_args); /** * GPE request structure. Used by GPE functions to schedule request. */ GpeRequest G_get_tod_request; /** * Specifies whether the GPE request was scheduled. If false, the request * finished or has never been scheduled/initialized. */ bool G_get_tod_req_scheduled = false; /** * Specifies whether the results of the GPE request are available. Must be * declared volatile since it is used by both regular and callback functions. */ volatile bool G_get_tod_results_available = false; /** * Number of consecutive errors that have occurred. Cleared when we * successfully obtain the current time of day. */ uint8_t G_get_tod_error_count = 0; /** * Specifies whether this task is enabled. If the task is disabled it will no * longer attempt to get the current time of day. */ bool G_get_tod_enabled = true; /** * GPE shared data area for gpe0 tracebuffer and size */ extern gpe_shared_data_t G_shared_gpe_data; //****************************************************************************** // Private Functions //****************************************************************************** /** * Increment the error count. */ void get_tod_increment_error_count() { // Increment error count if we are below the maximum if (G_get_tod_error_count < GET_TOD_MAX_ERRORS) { ++G_get_tod_error_count; } // Set time of day to unknown if needed if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_UNKNOWN) { G_tod = TOD_VALUE_UNKNOWN; } } /** * Clear the error count. * * If there had previously been errors, trace that we have recovered. */ void get_tod_clear_error_count() { // If one or more errors had occurred if (G_get_tod_error_count > 0) { // Trace that we recovered TRAC_INFO("get_tod_clear_error_count: Task recovered after %u errors", G_get_tod_error_count); // Clear error count G_get_tod_error_count = 0; } } /** * Logs and commits an unrecoverable error. Calls out the processor. Creates a * user details section if needed containing the specified additional data. * Does nothing if an error has already been logged. * * Disables this task. We will no longer try to read the current time of day. * * Note that the required error log comment containing tags like 'userdata4' and * 'devdesc' must be located by the call to this function. It is not located * inside this function because the value of those tags varies. * * @param i_modId Module ID * @param i_reasonCode Reason code * @param i_extReasonCode Extended reason code * @param i_userData1 Userdata1 value * @param i_userData2 Userdata2 value * @param i_usrDtlsData Data to store in a user details section (if any) */ void get_tod_log_error(uint16_t i_modId, uint8_t i_reasonCode, uint16_t i_extReasonCode, uint32_t i_userData1, uint32_t i_userData2, GET_TOD_ERRL_USR_DTLS_DATA i_usrDtlsData) { // Exit if we have already logged an error static bool L_error_logged = false; if (L_error_logged) { return; } // Create unrecoverable error errlHndl_t l_errl = createErrl(i_modId, // Module ID i_reasonCode, // Reason code i_extReasonCode, // Extended reason code ERRL_SEV_UNRECOVERABLE, // Severity NULL, // Trace Buffers DEFAULT_TRACE_SIZE, // Trace Size i_userData1, // Userdata1 i_userData2); // Userdata2 // If specified, add user details section to hold ffdc field from GPE if (i_usrDtlsData == GET_TOD_ERRL_USR_DTLS_GPE_FFDC) { addUsrDtlsToErrl(l_errl, (uint8_t *) &(G_get_tod_args.error.ffdc), sizeof(G_get_tod_args.error.ffdc), ERRL_USR_DTL_STRUCT_VERSION_1, ERRL_USR_DTL_BINARY_DATA); } if (i_usrDtlsData == GET_TOD_ERRL_USR_DTLS_GPE_TRACE) { addUsrDtlsToErrl(l_errl, (uint8_t *) G_shared_gpe_data.gpe0_tb_ptr, G_shared_gpe_data.gpe0_tb_sz, ERRL_USR_DTL_STRUCT_VERSION_1, ERRL_USR_DTL_TRACE_DATA); } // Add processor callout addCalloutToErrl(l_errl, ERRL_CALLOUT_TYPE_HUID, G_sysConfigData.proc_huid, ERRL_CALLOUT_PRIORITY_MED); // Commit error commitErrl(&l_errl); L_error_logged = true; // Disable this task TRAC_ERR("get_tod_log_error: Disabled task due to logging an error"); G_get_tod_enabled = false; } /** * Returns whether the global GPE request struct is idle and ready for re-use. * Returns true immediately if the request was not scheduled. If the request * was scheduled, checks to see if it has finished. * * @return true if GPE request is idle, false otherwise */ bool get_tod_is_request_idle(void) { // If the request was not previously scheduled, then it is idle. This also // handles the case where the request has not been initialized yet. if (!G_get_tod_req_scheduled) { return true; } // Request was scheduled; check if it finished and is now idle if (async_request_is_idle(&G_get_tod_request.request)) { // Request is now idle and ready for re-use G_get_tod_req_scheduled = false; return true; } // Request was scheduled but has not finished. Increment error count. get_tod_increment_error_count(); // Trace if necessary if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_TRACE) { TRAC_ERR("get_tod_is_request_idle: Waiting for request to finish"); } // Log error if necessary if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_LOG) { /* @ * @errortype * @moduleid GET_TOD_IS_REQ_IDLE_MOD * @reasoncode GPE_REQUEST_TASK_NOT_IDLE * @userdata1 0 * @userdata2 0 * @userdata4 ERC_GENERIC_TIMEOUT * @devdesc GPE request not finished after waiting repeatedly */ get_tod_log_error(GET_TOD_IS_REQ_IDLE_MOD, GPE_REQUEST_TASK_NOT_IDLE, ERC_GENERIC_TIMEOUT, 0, 0, GET_TOD_ERRL_USR_DTLS_GPE_TRACE); } // Return false since request is not idle return false; } /** * Callback that is invoked when the GPE request completes. * * @param i_arg Callback argument specified during gpe_request_create(). Not used. */ int get_tod_callback(void * i_arg) { // NOTE: No tracing allowed in callback functions // If GPE request was successful copy current time of day into G_tod. We do // this in a callback so G_tod is updated as soon as possible. if (G_get_tod_args.error.rc == GPE_RC_SUCCESS) { G_tod = G_get_tod_args.tod; } // Set flag indicating results of GPE request are available. Any errors // will be handled later since callbacks cannot trace. G_get_tod_results_available = true; // Return 0 indicating to async framework that callback ran successfully return 0; } /** * Handles the results of the previous GPE request. */ void get_tod_handle_request_results(void) { // Check if results from previous GPE request are available if (!G_get_tod_results_available) { // No results available, so there is nothing to do. There was no // previous request, or previous request didn't complete due to errors. return; } // Check whether GPE request successfully read time of day if (G_get_tod_args.error.rc == GPE_RC_SUCCESS) { // Request succeeded. Callback already set G_tod. Clear error counter. get_tod_clear_error_count(); } else { // Request failed to read time of day; increment error count get_tod_increment_error_count(); // Trace if needed if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_TRACE) { TRAC_ERR("get_tod_handle_request_results: GPE0 error reading TOD register: " "addr=0x%08X, rc=0x%08X, ffdc=0x%08X%08X", G_get_tod_args.error.addr, G_get_tod_args.error.rc, (uint32_t) (G_get_tod_args.error.ffdc >> 32), (uint32_t) (G_get_tod_args.error.ffdc & 0x00000000FFFFFFFFull)); } // Log error if needed if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_LOG) { /* @ * @errortype * @moduleid GET_TOD_HNDL_REQ_RSLT_MOD * @reasoncode GPE_REQUEST_RC_FAILURE * @userdata1 SCOM address * @userdata2 RC from GPE IPC function * @userdata4 ERC_GETSCOM_FAILURE * @devdesc GPE request to read SCOM TOD register failed */ get_tod_log_error(GET_TOD_HNDL_REQ_RSLT_MOD, GPE_REQUEST_RC_FAILURE, ERC_GETSCOM_FAILURE, G_get_tod_args.error.addr, G_get_tod_args.error.rc, GET_TOD_ERRL_USR_DTLS_GPE_FFDC); } } // Clear flag since we handled the results of the previous GPE request G_get_tod_results_available = false; } /** * Schedules a GPE request to read the TOD register to get current time of day. */ void get_tod_schedule_request(void) { // Create (initialize) GPE request if needed static bool L_request_created = false; if (!L_request_created) { int l_rc = gpe_request_create(&G_get_tod_request, // GpeRequest &G_async_gpe_queue0, // Queue for GPE0 IPC_ST_GET_TOD_FUNCID, // IPC Function ID &G_get_tod_args, // IPC Command Data SSX_WAIT_FOREVER, // Timeout (none) get_tod_callback, // Callback NULL, // Callback argument ASYNC_CALLBACK_IMMEDIATE); // Options if (l_rc != 0) { // Create failed; trace and log error, then exit. Ignore error // count because we don't retry creates. TRAC_ERR("get_tod_schedule_request: Request create failure: rc=0x%08X", l_rc); /* @ * @errortype * @moduleid GET_TOD_SCHED_REQ_MOD * @reasoncode GPE_REQUEST_CREATE_FAILURE * @userdata1 Return code from gpe_request_create() * @userdata2 0 * @userdata4 OCC_NO_EXTENDED_RC * @devdesc Failed to create GPE request */ get_tod_log_error(GET_TOD_SCHED_REQ_MOD, GPE_REQUEST_CREATE_FAILURE, OCC_NO_EXTENDED_RC, l_rc, 0, GET_TOD_ERRL_USR_DTLS_NONE); return; } L_request_created = true; } // Schedule GPE request int l_rc = gpe_request_schedule(&G_get_tod_request); if (l_rc != 0) { // Schedule failed; increment error count get_tod_increment_error_count(); // Trace if needed if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_TRACE) { TRAC_ERR("get_tod_schedule_request: Request schedule failure: rc=0x%08X", l_rc); } // Log error if needed if (G_get_tod_error_count == GET_TOD_ERRORS_BEFORE_LOG) { /* @ * @errortype * @moduleid GET_TOD_SCHED_REQ_MOD * @reasoncode GPE_REQUEST_SCHEDULE_FAILURE * @userdata1 Return code from gpe_request_schedule() * @userdata2 0 * @userdata4 OCC_NO_EXTENDED_RC * @devdesc Failed to schedule GPE request */ get_tod_log_error(GET_TOD_SCHED_REQ_MOD, GPE_REQUEST_SCHEDULE_FAILURE, OCC_NO_EXTENDED_RC, l_rc, 0, GET_TOD_ERRL_USR_DTLS_NONE); } return; } // Successfully scheduled request. Request is not blocking, so we will not // get the results until later. Set flag indicating request is scheduled. G_get_tod_req_scheduled = true; } //****************************************************************************** // Public Functions //****************************************************************************** // See description in header file void task_get_tod(task_t * i_self) { // Exit if this task is disabled if (!G_get_tod_enabled) { return; } // Exit if the previous GPE request has not finished if (!get_tod_is_request_idle()) { return; } // Handle results of previous GPE request get_tod_handle_request_results(); if (!G_get_tod_enabled) { // Task disabled due to errors while handling request results return; } // Schedule new GPE request to get time of day get_tod_schedule_request(); } <|start_filename|>src/occ_gpe0/nest_dts.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_gpe0/nest_dts.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <nest_dts.h> #include <ppe42_msr.h> #include <ppe42_scom.h> uint32_t get_nest_dts(NestDts_t* o_data) { uint64_t value64 = 0; uint64_t* ptr = (uint64_t*)o_data; uint32_t rc = 0; uint32_t nest1Select = CHIPLET_NEST_ID(1); uint32_t nest3Select = CHIPLET_NEST_ID(3); dts_sensor_result_reg_t dts_scom_data; int i; for(i = 0; i < sizeof(NestDts_t) / 8; ++i) { ptr[i] = 0; } // Turn off MCR bits to prevent machine check on error on scom readings // bits 1:7 uint32_t org_sem = mfmsr() & MSR_SEM; // Clear SIBRC and SIBRCA // mask off SIB errors as machine checks, return rc instead mtmsr((mfmsr() & ~(MSR_SIBRC | MSR_SIBRCA)) | MSR_SEM); // Get DTS readings PPE_LVD(nest1Select + THERM_DTS_RESULT, value64); dts_scom_data.value = value64; o_data->sensor0.result = dts_scom_data.half_words.reading[0]; PPE_LVD(nest3Select + THERM_DTS_RESULT, value64); dts_scom_data.value = value64; o_data->sensor1.result = dts_scom_data.half_words.reading[0]; o_data->sensor2.result = dts_scom_data.half_words.reading[1]; // Check rc accumulated - ignore rc == 0 uint32_t sibrca = (mfmsr() & 0x0000007f); if(sibrca) { // Report most severe error in rc rc = 7; uint32_t mask = 1; for(; mask != 0x00000080; mask <<= 1) { if( mask & sibrca ) { break; } --rc; } } // Clear masks SIB masks (MSR_SEM) // Clear SIBRC and SIMBRCA // Restore any SIB masks that may have been on before. mtmsr((mfmsr() & ~(MSR_SEM | MSR_SIBRC | MSR_SIBRCA)) | (org_sem & MSR_SEM)); return rc; } <|start_filename|>src/ssx/ppc405/ppc405_spr.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_spr.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_SPR_H__ #define __PPC405_SPR_H__ /// \file ppc405_spr.h /// \brief Everything related to PPC405-specific SPRs /// \defgroup ppc405_sprs PowerPC 405 SPRs /// /// These are the documented SPRs of the PPC405. Most of these SPRs are /// available in RISCWatch and eCmd using the defined names (minus SPRN_). In /// some cases RISCWatch/eCMD use different names, which appear in square /// brackets in the brief comments for each register. RISCWatch/eCMD also /// allow CR, MSR and IAR (Instruction Address Register) to be accessed as /// SPRs. /// /// @{ #define SPRN_CCR0 0x3b3 /// Core configuration register 0 #define SPRN_CCR1 0x378 /// Core configuration register 1 #define SPRN_CTR 0x009 /// Count register #define SPRN_DAC1 0x3f6 /// Data address compare 1 #define SPRN_DAC2 0x3f7 /// Data address compare 2 #define SPRN_DBCR0 0x3f2 /// Debug control register 0 #define SPRN_DBCR1 0x3bd /// Debug control register 1 #define SPRN_DBSR 0x3f0 /// Debug status register #define SPRN_DCCR 0x3fa /// Data cacheability (real mode) #define SPRN_DCWR 0x3ba /// Data cache writeback (real mode) #define SPRN_DEAR 0x3d5 /// Data exception address register #define SPRN_DVC1 0x3b6 /// Data value compare 1 #define SPRN_DVC2 0x3b7 /// Data value compare 2 #define SPRN_ESR 0x3d4 /// Exception syndrome register #define SPRN_EVPR 0x3d6 /// Exception. vec. prefix reg. #define SPRN_IAC1 0x3f4 /// Instruction address compare 1 #define SPRN_IAC2 0x3f5 /// Instruction address compare 2 #define SPRN_IAC3 0x3b4 /// Instruction address compare 3 #define SPRN_IAC4 0x3b5 /// Instruction address compare 4 #define SPRN_ICCR 0x3fb /// Instruction cache. (real mode) #define SPRN_ICDBDR 0x3d3 /// Instruction cache debug data reg. #define SPRN_LR 0x008 /// Link register #define SPRN_MCSR 0x23c /// Machine check syndrome register #define SPRN_PID 0x3b1 /// Process ID #define SPRN_PIT 0x3db /// Programmable interrupt timer #define SPRN_PVR 0x11f /// Processor version register #define SPRN_SGR 0x3b9 /// Storage guarded (real mode) #define SPRN_SLER 0x3bb /// Storage little-endian (real mode) #define SPRN_SPRG0 0x110 /// SPR general register 0 #define SPRN_SPRG1 0x111 /// SPR general register 1 #define SPRN_SPRG2 0x112 /// SPR general register 2 #define SPRN_SPRG3 0x113 /// SPR general register 3 #define SPRN_SPRG4 0x114 /// SPR general register 4 [SPRG4_W] #define SPRN_SPRG5 0x115 /// SPR general register 5 [SPRG5_W] #define SPRN_SPRG6 0x116 /// SPR general register 6 [SPRG6_W] #define SPRN_SPRG7 0x117 /// SPR general register 7 [SPRG7_W] #define SPRN_SRR0 0x01a /// Save/restore register 0 #define SPRN_SRR1 0x01b /// Save/restore register 1 #define SPRN_SRR2 0x3de /// Save/restore register 2 #define SPRN_SRR3 0x3df /// Save/restore register 3 #define SPRN_SU0R 0x3bc /// Storage user 0 (real mode) #define SPRN_TBL 0x11c /// Time base lower [TBL_W] #define SPRN_TBU 0x11d /// Time base upper [TBU_W] #define SPRN_TCR 0x3da /// Timer control register #define SPRN_TSR 0x3d8 /// Timer status register #define SPRN_USPRG0 0x100 /// User read/write SPR general 0 #define SPRN_XER 0x001 /// Fixed-point exception register #define SPRN_ZPR 0x3b0 /// Zone protection register #define SPRN_UR_SPRG4 0x104 /// User-readable SPRG4 [SPRG4_R] #define SPRN_UR_SPRG5 0x105 /// User-readable SPRG5 [SPRG5_R] #define SPRN_UR_SPRG6 0x106 /// User-readable SPRG6 [SPRG6_R] #define SPRN_UR_SPRG7 0x107 /// User-readable SPRG7 [SPRG7_R] #define SPRN_UR_TBL 0x10c /// User-readable TBL [TBL, TBL_R] #define SPRN_UR_TBU 0x10d /// User-readable TBU [TBU, TBU_R] /// @} /// \defgroup ppc405_undocumented_sprs PowerPC 405 Undocumented SPRs /// /// These are undocumented SPRs related to RISCWatch and debugging. These /// registers are also available in RISCWatch/eCMD. /// /// - DBDR is a scratch register used by RISCwatch when "RAM-ing" data in/out of /// the core. This register can be read and written. /// /// - DBSRS and TSRS are "hidden" registers connected to DBSR and TSR /// respectively. These are write-only registers. When written, any 1 bits in /// the write data are OR-ed into the DBSR and TSR respectively, as a way to /// force status bits and cause interrupts. /// /// @{ #define SPRN_DBDR 0x3f3 /// Debug data register 0x3f3 */ #define SPRN_DBSRS 0x3f1 /// Debug status register set 0x3f1 */ #define SPRN_TSRS 0x3d9 /// Timer status register set 0x3d9 */ /// @} /* CCR0 - Cache Control Register 0 */ #define CCR0_LWL 0x02000000 /* Load Word as Line */ #define CCR0_LWOA 0x01000000 /* Load Without Allocate */ #define CCR0_SWOA 0x00800000 /* Store Without Allocate */ #define CCR0_DPP1 0x00400000 /* DCU PLB Priority Bit 1 */ #define CCR0_IPP0 0x00200000 /* ICU PLB Priority Bit 0 */ #define CCR0_IPP1 0x00100000 /* ICU PLB Priority Bit 1 */ #define CCR0_DPE 0x00080000 /* Data Cache Parity Enable */ #define CCR0_DPP 0x00040000 /* DCU Parity is Precise (0/1) */ #define CCR0_U0XE 0x00020000 /* Enable U0 Exception */ #define CCR0_LDBE 0x00010000 /* Load Debug Enable */ #define CCR0_IPE 0x00002000 /* Instruction Cache Parity Enable */ #define CCR0_TPE 0x00001000 /* TLB Parity Enable */ #define CCR0_PFC 0x00000800 /* ICU Prefetching for Cacheable Regions */ #define CCR0_PFNC 0x00000400 /* ICU Prefetching for Non-Cacheable Regions */ #define CCR0_NCRS 0x00000200 /* Non-Cacheable ICU request is 16(0)/32(1)B */ #define CCR0_FWOA 0x00000100 /* Fetch Without Allocate */ #define CCR0_CIS 0x00000010 /* Cache Information Select Data(0)/Tag(1) */ #define CCR0_PRS 0x00000008 /* Parity Read Select */ #define CCR0_CWS 0x00000001 /* Cache Way Select A(0)/B(1) */ /* CCR1 - Cache Control Register 1 */ #define CCR1_ICTE 0x80000000 /* Instruction Cache Tag Parity Insertion */ #define CCR1_ICDE 0x40000000 /* Instruction Cache Data Parity Insertion */ #define CCR1_DCTE 0x20000000 /* Data Cache Tag Parity Insertion */ #define CCR1_DCDE 0x10000000 /* Data Cache Data Parity Insertion */ #define CCR1_TLBE 0x08000000 /* TLB Parity Insertion */ /* DBCR0 - Debug Control Register 0 */ #define DBCR0_EDM 0x80000000 /* External Debug Mode */ #define DBCR0_IDM 0x40000000 /* Internal Debug Mode */ #define DBCR0_RST_MASK 0x30000000 /* ReSeT */ #define DBCR0_RST_NONE 0x00000000 /* No action */ #define DBCR0_RST_CORE 0x10000000 /* Core reset */ #define DBCR0_RST_CHIP 0x20000000 /* Chip reset */ #define DBCR0_RST_SYSTEM 0x30000000 /* System reset */ #define DBCR0_IC 0x08000000 /* Instruction Completion debug event */ #define DBCR0_BT 0x04000000 /* Branch Taken debug event */ #define DBCR0_EDE 0x02000000 /* Exception Debug Event */ #define DBCR0_TDE 0x01000000 /* Trap Debug Event */ #define DBCR0_IA1 0x00800000 /* IAC (Instruction Address Compare) 1 debug event */ #define DBCR0_IA2 0x00400000 /* IAC 2 debug event */ #define DBCR0_IA12 0x00200000 /* Instruction Address Range Compare 1-2 */ #define DBCR0_IA12X 0x00100000 /* IA12 eXclusive */ #define DBCR0_IA3 0x00080000 /* IAC 3 debug event */ #define DBCR0_IA4 0x00040000 /* IAC 4 debug event */ #define DBCR0_IA34 0x00020000 /* Instruction Address Range Compare 3-4 */ #define DBCR0_IA34X 0x00010000 /* IA34 eXclusive */ #define DBCR0_IA12T 0x00008000 /* Instruction Address Range Compare 1-2 range Toggle */ #define DBCR0_IA34T 0x00004000 /* Instruction Address Range Compare 3-4 range Toggle */ #define DBCR0_FT 0x00000001 /* Freeze Timers on debug event */ /* DBSR - Debug Status Register */ #define DBSR_IC 0x80000000 /* Instruction completion debug event */ #define DBSR_BT 0x40000000 /* Branch Taken debug event */ #define DBSR_EDE 0x20000000 /* Exception debug event */ #define DBSR_TIE 0x10000000 /* Trap Instruction debug event */ #define DBSR_UDE 0x08000000 /* Unconditional debug event */ #define DBSR_IA1 0x04000000 /* IAC1 debug event */ #define DBSR_IA2 0x02000000 /* IAC2 debug event */ #define DBSR_DR1 0x01000000 /* DAC1 Read debug event */ #define DBSR_DW1 0x00800000 /* DAC1 Write debug event */ #define DBSR_DR2 0x00400000 /* DAC2 Read debug event */ #define DBSR_DW2 0x00200000 /* DAC2 Write debug event */ #define DBSR_IDE 0x00100000 /* Imprecise debug event */ #define DBSR_IA3 0x00080000 /* IAC3 debug event */ #define DBSR_IA4 0x00040000 /* IAC4 debug event */ #define DBSR_MRR 0x00000300 /* Most recent reset */ /* TCR - Timer Control Register */ #define TCR_WP_MASK 0xc0000000 /* Watchdog Period mask */ #define TCR_WP_2_17 0x00000000 /* 2**17 clocks */ #define TCR_WP_2_21 0x40000000 /* 2**21 clocks */ #define TCR_WP_2_25 0x80000000 /* 2**25 clocks */ #define TCR_WP_2_29 0xc0000000 /* 2**29 clocks */ #define TCR_WRC_MASK 0x30000000 /* Watchdog Reset Control mask */ #define TCR_WRC_NONE 0x00000000 /* No watchdog reset */ #define TCR_WRC_CORE 0x10000000 /* Core reset */ #define TCR_WRC_CHIP 0x20000000 /* Chip reset */ #define TCR_WRC_SYSTEM 0x30000000 /* System reset */ #define TCR_WIE 0x08000000 /* Watchdog Interrupt Enable */ #define TCR_PIE 0x04000000 /* PIT Interrupt Enable */ #define TCR_FP_MASK 0x03000000 /* FIT Period */ #define TCR_FP_2_9 0x00000000 /* 2**9 clocks */ #define TCR_FP_2_13 0x01000000 /* 2**13 clocks */ #define TCR_FP_2_17 0x02000000 /* 2**17 clocks */ #define TCR_FP_2_21 0x03000000 /* 2**21 clocks */ #define TCR_FIE 0x00800000 /* FIT Interrupt Enable */ #define TCR_ARE 0x00400000 /* Auto-reload Enable */ #ifndef __ASSEMBLER__ typedef union { uint32_t value; struct { unsigned int wp : 2; unsigned int wrc : 2; unsigned int wie : 1; unsigned int pie : 1; unsigned int fp : 2; unsigned int fie : 1; unsigned int are : 1; unsigned int reserved : 22; } fields; } Ppc405TCR; #endif /* __ASSEMBLER__ */ /* TSR - Timer Status Register */ #define TSR_ENW 0x80000000 /* Enable Next Watchdog */ #define TSR_WIS 0x40000000 /* Watchdog Interrupt Status */ #define TSR_WRS_MASK 0x30000000 /* Watchdog Reset Status */ #define TSR_WRS_NONE 0x00000000 /* No watchdog reset has occurred */ #define TSR_WRS_CORE 0x10000000 /* Core reset was forced by the watchdog */ #define TSR_WRS_CHIP 0x20000000 /* Chip reset was forced by the watchdog */ #define TSR_WRS_SYSTEM 0x30000000 /* System reset was forced by the watchdog */ #define TSR_PIS 0x08000000 /* PIT Interrupt Status */ #define TSR_FIS 0x04000000 /* FIT Interrupt Status */ #ifndef __ASSEMBLER__ /// Move From SPR /// /// Note that \a sprn must be a compile-time constant. #define mfspr(sprn) \ ({uint32_t __value; \ asm volatile ("mfspr %0, %1" : "=r" (__value) : "i" (sprn)); \ __value;}) /// Move to SPR /// /// Note that \a sprn must be a compile-time constant. #define mtspr(sprn, value) \ ({uint32_t __value = (value); \ asm volatile ("mtspr %0, %1" : : "i" (sprn), "r" (__value)); \ }) /// Read-Modify-Write an SPR with OR (Set SPR bits) /// /// Note that \a sprn must be a compile-time constant. This operation is only /// guaranteed atomic in a critical section. #define or_spr(sprn, x) \ mtspr(sprn, mfspr(sprn) | (x)) /// Read-Modify-Write an SPR with AND complement (Clear SPR bits) /// /// Note that \a sprn must be a compile-time constant. This operation is only /// guaranteed atomic in a critical section. #define andc_spr(sprn, x) \ mtspr(sprn, mfspr(sprn) & ~(x)) /// Move From Time Base (Lower) #define mftb() mfspr(SPRN_TBL) /// Move To Time Base (Lower) #define mttbl(x) mtspr(SPRN_TBL, (x)) /// Move From Time Base (Upper) #define mftbu() mfspr(SPRN_TBU) /// Move To Time Base (UPPER) #define mttbu(x) mtspr(SPRN_TBU, (x)) #endif /* __ASSEMBLER__ */ #ifdef __ASSEMBLER__ // *INDENT-OFF* /// \cond // Use this macro to define new mt<spr> and mf<spr> instructions that // may not exist in the assembler. .macro _sprinstrs, name, num .macro mt\name, reg mtspr \num, \reg .endm .macro mf\name, reg mfspr \reg, \num .endm .endm _sprinstrs ccr0, SPRN_CCR0 _sprinstrs ccr1, SPRN_CCR1 _sprinstrs dbcr0, SPRN_DBCR0 _sprinstrs dbcr1, SPRN_DBCR1 _sprinstrs dcwr, SPRN_DCWR _sprinstrs mcsr, SPRN_MCSR _sprinstrs pid, SPRN_PID _sprinstrs sgr, SPRN_SGR _sprinstrs sler, SPRN_SLER _sprinstrs su0r, SPRN_SU0R _sprinstrs usprg0, SPRN_USPRG0 /// \endcond // *INDENT-ON* #endif /* __ASSEMBLER__ */ #endif /* __PPC405_SPR_H__ */ <|start_filename|>src/include/registers/cppm_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/include/registers/cppm_firmware_registers.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CPPM_FIRMWARE_REGISTERS_H__ #define __CPPM_FIRMWARE_REGISTERS_H__ /// \file cppm_firmware_registers.h /// \brief C register structs for the CPPM unit // *** WARNING *** - This file is generated automatically, do not edit. #ifndef SIXTYFOUR_BIT_CONSTANT #ifdef __ASSEMBLER__ #define SIXTYFOUR_BIT_CONSTANT(x) x #else #define SIXTYFOUR_BIT_CONSTANT(x) x##ull #endif #endif #ifndef __ASSEMBLER__ #include <stdint.h> typedef union cppm_cpmmr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ppm_write_disable : 1; uint64_t ppm_write_override : 1; uint64_t reserved0 : 7; uint64_t fused_core_mode : 1; uint64_t reserved1 : 2; uint64_t cme_err_notify_dis : 1; uint64_t wkup_notify_select : 1; uint64_t enable_pece : 1; uint64_t cme_special_wkup_done_dis : 1; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t cme_special_wkup_done_dis : 1; uint64_t enable_pece : 1; uint64_t wkup_notify_select : 1; uint64_t cme_err_notify_dis : 1; uint64_t reserved1 : 2; uint64_t fused_core_mode : 1; uint64_t reserved0 : 7; uint64_t ppm_write_override : 1; uint64_t ppm_write_disable : 1; #endif // _BIG_ENDIAN } fields; } cppm_cpmmr_t; typedef union cppm_cpmmr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ppm_write_disable : 1; uint64_t ppm_write_override : 1; uint64_t reserved1 : 10; uint64_t cme_err_notify_dis : 1; uint64_t wkup_notify_select : 1; uint64_t enable_pece : 1; uint64_t cme_special_wkup_done_dis : 1; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t cme_special_wkup_done_dis : 1; uint64_t enable_pece : 1; uint64_t wkup_notify_select : 1; uint64_t cme_err_notify_dis : 1; uint64_t reserved1 : 10; uint64_t ppm_write_override : 1; uint64_t ppm_write_disable : 1; #endif // _BIG_ENDIAN } fields; } cppm_cpmmr_clr_t; typedef union cppm_cpmmr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ppm_write_disable : 1; uint64_t ppm_write_override : 1; uint64_t reserved1 : 10; uint64_t cme_err_notify_dis : 1; uint64_t wkup_notify_select : 1; uint64_t enable_pece : 1; uint64_t cme_special_wkup_done_dis : 1; uint64_t reserved2 : 48; #else uint64_t reserved2 : 48; uint64_t cme_special_wkup_done_dis : 1; uint64_t enable_pece : 1; uint64_t wkup_notify_select : 1; uint64_t cme_err_notify_dis : 1; uint64_t reserved1 : 10; uint64_t ppm_write_override : 1; uint64_t ppm_write_disable : 1; #endif // _BIG_ENDIAN } fields; } cppm_cpmmr_or_t; typedef union cppm_perrsum { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cppm_error : 1; uint64_t reserved1 : 63; #else uint64_t reserved1 : 63; uint64_t cppm_error : 1; #endif // _BIG_ENDIAN } fields; } cppm_perrsum_t; typedef union cppm_err { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pcb_interrupt_protocol_err : 1; uint64_t special_wkup_protocol_err : 1; uint64_t clk_sync_err : 1; uint64_t reserved_3 : 1; uint64_t pece_intr_disabled : 1; uint64_t deconfigured_intr : 1; uint64_t reserved_6_71 : 2; uint64_t reserved2 : 56; #else uint64_t reserved2 : 56; uint64_t reserved_6_71 : 2; uint64_t deconfigured_intr : 1; uint64_t pece_intr_disabled : 1; uint64_t reserved_3 : 1; uint64_t clk_sync_err : 1; uint64_t special_wkup_protocol_err : 1; uint64_t pcb_interrupt_protocol_err : 1; #endif // _BIG_ENDIAN } fields; } cppm_err_t; typedef union cppm_errmsk { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t reserved1 : 8; uint64_t reserved2 : 56; #else uint64_t reserved2 : 56; uint64_t reserved1 : 8; #endif // _BIG_ENDIAN } fields; } cppm_errmsk_t; typedef union cppm_nc0indir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ncn_indirect : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ncn_indirect : 32; #endif // _BIG_ENDIAN } fields; } cppm_nc0indir_t; typedef union cppm_nc0indir_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ncn_indirect : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ncn_indirect : 32; #endif // _BIG_ENDIAN } fields; } cppm_nc0indir_clr_t; typedef union cppm_nc0indir_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ncn_indirect : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ncn_indirect : 32; #endif // _BIG_ENDIAN } fields; } cppm_nc0indir_or_t; typedef union cppm_nc1indir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ncn_indirect : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ncn_indirect : 32; #endif // _BIG_ENDIAN } fields; } cppm_nc1indir_t; typedef union cppm_nc1indir_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ncn_indirect : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ncn_indirect : 32; #endif // _BIG_ENDIAN } fields; } cppm_nc1indir_clr_t; typedef union cppm_nc1indir_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ncn_indirect : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t ncn_indirect : 32; #endif // _BIG_ENDIAN } fields; } cppm_nc1indir_or_t; typedef union cppm_csar { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t scratch_atomic_data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t scratch_atomic_data : 32; #endif // _BIG_ENDIAN } fields; } cppm_csar_t; typedef union cppm_csar_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t scratch_atomic_data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t scratch_atomic_data : 32; #endif // _BIG_ENDIAN } fields; } cppm_csar_clr_t; typedef union cppm_csar_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t scratch_atomic_data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t scratch_atomic_data : 32; #endif // _BIG_ENDIAN } fields; } cppm_csar_or_t; typedef union cppm_caccr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t clk_sb_strength : 4; uint64_t clk_sb_spare : 1; uint64_t clk_sb_pulse_mode_en : 1; uint64_t clk_sb_pulse_mode : 2; uint64_t clk_sw_resclk : 4; uint64_t clk_sw_spare : 1; uint64_t quad_clk_sb_override : 1; uint64_t quad_clk_sw_override : 1; uint64_t clk_sync_enable : 1; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t clk_sync_enable : 1; uint64_t quad_clk_sw_override : 1; uint64_t quad_clk_sb_override : 1; uint64_t clk_sw_spare : 1; uint64_t clk_sw_resclk : 4; uint64_t clk_sb_pulse_mode : 2; uint64_t clk_sb_pulse_mode_en : 1; uint64_t clk_sb_spare : 1; uint64_t clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } cppm_caccr_t; typedef union cppm_caccr_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t clk_sb_strength : 4; uint64_t clk_sb_spare : 1; uint64_t clk_sb_pulse_mode_en : 1; uint64_t clk_sb_pulse_mode : 2; uint64_t clk_sw_resclk : 4; uint64_t clk_sw_spare : 1; uint64_t quad_clk_sb_override : 1; uint64_t quad_clk_sw_override : 1; uint64_t clk_sync_enable : 1; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t clk_sync_enable : 1; uint64_t quad_clk_sw_override : 1; uint64_t quad_clk_sb_override : 1; uint64_t clk_sw_spare : 1; uint64_t clk_sw_resclk : 4; uint64_t clk_sb_pulse_mode : 2; uint64_t clk_sb_pulse_mode_en : 1; uint64_t clk_sb_spare : 1; uint64_t clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } cppm_caccr_clr_t; typedef union cppm_caccr_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t clk_sb_strength : 4; uint64_t clk_sb_spare : 1; uint64_t clk_sb_pulse_mode_en : 1; uint64_t clk_sb_pulse_mode : 2; uint64_t clk_sw_resclk : 4; uint64_t clk_sw_spare : 1; uint64_t quad_clk_sb_override : 1; uint64_t quad_clk_sw_override : 1; uint64_t clk_sync_enable : 1; uint64_t reserved1 : 48; #else uint64_t reserved1 : 48; uint64_t clk_sync_enable : 1; uint64_t quad_clk_sw_override : 1; uint64_t quad_clk_sb_override : 1; uint64_t clk_sw_spare : 1; uint64_t clk_sw_resclk : 4; uint64_t clk_sb_pulse_mode : 2; uint64_t clk_sb_pulse_mode_en : 1; uint64_t clk_sb_spare : 1; uint64_t clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } cppm_caccr_or_t; typedef union cppm_cacsr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t actual_clk_sb_strength : 4; uint64_t actual_clk_sb_spare : 1; uint64_t actual_clk_sb_pulse_mode_en : 1; uint64_t actual_clk_sb_pulse_mode : 2; uint64_t actual_clk_sw_resclk : 4; uint64_t actual_clk_sw_spare : 1; uint64_t clk_sync_done : 1; uint64_t reserved1 : 50; #else uint64_t reserved1 : 50; uint64_t clk_sync_done : 1; uint64_t actual_clk_sw_spare : 1; uint64_t actual_clk_sw_resclk : 4; uint64_t actual_clk_sb_pulse_mode : 2; uint64_t actual_clk_sb_pulse_mode_en : 1; uint64_t actual_clk_sb_spare : 1; uint64_t actual_clk_sb_strength : 4; #endif // _BIG_ENDIAN } fields; } cppm_cacsr_t; typedef union cppm_cmedb0 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_number0 : 8; uint64_t cme_message_hi : 56; #else uint64_t cme_message_hi : 56; uint64_t cme_message_number0 : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb0_t; typedef union cppm_cmedb0_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_number0 : 8; uint64_t cme_message_hi : 56; #else uint64_t cme_message_hi : 56; uint64_t cme_message_number0 : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb0_clr_t; typedef union cppm_cmedb0_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_number0 : 8; uint64_t cme_message_hi : 56; #else uint64_t cme_message_hi : 56; uint64_t cme_message_number0 : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb0_or_t; typedef union cppm_cmedb1 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb1_t; typedef union cppm_cmedb1_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb1_clr_t; typedef union cppm_cmedb1_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb1_or_t; typedef union cppm_cmedb2 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb2_t; typedef union cppm_cmedb2_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb2_clr_t; typedef union cppm_cmedb2_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb2_or_t; typedef union cppm_cmedb3 { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb3_t; typedef union cppm_cmedb3_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb3_clr_t; typedef union cppm_cmedb3_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message_numbern : 8; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t cme_message_numbern : 8; #endif // _BIG_ENDIAN } fields; } cppm_cmedb3_or_t; typedef union cppm_cmedata { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cppm_cmedata_t; typedef union cppm_cmedata_clr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cppm_cmedata_clr_t; typedef union cppm_cmedata_or { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t data : 32; uint64_t reserved1 : 32; #else uint64_t reserved1 : 32; uint64_t data : 32; #endif // _BIG_ENDIAN } fields; } cppm_cmedata_or_t; typedef union cppm_cmemsg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t cme_message : 64; #else uint64_t cme_message : 64; #endif // _BIG_ENDIAN } fields; } cppm_cmemsg_t; typedef union cppm_cisr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t hyp_intr_present : 4; uint64_t os_intr_present : 4; uint64_t msgsnd_intr_present : 4; uint64_t ebb_intr_present : 4; uint64_t hyp_intr_requested : 4; uint64_t os_intr_requested : 4; uint64_t msgsnd_intr_requested : 4; uint64_t msgsnd_intr_sample : 4; uint64_t msgsnd_ack : 1; uint64_t malf_alert_present : 1; uint64_t malf_alert_requested : 1; uint64_t cme_special_wkup_done : 1; uint64_t reserved1 : 28; #else uint64_t reserved1 : 28; uint64_t cme_special_wkup_done : 1; uint64_t malf_alert_requested : 1; uint64_t malf_alert_present : 1; uint64_t msgsnd_ack : 1; uint64_t msgsnd_intr_sample : 4; uint64_t msgsnd_intr_requested : 4; uint64_t os_intr_requested : 4; uint64_t hyp_intr_requested : 4; uint64_t ebb_intr_present : 4; uint64_t msgsnd_intr_present : 4; uint64_t os_intr_present : 4; uint64_t hyp_intr_present : 4; #endif // _BIG_ENDIAN } fields; } cppm_cisr_t; typedef union cppm_peces { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t pece_t0 : 6; uint64_t reserved1 : 2; uint64_t pece_t1 : 6; uint64_t reserved2 : 2; uint64_t pece_t2 : 6; uint64_t reserved3 : 2; uint64_t pece_t3 : 6; uint64_t reserved4 : 2; uint64_t use_pece : 4; uint64_t fused_core_mode : 1; uint64_t reserved5 : 27; #else uint64_t reserved5 : 27; uint64_t fused_core_mode : 1; uint64_t use_pece : 4; uint64_t reserved4 : 2; uint64_t pece_t3 : 6; uint64_t reserved3 : 2; uint64_t pece_t2 : 6; uint64_t reserved2 : 2; uint64_t pece_t1 : 6; uint64_t reserved1 : 2; uint64_t pece_t0 : 6; #endif // _BIG_ENDIAN } fields; } cppm_peces_t; typedef union cppm_civrmlcr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t ivrm_local_control : 1; uint64_t reserved_1_2 : 2; uint64_t ivrm_ureg_test_en : 1; uint64_t ivrm_ureg_test_id : 4; uint64_t reserved1 : 56; #else uint64_t reserved1 : 56; uint64_t ivrm_ureg_test_id : 4; uint64_t ivrm_ureg_test_en : 1; uint64_t reserved_1_2 : 2; uint64_t ivrm_local_control : 1; #endif // _BIG_ENDIAN } fields; } cppm_civrmlcr_t; typedef union cppm_ippmcmd { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t qppm_reg : 8; uint64_t qppm_rnw : 1; uint64_t reserved1 : 1; uint64_t reserved2 : 54; #else uint64_t reserved2 : 54; uint64_t reserved1 : 1; uint64_t qppm_rnw : 1; uint64_t qppm_reg : 8; #endif // _BIG_ENDIAN } fields; } cppm_ippmcmd_t; typedef union cppm_ippmstat { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t qppm_ongoing : 1; uint64_t qppm_status : 2; uint64_t reserved1 : 61; #else uint64_t reserved1 : 61; uint64_t qppm_status : 2; uint64_t qppm_ongoing : 1; #endif // _BIG_ENDIAN } fields; } cppm_ippmstat_t; typedef union cppm_ippmwdata { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t qppm_wdata : 64; #else uint64_t qppm_wdata : 64; #endif // _BIG_ENDIAN } fields; } cppm_ippmwdata_t; typedef union cppm_ippmrdata { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t qppm_rdata : 64; #else uint64_t qppm_rdata : 64; #endif // _BIG_ENDIAN } fields; } cppm_ippmrdata_t; #endif // __ASSEMBLER__ #endif // __CPPM_FIRMWARE_REGISTERS_H__ <|start_filename|>src/lib/occlib/ipc_ping.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/occlib/ipc_ping.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ipc_ping.h" #ifdef IPC_ENABLE_PING //server side ping message handler void ipc_ping_handler(ipc_msg_t* cmd, void* arg) { //NOTE: this will run in a critical interrupt when sent to the 405 //ignore return codes ipc_send_rsp(cmd, IPC_RC_SUCCESS); } //Note: This runs in a critical interrupt on the 405 but SSX functions // can not be called from a critical interrupt. Instead, it must be // deferred to a non-critical handler. void ipc_ping_response(ipc_msg_t* rsp, void* arg) { ipc_ping_cmd_t* ping_cmd = (ipc_ping_cmd_t*)rsp; if(KERN_CONTEXT_CRITICAL_INTERRUPT()) { //NOTE: this is a no-op on PPE IPC_DEFER_TO_NONCRITICAL(rsp); } else { KERN_SEMAPHORE_POST(&ping_cmd->sem); ipc_free_msg(&ping_cmd->msg); } } //Command that can be run in a thread context to ping another target //The message is allocated on the stack int ipc_ping(ipc_ping_cmd_t* ping_cmd, uint32_t target_id) { int rc; do { //set the target (since this is a multi-target command) rc = ipc_set_cmd_target(&ping_cmd->msg, target_id); if(rc) { break; } //send the command rc = ipc_send_cmd(&ping_cmd->msg); if(rc) { break; } //assume that if we timed out then the target must have gone down. rc = KERN_SEMAPHORE_PEND(&ping_cmd->sem, KERN_SECONDS(1)); if(rc) { if(rc == -KERN_SEMAPHORE_PEND_TIMED_OUT) { rc = IPC_RC_TIMEOUT; } break; } //response message was received. Now return the ipc_rc rc = ipc_get_rc(&ping_cmd->msg); } while(0); return rc; } #endif /*IPC_ENABLE_PING*/ <|start_filename|>src/ppe/pk/ppe42/ppe42_msr.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42_msr.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPE42_MSR_H__ #define __PPE42_MSR_H__ /// \file ppe42_msr.h /// \brief Everything related to the PPE42 Machine State Register /// /// All of the macros defined here that \e modify the MSR create a compiler /// memory barrier that will cause GCC to flush/invalidate all memory data /// held in registers before the macro. This is consistent with other systems, /// e.g., the PowerPC Linux kernel, and is the safest way to define these /// macros as it guarantess for example that kernel data structure updates /// have completed before exiting a critical section. #define MSR_SEM 0x7f000000 /* SIB Error Mask */ #define MSR_IS0 0x00800000 /* Instance-Specific Field 0 */ #define MSR_SIBRC 0x00700000 /* Last SIB return code */ #define MSR_LP 0x00080000 /* Low Priority */ #define MSR_WE 0x00040000 /* Wait State Enable */ #define MSR_IS1 0x00020000 /* Instance-Specific Field 1 */ #define MSR_UIE 0x00010000 /* Unmaskable Interrupt Enable */ #define MSR_EE 0x00008000 /* External Interrupt Enable */ #define MSR_ME 0x00001000 /* Machine Check Exception Enable */ #define MSR_IS2 0x00000800 /* Instance-Specific field 2 */ #define MSR_IS3 0x00000400 /* Instance-Specific field 3 */ #define MSR_IPE 0x00000100 /* Imprecise Mode Enable */ #define MSR_SIBRCA 0x000000ff /* SIB Return Code Accumulator */ //#define MSR_CE_BIT 14 #define MSR_EE_BIT 16 //#define MSR_IR_BIT 26 //#define MSR_DR_BIT 27 #define MSR_SEM_START_BIT 1 #define MSR_SEM_LEN 7 #define MSR_SEM1 0x40000000 #define MSR_SEM2 0x20000000 #define MSR_SEM3 0x10000000 #define MSR_SEM4 0x08000000 #define MSR_SEM5 0x04000000 #define MSR_SEM6 0x02000000 #define MSR_SEM7 0x01000000 #define MSR_SIBRC_START_BIT 9 #define MSR_SIBRC_LEN 3 #ifndef __ASSEMBLER__ /// Move From MSR #define mfmsr() \ ({uint32_t __msr; \ asm volatile ("mfmsr %0" : "=r" (__msr) : : "memory"); \ __msr;}) /// Move to MSR #define mtmsr(value) \ asm volatile ("mtmsr %0" : : "r" (value) : "memory") /// Read-Modify-Write the MSR with OR (Set MSR bits). This operation is only /// guaranteed atomic in a critical section. #define or_msr(x) \ mtmsr(mfmsr() | (x)) /// Read-Modify-Write the MSR with AND complement (Clear MSR bits). This /// operation is only guaranteed atomic in a critical section. #define andc_msr(x) \ mtmsr(mfmsr() & ~(x)) /// Write MSR[EE] with an immediate value (0/1) /// /// Note that the immediate value \a i must be a compile-time constant. #define wrteei(i) \ asm volatile ("wrteei %0" : : "i" (i) : "memory") /// Write MSR[EE] from the EE bit of another MSR #define wrtee(other_msr) \ asm volatile ("wrtee %0" : : "r" (other_msr) : "memory") #endif /* __ASSEMBLER__ */ #endif /* __PPE42_MSR_H__ */ <|start_filename|>src/ssx/ssx/ssx_kernel.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ssx/ssx_kernel.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __SSX_KERNEL_H__ #define __SSX_KERNEL_H__ /// \file ssx_kernel.h /// \brief SSX portable kernel (non-API) data and data structures /// /// \todo In theory, as long as the critical section entry/exit macros use GCC /// memory barriers, we should be able to eliminate all of the 'volatile' /// declarations in SSX code. These have been added to the PPC405 port, so /// we should try it. #ifdef __SSX_CORE_C__ #define IF__SSX_CORE_C__(x) x #define UNLESS__SSX_CORE_C__(x) #else #define IF__SSX_CORE_C__(x) #define UNLESS__SSX_CORE_C__(x) x #endif #if SSX_MINIMIZE_KERNEL_CODE_SPACE #define IF_SSX_MINIMIZE_KERNEL_CODE_SPACE(x) x #define UNLESS_SSX_MINIMIZE_KERNEL_CODE_SPACE(x) #else #define IF_SSX_MINIMIZE_KERNEL_CODE_SPACE(x) #define UNLESS_SSX_MINIMIZE_KERNEL_CODE_SPACE(x) x #endif #ifndef __ASSEMBLER__ /// This is the stack pointer saved when switching from a thread or /// non-critical interrupt context to a full-mode critical interrupt context. UNLESS__SSX_CORE_C__(extern) volatile SsxAddress __ssx_saved_sp_critical; /// The critical interrupt stack; constant once defined by the call of /// ssx_initialize(). UNLESS__SSX_CORE_C__(extern) volatile SsxAddress __ssx_critical_stack; /// This is the stack pointer saved when switching from a thread context to a /// full-mode non-critical interrupt context. UNLESS__SSX_CORE_C__(extern) volatile SsxAddress __ssx_saved_sp_noncritical; /// The non-critical interrupt stack; constant once defined by the call of /// ssx_initialize(). UNLESS__SSX_CORE_C__(extern) volatile SsxAddress __ssx_noncritical_stack; /// This is the run queue - the queue of mapped runnable tasks. UNLESS__SSX_CORE_C__(extern) volatile SsxThreadQueue __ssx_run_queue; /// This flag is set by \c __ssx_schedule() if a new highest-priority thread /// becomes runnable during an interrupt handler. The context switch will /// take place at the end of non-critical interrupt processing, and the /// interrupt handling code will clear the flag. UNLESS__SSX_CORE_C__(extern) volatile int __ssx_delayed_switch; /// The currently running thread, or NULL (0) to indicate the idle thread /// /// \a __ssx_current_thread holds a pointer to the currently executing /// thread. This pointer will be NULL (0) under the following conditions: /// /// - After ssx_initialize() but prior to ssx_start_threads() /// /// - After ssx_start_threads(), when no threads are runnable. In this case /// the NULL (0) value indicates that the SSX idle thread is 'running'. /// /// - After ssx_start_threads(), when the current (non-idle) thread has /// completed or been deleted. /// /// If \a __ssx_current_thread == 0 then there is no requirement to save any /// register state on a context switch, either because the SSX idle thread has /// no permanent context, or because any thread context on the kernel stack is /// associated with a deleted thread. /// /// If \a __ssx_current_thread != 0 then \a __ssx_current_thread is a pointer /// to the currently executing thread. In an interrupt handler \a /// ssx_current_thread is a pointer to the thread whose context is saved on /// the kernel stack. UNLESS__SSX_CORE_C__(extern) volatile SsxThread* __ssx_current_thread; /// The thread to switch to during the next context switch, or NULL (0). /// /// \a __ssx_next_thread is computed by __ssx_schedule(). \a /// __ssx_next_thread holds a pointer to the thread to switch to at the next /// context switch. In a thread context the switch happens immediately if \a /// __ssx_next_thread == 0 or \a __ssx_next_thread != \a __ssx_current_thread. /// In an interrupt context the check happens at the end of processing all /// SSX_NONCRITICAL interrupts. /// /// \a __ssx_next_thread may be NULL (0) under the following /// conditions: /// /// - After ssx_initialize() but prior to ssx_start_threads(), assuming no /// threads have been made runnable. /// /// - After ssx_start_threads(), when no threads are runnable. In this case /// the NULL (0) value indicates that the SSX idle thread is the next thread /// to 'run'. /// /// If \a __ssx_next_thread == 0 then there is no requirement to restore /// any register state on a context switch, because the SSX idle thread has /// no permanent context. /// /// If \a __ssx_next_thread != 0 then \a __ssx_next_thread is a pointer /// to the thread whose context will be restored at the next context switch. UNLESS__SSX_CORE_C__(extern) volatile SsxThread* __ssx_next_thread; /// The priority of \a __ssx_next_thread /// /// If \a __ssx_next_thread == 0, the \a __ssx_next_priority == SSX_THREADS. UNLESS__SSX_CORE_C__(extern) volatile SsxThreadPriority __ssx_next_priority; /// This variable holds the default thread machine context for newly created /// threads. The idle thread also uses this context. This variable is normally /// constant after the call of \c ssx_initialize(). UNLESS__SSX_CORE_C__(extern) volatile SsxMachineContext __ssx_thread_machine_context_default; /// The size of the noncritical stack (bytes). UNLESS__SSX_CORE_C__(extern) volatile size_t __ssx_noncritical_stack_size; /// The size of the critical stack (bytes). UNLESS__SSX_CORE_C__(extern) volatile size_t __ssx_critical_stack_size; /// This table maps priorities to threads, and contains SSX_THREADS + 1 /// entries. The final entry is for the idle thread and will always be null /// after initizlization. UNLESS__SSX_CORE_C__(extern) volatile SsxThread* __ssx_priority_map[SSX_THREADS + 1]; /// The SSX time queue structure /// /// This structure is defined for use by the kernel, however applications /// could also use this structure to define their own time queues. typedef struct { /// A sentinel node for the time queue. /// /// The time queue is an SsxDeque managed as a FIFO queue for queue /// management purpose, although events time out in time order. /// /// This pointer container is defined as the first element of the /// structure to allow the SsxTimeQueue to be cast to an SsxDeque. SsxDeque queue; /// The next timeout in absolute time. SsxTimebase next_timeout; /// A pointer to allow preemption of time queue processing /// /// If non-0, then this is the next timer in the time queue to handle, or /// a pointer to the \a queue object indicating no more timers to handle. /// /// \a cursor != 0 implies that time queue handler is in the midst of /// processing the time queue, but has enabled interrupt preemption for /// processing a timer handler. This means that 1) if the timer pointed to /// by \a cursor is deleted then the cursor must be assigned to the /// next timer in the queue; and 2) if a new timer is scheduled then /// activating the next timeout will be handled by the timer handler. SsxDeque* cursor; } SsxTimeQueue; UNLESS__SSX_CORE_C__(extern) SsxTimeQueue __ssx_time_queue; /// Return a pointer to the SsxThread object of the currently running thread, /// or NULL (0) if SSX is idle or has not been started. /// /// In this API the current thread is not volatile - it will never change /// inside application code - thus the 'volatile' is cast away. The SSX kernel /// does not (must not) use this API. UNLESS__SSX_CORE_C__(extern) inline SsxThread* ssx_current(void) { return (SsxThread*)__ssx_current_thread; } /// Set the timebase. This is only called at initialization. Machine /// specific. void __ssx_timebase_set(SsxTimebase t); /// Schedule the next timeout in a machine-specific way. void __ssx_schedule_hardware_timeout(SsxTimebase timeout); /// Cancel the next timeout in a machine-specific way. void __ssx_cancel_hardware_timeout(void); /// The thread timeout handler. Portable. SSX_TIMER_CALLBACK(__ssx_thread_timeout); /// Generic stack initialization. Portable. int __ssx_stack_init(SsxAddress* stack, size_t* size); /// Machine-specific thread context initialization. void __ssx_thread_context_initialize(SsxThread* thread, SsxThreadRoutine thread_routine, void* arg); /// Machine specific resumption of __ssx_next_thread at __ssx_next_priority /// without saving the current context. void __ssx_next_thread_resume(void); /// Schedule a timer in the time queue. Portable. void __ssx_timer_schedule(SsxTimer* timer); /// Remove a timer from the time queue. Portable. int __ssx_timer_cancel(SsxTimer* timer); void __ssx_schedule(void); // Call the application main(). Portable. void __ssx_main(int argc, char** argv); #endif /* __ASSEMBLER__ */ #endif /* __SSX_KERNEL_H__ */ <|start_filename|>src/include/registers/p9_misc_scom_addresses.h<|end_filename|> #if !defined(_P9_MISC_SCOM_ADDRESSES_H_) #define _P9_MISC_SCOM_ADDRESSES_H_ #define PU_GPIO_INPUT 0x000B0050 #define PU_GPIO_OUTPUT 0x000B0051 #define PU_GPIO_OUTPUT_OR 0x000B0052 #define PU_GPIO_OUTPUT_CLR 0x000B0053 #define PU_GPIO_OUTPUT_EN 0x000B0054 // Found in Cumulus nest "MC Fault Isolation Register" #define MCS_0_MCFIR 0x05010800 #define MCS_1_MCFIR 0x05010880 #define MCS_2_MCFIR 0x03010800 #define MCS_3_MCFIR 0x03010880 // found in Cumulus nest "MC Mode0 Register" #define MCS_0_MCMODE0 0x05010811 #define MCS_1_MCMODE0 0x05010891 #define MCS_2_MCMODE0 0x03010811 #define MCS_3_MCMODE0 0x03010891 // found in Cumulus nest "MC Primary Memory Configuration Register" #define MCS_0_MCRSVDE 0x0501080E #define MCS_0_MCRSVDF 0x0501080F #define MCS_1_MCRSVDE 0x0501088E #define MCS_1_MCRSVDF 0x0501088F #define MCS_2_MCRSVDE 0x0301080E #define MCS_2_MCRSVDF 0x0301080F #define MCS_3_MCRSVDE 0x0301088E #define MCS_3_MCRSVDF 0x0301088F #define MCS_0_MCSYNC 0x05010815 #define MCS_1_MCSYNC 0x05010895 #define MCS_2_MCSYNC 0x03010815 #define MCS_3_MCSYNC 0x03010895 // MC Memory Configuration Register FIR/CFG #define MCP_CHAN0_CHI_FIR 0x07010900 #define MCP_CHAN1_CHI_FIR 0x07010940 #define MCP_CHAN2_CHI_FIR 0x07010980 #define MCP_CHAN3_CHI_FIR 0x070109C0 #define MCP_CHAN4_CHI_FIR 0x08010900 #define MCP_CHAN5_CHI_FIR 0x08010940 #define MCP_CHAN6_CHI_FIR 0x08010980 #define MCP_CHAN7_CHI_FIR 0x080109C0 #define MCP_CHAN0_CHI_MCICFG1Q 0x0701090E #define MCP_CHAN1_CHI_MCICFG1Q 0x0701094E #define MCP_CHAN2_CHI_MCICFG1Q 0x0701098E #define MCP_CHAN3_CHI_MCICFG1Q 0x070109CE #define MCP_CHAN4_CHI_MCICFG1Q 0x0801090E #define MCP_CHAN5_CHI_MCICFG1Q 0x0801094E #define MCP_CHAN6_CHI_MCICFG1Q 0x0801098E #define MCP_CHAN7_CHI_MCICFG1Q 0x080109CE #endif <|start_filename|>src/ppe/pk/ppe42/ppe42_spr.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42_spr.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPE42_SPR_H__ #define __PPE42_SPR_H__ /// \file ppe42_spr.h /// \brief Everything related to PPE42-specific SPRs /// \defgroup ppe42_sprs PPE42 SPRs /// /// These are the documented SPRs of the PPE42. Most of these SPRs are /// available in RISCWatch and eCmd using the defined names (minus SPRN_). In /// some cases RISCWatch/eCMD use different names, which appear in square /// brackets in the brief comments for each register. RISCWatch/eCMD also /// allow CR, MSR and IAR (Instruction Address Register) to be accessed as /// SPRs. /// /// @{ #define SPRN_XER 0x001 /// Fixed-point exception register #define SPRN_LR 0x008 /// Link register #define SPRN_CTR 0x009 /// Count register #define SPRN_DEC 0x016 /// Decrementer #define SPRN_SRR0 0x01a /// Save/restore register 0 #define SPRN_SRR1 0x01b /// Save/restore register 1 #define SPRN_EDR 0x03d /// Error Data Register #define SPRN_ISR 0x03e /// Interrupt Status Register #define SPRN_IVPR 0x03f /// Interrupt Vector Prefix Register #define SPRN_SPRG0 0x110 /// SPR general register 0 #define SPRN_PIR 0x11e /// Processor Identification Register #define SPRN_PVR 0x11f /// Processor version register #define SPRN_DBCR 0x134 /// Debug Control Register #define SPRN_DACR 0x13c /// Debug Address Compare Register #define SPRN_TSR 0x150 /// Timer Status Register #define SPRN_TCR 0x154 /// Timer Control Register /* DBCR - Debug Control Register */ #define DBCR_RST_SOFT 0x10000000 /* Reset: 01=Soft Reset */ #define DBCR_RST_HARD 0x20000000 /* Reset: 10=Hard Reset */ #define DBCR_RST_HALT 0x30000000 /* Reset: 11=Halt */ #define DBCR_TRAP 0x01000000 /* Trap Instruction Enable */ #define DBCR_IACE 0x00800000 /* Instruction Address Compare Enable */ #define DBCR_DACE_ST 0x00040000 /* Data Address Compare Enable: 01=store */ #define DBCR_DACE_LD 0x00080000 /* Data Address Compare Enable: 10=load */ #define DBCR_DACE_STLD 0x000C0000 /* Data Address Compare Enable: 11=both */ /* TCR - Timer Control Register */ #define TCR_WP_MASK 0xc0000000 /* Watchdog timer select bits */ #define TCR_WP_0 0x00000000 /* WDT uses timer 0 */ #define TCR_WP_1 0x40000000 /* WDT uses timer 1 */ #define TCR_WP_2 0x80000000 /* WDT uses timer 2 */ #define TCR_WP_3 0xc0000000 /* WDT uses timer 3 */ #define TCR_WRC_MASK 0x30000000 /* Watchdog Reset Control mask */ #define TCR_WRC_NONE 0x00000000 /* WDT results in no action */ #define TCR_WRC_SOFT 0x10000000 /* WDT results in Soft reset */ #define TCR_WRC_HARD 0x20000000 /* WDT results in Hard reset */ #define TCR_WRC_HALT 0x30000000 /* WDT results in Halt */ #define TCR_WIE 0x08000000 /* Watchdog Interrupt Enable */ #define TCR_DIE 0x04000000 /* Decrementer Interrupt Enable */ #define TCR_FP_MASK 0x03000000 /* FIT Timer Select bits*/ #define TCR_FP_0 0x00000000 /* FIT uses timer 0 */ #define TCR_FP_1 0x01000000 /* FIT uses timer 1 */ #define TCR_FP_2 0x02000000 /* FIT uses timer 2 */ #define TCR_FP_3 0x03000000 /* FIT uses timer 3 */ #define TCR_FIE 0x00800000 /* FIT Interrupt Enable */ #define TCR_DS 0x00400000 /* Decrementer timer select: 0=every cycle, 1=use dec_timer input signal */ #ifndef __ASSEMBLER__ typedef union { uint32_t value; struct { unsigned int wp : 2; unsigned int wrc : 2; unsigned int wie : 1; unsigned int die : 1; unsigned int fp : 2; unsigned int fie : 1; unsigned int ds : 1; unsigned int reserved : 22; } fields; } Ppe42TCR; #endif /* __ASSEMBLER__ */ /* TSR - Timer Status Register */ #define TSR_ENW 0x80000000 /* Enable Next Watchdog */ #define TSR_WIS 0x40000000 /* Watchdog Interrupt Status */ #define TSR_WRS_MASK 0x30000000 /* Watchdog Reset Status */ #define TSR_WRS_NONE 0x00000000 /* No watchdog reset has occurred */ #define TSR_WRS_SOFT 0x10000000 /* Soft reset was forced by the watchdog */ #define TSR_WRS_HARD 0x20000000 /* Hard reset was forced by the watchdog */ #define TSR_WRS_HALT 0x30000000 /* Halt was forced by the watchdog */ #define TSR_DIS 0x08000000 /* Decrementer Interrupt Status */ #define TSR_FIS 0x04000000 /* FIT Interrupt Status */ /* PIR - Processor Identification Register */ #define PIR_PPE_TYPE_MASK 0x000000E0 #define PIR_PPE_TYPE_GPE 0x00000020 #define PIR_PPE_TYPE_CME 0x00000040 #define PIR_PPE_INSTANCE_MASK 0x0000001F #ifndef __ASSEMBLER__ /// Move From SPR /// /// Note that \a sprn must be a compile-time constant. #define mfspr(sprn) \ ({uint32_t __value; \ asm volatile ("mfspr %0, %1" : "=r" (__value) : "i" (sprn) : "memory"); \ __value;}) /// Move to SPR /// /// Note that \a sprn must be a compile-time constant. #define mtspr(sprn, value) \ ({uint32_t __value = (value); \ asm volatile ("mtspr %0, %1" : : "i" (sprn), "r" (__value) : "memory"); \ }) /// Read-Modify-Write an SPR with OR (Set SPR bits) /// /// Note that \a sprn must be a compile-time constant. This operation is only /// guaranteed atomic in a critical section. #define or_spr(sprn, x) \ mtspr(sprn, mfspr(sprn) | (x)) /// Read-Modify-Write an SPR with AND complement (Clear SPR bits) /// /// Note that \a sprn must be a compile-time constant. This operation is only /// guaranteed atomic in a critical section. #define andc_spr(sprn, x) \ mtspr(sprn, mfspr(sprn) & ~(x)) #endif /* __ASSEMBLER__ */ #ifdef __ASSEMBLER__ // *INDENT-OFF* /// \cond // Use this macro to define new mt<spr> and mf<spr> instructions that // may not exist in the assembler. .macro _sprinstrs, name, num .macro mt\name, reg mtspr \num, \reg .endm .macro mf\name, reg mfspr \reg, \num .endm .endm _sprinstrs dbcr, SPRN_DBCR _sprinstrs tcr, SPRN_TCR _sprinstrs tsr, SPRN_TSR _sprinstrs sprg0, SPRN_SPRG0 _sprinstrs ivpr, SPRN_IVPR _sprinstrs dec, SPRN_DEC /// \endcond // *INDENT-ON* #endif /* __ASSEMBLER__ */ #endif /* __PPE42_SPR_H__ */ <|start_filename|>src/occ_405/state.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/state.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _state_h #define _state_h #include <occ_common.h> #include <common_types.h> #include "rtls.h" #include "errl.h" #include "mode.h" // Maximum allowed value approx. 16.3 ms #define PCBS_HEARBEAT_TIME_US 16320 extern uint32_t G_smgr_validate_data_active_mask; extern uint32_t G_smgr_validate_data_observation_mask; enum eResetStates { RESET_NOT_REQUESTED = 0, NOMINAL_REQUESTED_DUE_TO_ERROR, RESET_REQUESTED_DUE_TO_ERROR, }; /** * @enum OCC_STATE * @brief Typedef of the various states that TMGT can put OCC into. */ typedef enum { OCC_STATE_NOCHANGE = 0x00, OCC_STATE_STANDBY = 0x01, OCC_STATE_OBSERVATION = 0x02, OCC_STATE_ACTIVE = 0x03, OCC_STATE_SAFE = 0x04, OCC_STATE_CHARACTERIZATION = 0x05, // Make sure this is after the last valid state OCC_STATE_COUNT, // These are used for state transition table, and are not // a valid state in and of itself. OCC_STATE_ALL = 0xFE, OCC_STATE_INVALID = 0xFF, } OCC_STATE; // These are the only states that TMGT/HTMGT can send #define OCC_STATE_IS_VALID(state) ((state == OCC_STATE_NOCHANGE) || \ (state == OCC_STATE_OBSERVATION) || \ (state == OCC_STATE_CHARACTERIZATION) || \ (state == OCC_STATE_ACTIVE)) /** * @brief TMGT Poll contains a byte that indicates status based on this * bitmask */ #define SMGR_MASK_MASTER_OCC 0x80 ///This is the master OCC #define SMGR_MASK_RESERVED_6 0x40 ///Reserved #define SMGR_MASK_RESERVED_5 0x20 ///Reserved #define SMGR_MASK_STATUS_REG_CHANGE 0x10 ///Change in status register #define SMGR_MASK_ATTN_ENABLED 0x08 ///Attentions to FSP are enabled #define SMGR_MASK_RESERVED_2 0x04 ///Reserved #define SMGR_MASK_OBSERVATION_READY 0x02 ///Observation Ready #define SMGR_MASK_ACTIVE_READY 0x01 ///Active Ready /** * @enum SMGR_VALIDATE_STATES * @brief Config Data Formats needed from TMGT to trans. between states * */ #define SMGR_VALIDATE_DATA_OBSERVATION_MASK_HARDCODES \ (DATA_MASK_SYS_CNFG | \ DATA_MASK_APSS_CONFIG | \ DATA_MASK_SET_ROLE | \ DATA_MASK_MEM_CFG | \ DATA_MASK_THRM_THRESHOLDS | \ DATA_MASK_AVSBUS_CONFIG ) #define SMGR_VALIDATE_DATA_ACTIVE_MASK G_smgr_validate_data_active_mask #define SMGR_VALIDATE_DATA_OBSERVATION_MASK G_smgr_validate_data_observation_mask #define SMGR_VALIDATE_DATA_ACTIVE_MASK_HARDCODES \ (SMGR_VALIDATE_DATA_OBSERVATION_MASK_HARDCODES | \ DATA_MASK_FREQ_PRESENT | \ DATA_MASK_PCAP_PRESENT ) // Used by OCC FW to request an OCC Reset because of an error. // It's the action flag that actually requests the reset. // Severity will be set to UNRECOVERABLE if it is INFORMATIONAL. #define REQUEST_RESET(error_log) \ {\ reset_state_request(RESET_REQUESTED_DUE_TO_ERROR);\ setErrlActions(error_log, ERRL_ACTIONS_RESET_REQUIRED);\ commitErrl(&error_log);\ } #define REQUEST_SAFE_MODE(error_log) \ {\ reset_state_request(RESET_REQUESTED_DUE_TO_ERROR);\ setErrlActions(error_log, ERRL_ACTIONS_SAFE_MODE_REQUIRED);\ commitErrl(&error_log);\ } #define REQUEST_WOF_RESET(error_log) \ {\ reset_state_request(RESET_REQUESTED_DUE_TO_ERROR);\ setErrlActions(error_log, ERRL_ACTIONS_WOF_RESET_REQUIRED);\ commitErrl(&error_log);\ } // Used by OCC FW to request that OCC go to Nominal because of an error #define REQUEST_NOMINAL() reset_state_request(NOMINAL_REQUESTED_DUE_TO_ERROR); // Used by OCC FW to signify that OCC can leave Nominal state because the // error that caused OCC to go to Nominal has cleared. #define CLEAR_NOMINAL() reset_state_request(RESET_NOT_REQUESTED); // Used to indicate that OCC has established TMGT Comm, and should no longer // halt() on a reset request. #define DISABLE_HALT_ON_RESET_REQUEST() reset_disable_halt(); // Returns the current OCC State #define CURRENT_STATE() G_occ_internal_state // Returns the 'OCC Requested' OCC State #define REQUESTED_STATE() G_occ_internal_req_state // Returns true if OCC State is active #define IS_OCC_STATE_ACTIVE() ( (OCC_STATE_ACTIVE == G_occ_internal_state)? 1 : 0 ) // Returns true if OCC State is observation #define IS_OCC_STATE_OBSERVATION() ( (OCC_STATE_OBSERVATION == G_occ_internal_state)? 1 : 0 ) // Returns true if OCC State is charaterization #define IS_OCC_STATE_CHARACTERIZATION() ( (OCC_STATE_CHARACTERIZATION == G_occ_internal_state)? 1 : 0 ) /** * @struct smgr_state_trans_t * @brief Used by the "Set State" command to call the correct transition * function, based on the current & new states. */ typedef struct { uint8_t old_state; uint8_t new_state; errlHndl_t (*trans_func_ptr)(void); } smgr_state_trans_t; extern OCC_STATE G_occ_internal_state; extern OCC_STATE G_occ_internal_req_state; extern OCC_STATE G_occ_master_state; extern OCC_STATE G_occ_external_req_state; // State Transition Function Calls errlHndl_t SMGR_standby_to_observation(); errlHndl_t SMGR_standby_to_characterization(); errlHndl_t SMGR_standby_to_active(); errlHndl_t SMGR_observation_to_characterization(); errlHndl_t SMGR_observation_to_active(); errlHndl_t SMGR_characterization_to_observation(); errlHndl_t SMGR_characterization_to_active(); errlHndl_t SMGR_active_to_observation(); errlHndl_t SMGR_active_to_characterization(); errlHndl_t SMGR_all_to_standby(); errlHndl_t SMGR_all_to_safe(); inline bool SMGR_is_state_transitioning(void); // Used by macro above to clear flag indicating to not halt OCC when a reset // is requested. inline void reset_disable_halt(void); // Used to see if anyone has requested reset/safe state bool isSafeStateRequested(void); // Used by macros to request reset states extenally void reset_state_request(uint8_t i_request); // Task that will check for checkstop void task_check_for_checkstop(task_t *i_self); // Used to set OCC State errlHndl_t SMGR_set_state(OCC_STATE i_state); // Used to indicate which OCC States are valid, given the config data/system // parms we currently know. uint8_t SMGR_validate_get_valid_states(void); #endif // _state_h <|start_filename|>src/occ_405/rtls/rtls.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/rtls/rtls.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _RTLSCH_H #define _RTLSCH_H #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include "occhw_async.h" typedef struct task { uint32_t flags; void (*func_ptr)(struct task*); void *data_ptr; }task_t; // Task ID values // These are used as indices into the task table defined below. typedef enum { TASK_ID_APSS_START = 0x00, TASK_ID_CORE_DATA_LOW, TASK_ID_APSS_CONT, TASK_ID_CORE_DATA_HIGH, TASK_ID_APSS_DONE, TASK_ID_DCOM_RX_INBX, TASK_ID_DCOM_TX_INBX, TASK_ID_POKE_WDT, // Reset ppc405 watchdog and OCB timer TASK_ID_DCOM_WAIT_4_MSTR, TASK_ID_DCOM_RX_OUTBX, TASK_ID_DCOM_TX_OUTBX, TASK_ID_MISC_405_CHECKS, // Miscellaneous checks to be done by 405 TASK_ID_DCOM_PARSE_FW_MSG, TASK_ID_AMEC_SLAVE, // AMEC SMH tasks TASK_ID_AMEC_MASTER, // AMEC SMH tasks TASK_ID_CORE_DATA_CONTROL, TASK_ID_GPU_SM, // GPU State Machine TASK_ID_DIMM_SM, // DIMM State Machine TASK_ID_MEMORY_CONTROL, // Memory (centaur/dimm) control task TASK_ID_NEST_DTS, TASK_ID_24X7, // 24x7 data collection task TASK_ID_GPE_TIMINGS, TASK_ID_GET_TOD, // Get time of day task TASK_ID_APSS_RESET, // (HW) reset APSS TASK_END // This must always be the last enum in this list, // so that TASK_END always equals the last task ID + 1. } task_id_t; // Structure containing the durations measured within a tick typedef struct { uint32_t rtl_dur; // Duration of RTL tick interrupt uint32_t ameint_dur; // Combined duration of mstr & slv AMEC tasks uint32_t amess_dur; // Combined duration of last mstr & slv AMEC state uint8_t amess_state; // Last AMEC state that was run uint64_t rtl_start; // SsxTimebase of Start of current RTL Tick uint64_t rtl_start_gpe[2]; // SsxTimebase of Start of current RTL Tick (for GPE > 1 tick) uint32_t gpe_dur[2]; // Duration of the GPE Engines / tick GpeRequest* gpe0_timing_request; // GPE Request that facilitates GPE WC meas GpeRequest* gpe1_timing_request; // GPE Request that facilitates GPE WC meas } fw_timing_t; // Bit flags to define when a task can run // NOTE: whenever new flag is added, it must also be added to the // RTL_ALL_FLAGS define. #define RTL_FLAG_NONE 0x00000000 // Task has been turned off permanently #define RTL_FLAG_RUN 0x00000001 // Task has been requested to run #define RTL_FLAG_MSTR 0x00000002 // Task can run on the master #define RTL_FLAG_NOTMSTR 0x00000004 // Task can run on non-masters #define RTL_FLAG_OBS 0x00000008 // Task can run in observation state #define RTL_FLAG_ACTIVE 0x00000010 // Task can run in active state #define RTL_FLAG_RST_REQ 0x00000020 // Task can run after a reset request #define RTL_FLAG_NO_APSS 0x00000040 // Task can run with no APSS present #define RTL_FLAG_MSTR_READY 0x00000080 // Task can run Master is ready #define RTL_FLAG_STANDBY 0x00000100 // Task can run in Standby state #define RTL_FLAG_APSS_NOT_INITD 0x00000200 // Task can run while APSS is not initialized #define RTL_ALL_FLAGS (RTL_FLAG_RUN | RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | \ RTL_FLAG_OBS | RTL_FLAG_ACTIVE | RTL_FLAG_RST_REQ | \ RTL_FLAG_NO_APSS | RTL_FLAG_MSTR_READY | RTL_FLAG_STANDBY | \ RTL_FLAG_APSS_NOT_INITD) #define MEMORY_CONTROL_RTL_FLAGS (RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_ACTIVE | \ RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | \ RTL_FLAG_APSS_NOT_INITD) #define MEMORY_DATA_RTL_FLAGS (RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | \ RTL_FLAG_ACTIVE | RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | \ RTL_FLAG_RUN | RTL_FLAG_APSS_NOT_INITD) #define GPU_RTL_FLAGS (RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_OBS | RTL_FLAG_ACTIVE | \ RTL_FLAG_MSTR_READY | RTL_FLAG_NO_APSS | RTL_FLAG_RUN | \ RTL_FLAG_APSS_NOT_INITD) // Tick Timer definitions: #define MICS_PER_TICK G_mics_per_tick // Number of micro-seconds per tick #define MAX_NUM_TICKS 16 // Number of entries in the global tick table (power of 2) // MICS_PER_TICK must be lower than 62ms to guarantee the tick table completes in < 1s (for health monitor) #define HW_MICS_PER_TICK 500 #define SIMICS_MICS_PER_TICK 20000 // slow down RTL to 20ms for Simics #define DCOM_TX_APSS_WAIT_TIME G_dcom_tx_apss_wait_time // core data collection time. All cores collected one time thru tick table #define CORE_DATA_COLLECTION_US (MICS_PER_TICK * MAX_NUM_TICKS) //Number of samples per second for performance-related algorithms (e.g. UTILCy) #define AMEC_DPS_SAMPLING_RATE (1000000 / CORE_DATA_COLLECTION_US) //Time interval for averaging utilization and frequency (IPS algorithm) 3 seconds #define AMEC_IPS_AVRG_INTERVAL 3 // NOTE: for IPS timings to work, need to make sure the check for amec_mst_ips_main() is at the same frequency // i.e. core data is collected every CORE_DATA_COLLECTION_US the checking for amec_mst_ips_main() must be same. // If core data collection time changes must adjust the checking for amec_mst_ips_main() to match // The value of the current tick extern uint32_t G_current_tick; // The number of micro-seconds per tick extern uint32_t G_mics_per_tick; // The number of micro-seconds to wait for APSS data to complete extern uint32_t G_dcom_tx_apss_wait_time; // The durations measured within the current tick extern fw_timing_t G_fw_timing; // Preferred macro for accessing the current tick value #define CURRENT_TICK G_current_tick // Responsible for initializing the hardware timer in occ control block. // It is the timer that supplies the periodic RTL interrupt. void rtl_ocb_init(void) INIT_SECTION; // RTL intr handler, a full-mode handler that invokes through the macro brige // Runs all tasks in the current tick sequence. void rtl_do_tick(void *private, SsxIrqId irq, int priority); // Request that a task runs, starting the next time it comes up // in a tick sequence. void rtl_start_task(const task_id_t i_task_id); // Request that a task NOT run any time it comes up in a tick sequence. void rtl_stop_task(const task_id_t i_task_id); // Find out if a task can run or not. bool rtl_task_is_runnable(const task_id_t i_task_id); // Changes the data pointer for the specified task. void rtl_set_task_data(const task_id_t i_task_id, void* i_data_ptr); // Stores the bitwise-or of i_flag and the global run mask // into the global run mask. void rtl_set_run_mask(const uint32_t i_flags); void rtl_set_run_mask_deferred( const uint32_t i_flags ); // Stores the bitwise-and of the inverse of i_flag and the global run mask // into the global run mask. void rtl_clr_run_mask(const uint32_t i_flags); void rtl_clr_run_mask_deferred( const uint32_t i_flags ); #endif //_RTLSCH_H <|start_filename|>src/occ_gpe0/firdata/ecc.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ/firdata/ecc.H $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PNOR_ECC_H #define __PNOR_ECC_H #include <native.h> /** @file ecc.H * @brief Interfaces for the P8 8-byte ECC algorithm. */ /** Status for the ECC removal function. */ typedef uint8_t eccStatus; #define ECC_CLEAN 0x00 /*< No ECC Error was detected. */ #define ECC_CORRECTED 0x01 /*< ECC error detected and corrected. */ #define ECC_UNCORRECTABLE 0x02 /*< ECC error detected and uncorrectable. */ /** Bit field identifiers for syndrome calculations. */ typedef uint8_t eccBitfields; #define ECC_GD 0xff /*< Good ECC matches. */ #define ECC_UE 0xfe /*< Uncorrectable. */ #define ECC_E0 71 /*< Error in ECC bit 0 */ #define ECC_E1 70 /*< Error in ECC bit 1 */ #define ECC_E2 69 /*< Error in ECC bit 2 */ #define ECC_E3 68 /*< Error in ECC bit 3 */ #define ECC_E4 67 /*< Error in ECC bit 4 */ #define ECC_E5 66 /*< Error in ECC bit 5 */ #define ECC_E6 65 /*< Error in ECC bit 6 */ #define ECC_E7 64 /*< Error in ECC bit 7 */ /** Inject ECC into a data stream. * * @param[in] i_src - Source data to create ECC on. * @param[in] i_srcSz - Size in bytes of source data. * @param[out] o_dst - Destination buffer of data+ECC. * * @note i_srcSz must be a multiple of 8 bytes. */ void injectECC(const uint8_t* i_src, uint32_t i_srcSz, uint8_t* o_dst); /** Remove ECC from a data stream. * * @param[in,out] io_src - Source data+ECC stream. * @param[out] o_dst - Destination buffer for data only. * @param[in] i_dstSz - Size in bytes of destination ((srcSz / 9) * 8). * * @note i_dstSz must be a multiple of 8 bytes. */ eccStatus removeECC(uint8_t* io_src, uint8_t* o_dst, uint32_t i_dstSz); #endif <|start_filename|>src/ssx/ppc405/ppc405_core.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_core.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppc405_core.c /// \brief The final bits of SSX runtime code required to complete the PPC405 /// port. /// /// The entry points in this file are considered 'core' routines that will /// always be present during runtime in any SSX application. #define __PPC405_CORE_C__ #include "ssx.h" // Even though the external timebase is only a 32 bit register, we emulate // a 64 bit timebase by keeping the upper 32 bits in SRAM. volatile SsxTimebase ppc405_64bit_ext_timebase = 0; #if APPCFG_USE_EXT_TIMEBASE_FOR_TRACE typedef union { struct { uint32_t tbu; uint32_t tbl; }; SsxTimebase tb64; } SsxExtTimebase; SsxTimebase ssx_ext_timebase_get(void) { SsxExtTimebase snapshot; volatile SsxExtTimebase* cur_tb = (SsxExtTimebase*)&ppc405_64bit_ext_timebase; uint32_t tbr; uint32_t high; //read our in-memory timebase accumulator. //NOTE: 64 bit reads are not atomic on the ppc405. This means that the //accumulator can be updated between reading the upper 32 bits and lower //32 bits. It's ok if only the lower 32 bits changed, but if the upper //32 bits changed, then we will report the wrong time stamp. Therefore, //we check the upper 32 bits after reading the lower 32 bits to make sure //it hasn't changed. do { snapshot.tbu = cur_tb->tbu; snapshot.tbl = cur_tb->tbl; high = cur_tb->tbu; } while(snapshot.tbu != high); //Now read the external timebase register tbr = in32(OCB_OTBR); //Check if we need to increment the upper 32 bits if(tbr < snapshot.tbl) { snapshot.tbu++; } snapshot.tbl = tbr; return snapshot.tb64; } #endif /* APPCFG_USE_EXT_TIMEBASE_FOR_TRACE */ /// Get the 64-bit timebase following the PowerPC protocol /// /// Note that the only way to guarantee that the value returned is the value /// \e right \e now is to call this API from a critical section. SsxTimebase ssx_timebase_get(void) { Uint64 tb; uint32_t high; do { tb.word[0] = mftbu(); tb.word[1] = mftb(); high = mftbu(); } while (high != tb.word[0]); return tb.value; } /// Set the 64-bit timebase in an SSX_CRITICAL critical section /// /// It is assumed that the caller knows what they are doing; e.g., is aware of /// what may happen when time warps as a result of this call. void ssx_timebase_set(SsxTimebase timebase) { SsxMachineContext ctx; Uint64 tb; tb.value = timebase; ssx_critical_section_enter(SSX_CRITICAL, &ctx); mttbl(0); mttbu(tb.word[0]); mttbl(tb.word[1]); ssx_critical_section_exit(&ctx); } /// Enable interrupt preemption /// /// This API can only be called from an interrupt context. Threads will /// always be preempted by interrupts unless they explicitly disable /// interrupts with the \c ssx_interrupt_disable() API. It is legal to call /// this API redundantly. /// /// Be careful when enabling interrupt handler preemption that the interrupt /// being handled does not/can not trigger again, as this could rapidly lead /// to stack overflows. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_ILLEGAL_CONTEXT The API call was not made from an interrupt /// context. int ssx_interrupt_preemption_enable() { if (SSX_ERROR_CHECK_API) { SSX_ERROR_UNLESS_ANY_INTERRUPT_CONTEXT(); } if (__ssx_kernel_context_noncritical_interrupt()) { wrteei(1); } else { or_msr(MSR_CE); } return SSX_OK; } /// Disable interrupt preemption /// /// This API can only be called from an interrupt context. Threads will /// always be preempted by interrupts unless they explicitly disable /// interrupts with the \c ssx_interrupt_disable() API. It is legal to call /// this API redundantly. /// /// Return values other then SSX_OK (0) are errors; see \ref ssx_errors /// /// \retval 0 Successful completion /// /// \retval -SSX_ILLEGAL_CONTEXT The API call was not made from an interrupt /// context. int ssx_interrupt_preemption_disable() { if (SSX_ERROR_CHECK_API) { SSX_ERROR_UNLESS_ANY_INTERRUPT_CONTEXT(); } if (__ssx_kernel_context_noncritical_interrupt()) { wrteei(0); } else { andc_msr(MSR_CE); } return SSX_OK; } #if SSX_TIMER_SUPPORT // The tickless kernel timer mechanism for PPC405 // // This routine must be called from an SSX_NONCRITICAL critical section. // // Tickless timeouts are provided by programming the PIT timer based on when // the next timeout will occur. If the timeout is for the end of time there's // nothing to do - SSX does not use auto-reload mode so no more PIT interrupts // will be arriving. Otherwise, if the timeout is longer than the 32-bit PIT // timer can handle, we simply schedule the timeout for 2**32 - 1 and // __ssx_timer_handler() will keep rescheduling it until it finally occurs. // If the \a timeout is in the past, we schedule the PIT interrupt for 1 tick // in the future in accordance with the SSX specification. void __ssx_schedule_hardware_timeout(SsxTimebase timeout) { SsxTimebase now; uint32_t pit; if (timeout != SSX_TIMEBASE_MAX) { now = ssx_timebase_get(); if (timeout <= now) { pit = 1; } else if ((timeout - now) > 0xffffffff) { pit = 0xffffffff; } else { pit = timeout - now; } mtspr(SPRN_PIT, pit); #if APPCFG_USE_EXT_TIMEBASE_FOR_TRACE ppc405_64bit_ext_timebase = ssx_ext_timebase_get(); #endif /* APPCFG_USE_EXT_TIMEBASE_FOR_TRACE */ } } // Cancel the PPC405 tickless kernel timeout // // This routine must be called from an SSX_NONCRITICAL critical section. SSX // does not use auto-reload mode of the PIT, so simply writing the PIT with 0 // effectively cancels the timer. void __ssx_cancel_hardware_timeout() { mtspr(SPRN_PIT, 0); } #endif /* SSX_TIMER_SUPPORT */ #undef __PPC405_CORE_C__ <|start_filename|>src/lib/ppc405lib/chip_config.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/chip_config.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __CHIP_CONFIG_H__ #define __CHIP_CONFIG_H__ /// \file chip_config.h /// \brief Chip configuration data structures for OCC procedures #ifndef __ASSEMBLER__ #include <stdint.h> /// A bitmask defining a chip configuration /// /// Since we are using the conventional big-endian notation, any use of these /// bitmasks requires that the data being tested is of this type - otherwise /// the masks won't work. /// /// Layout: /// /// Bits 0:15 - Core chiplet 0..15 is configured /// Bits 16:23 - MCS 0..7 is configured /// Bits 24:31 - Centaur 0..7 is configured typedef uint64_t ChipConfig; typedef uint16_t ChipConfigCores; typedef uint8_t ChipConfigMcs; typedef uint8_t ChipConfigCentaur; /// Convert a ChipConfig into a mask suitable for use as the 32-bit chiplet /// mask argument of a PORE wakeup program. #if 0 static inline uint32_t pore_exe_mask(ChipConfig config) { return (uint32_t)((config >> 32) & 0xffffff00); } #endif /// Left justify and mask core chiplet configuration into a uint32_t static inline uint32_t left_justify_core_config(ChipConfig config) { return (uint32_t)((config >> 32) & 0xffffff00); } /// Left justify and mask MCS configuration into a uint32_t static inline uint32_t left_justify_mcs_config(ChipConfig config) { return (uint32_t)((config >> 16) & 0xff000000); } /// Left justify and mask Centaur configuration into a uint32_t static inline uint32_t left_justify_centaur_config(ChipConfig config) { return (uint32_t)((config >> 8) & 0xff000000); } #endif // __ASSEMBLER__ #endif /* __CHIP_CONFIG_H__ */ <|start_filename|>src/occ_gpe0/firdata/firData.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ/firdata/firData.H $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __firData_h #define __firData_h #include "native.h" /** @brief Reads the register list from the HOMER data, SCOMs hardware, and * stores the register values in PNOR. * @param i_hBuf SRAM pointer to the beginning of the HOMER data buffer. * This should contain the FIR data information provided by * PRD that is used to define which registers the OCC will * need to SCOM. * @param i_hBufSize Total size of the HOMER data buffer. * @param i_pBuf SRAM pointer to the beginning of the PNOR data buffer. * This will be used by this function as a temporary area * of memory to store the PNOR data before writing that * data to the PNOR. * @param i_pBufSize Total size of the PNOR data buffer. * @return Non-SUCCESS if an internal function fails. SUCCESS otherwise. */ int32_t FirData_captureCsFirData( uint8_t * i_hBuf, uint32_t i_hBufSize, uint8_t * i_pBuf, uint32_t i_pBufSize ); #endif /* __firData_h */ <|start_filename|>src/ppe/pk/ppe42/ppe42_irq_init.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42_irq_init.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------- // *! (C) Copyright International Business Machines Corp. 2014 // *! All Rights Reserved -- Property of IBM // *! *** IBM Confidential *** //----------------------------------------------------------------------------- /// \file ppe42_irq_init.c /// \brief PPE42 IRQ initialization routines /// /// The entry points in this file are routines that are typically used during /// initialization, and their code space could be deallocated and recovered if /// no longer needed by the application after initialization. #include "pk.h" /// Set up a PPE42 Fixed Interval Timer (FIT) handler /// /// See the PK specification for full details on setting up a FIT handler. /// /// Return values other then PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// int ppe42_fit_setup(PkIrqHandler handler, void* arg) { PkMachineContext ctx; Ppe42TCR tcr; pk_critical_section_enter(&ctx); tcr.value = mfspr(SPRN_TCR); if (handler) { tcr.fields.fp = 0; tcr.fields.fie = 1; __ppe42_fit_routine = handler; __ppe42_fit_arg = arg; } else { tcr.fields.fie = 0; } mtspr(SPRN_TCR, tcr.value); sync(); pk_critical_section_exit(&ctx); return PK_OK; } <|start_filename|>src/occ_405/lock/lock.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/lock/lock.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _LOCK_H #define _LOCK_H #include <occ_common.h> #include <dimm.h> // Release the OCC lock indefinitely // This should be called when OCC goes into safe mode or will be reset // to allow the host to use the specified I2C engines. // Use PIB_I2C_ENGINE_ALL, if locks for all I2C engines should be released void occ_i2c_lock_release(const uint8_t i_engine); // Check and update lock ownership for the specified i2c engine // If host has requesed lock, and there is no other outstanding interrupt // release the lock, generate and external interrupt and return false. // If the host has not released the lock, set ownership back to OCC and // return true. // // Returns true if OCC owns the lock, or false if host owns lock bool check_and_update_i2c_lock(const uint8_t i_engine); #endif //_LOCK_H <|start_filename|>src/occ_gpe0/firdata/scom_trgt.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ/firdata/scom.H $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __scom_trgt_h #define __scom_trgt_h #include <firDataConst_common.h> #include <native.h> typedef struct { /** See enum TrgtType_t. NOTE: This value is not consistant with Hostboot * target types. */ TrgtType_t type; /** Absolute position of the connected PROC within the node. This value * should be consistant with the Hostboot target positions. */ uint8_t procPos; /** Unit position relative to the connected PROC. This value should be * consistant with the Hostboot target positions. */ uint8_t procUnitPos; /** Indicates this target is, or is connected to, the master processor. */ bool isMaster; /** This target's FSI base address. */ uint32_t fsiBaseAddr; } SCOM_Trgt_t; /** @param i_type See enum Type. * @param i_procPos Absolute position within the node of the connected * PROC target. * @param i_procUnitPos Unit position relative to the connected PROC. Will be * explicitly set to 0 for PROC targets. * @param i_fsiBaseAddr For EX and MCS, the FSI base address for the * connected PROC. For MEMB and MBA, the FSI base * address for the connected MEMB. * @param i_isMaster True, if this target is, or is connected to, the * master processor. False, otherwise. Will be explicitly * set to false for MEMB and MBA targets. * @return A SCOM_Trgt_t struct. */ SCOM_Trgt_t SCOM_Trgt_getTrgt( TrgtType_t i_type, uint8_t i_procPos, uint8_t i_procUnitPos, uint32_t i_fsiBaseAddr, bool i_isMaster ); /** @param i_trgt The SCOM target. * @return This target's absolute position of the parent chip (PROC or * MEMB) within the node. */ uint8_t SCOM_Trgt_getChipPos( SCOM_Trgt_t i_trgt ); /** @param i_trgt The SCOM target. * @return This target's unit position relative to the parent chip. Only * valid for EX, MCS, and MBA units. Will return 0 for PROC and * MEMB chips. */ uint8_t SCOM_Trgt_getChipUnitPos( SCOM_Trgt_t i_trgt ); /** @param i_trgt The SCOM target. * @return A target for the containing parent chip (PROC or MEMB). */ SCOM_Trgt_t SCOM_Trgt_getParentChip( SCOM_Trgt_t i_trgt ); #endif /* __scom_trgt_h */ <|start_filename|>src/occ_gpe0/firdata/scom_addr_util.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/scom_addr_util.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "scom_addr_util.h" void set_sat_id(const uint8_t i_sat_id, uint64_t * o_addr) { *o_addr &= 0xFFFFFFFFFFFFFC3FULL; *o_addr |= ((i_sat_id & 0xF) << 6); } void set_chiplet_id(const uint8_t i_chiplet_id, uint64_t * o_addr) { *o_addr &= 0xFFFFFFFFC0FFFFFFULL; *o_addr |= ((i_chiplet_id & 0x3F) << 24); } void set_ring(const uint8_t i_ring, uint64_t * o_addr) { *o_addr &= 0xFFFFFFFFFFFF03FFULL; *o_addr |= ((i_ring & 0x3F) << 10); } void set_sat_offset(const uint8_t i_sat_offset, uint64_t * o_addr) { *o_addr &= 0xFFFFFFFFFFFFFFC0ULL; *o_addr |= (i_sat_offset & 0x3F); } void set_rxtx_group_id(const uint8_t i_grp_id, uint64_t * o_addr) { *o_addr &= 0xFFFFF81FFFFFFFFFULL; *o_addr |= (i_grp_id & 0x3FULL) << 37; } uint8_t get_sat_id(const uint64_t i_addr) { return ((i_addr >> 6) & 0xF); } uint8_t get_chiplet_id(const uint64_t i_addr) { return ((i_addr >> 24) & 0x3F); } uint8_t get_ring(const uint64_t i_addr) { return ((i_addr >> 10) & 0x3F); } uint8_t get_sat_offset(const uint64_t i_addr) { return (i_addr & 0x3F); } uint8_t get_rxtx_group_id(const uint64_t i_addr) { return (i_addr >> 37) & 0x3F; } <|start_filename|>src/ppe/pk/ppe42/ppe42_scom.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42_scom.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ppe42_scom.c /// \brief Lowest level PK SCOM definitions. /// /// Currently these SCOM functions are only optimized for functionality, not /// speed. Speed optimization will be done when we have full compiler support /// for the low-level stvd and lvd SCOM OPs. /// /// A FAPI-lite SCOM can call these PK SCOM functions. /// /// Comment: /// - No need to poll for SCOM completion, nor return error code of SCOM fails. /// A SCOM fail will cause the GPE to hang if configured to do so. But do we /// necessarily have to do this? Wouldn't a gentle recovery from a SCOM fail /// be preferred? #include "pk.h" #include "ppe42_scom.h" #include "ppe42_msr.h" uint32_t putscom_abs(const uint32_t i_address, uint64_t i_data) { // Perform the Store Virtual Double instruction PPE_STVD(i_address, i_data); // Get the MSR[SIBRC] as the return code uint32_t rc = mfmsr(); rc = ((rc & MSR_SIBRC) >> (32 - (MSR_SIBRC_START_BIT + MSR_SIBRC_LEN))); return (rc); } uint32_t _putscom( uint32_t i_chiplet_id, uint32_t i_address, uint64_t i_data) { // Perform the Store Virtual Double Index instruction PPE_STVDX(i_chiplet_id, i_address, i_data); // Get the MSR[SIBRC] as the return code uint32_t rc = mfmsr(); rc = ((rc & MSR_SIBRC) >> (32 - (MSR_SIBRC_START_BIT + MSR_SIBRC_LEN))); return (rc); } uint32_t getscom_abs( const uint32_t i_address, uint64_t* o_data) { uint64_t temp; // Perform the Load Virtual Double instruction PPE_LVD(i_address, temp); PPE_STVD(o_data, temp); // Get the MSR[SIBRC] as the return code uint32_t rc = mfmsr(); rc = ((rc & MSR_SIBRC) >> (32 - (MSR_SIBRC_START_BIT + MSR_SIBRC_LEN))); return (rc); } uint32_t _getscom( const uint32_t i_chiplet_id, const uint32_t i_address, uint64_t* o_data) { uint64_t temp; // Perform the Load Virtual Double Index instruction PPE_LVDX(i_chiplet_id, i_address, temp); PPE_STVD(o_data, temp); // Get the MSR[SIBRC] as the return code uint32_t rc = mfmsr(); rc = ((rc & MSR_SIBRC) >> (32 - (MSR_SIBRC_START_BIT + MSR_SIBRC_LEN))); return (rc); } <|start_filename|>src/common/i2c.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/common/i2c.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _I2C_H #define _I2C_H // I2C SCOM Addresses: // (There are unique constants/addresses per engine, but to make the calls generic, // these constants are defined instead of using the base constants) #define PIB_BASE 0x000A0000 // Engine B 0x00A0000 // Engine C 0x00A1000 // Engine D 0x00A2000 // Engine E 0x00A3000 // Fast mode I2C registers #define I2C_FM_CTRL_REG 0x000A0000 // Write only #define I2C_FM_DATA_8TO15_REG 0x000A0001 // Read-only #define I2C_FM_RESET_I2C_REG 0x000A0001 // Write #define I2C_FM_STATUS_REG 0x000A0002 #define I2C_FM_DATA_0TO7_REG 0x000A0003 // First 8 bytes of read, 5th to 12th bytes of write // Typical I2C registers #define I2C_FIFO1_REG_READ 0x000A0004 #define I2C_COMMAND_REG 0x000A0005 #define I2C_MODE_REG 0x000A0006 #define I2C_INTERRUPT_MASK_REG 0x000A0008 #define I2C_STATUS_REG 0x000A000B // read #define I2C_IMM_RESET_I2C 0x000A000B // write #define I2C_BUSY_REGISTER 0x000A000E #define I2C_FIFO4_REG_READ 0x000A0012 #define SCOM_ENGINE_OFFSET(engine) (engine << 12) // Fast mode I2C status register masks #define FM_STATUS_ERROR_MASK 0x000000000007E400 #define FM_ERROR_OR_COMPLETE_MASK 0x000000000007FC00 #define FM_STATUS_COMPLETE_MASK 0x0000000000000800 #define FM_STATUS_DATA_REQ_MASK 0x0000000000001000 // I2C Status Register masks #define STATUS_ERROR_MASK 0xFC80000000000000 #define STATUS_ERROR_OR_COMPLETE_MASK 0xFF80000000000000 #define STATUS_COMPLETE_MASK 0x0100000000000000 #define PEEK_ERROR_MASK 0x00000000FC000000 #define PEEK_MORE_DATA 0x0000000002000000 // 0-15: Bit Rate Divisor - 0x0049 gives approx 391kHz (and allows margin for clock variation) // 16-21: Port Number (0-5) // 22-26: reserved (0s) #define I2C_MODE_REG_DIVISOR 0x0049000000000000 typedef enum { PIB_I2C_ENGINE_C = 0x01, PIB_I2C_ENGINE_D = 0x02, PIB_I2C_ENGINE_E = 0x03, PIB_I2C_ENGINE_ALL = 0xFF, } PIB_I2C_ENGINE; #endif // _I2C_H <|start_filename|>src/lib/ppc405lib/ssx_dump.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/ssx_dump.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file ssx_dump.c /// \brief Routines for dumping SSX kernel data structures /// /// \note This is a quick hack to help solve a P8 bringup issue. This code is /// PPC405 (OCC) specific, i.e., not "portable" SSX. Ideally this type of dump /// would be implemented in an external debugging tool as well, however it's /// simplest to implement here in the execution context. #include "ssx_dump.h" #define SSX_DUMP_UNIMPLEMENTED 0x00d86701 static const char* _threadState[] = { 0, "Suspended Runnable", "Mapped", "Suspended Blocked", "Completed", "Deleted", }; static const char* _threadFlags[] = { 0, "Semaphore Pend", "Timer Pend", "Timer Pend | Semaphore Pend", "Timed Out", "Timed Out | Semaphore Pend", "Timed Out | Timer Pend", "Timed Out | Timer Pend | Semaphore Pend", }; static void _dumpTimer(FILE* stream, SsxTimer* timer) { fprintf(stream, "-- Timer @ %p\n" "-- Deque.previous = %p\n" "-- Deque.next = %p\n" "-- Timeout = 0x%016llx\n" "-- Period = 0x%016llx\n" "-- Callback = %p\n" "-- Arg = %p\n" "-- Options = 0x%02x\n", timer, timer->deque.previous, timer->deque.next, timer->timeout, (unsigned long long)(timer->period), timer->callback, timer->arg, timer->options); } static void _dumpThread(FILE* stream, SsxThread* thread) { SsxThreadContext* threadCtx; SsxThreadContextFullIrq* threadCtxIrq; uint32_t srr[4], lr, sp; fprintf(stream, "-- Thread mapped at priority %d (%p)\n" "-- Thread state = %s (%d)\n" "-- Thread flags = %s (0x%02x)\n" "-- Saved Stack Pointer = %p\n", thread->priority, thread, _threadState[thread->state], thread->state, _threadFlags[thread->flags], thread->flags, (void*)thread->saved_stack_pointer); if (thread->flags & SSX_THREAD_FLAG_SEMAPHORE_PEND) { fprintf(stream, "-- Semaphore = %p\n", (void*)thread->semaphore); } fprintf(stream, "---------------------------------------------\n"); if (thread->flags & SSX_THREAD_FLAG_TIMER_PEND) { _dumpTimer(stream, &(thread->timer)); fprintf(stream, "---------------------------------------------\n"); } if ((thread == ssx_current()) && !__ssx_kernel_context_any_interrupt()) { fprintf(stream, "-- This thread is executing ssx_dump()\n"); } else { if (thread == ssx_current()) { // This is the interrupted thread, and only has its volatile // context saved. The thread stack pointer is stored in a global // kernel variable. if (__ssx_kernel_context_critical_interrupt()) { SSX_PANIC(SSX_DUMP_UNIMPLEMENTED); srr[0] = srr[1] = srr[2] = srr[3] = lr = sp = 0; /* For GCC */ } else { threadCtxIrq = (SsxThreadContextFullIrq*)__ssx_saved_sp_noncritical; srr[0] = threadCtxIrq->srr0; srr[1] = threadCtxIrq->srr1; srr[2] = threadCtxIrq->srr2; srr[3] = threadCtxIrq->srr3; lr = threadCtxIrq->lr; sp = threadCtxIrq->r1; } } else { // This is a fully swapped-out thread. The context is saved in // at the stored stack pointer. threadCtx = (SsxThreadContext*)(thread->saved_stack_pointer); srr[0] = threadCtx->srr0; srr[1] = threadCtx->srr1; srr[2] = threadCtx->srr2; srr[3] = threadCtx->srr3; lr = threadCtx->lr; sp = ((uint32_t*)threadCtx->r1)[0]; } fprintf(stream, "-- SRR0: 0x%08x SRR1: 0x%08x " "SRR2: 0x%08x SRR3: 0x%08x\n" "-- LR: 0x%08x\n", srr[0], srr[1], srr[2], srr[3], lr); fprintf(stream, "---------------------------------------------\n"); // Unwind the stack while (sp != 0) { fprintf(stream, "-- SP: 0x%08x *LR*:0x%08x\n", sp, ((uint32_t*)sp)[1]); sp = ((uint32_t*)sp)[0]; } } } void ssx_dump(FILE* stream, int options) { int i, sep; SsxThread* thread; fprintf(stream, "------------------------------------------------------------\n"); fprintf(stream, "-- SSX Kernel Dump @ 0x%016llx\n" "-- USPRG0 = 0x%08x\n" "-- __ssx_run_queue = 0x%08x\n", ssx_timebase_get(), mfspr(SPRN_USPRG0), __ssx_run_queue); fprintf(stream, "------------------------------------------------------------\n"); sep = 0; for (i = 0; i < SSX_THREADS; i++) { ssx_thread_at_priority(i, &thread); if (thread) { if (sep) { fprintf(stream, "*********************************************\n"); } _dumpThread(stream, thread); sep = 1; } } fprintf(stream, "------------------------------------------------------------\n"); } <|start_filename|>src/occ_405/proc/proc_pstate.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/proc/proc_pstate.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "proc_data_service_codes.h" #include "errl.h" #include "trac.h" #include "rtls.h" #include "dcom.h" #include "occ_common.h" #include "state.h" #include "cmdh_fsp_cmds.h" #include "proc_data.h" #include "proc_pstate.h" #include "homer.h" #include <amec_freq.h> #include <common.h> #include <amec_oversub.h> #include <amec_sys.h> #include <pstate_pgpe_occ_api.h> #include <p9_pstates_occ.h> //OPAL processor and memory throttle reason coming from the frequency voting boxes. extern opal_proc_voting_reason_t G_amec_opal_proc_throt_reason; extern opal_mem_voting_reason_t G_amec_opal_mem_throt_reason; //Global OCC Pstate Parameters Block Structure extern OCCPstateParmBlock G_oppb; //Trace flags extern uint16_t G_allow_trace_flags; // Indicates if we have determined GPU presence extern bool G_gpu_config_done; // GPU Present bit mask extern uint32_t G_first_proc_gpu_config; //Holds Fmax for ease of proc_freq2pstate calculation = max(fturbo,futurbo) uint16_t G_proc_fmax_mhz; uint8_t G_desired_pstate[MAXIMUM_QUADS]; // A global variable indicating whether the pstates have been enabled. // initialized to PSTATES_DISABLED, turns to PSTATES_ENABLED only after // the PGPE IPC that enable pstates completes successfully. While the IPC // task is still running, this variable be set to PSTATES_IN_TRANSITION volatile pstateStatus G_proc_pstate_status = PSTATES_DISABLED; // A Global parameter indicating the owner of the PMCR. volatile PMCR_OWNER G_proc_pmcr_owner = PMCR_OWNER_HOST; // OPAL Dynamic data, updated whenever any OCC G_opal_table.dynamic parameter change // Since this is happening multiple times need to keep track of it being scheduled DMA_BUFFER( opal_dynamic_table_t G_opal_dynamic_table ) = {{0}}; bool G_opal_dynamic_bce_req_scheduled = false; BceRequest G_opal_dynamic_bce_req; #define OPAL_DYNAMIC_UPDATE_BCE_RETRIES 2 // OPAL Static data, updated once at transition to active state DMA_BUFFER( opal_static_table_t G_opal_static_table ) = {{0}}; BceRequest G_opal_static_bce_req; volatile uint8_t G_opal_table_update_state = OPAL_TABLE_UPDATE_IDLE; // Function Specification // // Name: proc_is_hwpstate_enabled // // Description: Checks OCC to see if Pstate HW Mode is enabled. // // End Function Specification bool proc_is_hwpstate_enabled(void) { return ( G_proc_pstate_status == PSTATES_ENABLED ? TRUE : FALSE); } // Function Specification // // Name: proc_pstate2freq // // Description: Convert Pstate to Frequency in kHz // // End Function Specification uint32_t proc_pstate2freq(Pstate i_pstate) { // The higher the pstate number, the lower the frequency: // If passed in Pstate is lower than Pmin (higher pstate value), // just use Pmin. if(i_pstate > G_oppb.pstate_min) { i_pstate = G_oppb.pstate_min; } // Calculate Frequency in kHz based on Pstate return ( G_oppb.frequency_max_khz - (i_pstate * G_oppb.frequency_step_khz)); } // Function Specification // // Name: proc_freq2pstate // // Description: Convert Frequency to Nearest Pstate // // End Function Specification Pstate proc_freq2pstate(uint32_t i_freq_mhz) { int8_t l_pstate = 0; int8_t l_temp_pstate = 0; int32_t l_temp_freq_khz = 0; uint32_t l_freq_khz = 0; do { // Freq Units need to be in kHz, not Mhz for the following calculations l_freq_khz = i_freq_mhz * 1000; // Return Pmin if the frequency is below or equal to the min Freq for the lowest Pstate if(l_freq_khz <= G_oppb.frequency_min_khz ) { l_pstate = G_oppb.pstate_min; break; } if(i_freq_mhz < G_sysConfigData.sys_mode_freq.table[OCC_MODE_MIN_FREQUENCY]) { l_freq_khz = G_sysConfigData.sys_mode_freq.table[OCC_MODE_MIN_FREQUENCY] * 1000; } if(l_freq_khz < G_oppb.frequency_max_khz) { // First, calculate the delta between passed in freq, and Pmax l_temp_freq_khz = G_oppb.frequency_max_khz - l_freq_khz; // Next, calculate how many Pstate steps there are in that delta l_temp_pstate = l_temp_freq_khz / (int32_t) G_oppb.frequency_step_khz; // Higher Pstates are lower frequency, add number of steps to the highest frequency Pstate l_pstate = PMAX + l_temp_pstate; // As an extra safety check make sure the calculated Pstate is not out of the PGPE range // this should never happen! if(l_pstate > G_oppb.pstate_min) { TRAC_ERR("proc_freq2pstate: Invalid calculated Pstate[%d] for freq[%dkHz] PGPE min Pstate[%d] freq[%dkHz]", l_pstate, l_freq_khz, G_oppb.pstate_min, G_oppb.frequency_min_khz); l_pstate = G_oppb.pstate_min; } } else { // Freq is higher than or equal to the maximum frequency -- return Pmax l_pstate = PMAX; } } while(0); return (Pstate) l_pstate; } // Function Specification // // Name: proc_pstate_kvm_setup // // Description: Copy Pstate table to OPAL shared memory this should only be called once // when going to active state // // End Function Specification void proc_pstate_kvm_setup() { TRAC_IMP("proc_pstate_kvm_setup: populate static OPAL data"); // Initialize the opal table in SRAM (sets valid bit) populate_opal_static_data(); // copy sram image into mainstore HOMER populate_opal_tbl_to_mem(OPAL_STATIC); } // Function Specification // // Name: opal_table_bce_callback // // Description: Callback function for populate_opal_tbl_to_mem() BCE request // NO TRACING OR CALLING FUNCTIONS THAT TRACE ALLOWED // // End Function Specification void opal_table_bce_callback( void ) { // If the BCE that just finished was for a dynamic table update notify host if(G_opal_table_update_state == OPAL_TABLE_UPDATE_DYNAMIC_COPY) { G_opal_table_update_state = OPAL_TABLE_UPDATE_NOTIFY_HOST; } } // Function Specification // // Name: populate_opal_dynamic_data // // Description: populate the dynamic data entries in the OPAL table // // End Function Specification void populate_opal_dynamic_data() { memset(&G_opal_dynamic_table, 0, sizeof(G_opal_dynamic_table)); // Dynamic OPAL runtime data G_opal_dynamic_table.dynamic.occ_state = CURRENT_STATE(); // Add GPUs presence if this is a system that has GPUs OCC would monitor if(G_gpu_config_done) { // set minor version to indicate OCC determined GPU presence, this is so // OPAL can tell the difference between no GPUs present and fw that didn't support G_opal_dynamic_table.dynamic.dynamic_minor_version = DYNAMIC_MINOR_V_GPU_PRESENCE; G_opal_dynamic_table.dynamic.gpus_present = G_first_proc_gpu_config; } //If safe state is requested then that overrides anything from amec if(isSafeStateRequested()) { G_opal_dynamic_table.dynamic.proc_throt_status = OCC_RESET; } else { G_opal_dynamic_table.dynamic.proc_throt_status = G_amec_opal_proc_throt_reason; } G_opal_dynamic_table.dynamic.mem_throt_status = G_amec_opal_mem_throt_reason; G_opal_dynamic_table.dynamic.quick_power_drop = AMEC_INTF_GET_OVERSUBSCRIPTION(); G_opal_dynamic_table.dynamic.power_shift_ratio = G_sysConfigData.psr; G_opal_dynamic_table.dynamic.power_cap_type = G_sysConfigData.pcap.source; G_opal_dynamic_table.dynamic.min_power_cap = G_sysConfigData.pcap.hard_min_pcap; G_opal_dynamic_table.dynamic.max_power_cap = G_sysConfigData.pcap.max_pcap; G_opal_dynamic_table.dynamic.current_power_cap = g_amec->pcap.active_node_pcap; G_opal_dynamic_table.dynamic.soft_min_power_cap = G_sysConfigData.pcap.soft_min_pcap; } // Function Specification // // Name: populate_opal_static_data // // Description: populate the static configuration entries, // the generated pstates table, and maximum pstates // for all possible number of active cores. // // End Function Specification void populate_opal_static_data() { // clear all entries of the OPAL static table memset(&G_opal_static_table, 0, sizeof(G_opal_static_table)); populate_opal_static_config_data(); populate_opal_static_pstates_data(); } // Function Specification // // Name: populate_opal_static_config_data // // Description: populate the static configuration entries, // // End Function Specification void populate_opal_static_config_data(void) { // Static OPAL configuration data G_opal_static_table.config.valid = 1; G_opal_static_table.config.version = 0x90; G_opal_static_table.config.occ_role = G_occ_role; G_opal_static_table.config.pmin = proc_freq2pstate(g_amec->sys.fmin); G_opal_static_table.config.pnominal = proc_freq2pstate(G_sysConfigData.sys_mode_freq.table[OCC_MODE_NOMINAL]); G_opal_static_table.config.pturbo = proc_freq2pstate(G_sysConfigData.sys_mode_freq.table[OCC_MODE_TURBO]); G_opal_static_table.config.puturbo = proc_freq2pstate(G_proc_fmax_mhz); } // Function Specification // // Name: populate_opal_static_data // // Description: populate the generated pstates table, and maximum // pstates for all possible number of active cores. // // End Function Specification void populate_opal_static_pstates_data(void) { uint16_t i; // loop variable for (i=0; i <= G_oppb.pstate_min; i++) { G_opal_static_table.pstates[i].pstate = i; // pstate number G_opal_static_table.pstates[i].flag = 0; // flag is reserved for future use G_opal_static_table.pstates[i].freq_khz = proc_pstate2freq(i); // pstate's frequency } for (i=0; i<MAX_NUM_CORES; i++) { // TODO - RTC:170582 fix entries for WOF systems G_opal_static_table.max_pstate[i] = G_opal_static_table.config.puturbo; } } // Function Specification // // Name: populate_opal_tbl_to_mem // // Description: use the upload copy engine to copy OPAL // OPAL table's static/dynamic entries to main memory. // // End Function Specification void populate_opal_tbl_to_mem(opalDataType opal_data_type) { int l_ssxrc = SSX_OK; uint32_t l_reasonCode = 0; uint32_t l_extReasonCode = 0; // Set up copy request for type of data being updated. NOTE: only DYNAMIC uses the callback if(opal_data_type == OPAL_STATIC) { // static is only updated when going active and should be blocking to make sure // this complets before reporting back that the state change finished l_ssxrc = bce_request_create(&G_opal_static_bce_req, // block copy object &G_pba_bcue_queue, // sram to mainstore copy engine OPAL_STATIC_ADDRESS_HOMER, // mainstore address (uint32_t) &G_opal_static_table, // sram starting address (size_t) sizeof(G_opal_static_table), // size of copy SSX_SECONDS(2), // timeout NULL, // no call back NULL, // call back arguments ASYNC_REQUEST_BLOCKING); } else if(opal_data_type == OPAL_DYNAMIC) { // dynamic data can be updated while active and should NOT be blocking l_ssxrc = bce_request_create(&G_opal_dynamic_bce_req, // block copy object &G_pba_bcue_queue, // sram to mainstore copy engine OPAL_DYNAMIC_ADDRESS_HOMER, // mainstore address (uint32_t) &G_opal_dynamic_table, // sram starting address (size_t) sizeof(G_opal_dynamic_table), // size of copy SSX_WAIT_FOREVER, // no timeout (AsyncRequestCallback) opal_table_bce_callback, // call back NULL, // call back arguments ASYNC_CALLBACK_IMMEDIATE); } else { TRAC_ERR("populate_opal_tbl_to_mem: Invalid OPAL Table data type"); return; } do { if(l_ssxrc != SSX_OK) { TRAC_ERR("populate_opal_tbl_to_mem: PBA request create failure rc=[%08X]", -l_ssxrc); /* * @errortype * @moduleid PROC_POP_OPAL_TBL_TO_MEM_MOD * @reasoncode OPAL_TABLE_UPDATE_ERROR * @userdata1 RC for PBA block-copy engine * @userdata4 ERC_BCE_REQUEST_CREATE_FAILURE * @devdesc Failed to create BCUE request */ l_reasonCode = OPAL_TABLE_UPDATE_ERROR; l_extReasonCode = ERC_BCE_REQUEST_CREATE_FAILURE; break; } // Do actual copying if(opal_data_type == OPAL_STATIC) { l_ssxrc = bce_request_schedule(&G_opal_static_bce_req); } else { l_ssxrc = bce_request_schedule(&G_opal_dynamic_bce_req); } if(l_ssxrc != SSX_OK) { TRAC_ERR("populate_opal_tbl_to_mem: PBA request schedule failure rc=[%08X]", -l_ssxrc); /* * @errortype * @moduleid PROC_POP_OPAL_TBL_TO_MEM_MOD * @reasoncode OPAL_TABLE_UPDATE_ERROR * @userdata1 RC for PBA block-copy engine * @userdata4 ERC_BCE_REQUEST_SCHEDULE_FAILURE * @devdesc Failed to copy OPAL data by using BCUE */ l_reasonCode = OPAL_TABLE_UPDATE_ERROR; l_extReasonCode = ERC_BCE_REQUEST_SCHEDULE_FAILURE; break; } } while(0); if ( l_ssxrc != SSX_OK ) { // set back to idle since callback won't happen if( (opal_data_type == OPAL_DYNAMIC) && (G_opal_table_update_state == OPAL_TABLE_UPDATE_DYNAMIC_COPY) ) { G_opal_table_update_state = OPAL_TABLE_UPDATE_IDLE; } // data in main mem only matters for OPAL so only log error if OPAL if(G_sysConfigData.system_type.kvm) { errlHndl_t l_errl = createErrl(PROC_POP_OPAL_TBL_TO_MEM_MOD, //modId l_reasonCode, //reasoncode l_extReasonCode, //Extended reason code ERRL_SEV_UNRECOVERABLE, //Severity NULL, //Trace Buf 0, //Trace Size -l_ssxrc, //userdata1 0); //userdata2 // Callout firmware addCalloutToErrl(l_errl, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_FIRMWARE, ERRL_CALLOUT_PRIORITY_HIGH); // Callout processor addCalloutToErrl(l_errl, ERRL_CALLOUT_TYPE_HUID, G_sysConfigData.proc_huid, ERRL_CALLOUT_PRIORITY_MED); commitErrl(&l_errl); } } else if(opal_data_type == OPAL_DYNAMIC) { G_opal_dynamic_bce_req_scheduled = true; } } // Function Specification // // Name: check_for_opal_updates // // Description: Checks if any of the dynamic fields in the opal shared memory // needs to be updated and updates if necessary. // // End Function Specification void check_for_opal_updates(void) { bool dynamic_data_change = false; bool l_log_crit_error = false; static uint8_t L_num_bce_checks = 0; static bool L_first_throttle_trace = true; static bool L_first_unthrottle_trace = true; static bool L_first_mem_trace = true; // check if BCE for previous change finished and now need to notify host if(G_opal_table_update_state == OPAL_TABLE_UPDATE_NOTIFY_HOST) { // regardless of if we notify host we are done with this change G_opal_table_update_state = OPAL_TABLE_UPDATE_IDLE; if(G_sysConfigData.system_type.kvm) // only notify if OPAL { notify_host(INTR_REASON_OPAL_SHARED_MEM_CHANGE); } } // check if previous change is not complete else if( (G_opal_table_update_state == OPAL_TABLE_UPDATE_DYNAMIC_COPY) || (G_opal_dynamic_bce_req_scheduled && !(async_request_is_idle(&G_opal_dynamic_bce_req.request))) ) { if(L_num_bce_checks <= OPAL_DYNAMIC_UPDATE_BCE_RETRIES) { L_num_bce_checks++; } else { TRAC_ERR("check_for_opal_updates: BCE not idle %u times, done retrying", L_num_bce_checks); l_log_crit_error = true; } } else if(G_opal_table_update_state == OPAL_TABLE_UPDATE_BCE_FAIL) { // BCE failed re-populate the data and retry the BCE if under retry count if(L_num_bce_checks <= OPAL_DYNAMIC_UPDATE_BCE_RETRIES) { dynamic_data_change = true; } else { TRAC_ERR("check_for_opal_updates: BCE failed %u times, done retrying", L_num_bce_checks); l_log_crit_error = true; } } else // check if any of the data changed { // check if processor throttle status changed if going to safe state check for reset status // else just check for any change since not in safe state if( isSafeStateRequested() ) { if(G_opal_dynamic_table.dynamic.proc_throt_status != OCC_RESET) { dynamic_data_change = true; TRAC_INFO("check_for_opal_updates: safe state processor throttle status change - 0x%02X->0x%02X", G_opal_dynamic_table.dynamic.proc_throt_status, G_amec_opal_proc_throt_reason); } } else if(G_opal_dynamic_table.dynamic.proc_throt_status != G_amec_opal_proc_throt_reason) { dynamic_data_change = true; // Only want to trace the first time we throttle, and the first // time we unthrottle. If ALLOW_OPAL_TRACE is set, trace every time bool l_trace = false; if( (G_allow_trace_flags & ALLOW_OPAL_TRACE) || (L_first_throttle_trace) ) { l_trace = true; L_first_throttle_trace = false; } else if( (G_amec_opal_proc_throt_reason == 0) && (L_first_unthrottle_trace) ) { l_trace = true; L_first_unthrottle_trace = false; } if(l_trace) { TRAC_INFO("check_for_opal_updates: " "processor throttle status change - 0x%02X->0x%02X", G_opal_dynamic_table.dynamic.proc_throt_status, G_amec_opal_proc_throt_reason); } } // check if memory throttle status or Quick Power Drop changed if( (G_opal_dynamic_table.dynamic.mem_throt_status != G_amec_opal_mem_throt_reason) || (G_opal_dynamic_table.dynamic.quick_power_drop != AMEC_INTF_GET_OVERSUBSCRIPTION()) ) { dynamic_data_change = true; if( (G_allow_trace_flags & ALLOW_OPAL_TRACE ) || (L_first_mem_trace) || (G_opal_dynamic_table.dynamic.quick_power_drop != AMEC_INTF_GET_OVERSUBSCRIPTION()) ) { TRAC_INFO("check_for_opal_updates:" " memory throttle status - 0x%02X->0x%02X" " QPD - 0x%02X->0x%02X", G_opal_dynamic_table.dynamic.mem_throt_status, G_amec_opal_mem_throt_reason, G_opal_dynamic_table.dynamic.quick_power_drop, AMEC_INTF_GET_OVERSUBSCRIPTION()); L_first_mem_trace = false; } } // check for OCC state change if(G_opal_dynamic_table.dynamic.occ_state != CURRENT_STATE()) { dynamic_data_change = true; TRAC_INFO("check_for_opal_updates: OCC state change 0x%02X->0x%02X", G_opal_dynamic_table.dynamic.occ_state, CURRENT_STATE()); } // check for change in power cap data must look at slave copy // do NOT use G_master_pcap_data as that is not populated on slaves if( (G_opal_dynamic_table.dynamic.min_power_cap != G_sysConfigData.pcap.hard_min_pcap) || (G_opal_dynamic_table.dynamic.max_power_cap != G_sysConfigData.pcap.max_pcap) || (G_opal_dynamic_table.dynamic.soft_min_power_cap != G_sysConfigData.pcap.soft_min_pcap) || (G_opal_dynamic_table.dynamic.power_shift_ratio != G_sysConfigData.psr) || (G_opal_dynamic_table.dynamic.power_cap_type != G_sysConfigData.pcap.source) || (G_opal_dynamic_table.dynamic.current_power_cap != g_amec->pcap.active_node_pcap) ) { dynamic_data_change = true; TRAC_INFO("check_for_opal_updates: soft min Pcap = 0x%04X->0x%04X hard min Pcap = 0x%04X->0x%04X", G_opal_dynamic_table.dynamic.soft_min_power_cap, G_sysConfigData.pcap.soft_min_pcap, G_opal_dynamic_table.dynamic.min_power_cap, G_sysConfigData.pcap.hard_min_pcap); TRAC_INFO("check_for_opal_updates: max Pcap = 0x%04X->0x%04X active Pcap = 0x%04X->0x%04X", G_opal_dynamic_table.dynamic.max_power_cap, G_sysConfigData.pcap.max_pcap, G_opal_dynamic_table.dynamic.current_power_cap, g_amec->pcap.active_node_pcap); TRAC_INFO("check_for_opal_updates: Pcap PSR = %u->%u Pcap source = %u->%u", G_opal_dynamic_table.dynamic.power_shift_ratio, G_sysConfigData.psr, G_opal_dynamic_table.dynamic.power_cap_type, G_sysConfigData.pcap.source); } // check if GPU presence was determined if( (G_opal_dynamic_table.dynamic.dynamic_minor_version != DYNAMIC_MINOR_V_GPU_PRESENCE) && (G_gpu_config_done) ) { dynamic_data_change = true; TRAC_INFO("check_for_opal_updates: GPU presence determined = 0x%04X", G_first_proc_gpu_config); } } // else check for changes // If there was a change copy to main memory and notify host when BCE finishes if(dynamic_data_change) { G_opal_table_update_state = OPAL_TABLE_UPDATE_DYNAMIC_COPY; update_dynamic_opal_data(); // if the BCE schedule fails the state will go back to IDLE, retry next time called if(G_opal_table_update_state == OPAL_TABLE_UPDATE_IDLE) { G_opal_table_update_state = OPAL_TABLE_UPDATE_BCE_FAIL; L_num_bce_checks++; } else { L_num_bce_checks = 0; } } else if(l_log_crit_error) { // stop trying to update dynamic data, this only really matters on OPAL systems so // only log the error if OPAL G_opal_table_update_state = OPAL_TABLE_UPDATE_CRITICAL_ERROR; if(G_sysConfigData.system_type.kvm) { // Create and commit error /* @ * @errortype * @moduleid PROC_CHECK_FOR_OPAL_UPDATES_MOD * @reasoncode OPAL_TABLE_UPDATE_ERROR * @userdata1 0 * @userdata2 0 * @userdata4 ERC_GENERIC_TIMEOUT * @devdesc BCE request failure to update dynamic opal table */ errlHndl_t l_errl = createErrl(PROC_CHECK_FOR_OPAL_UPDATES_MOD, // Module ID OPAL_TABLE_UPDATE_ERROR, // Reason code ERC_GENERIC_TIMEOUT, // Extended reason code ERRL_SEV_UNRECOVERABLE, // Severity NULL, // Trace Buffers DEFAULT_TRACE_SIZE, // Trace Size 0, // Userdata1 0); // Userdata2 // Callout firmware addCalloutToErrl(l_errl, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_FIRMWARE, ERRL_CALLOUT_PRIORITY_HIGH); // Callout processor addCalloutToErrl(l_errl, ERRL_CALLOUT_TYPE_HUID, G_sysConfigData.proc_huid, ERRL_CALLOUT_PRIORITY_MED); commitErrl(&l_errl); } } } // Function Specification // // Name: update_dynamic_opal_data // // Description: update dynamic opal data in SRAM and // copy it over to OPAL space in main memory. // // End Function Specification void update_dynamic_opal_data (void) { // Initialize the dynamic opal table in SRAM populate_opal_dynamic_data(); // copy sram image into mainstore HOMER populate_opal_tbl_to_mem(OPAL_DYNAMIC); } <|start_filename|>src/ppe/pk/ppe42/ppe42_asm.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42_asm.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPE42_ASM_H__ #define __PPE42_ASM_H__ /// \file ppe42_asm.h /// \brief Generic assembler macros for 32-bit PPE42 // Doxygen is confused by assembler; the best I know how to make it // work is to put all of the documentation at the beginning like below // and effectively comment out the code using Doxygen cond/endcond. /// \page ppe42_asm Generic assembler macros for 32-bit PPE42 /// /// /// \section _lxzi _l<w,h,b>zi - Load register and Zero from Immediate address /// /// These macros encapsulate the 2-instruction sequence required to /// load from a 32-bit immediate address. /// /// \arg \c dreg A register to receive the load data. /// \arg \c areg A register to hold the immediate address. This can \e /// not be register 0. Note that if \a areg != \a dreg /// then \a areg will contain the address at the end of /// the macro sequence. /// \arg \c addr A 32-bit immediate address, which may be either an /// absolute or relocatable expression. /// /// Forms: /// /// \b _lbzi \a dreg, \a areg, \a addr - Load Byte and Zero from Immediate address \n /// \b _lhzi \a dreg, \a areg, \a addr - Load Halfword and Zero from Immediate address \n /// \b _lwzi \a dreg, \a areg, \a addr - Load Word and Zero from Immediate address \n /// /// /// \section _stxi _st<w,h,b>i - STore register to Immediate address /// /// These macros encapsulate the 2-instruction sequence required to /// store to a 32-bit immediate address. /// /// \arg \c dreg The register to store. /// \arg \c areg A register to hold the immediate address. This can \e /// not be register 0, and can not be the same as \a dreg. /// Note that \a areg will contain the address at the end of /// the macro sequence. /// \arg \c addr A 32-bit immediate address, which may be either an /// absolute or relocatable expression. /// /// Forms: /// /// \b _stbi \a dreg, \a areg, \a addr - STore Byte to Immediate address \n /// \b _sthi \a dreg, \a areg, \a addr - STore Halfword to Immediate address \n /// \b _stwi \a dreg, \a areg, \a addr - STore Word to Immediate address \n /// /// /// \section _lstzsd _<l,st><w,h,b><z>sd - Load/STore register from/to Small Data area /// /// These macros encapulate the small data area relocations for access /// to storage in the small data sections .sbss, .sdata, .sbss2 and /// .sdata2. Use of these macros implies small data area support in /// the compile environment (for variables shared between compiled and /// assembled code) and initialization code that sets up the small data /// area registers R13 (and optionally R2). /// /// The relocations generated by this macro will work for both SVR4 ABI /// and EABI environments. In particular, for EABI environments /// the link editor will insert offsets to either R13 or R2 depending /// on the section of the symbol. /// /// \arg \c dreg The register to load or store. /// \arg \c addr A 32-bit immediate address, assumed to be a /// relocatable address in one of the small data sections. /// /// Forms: /// /// \b _lbzsd \a dreg, \a addr - Load Byte and Zero from Small Data area \n /// \b _lhzsd \a dreg, \a addr - Load Halfword and Zero from Small Data area \n /// \b _lwzsd \a dreg, \a addr - Load Word and Zero from Small Data area \n /// \b _stbsd \a dreg, \a addr - STore Byte to Small Data area \n /// \b _sthsd \a dreg, \a addr - STore Halfword to Small Data area \n /// \b _stwsd \a dreg, \a addr - STore Word to Small Data area \n /// /// /// \section _liw _liw<a> - Load Immediate Word (Absolute) /// /// These macros encapsulate the two instructions required to load a /// 32-bit immediate value into a register. If the immediate is an /// absolute expression, then the \c 'a' form may be able to optimize /// to a single instruction depending on whether only the high- or /// low-order bits of the immediate are non-zero. /// /// Forms: /// /// \b _liw \a rd, \a imm - Load register \a rd with the 32-bit immediate \a imm \n /// \b _liwa \a rd, \a imm - Load register \a rd with the 32-bit absolute immediate \a imm \n /// /// /// \section _oriwa _oriwa - OR Immediate Word Absolute /// /// This macro encapsulates the logical OR of a 32-bit immediate with a /// register. The immediate value must be an absolute expression. /// /// The PowerPC has instructions for OR-ing 16-bit immediates into the /// upper (\c oris) and lower (\c ori) portions of a register. This /// macro optimizes the generated code based on which bits (if any) of /// the absolte immediate are non-zero. /// /// This special macro is only provided for the OR function. For other /// logical operations and recording forms it is necessary in general /// to first load the 32-bit immediate into a register (e.g., with \c /// _liwa) then perform the logical operation. /// /// \arg \c rd The destination register; at the end will contain \c rs /// OR \a imm /// \arg \c rs The source register. /// \arg \c imm 32-bit absolute expression. /// /// Forms: /// /// \b _oriwa \a rd, \a rs, \a imm - \a rd gets \a rs OR \a imm \n /// /// /// \section _incr64_fast - 64-bit increment for fast interrupt handlers /// /// This macros implements 64-bit counter update in fast interrupt handlers /// which are forbidden from using the carry-bit in the XER (without /// saving/restoring it.) /// /// \arg \c rs Scratch register /// \arg \c ra Register containing the counter address at entry /// /// \a rs and \a ra must be unique. At the end of the macro the count /// is updated to memory and \a ra is unmodified. /// /// /// \section _setclear_bits Set/Clear/Copy Bits from Immediate Positions /// /// There are situations where it is easier/faster to clear individual bits /// and bit fields, set bits or copy fields, based on immediate bit numbers /// and locations, rather than loading masks, since setting up a mask /// requires 2 instruction in general, whereas these macros generate a single /// instruction. /// /// \arg \c rd - The destination register /// \arg \c rs - The source register /// \arg \c n - An immediate size of a bit field, in the range 0 to 32 /// \arg \c b - An immediate big-endian bit number in the range 0 to 31 /// /// Forms: /// /// \b _clrfield \a rd, \a rs, \a n, \a b - Clear an \a n bit field from \a rs /// to \a rd starting from bit \a b \n /// \b _clrbit \a rd, \a rs, \a b - Clear bit \a b \n /// \b _setbit \a rd, \a rs, \a b - Set bit \a b \n /// \b _copyfield \a rd, \a rs, \a n, \a b - Copy an n-bit field from \a rs to /// \a rd starting from bit \a b \n /// /// /// \section pseudo_ops Assembler Pseudo-Ops Macros /// /// Several macros define new 'pseudo-ops'. /// /// \subsection cache_align .cache_align /// /// The \c .cache_align pseudo-op is used to force alignment on a /// cache-line boundary. It requires a preprocessor symbol definition for /// \c LOG_CACHE_LINE_SIZE /// /// Forms: /// /// \b .cache_align \n /// /// /// \subsection global_function Local and Global Functions /// /// The \c .function and \c .global_function pseudo-ops define function /// symbols in the \c .text section. /// /// Forms: /// /// \b .function \a symbol - Define a local function \a symbol \n /// \b .global_function \a symbol - Define a global function \a symbol \n /// /// /// \subsection epilogue .epilogue /// /// The \c .epilogue pseudo-op adds size and type information for /// functions defined in assembler. /// /// \arg \c symbol - Assembler epilogue for the function \a symbol. /// /// Forms: /// /// \b .epilogue \a symbol \n /// /// /// \cond #ifdef __ASSEMBLER__ ### **************************************************************************** ### _l<b,h,w>zi ### _st<b,h,w>i ### **************************************************************************** .macro _lbzi dreg, areg, addr lis \areg, \addr@ha .ifc \areg, \dreg lbz \dreg, \addr@l(\areg) .else lbzu \dreg, \addr@l(\areg) .endif .endm .macro _lhzi dreg, areg, addr lis \areg, \addr@ha .ifc \areg, \dreg lhz \dreg, \addr@l(\areg) .else lhzu \dreg, \addr@l(\areg) .endif .endm .macro _lwzi dreg, areg, addr lis \areg, \addr@ha .ifc \areg, \dreg lwz \dreg, \addr@l(\areg) .else lwzu \dreg, \addr@l(\areg) .endif .endm .macro _stbi dreg, areg, addr .ifc \areg, \dreg .err .endif lis \areg, \addr@ha stbu \dreg, \addr@l(\areg) .endm .macro _sthi dreg, areg, addr .ifc \areg, \dreg .err .endif lis \areg, \addr@ha sthu \dreg, \addr@l(\areg) .endm .macro _stwi dreg, areg, addr .ifc \areg, \dreg .err .endif lis \areg, \addr@ha stwu \dreg, \addr@l(\areg) .endm ### **************************************************************************** ### _l<b,h,w>zsd ### _st<b,h,w>sd ### **************************************************************************** .macro _lbzsd dreg, addr lbz \dreg, \addr@sda21(0) .endm .macro _lhzsd dreg, addr lhz \dreg, \addr@sda21(0) .endm .macro _lwzsd dreg, addr lwz \dreg, \addr@sda21(0) .endm .macro _stbsd dreg, addr stb \dreg, \addr@sda21(0) .endm .macro _sthsd dreg, addr sth \dreg, \addr@sda21(0) .endm .macro _stwsd dreg, addr stw \dreg, \addr@sda21(0) .endm ### **************************************************************************** ### _liw<a> ### _oriwa ### **************************************************************************** .macro _liw rd, imm lis \rd, \imm@h ori \rd, \rd, \imm@l .endm .macro _liwa rd, imm .if (\imm & 0xffff0000) lis \rd, \imm@h .if (\imm & 0xffff) ori \rd, \rd, \imm@l .endif .else li \rd, \imm@l .endif .endm .macro _oriwa rd, rs, imm .if (\imm & 0xffff0000) oris \rd, \rs, \imm@h .if (\imm & 0xffff) ori \rd, \rd, \imm@l .endif .else ori \rd, \rs, \imm@l .endif .endm ### **************************************************************************** ### _incr64_fast ### **************************************************************************** .macro _incr64_fast, rs:req, ra:req lwz \rs, 4(\ra) addi \rs, \rs, 1 cmpwi \rs, 0 stw \rs, 4(\ra) bne 233643278f lwz \rs, 0(\ra) addi \rs, \rs, 1 stw \rs, 0(\ra) 233643278: .endm ### **************************************************************************** ### _clrfield ### _clrbit ### _setbit ### _copyfield ### **************************************************************************** .macro _clrfield, rd, rs, n, b rlwinm \rd, \rs, 0, (\b + \n) & 0x1f, (\b - 1) & 0x1f .endm .macro _clrbit, rd, rs, b _clrfield \rd, \rs, 1, \b .endm .macro _setbit, rd, rs, b .ifle \b - 15 oris \rd, \rs, 1 << (15 - \b) .else ori \rd, \rs, 1 << (31 - \b) .endif .endm .macro _copyfield, rd, rs, n, b rlwimi \rd, \rs, 0, \b , (\b + \n - 1) .endm ### **************************************************************************** ### .cache_align ### .<global_>function ### .epilogue ### **************************************************************************** .set _log_cache_line_size, LOG_CACHE_LINE_SIZE .macro .cache_align .align _log_cache_line_size .endm .macro .function symbol .text .align 2 .endm .macro .global_function symbol .text .align 2 .global \symbol .endm .macro .epilogue symbol .type \symbol, @function .size \symbol, . - \symbol .endm ### *************************************************************************** ### 64-bit macros ### *************************************************************************** ### *************************************************************************** ### Using symbols for register names makes the code more readable and allows ### us to do register arithmetic within macros. ### *************************************************************************** .equiv r0, 0 .equiv r1, 1 .equiv sp, 1 .equiv r3, 3 .equiv r4, 4 .equiv r5, 5 .equiv r6, 6 .equiv r7, 7 .equiv r8, 8 .equiv r9, 9 .equiv r10, 10 .equiv r28, 28 .equiv r29, 29 .equiv r30, 30 .equiv r31, 31 .equiv d3, 3 .equiv d4, 4 .equiv d5, 5 .equiv d6, 6 .equiv d7, 7 .equiv d8, 8 .equiv d9, 9 .equiv d10, 10 .equiv d28, 28 .equiv d29, 29 .equiv d30, 30 .equiv d31, 31 ### *************************************************************************** ### Load virtual doubleword generic. Load a virtual doubleword from a relocatable ### address expression. If the optional RA is specified, the address remains in ### RA. ### *************************************************************************** .macro _lvdg DT:req addr:req RA=-1 .if \RA == -1 lis \DT, (\addr)@ha lvd \DT, (\addr)@l(\DT) .else lis \RA, (\addr)@ha lvdu \DT, (\addr)@l(\RA) .endif .endm ### *************************************************************************** ### Load virtual doubleword from a relocatable small data area address ### *************************************************************************** .macro _lvdsd DT:req addr:req lvd \DT, (\addr)@sda21(0) .endm ### *************************************************************************** ### Store virtual doubleword generic. Store a virtual doubleword based on a ### relocatable address expression. The address remains in RA. ### *************************************************************************** .macro _stvdg DS:req addr:req RA:req lis \RA, (\addr)@ha stvdu \DS, (\addr)@l(\RA) .endm ### *************************************************************************** ### Store virtual doubleword to a relocatable small data address expression ### *************************************************************************** .macro _stvdsd DS:req addr:req stvd \DS, (\addr)@sda21(0) .endm ### *************************************************************************** ### Load virtual doubleword absolute. Set DT to an absolute 64-bit constant ### *************************************************************************** .macro _lvda DT, cvalue lwa (\DT + 1)%32, (\cvalue) & 0x00000000ffffffff lwa \DT, (\cvalue) >> 32 .endm ### *************************************************************************** ### ### 64-bit arithmetic macros ### ### *************************************************************************** .macro check_overlap2 DA, DB .if ((\DA - \DB) % 32) == 1 || ((\DA - \DB) % 32) == -1 .error "virtual doubleword registers must be identical or non-overlapping" .endif .endm .macro check_overlap3 DA, DB, DC check_overlap2 \DA, \DB check_overlap2 \DA, \DC check_overlap2 \DB, \DC .endm ### *************************************************************************** ### Add virtual doubleword carrying ### *************************************************************************** .macro _addvdc DT, DA, DB check_overlap3 \DT, \DA, \DB addc (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 adde \DT, \DA, \DB .endm ### *************************************************************************** ### Add virtual doubleword to signed 16-bit immediate carrying ### *************************************************************************** .macro _addvdic DT, DA, SI .if \DA == 31 .error "d31 for addend register is not supported" .endif check_overlap2 \DT, \DA addi (\DT+1)%32, \DA+1, SI addze \DT, \DA .endm ### *************************************************************************** ### Add virtual doubleword to unsigned word carrying ### *************************************************************************** .macro _addvdwuc DT, DA, RB check_overlap2 \DT, \DA addc (\DT+1)%32, (\DA+1)%32, \RB addze \DT, \DA .endm ### *************************************************************************** ### Subtract virtual doubleword carrying ### *************************************************************************** .macro _subvdc DT, DA, DB check_overlap3 \DT, \DA, \DB subfc (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 subfe \DT, \DA, \DB .endm ### *************************************************************************** ### ### 64-bit logic macros ### ### *************************************************************************** ### *************************************************************************** ### AND virtual doubleword ### *************************************************************************** .macro _andvd DT, DA, DB check_overlap3 \DT, \DA, \DB and (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 and \DT, \DA, \DB .endm ### *************************************************************************** ### ANDC virtual doubleword ### *************************************************************************** .macro _andcvd DT, DA, DB check_overlap3 \DT, \DA, \DB andc (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 andc \DT, \DA, \DB .endm ### *************************************************************************** ### EQV virtual doubleword ### *************************************************************************** .macro _eqvvd DT, DA, DB check_overlap3 \DT, \DA, \DB eqv (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 eqv \DT, \DA, \DB .endm ### *************************************************************************** ### OR virtual doubleword ### *************************************************************************** .macro _orvd DT, DA, DB check_overlap3 \DT, \DA, \DB or (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 or \DT, \DA, \DB .endm ### *************************************************************************** ### ORC virtual doubleword ### *************************************************************************** .macro _orcvd DT, DA, DB check_overlap3 \DT, \DA, \DB orc (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 orc \DT, \DA, \DB .endm ### *************************************************************************** ### XOR virtual doubleword ### *************************************************************************** .macro _xorvd DT, DA, DB check_overlap3 \DT, \DA, \DB xor (\DT+1)%32, (\DA+1)%32, (\DB+1)%32 xor \DT, \DA, \DB .endm #endif /* __ASSEMBLER__ */ /// \endcond // Local Variables: // mode:asm // End: #endif /* __PPE42_ASM_H__ */ <|start_filename|>src/occ_405/gpu/gpu.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/gpu/gpu.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifdef GPU_DEBUG #define GPU_DBG(frmt,args...) DBG_PRINT(frmt,##args) #else #define GPU_DBG(frmt,args...) #endif #include <ssx.h> #include <occhw_async.h> #include <trac_interface.h> #include <trac.h> #include <occ_common.h> #include <comp_ids.h> #include <occ_service_codes.h> #include <state.h> #include <occ_sys_config.h> #include "sensor.h" #include "amec_sys.h" #include "lock.h" #include "common.h" #include "amec_health.h" #include "gpu.h" #include "gpu_structs.h" #include "gpu_service_codes.h" #include "i2c.h" // Number calls with assumption the GPU SM task is called every other tick #define GPU_TEMP_READ_1S ( 1000000 / (MICS_PER_TICK * 2) ) #define GPU_TIMEOUT ( 10000000 / (MICS_PER_TICK *2) ) #define GPU_TICKS_TO_100MS ( 100000 / (MICS_PER_TICK * 2) ) #define GPU_TICKS_TO_1S ( 1000000 / (MICS_PER_TICK * 2) ) // Number of consecutive failures to ignore after GPU is taken out of reset to give GPU init time #define GPU_INIT_ERROR_COUNT 300 // approximately 300 seconds #define MAX_CONSECUTIVE_GPU_RESETS 5 #define MAX_GPU_RESET_STATE_RETRY 3 #define MAX_RESET_STATE_NOT_DONE_COUNT 100 #define MAX_GPU_READ_ATTEMPT 3 #define GPU_ERRORS_BEFORE_I2C_RESET 5 // consecutive error counts for GPU command failures before error is logged if GPU is not in reset #define GPU_CHECK_DRIVER_ERROR_COUNT 5 #define GPU_READ_MEM_CAP_ERROR_COUNT 5 #define GPU_READ_PWR_LIMIT_ERROR_COUNT 5 #define GPU_SET_PWR_LIMIT_ERROR_COUNT 5 #define GPU_I2C_ENGINE PIB_I2C_ENGINE_C extern data_cnfg_t * G_data_cnfg; extern PWR_READING_TYPE G_pwr_reading_type; // this is the global GPU task sm state each task within the GPU SM may have its own "state" // to allow several calls to complete the task gpuState_e G_gpu_state = GPU_STATE_IDLE; bool G_gpu_monitoring_allowed = FALSE; // Set to true if GPU is present bool G_gpu_i2c_reset_required = FALSE; uint32_t G_gpu_reset_cause = 0; // GPE Requests GpeRequest G_gpu_op_request; GpeRequest G_gpu_init_request; // GPE arguments GPE_BUFFER(gpu_sm_args_t G_gpu_op_req_args); GPE_BUFFER(gpu_init_args_t G_gpu_init_args); gpu_sm_args_t G_new_gpu_req_args = {{{{0}}}}; uint8_t G_current_gpu_id = 0; // ID 0..2 of GPU currently being processed gpuTimingTable_t G_gpu_tick_times; void update_gpu_tick_sensor(gpuTimingSensor_t *sensor, uint32_t ticks) { if(ticks > sensor->max) { sensor->max = ticks; } if(ticks > GPU_TICKS_TO_1S) { sensor->count_1s++; } else if( (ticks > GPU_TICKS_TO_100MS) ) { sensor->count_100ms++; } else { sensor->count_lt100ms++; } sensor->count++; sensor->accum += ticks; sensor->avg = sensor->accum / sensor->count; } // Find first present non-failed GPU. returns 0xFF if no GPUs present/functional uint8_t get_first_gpu(void) { uint8_t first_gpu = 0xFF; // default no GPUs present/functional uint8_t i = 0; for (i=0; i<MAX_NUM_GPU_PER_DOMAIN; i++) { if((GPU_PRESENT(i)) && (!g_amec->gpu[i].status.disabled) ) { first_gpu = i; break; } } return first_gpu; } // Get GPU number for next present non-failed GPU from G_current_gpu_id // returns 0xFF if there is no next GPU i.e. wrapped back to first GPU uint8_t get_next_gpu(void) { uint8_t next_gpu = G_current_gpu_id; if(G_current_gpu_id != 0xFF) { do { if(++next_gpu == MAX_NUM_GPU_PER_DOMAIN) { next_gpu = 0; } if( (GPU_PRESENT(next_gpu)) && (!g_amec->gpu[next_gpu].status.disabled) ) { break; } }while(next_gpu != G_current_gpu_id); } if(next_gpu == get_first_gpu()) { next_gpu = 0xFF; } return next_gpu; } // Get GPU number for a GPU that needs to be checked if driver is loaded // returns 0xFF if no GPU needs to be checked uint8_t gpu_id_need_driver_check(void) { uint8_t gpu_id = 0xFF; // default none needs checking uint8_t i = 0; // checking for driver loaded can be repeated until driver is loaded which may never happen // to avoid infinite loop checking the same GPU over and over we will use a static and each call // will start looking at the next GPU, after all GPUs checked will allow none before re-checking all GPUs static uint8_t L_current_gpu_id = 0; if(L_current_gpu_id == 0xFF) { // checked all GPUs once, do not check any this time and start over with GPU 0 on next call L_current_gpu_id = 0; } else { for (i=L_current_gpu_id; i<MAX_NUM_GPU_PER_DOMAIN; i++) { // only check for driver after i2c comm (readOnce) has been established if((GPU_PRESENT(i)) && (!g_amec->gpu[i].status.disabled) && (g_amec->gpu[i].status.readOnce) && (g_amec->gpu[i].status.checkDriverLoaded)) { gpu_id = i; break; } } // setup L_current_gpu_id for next call based on what is happening this time if(gpu_id == 0xFF) { // no GPU needs checking start back at 0 next time L_current_gpu_id = 0; } else if(gpu_id == (MAX_NUM_GPU_PER_DOMAIN - 1) ) { // last GPU is having driver checked do not check any next time L_current_gpu_id = 0xFF; } else { // next time look at the next GPU ID first L_current_gpu_id = gpu_id + 1; } } return gpu_id; } uint8_t gpu_id_need_memory_temp_capability_check(void) { uint8_t gpu_id = 0xFF; // default none needs checking uint8_t i = 0; // checking for memory temp capability will be repeated until memory temp is capable which may never happen // to avoid infinite loop checking the same GPU over and over we will use a static and each call // will start looking at the next GPU, after all GPUs checked will allow none before re-checking all GPUs static uint8_t L_current_gpu_id = 0; if(L_current_gpu_id == 0xFF) { // checked all GPUs once, do not check any this time and start over with GPU 0 on next call L_current_gpu_id = 0; } else { for (i=L_current_gpu_id; i<MAX_NUM_GPU_PER_DOMAIN; i++) { // driver must be loaded for memory temp capability if( (!g_amec->gpu[i].status.disabled) && (g_amec->gpu[i].status.driverLoaded) && (g_amec->gpu[i].status.checkMemTempSupport) ) { gpu_id = i; break; } } // setup L_current_gpu_id for next call based on what is happening this time if(gpu_id == 0xFF) { // no GPU needs checking start back at 0 next time L_current_gpu_id = 0; } else if(gpu_id == (MAX_NUM_GPU_PER_DOMAIN - 1) ) { // last GPU is having memory capability checked do not check any next time L_current_gpu_id = 0xFF; } else { // next time look at the next GPU ID first L_current_gpu_id = gpu_id + 1; } } return gpu_id; } // Find first functional GPU with memory temp capability // returns 0xFF if no functional GPU has memory temp capability uint8_t get_first_mem_temp_capable_gpu(void) { uint8_t first_gpu = 0xFF; // default no GPU with mem temp capability uint8_t i = 0; for (i=0; i<MAX_NUM_GPU_PER_DOMAIN; i++) { if( (!g_amec->gpu[i].status.disabled) && (g_amec->gpu[i].status.memTempSupported) ) // memTempSupported implies that driver is loaded { first_gpu = i; break; } } return first_gpu; } // Get GPU number for next functional GPU from G_current_gpu_id with mem temp capability // returns 0xFF if there is no next GPU i.e. wrapped back to first GPU with mem temp uint8_t get_next_mem_temp_capable_gpu(void) { uint8_t next_gpu = G_current_gpu_id; if(G_current_gpu_id != 0xFF) { do { if(++next_gpu == MAX_NUM_GPU_PER_DOMAIN) { next_gpu = 0; } if( (!g_amec->gpu[next_gpu].status.disabled) && (g_amec->gpu[next_gpu].status.memTempSupported) ) // memTempSupported implies that driver is loaded { break; } }while(next_gpu != G_current_gpu_id); } if(next_gpu == get_first_mem_temp_capable_gpu()) { next_gpu = 0xFF; } else if( (next_gpu != 0xFF) && (!g_amec->gpu[next_gpu].status.memTempSupported) ) { next_gpu = 0xFF; } return next_gpu; } // Get GPU number for a GPU that needs power limits read // returns 0xFF if no GPU needs power limits read uint8_t gpu_id_need_power_limits(void) { uint8_t gpu_id = 0xFF; // default none uint8_t i = 0; static uint8_t L_current_gpu_id = 0; if(0xFF == L_current_gpu_id) { // We attempted to read power limits for all GPUs // do not check any this time and start over with GPU 0 on next call L_current_gpu_id = 0; } else { for (i=L_current_gpu_id; i<MAX_NUM_GPU_PER_DOMAIN; i++) { // to read power limits requires that the driver is loaded if( (g_amec->gpu[i].status.driverLoaded) && (g_amec->gpu[i].pcap.check_pwr_limit)) { // If there is no power capping support skip reading power limits if(G_pwr_reading_type == PWR_READING_TYPE_NONE) { g_amec->gpu[i].pcap.check_pwr_limit = false; } else { gpu_id = i; break; } } } if(0xFF == gpu_id) { // We don't need to read power limits from any GPUs at the moment L_current_gpu_id = 0; } else if( (MAX_NUM_GPU_PER_DOMAIN - 1) == gpu_id) { // We're reading from last GPU, do not check any next time L_current_gpu_id = 0xFF; } else { // Next time look at next GPU ID first L_current_gpu_id = gpu_id + 1; } } return gpu_id; } // Get GPU number for a GPU that needs power limit set // returns 0xFF if no GPU needs power limit set uint8_t gpu_id_need_set_power_limit(void) { uint8_t gpu_id = 0xFF; // default none uint8_t i = 0; static uint8_t L_current_gpu_id = 0; if(0xFF == L_current_gpu_id) { // We've checked to see if all GPUs need a power cap set, start over // with GPU 0 next time L_current_gpu_id = 0; } else { for (i=L_current_gpu_id; i<MAX_NUM_GPU_PER_DOMAIN; i++) { // to set power limit requires that the driver is loaded and power limits were read if( (g_amec->gpu[i].status.driverLoaded) && (g_amec->gpu[i].pcap.pwr_limits_read) && (!g_amec->gpu[i].pcap.set_failed) && (g_amec->gpu[i].pcap.gpu_desired_pcap_mw != 0) && (g_amec->gpu[i].pcap.gpu_desired_pcap_mw != g_amec->gpu[i].pcap.gpu_requested_pcap_mw) ) { gpu_id = i; break; } } if(0xFF == gpu_id) { // no GPU needs checking start back at 0 next time L_current_gpu_id = 0; } else if( (MAX_NUM_GPU_PER_DOMAIN - 1) == gpu_id ) { // Last GPU is being set do not check any next time L_current_gpu_id = 0xFF; } else { // next time look at the next GPU ID first L_current_gpu_id = gpu_id + 1; } } return gpu_id; } // For the given GPU clear status/data that requires GPU driver to be loaded void clear_gpu_driver_status(uint8_t i_gpu_num) { g_amec->gpu[i_gpu_num].status.checkDriverLoaded = false; g_amec->gpu[i_gpu_num].status.driverLoaded = false; // Reading memory temperature requires driver to be loaded. g_amec->gpu[i_gpu_num].status.checkMemTempSupport = false; g_amec->gpu[i_gpu_num].status.memTempSupported = false; g_amec->gpu[i_gpu_num].status.memErrorCount = 0; // Power capping requires driver to be loaded. Clear GPU power limits g_amec->gpu[i_gpu_num].pcap.check_pwr_limit = false; g_amec->gpu[i_gpu_num].pcap.pwr_limits_read = false; g_amec->gpu[i_gpu_num].pcap.set_failed = false; g_amec->gpu[i_gpu_num].pcap.gpu_min_pcap_mw = 0; g_amec->gpu[i_gpu_num].pcap.gpu_max_pcap_mw = 0; g_amec->gpu[i_gpu_num].pcap.gpu_requested_pcap_mw = 0; g_amec->gpu[i_gpu_num].pcap.gpu_default_pcap_mw = 0; //amec will need to recalculate after power limits are read to handle any clipping with new GPU min/max g_amec->gpu[i_gpu_num].pcap.gpu_desired_pcap_mw = 0; } // Handles GPU not able to process request due to driver load or un-load void handle_driver_change(void) { // Clear out driver status while driver change completes and is determined if loaded/un-loaded clear_gpu_driver_status(G_current_gpu_id); // memory temp only available when driver is loaded. clear error and set not available g_amec->gpu[G_current_gpu_id].status.memTempFailure = false; g_amec->gpu[G_current_gpu_id].status.memTempNotAvailable = true; // when driver change is complete we must re-query to see if driver is loaded or not g_amec->gpu[G_current_gpu_id].status.checkDriverLoaded = true; } // For all GPUs read GPU reset status and take action if reset status has changed void update_gpu_reset_status(void) { uint8_t gpu_num = 0; // GPU reset status is in the OCC FLAGS register and is updated by OPAL // Read the current reset status for all GPUs. A reset status of '1' indicates NOT in reset ocb_occflg_t occ_flags = {0}; occ_flags.value = in32(OCB_OCCFLG); bool not_in_reset[3] = {occ_flags.fields.gpu0_reset_status, occ_flags.fields.gpu1_reset_status, occ_flags.fields.gpu2_reset_status}; // reset status of '0' (IN reset) is the default // the OCC will still try to read GPU when IN reset but will not log errors // this is so we still communicate with the GPUs without OPAL support to indicate // a GPU is not in reset. // Full OCC support below for when OPAL starts updating the reset status for (gpu_num=0; gpu_num<MAX_NUM_GPU_PER_DOMAIN; gpu_num++) { if(not_in_reset[gpu_num] != g_amec->gpu[gpu_num].status.notReset) { INTR_TRAC_IMP("update_gpu_reset_status: GPU%d NOT in reset is now = %d", gpu_num, not_in_reset[gpu_num]); // There has been a change to the reset status clear everything out except for errors logged so we don't log again clear_gpu_driver_status(gpu_num); g_amec->gpu[gpu_num].status.errorCount = 0; g_amec->gpu[gpu_num].status.retryCount = 0; // readOnce of false will force comm to be established and once established then checkDriverLoaded will get set g_amec->gpu[gpu_num].status.readOnce = false; if(not_in_reset[gpu_num]) { // GPU was taken out of reset clear disabled to allow communication again g_amec->gpu[gpu_num].status.disabled = false; } else { // GPU was put in reset. Clear temperature sensor errors and set to not available g_amec->gpu[gpu_num].status.coreTempFailure = false; g_amec->gpu[gpu_num].status.coreTempNotAvailable = true; g_amec->gpu[gpu_num].status.memTempFailure = false; g_amec->gpu[gpu_num].status.memTempNotAvailable = true; } g_amec->gpu[gpu_num].status.notReset = not_in_reset[gpu_num]; } // if GPU reset status changed } // for each GPU } // end update_gpu_reset_status() // Disable GPU monitoring for all GPUs void disable_all_gpus(void) { uint8_t i = 0; // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); G_gpu_monitoring_allowed = FALSE; // mark all GPUs as disabled for (i=0; i<MAX_NUM_GPU_PER_DOMAIN; i++) { g_amec->gpu[i].status.disabled = TRUE; } } // schedule request to init gpu info on gpe1 void schedule_gpe_gpu_init_req() { errlHndl_t err = NULL; int rc = 0; memset(&G_gpu_init_args, 0, sizeof(G_gpu_init_args)); // Need to add gpu i2c info // G_gpu_init_args.gpu_i2c rc = gpe_request_schedule(&G_gpu_init_request); if (rc) { INTR_TRAC_ERR ("schedule_gpe_gpu_init_req: gpe gpu init schedule failed w/rc=0x%08X", rc); /* * @errortype * @moduleid GPU_MID_GPE_GPU_INIT_SCHED_REQ * @reasoncode SSX_GENERIC_FAILURE * @userdata1 GPE schedule returned code * @userdata4 ERC_GPU_SCHEDULE_FAILURE * @devdesc Failed to schedule GPE GPU initial request */ err = createErrl(GPU_MID_GPE_GPU_INIT_SCHED_REQ, SSX_GENERIC_FAILURE, ERC_GPU_SCHEDULE_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, rc, 0); commitErrl(&err); // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); G_gpu_monitoring_allowed = FALSE; } } // Create GPU IPC requests void gpu_ipc_init() { errlHndl_t l_err = NULL; int rc = 0; do { // Initialize IPC request for GPU operation requests GPU_DBG("gpu_ipc_init: Creating GPE1 IPC request for GPU op requests"); rc = gpe_request_create(&G_gpu_op_request, &G_async_gpe_queue1, IPC_ST_GPU_SM_FUNCID, &G_gpu_op_req_args, SSX_WAIT_FOREVER, NULL, // no callback/arg NULL, ASYNC_CALLBACK_IMMEDIATE); if (rc) { TRAC_ERR("gpu_ipc_init: Failed to create GPE1 IPC request for GPU op req (rc=%d)", rc); break; } // Initialize GPU support on GPE1 GPU_DBG("gpu_ipc_init: Creating GPE1 IPC request for GPU initialization"); rc = gpe_request_create(&G_gpu_init_request, &G_async_gpe_queue1, IPC_ST_GPE_GPU_INIT_FUNCID, &G_gpu_init_args, SSX_WAIT_FOREVER, NULL, // no callback NULL, // no args ASYNC_CALLBACK_IMMEDIATE); if (rc) { TRAC_ERR("gpu_ipc_init: Failed to create GPE1 GPU init request. (rc=%d)", rc); break; } } while(0); if (rc) { /* @ * @errortype * @moduleid GPU_MID_INIT * @reasoncode SSX_GENERIC_FAILURE * @userdata1 return code * @userdata4 OCC_NO_EXTENDED_RC * @devdesc Failed to create GPE1 GPU IPC request */ l_err = createErrl(GPU_MID_INIT, SSX_GENERIC_FAILURE, OCC_NO_EXTENDED_RC, ERRL_SEV_PREDICTIVE, NULL, // trace buffer DEFAULT_TRACE_SIZE, rc, 0); REQUEST_RESET(l_err); // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); G_gpu_monitoring_allowed = FALSE; } else { // if (redundant ps policy is set) if (G_sysConfigData.system_type.non_redund_ps == false) { // gpe gpu init only needs to be done once, so do it here. schedule_gpe_gpu_init_req(); } } } // Called after a failure reading core temp for a specified GPU. The error will // be counted and if threshold is reached, an error will be created with // the GPU as a callout if the GPU is not in reset void mark_gpu_failed(const gpu_sm_args_t *i_arg) { uint32_t gpu_id = i_arg->gpu_id; do { if((false == g_amec->gpu[gpu_id].status.disabled) && (true == g_amec->gpu[gpu_id].status.readOnce)) { GPU_DBG("mark_gpu_failed: GPU%d failed in op/rc/count=0x%06X " "(ffdc 0x%08X%08X)", gpu_id, (i_arg->operation << 16) | (i_arg->error.rc << 8) | g_amec->gpu[gpu_id].status.errorCount, WORD_HIGH(i_arg->error.ffdc), WORD_LOW(i_arg->error.ffdc)); } // Always inc retry count for I2C reset regardless of if GPU is in reset or not g_amec->gpu[gpu_id].status.retryCount++; // Only inc error count if it is known that GPU is NOT in reset // NOTE: Default is IN reset so this will only be true when OPAL/OS supports telling the OCC reset status // if OS never tells the OCC reset status the OCC will never disable or log a comm error if(g_amec->gpu[gpu_id].status.notReset) { // INC count and check if reached error threshold if( ++g_amec->gpu[gpu_id].status.errorCount > GPU_INIT_ERROR_COUNT) { // set that GPU temperature readings failed g_amec->gpu[gpu_id].status.memTempFailure = true; g_amec->gpu[gpu_id].status.memTempNotAvailable = true; g_amec->gpu[gpu_id].status.coreTempFailure = true; g_amec->gpu[gpu_id].status.coreTempNotAvailable = true; // Disable this GPU. GPU will get re-enabled if detected that GPU is put in reset and then taken out g_amec->gpu[gpu_id].status.disabled = true; INTR_TRAC_ERR("mark_gpu_failed: disabling GPU%d due to %d consecutive errors (op=%d)", gpu_id, g_amec->gpu[gpu_id].status.errorCount, i_arg->operation); if(g_amec->gpu[gpu_id].status.commErrorLogged == false) { errlHndl_t l_err = NULL; /* * @errortype * @moduleid GPU_MID_MARK_GPU_FAILED * @reasoncode GPU_FAILURE * @userdata1 GPE returned rc code * @userdata4 ERC_GPU_COMPLETE_FAILURE * @devdesc GPU failure */ l_err = createErrl(GPU_MID_MARK_GPU_FAILED, GPU_FAILURE, ERC_GPU_COMPLETE_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, i_arg->error.rc, 0); addUsrDtlsToErrl(l_err, (uint8_t*)&i_arg->error.ffdc, sizeof(i_arg->error.ffdc), ERRL_STRUCT_VERSION_1, ERRL_USR_DTL_BINARY_DATA); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[gpu_id], ERRL_CALLOUT_PRIORITY_MED); } commitErrl(&l_err); g_amec->gpu[gpu_id].status.commErrorLogged = true; } // if !commErrorLogged } // if errorCount > threshold } // if notReset } while(0); // Do an I2C reset if reached retry count // don't want to do I2C reset every time since could be that this GPU really is in reset and // while resetting I2C we are unable to read other GPUs that may not be in reset if( g_amec->gpu[gpu_id].status.retryCount > GPU_ERRORS_BEFORE_I2C_RESET) { g_amec->gpu[gpu_id].status.retryCount = 0; G_gpu_i2c_reset_required = true; G_gpu_reset_cause = gpu_id<<24 | (i_arg->error.rc & 0xFFFF); } } // end mark_gpu_failed() // Schedule a GPE request for GPU operation bool schedule_gpu_req(const gpu_op_req_e i_operation, gpu_sm_args_t i_new_args) { bool l_scheduled = false; bool scheduleRequest = true; errlHndl_t err = NULL; GPU_DBG(">>schedule_gpu_req(op 0x%02X)", i_operation); if (!async_request_is_idle(&G_gpu_op_request.request)) { INTR_TRAC_INFO("E>schedule_gpu_req: prior request (op 0x%02X) not idle when scheduling 0x%02X (tick=%d)", G_gpu_op_req_args.operation, i_operation, GPU_TICK); } else { // Ready for next request G_gpu_op_req_args = i_new_args; switch(i_operation) { // Init case GPU_REQ_INIT: break; // Read GPU memory temp capability case GPU_REQ_READ_CAPS_START: case GPU_REQ_READ_CAPS_2: case GPU_REQ_READ_CAPS_3: case GPU_REQ_READ_CAPS_FINISH: break; // Read GPU core temp case GPU_REQ_READ_TEMP_START: case GPU_REQ_READ_TEMP_FINISH: break; // Read GPU memory temp case GPU_REQ_READ_MEM_TEMP_START: case GPU_REQ_READ_MEM_TEMP_2: case GPU_REQ_READ_MEM_TEMP_3: case GPU_REQ_READ_MEM_TEMP_FINISH: break; // Check if driver is loaded case GPU_REQ_CHECK_DRIVER_START: case GPU_REQ_CHECK_DRIVER_2: case GPU_REQ_CHECK_DRIVER_3: case GPU_REQ_CHECK_DRIVER_FINISH: break; // Read GPU Power Limit case GPU_REQ_GET_PWR_LIMIT_1_START: case GPU_REQ_GET_PWR_LIMIT_1_2: case GPU_REQ_GET_PWR_LIMIT_1_3: case GPU_REQ_GET_PWR_LIMIT_1_FINISH: case GPU_REQ_GET_PWR_LIMIT_2_START: case GPU_REQ_GET_PWR_LIMIT_2_2: case GPU_REQ_GET_PWR_LIMIT_2_FINISH: case GPU_REQ_GET_PWR_LIMIT_3_START: case GPU_REQ_GET_PWR_LIMIT_3_2: case GPU_REQ_GET_PWR_LIMIT_3_3: case GPU_REQ_GET_PWR_LIMIT_3_FINISH: case GPU_REQ_GET_PWR_LIMIT_4_START: case GPU_REQ_GET_PWR_LIMIT_4_2: case GPU_REQ_GET_PWR_LIMIT_4_3: case GPU_REQ_GET_PWR_LIMIT_4_FINISH: case GPU_REQ_GET_PWR_LIMIT_5_START: case GPU_REQ_GET_PWR_LIMIT_5_2: case GPU_REQ_GET_PWR_LIMIT_5_3: case GPU_REQ_GET_PWR_LIMIT_5_FINISH: break; // Set GPU Power Limit case GPU_REQ_SET_PWR_LIMIT_1_START: case GPU_REQ_SET_PWR_LIMIT_1_2: case GPU_REQ_SET_PWR_LIMIT_1_3: case GPU_REQ_SET_PWR_LIMIT_1_FINISH: case GPU_REQ_SET_PWR_LIMIT_2_START: case GPU_REQ_SET_PWR_LIMIT_2_2: case GPU_REQ_SET_PWR_LIMIT_2_3: case GPU_REQ_SET_PWR_LIMIT_2_FINISH: case GPU_REQ_SET_PWR_LIMIT_3_START: case GPU_REQ_SET_PWR_LIMIT_3_2: case GPU_REQ_SET_PWR_LIMIT_3_3: case GPU_REQ_SET_PWR_LIMIT_3_FINISH: case GPU_REQ_SET_PWR_LIMIT_4_START: case GPU_REQ_SET_PWR_LIMIT_4_2: case GPU_REQ_SET_PWR_LIMIT_4_FINISH: break; // I2C reset case GPU_REQ_RESET: break; default: INTR_TRAC_ERR("schedule_gpu_req: Invalid GPU request operation: 0x%02X", i_operation); /* * @errortype * @moduleid GPU_MID_GPU_SCHED_REQ * @reasoncode GPU_FAILURE * @userdata1 operation * @userdata2 0 * @userdata4 ERC_GPU_INVALID_GPU_OPERATION * @devdesc Invalid GPU request operation */ err = createErrl(GPU_MID_GPU_SCHED_REQ, GPU_FAILURE, ERC_GPU_INVALID_GPU_OPERATION, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, i_operation, 0); commitErrl(&err); scheduleRequest = false; // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); G_gpu_monitoring_allowed = FALSE; break; } if (scheduleRequest) { // Clear errors and init common arguments for GPE G_gpu_op_req_args.error.error = 0; G_gpu_op_req_args.gpu_rc = 0; G_gpu_op_req_args.operation = i_operation; G_gpu_op_req_args.gpu_id = G_current_gpu_id; GPU_DBG("schedule_gpu_req: Scheduling GPE1 GPU operation 0x%02X (tick %d)", i_operation, GPU_TICK); int l_rc = gpe_request_schedule(&G_gpu_op_request); if (0 == l_rc) { l_scheduled = true; } else { INTR_TRAC_ERR("schedule_gpu_req: schedule failed w/rc=0x%08X (%d us)", l_rc, (int) ((ssx_timebase_get())/(SSX_TIMEBASE_FREQUENCY_HZ/1000000))); /* * @errortype * @moduleid GPU_MID_GPU_SCHED_REQ * @reasoncode SSX_GENERIC_FAILURE * @userdata1 GPE schedule returned code * @userdata2 GPU operation * @userdata4 ERC_GPU_SCHEDULE_FAILURE * @devdesc Failed to schedule GPU operation request */ err = createErrl(GPU_MID_GPU_SCHED_REQ, SSX_GENERIC_FAILURE, ERC_GPU_SCHEDULE_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, l_rc, i_operation); commitErrl(&err); // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); G_gpu_monitoring_allowed = FALSE; } } } return l_scheduled; } // end schedule_gpu_req() // Function Specification // // Name: gpu_reset_sm // // Description: GPU Reset State Machine. This is not called per GPU if any handling is needed // per GPU this function must handle and not indicate that reset is complete // until all present GPUs are ready // // End Function Specification bool gpu_reset_sm() { bool l_complete = FALSE; // only return TRUE when the reset AND initialization is complete static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_state_retry_count = 0; static uint8_t L_consec_reset_failure_count = 0; static gpuResetState_e L_reset_state = GPU_RESET_STATE_NEW; // 1st state for a reset if (async_request_is_idle(&G_gpu_op_request.request)) { // check if the previous state was successfully scheduled and success/done if( (L_reset_state != GPU_RESET_STATE_NEW) && (L_reset_state != GPU_RESET_STATE_RESET_SLAVE_WAIT) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // Check if failure was due to GPE image not having GPU support if(G_gpu_op_req_args.error.rc == GPE_RC_NO_GPU_SUPPORT) { // No GPU Support, log error and disable all GPUs INTR_TRAC_ERR("gpu_reset_sm: GPE image doesn't support GPUs!"); /* * @errortype * @moduleid GPU_MID_GPU_RESET_SM * @reasoncode GPU_NO_GPE_SUPPORT * @userdata1 0 * @userdata2 0 * @userdata4 ERC_GPU_NO_GPE_SUPPORT * @devdesc GPE1 image doesn't support GPU communication */ errlHndl_t err = createErrl(GPU_MID_GPU_RESET_SM, GPU_NO_GPE_SUPPORT, ERC_GPU_NO_GPE_SUPPORT, ERRL_SEV_UNRECOVERABLE, NULL, DEFAULT_TRACE_SIZE, 0, 0); commitErrl(&err); disable_all_gpus(); L_reset_state = GPU_RESET_STATE_NEW; return FALSE; // GPUs are not ready for communication } else { // Stay in current state if haven't reached state retry count if(L_state_retry_count < MAX_GPU_RESET_STATE_RETRY) { // INC state retry count and retry current state L_state_retry_count++; } else // this reset attempt failed { // Stop trying if reached max resets if(L_consec_reset_failure_count > MAX_CONSECUTIVE_GPU_RESETS) { INTR_TRAC_ERR("gpu_reset_sm: Max Resets reached! state[0x%02X] rc[0x%08X] addr[0x%08X] ffdc[0x%08X%08X]", L_reset_state, G_gpu_op_req_args.error.rc, G_gpu_op_req_args.error.addr, (uint32_t) (G_gpu_op_req_args.error.ffdc >> 32), (uint32_t) G_gpu_op_req_args.error.ffdc); /* * @errortype * @moduleid GPU_MID_GPU_RESET_SM * @reasoncode GPU_FAILURE * @userdata1 GPU reset state * @userdata2 GPE failure RC * @userdata4 ERC_GPU_RESET_FAILURE * @devdesc Failure resetting GPU interface */ errlHndl_t err = createErrl(GPU_MID_GPU_RESET_SM, GPU_FAILURE, ERC_GPU_RESET_FAILURE, ERRL_SEV_UNRECOVERABLE, NULL, DEFAULT_TRACE_SIZE, L_reset_state, G_gpu_op_req_args.error.rc); commitErrl(&err); disable_all_gpus(); L_reset_state = GPU_RESET_STATE_NEW; return FALSE; // GPUs are not ready for communication } else // try the reset again from the beginning { L_consec_reset_failure_count++; L_state_retry_count = 0; L_reset_state = GPU_RESET_STATE_INIT_BUS; } } // else reset attempt failed } // else GPE supports GPU }// if previous state failed else // success on last state go to next state and process it { L_state_retry_count = 0; L_reset_state++; } L_scheduled = FALSE; // default nothing scheduled switch (L_reset_state) { case GPU_RESET_STATE_INIT_BUS: // Setup I2C Interrupt Mask Register L_scheduled = schedule_gpu_req(GPU_REQ_INIT, G_new_gpu_req_args); break; case GPU_RESET_STATE_RESET_MASTER: G_new_gpu_req_args.data[0] = GPU_RESET_REQ_MASTER; L_scheduled = schedule_gpu_req(GPU_REQ_RESET, G_new_gpu_req_args); break; case GPU_RESET_STATE_RESET_SLAVE: G_new_gpu_req_args.data[0] = GPU_RESET_REQ_SLV; L_scheduled = schedule_gpu_req(GPU_REQ_RESET, G_new_gpu_req_args); break; case GPU_RESET_STATE_RESET_SLAVE_WAIT: // Delay to allow reset to complete GPU_DBG("gpu_reset_sm: waiting during slave port 4 reset"); break; case GPU_RESET_STATE_RESET_SLAVE_COMPLETE: G_new_gpu_req_args.data[0] = GPU_RESET_REQ_SLV_COMPLETE; L_scheduled = schedule_gpu_req(GPU_REQ_RESET, G_new_gpu_req_args); break; case GPU_RESET_STATE_RESET_FINISH: // Reset and init is complete ready to start sending commands to the GPUs l_complete = TRUE; L_consec_reset_failure_count = 0; // next time this is called will be to start a new reset L_reset_state = GPU_RESET_STATE_NEW; break; default: INTR_TRAC_ERR("gpu_reset_sm: INVALID STATE: 0x%02X when reset is required", L_reset_state); L_reset_state = GPU_RESET_STATE_NEW; break; } // switch L_reset_state if(L_scheduled) { GPU_DBG("gpu_reset_sm: Scheduled reset state 0x%02X", L_reset_state); } // check if the state was expected to have a schedule. Only new and slave wait // don't schedule for all other states the schedule must have failed else if( (L_reset_state != GPU_RESET_STATE_NEW) && (L_reset_state != GPU_RESET_STATE_RESET_SLAVE_WAIT) ) { INTR_TRAC_ERR("gpu_reset_sm: failed to schedule state 0x%02X", L_reset_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_reset_sm: NOT idle for state 0x%02X", L_reset_state); } return l_complete; } // end gpu_reset_sm() // Function Specification // // Name: gpu_check_driver_loaded_sm // // Description: Called from gpu_task_sm to check if driver is loaded for G_current_gpu_id // This function should only return that complete is TRUE when the check // is complete (or determined failed) and ready for a different GPU // // Pre-Req: Caller must have G_current_gpu_id set for GPU to check // // End Function Specification bool gpu_check_driver_loaded_sm() { bool l_complete = FALSE; // only return TRUE when the read is complete or failed bool l_new_driver_loaded = FALSE; static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_check_driver_failure_count[MAX_NUM_GPU_PER_DOMAIN] = {0}; static uint8_t L_state_failure_count = 0; static gpuCheckDriverLoadedState_e L_check_driver_state = GPU_STATE_CHECK_DRIVER_LOADED_NEW; static bool L_error_logged[MAX_NUM_GPU_PER_DOMAIN] = {FALSE}; static uint32_t L_num_ticks = 0; L_num_ticks++; if (async_request_is_idle(&G_gpu_op_request.request)) { // If not starting a new read then need to check status of current state before moving on // stay in current state if the schedule failed or the state isn't finished/failed if( (L_check_driver_state != GPU_STATE_CHECK_DRIVER_LOADED_NEW) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // Check if failure was due to driver change if(G_gpu_op_req_args.error.rc == GPE_RC_GPU_DRIVER_CHANGE) { handle_driver_change(); // Request can't be processed by GPU at this time so we are done with this GPU // setup to start new request L_state_failure_count = 0; L_check_driver_failure_count[G_current_gpu_id] = 0; // clear driver failure count since there's a driver change L_check_driver_state = GPU_STATE_CHECK_DRIVER_LOADED_NEW; return TRUE; // Done with this GPU, let GPU SM move to next } // If reached state retry count give up on this read else if(L_state_failure_count > MAX_GPU_READ_ATTEMPT) { // if GPU is not in reset then INC error count and check if reached threshold if(g_amec->gpu[G_current_gpu_id].status.notReset) { if(++L_check_driver_failure_count[G_current_gpu_id] > GPU_CHECK_DRIVER_ERROR_COUNT) { INTR_TRAC_ERR("gpu_check_driver_loaded: Failed to check driver loaded for GPU%d RC: 0x%02X", G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // give up checking driver loaded for this GPU // It will be retried if detected that GPU is put in reset and then taken out g_amec->gpu[G_current_gpu_id].status.checkDriverLoaded = false; L_check_driver_failure_count[G_current_gpu_id] = 0; // without driver loaded cannot read memory temp, mark memory temp as failed g_amec->gpu[G_current_gpu_id].status.memTempFailure = true; g_amec->gpu[G_current_gpu_id].status.memTempNotAvailable = true; // log one time error that driver loaded couldn't be determined if(!L_error_logged[G_current_gpu_id]) { L_error_logged[G_current_gpu_id] = TRUE; // Log error /* @ * @errortype * @moduleid GPU_MID_GPU_CHECK_DRIVER_LOADED * @reasoncode GPU_FAILURE * @userdata1 GPU ID * @userdata2 GPU RC * @userdata4 ERC_GPU_CHECK_DRIVER_LOADED_FAILURE * @devdesc Failure to check GPU driver loaded * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_CHECK_DRIVER_LOADED, GPU_FAILURE, ERC_GPU_CHECK_DRIVER_LOADED_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); } // if error not logged } // if reached error count } // if notReset L_check_driver_state = GPU_STATE_CHECK_DRIVER_LOADED_NEW; L_state_failure_count = 0; return TRUE; // Done with this GPU, let GPU SM move to next } // if reached state retry count else { // INC failure count and retry current state L_state_failure_count++; } } else // success on last state go to next state and process it { L_state_failure_count = 0; L_check_driver_state++; } L_scheduled = FALSE; // default nothing scheduled switch (L_check_driver_state) { case GPU_STATE_CHECK_DRIVER_LOADED_START: L_num_ticks = 1; L_scheduled = schedule_gpu_req(GPU_REQ_CHECK_DRIVER_START, G_new_gpu_req_args); break; case GPU_STATE_CHECK_DRIVER_LOADED_2: L_scheduled = schedule_gpu_req(GPU_REQ_CHECK_DRIVER_2, G_new_gpu_req_args); break; case GPU_STATE_CHECK_DRIVER_LOADED_3: L_scheduled = schedule_gpu_req(GPU_REQ_CHECK_DRIVER_3, G_new_gpu_req_args); break; case GPU_STATE_CHECK_DRIVER_LOADED_READ: L_scheduled = schedule_gpu_req(GPU_REQ_CHECK_DRIVER_FINISH, G_new_gpu_req_args); break; case GPU_STATE_CHECK_DRIVER_LOADED_COMPLETE: // Update GPU tick timing table update_gpu_tick_sensor(&G_gpu_tick_times.checkdriver[G_current_gpu_id], L_num_ticks); // Update driver loaded l_new_driver_loaded = G_gpu_op_req_args.data[0] & 0x01; if(l_new_driver_loaded != g_amec->gpu[G_current_gpu_id].status.driverLoaded) { // Driver loaded status changed GPU_DBG("gpu_check_driver_loaded: GPU%d driver loaded changed to %d", G_current_gpu_id, l_new_driver_loaded); if(l_new_driver_loaded) { // Driver is now loaded do checking that required driver to be loaded g_amec->gpu[G_current_gpu_id].pcap.check_pwr_limit = true; g_amec->gpu[G_current_gpu_id].status.checkMemTempSupport = true; // done checking for driver to be loaded g_amec->gpu[G_current_gpu_id].status.checkDriverLoaded = false; } else { // Driver is no longer loaded clear_gpu_driver_status(G_current_gpu_id); // memory temp only available when driver is loaded // clear error and set not available g_amec->gpu[G_current_gpu_id].status.memTempFailure = false; g_amec->gpu[G_current_gpu_id].status.memTempNotAvailable = true; // Need to keep query for driver loaded to detect when driver is loaded g_amec->gpu[G_current_gpu_id].status.checkDriverLoaded = true; } g_amec->gpu[G_current_gpu_id].status.driverLoaded = l_new_driver_loaded; } // Done with this GPU ready to move to new one L_check_driver_failure_count[G_current_gpu_id] = 0; L_check_driver_state = GPU_STATE_CHECK_DRIVER_LOADED_NEW; l_complete = TRUE; break; default: INTR_TRAC_ERR("gpu_check_driver_loaded: INVALID STATE: 0x%02X", L_check_driver_state); L_check_driver_state = GPU_STATE_CHECK_DRIVER_LOADED_NEW; l_complete = TRUE; break; } // switch L_check_driver_state if(L_scheduled) { GPU_DBG("gpu_check_driver_loaded: Scheduled check driver loaded state 0x%02X at tick %d", L_check_driver_state, GPU_TICK); } else if(!l_complete) // if not complete there must have been a failure on the schedule { INTR_TRAC_ERR("gpu_check_driver_loaded: failed to schedule state 0x%02X", L_check_driver_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_check_driver_loaded: NOT idle for state 0x%02X", L_check_driver_state); } return l_complete; } // end gpu_check_driver_loaded_sm() // Function Specification // // Name: gpu_read_pwr_limit_sm // // Description: Called from gpu_task_sm to read GPU power limits for G_current_gpu_id // This function should only return that complete is TRUE when the read // is complete (or determined failed) and ready for a different GPU // // Pre-Req: Caller must have G_current_gpu_id set for GPU to read // // End Function Specification bool gpu_read_pwr_limit_sm() { bool l_complete = FALSE; // only return TRUE when the read is complete or failed static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_read_pwr_limit_failure_count[MAX_NUM_GPU_PER_DOMAIN] = {0}; static uint8_t L_state_failure_count = 0; static gpuReadPwrLimitState_e L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_NEW; static bool L_error_logged[MAX_NUM_GPU_PER_DOMAIN] = {FALSE}; static uint32_t L_attempts = 0; static uint32_t L_last_min[MAX_NUM_GPU_PER_DOMAIN] = {0}; static uint32_t L_last_max[MAX_NUM_GPU_PER_DOMAIN] = {0}; static uint32_t L_num_ticks = 0; static bool L_retry_necessary = FALSE; L_num_ticks++; if (async_request_is_idle(&G_gpu_op_request.request)) { // If not starting a new read then need to check status of current state before moving on // stay in current state if the schedule failed or the state isn't finished/failed if( (L_read_pwr_limit_state != GPU_STATE_READ_PWR_LIMIT_NEW) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // Repeat step 2 until it succeeds. More details on this in GPE code. if( (L_read_pwr_limit_state == GPU_STATE_READ_PWR_LIMIT_2_FINISH) && (GPE_RC_NOT_COMPLETE == G_gpu_op_req_args.error.rc) && (L_attempts <= GPU_TIMEOUT) ) { L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_2_START; L_state_failure_count = 0; L_attempts++; } else if( (L_read_pwr_limit_state == GPU_STATE_READ_PWR_LIMIT_1_3) && (GPE_RC_GPU_BUSY == G_gpu_op_req_args.error.rc) ) { L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_1_FINISH; L_retry_necessary = TRUE; } // Check if failure was due to driver change else if(G_gpu_op_req_args.error.rc == GPE_RC_GPU_DRIVER_CHANGE) { handle_driver_change(); // Request can't be processed by GPU at this time so we are done with this GPU // setup to start new request L_state_failure_count = 0; L_read_pwr_limit_failure_count[G_current_gpu_id] = 0; // clear failure count since there's a driver change L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_NEW; L_attempts = 0; L_retry_necessary = FALSE; return TRUE; // Done with this GPU, let GPU SM move to next } // If reached retry count give up on this read else if( (L_state_failure_count > MAX_GPU_READ_ATTEMPT) || (L_attempts > GPU_TIMEOUT) ) { if(L_attempts > GPU_TIMEOUT) { // give up trying to read power limits for this GPU // It will be retried if detected that GPU is put in reset and then taken out g_amec->gpu[G_current_gpu_id].pcap.check_pwr_limit = false; L_read_pwr_limit_failure_count[G_current_gpu_id] = 0; } // if GPU is not in reset then INC error count and check if reached threshold if(g_amec->gpu[G_current_gpu_id].status.notReset) { if(++L_read_pwr_limit_failure_count[G_current_gpu_id] > GPU_READ_PWR_LIMIT_ERROR_COUNT) { INTR_TRAC_ERR("gpu_read_pwr_limit_sm: Failed to read power limits for GPU%d RC: 0x%02X", G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // give up trying to read power limits for this GPU // It will be retried if detected that GPU is put in reset and then taken out g_amec->gpu[G_current_gpu_id].pcap.check_pwr_limit = false; L_read_pwr_limit_failure_count[G_current_gpu_id] = 0; // log one time error that power limits could not be read if(!L_error_logged[G_current_gpu_id]) { L_error_logged[G_current_gpu_id] = TRUE; // Log error /* @ * @errortype * @moduleid GPU_MID_GPU_READ_PWR_LIMIT * @reasoncode GPU_FAILURE * @userdata1 GPU ID * @userdata2 GPU RC * @userdata4 ERC_GPU_READ_PWR_LIMIT_FAILURE * @devdesc Failure to read GPU power limits * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_READ_PWR_LIMIT, GPU_FAILURE, ERC_GPU_READ_PWR_LIMIT_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); } // if error not logged } // if reached error count } // if notReset L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_NEW; L_state_failure_count = 0; L_attempts = 0; return TRUE; // Done with this GPU, let GPU SM move to next } // if reached retry count else { // INC failure count and retry current state L_state_failure_count++; } } else // success on last state go to next state and process it { L_state_failure_count = 0; if( (GPU_STATE_READ_PWR_LIMIT_1_FINISH == L_read_pwr_limit_state) && (L_retry_necessary) ) { // Let SM move on L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_NEW; return TRUE; } else { L_read_pwr_limit_state++; } } L_scheduled = FALSE; // default nothing scheduled switch (L_read_pwr_limit_state) { // Step 1 case GPU_STATE_READ_PWR_LIMIT_1_START: if(!L_retry_necessary) L_num_ticks = 1; L_retry_necessary = FALSE; L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_1_START, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_1_2: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_1_2, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_1_3: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_1_3, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_1_FINISH: L_attempts = 0; L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_1_FINISH, G_new_gpu_req_args); break; // Step 2 case GPU_STATE_READ_PWR_LIMIT_2_START: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_2_START, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_2_2: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_2_2, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_2_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_2_FINISH, G_new_gpu_req_args); break; // Step 3 case GPU_STATE_READ_PWR_LIMIT_3_START: GPU_DBG("gpu_read_pwr_limit_sm: took %d ticks to finish read pcap for GPU%d", L_attempts, G_current_gpu_id); L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_3_START, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_3_2: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_3_2, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_3_3: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_3_3, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_3_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_3_FINISH, G_new_gpu_req_args); break; // Step 4 case GPU_STATE_READ_PWR_LIMIT_4_START: G_new_gpu_req_args.data[0] = G_gpu_op_req_args.data[0]; L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_4_START, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_4_2: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_4_2, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_4_3: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_4_3, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_4_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_4_FINISH, G_new_gpu_req_args); break; // Step 5 case GPU_STATE_READ_PWR_LIMIT_5_START: G_new_gpu_req_args.data[0] = G_gpu_op_req_args.data[0]; G_new_gpu_req_args.data[1] = G_gpu_op_req_args.data[1]; L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_5_START, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_5_2: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_5_2, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_5_3: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_5_3, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_5_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_GET_PWR_LIMIT_5_FINISH, G_new_gpu_req_args); break; case GPU_STATE_READ_PWR_LIMIT_COMPLETE: update_gpu_tick_sensor(&G_gpu_tick_times.getpcap[G_current_gpu_id], L_num_ticks); g_amec->gpu[G_current_gpu_id].pcap.check_pwr_limit = FALSE; // Update power limits g_amec->gpu[G_current_gpu_id].pcap.pwr_limits_read = TRUE; g_amec->gpu[G_current_gpu_id].pcap.gpu_min_pcap_mw = G_gpu_op_req_args.data[0]; g_amec->gpu[G_current_gpu_id].pcap.gpu_max_pcap_mw = G_gpu_op_req_args.data[1]; g_amec->gpu[G_current_gpu_id].pcap.gpu_default_pcap_mw = G_gpu_op_req_args.data[2]; if( (g_amec->gpu[G_current_gpu_id].pcap.gpu_min_pcap_mw != L_last_min[G_current_gpu_id]) || (g_amec->gpu[G_current_gpu_id].pcap.gpu_max_pcap_mw != L_last_max[G_current_gpu_id]) ) { L_last_min[G_current_gpu_id] = g_amec->gpu[G_current_gpu_id].pcap.gpu_min_pcap_mw; L_last_max[G_current_gpu_id] = g_amec->gpu[G_current_gpu_id].pcap.gpu_max_pcap_mw; TRAC_IMP("gpu_read_pwr_limit: GPU%d min=0x%08XmW max=0x%08XmW", G_current_gpu_id, g_amec->gpu[G_current_gpu_id].pcap.gpu_min_pcap_mw, g_amec->gpu[G_current_gpu_id].pcap.gpu_max_pcap_mw); } // Done with this GPU ready to move to new one L_read_pwr_limit_failure_count[G_current_gpu_id] = 0; L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_NEW; L_attempts = 0; l_complete = TRUE; break; default: INTR_TRAC_ERR("gpu_read_pwr_limit: INVALID STATE: 0x%02X", L_read_pwr_limit_state); L_read_pwr_limit_state = GPU_STATE_READ_PWR_LIMIT_NEW; l_complete = TRUE; break; } // switch L_read_pwr_limit_state if(L_scheduled) { GPU_DBG("gpu_read_pwr_limit: Scheduled check driver loaded state 0x%02X at tick %d", L_read_pwr_limit_state, GPU_TICK); } else if(!l_complete) // if not complete there must have been a failure on the schedule { INTR_TRAC_ERR("gpu_read_pwr_limit: failed to schedule state 0x%02X", L_read_pwr_limit_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_read_pwr_limit: NOT idle for state 0x%02X", L_read_pwr_limit_state); } return l_complete; } // end gpu_read_pwr_limit_sm() // Function Specification // // Name: gpu_set_pwr_limit_sm // // Description: Called from gpu_task_sm to set GPU power limit for G_current_gpu_id // This function should only return that complete is TRUE when the set // is complete (or determined failed) and ready for a different GPU // // Pre-Req: Caller must have G_current_gpu_id set for GPU to read // // End Function Specification bool gpu_set_pwr_limit_sm() { bool l_complete = FALSE; // only return TRUE when complete or failed static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_state_failure_count = 0; static uint8_t L_set_pwr_limit_failure_count[MAX_NUM_GPU_PER_DOMAIN] = {0}; static gpuSetPwrLimitState_e L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_NEW; static bool L_error_logged[MAX_NUM_GPU_PER_DOMAIN] = {FALSE}; static uint32_t L_attempts = 0; static uint32_t L_last_pcap[MAX_NUM_GPU_PER_DOMAIN] = {0}; static uint32_t L_num_ticks = 0; static bool L_retry_necessary = FALSE; L_num_ticks++; if (async_request_is_idle(&G_gpu_op_request.request)) { // If not starting a new set limit then need to check status of current state before moving on // stay in current state if the schedule failed or the state isn't finished/failed if( (L_set_pwr_limit_state != GPU_STATE_SET_PWR_LIMIT_NEW) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // Repeat step 4 until it succeeds. More details on this in GPE code. if( (L_set_pwr_limit_state == GPU_STATE_SET_PWR_LIMIT_4_FINISH) && (GPE_RC_NOT_COMPLETE == G_gpu_op_req_args.error.rc) && (L_attempts <= GPU_TIMEOUT) ) { L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_4_START; L_state_failure_count = 0; L_attempts++; } else if( (L_set_pwr_limit_state == GPU_STATE_SET_PWR_LIMIT_3_3) && (GPE_RC_GPU_BUSY == G_gpu_op_req_args.error.rc) ) { L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_3_FINISH; L_retry_necessary = TRUE; } // Check if failure was due to driver change else if(G_gpu_op_req_args.error.rc == GPE_RC_GPU_DRIVER_CHANGE) { handle_driver_change(); // Request can't be processed by GPU at this time so we are done with this GPU // setup to start new request L_state_failure_count = 0; L_set_pwr_limit_failure_count[G_current_gpu_id] = 0; // clear failure count since there's a driver change L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_NEW; L_attempts = 0; L_retry_necessary = FALSE; return TRUE; // Done with this GPU, let GPU SM move to next } // If reached retry count give up on this read else if( (L_state_failure_count > MAX_GPU_READ_ATTEMPT) || (L_attempts > GPU_TIMEOUT) ) { if(L_attempts > GPU_TIMEOUT) { // give up trying to set power limit for this GPU // It will be retried if detected that GPU is put in reset and then taken out or driver change g_amec->gpu[G_current_gpu_id].pcap.set_failed = true; L_set_pwr_limit_failure_count[G_current_gpu_id] = 0; INTR_TRAC_ERR("gpu_set_pwr_limit: Timedout setting power limit %d for GPU%d [attempts:%d][state_fail:%d]", G_gpu_op_req_args.data[0], G_current_gpu_id, L_attempts, L_state_failure_count); } // if GPU is not in reset then INC error count and check if reached threshold if(g_amec->gpu[G_current_gpu_id].status.notReset) { if(++L_set_pwr_limit_failure_count[G_current_gpu_id] > GPU_SET_PWR_LIMIT_ERROR_COUNT) { INTR_TRAC_ERR("gpu_set_pwr_limit: Failed to set power limit %d for GPU%d RC: 0x%02X", G_gpu_op_req_args.data[0], G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // give up trying to set power limit for this GPU // It will be retried if detected that GPU is put in reset and then taken out or driver change g_amec->gpu[G_current_gpu_id].pcap.set_failed = true; L_set_pwr_limit_failure_count[G_current_gpu_id] = 0; // log error that power limit could not be set if(!L_error_logged[G_current_gpu_id]) { L_error_logged[G_current_gpu_id] = TRUE; // Log error /* @ * @errortype * @moduleid GPU_MID_GPU_SET_PWR_LIMIT * @reasoncode GPU_FAILURE * @userdata1 GPU ID * @userdata2 GPU RC * @userdata4 ERC_GPU_SET_PWR_LIMIT_FAILURE * @devdesc Failure to set GPU power limit * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_SET_PWR_LIMIT, GPU_FAILURE, ERC_GPU_SET_PWR_LIMIT_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); } // if error not logged } // if reached error count } // if notReset L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_NEW; L_state_failure_count = 0; L_attempts = 0; return TRUE; // Done with this GPU, let GPU SM move to next } // if reached retry count else { // INC failure count and retry current state L_state_failure_count++; } } else // success on last state go to next state and process it { L_state_failure_count = 0; if( (GPU_STATE_SET_PWR_LIMIT_4_FINISH == L_set_pwr_limit_state ) && (L_retry_necessary) ) { // Let SM move to next L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_NEW; return TRUE; } else { L_set_pwr_limit_state++; } } L_scheduled = FALSE; // default nothing scheduled switch (L_set_pwr_limit_state) { // Step 1 case GPU_STATE_SET_PWR_LIMIT_1_START: if(!L_retry_necessary) L_num_ticks = 1; L_retry_necessary = FALSE; L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_1_START, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_1_2: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_1_2, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_1_3: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_1_3, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_1_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_1_FINISH, G_new_gpu_req_args); break; // Step 2 case GPU_STATE_SET_PWR_LIMIT_2_START: // send the desired GPU power cap to the GPE to send to GPU GPU_DBG("gpu_set_pwr_limit_sm: setting power limit to %dmW on GPU%d", g_amec->gpu[G_current_gpu_id].pcap.gpu_desired_pcap_mw, G_current_gpu_id); G_new_gpu_req_args.data[1] = g_amec->gpu[G_current_gpu_id].pcap.gpu_desired_pcap_mw; L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_2_START, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_2_2: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_2_2, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_2_3: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_2_3, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_2_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_2_FINISH, G_new_gpu_req_args); break; // Step 3 case GPU_STATE_SET_PWR_LIMIT_3_START: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_3_START, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_3_2: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_3_2, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_3_3: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_3_3, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_3_FINISH: L_attempts = 0; L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_3_FINISH, G_new_gpu_req_args); break; // Step 4 case GPU_STATE_SET_PWR_LIMIT_4_START: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_4_START, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_4_2: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_4_2, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_4_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_SET_PWR_LIMIT_4_FINISH, G_new_gpu_req_args); break; case GPU_STATE_SET_PWR_LIMIT_COMPLETE: update_gpu_tick_sensor(&G_gpu_tick_times.setpcap[G_current_gpu_id], L_num_ticks); GPU_DBG("gpu_set_pwr_limit_sm: took %d ticks to finish setting pcap for GPU%d", L_attempts, G_current_gpu_id); // Update the requested power limit since it was successfully sent // NOTE: want this value to be sent back from the GPE to know what was set in case AMEC // has caluclated a new desired pcap while this one was already in process of being set g_amec->gpu[G_current_gpu_id].pcap.gpu_requested_pcap_mw = (uint32_t) G_gpu_op_req_args.data[0]; if(g_amec->gpu[G_current_gpu_id].pcap.gpu_requested_pcap_mw != L_last_pcap[G_current_gpu_id]) { L_last_pcap[G_current_gpu_id] = g_amec->gpu[G_current_gpu_id].pcap.gpu_requested_pcap_mw; TRAC_IMP("gpu_set_pwr_limit_sm: successfully set power limit to %dmW on GPU%d", g_amec->gpu[G_current_gpu_id].pcap.gpu_desired_pcap_mw, G_current_gpu_id); } // Done with this GPU ready to move to new one L_set_pwr_limit_failure_count[G_current_gpu_id] = 0; L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_NEW; L_attempts = 0; l_complete = TRUE; break; default: INTR_TRAC_ERR("gpu_set_pwr_limit: INVALID STATE: 0x%02X", L_set_pwr_limit_state); L_set_pwr_limit_state = GPU_STATE_SET_PWR_LIMIT_NEW; l_complete = TRUE; break; } // switch L_set_pwr_limit_state if(L_scheduled) { GPU_DBG("gpu_set_pwr_limit: Scheduled set power cap state 0x%02X at tick %d", L_set_pwr_limit_state, GPU_TICK); } else if(!l_complete) // if not complete there must have been a failure on the schedule { INTR_TRAC_ERR("gpu_set_pwr_limit: failed to schedule state 0x%02X", L_set_pwr_limit_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_set_pwr_limit: NOT idle for state 0x%02X", L_set_pwr_limit_state); } return l_complete; } // end gpu_set_pwr_limit_sm() // Function Specification // // Name: gpu_read_temp_sm // // Description: Called from gpu_task_sm to read GPU core temperature of G_current_gpu_id // This function should only return that complete is TRUE when the temperature // read is complete (or determined failed) and ready to start reading a different GPU // // Pre-Req: Caller must have G_current_gpu_id set for GPU to read and // verified G_gpu_op_request is idle to allow scheduling // End Function Specification bool gpu_read_temp_sm() { bool l_complete = FALSE; // only return TRUE when the read is complete or failed uint16_t l_temp = 0; static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_read_failure_count = 0; // Used for I2C errors static bool L_trace_success = FALSE; static gpuReadTempState_e L_read_temp_state = GPU_STATE_READ_TEMP_NEW; // 1st state for reading temp static uint32_t L_num_ticks = 0; L_num_ticks++; if (async_request_is_idle(&G_gpu_op_request.request)) { // If not starting a new read then need to check status of current state before moving on // stay in current state if the schedule failed or the state isn't finished/failed if( (L_read_temp_state != GPU_STATE_READ_TEMP_NEW) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // If reached retry count give up on this GPU if( (L_read_failure_count > MAX_GPU_READ_ATTEMPT) || (GPE_RC_I2C_ERROR == G_gpu_op_req_args.error.rc) ) { mark_gpu_failed(&G_gpu_op_req_args); L_read_temp_state = GPU_STATE_READ_TEMP_NEW; L_read_failure_count = 0; return TRUE; // Done with this GPU, let GPU SM move to next } else { // INC failure count and retry current state L_read_failure_count++; } } else // success on last state go to next state and process it { L_read_failure_count = 0; L_read_temp_state++; } L_scheduled = FALSE; // default nothing scheduled switch (L_read_temp_state) { case GPU_STATE_READ_TEMP_START: L_num_ticks = 1; L_scheduled = schedule_gpu_req(GPU_REQ_READ_TEMP_START, G_new_gpu_req_args); break; case GPU_STATE_READ_TEMP_FINISH: L_scheduled = schedule_gpu_req(GPU_REQ_READ_TEMP_FINISH, G_new_gpu_req_args); break; case GPU_STATE_READ_TEMP_COMPLETE: update_gpu_tick_sensor(&G_gpu_tick_times.coretemp[G_current_gpu_id], L_num_ticks); if( (!g_amec->gpu[G_current_gpu_id].status.readOnce) && (0 != G_gpu_op_req_args.data[0]) ) { g_amec->gpu[G_current_gpu_id].status.readOnce = true; // Only trace this once if(FALSE == L_trace_success) { TRAC_INFO("First successful attempt to read temp from GPU%d was on tick %d", G_current_gpu_id, CURRENT_TICK); L_trace_success = TRUE; } // comm is now established update for capability checking to take place g_amec->gpu[G_current_gpu_id].status.checkDriverLoaded = TRUE; } // Update sensor l_temp = G_gpu_op_req_args.data[0]; sensor_update(AMECSENSOR_PTR(TEMPGPU0 + G_current_gpu_id), l_temp); // Clear all past errors g_amec->gpu[G_current_gpu_id].status.coreTempFailure = false; g_amec->gpu[G_current_gpu_id].status.coreTempNotAvailable = false; g_amec->gpu[G_current_gpu_id].status.errorCount = 0; g_amec->gpu[G_current_gpu_id].status.retryCount = 0; // check if there is an overtemp that hasn't been reported if((G_data_cnfg->thrm_thresh.data[DATA_FRU_GPU].error) && (l_temp > G_data_cnfg->thrm_thresh.data[DATA_FRU_GPU].error) && (!g_amec->gpu[G_current_gpu_id].status.overtempError) ) { g_amec->gpu[G_current_gpu_id].status.overtempError = TRUE; INTR_TRAC_ERR("gpu_read_temp: GPU%d OT! temp[%d]", G_current_gpu_id, l_temp); // Log an OT error /* @ * @errortype * @moduleid GPU_MID_GPU_READ_TEMP * @reasoncode GPU_ERROR_TEMP * @userdata1 GPU ID * @userdata2 GPU memory temperature * @userdata4 OCC_NO_EXTENDED_RC * @devdesc GPU memory has reached error temperature * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_READ_TEMP, GPU_ERROR_TEMP, OCC_NO_EXTENDED_RC, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_current_gpu_id, l_temp); // Callout the over temperature procedure addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_OVER_TEMPERATURE, ERRL_CALLOUT_PRIORITY_HIGH); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); } // if OT error // Done with this GPU ready to move to new one L_read_temp_state = GPU_STATE_READ_TEMP_NEW; l_complete = TRUE; break; default: INTR_TRAC_ERR("gpu_read_temp_sm: INVALID STATE: 0x%02X", L_read_temp_state); L_read_temp_state = GPU_STATE_READ_TEMP_NEW; l_complete = TRUE; break; } // switch L_read_temp_state if(L_scheduled) { GPU_DBG("gpu_read_temp_sm: Scheduled read temp state 0x%02X at tick %d", L_read_temp_state, GPU_TICK); } else if(!l_complete) // if not complete there must have been a failure on the schedule { INTR_TRAC_ERR("gpu_read_temp_sm: failed to schedule state 0x%02X", L_read_temp_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_read_temp_sm: NOT idle for state 0x%02X", L_read_temp_state); } return l_complete; } // end gpu_read_temp_sm() // Function Specification // // Name: gpu_read_mem_temp_capability_sm // // Description: Called from gpu_task_sm to read GPU memory temp capability of G_current_gpu_id // This function should only return that complete is TRUE when the capability // read is complete (or determined failed) and ready to start reading a different GPU // // Pre-Req: Caller must have G_current_gpu_id set for GPU to read // // End Function Specification bool gpu_read_mem_temp_capability_sm() { bool l_complete = FALSE; // only return TRUE when the read is complete or failed static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_read_mem_cap_failure_count[MAX_NUM_GPU_PER_DOMAIN] = {0}; static uint8_t L_state_failure_count = 0; static gpuReadMemTempCapableState_e L_read_cap_state = GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW; static bool L_error_logged[MAX_NUM_GPU_PER_DOMAIN] = {FALSE}; static uint32_t L_num_ticks = 0; L_num_ticks++; if (async_request_is_idle(&G_gpu_op_request.request)) { // If not starting a new read then need to check status of current state before moving on // stay in current state if the schedule failed or the state isn't finished/failed if( (L_read_cap_state != GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // Check if failure was due to driver change if(G_gpu_op_req_args.error.rc == GPE_RC_GPU_DRIVER_CHANGE) { handle_driver_change(); // Request can't be processed by GPU at this time so we are done with this GPU // setup to start new request L_state_failure_count = 0; L_read_mem_cap_failure_count[G_current_gpu_id] = 0; // clear failure count since there's a driver change L_read_cap_state = GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW; return TRUE; // Done with this GPU, let GPU SM move to next } // If reached state retry count give up on this read else if(L_state_failure_count > MAX_GPU_READ_ATTEMPT) { // if GPU is not in reset then INC error count and check if reached threshold if(g_amec->gpu[G_current_gpu_id].status.notReset) { if(++L_read_mem_cap_failure_count[G_current_gpu_id] > GPU_READ_MEM_CAP_ERROR_COUNT) { INTR_TRAC_ERR("gpu_read_mem_temp_capable: Failed to read capability for GPU%d RC: 0x%02X", G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // give up trying to read mem temp capability for this GPU // It will be retried if detected that GPU driver is re-loaded g_amec->gpu[G_current_gpu_id].status.checkMemTempSupport = FALSE; L_read_mem_cap_failure_count[G_current_gpu_id] = 0; // cannot determine memory temp capability, mark memory temp as failed g_amec->gpu[G_current_gpu_id].status.memTempFailure = true; g_amec->gpu[G_current_gpu_id].status.memTempNotAvailable = true; // log one time error that memory temp capability couldn't be determined if(!L_error_logged[G_current_gpu_id]) { L_error_logged[G_current_gpu_id] = TRUE; // Log error /* @ * @errortype * @moduleid GPU_MID_GPU_READ_MEM_TEMP_CAPABLE * @reasoncode GPU_FAILURE * @userdata1 GPU ID * @userdata2 GPU RC * @userdata4 ERC_GPU_READ_MEM_TEMP_CAPABLE_FAILURE * @devdesc Failure to read memory temp capability * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_READ_MEM_TEMP_CAPABLE, GPU_FAILURE, ERC_GPU_READ_MEM_TEMP_CAPABLE_FAILURE, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_current_gpu_id, G_gpu_op_req_args.gpu_rc); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); } // if error not logged } // if reached error count } // if notReset L_read_cap_state = GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW; L_state_failure_count = 0; return TRUE; // Done with this GPU, let GPU SM move to next } // if reached state retry count else { // INC failure count and retry current state L_state_failure_count++; } } else // success on last state go to next state and process it { L_state_failure_count = 0; L_read_cap_state++; } L_scheduled = FALSE; // default nothing scheduled switch (L_read_cap_state) { case GPU_STATE_READ_MEM_TEMP_CAPABLE_START: L_num_ticks = 1; L_scheduled = schedule_gpu_req(GPU_REQ_READ_CAPS_START, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_CAPABLE_2: L_scheduled = schedule_gpu_req(GPU_REQ_READ_CAPS_2, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_CAPABLE_3: L_scheduled = schedule_gpu_req(GPU_REQ_READ_CAPS_3, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_CAPABLE_READ: L_scheduled = schedule_gpu_req(GPU_REQ_READ_CAPS_FINISH, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_CAPABLE_COMPLETE: update_gpu_tick_sensor(&G_gpu_tick_times.capabilities[G_current_gpu_id], L_num_ticks); // Update capability g_amec->gpu[G_current_gpu_id].status.memTempSupported = G_gpu_op_req_args.data[0] & 0x01; if(g_amec->gpu[G_current_gpu_id].status.memTempSupported) { // mem temp is supported no need to re-check capability g_amec->gpu[G_current_gpu_id].status.checkMemTempSupport = FALSE; } else { // Need to keep query for mem temp capability to detect if ever changes to capable g_amec->gpu[G_current_gpu_id].status.checkMemTempSupport = TRUE; } // Done with this GPU ready to move to new one L_read_mem_cap_failure_count[G_current_gpu_id] = 0; L_read_cap_state = GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW; l_complete = TRUE; break; default: INTR_TRAC_ERR("gpu_read_mem_temp_capable: INVALID STATE: 0x%02X", L_read_cap_state); L_read_cap_state = GPU_STATE_READ_MEM_TEMP_CAPABLE_NEW; l_complete = TRUE; break; } // switch L_read_cap_state if(L_scheduled) { GPU_DBG("gpu_read_mem_temp_capable: Scheduled read temp capability state 0x%02X at tick %d", L_read_cap_state, GPU_TICK); } else if(!l_complete) // if not complete there must have been a failure on the schedule { INTR_TRAC_ERR("gpu_read_mem_temp_capable: failed to schedule state 0x%02X", L_read_cap_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_read_mem_temp_capable: NOT idle for state 0x%02X", L_read_cap_state); } return l_complete; } // end gpu_read_mem_temp_capability_sm() // Function Specification // // Name: gpu_read_memory_temp_sm // // Description: Called from gpu_task_sm to read GPU memory temperature of G_current_gpu_id // This function should only return that complete is TRUE when the temperature // read is complete (or determined failed) and ready to start reading a different GPU // // Pre-Req: Caller must have G_current_gpu_id set for GPU to read // // End Function Specification bool gpu_read_memory_temp_sm() { bool l_complete = FALSE; // only return TRUE when the read is complete or failed uint16_t l_temp = 0; static bool L_scheduled = FALSE; // indicates if a GPU GPE request was scheduled static uint8_t L_read_failure_count = 0; static gpuReadMemTempState_e L_read_temp_state = GPU_STATE_READ_MEM_TEMP_NEW; // 1st state for reading temp static uint32_t L_num_ticks = 0; L_num_ticks++; if (async_request_is_idle(&G_gpu_op_request.request)) { // If not starting a new read then need to check status of current state before moving on // stay in current state if the schedule failed or the state isn't finished/failed if( (L_read_temp_state != GPU_STATE_READ_MEM_TEMP_NEW) && (!L_scheduled || (GPE_RC_SUCCESS != G_gpu_op_req_args.error.rc)) ) { // Check if failure was due to driver change if(G_gpu_op_req_args.error.rc == GPE_RC_GPU_DRIVER_CHANGE) { handle_driver_change(); // Request can't be processed by GPU at this time so we are done with this GPU // setup to start new request L_read_failure_count = 0; g_amec->gpu[G_current_gpu_id].status.memErrorCount = 0; L_read_temp_state = GPU_STATE_READ_MEM_TEMP_NEW; return TRUE; // Done with this GPU, let GPU SM move to next } // If reached retry count or GPU indicated cmd not supported then give up on this read else if( (L_read_failure_count > MAX_GPU_READ_ATTEMPT) || (G_gpu_op_req_args.error.rc == GPE_RC_GPU_CMD_NOT_SUPPORTED) ) { // if GPU is not in reset or the GPU responded with command not supported then // INC memory error count and check if reached timeout for new mem temp if( (g_amec->gpu[G_current_gpu_id].status.notReset) || (G_gpu_op_req_args.error.rc == GPE_RC_GPU_CMD_NOT_SUPPORTED) ) { g_amec->gpu[G_current_gpu_id].status.memErrorCount++; uint8_t max_read_timeout = G_data_cnfg->thrm_thresh.data[DATA_FRU_GPU_MEM].max_read_timeout; if((max_read_timeout) && (max_read_timeout != 0xFF) && (g_amec->gpu[G_current_gpu_id].status.memErrorCount >= max_read_timeout) ) { // Disable memory temp reading for this GPU and log error g_amec->gpu[G_current_gpu_id].status.memTempSupported = FALSE; // so BMC knows there is an error for fan control set failure g_amec->gpu[G_current_gpu_id].status.memTempFailure = true; g_amec->gpu[G_current_gpu_id].status.memTempNotAvailable = true; INTR_TRAC_ERR("gpu_read_memory_temp: disabling memory temp for GPU%d due to %d consecutive errors", G_current_gpu_id, g_amec->gpu[G_current_gpu_id].status.memErrorCount); if(g_amec->gpu[G_current_gpu_id].status.commErrorLogged == false) { INTR_TRAC_ERR("notReset: %d rc: 0x%0X", g_amec->gpu[G_current_gpu_id].status.notReset, G_gpu_op_req_args.error.rc); // Log error /* @ * @errortype * @moduleid GPU_MID_GPU_READ_MEM_TEMP * @reasoncode GPU_FAILURE * @userdata1 GPU ID * @userdata2 GPU RC * @userdata4 ERC_GPU_READ_MEM_TEMP_TIMEOUT * @devdesc Timeout reading new GPU memory temperature * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_READ_MEM_TEMP, GPU_FAILURE, ERC_GPU_READ_MEM_TEMP_TIMEOUT, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_gpu_op_req_args.gpu_rc, g_amec->gpu[G_current_gpu_id].status.memErrorCount); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); g_amec->gpu[G_current_gpu_id].status.commErrorLogged = true; } // if !commErrorLogged } // if timeout error else if(G_gpu_op_req_args.error.rc == GPE_RC_GPU_CMD_NOT_SUPPORTED) { // GPU indicated command not supported, re-check mem temp capability // if we try to read mem temp again that means mem temp was reported capable // and if this continues to fail eventually an error will be logged above at timeout g_amec->gpu[G_current_gpu_id].status.checkMemTempSupport = true; g_amec->gpu[G_current_gpu_id].status.memTempSupported = false; } } // if notReset or command not supported // setup to start new request L_read_failure_count = 0; L_read_temp_state = GPU_STATE_READ_MEM_TEMP_NEW; return TRUE; // Done with this GPU, let GPU SM move to next } // else if failure count exceeded or command not supported else { // INC failure count and retry current state L_read_failure_count++; } } else // success on last state go to next state and process it { L_read_failure_count = 0; L_read_temp_state++; } L_scheduled = FALSE; // default nothing scheduled switch (L_read_temp_state) { case GPU_STATE_READ_MEM_TEMP_START: L_num_ticks = 1; L_scheduled = schedule_gpu_req(GPU_REQ_READ_MEM_TEMP_START, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_2: L_scheduled = schedule_gpu_req(GPU_REQ_READ_MEM_TEMP_2, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_3: L_scheduled = schedule_gpu_req(GPU_REQ_READ_MEM_TEMP_3, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_READ: L_scheduled = schedule_gpu_req(GPU_REQ_READ_MEM_TEMP_FINISH, G_new_gpu_req_args); break; case GPU_STATE_READ_MEM_TEMP_COMPLETE: update_gpu_tick_sensor(&G_gpu_tick_times.memtemp[G_current_gpu_id], L_num_ticks); // Update sensor l_temp = G_gpu_op_req_args.data[0]; sensor_update(AMECSENSOR_PTR(TEMPGPU0MEM + G_current_gpu_id), l_temp); // Clear past errors g_amec->gpu[G_current_gpu_id].status.memTempFailure = false; g_amec->gpu[G_current_gpu_id].status.memTempNotAvailable = false; g_amec->gpu[G_current_gpu_id].status.memErrorCount = 0; // check if there is an overtemp that hasn't been reported if((G_data_cnfg->thrm_thresh.data[DATA_FRU_GPU_MEM].error) && (l_temp > G_data_cnfg->thrm_thresh.data[DATA_FRU_GPU_MEM].error) && (!g_amec->gpu[G_current_gpu_id].status.memOvertempError) ) { g_amec->gpu[G_current_gpu_id].status.memOvertempError = TRUE; INTR_TRAC_ERR("gpu_read_memory_temp: GPU%d memory OT! temp[%d]", G_current_gpu_id, l_temp); // Log an OT error /* @ * @errortype * @moduleid GPU_MID_GPU_READ_MEM_TEMP * @reasoncode GPU_MEMORY_ERROR_TEMP * @userdata1 GPU ID * @userdata2 GPU memory temperature * @userdata4 OCC_NO_EXTENDED_RC * @devdesc GPU memory has reached error temperature * */ errlHndl_t l_err = createErrl(GPU_MID_GPU_READ_MEM_TEMP, GPU_MEMORY_ERROR_TEMP, OCC_NO_EXTENDED_RC, ERRL_SEV_PREDICTIVE, NULL, DEFAULT_TRACE_SIZE, G_current_gpu_id, l_temp); // Callout the over temperature procedure addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_COMPONENT_ID, ERRL_COMPONENT_ID_OVER_TEMPERATURE, ERRL_CALLOUT_PRIORITY_HIGH); // Callout the GPU if have sensor ID for it if(G_sysConfigData.gpu_sensor_ids[G_current_gpu_id]) { addCalloutToErrl(l_err, ERRL_CALLOUT_TYPE_GPU_ID, G_sysConfigData.gpu_sensor_ids[G_current_gpu_id], ERRL_CALLOUT_PRIORITY_MED); } // Commit Error commitErrl(&l_err); } // if OT error // Done with this GPU ready to move to new one L_read_temp_state = GPU_STATE_READ_MEM_TEMP_NEW; l_complete = TRUE; break; default: INTR_TRAC_ERR("gpu_read_memory_temp_sm: INVALID STATE: 0x%02X", L_read_temp_state); L_read_temp_state = GPU_STATE_READ_MEM_TEMP_NEW; l_complete = TRUE; break; } // switch L_read_temp_state if(L_scheduled) { GPU_DBG("gpu_read_memory_temp_sm: Scheduled read temp state 0x%02X at tick %d", L_read_temp_state, GPU_TICK); } else if(!l_complete) // if not complete there must have been a failure on the schedule { INTR_TRAC_ERR("gpu_read_memory_temp_sm: failed to schedule state 0x%02X", L_read_temp_state); } } // if async_request_is_idle else { INTR_TRAC_ERR("gpu_read_memory_temp_sm: NOT idle for state 0x%02X", L_read_temp_state); } return l_complete; } // end gpu_read_memory_temp_sm() // Function Specification // // Name: gpu_sm_handle_idle_state // // Description: Called when GPU SM is idle to determine what state (if any) should // be done next // End Function Specification bool gpu_sm_handle_idle_state(bool i_read_temp_start_needed, bool i_mem_temp_needed) { bool l_new_state = FALSE; // return TRUE if there is a new state for GPU communication uint8_t l_gpu_id = 0; do { // Check for next state in order of priority // 1. Need to set a power limit on a GPU? l_gpu_id = gpu_id_need_set_power_limit(); if(l_gpu_id != 0xFF) { // Found a GPU that needs a power limit set G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_SET_PWR_LIMIT; l_new_state = TRUE; break; } // 2. check if Host needs lock if (!check_and_update_i2c_lock(GPU_I2C_ENGINE)) { // We don't own the lock anymore // can't do anything until we get ownership back G_gpu_state = GPU_STATE_NO_LOCK; l_new_state = FALSE; break; } // 3. Time to start new temperature reads? if(i_read_temp_start_needed) { // Start reading core temp from first present and functional GPU l_gpu_id = get_first_gpu(); if(l_gpu_id != 0xFF) { // Read core temp for this GPU G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_READ_TEMP; l_new_state = TRUE; break; } else // no functional GPUs { // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); G_gpu_state = GPU_STATE_NO_LOCK; G_gpu_monitoring_allowed = FALSE; l_new_state = FALSE; // No new state for GPU communication break; } } // 4. Need to check if driver is loaded? l_gpu_id = gpu_id_need_driver_check(); if(l_gpu_id != 0xFF) { // Found a GPU that needs driver checked G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_CHECK_DRIVER_LOADED; l_new_state = TRUE; break; } // 5. Need to read power limits? l_gpu_id = gpu_id_need_power_limits(); if(l_gpu_id != 0xFF) { // Found a GPU that needs power limits read G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_READ_PWR_LIMIT; l_new_state = TRUE; break; } // 6. Need to read memory temps? if(i_mem_temp_needed) { // first check if there is a GPU that needs memory temp capability checked l_gpu_id = gpu_id_need_memory_temp_capability_check(); if(l_gpu_id != 0xFF) { // Determine memory temp capability for this GPU G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_CHECK_MEM_TEMP_CAPABLE; l_new_state = TRUE; break; } else { // memory temp capability checking is done start reading memory temp from capable GPUs l_gpu_id = get_first_mem_temp_capable_gpu(); if(l_gpu_id != 0xFF) { // Read memory temp for this GPU G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_READ_MEMORY_TEMP; l_new_state = TRUE; break; } } } // Else nothing stay idle }while(0); return l_new_state; } // Function Specification // // Name: task_gpu_sm // // Description: GPU State Machine - Called from tick table to manage GPUs // // Task Flags: RTL_FLAG_ACTIVE // // End Function Specification void task_gpu_sm(struct task *i_self) { bool l_start_next_state = FALSE; bool l_next_state = FALSE; uint8_t l_gpu_id = 0; static bool L_occ_owns_lock = FALSE; static bool L_gpu_first_run = TRUE; static uint16_t L_numCallsForTempRead = 0; // # of calls since last temp read was started static bool L_read_temp_start_needed = FALSE; // set to true when it is time to start reading GPU temps static bool L_mem_temp_needed = FALSE; // set to true after rading GPU core temp to read GPU memory temp // GPU monitoring is enabled if GPUs are present and will be disabled if no GPUs // are functional or GPU I2C interface is broken if(G_gpu_monitoring_allowed) { // Read and update reset status for all GPUs update_gpu_reset_status(); // Initialize the IPC commands if this is our first run if(L_gpu_first_run) { gpu_ipc_init(); L_gpu_first_run = FALSE; } // Check if time to start reading temperatures // GPU temperatures (core and memory) are only used for fan control which happens every 1s // so there is no need to read the GPU temperatures any faster than every 1s if(!L_read_temp_start_needed) { L_numCallsForTempRead++; if(L_numCallsForTempRead >= GPU_TEMP_READ_1S) { L_read_temp_start_needed = TRUE; L_mem_temp_needed = FALSE; // will get set to TRUE when core temp reads finish } } // make sure OCC owns the lock in order to send commands to the GPU if( (L_occ_owns_lock == FALSE) || (G_gpu_state == GPU_STATE_NO_LOCK) ) { // Check if host gave up the I2C lock L_occ_owns_lock = check_and_update_i2c_lock(GPU_I2C_ENGINE); if (L_occ_owns_lock) { // We now own the lock start with reset and init state G_gpu_state = GPU_STATE_RESET; } else { // Don't own the lock can't do anything this time G_gpu_state = GPU_STATE_NO_LOCK; } } // Process GPE response for what was scheduled on the last call // and if that state finished schedule GPE job to start next state // This means that this state machine can be ran twice do { if(l_start_next_state) { // This is start of 2nd time processing state set next so we don't go thru here a 3rd time l_next_state = TRUE; } // make sure previous action didn't disable GPU monitoring if(!G_gpu_monitoring_allowed) { // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); L_occ_owns_lock = FALSE; G_gpu_state = GPU_STATE_NO_LOCK; } switch(G_gpu_state) { case GPU_STATE_RESET: // Call the GPU Reset SM if (gpu_reset_sm()) { // Reset complete and GPUs are ready for communication // Start first with reading core temp of first functional GPU L_numCallsForTempRead = 0; // to track start of next temp reading in 1s L_read_temp_start_needed = FALSE; // start is no longer needed L_mem_temp_needed = FALSE; // will get set to TRUE when core temp reads finish l_gpu_id = get_first_gpu(); if(l_gpu_id != 0xFF) { // Read core temp for this GPU G_current_gpu_id = l_gpu_id; G_gpu_state = GPU_STATE_READ_TEMP; l_start_next_state = TRUE; } else // no functional GPUs { // release I2C lock to the host for this engine and stop monitoring occ_i2c_lock_release(GPU_I2C_ENGINE); L_occ_owns_lock = FALSE; G_gpu_state = GPU_STATE_NO_LOCK; G_gpu_monitoring_allowed = FALSE; l_start_next_state = FALSE; } } break; case GPU_STATE_READ_TEMP: // Call the read core GPU temperature SM for the current GPU being processed if(gpu_read_temp_sm()) { // Temp read complete for this GPU, move to next GPU // or memory temps if all GPU core temps were read l_gpu_id = get_next_gpu(); if(l_gpu_id == 0xFF) { // Done reading core temps, now read GPU memory temps // set state to IDLE first to check if a higher priority // action is needed before starting to read memory temps L_mem_temp_needed = TRUE; G_gpu_state = GPU_STATE_IDLE; } else { // Stay in temperature read state and read temp for next GPU G_current_gpu_id = l_gpu_id; } l_start_next_state = TRUE; } break; case GPU_STATE_READ_MEMORY_TEMP: // Call the read GPU memory temperature SM for the current GPU being processed if(gpu_read_memory_temp_sm()) { // Temp read complete for this GPU, move to next GPU // or idle if all GPU memory temps were read l_gpu_id = get_next_mem_temp_capable_gpu(); if(l_gpu_id == 0xFF) { // Done reading memory temps G_gpu_state = GPU_STATE_IDLE; } else { // Stay in memory read state and read memory temp for next GPU G_current_gpu_id = l_gpu_id; } l_start_next_state = TRUE; } break; case GPU_STATE_CHECK_MEM_TEMP_CAPABLE: // Check if current GPU has memory temperature capability if(gpu_read_mem_temp_capability_sm()) { // Capability check complete for this GPU, go to IDLE state // to let IDLE SM decide what to do next G_gpu_state = GPU_STATE_IDLE; l_start_next_state = TRUE; } break; case GPU_STATE_CHECK_DRIVER_LOADED: // Check if driver is loaded for current GPU if(gpu_check_driver_loaded_sm()) { // Driver check complete for this GPU, // NOTE: Do not set status.checkDriverLoaded to false here, if driver is // not loaded we need to keep checking for driver to be loaded this is decided // inside gpu_check_driver_loaded_sm() // go to IDLE state to let IDLE SM decide what to do next G_gpu_state = GPU_STATE_IDLE; l_start_next_state = TRUE; } break; case GPU_STATE_READ_PWR_LIMIT: // Read power limits for current GPU if(gpu_read_pwr_limit_sm()) { // Read power limits complete for this GPU, go to IDLE state // to let IDLE SM decide what to do next G_gpu_state = GPU_STATE_IDLE; l_start_next_state = TRUE; } break; case GPU_STATE_SET_PWR_LIMIT: // Set power limit on current GPU if(gpu_set_pwr_limit_sm()) { // Set power limit complete for this GPU, go to IDLE state // to let IDLE SM decide what to do next G_gpu_state = GPU_STATE_IDLE; l_start_next_state = TRUE; } break; case GPU_STATE_NO_LOCK: // Host owns the I2C engine. Need to wait until we get the lock l_start_next_state = FALSE; break; default: // Nothing happened on last call G_gpu_state = GPU_STATE_IDLE; break; } // switch G_gpu_state // check if the previous action requires a reset if(G_gpu_i2c_reset_required) { G_gpu_i2c_reset_required = FALSE; // before starting the reset check if OPAL needs the lock L_occ_owns_lock = check_and_update_i2c_lock(GPU_I2C_ENGINE); if (L_occ_owns_lock) { // We still own the lock start the reset G_gpu_state = GPU_STATE_RESET; l_start_next_state = TRUE; } else { // We don't own the lock, the reset will happen when we get the lock back G_gpu_state = GPU_STATE_NO_LOCK; l_start_next_state = FALSE; } break; } else if(G_gpu_state == GPU_STATE_IDLE) { // time to decide what to do next l_start_next_state = gpu_sm_handle_idle_state(L_read_temp_start_needed, L_mem_temp_needed); if(l_start_next_state) { if(G_gpu_state == GPU_STATE_READ_TEMP) { // new state to read core temp reset temperature reading timer L_numCallsForTempRead = 0; L_read_temp_start_needed = FALSE; // start no longer needed L_mem_temp_needed = FALSE; // will get set to TRUE when core temp reads finish } else if(G_gpu_state == GPU_STATE_READ_MEMORY_TEMP) { // new state to start reading memory temps, reset mem temp needed L_mem_temp_needed = FALSE; } } } }while((l_start_next_state) && (!l_next_state)); } // GPU monitoring enabled } // end task_gpu_sm() <|start_filename|>src/ssx/ppc405/ppc405_irq.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/ppc405/ppc405_irq.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPC405_IRQ_H__ #define __PPC405_IRQ_H__ /// \file ppc405_irq.h /// \brief PPC405 interrupt handling for SSX /// /// Interrupt handling protocols and interrupt controller programming are /// inherently non-portable, however SSX defines APIs that may be useful among /// different machines. /// /// The interrupt controllers in PPC405 ASICS and OCCHW allow interrupts to be /// programmed as critical or non-critical, with programmable polarity and /// edge or level sensitivity. // Define pseudo-IRQ numbers for PPC405 built-in interrupts. These numbers // will appear in bits 16:23 of USPRG0 (__SsxKernelContext) when the handlers // are active, and are also passed as the second argument of the handlers when // they are invoked. #define PPC405_IRQ_PIT 0x80 #define PPC405_IRQ_FIT 0x81 #define PPC405_IRQ_WATCHDOG 0x82 #define PPC405_IRQ_DEBUG 0x83 // These are suggested values to use for the IRQ in the __SsxKernelContext if // the application defines handlers for any of the 'unhandled exceptions'. #define PPC405_EXC_MACHINE_CHECK 0x90 #define PPC405_EXC_DATA_STORAGE 0x91 #define PPC405_EXC_INSTRUCTION_STORAGE 0x92 #define PPC405_EXC_ALIGNMENT 0x93 #define PPC405_EXC_PROGRAM 0x94 #define PPC405_EXC_FPU_UNAVAILABLE 0x95 #define PPC405_EXC_APU_UNAVAILABLE 0x96 #define PPC405_EXC_DATA_TLB_MISS 0x97 #define PPC405_EXC_INSTRUCTION_TLB_MISS 0x98 // Unhandled exceptions default to a kernel panic, but the application can // override these definition. Note that the exception area only allocates 32 // bytes (8 instructions) to an unhandled exception, so any redefinition // would most likely be a branch to an application-defined handler. #ifndef PPC405_MACHINE_CHECK_HANDLER #define PPC405_MACHINE_CHECK_HANDLER SSX_PANIC(0x0200) #endif #ifndef PPC405_DATA_STORAGE_HANDLER #define PPC405_DATA_STORAGE_HANDLER SSX_PANIC(0x0300) #endif #ifndef PPC405_INSTRUCTION_STORAGE_HANDLER #define PPC405_INSTRUCTION_STORAGE_HANDLER SSX_PANIC(0x0400) #endif #ifndef PPC405_ALIGNMENT_HANDLER #define PPC405_ALIGNMENT_HANDLER SSX_PANIC(0x0600) #endif #ifndef PPC405_PROGRAM_HANDLER #define PPC405_PROGRAM_HANDLER SSX_PANIC(0x0700) #endif #ifndef PPC405_FPU_UNAVAILABLE_HANDLER #define PPC405_FPU_UNAVAILABLE_HANDLER SSX_PANIC(0x0800) #endif #ifndef PPC405_APU_UNAVAILABLE_HANDLER #define PPC405_APU_UNAVAILABLE_HANDLER SSX_PANIC(0x0f20) #endif #ifndef PPC405_DATA_TLB_MISS_HANDLER #define PPC405_DATA_TLB_MISS_HANDLER SSX_PANIC(0x1100) #endif #ifndef PPC405_INSTRUCTION_TLB_MISS_HANDLER #define PPC405_INSTRUCTION_TLB_MISS_HANDLER SSX_PANIC(0x1200) #endif //////////////////////////////////////////////////////////////////////////// // SSX API //////////////////////////////////////////////////////////////////////////// #ifndef __ASSEMBLER__ /// An IRQ handler takes 3 arguments: /// \arg \c arg - Private handler data installed by \c ssx_irq_setup() or /// \c ssx_irq_handler_set(). /// \arg \c irq - The IRQ id; to enable a generic handler to manipulate /// its own interrupt status . /// \arg \c priority - One of the values \c SSX_CRITICAL or \c /// SSX_NONCRITICAL; to enable a generic handler to choose /// a behavior appropriate for the interrupt priority. typedef void (*SsxIrqHandler)(void* arg, SsxIrqId irq, int priority); /// Declare a subroutine as an IRQ handler #define SSX_IRQ_HANDLER(f) void f(void *arg, SsxIrqId irq, int priority) int ssx_irq_setup(SsxIrqId irq, int polarity, int trigger); int ssx_irq_handler_set(SsxIrqId irq, SsxIrqHandler handler, void* arg, int priority); void ssx_irq_enable(SsxIrqId irq); void ssx_irq_disable(SsxIrqId irq); void ssx_irq_statusclear(SsxIrqId irq); SSX_IRQ_HANDLER(__ppc405_default_irq_handler); SSX_IRQ_HANDLER(__ppc405_phantom_irq_handler); int ppc405_fit_setup(int tcr_fp, SsxIrqHandler handler, void* arg); /// The address of the optional FIT interrupt handler UNLESS__PPC405_IRQ_CORE_C__(extern) volatile SsxIrqHandler __ppc405_fit_routine; /// The private data of the optional FIT interrupt handler UNLESS__PPC405_IRQ_CORE_C__(extern) volatile void* __ppc405_fit_arg; int ppc405_watchdog_setup(int tcr_wp, int tcr_wrc, SsxIrqHandler handler, void* arg); /// The address of the optional Watchdog interrupt handler UNLESS__PPC405_IRQ_CORE_C__(extern) volatile SsxIrqHandler __ppc405_watchdog_routine; /// The private data of the optional Watchdog interrupt handler UNLESS__PPC405_IRQ_CORE_C__(extern) volatile void* __ppc405_watchdog_arg; int ppc405_debug_setup(SsxIrqHandler handler, void* arg); /// The address of the optional Debug interrupt handler UNLESS__PPC405_IRQ_CORE_C__(extern) volatile SsxIrqHandler __ppc405_debug_routine; /// The private data of the optional Watchdog interrupt handler UNLESS__PPC405_IRQ_CORE_C__(extern) volatile void* __ppc405_debug_arg; // Note: Why SSX_IRQ_FAST2FULL (below) is implemented so strangely. // // I am adamant that I want to have a a macro in the 'C' environment to create // these bridge functions. However the limitations of the C preprocessor and // the intelligence of the GCC 'asm' facility consipre against a // straightforward solution. The only way that I was able to find to get // naked assembly code into the output stream is to use 'asm' with simple // strings - I couldn't make it work with any kind of argument, as 'asm' would // reinterpret the arguments and resulting assembler code in various ways. // // There is another alternative that I tried wherby I created a subroutine // call and then filled in the subroutine body with 'asm' code. However, the // subroutine wrapper that GCC creates only works for PowerPC fast-mode // handlers if GCC is invoked with optimization, which ensures that the // wrapper doesn't touch the stack pointer or other registers. True, we'll // always use optimization, but I did not want to have to make this // requirement for using this macro. /// This macro creates a 'bridge' handler that converts the initial fast-mode /// IRQ dispatch into a call of a full-mode IRQ handler. The full-mode /// handler is defined by the user (presumably as a \c C subroutine) and has /// the same prototype (type SsxIrqHandler) as the fast handler. /// /// \param fast_handler This will be the global function name of the fast /// IRQ handler created by this macro. This is the symbol /// that should be passed in as the \a handler argument /// of \c ssx_irq_setup() and \c ssx_irq_handler_set(). /// /// \param full_handler This is the name of the user-defined full-mode /// handler which is invoked through this bridge. /// /// \e BUG \e ALERT : Beware of passing the \c full_handler to IRQ setup /// APIs. This won't be caught by the compiler (because the \c full_handler /// has the correct prototype) and will lead to nasty bugs. Always pass in /// the \c fast_handler symbol to IRQ setup APIS. /// /// The code stream injected into the GCC assembler output in response to /// /// SSX_IRQ_FAST2FULL(fast_handler, full_handler) /// /// is (comments added for clarification) : /// /// \code /// .text /// .global fast_handler /// .align 5 # Hard-coded PPC405 cache-line alignment /// fast_handler = . # Can't macro expand LABEL: - this is equivalent /// bl __ssx_irq_fast2full # The fast-mode to full-mode conversion sequence /// bl full_handler /// b __ssx_irq_full_mode_exit /// \endcode /// /// The macro also declares the prototype of the fast handler: /// /// \code /// SSX_IRQ_HANDLER(fast_handler); /// \endcode /// #define SSX_IRQ_FAST2FULL(fast_handler, full_handler) \ SSX_IRQ_HANDLER(fast_handler); \ __SSX_IRQ_FAST2FULL(.global fast_handler, fast_handler = ., bl full_handler) #define __SSX_IRQ_FAST2FULL(global, label, call) \ asm(".text"); \ asm(#global); \ asm(".align 5"); \ asm(#label); \ asm("bl __ssx_irq_fast2full"); \ asm(#call); \ asm("b __ssx_irq_full_mode_exit"); #endif /* __ASSEMBLER__ */ // It's hard to be portable and get all of the definitions and headers in the // correct order. We need to bring in the system IRQ header here. #ifdef HWMACRO_OCC #include "occhw_irq.h" #endif /// \page ppc405_irq_macros_page PPC405 SSX IRQ Assembler Macros /// /// /// \section fast2full_asm Fast-Mode to Full-Mode Handler Conversion /// /// This macro produces the calling sequence required to convert a /// fast-mode interrupt handler to a full-mode interrupt handler. The /// full-mode handler is implemented by another subroutine. The /// requirements for invoking this macro are: /// /// \li The stack pointer and stack must be exactly as they were when the /// fast-mode handler was entered. /// /// \li No changes have been made to the MSR - the interrupt level must /// remain disabled. /// /// \li The handler owns the fast context and has not modified the other /// register context. The conversion process will not modify any /// register in the fast context (other than the LR used for /// subroutine linkage). /// /// The final condition above means that the \a full_handler will /// begin with the fast-mode context exactly as it was (save for LR) /// at conversion, including the contents of GPR3-7 (the first 5 /// PowerPC ABI paramater passing registers) and the entire CR. /// /// Forms: /// /// \c _ssx_irq_fast2full \a full_handler /// \cond #ifdef __ASSEMBLER__ // *INDENT-OFF* .macro _ssx_irq_fast2full full_handler bl __ssx_irq_fast2full bl \full_handler b __ssx_irq_full_mode_exit .endm // *INDENT-ON* #endif /* __ASSEMBLER__ */ /// \endcond #ifndef __ASSEMBLER__ /// This structure holds the interrupt handler routine addresses and private /// data. Assembler code assumes the given structure layout, so any changes /// to this structure will need to be reflected down into the interrupt /// dispatch assembler code. typedef struct { SsxIrqHandler handler; void* arg; } Ppc405IrqHandler; /// Interrupt handlers for real (implemented interrupts) UNLESS__PPC405_IRQ_CORE_C__(extern) Ppc405IrqHandler __ppc405_irq_handlers[EXTERNAL_IRQS]; /// The 'phantom interrupt' handler /// /// A 'phantom' interrupt occurs when the interrupt handling code in the /// kernel is entered, but no interrupt is found pending in the controller. /// This is considered a serious bug, as it indictates a short window /// condition where a level-sensitive interrupt has been asserted and then /// quickly deasserted before it can be handled. UNLESS__PPC405_IRQ_CORE_C__(extern) Ppc405IrqHandler __ppc405_phantom_irq; #endif /* __ASSEMBLER__ */ #endif /* __PPC405_IRQ_H__ */ <|start_filename|>src/lib/ppc405lib/errno.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/errno.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __ERRNO_H__ #define __ERRNO_H__ /// \file errno.h /// \brief Replacement for <errno.h> /// /// SSX does not support a per-thread or global 'errno'. The standard Unix /// errno values returned by library functions are defined here. The prefix /// code is the 'telephone code' for "errn". #define EINVAL 0x00377601 #define EBADF 0x00377602 #define EAGAIN 0x00377603 #define ENXIO 0x00377604 #define ENOMEM 0x00377605 #endif /* __ERRNO_H__ */ <|start_filename|>src/ppe/pk/ppe42/ppe42.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ppe/pk/ppe42/ppe42.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PPE42_H__ #define __PPE42_H__ /// \file ppe42.h /// \brief PPE42 port header for PK // Macros to define where declared code is actually compiled #ifdef __PPE42_CORE_C__ #define IF__PPE42_CORE_C__(x) x #define UNLESS__PPE42_CORE_C__(x) #else #define IF__PPE42_CORE_C__(x) #define UNLESS__PPE42_CORE_C__(x) x #endif #ifdef __PPE42_IRQ_CORE_C__ #define IF__PPE42_IRQ_CORE_C__(x) x #define UNLESS__PPE42_IRQ_CORE_C__(x) #else #define IF__PPE42_IRQ_CORE_C__(x) #define UNLESS__PPE42_IRQ_CORE_C__(x) x #endif #ifdef HWMACRO_GPE #include "gpe.h" #elif defined(HWMACRO_STD) #include "std.h" #elif defined(HWMACRO_PPE) #include "ppe.h" #else #error "Macro Type not specified. Are you building from the correct directory?" #endif #include "ppe42_asm.h" #include "ppe42_gcc.h" #include "ppe42_spr.h" #include "ppe42_msr.h" ///start /// The synchronization macros defined here all create a compiler /// memory barrier that will cause GCC to flush/invalidate all memory data /// held in registers before the macro. This is consistent with other systems, /// e.g., the PowerPC Linux kernel, and is the safest way to define these /// macros. // Condition register fields #define CR_LT(n) (0x80000000u >> (4 * (n))) #define CR_GT(n) (0x40000000u >> (4 * (n))) #define CR_EQ(n) (0x20000000u >> (4 * (n))) #define CR_SO(n) (0x10000000u >> (4 * (n))) #ifndef __ASSEMBLER__ #include "stdint.h" /// ssize_t is defined explictly rather than bringing in all of <unistd.h> #ifndef __ssize_t_defined #define __ssize_t_defined typedef int ssize_t; #endif /// A memory barrier #define barrier() asm volatile ("" : : : "memory") /// Ensure In-order Execution of Input/Output #define eieio() asm volatile ("sync" : : : "memory") /// Memory barrier #define sync() asm volatile ("sync" : : : "memory") /// Instruction barrier #define isync() asm volatile ("sync" : : : "memory") /// CouNT Leading Zeros Word #define cntlzw(x) \ ({uint32_t __x = (x); \ uint32_t __lzw; \ asm volatile ("cntlzw %0, %1" : "=r" (__lzw) : "r" (__x)); \ __lzw;}) /// CouNT Leading Zeros : uint32_t static inline int cntlz32(uint32_t x) { return cntlzw(x); } /// CouNT Leading Zeros : uint64_t static inline int cntlz64(uint64_t x) { if (x > 0xffffffff) { return cntlz32(x >> 32); } else { return 32 + cntlz32(x); } } /// 32-bit population count static inline int popcount32(uint32_t x) { return __builtin_popcount(x); } /// 64-bit population count static inline int popcount64(uint64_t x) { return __builtin_popcountll(x); } // NB: Normally we wouldn't like to force coercion inside a macro because it // can mask programming errors, but for the MMIO macros the addresses are // typically manifest constants or 32-bit unsigned integer expressions so we // embed the coercion to avoid warnings. /// 8-bit MMIO Write #define out8(addr, data) \ do {*(volatile uint8_t *)(addr) = (data);} while(0) /// 8-bit MMIO Read #define in8(addr) \ ({uint8_t __data = *(volatile uint8_t *)(addr); __data;}) /// 16-bit MMIO Write #define out16(addr, data) \ do {*(volatile uint16_t *)(addr) = (data);} while(0) /// 16-bit MMIO Read #define in16(addr) \ ({uint16_t __data = *(volatile uint16_t *)(addr); __data;}) /// 32-bit MMIO Write #define out32(addr, data) \ do {*(volatile uint32_t *)(addr) = (data);} while(0) /// 32-bit MMIO Read #define in32(addr) \ ({uint32_t __data = *(volatile uint32_t *)(addr); __data;}) /// 64-bit MMIO Write #define out64(addr, data) \ {\ uint64_t __d = (data); \ uint32_t* __a = (uint32_t*)(addr); \ asm volatile \ (\ "stvd %1, %0 \n" \ : "=o"(*__a) \ : "r"(__d) \ ); \ } #define in64(addr) \ ({\ uint64_t __d; \ uint32_t* __a = (uint32_t*)(addr); \ asm volatile \ (\ "lvd %0, %1 \n" \ :"=r"(__d) \ :"o"(*__a) \ ); \ __d; \ }) #endif /* __ASSEMBLER__ */ #include "ppe42_irq.h" #ifndef __ASSEMBLER__ /// Store revision information as a (global) string constant #define REVISION_STRING(symbol, rev) const char* symbol = rev; #else // __ASSEMBLER__ // *INDENT-OFF* /// Store revision information as a global string constant .macro .revision_string, symbol:req, rev:req .pushsection .rodata .balign 4 .global \symbol \symbol\(): .asciz "\rev" .balign 4 .popsection .endm // *INDENT-ON* #endif // __ASSEMBLER__ #include "ppe42_context.h" #include "pk_panic_codes.h" // PPE42 stack characteristics for PK. The pre-pattern pattern is selected // to be easily recognizable yet be an illegal instruction. #define PK_STACK_DIRECTION -1 #define PK_STACK_PRE_DECREMENT 1 #define PK_STACK_ALIGNMENT 8 #define PK_STACK_TYPE unsigned int #define PK_STACK_PATTERN 0x03abcdef // Kernel data structure offsets for assembler code #define PK_THREAD_OFFSET_SAVED_STACK_POINTER 0 #define PK_THREAD_OFFSET_STACK_LIMIT 4 #define PK_THREAD_OFFSET_STACK_BASE 8 // Application-overrideable definitions /// The default thread machine context has /// MSR[CE], MSR[EE] MSR[ME] MSR[IS0] MSR[IS1] MSR[IS2] set. /// MSR[IPE] is set if USE_PPE_IMPRECISE_MODE is defined. /// and all other MSR bits cleared. /// /// MSR[IS0] = Data Cache Populate /// MSR[IS1] = Store Gathering /// MSR[IS2] = Instruction Cache Prefetch /// MSR[IS3] = Reserved /// /// The default definition allows external and machine check exceptions. This /// definition can be overriden by the application. #ifndef PK_THREAD_MACHINE_CONTEXT_DEFAULT #if defined(USE_PPE_IMPRECISE_MODE) #if defined(MASK_MSR_SEM6) #define PK_THREAD_MACHINE_CONTEXT_DEFAULT \ (MSR_UIE | MSR_EE | MSR_ME | MSR_IS0 | MSR_IS1 | MSR_IS2 | MSR_IPE | MSR_SEM6) #else #define PK_THREAD_MACHINE_CONTEXT_DEFAULT \ (MSR_UIE | MSR_EE | MSR_ME | MSR_IS0 | MSR_IS1 | MSR_IS2 | MSR_IPE) #endif /*MASK_MSR_SEM6*/ #else #if defined(MASK_MSR_SEM6) #define PK_THREAD_MACHINE_CONTEXT_DEFAULT \ (MSR_UIE | MSR_EE | MSR_ME | MSR_IS0 | MSR_IS1 | MSR_IS2 | MSR_SEM6) #else #define PK_THREAD_MACHINE_CONTEXT_DEFAULT \ (MSR_UIE | MSR_EE | MSR_ME | MSR_IS0 | MSR_IS1 | MSR_IS2) #endif /*MASK_MSR_SEM6*/ #endif /*USE_PPE_IMPRECISE_MODE*/ #endif /*PK_THREAD_MACHINE_CONTEXT_DEFAULT*/ #ifndef __ASSEMBLER__ /// The PK kernel default panic sequence for C code is to issue a trap /// instruction with DBCR[TRAP] set, which causes XSR[TRAP] <- 1 /// and causes the PPE to halt. /// /// /// The Simics environment does not model Debug events correctly. It executes /// the TRAP as an illegal instruction and branches to the Program Interrupt /// handler, destroying the contents of SRR0 and SRR1. Therefore we always /// insert a special Simics magic breakpoint (which is an effective NOP) /// before the hardware trap. The special-form magic instruction is /// recognized by our Simics support scripts which decode the kernel state and /// try to help the user interpret what happened based on the TRAP code. /// NOTE! SIMICS does not seem to recognize the "magic breakpoint" on PPE! #ifndef PK_PANIC #if SIMICS_ENVIRONMENT #define PK_PANIC(code) \ do { \ asm volatile ("stw %r3, __pk_panic_save_r3@sda21(0)"); \ asm volatile ("lwz %r3, __pk_panic_dbcr@sda21(0)"); \ asm volatile ("mtdbcr %r3"); \ asm volatile (".long %0" : : "i" (code)); \ } while(0) #else #define PK_PANIC(code) \ do { \ asm volatile ("tw 31, %0, %1" : : "i" (code/256) , "i" (code%256)); \ } while (0) #endif #endif // SIMICS_ENVIRONMENT // These variables are used by the PK_PANIC() definition above to save and // restore state. __pk_panic_dbcr is the value loaded into DBCR to force // traps to halt the PPE and freeze the timers. #if SIMICS_ENVIRONMENT #ifdef __PPE42_CORE_C__ uint32_t __pk_panic_save_r3; uint32_t __pk_panic_dbcr = DBCR_RST_HALT; #define __PK_PANIC_DEFS__ #else #define __PK_PANIC_DEFS__ \ extern uint32_t __pk_panic_save_r3; \ extern uint32_t __pk_panic_dbcr; #endif //SIMICS_ENVIRONMENT #endif // PK_PANIC /// This is the Simics 'magic breakpoint' instruction. /// /// Note that this form does not include a memory barrier, as doing so might /// change the semantics of the program. There is an alternative form /// SIMICS_MAGIC_BREAKPOINT_BARRIER that does include a barrier. //#define SIMICS_MAGIC_BREAKPOINT asm volatile ("rlwimi 0,0,0,0,0") /// This is the Simics 'magic breakpoint' instruction including a memory /// barrier. /// /// Note that the memory barrier guarantees that all variables held in /// registers are flushed to memory before the breakpoint, however this might /// change the semantics of the program. There is an alternative form of /// SIMICS_MAGIC_BREAKPOINT that does not include a barrier. If the idea is /// to use the breakpoint for tracing code execution in Simics, the barrier /// form may be preferred so that variable values will be visible in memory. /*#define SIMICS_MAGIC_BREAKPOINT_BARRIER \ asm volatile ("rlwimi 0,0,0,0,0" : : : "memory") */ #else // __ASSEMBLER__ // *INDENT-OFF* /// This is the Simics 'magic breakpoint' instruction. An assembler macro /// form is also provided for use within macros. //#define SIMICS_MAGIC_BREAKPOINT rlwimi 0,0,0,0,0 // .macro _simics_magic_breakpoint // rlwimi 0,0,0,0,0 // .endm /// The PK kernel panic default panic sequence for assembler code /// /// By default a kernel panic from assembler forces external debug mode then /// generates a \c trap instruction followed by the error code. The \a code /// argument must be a compile-time integer immediate. This definition can be /// overriden by the application. /// /// See the comments for the non-ASSEMBLER version for further details. Note /// that the code space reserved for exception handlers is only 8 /// instructions, so in the assembler context we don't save DBCR0 as doing so /// would require 10. #ifndef PK_PANIC #define PK_PANIC(code) _pk_panic code #if SIMICS_ENVIRONMENT .macro _pk_panic, code stw %r3, __pk_panic_save_r3@sda21(0) lwz %r3, __pk_panic_dbcr@sda21(0) mtdbcr %r3, .long (\code) .endm #else .macro _pk_panic, code tw 31,(\code)/256, (\code)%256 .endm #endif // SIMICS_ENVIRONMENT #endif // PK_PANIC // *INDENT-ON* #endif // __ASSEMBLER__ // Application-overridible definitions for the PK boot loader /// In order to enable the default kernel panic (a trap) to halt the machine, /// the Debug Control Register 0 (DBCR0) is initialized in externel debug /// mode, with the Trap Debug Event enabled so that the trap will not cause a /// program exception, and the FT bit set so that the timers will freeze. /// This definition can be overridden by the application. /// /// NB: It is expected that a reliable production system will redefine all of /// the 'panic' macros and the default DBCR0 setup. #ifndef PPE42_DBCR_INITIAL #define PPE42_DBCR_INITIAL DBCR_TRAP #endif /// This is the value of the MSR used during initialization. Once PK threads /// are started (with \c pk_start_threads()), all machine contexts derive /// from the default thread context \c /// PK_THREAD_MACHINE_CONTEXT_DEFAULT. This definition can be overriden by /// the application. /// #ifndef PPE42_MSR_INITIAL #if defined(USE_PPE_IMPRECISE_MODE) #define PPE42_MSR_INITIAL (MSR_ME | MSR_IS0 | MSR_IS1 | MSR_IS2 | MSR_IPE) #else #define PPE42_MSR_INITIAL (MSR_ME | MSR_IS0 | MSR_IS1 | MSR_IS2) #endif #endif /// The \a argc argument passed to \c main(). This definition can be overriden /// by the application. #ifndef PPE42_ARGC_INITIAL #define PPE42_ARGC_INITIAL 0 #endif /// The \a argv argument passed to \c main(). This definition can be overriden /// by the application. #ifndef PPE42_ARGV_INITIAL #define PPE42_ARGV_INITIAL 0 #endif /// Optionally trap the reset for the debugger, which means that the PPE42 /// will simply spin at the symbol \c __reset_trap after a chip reset. Set R0 /// to a non-zero value in the debugger to continue execution. This definition /// can be overriden by the application. #ifndef PPE42_RESET_TRAP #define PPE42_RESET_TRAP 0 #endif #ifndef __ASSEMBLER__ /// The PPE42 PK machine context is simply the MSR, a 32-bit integer. typedef uint32_t PkMachineContext; /// Disable interrupts and return the current /// context. /// /// \param context A pointer to an PkMachineContext, this is the context that /// existed before interrupts were disabled. Typically this /// context is restored at the end of a critical section. /// /// Return values other then PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_ARGUMENT_INTERRUPT An illegal priority was specified. UNLESS__PPE42_CORE_C__(extern) inline int pk_interrupt_disable(PkMachineContext* context) { *context = mfmsr(); wrteei(0); return PK_OK; } /// Set the machine context. /// /// \param context A pointer to an PkMachineContext /// /// Return values other then PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_ARGUMENT_CONTEXT_SET A null pointer was provided as /// the \a context argument or an illegal machine context was specified. UNLESS__PPE42_CORE_C__(extern) inline int pk_machine_context_set(PkMachineContext* context) { if (PK_ERROR_CHECK_API) { PK_ERROR_IF(context == 0, PK_INVALID_ARGUMENT_CONTEXT_SET); } mtmsr(*context); return PK_OK; } /// Get the machine context. /// /// \param context A pointer to an PkMachineContext. /// /// Return values other then PK_OK (0) are errors; see \ref pk_errors /// /// \retval 0 Successful completion /// /// \retval -PK_INVALID_ARGUMENT_CONTEXT_GET A null pointer was provided as /// the \a context argument. UNLESS__PPE42_CORE_C__(extern) inline int pk_machine_context_get(PkMachineContext* context) { if (PK_ERROR_CHECK_API) { PK_ERROR_IF(context == 0, PK_INVALID_ARGUMENT_CONTEXT_GET); } *context = mfmsr(); return PK_OK; } extern void __ctx_switch(); /// The PK context switch for the PPE kernel // There is no protected mode in PPE42 so just call kernel code #define __pk_switch() __ctx_switch() /// In the PowerPC EABI all initial stack frames require 8 bytes - the 4 bytes /// at the SP are zeroed to indicate the end of the stack, and the 4 bytes /// behind the SP are for the initial subroutine's LR. static inline void __pk_stack_create_initial_frame(PkAddress* stack, size_t* size) { *stack -= 8; * size -= 8; * ((PK_STACK_TYPE*)(*stack)) = 0; } /// The PK Kernel Context for PPE42 /// /// The PK portable kernel does not define how the kernel keeps track of /// whether PK is running, interrupt levels, and other debug /// information. Instead it defines an API that the port must provide to the /// portable kernel. /// /// In the PPE42 port, the kernel context is maintained in SPRG0. This /// 32-bit value is treated as 6 distinct fields as indicated in the structure /// definition. typedef union { uint32_t value; struct { /// A flag indicating that PK is in thread mode after a call of /// pk_start_threads(). unsigned thread_mode : 1; /// If this field is non-zero then PK is processing an interrupt /// and the \c irq field will contain the PkIrqId of the interrupt /// that kicked off interrupt processing. unsigned processing_interrupt : 1; /// The priority of the currently running thread. In an interrupt /// context, this is the priority of the thread that was interrupted. unsigned thread_priority : 6; /// This bit tracks whether the current context can be discarded or /// if the context must be saved. If the processor takes an interrupt /// and this bit is set, then the current context will be discarded. /// This bit is set at the end of handling an interrupt and prior /// to entering the wait enabled state. unsigned discard_ctx : 1; /// The PkIrqId of the currently running (or last run) handler. If /// \c processing_interrupt is set, then this is the /// PkIrqId of the IRQ that is currently executing. unsigned irq : 7; /// Each PPE application will define (or not) the interpretation of /// this field. Since SPRG0 is saved and restored during during thread /// context switches, this field can be used to record the progress of /// individual threads. The kernel and/or application will provide /// APIs or macros to read and write this field. unsigned app_specific : 16; } fields; } __PkKernelContext; // These APIs are provided for applications to get and set the app_specific // field of the kernel context which is held in sprg0. static inline uint16_t ppe42_app_ctx_get(void) { __PkKernelContext __ctx; __ctx.value = mfspr(SPRN_SPRG0); return __ctx.fields.app_specific; } static inline void ppe42_app_ctx_set(uint16_t app_ctx) { PkMachineContext mctx; __PkKernelContext __ctx; mctx = mfmsr(); wrteei(0); __ctx.value = mfspr(SPRN_SPRG0); __ctx.fields.app_specific = app_ctx; mtspr(SPRN_SPRG0, __ctx.value); mtmsr(mctx); } // These APIs are provided to the PK portable kernel by the port. /// PK threads have been started by a call of pk_start_threads(). #define __pk_kernel_mode_thread() \ ({ \ __PkKernelContext __ctx; \ __ctx.value = mfspr(SPRN_SPRG0); \ __ctx.fields.thread_mode;}) /// PK is executing in a thread context (not an interrupt handler). #define __pk_kernel_context_thread() \ ({ \ __PkKernelContext __ctx; \ __ctx.value = mfspr(SPRN_SPRG0); \ __ctx.fields.thread_mode && !__ctx.fields.processing_interrupt;}) /// PK is executing an interrupt handler of any priority. #define __pk_kernel_context_any_interrupt() \ ({ \ __PkKernelContext __ctx; \ __ctx.value = mfspr(SPRN_SPRG0); \ __ctx.fields.processing_interrupt;}) // PK requires the port to define the type PkThreadQueue, which is a // priority queue (where 0 is the highest priority). This queue must be able // to handle PK_THREADS + 1 priorities (the last for the idle thread) The // port must also define methods for clearing, insertion, deletion and min // (with assumed legal priorities). The min operation returns PK_THREADS if // the queue is empty (or a queue could be initialized with that entry always // present - PK code never tries to delete the idle thread from a thread // queue). // // These queues are used both for the run queue and the pending queue // associated with every semaphore. // // On PPE42 with 32 threads (implied), this is a job for a uint32_t and // cntlzw(). static inline void __pk_thread_queue_clear(volatile PkThreadQueue* queue) { *queue = 0; } static inline void __pk_thread_queue_insert(volatile PkThreadQueue* queue, PkThreadPriority priority) { *queue |= (0x80000000u >> priority); } static inline void __pk_thread_queue_delete(volatile PkThreadQueue* queue, PkThreadPriority priority) { *queue &= ~(0x80000000u >> priority); } static inline PkThreadPriority __pk_thread_queue_min(volatile PkThreadQueue* queue) { return cntlzw(*queue); } static inline int __pk_thread_queue_member(volatile PkThreadQueue* queue, PkThreadPriority priority) { return ((*queue >> (31 - priority)) & 1); } static inline void __pk_thread_queue_union(volatile PkThreadQueue* queue0, volatile PkThreadQueue* queue1) { *queue0 |= *queue1; } static inline int __pk_thread_queue_count(volatile PkThreadQueue* queue) { return __builtin_popcount(*queue); } /// This macro is used to call __pk_start_threads() using the kernel stack, /// in a critical section. #define __pk_call_pk_start_threads() \ do { \ PkMachineContext ctx; \ pk_critical_section_enter(&ctx); \ asm volatile ("mr 1, %0; mtlr %1; blrl" : : \ "r" (__pk_kernel_stack), \ "r" (__pk_start_threads)); \ PK_PANIC(PK_START_THREADS_RETURNED); \ } while (0) #endif /* __ASSEMBLER__ */ /// The __PkKernelContext 'thread_mode' bit as a flag #define PPE42_THREAD_MODE 0x8000 #define PPE42_PROC_IRQ 0x4000 #define PPE42_DISCARD_CTX 0x0080 #define PPE42_THREAD_MODE_BIT 0 #define PPE42_PROC_IRQ_BIT 1 #define PPE42_DISCARD_CTX_BIT 8 #ifndef __ASSEMBLER__ /// Code breakpoints for PPE42 /// /// This macro inserts a special PPE42-only breakpoint into the object code /// at the place the macro invocation appears. This facility is designed for /// VBU/VPO procedure debugging. This type of breakpoint may not be required /// on real hardware as we will then have the full power of RISCWatch, gdb, /// etc. Once inserted into the code, code breakpoints can be enabled or /// disabled by manipulating the global variable _code_breakpoint_enable, /// which defaults to 1. /// /// The code breakpoint is implemented as a setup routine and a teardown /// routine, executed in an critical section. The actual break /// will occur at the address of the call of the teardown routine, in the /// context of the calling code. The setup routine saves the state of DBCR0/1 /// and IAC4, then programs the DBCR for an external debug mode, IAC4 /// breakpoint. The IAC4 breakpoint is set for the address of the call of the /// teardown routine. The teardown routine simply restores the state of the /// debug registers that existed before the code breakpoint. /// /// Once hit, restarting from the break requires clearing IAC4 and restarting /// instructions: /// /// \code /// /// putspr pu.occ iac4 0 /// cipinstruct pu.occ start /// /// \endcode /// /// The above restart processes is also encapsulated as the p8_tclEcmd /// procedure 'unbreakOcc'. /// /// In code built for the Simics environment (i.e., with the preprocessor /// macro SIMICS_ENVIRONMENT=1) this macro simply expands into /// SIMICS_MAGIC_BREAKPOINT, and simulation can be continued from the break as /// normal. This Simics magic breakpoint is also under the control of /// _code_breakpoint_enable. In code not built with SIMICS_ENVIROMENT=1, note /// that the CODE_BREAKPOINT is ignored by the Simics PPE42 model as it does /// not model debug events. //void //_code_breakpoint_prologue(void); //void //_code_breakpoint_epilogue(void); //extern uint32_t _code_breakpoint_enable; #endif // __ASSEMBLER__ #endif /* __PPE42_H__ */ <|start_filename|>src/lib/ppc405lib/strtox.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/ppc405lib/strtox.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file strtox.c /// \brief Implementation of strtol(), strtoul(), strtoll() and strtoull() /// /// <b> Standard String Conversion Routines </b> /// /// This file contains implementaions of strtol(), strtoul(), strtoll() and /// strtoull(). These APIs are all called as /// /// \code /// strtoX(const char* str, char** endptr, int base) /// \endcode /// /// where X is /// /// - l : Convert to a long integer /// - ul : Convert to an unsigned long integer /// - ll : Convert to a long long integer /// - ull : Convert to an unsigned long long integer /// /// \param str The string to convert /// /// \param endptr If non-null, will be set to a pointer to the portion of the /// string following the convertable portion. If no conversion is performed /// then the original \a str is returned here. /// /// \param base Either 0 to indicate that the base should be derived from /// radix markers in the string, or a number in the range 2 to 36 inclusive. /// /// The APIs convert the initial portion of the string pointed to by \a str to /// an integer, which is either a long integer (strtol), an unsigned long /// (strtoul()), a long long (strtoll), or an unsigned long long /// (strtoull). First, the APIs decompose the input string into three parts: /// /// - An initial, possibly empty, sequence of white-space characters (as /// specified by isspace()) /// /// - A subject sequence interpreted as an integer represented in some radix /// determined by the value of \a base /// /// - A final string of one or more unrecognized characters, including the /// terminating null byte of the input string. /// /// The APIs then attempt to convert the subject sequence to an integer of the /// required type and returns the result. /// /// If the value of \a base is 0, the expected form of the subject sequence is /// that of a decimal constant, octal constant, or hexadecimal constant, any /// of which may be preceded by a '+' or '-' sign. A decimal constant begins /// with a non-zero digit, and consists of a sequence of decimal digits. An /// octal constant consists of the prefix '0' optionally followed by a /// sequence of the digits '0' to '7' only. A hexadecimal constant consists of /// the prefix 0x or 0X followed by a sequence of the decimal digits and /// letters 'a' (or 'A' ) to 'f' (or 'F' ) with values 10 to 15 respectively. /// /// If the value of \a base is between 2 and 36, the expected form of the /// subject sequence is a sequence of letters and digits representing an /// integer with the radix specified by base, optionally preceded by a '+' or /// '-' sign. The letters from 'a' (or 'A' ) to 'z' (or 'Z' ) inclusive are /// ascribed the values 10 to 35; only letters whose ascribed values are less /// than that of base are permitted. If the value of base is 16, the /// characters 0x or 0X may optionally precede the sequence of letters and /// digits, following the sign if present. /// /// The subject sequence is defined as the longest initial subsequence of the /// input string, starting with the first non-white-space character that is of /// the expected form. The subject sequence contains no characters if the /// input string is empty or consists entirely of white-space characters, or if /// the first non-white-space character is other than a sign or a permissible /// letter or digit. /// /// If the subject sequence has the expected form and the value of base is 0, /// the sequence of characters starting with the first digit will be /// interpreted as an integer constant. If the subject sequence has the /// expected form and the value of base is between 2 and 36, it will be used /// as the base for conversion, ascribing to each letter its value as given /// above. If the subject sequence begins with a minus sign, the value /// resulting from the conversion will be negated. A pointer to the final /// string will be stored in the object pointed to by \a endptr, provided that /// \a endptr is not a null pointer. /// /// If the subject sequence is empty or does not have the expected form, no /// conversion is performed; the value of \a str is stored in the object /// pointed to by \a endptr, provided that \a endptr is not a null pointer. /// /// Note that the unsigned APIs silently convert signed representations into /// the equivalent unsigned number. /// /// Since 0, (L)LONG_MIN and (U)(L)LONG_MAX are returned on error and are /// also valid returns on success, there is no way for an SSX application to /// determine whether the conversion succeeded or failed (since SSX does not /// support \a errno). For this reason it is recommended that SSX-only /// applications use the underlying APIs _strtol(), _strtoul(), _strtoll() and /// _strtoull(), or even better the extended APIs strtoi32(), strtou32(), /// strtoi64() or strtou64() discussed further below. /// /// Upon successful completion, strtoX() returns the converted /// value, if any. If no conversion could be performed or there was an error /// in the base specification, 0 is returned. /// /// If the correct value is outside the range of representable values, /// (L)LONG_MIN or (U)(L)LONG_MAX will be returned (according to the sign /// and type of the value). /// /// Note: This specification is adapted from IEEE Std. 10003.1, 2003 Edition /// /// /// <b> Underlying APIs </b> /// /// The APIs underlying the standard APIs are all called as /// /// \code /// int _strtoX(const char* str, char** endptr, int radix, <type>* value) /// \endcode /// /// where X is /// /// - l : Convert to a long integer /// - ul : Convert to an unsigned long integer /// - ll : Convert to a long long integer /// - ull : Convert to an unsigned long long integer /// /// \param str The string to convert /// /// \param endptr If non-null, will be set to a pointer to the portion of the /// string following the convertable portion. If no conversion is performed /// then the original \a str is returned here. /// /// \param base Either 0 to indicate that the base should be derived from /// radix markers in the string, or a number in the range 2 to 36 inclusive. /// /// \param value The converted value, returned as the return value of the /// standard API. /// /// The return value of the underlying APIs is one of the following /// /// \retval 0 Success /// /// \retval -STRTOX_NO_CONVERSION_EMPTY No conversion was performed because the /// string was effectively empty. /// /// \retval -STRTOX_NO_CONVERSION_PARSE No conversion was performed because the /// string did not parse as an integer. /// /// \retval -STRTOX_INVALID_ARGUMENT No conversion was performed because the /// \a base specification was not valid. /// /// \retval -STRTOX_UNDERFLOW_STRTOL1 Conversion resulted in underflow /// /// \retval -STRTOX_UNDERFLOW_STRTOL2 Conversion resulted in underflow /// /// \retval -STRTOX_UNDERFLOW_STRTOLL1 Conversion resulted in underflow /// /// \retval -STRTOX_UNDERFLOW_STRTOLL2 Conversion resulted in underflow /// /// \retval -STRTOX_OVERFLOW_STRTOL1 Conversion resulted in overflow /// /// \retval -STRTOX_OVERFLOW_STRTOL2 Conversion resulted in overflow /// /// \retval -STRTOX_OVERFLOW_STRTOLL1 Conversion resulted in overflow /// /// \retval -STRTOX_OVERFLOW_STRTOLL2 Conversion resulted in overflow /// /// /// <b> Extended APIs </b> /// /// The extended APIs are the preferred way to do portable integer /// conversion. These APIs are all called as /// /// \code /// int strtoX(const char* str, char** endptr, int radix, <type>* value) /// \endcode /// /// where X is /// /// - i32 : Convert to an int32_t /// - u32 : Convert to a uint32_t /// - i64 : Convert to an int64_t /// - u64 : Convert to a uint64_t /// /// \param str The string to convert /// /// \param endptr If non-null, will be set to a pointer to the portion of the /// string following the convertable portion. If no conversion is performed /// then the original \a str is returned here. /// /// \param base Either 0 to indicate that the base should be derived from /// radix markers in the string, or a number in the range 2 to 36 inclusive. /// /// \param value The converted value /// /// The return value of the underlying APIs is one of the following /// /// \retval 0 Success /// /// \retval -STRTOX_NO_CONVERSION_EMPTY No conversion was performed because the /// string was effectively empty. /// /// \retval -STRTOX_NO_CONVERSION_PARSE No conversion was performed because the /// string did not parse as an integer. /// /// \retval -STRTOX_INVALID_ARGUMENT No conversion was performed because the /// \a base specification was not valid. /// /// \retval -STRTOX_UNDERFLOW_STRTOL1 Conversion resulted in underflow /// /// \retval -STRTOX_UNDERFLOW_STRTOL2 Conversion resulted in underflow /// /// \retval -STRTOX_UNDERFLOW_STRTOLL1 Conversion resulted in underflow /// /// \retval -STRTOX_UNDERFLOW_STRTOLL2 Conversion resulted in underflow /// /// \retval -STRTOX_OVERFLOW_STRTOL1 Conversion resulted in overflow /// /// \retval -STRTOX_OVERFLOW_STRTOL2 Conversion resulted in overflow /// /// \retval -STRTOX_OVERFLOW_STRTOLL1 Conversion resulted in overflow /// /// \retval -STRTOX_OVERFLOW_STRTOLL2 Conversion resulted in overflow /// #include "ssx.h" #include "ctype.h" #include "libssx.h" #include "strtox.h" // Skip whitespace static const char * skip_whitespace(const char *s) { while (isspace(*s)) { s++; } return s; } // Pick up a +/- sign. This is a predicate returning 1 if the value is // negated. static int sign(const char** s) { if (**s == '+') { (*s)++; return 0; } else if (**s == '-') { (*s)++; return 1; } else { return 0; } } // Look for a radix mark (0, 0[xX]). The string pointer is advanced if it is a // hex mark (0[xX]), but not for a simple '0' which could be either the start // of an octal constant or simply the number 0. The return value is either 8, // 10 or 16. static int radix_mark(const char** s) { const char* p = *s; if (p[0] == '0') { if ((p[1] == 'x') || (p[1] == 'X')) { *s += 2; return 16; } else { return 8; } } else { return 10; } } // Parse a character as a radix-base digit. Return the value of the digit or // -1 if it is not a legal digit for the radix. static int parse_digit(char c, int radix) { if (isdigit(c)) { if ((c - '0') < radix) { return c - '0'; } else { return -1; } } else if (radix <= 10) { return -1; } else { if (islower(c)) { if ((c - 'a') < (radix - 10)) { return c - 'a' + 10; } else { return -1; } } else if (isupper(c)) { if ((c - 'A') < (radix - 10)) { return c - 'A' + 10; } else { return -1; } } else { return -1; } } } // The most basic API is strtox(), which converts a string to an unsigned long // long. All of the base APIs are written in terms of this. This is legal due // to the fact that conversion is defined to continue even in the event of // overflow. This API may return the codes STRTOX_NO_CONVERSION_EMPTY, // STRTOX_NO_CONVERSION_PARSE or STRTOX_INVALID_ARGUMENT, // which the standard APIs always convert to a 0 // return value. Otherwise the flags 'overflow' and 'negative' are used by // the base APIs to determine how to handle special cases. static int strtox(const char *str, char **endptr, int base, unsigned long long* value, int* negative, int* overflow) { const char* s; unsigned long long new; int rc, radix, digit; do { s = str; *value = 0; *negative = 0; *overflow = 0; // Initial error checks if ((base != 0) && ((base < 2) || (base > 36))) { rc = STRTOX_INVALID_ARGUMENT; break; } // Skip whitespace s = skip_whitespace(s); if (*s == '\0') { rc = STRTOX_NO_CONVERSION_EMPTY; break; } // Process a +/- sign. Only one is allowed. *negative = sign(&s); // Look for a radix mark. Note that if base == 16 this will cause the // skip of a leading 0 in the string not followed by [xX], but that's // OK because it doesn't change the result of the conversion. if (base == 0) { radix = radix_mark(&s); } else { radix = base; if (radix == 16) { radix_mark(&s); } } // Parse. Note that once overflow is detected we continue to parse // (but ignore the data). rc = STRTOX_NO_CONVERSION_PARSE; while ((digit = parse_digit(*s, radix)) >= 0) { s++; if (!*overflow) { rc = 0; new = (*value * radix) + digit; if (new < *value) { *overflow = 1; } else { *value = new; } } } } while(0); if (endptr) { if (rc == 0) { *endptr = (char*)s; } else { *endptr = (char*)str; } } return rc; } /// See documentation for the file strtox.c int _strtol(const char* str, char** endptr, int base, long* value) { int rc, negative, overflow; unsigned long long value_ull; rc = strtox(str, endptr, base, &value_ull, &negative, &overflow); if (rc) { *value = 0; } else { if (overflow || (value_ull != (unsigned long)value_ull)) { if (negative) { rc = STRTOX_UNDERFLOW_STRTOL1; *value = LONG_MIN; } else { rc = STRTOX_OVERFLOW_STRTOL1; *value = LONG_MAX; } } else if (negative) { if (value_ull > ((unsigned long long)LONG_MAX + 1ull)) { rc = STRTOX_UNDERFLOW_STRTOL2; *value = LONG_MIN; } else { *value = ~value_ull + 1; } } else if (value_ull > (unsigned long long)LONG_MAX) { rc = STRTOX_OVERFLOW_STRTOL2; *value = LONG_MAX; } else { *value = value_ull; } } return rc; } /// See documentation for the file strtox.c int _strtoll(const char* str, char** endptr, int base, long long* value) { int rc, negative, overflow; unsigned long long value_ull; rc = strtox(str, endptr, base, &value_ull, &negative, &overflow); if (rc) { *value = 0; } else { if (overflow) { if (negative) { rc = STRTOX_UNDERFLOW_STRTOLL1; *value = LLONG_MIN; } else { rc = STRTOX_OVERFLOW_STRTOLL1; *value = LLONG_MAX; } } else if (negative) { if (value_ull > ((unsigned long long)LLONG_MAX + 1ull)) { rc = STRTOX_UNDERFLOW_STRTOLL2; *value = LLONG_MIN; } else { *value = ~value_ull + 1; } } else if (value_ull > (unsigned long long)LLONG_MAX) { rc = STRTOX_OVERFLOW_STRTOLL2; *value = LLONG_MAX; } else { *value = value_ull; } } return rc; } /// See documentation for the file strtox.c int _strtoul(const char* str, char** endptr, int base, unsigned long* value) { int rc, negative, overflow; unsigned long long value_ull; rc = strtox(str, endptr, base, &value_ull, &negative, &overflow); if (rc) { *value = 0; } else { if (overflow || (value_ull != (unsigned long)value_ull)) { rc = STRTOX_OVERFLOW_STRTOUL; *value = ULONG_MAX; } else { *value = value_ull; if (negative) { *value = ~*value + 1; } } } return rc; } /// See documentation for the file strtox.c int _strtoull(const char* str, char** endptr, int base, unsigned long long* value) { int rc, negative, overflow; rc = strtox(str, endptr, base, value, &negative, &overflow); if (rc) { *value = 0; } else { if (overflow) { rc = STRTOX_OVERFLOW_STRTOULL; *value = ULLONG_MAX; } else { if (negative) { *value = ~*value + 1; } } } return rc; } /// See documentation for the file strtox.c long int strtol(const char* str, char** endptr, int base) { long int value; _strtol(str, endptr, base, &value); return value; } /// See documentation for the file strtox.c long long int strtoll(const char* str, char** endptr, int base) { long long int value; _strtoll(str, endptr, base, &value); return value; } /// See documentation for the file strtox.c unsigned long int strtoul(const char* str, char** endptr, int base) { unsigned long int value; _strtoul(str, endptr, base, &value); return value; } /// See documentation for the file strtox.c unsigned long long int strtoull(const char* str, char** endptr, int base) { unsigned long long int value; _strtoull(str, endptr, base, &value); return value; } #if (__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ <= 1)) /// Internal version of strtol() /// /// ppcnf-mcp5 (GCC 4.1) requires that the entry point __strtol_internal() be /// present at certain optimization levels. This is equivalent to strtol() /// except that it takes an extra argument that must be == 0. The \a group /// parameter is supposed to control locale-specific thousands grouping. long int __strtol_internal(const char* str, char** endptr, int base, int group) { if (group != 0) { SSX_PANIC(STRTOX_INVALID_ARGUMENT_STRTOL); } return strtol(str, endptr, base); } #endif <|start_filename|>src/ssx/occhw/occhw_scom.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/ssx/occhw/occhw_scom.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file occhw_scom.c /// \brief procedures and support for scom operations /// /// <b> SCOM Operations </b> /// /// The maximum latency of a PIB operation has a hard upper /// bound derived from the hardware implementation. The putscom()/getscom() /// drivers here take advantage of this upper bound and implement tight /// timeouts, enforced by polling the timebase while waiting for the SCOM /// operations to complete. /// /// The latencies are small enough and so well understood that the /// getscom()/putscom() procedures operate in SSX_CRITICAL critical /// sections. There should be no problem for thread-based procedures to be /// written using getscom()/putscom() directly - in fact for short procedures /// it may be less overhead to use getscom()/putscom() than queuing a PORE-GPE /// program. All mainline procedures used by hard real-time code should /// remain as PORE-GPE programs however. /// /// SCOM operations return non-zero error codes that may or may not indicate /// an actual error, depending on which SCOM is being accessed. This error /// code (or 0 for success) is returned as the value of getscom()/putscom(). /// The error severity increases with the severity of the error: /// \code /// /// #define PCB_ERROR_NONE 0 /// #define PCB_ERROR_RESOURCE_OCCUPIED 1 /// #define PCB_ERROR_CHIPLET_OFFLINE 2 /// #define PCB_ERROR_PARTIAL_GOOD 3 /// #define PCB_ERROR_ADDRESS_ERROR 4 /// #define PCB_ERROR_CLOCK_ERROR 5 /// #define PCB_ERROR_PACKET_ERROR 6 /// #define PCB_ERROR_TIMEOUT 7 /// \endcode /// /// The default configuration variable SCOM_ERROR_LIMIT defines the maximum /// error code that will be returned - error codes above the limit (plus hard /// timeouts and other protocol errors) cause an immediate kernel panic. In /// the event of a non-0 error code, getscom() always sets the returned data /// to 0. /// /// In addition to getscom()/putscom() that implement the above defined error /// protocols, the raw APIs _getscom()/_putscom() are also available and /// allow the application full control over timeouts and error handling on a /// SCOM-by-SCOM basis. /// /// \bug Modify getscom/putscom to return the SSX error codes rather than /// 1-7. /// /// \bug Implement and use a generic poll_with_timeout(f, arg, t) #include "ssx.h" #include "occhw_scom.h" #include "occhw_shared_data.h" //////////////////////////////////////////////////////////////////////////// // SCOM //////////////////////////////////////////////////////////////////////////// // Common SCOM polling loop with software timeout. The PMC is always polled // at least twice to guarantee that we always poll once after a timeout. static int poll_scom(SsxInterval timeout) { SsxTimebase start; int timed_out; int rc; start = ssx_timebase_get(); timed_out = 0; do { rc = ssx_irq_status_get(OCCHW_IRQ_IPI_SCOM); if (!rc) { break; } if (timed_out) { rc = -SCOM_TIMEOUT_ERROR; break; } timed_out = ((timeout != SSX_WAIT_FOREVER) && ((ssx_timebase_get() - start) > timeout)); } while (1); return rc; } /// A raw getscom() through the PMC OCI/PIB bridge /// /// \param address A standard 32-bit SCOM address, including multicast /// addresses. /// /// \param data Points to a container for the returned data. /// /// \param timeout The software timeout as an SSX interval (timebase ticks), /// or the special value SSX_WAIT_FOREVER to indicate no software timeout. /// /// This routine executes in an SSX_CRITICAL critical section. /// /// Unlike most other APIs, this API returns both positive and negative error /// codes, as well as the 0 code for success. In the event of PCB errors, the /// returned \a data is obtained from the PMC O2P data registers. In the /// event of non-PCB errors, the caller \a data is not modified. /// /// If the transaction experiences a software timeout (controlled by the \a /// timeout parameter) or a protocol error, the PMC PIB master will be left in /// a state in which it is illegal to perform further SCOM access through the /// PMC until the ongoing transaction is finished. /// /// \retval 0 Success /// ///\ retval 1-7 A PCB error code. See \c pcb_common.h /// /// \retval -SCOM_TIMEOUT_ERROR The software timeout specified by the \a /// timeout parameter expired before the transaction completed. /// /// retval -SCOM_PROTOCOL_ERROR_GETSCOM_BUSY The PMC SCOM engine was busy when /// the call was made. int _getscom(uint32_t address, uint64_t* data, SsxInterval timeout) { SsxMachineContext ctx; int rc; occhw_scom_cmd_t* scom_cmd = &OSD_PTR->scom_cmd; occhw_scom_status_t scom_status; do { if(address & OCCHW_SCOM_READ_MASK) { rc = -SCOM_INVALID_ADDRESS; break; } ssx_critical_section_enter(SSX_CRITICAL, &ctx); // Check for a transaction already ongoing rc = ssx_irq_status_get(OCCHW_IRQ_IPI_SCOM); if (rc) { ssx_critical_section_exit(&ctx); rc = -SCOM_PROTOCOL_ERROR_GETSCOM_BUSY; break; } // Setup the write. The 'read' bit is set in the address. scom_cmd->scom_status.status32 = OCCHW_SCOM_PENDING; scom_cmd->scom_addr = address | OCCHW_SCOM_READ_MASK; // Notify the GPE (by raising an interrupt) that a request is pending ssx_irq_status_set(OCCHW_IRQ_IPI_SCOM, 1); // Poll until completed or timed out rc = poll_scom(timeout); // Extract the data and status out of the scom command block *data = scom_cmd->scom_data; scom_status.status32 = scom_cmd->scom_status.status32; ssx_critical_section_exit(&ctx); if(!rc) { //check that the GPE updated the scom status. Normally, //the gpe won't clear the interrupt until it has updated //the status field. The exception is if the GPE gets //reset. if(scom_status.status32 == OCCHW_SCOM_PENDING) { rc = -SCOM_PROTOCOL_ERROR_GETSCOM_RST; } else { //The SIBRC field of the MSR is where we get the status for //the last scom operation. rc = scom_status.sibrc; } } } while(0); return rc; } /// getscom() through the PMC OCI/PIB bridge /// /// \param address A standard 32-bit SCOM address, including multicast /// addresses. /// /// \param data Points to a container for the returned data. /// /// This routine executes in an SSX_CRITICAL critical section. /// /// Unlike most other APIs, this API returns positive error /// codes, as well as the 0 code for success. In the event of PCB errors, the /// returned \a data is set to 0. /// /// If the transaction experiences a software timeout (controlled by the \a /// timeout parameter), a protocol error, or a PCB error greater than the /// configuration constant SCOM_ERROR_LIMIT this routine causes a kernel /// panic. This may leave the PMC PIB master in a state in which it is illegal /// to perform further SCOM access through the PMC (until the ongoing /// transaction is finished.) /// /// \retval 0 Success /// ///\ retval 1-7 A PCB error code. See \c pcb_common.h int getscom(uint32_t address, uint64_t* data) { int rc; rc = _getscom(address, data, SCOM_TIMEOUT); if (rc == 0) { return 0; } if ((rc > 0) && (rc <= SCOM_ERROR_LIMIT)) { *data = 0; } else { //printk("getscom(0x%08x, %p) : Failed with error %d\n", // address, data, rc); if (rc > 0) { switch (rc) { case 1: SSX_PANIC(SCOM_PCB_ERROR_1_GETSCOM); break; case 2: SSX_PANIC(SCOM_PCB_ERROR_2_GETSCOM); break; case 3: SSX_PANIC(SCOM_PCB_ERROR_3_GETSCOM); break; case 4: SSX_PANIC(SCOM_PCB_ERROR_4_GETSCOM); break; case 5: SSX_PANIC(SCOM_PCB_ERROR_5_GETSCOM); break; case 6: SSX_PANIC(SCOM_PCB_ERROR_6_GETSCOM); break; default: SSX_PANIC(SCOM_PCB_ERROR_7_GETSCOM); break; } } else if (rc == -SCOM_TIMEOUT_ERROR) { SSX_PANIC(SCOM_TIMEOUT_ERROR_GETSCOM); } else { SSX_PANIC(SCOM_PROTOCOL_ERROR_GETSCOM); } } return rc; } /// A raw putscom() through the PMC OCI/PIB bridge /// /// \param address A standard 32-bit SCOM address, including multicast /// addresses. /// /// \param data The SCOM write data /// /// \param timeout The software timeout as an SSX interval (timebase ticks), /// or the special value SSX_WAIT_FOREVER to indicate no timeout. /// /// This routine executes in an SSX_CRITICAL critical section. /// /// Unlike most other APIs, this API returns both positive and negative error /// codes, as well as the 0 code for success. /// /// If the transaction experiences a software timeout (controlled by the \a /// timeout parameter) or a protocol error, the PMC PIB master will be left in /// a state in which it is illegal to perform further SCOM access through the /// PMC until the ongoing transaction is finished. /// /// \retval 0 Success /// /// \retval 1-7 A PCB error code. See \c pcb_common.h /// /// \retval -SCOM_TIMEOUT The software timeout specified by the \a timeout /// parameter expired before the transaction completed. /// /// \retval -SCOM_PROTOCOL_ERROR_PUTSCOM_BUSY The PMC SCOM engine was busy when /// the call was made. int _putscom(uint32_t address, uint64_t data, SsxInterval timeout) { SsxMachineContext ctx; int rc; occhw_scom_cmd_t* scom_cmd = &OSD_PTR->scom_cmd; occhw_scom_status_t scom_status; do { if(address & OCCHW_SCOM_READ_MASK) { rc = -SCOM_INVALID_ADDRESS; break; } ssx_critical_section_enter(SSX_CRITICAL, &ctx); // Check for a transaction already ongoing rc = ssx_irq_status_get(OCCHW_IRQ_IPI_SCOM); if (rc) { ssx_critical_section_exit(&ctx); rc = -SCOM_PROTOCOL_ERROR_PUTSCOM_BUSY; break; } // Setup the write. The 'read' bit is cleared in the address. scom_cmd->scom_status.status32 = OCCHW_SCOM_PENDING; scom_cmd->scom_addr = address; scom_cmd->scom_data = data; // Notify the GPE (by raising an interrupt) that a request is pending ssx_irq_status_set(OCCHW_IRQ_IPI_SCOM, 1); // Poll until completed or timed out rc = poll_scom(timeout); scom_status.status32 = scom_cmd->scom_status.status32; ssx_critical_section_exit(&ctx); if(!rc) { //check that the GPE updated the scom status. Normally, //the gpe won't clear the interrupt until it has updated //the status field. The exception is if the GPE gets //reset. if(scom_status.status32 == OCCHW_SCOM_PENDING) { rc = -SCOM_PROTOCOL_ERROR_PUTSCOM_RST; } else { //The SIBRC field of the MSR is where we get the status for //the last scom operation. rc = scom_status.sibrc; } } } while(0); return rc; } /// putscom() through the PMC OCI/PIB bridge /// /// \param address A standard 32-bit SCOM address, including multicast /// addresses. /// /// \param data The SCOM write data. /// /// This routine executes in an SSX_CRITICAL critical section. /// /// Unlike most other APIs, this API returns positive error /// codes, as well as the 0 code for success. /// /// If the transaction experiences a software timeout (controlled by the \a /// timeout parameter), a protocol error, or a PCB error greater than the /// configuration constant SCOM_ERROR_LIMIT this routine causes a kernel /// panic. This may leave the PMC PIB master in a state in which it is illegal /// to perform further SCOM access through the PMC (until the ongoing /// transaction is finished.) /// /// \retval 0 Success /// /// \retval 1-7 A PCB error code. See \c pcb_common.h int putscom(uint32_t address, uint64_t data) { int rc; rc = _putscom(address, data, SCOM_TIMEOUT); if ((rc == 0) || ((rc > 0) && (rc <= SCOM_ERROR_LIMIT))) { return rc; } //printk("putscom(0x%08x, 0x%016llx) : Failed with error %d\n", // address, data, rc); if (rc > 0) { switch (rc) { case 1: SSX_PANIC(SCOM_PCB_ERROR_1_PUTSCOM); break; case 2: SSX_PANIC(SCOM_PCB_ERROR_2_PUTSCOM); break; case 3: SSX_PANIC(SCOM_PCB_ERROR_3_PUTSCOM); break; case 4: SSX_PANIC(SCOM_PCB_ERROR_4_PUTSCOM); break; case 5: SSX_PANIC(SCOM_PCB_ERROR_5_PUTSCOM); break; case 6: SSX_PANIC(SCOM_PCB_ERROR_6_PUTSCOM); break; default: SSX_PANIC(SCOM_PCB_ERROR_7_PUTSCOM); break; } } else if (rc == -SCOM_TIMEOUT_ERROR) { SSX_PANIC(SCOM_TIMEOUT_ERROR_PUTSCOM); } else { SSX_PANIC(SCOM_PROTOCOL_ERROR_PUTSCOM); } return rc; } <|start_filename|>src/occ_gpe0/firdata/fir_data_collect.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/firdata/fir_data_collect.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <fir_data_collect.h> #include "tpc_firmware_registers.h" #include "tpc_register_addresses.h" #include <firData.h> #include <gpe_export.h> extern gpe_shared_data_t * G_gpe_shared_data; extern void busy_wait(uint32_t t_microseconds); /* * Function Specification * * Name: fir_data_collect * * Description: Collects FIR data on checkstop. * * End Function Specification */ void fir_data_collect(void) { int32_t l_rc = 0; // Homer data section and size uint8_t *l_hBuf = (uint8_t*) G_gpe_shared_data->fir_params_buffer_ptr; uint32_t l_hBufSize = FIR_PARMS_SECTION_SIZE; // PNOR working buffer in SRAM and size uint8_t *l_pBuf = (uint8_t*) G_gpe_shared_data->fir_heap_buffer_ptr; uint32_t l_pBufSize = FIR_HEAP_SECTION_SIZE; busy_wait(2000000); // wait two seconds l_rc = FirData_captureCsFirData(l_hBuf, l_hBufSize, l_pBuf, l_pBufSize); // Trace the rc only, error logs cannot be collected in this state TRAC_IMP("Checkstop FIR data capture completed with rc=%d", l_rc); } <|start_filename|>src/occ_405/amec/amec_part.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_part.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /*----------------------------------------------------------------------------*/ /* Includes */ /*----------------------------------------------------------------------------*/ #include <common_types.h> #include <mode.h> #include <amec_sys.h> #include <amec_part.h> #include <trac.h> #include <dcom.h> /*----------------------------------------------------------------------------*/ /* Constants */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Globals */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Typedef / Enum */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* Code */ /*----------------------------------------------------------------------------*/ // Given partition id, return pointer to existing partition or NULL static amec_part_t* amec_part_find_by_id(amec_part_config_t* i_config, const uint8_t i_id) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ amec_part_t *l_part = NULL; uint16_t l_idx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ for (l_idx=0; l_idx<AMEC_PART_MAX_PART; l_idx++) { if (i_config->part_list[l_idx].id == i_id && i_config->part_list[l_idx].valid) { l_part = &(i_config->part_list[l_idx]); break; } } return l_part; } // Function Specification // // Name: amec_isr_speed_to_freq // // Description: Given a core, return a valid partition that owns it, or NULL. // // End Function Specification amec_part_t* amec_part_find_by_core(amec_part_config_t* i_config, const uint16_t i_core_index) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ amec_part_t *l_part = NULL; uint16_t l_part_index = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { if (i_core_index >= MAX_NUM_CORES) { break; // illegal core number } l_part_index = i_config->core2part[i_core_index]; if (l_part_index >= AMEC_PART_MAX_PART) { break; // illegal partition number } if (i_config->part_list[l_part_index].valid) { l_part = (amec_part_t*) &(i_config->part_list[l_part_index]); } } while(0); return l_part; } // Function Specification // // Name: amec_part_add // // Description: Add a core group. // // End Function Specification void amec_part_add(uint8_t i_id) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ amec_part_t *l_part; uint16_t l_idx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ do { l_part = (amec_part_t*) amec_part_find_by_id(&g_amec->part_config, i_id); if (l_part != NULL) { break; // Partition already exists } // Find new slot for (l_idx=0; l_idx<AMEC_PART_MAX_PART; l_idx++) { if (!g_amec->part_config.part_list[l_idx].valid) { l_part = &g_amec->part_config.part_list[l_idx]; break; } } if (l_part == NULL) { // This should never happen, since table should be large enough // to hold as many partitions as can be created on system. break; } // Enter new partition into table with default values l_part->id = i_id; l_part->valid = 1; //Mark them as valid l_part->ncores = 0; //No cores for (l_idx=0; l_idx<AMEC_PART_NUM_CORES; l_idx++) { l_part->core_list[l_idx] = AMEC_PART_NUM_CORES; } // For now, create a single partition with all cores assigned to it // until we write the interface to talk to PHYP if (i_id == 0) { l_part->ncores = MAX_NUM_CORES; for (l_idx=0; l_idx<MAX_NUM_CORES; l_idx++) { l_part->core_list[l_idx] = l_idx; } } // Set default soft frequency boundaries to use full frequency range l_part->soft_fmin = 0x0000; l_part->soft_fmax = 0xFFFF; // Set default values for DPS parameters (Favor Energy) l_part->dpsalg.step_up = 8; l_part->dpsalg.step_down = 8; l_part->dpsalg.tlutil = 9800; l_part->dpsalg.sample_count_util = 16; l_part->dpsalg.epsilon_perc = 1800; l_part->dpsalg.alpha_up = 9800; l_part->dpsalg.alpha_down = 9800; l_part->dpsalg.type = 0; //No algorithm is selected yet l_part->dpsalg.freq_request = UINT16_MAX; l_part->es_policy = OCC_INTERNAL_MODE_MAX_NUM; l_part->follow_sysmode = TRUE; } while (0); return; } void amec_part_init() { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ uint16_t l_idx = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // Initial core to partition mapping. Cores point to an invalid core group // id. // For now, we assume a single partition (id 0) with all cores assigned to // it. Once the PHYP interface has been written, we can remove this // assumption. for (l_idx=0; l_idx<MAX_NUM_CORES; l_idx++) { g_amec->part_config.core2part[l_idx] = 0; // AMEC_PART_INVALID_ID; } for (l_idx=0; l_idx<AMEC_PART_MAX_PART; l_idx++) { // Creating all possible partitions amec_part_add(l_idx); g_amec->part_config.part_list[l_idx].dpsalg.util_speed_request = g_amec->sys.fmax; } } void amec_part_update_dps_parameters(amec_part_t* io_part) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // If partition doesn't exist, just exit if (io_part == NULL) { return; } // Check to see if parameter values have been overwritten by user if (g_amec->slv_dps_param_overwrite == TRUE) { // Then, exit right away return; } // By default, let's use the DPS-Favor Energy settings io_part->dpsalg.step_up = 8; io_part->dpsalg.step_down = 8; io_part->dpsalg.tlutil = 9800; io_part->dpsalg.sample_count_util = 16; io_part->dpsalg.epsilon_perc = 1800; io_part->dpsalg.alpha_up = 9800; io_part->dpsalg.alpha_down = 9800; io_part->dpsalg.type = 41; // If core group policy is DPS-Favor Performance, then write those settings if (io_part->es_policy == OCC_INTERNAL_MODE_DPS_MP) { io_part->dpsalg.step_up = 1000; io_part->dpsalg.step_down = 8; io_part->dpsalg.tlutil = 1000; io_part->dpsalg.sample_count_util = 1; io_part->dpsalg.epsilon_perc = 0; io_part->dpsalg.alpha_up = 9990; io_part->dpsalg.alpha_down = 9990; io_part->dpsalg.type = 41; // Check if this is a multi-node system if (G_sysConfigData.system_type.single == 0) { // These parameter values will result in static turbo frequency io_part->dpsalg.alpha_down = 0; io_part->dpsalg.tlutil = 0; TRAC_IMP("Multi-node system found! Updating DPS-FP parameters: single_node_bit[%u] alpha_down[%u] tlutil[%u]", G_sysConfigData.system_type.single, io_part->dpsalg.alpha_down, io_part->dpsalg.tlutil); } } } void amec_part_update_perf_settings(amec_part_t* io_part) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ uint16_t j = 0; uint16_t l_core_index = 0; amec_core_perf_counter_t* l_perf; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ // If partition doesn't exist, just exit if (io_part == NULL) { return; } switch (io_part->es_policy) { case OCC_INTERNAL_MODE_DPS: case OCC_INTERNAL_MODE_DPS_MP: // These policies require that we reset the internal performance // settings of the cores in the partition for (j=0; j<io_part->ncores; j++) { l_core_index = io_part->core_list[j]; l_perf = &g_amec->proc[0].core[l_core_index % MAX_NUM_CORES].core_perf; memset(l_perf->ptr_util_slack_avg_buffer, 0, 2*MAX_UTIL_SLACK_AVG_LEN); memset(l_perf->ptr_util_active_avg_buffer, 0, 2*MAX_UTIL_SLACK_AVG_LEN); l_perf->util_active_core_counter = 0; l_perf->util_slack_core_counter = 0; l_perf->util_slack_accumulator = 0; l_perf->util_active_accumulator = 0; l_perf->ptr_putUtilslack = 0; } break; default: // For all other policies, reset the DPS frequency request for (j=0; j<io_part->ncores; j++) { l_core_index = io_part->core_list[j]; g_amec->proc[0].core[l_core_index % MAX_NUM_CORES] .core_perf.dps_freq_request = UINT16_MAX; } break; } } void AMEC_part_update_sysmode_policy(OCC_MODE i_occ_internal_mode) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ uint16_t i = 0; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ for (i=0; i<AMEC_PART_MAX_PART; i++) { // If a core group is not valid, skip it if (!g_amec->part_config.part_list[i].valid) { continue; } // If a core group has no cores assigned, skip it if (g_amec->part_config.part_list[i].ncores == 0) { continue; } // If a core group is not following the system power mode, skip it if (!g_amec->part_config.part_list[i].follow_sysmode) { continue; } // Set power mode for this core group to the system power mode switch (i_occ_internal_mode) { case OCC_MODE_NOMINAL: g_amec->part_config.part_list[i].es_policy = OCC_INTERNAL_MODE_NOM; break; case OCC_MODE_DYN_POWER_SAVE: g_amec->part_config.part_list[i].es_policy = OCC_INTERNAL_MODE_DPS; break; case OCC_MODE_DYN_POWER_SAVE_FP: g_amec->part_config.part_list[i].es_policy = OCC_INTERNAL_MODE_DPS_MP; break; default: g_amec->part_config.part_list[i].es_policy = OCC_INTERNAL_MODE_UNDEFINED; break; } // Update the DPS parameters based on the power policy if ((g_amec->part_config.part_list[i].es_policy == OCC_INTERNAL_MODE_DPS) || (g_amec->part_config.part_list[i].es_policy == OCC_INTERNAL_MODE_DPS_MP)) { amec_part_update_dps_parameters(&(g_amec->part_config.part_list[i])); } // Update internal performance settings for this partition amec_part_update_perf_settings(&(g_amec->part_config.part_list[i])); // Useful trace for debug //TRAC_INFO("AMEC_part_update_sysmode_policy: Core_group[%u] Num_cores[%u] ES_policy[0x%02x]", // i, g_amec->part_config.part_list[i].ncores, // g_amec->part_config.part_list[i].es_policy); } } void AMEC_part_overwrite_dps_parameters(void) { /*------------------------------------------------------------------------*/ /* Local Variables */ /*------------------------------------------------------------------------*/ uint16_t i = 0; uint16_t j = 0; uint16_t l_core_index = 0; amec_part_t* l_part = NULL; amec_core_perf_counter_t* l_perf = NULL; /*------------------------------------------------------------------------*/ /* Code */ /*------------------------------------------------------------------------*/ for (i=0; i<AMEC_PART_MAX_PART; i++) { // If a core group is not valid, skip it if (!g_amec->part_config.part_list[i].valid) { continue; } // If a core group has no cores assigned, skip it if (g_amec->part_config.part_list[i].ncores == 0) { continue; } // Overwrite the DPS parameters based on values sent by Master OCC l_part = &(g_amec->part_config.part_list[i]); l_part->dpsalg.alpha_up = G_dcom_slv_inbox_rx.alpha_up; l_part->dpsalg.alpha_down = G_dcom_slv_inbox_rx.alpha_down; l_part->dpsalg.sample_count_util = G_dcom_slv_inbox_rx.sample_count_util; l_part->dpsalg.step_up = G_dcom_slv_inbox_rx.step_up; l_part->dpsalg.step_down = G_dcom_slv_inbox_rx.step_down; l_part->dpsalg.epsilon_perc = G_dcom_slv_inbox_rx.epsilon_perc; l_part->dpsalg.tlutil = G_dcom_slv_inbox_rx.tlutil; // The algorithm type cannot be selected by customer, hardcoded here. l_part->dpsalg.type = 41; // Update internal performance settings for each core on this partition for (j=0; j<l_part->ncores; j++) { l_core_index = l_part->core_list[j]; l_perf = &g_amec->proc[0].core[l_core_index % MAX_NUM_CORES].core_perf; memset(l_perf->ptr_util_slack_avg_buffer, 0, 2*MAX_UTIL_SLACK_AVG_LEN); memset(l_perf->ptr_util_active_avg_buffer, 0, 2*MAX_UTIL_SLACK_AVG_LEN); l_perf->util_active_core_counter = 0; l_perf->util_slack_core_counter = 0; l_perf->util_slack_accumulator = 0; l_perf->util_active_accumulator = 0; l_perf->ptr_putUtilslack = 0; } } } /*----------------------------------------------------------------------------*/ /* End */ /*----------------------------------------------------------------------------*/ <|start_filename|>src/lib/common/memset.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/common/memset.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// \file memset.c /// \brief The memset() function #include "kernel.h" /// The memset() function fills the first \a n bytes of the memory area /// pointed to by \a s with the constant byte \a c. The memset() function /// returns a pointer to the memory area \a s. /// /// Note that memset() is optimized for setting large memory areas, and /// entails quite a bit of overhead to do this efficiently. If a memory area /// consists of a small number of basic data types (e.g., integers) it is /// probably more time-efficient to set the memory directly with a for loop /// (or unrolled loop). // This implementation should work well for both 32-bit and 64-bit // machines. The implementation assumes that it is worthwhile to align memory // pointers and do as much as possible using aligned addresses. [This doesn't // seem to matter on an X86 server processor, however]. It also assumes that // it is better to avoid the loop setup overhead by a test and branch for // cases where loops can be bypassed. //void * //memset(void *s, int c, size_t n) //{ // uint8_t byte = (uint8_t)c; // uint8_t *p = (uint8_t *)s; // // while(n--) { // *p++ = byte; // } // // return s; //} void * memset(void *s, int c, size_t n) { uint8_t byte, *p8; uint32_t word; uint64_t doubleword, *p64; size_t bytes, doublewords, octawords; // Any initial memory segment not aligned to an 8-byte boundary is set // bytewise. byte = (uint8_t)c; p8 = (uint8_t *)s; bytes = MIN(n, (unsigned long)s % 8); if (bytes) { n -= bytes; while (bytes--) { *p8++ = byte; } } // Short requests are finshed here as well. if (n < 8) { while (n--) { *p8++ = byte; } return s; } // We have at least 8 bytes of memory aligned on an 8-byte boundary. A // doubleword initializer is created. word = (byte << 8) | byte; word = (word << 16) | word; doubleword = ((uint64_t)word << 32) | word; // First set memory 32 bytes at a time. p64 = (uint64_t *)p8; octawords = n / 32; if (octawords) { n -= octawords * 32; while(octawords--) { *p64++ = doubleword; *p64++ = doubleword; *p64++ = doubleword; *p64++ = doubleword; } } // Now set memory 8 bytes at a time. This might actually be better done // explicitly rather than as a loop because the maximum loop count is 3 // here. doublewords = n / 8; if (doublewords) { n -= doublewords * 8; while (doublewords--) { *p64++ = doubleword; } } // Finally finish any remaining memory bytewise p8 = (uint8_t *)p64; if (n) { while (n--) { *p8++ = byte; } } return s; } <|start_filename|>src/occ_405/rtls/test/main.c<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/rtls/test/main.c $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include "ssx.h" #include "ssx_io.h" #include "simics_stdio.h" #include <thread.h> #include <errl.h> #include <rand.h> #include <rtls.h> #include <appletId.h> // For applet ID extern void __ssx_boot; IMAGE_HEADER (G_mainAppImageHdr,__ssx_boot,MAIN_APP_ID,OCC_APLT_TEST); // Period in which to run #timer_routine #define TIMER_INTERVAL (SsxInterval) SSX_MICROSECONDS(5000) int g_j = 0; int g_k = 0; extern uint32_t G_run_mask; // Globals from local copy of rtls_tables.c: extern task_t G_task_table[TASK_END]; // Global task table extern uint32_t task_0_data; // Default task data buffers extern uint32_t task_1_data; extern uint32_t task_2_data; extern uint32_t task_3_data; extern uint32_t task_0_alt_data; // Alternate task data buffers extern uint32_t task_1_alt_data; extern uint32_t task_2_alt_data; extern uint32_t task_3_alt_data; SimicsStdio simics_stdout; SimicsStdio simics_stderr; /*----------------------------------------------------------------------------*/ /* Critical/Non-Critical stack */ /*----------------------------------------------------------------------------*/ uint8_t noncritical_stack[NONCRITICAL_STACK_SIZE]; uint8_t critical_stack[CRITICAL_STACK_SIZE]; uint8_t test_thread_stack[THREAD_STACK_SIZE]; SsxThread test_thread; SsxTimer G_test_timer; // Inits the IRQ handler. extern void rtl_ocb_init( void ); // Run the IRQ handler for at least MAX_NUM_TICKS, then disable it again. int rtl_run_max_ticks(void); // Utility clears the data buffers in all tasks in the global task table. void clear_task_data_bufs(void); // Utility clears the flags in all tasks in the global task table. void clear_task_flags(void); // Utility writes the flags in the specified task to the specified value. void write_task_flags(task_id_t i_task_id, uint32_t new_flags); // Utility to dump flags & data for all tasks in G_task_table, along with // the current values of G_run_mask and CURRENT_TICK. void dump_global_state(void); // Tests the API that reads & writes the global & task run flags. void test_flags_api(void); // Tests the function ('rtl_stop_task') that indicates a task is NOT ready to run. void test_task_stop_api(void); // Tests the function ('rtl_set_task_data') that assigns a new data buffer to a // task in the global task list. void test_set_data_api(void); // Thread routine that runs all our tests. void test_thread_routine(void *private); // The main routine. int main(int argc, char **argv); // Function Specification // // Name: rtl_run_max_ticks // // Description: // Run the RTLS IRQ handler for at least MAX_NUM_TICKS, then stop. // Note: This function does not guarantee that the IRQ handler will run for // exactly MAX_NUM_TICKS ticks. It does guarantee that the IRQ handler will // run for _at_least_ MAX_NUM_TICKS ticks (but could run for more). // // End Function Specification int rtl_run_max_ticks(void) { // If we can loop this many cycles without seeing our IRQ stop condition, // then something is broken. #define MAX_WAIT_CYCLES 10000 int i = 0; // Counter int rc = 0; // Return Code // Start the RTLS IRQ timer. ssx_irq_enable( PGP_IRQ_OCC_TIMER0 ); // Wait for the timer to hit MAX_NUM_TICKS ticks. // Note: When we enter this loop, CURRENT_TICK may still equal 0xFFFFFFFF, // so handle that condition appropriately. for( i = 0; i < MAX_WAIT_CYCLES; i++) { // Warning: ssx_sleep only works if called from a thread OTHER than the one that // calls ocb_timer_setup (function called by rtl_ocb_init). If this rule is not // followed, the OCB IRQ handler will run a trap instruction and hang. ssx_sleep(1); if( (CURRENT_TICK >= MAX_NUM_TICKS) && (CURRENT_TICK < 0xFFFFFFFF) ) { ssx_irq_disable(PGP_IRQ_OCC_TIMER0); CURRENT_TICK = 0xFFFFFFFF; break; } } if( i >= MAX_WAIT_CYCLES ) { // We timed-out waiting for CURRENT_TICK to equal MAX_NUM_TICKS. Make noise & exit. printf(" ERROR: %s: %d: Timed-out waiting for CURRENT_TICK to reach %d.\n\n", __FILE__, __LINE__, MAX_NUM_TICKS); rc = -1; } return rc; } // Function Specification // // Name: clear_task_data_bufs // // Description: // Utility clears the data buffers in all tasks in the global task table. // // End Function Specification void clear_task_data_bufs(void) { int i; for( i = 0; i < TASK_END; i++ ) { *((uint32_t *)(G_task_table[i].data_ptr)) = 0x00000000; } } // Function Specification // // Name: clear_task_flags // // Description: // Utility clears the flags in all tasks in the global task table. // Note: This sets all task flags to 0. // // End Function Specification void clear_task_flags(void) { int i; for( i = 0; i < TASK_END; i++ ) { G_task_table[i].flags = 0x00000000; } } // Function Specification // // Name: write_task_flags // // Description: // Utility writes the flags in the specified task to the specified value. // Note: This overwrites the prior flags value for the given task. // // End Function Specification void write_task_flags(task_id_t i_task_id, uint32_t new_flags) { if( i_task_id >= TASK_END ) { printf("Warning: %s: write_task_flags: Invalid task ID: %02x. Not overwriting flags.\n", __FILE__, i_task_id); } else { G_task_table[i_task_id].flags = new_flags; } } // Function Specification // // Name: dump_global_state // // Description: // Utility to dump flags & data for all tasks in G_task_table, along with // the current values of G_run_mask and CURRENT_TICK. // // End Function Specification void dump_global_state(void) { int i; printf("\n G_run_mask = [0x%04x] ; CURRENT_TICK = [0x%04x]\n", G_run_mask, CURRENT_TICK); for( i = 0; i < TASK_END; i++ ) { printf(" TASK_ID_%02d : flags [0x%08x] ; data_p [0x%p] ; data [0x%08x]\n", \ i, G_task_table[i].flags, G_task_table[i].data_ptr, *((uint32_t *)(G_task_table[i].data_ptr)) ); } printf("\n"); } // Function Specification // // Name: test_1 // // Description: // This test is to stop ocb timer after complete 1 loop // // End Function Specification void test_1() { // Announce which test is running. printf("\ntest_1:\n"); // re-enable interrupt so RTL will continue again (CURRENT_TICK = 0xFFFFFFFF) printf(" Test_1_1: starting ocb timer\n"); rtl_run_max_ticks(); printf(" Test_1_1: exiting subroutine.\n"); return; } // Function Specification // // Name: test_2 // // Description: // This test to set and clear the global run mask interfaces // // End Function Specification void test_2() { // Announce which test is running. printf("\ntest_2:\n"); //test rtl_set_run_mask() interface G_run_mask = 0x00000000; printf(" Test_2_1: G_run_mask = 0x%08x before setting\n", G_run_mask); rtl_set_run_mask( RTL_FLAG_ACTIVE | RTL_FLAG_OBS ); printf(" Test_2_2: G_run_mask = 0x%08x after setting\n", G_run_mask); //test rtl_clr_run_mask() interface G_run_mask = RTL_FLAG_MSTR | RTL_FLAG_NOTMSTR | RTL_FLAG_ACTIVE | RTL_FLAG_OBS | RTL_FLAG_RST_REQ |RTL_FLAG_NO_APSS ; printf(" Test_2_3: G_run_mask = 0x%08x before clearing\n", G_run_mask); rtl_clr_run_mask( RTL_FLAG_ACTIVE | RTL_FLAG_OBS ); printf(" Test_2_4: G_run_mask = 0x%08x after clearing\n", G_run_mask); return; } // Function Specification // // Name: test_flags_api // // Description: Tests the global & task run flags, including the API that // reads & writes these flags. // // End Function Specification void test_flags_api(void) { int i = 0; // Counter BOOLEAN l_result = FALSE; // Local copy of new run mask (odd-numbered bits set). uint32_t l_odd_run_mask = RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_RST_REQ; // Partial inverse of l_odd_run_mask (even-numbered bits set, except for the 'run' flag: bit 0). uint32_t l_even_run_mask = RTL_FLAG_NOTMSTR | RTL_FLAG_ACTIVE | RTL_FLAG_NO_APSS; // Announce which test is running. printf("\ntest_flags_api:\n"); // Clear all task data & flags. clear_task_data_bufs(); clear_task_flags(); // Use API to set 'run' flag + odd-numbered bits in global flags mask. rtl_clr_run_mask(0xFFFFFFFF); rtl_set_run_mask(RTL_FLAG_RUN | l_odd_run_mask); // Set 1/2 the tasks to run w/same mask as global, and the other 1/2 of the // tasks to run w/opposite mask from the global. for (i = 0; i < TASK_END; i++) { // Use i as i_task_id if (i % 2) { // Task ID is odd write_task_flags((task_id_t) i, l_odd_run_mask); } else { // Task ID is even write_task_flags((task_id_t) i, l_even_run_mask); } } // Use API to set all tasks as runnable. for (i = 0; i < TASK_END; i++) { rtl_start_task((task_id_t) i); } // Use API to check which tasks are runnable. // Expect all tasks to report as runnable. printf(" Before IRQ enable. Using \'odd\' global mask.\n"); printf(" Expect: All tasks report as runnable.\n"); printf(" Actual: Tasks reporting as runnable: "); for (i = 0; i < TASK_END; i++) { l_result = rtl_task_is_runnable((task_id_t) i); if (l_result) { printf("%d ", i); } } printf("\n"); dump_global_state(); // Run the rtls for MAX_NUM_TICKS, then stop. rtl_run_max_ticks(); // Dump task data, task flags, global flags and CURRENT_TICK. printf(" After IRQ ran.\n"); printf(" Expect: Only tasks using the \'odd\' flags mask actually ran.\n"); printf(" Actual: Task state:\n"); dump_global_state(); // Clear all task data, but not the task flags. clear_task_data_bufs(); // Use the API to reverse the sense of the global flags only. rtl_clr_run_mask(0xFFFFFFFF); rtl_set_run_mask(RTL_FLAG_RUN | l_even_run_mask); // Use API to check which tasks are runnable. // Expect all tasks to report as runnable. printf(" Before IRQ enable. Using \'even\' global mask.\n"); printf(" Expect: All tasks report as runnable.\n"); printf(" Actual: Tasks reporting as runnable: "); for (i = 0; i < TASK_END; i++) { l_result = rtl_task_is_runnable((task_id_t) i); printf("%d ", i); } printf("\n"); dump_global_state(); // Run the rtls for MAX_NUM_TICKS, then stop. rtl_run_max_ticks(); // Dump task data, task flags, global flags and CURRENT_TICK. printf(" After IRQ ran.\n"); printf(" Expect: Only tasks using the \'even\' flags mask actually ran.\n"); printf(" Actual: Task state:\n"); dump_global_state(); return; } // Function Specification // // Name: test_task_stop_api // // Description: Tests the API function that indicates a task is NOT ready // to run: 'rtl_stop_task'. // // End Function Specification void test_task_stop_api(void) { int i = 0; // Counter BOOLEAN l_result = FALSE; // Local copy of new run mask (odd-numbered bits set). uint32_t l_odd_run_mask = RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_RST_REQ; // Announce which test is running. printf("\ntest_task_stop_api:\n"); // Clear all task data & flags. clear_task_data_bufs(); clear_task_flags(); // Use API to set 'run' flag + odd-numbered bits in global flags mask. rtl_clr_run_mask(0xFFFFFFFF); rtl_set_run_mask(RTL_FLAG_RUN | l_odd_run_mask); // Set other task flags so all task flags == global flag mask. // Use the API to set the RTL_FLAG_RUN flags in all tasks. for (i = 0; i < TASK_END; i++) { // Use i as i_task_id write_task_flags((task_id_t) i, l_odd_run_mask); rtl_start_task((task_id_t) i); } // Now use the API to "stop" ~1/2 the tasks (clear RTL_FLAG_RUN). for (i = 0; i < TASK_END; i++) { // Use i as i_task_id if ( (i % 2) == 0 ) { // Task ID is even rtl_stop_task((task_id_t) i); } } // Use API to check which tasks are runnable. Expect 1/2 the tasks are runnable. printf(" Before IRQ runs.\n"); printf(" Expect: Half of the tasks report as runnable.\n"); printf(" Actual: Tasks reporting as runnable: "); for (i = 0; i < TASK_END; i++) { l_result = rtl_task_is_runnable((task_id_t) i); if (l_result) { printf("%d ", i); } } printf("\n"); dump_global_state(); // Run the rtls for MAX_NUM_TICKS, then stop. rtl_run_max_ticks(); // Dump task data, task flags, global flags and CURRENT_TICK. printf(" After IRQ ran.\n"); printf(" Expect: \'Runnable\' tasks ran; \'non-runnable\' tasks did not run.\n"); printf(" Actual: Task state:\n"); dump_global_state(); return; } // Function Specification // // Name: test_set_data_apii // // Description: Tests the API function that assigns a new data buffer to a // task in the global task list: 'rtl_set_task_data'. // // End Function Specification void test_set_data_api(void) { int i = 0; // Counter BOOLEAN l_result = FALSE; uint32_t *l_task_1_old_data_p = NULL; // Copy of original task 1 data ptr uint32_t *l_task_3_old_data_p = NULL; // Copy of original task 3 data ptr // Local copy of new run mask (odd-numbered bits set). uint32_t l_odd_run_mask = RTL_FLAG_MSTR | RTL_FLAG_OBS | RTL_FLAG_RST_REQ; // Announce which test is running. printf("\ntest_set_data_api:\n"); // Clear all task data & flags. clear_task_data_bufs(); clear_task_flags(); // Use API to set global flags. rtl_clr_run_mask(0xFFFFFFFF); rtl_set_run_mask(RTL_FLAG_RUN | l_odd_run_mask); printf(" Before task data pointers re-assigned.\n"); dump_global_state(); // Save-off old data ptrs for tasks 1 & 3. // Use API to re-assign data ptrs for ~1/2 of the tasks. // Remember: The task data pointer won't get changed if // RTL_FLAG_RUN is set in the task's flags mask. l_task_1_old_data_p = G_task_table[1].data_ptr; l_task_3_old_data_p = G_task_table[3].data_ptr; rtl_set_task_data(TASK_ID_1, &task_1_alt_data); rtl_set_task_data(TASK_ID_3, &task_3_alt_data); // To be sure we start clean, clear the task data buffers again. clear_task_data_bufs(); // Use API to set task flags so all tasks will run. for (i = 0; i < TASK_END; i++) { // Use i as i_task_id write_task_flags((task_id_t) i, l_odd_run_mask); rtl_start_task((task_id_t) i); } // Use API to check which tasks are runnable. Expect all tasks are runnable. printf(" After task data pointers re-assigned; before IRQ runs.\n"); printf(" Expect: All tasks will report as runnable.\n"); printf(" Actual: Tasks reporting as runnable: "); for (i = 0; i < TASK_END; i++) { l_result = rtl_task_is_runnable((task_id_t) i); if (l_result) { printf("%d ", i); } } printf("\n"); dump_global_state(); // Run the rtls for MAX_NUM_TICKS, then stop. rtl_run_max_ticks(); // Dump task data, task flags, global flags and CURRENT_TICK. // Dump the old task data (the ones that were de-assigned). // Expect: New task data buffers indicate the tasks ran. Old task data buffers are still cleared. printf(" After IRQ ran.\n"); printf(" Expect: All tasks will have run. Old task data buffers will still be clear.\n"); printf(" Actual: Task state:\n"); dump_global_state(); printf(" TASK_ID_1 : old data_p: [0x%p] ; old data [0x%08x]\n", l_task_1_old_data_p, *l_task_1_old_data_p); printf(" TASK_ID_3 : old data_p: [0x%p] ; old data [0x%08x]\n", l_task_3_old_data_p, *l_task_3_old_data_p); printf("\n"); // Unless you want to report a "task busy" error when you un-do the data ptr assignments, // clear your task flags here (mainly just need to clear the run flag). clear_task_flags(); // Now un-do data ptr re-assignments. rtl_set_task_data(TASK_ID_1, &task_1_data); rtl_set_task_data(TASK_ID_3, &task_3_data); return; } // Function Specification // // Name: test_thread_routine // // Description: // We run our tests in a thread so that, when a test re-enables the OCB timer for the RTLS, // the timer will actually interrupt the test, and run until it hits MAX_NUM_TICKS and // is re-disabled. At that point, the test resumes its activity and dumps the results // of the RTLS IRQ's operation. // // End Function Specification void test_thread_routine(void *private) { test_1(); test_2(); test_flags_api(); test_task_stop_api(); test_set_data_api(); // Uncomment if you want to re-enable the OCB timer for further testing // after this test suite exits. // ssx_irq_enable( PGP_IRQ_OCC_TIMER0 ); } // Function Specification // // Name: main // // Description: Entry point for running our tests. // Sets up our OCB timer and our test thread, then kicks them both off. // // End Function Specification int main(int argc, char **argv) { // Initialize Trace Buffers immediately, so they can be used // from this point on. // Initialize stdout so we can do printf from within simics env simics_stdout_create(&simics_stdout); simics_stderr_create(&simics_stderr); stdout = (FILE *)(&simics_stdout); stderr = (FILE *)(&simics_stderr); // Initialize SSX Stacks (note that this also reinitializes the time base to 0) ssx_initialize((SsxAddress)noncritical_stack, NONCRITICAL_STACK_SIZE, (SsxAddress)critical_stack, CRITICAL_STACK_SIZE, 0); // Create our test thread ssx_thread_create(&test_thread, // Thread control block (struct) test_thread_routine, // Thread function (void *)0, // Thread function arg (SsxAddress)test_thread_stack,// Stack to use for this thread THREAD_STACK_SIZE, // Size of this thread's stack THREAD_PRIORITY_0); // This thread's priority (0 is highest) // Make the test thread runnable ssx_thread_resume(&test_thread); // Start rtl code rtl_ocb_init(); // Stop the interrupt handler and initialize CURRENT_TICK (just in case). // Also set the 'testing' flag. ssx_irq_disable(PGP_IRQ_OCC_TIMER0); CURRENT_TICK = 0xFFFFFFFF; printf("\n\nmain: ocb timer stopped; waiting for first test\n"); // Enter SSX Kernel ssx_start_threads(); return 0; } <|start_filename|>src/include/registers/mcs_firmware_registers.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/common/pmlib/include/registers/mcs_firmware_registers.h $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ #if !defined(__MCS_FIRWARE_REGISTERS_H__) #define __MCS_FIRWARE_REGISTERS_H__ typedef union mcfgpr { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t mcfgprq_valid : 1; uint64_t reserved0 : 2; uint64_t disable_extended_bar : 1 ; // low = P9 mode uint64_t mcfgprq_base_address : 31; uint64_t _reserved0 : 29; #else uint64_t _reserved0 : 29; uint64_t mcfgprq_base_address : 31; uint64_t disable_extended_bar : 1 ; // low = p9 mode uint64_t reserved0 : 2; uint64_t mcfgprq_valid : 1; #endif // _BIG_ENDIAN } fields; } mcfgpr_t; typedef union mcmcicfg { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t dontCare0 : 47; uint64_t disable_channel_fail : 1; uint64_t dontCare1 : 16; #else uint64_t dontcare1 : 16; uint64_t disable_channel_fail ; 1; uint64_t dontCare0 : 47; #endif } fields; } mcmcicfg_t; typedef union mcchifir { uint64_t value; struct { #ifdef _BIG_ENDIAN uint32_t high_order; uint32_t low_order; #else uint32_t low_order; uint32_t high_order; #endif // _BIG_ENDIAN } words; struct { #ifdef _BIG_ENDIAN uint64_t fir_scom_wr_perr : 1; uint64_t fir_scom_cfg_perr : 1; uint64_t fir_dsrc_no_forward_progress : 1; uint64_t fir_dsrc_perf_degrad : 1; uint64_t fir_dmi_channel_fail : 1; uint64_t fir_channel_init_timeout : 1; uint64_t fir_channel_interlock_err : 1; uint64_t dontCare0 : 5; uint64_t fir_replay_buffer_ue : 1; uint64_t dontCare1 : 1; uint64_t fir_replay_buffer_overrun : 1; uint64_t fir_df_sm_perr : 1; uint64_t fir_cen_checkstop : 1; uint64_t dontCare2 : 15; uint64_t fir_dsff_tag_overrun : 1; uint64_t dontCare3 : 7; uint64_t fir_dsff_mca_async_cmd_error : 2; uint64_t fir_dsff_seq_error : 1; uint64_t dontCare4 : 18; uint64_t fir_dsff_timeout : 1; uint64_t dontCare5 : 2; #else uint64_t dontCare : 64; #endif // _BIG_ENDIAN } fields; } mcchifir_t; #endif <|start_filename|>src/occ_405/amec/amec_master_smh.h<|end_filename|> /* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/occ_405/amec/amec_master_smh.h $ */ /* */ /* OpenPOWER OnChipController Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _AMEC_MASTER_SMH_H #define _AMEC_MASTER_SMH_H //************************************************************************* // Includes //************************************************************************* #include <occ_common.h> #include <ssx.h> #include <ssx_app_cfg.h> #include <amec_smh.h> //************************************************************************* // Externs //************************************************************************* //************************************************************************* // Macros //************************************************************************* //************************************************************************* // Defines/Enums //************************************************************************* #define AMEC_MST_STATE() AMEC_STATE(&G_amec_mst_state); #define AMEC_MST_SUBSTATE() AMEC_SUBSTATE(&G_amec_mst_state); #define AMEC_MST_SUB_SUBSTATE() AMEC_SUB_SUBSTATE(&G_amec_mst_state); #define AMEC_MST_STATE_NEXT() AMEC_STATE_NEXT(&G_amec_mst_state); #define AMEC_MST_SUBSTATE_NEXT() AMEC_SUBSTATE_NEXT(&G_amec_mst_state); #define AMEC_MST_SUB_SUBSTATE_NEXT() AMEC_SUB_SUBSTATE_NEXT(&G_amec_mst_state); #define AMEC_MST_SET_MNFG_FMIN(a) AMEC_MST_CUR_MNFG_FMIN() = a #define AMEC_MST_SET_MNFG_FMAX(a) AMEC_MST_CUR_MNFG_FMAX() = a #define AMEC_MST_SET_MNFG_FSTEP(a) g_amec->mnfg_parms.fstep = a #define AMEC_MST_SET_MNFG_DELAY(a) g_amec->mnfg_parms.delay = a #define AMEC_MST_START_AUTO_SLEW() g_amec->mnfg_parms.auto_slew = 1 #define AMEC_MST_STOP_AUTO_SLEW() g_amec->mnfg_parms.auto_slew = 0 #define AMEC_MST_CUR_SLEW_COUNT() g_amec->mnfg_parms.slew_counter #define AMEC_MST_CUR_MNFG_FMIN() g_amec->mnfg_parms.fmin #define AMEC_MST_CUR_MNFG_FMAX() g_amec->mnfg_parms.fmax //************************************************************************* // Structures //************************************************************************* //************************************************************************* // Globals //************************************************************************* extern const smh_tbl_t amec_mst_state_table[AMEC_SMH_STATES_PER_LVL]; extern smh_state_t G_amec_mst_state; extern smh_state_timing_t G_amec_mst_state_timings; typedef struct { uint16_t active_pcap; uint8_t pcap_valid; uint8_t reserved; }slave_pcap_info_t; extern slave_pcap_info_t G_slave_active_pcaps[MAX_OCCS]; extern uint8_t G_pcaps_mismatch_count; extern uint8_t G_over_cap_count; extern uint16_t G_mst_soft_fmin; extern uint16_t G_mst_soft_fmax; //************************************************************************* // Function Prototypes //************************************************************************* void amec_mst_update_smh_sensors(int i_smh_state, uint32_t i_duration); // PRE: master common tasks void amec_mst_common_tasks_pre(void); // POST: master common tasks void amec_mst_common_tasks_post(void); // Master auto-slewing function void amec_master_auto_slew(void); // OCC Power cap mismatch function void amec_mst_check_pcaps_match(void); // Check if under power cap function void amex_mst_check_under_pcap(void); // Idle Power Saver main algorithm void amec_mst_ips_main(void); // Get the current Idle Power Saver active status uint8_t AMEC_mst_get_ips_active_status(); void amec_mst_gen_soft_freq(void); // Master States void amec_mst_state_0(void); void amec_mst_state_1(void); void amec_mst_state_2(void); void amec_mst_state_3(void); void amec_mst_state_4(void); void amec_mst_state_5(void); void amec_mst_state_6(void); void amec_mst_state_7(void); // Master SubState 5 (odd SubStates currently unused) void amec_mst_substate_5_even(void); #endif <|start_filename|>src/lib/occlib/liboccfiles.mk<|end_filename|> # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: src/lib/occlib/liboccfiles.mk $ # # OpenPOWER OnChipController Project # # Contributors Listed Below - COPYRIGHT 2015,2016 # [+] International Business Machines Corp. # # # 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. # # IBM_PROLOG_END_TAG # @file liboccfiles.mk # # @brief mk for libocc.a object files ########################################################################## # INCLUDES ########################################################################## C-SOURCES = \ ipc_core.c \ ipc_init.c \ ipc_msgq.c \ ipc_ping.c \ occhw_xir_dump.c S-SOURCES = LIBOCC_OBJECTS = $(C-SOURCES:.c=.o) $(S-SOURCES:.S=.o)
dgilbert999/occ
<|start_filename|>app/dashboard/static/js/manage_sb.js<|end_filename|> var displayEmojiTrigger; var picker; var currentOnClick; $(document).ready(() => { displayEmojiTrigger = document.querySelector("#display_emoji"); displayEmojiTrigger.addEventListener("click", () => {togglePicker(); currentOnClick = setDisplayEmoji}) picker = document.querySelector("emoji-picker"); picker.addEventListener("emoji-click", event => {togglePicker(); currentOnClick(event.detail.emoji.unicode)}); }) function setDisplayEmoji(emojiUnicode) { displayEmojiTrigger.textContent = emojiUnicode; } function togglePicker() { if (picker.classList.contains("hidden")) { picker.classList.remove("hidden"); } else { picker.classList.add("hidden"); } }
CircuitsBots/Starboard-2
<|start_filename|>shared/response.js<|end_filename|> module.exports = function(data, error){ if(error){ return error; } else return data; } <|start_filename|>Database/utility/utility.js<|end_filename|> function sendDbResponse(err, rowCount, data, callback) { if (err) { callback(err); } else { if (rowCount < 1) { callback(null, false); } else { callback(null, data, rowCount); } } } function buildRow(columns, data) { var row = {}; columns.forEach(function (column) { row[column.metadata.colName] = column.value }); data.push(row); } module.exports = { sendDbResponse: sendDbResponse, buildRow: buildRow } <|start_filename|>routes.js<|end_filename|> const express = require('express'); function eRoutes() { const router = express.Router(); var employee = require('./repository/employee/employee.routes')(router); var department = require('./repository/department/department.routes')(router); return router; } module.exports = eRoutes; <|start_filename|>repository/department/department.respository.js<|end_filename|> var response = require('../../shared/response'); var TYPES = require('tedious').TYPES; function DepartmentRepository(dbContext) { function getDepartments(req, res) { var params = []; dbContext.getQuery("select * from tbl_department", params, false, function (error, data) { return res.json(response(data, error)); }); } return { getDepartments }; } module.exports = DepartmentRepository; <|start_filename|>models/Employee.model.js<|end_filename|> var TYPES = require('tedious').TYPES; const Employee = { title: TYPES.VarChar, description: TYPES.VarChar } <|start_filename|>repository/department/department.routes.js<|end_filename|> const DepartmentRepository = require('./department.respository'); const dbContext = require('../../Database/dbContext'); module.exports = function (router) { const departmentRepository = DepartmentRepository(dbContext); router.route('/departments') .get(departmentRepository.getDepartments); }
Ruben-Tjok/NodeWithSql
<|start_filename|>SurfaceReconstruction/App/Main.cpp<|end_filename|> /* * Copyright (C) 2018 by Author: Aroudj, Samir * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #include "App/TSR.h" #include "Platform/ResourceManagement/MemoryManager.h" #include "Platform/Utilities/HelperFunctions.h" using namespace Platform; using namespace std; #ifdef MEMORY_MANAGEMENT const uint32 ResourceManagement::DEFAULT_POOL_BUCKET_NUMBER = 5; const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_CAPACITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 1024, 1024, 1024, 1024, 1024 }; const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_GRANULARITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 16, 32, 64, 128, 256 }; #endif /// MEMORY_MANAGEMENT #ifdef _WINDOWS int32 WINAPI WinMain(HINSTANCE applicationHandle, HINSTANCE unused, LPSTR commandLineArguments, int32 windowShowState) { #else int main(int argumentCount, const char *commandLineArguments[]) { #endif // _WINDOWS // do cool stuff { vector<string> arguments; #ifdef _WINDOWS Utilities::getCommandLineArguments(arguments, commandLineArguments); #else Utilities::getCommandLineArguments(arguments, commandLineArguments, argumentCount); #endif // _WINDOWS TSR application ( #ifdef _WINDOWS applicationHandle, #endif // _WINDOWS arguments ); application.run(); } #ifdef MEMORY_MANAGEMENT ResourceManagement::MemoryManager::shutDown(); #endif /// MEMORY_MANAGEMENT return 0; } <|start_filename|>SurfaceReconstruction/SurfaceReconstruction/Scene/Samples.cpp<|end_filename|> /* * Copyright (C) 2018 by Author: Aroudj, Samir * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #include "CollisionDetection/CollisionDetection.h" #include "Math/MathCore.h" #include "Math/MathHelper.h" #include "Platform/FailureHandling/Exception.h" #include "Platform/Storage/File.h" #include "Platform/Utilities/Array.h" #include "Platform/Utilities/ParametersManager.h" #include "Platform/Utilities/PlyFile.h" #include "Platform/Utilities/RandomManager.h" #include "SurfaceReconstruction/Geometry/FlexibleMesh.h" #include "SurfaceReconstruction/Scene/Camera/Cameras.h" #include "SurfaceReconstruction/Scene/FileNaming.h" #include "SurfaceReconstruction/Scene/Samples.h" #include "SurfaceReconstruction/Scene/Scene.h" using namespace FailureHandling; using namespace Graphics; using namespace Math; using namespace std; using namespace Storage; using namespace SurfaceReconstruction; using namespace Utilities; const char *Samples::MAX_RELATIVE_SAMPLING_DISTANCE = "Samples::maxRelativeSamplingDistance"; const uint32 Samples::FILE_VERSION = 0; const uint32 Samples::INVALID_INDEX = (uint32) -1; Samples::Samples(const uint32 camsPerSample, const uint32 sampleCount, const Vector3 *AABBWS) : mAABBWS{Vector3(REAL_MAX, REAL_MAX, REAL_MAX), Vector3(-REAL_MAX, -REAL_MAX, -REAL_MAX)}, mMaxRelativeSamplingDistance(1.0f), mMaxCamsPerSample(camsPerSample), mValidParentLinkCount(0) { if (sampleCount > 0) resize(sampleCount); if (AABBWS) { mAABBWS[0] = AABBWS[0]; mAABBWS[1] = AABBWS[1]; } // load parameters const ParametersManager &manager = ParametersManager::getSingleton(); bool samplingDistanceLoaded = manager.get(mMaxRelativeSamplingDistance, MAX_RELATIVE_SAMPLING_DISTANCE); if (samplingDistanceLoaded) return; // error handling string message = "Scene: Could not load parameters:\n"; if (!samplingDistanceLoaded) { message += "Samples::maxRelativeSamplingDistance"; message += ", choosing 1.0\n"; } cerr << message << endl; } Samples::Samples(const Path &fileName) : Samples((uint32) -1, 0, NULL) { loadFromFile(fileName); } Samples::~Samples() { clear(); shrinkToFit(); } void Samples::clear() { // invalidate members mAABBWS[0] = Vector3(REAL_MAX, REAL_MAX, REAL_MAX); mAABBWS[1] = Vector3(-REAL_MAX, -REAL_MAX, -REAL_MAX); mValidParentLinkCount = 0; mMaxCamsPerSample = 0; // clear vectors mColors.clear(); mNormals.clear(); mPositions.clear(); mConfidences.clear(); mScales.clear(); mParentCameras.clear(); } void Samples::shrinkToFit() { mColors.shrink_to_fit(); mNormals.shrink_to_fit(); mPositions.shrink_to_fit(); mConfidences.shrink_to_fit(); mScales.shrink_to_fit(); mParentCameras.shrink_to_fit(); } void Samples::addToAABB(Vector3 AABB[2], const uint32 sampleIdx) const { // sample AABB Vector3 sampleMin; Vector3 sampleMax; getAABBWS(sampleMin, sampleMax, sampleIdx); AABB[0] = AABB[0].minimum(sampleMin); AABB[1] = AABB[1].maximum(sampleMax); } void Samples::addSamplesViaClouds(const vector<Path> &plyCloudFileNames, const vector<uint32> &viewToCameraIndices, const Matrix3x3 &inputOrientation, const Vector3 &inputOrigin) { // load each point cloud const uint32 fileCount = (uint32) plyCloudFileNames.size(); for (uint32 fileIdx = 0; fileIdx < fileCount; ++fileIdx) addSamplesViaCloud(plyCloudFileNames[fileIdx]); // transform samples Matrix3x3 inverseRotation(inputOrientation); inverseRotation.transpose(); const Vector3 translation = -inputOrigin * inverseRotation; const uint32 sampleCount = getCount(); #pragma omp parallel for for (int64 sampleIdx = 0; sampleIdx < sampleCount; ++sampleIdx) transform((uint32) sampleIdx, inverseRotation, translation); // update and count sample to parent camera links transformViewToParentCameraLinks(viewToCameraIndices); check(); computeValidParentCameraCount(); computeAABB(); } void Samples::addSamplesViaCloud(const Path &plyCloudFileName) { // open the file #ifdef _DEBUG cout << "\nStarting loading of ply sample cloud: " << plyCloudFileName << endl; #endif // _DEBUG PlyFile file(plyCloudFileName, File::OPEN_READING, true); // process ply header & body VerticesDescription verticesFormat; file.loadHeader(verticesFormat); // process ply body cout << "Loading samples from " << plyCloudFileName << "." << endl; const uint32 loadedSamplesCount = addSamplesViaCloud(file, plyCloudFileName, verticesFormat); #ifdef _DEBUG cout << "\nFinished loading ply sample cloud, loaded " << loadedSamplesCount << " samples from cloud file." << endl; #endif // _DEBUG } uint32 Samples::addSamplesViaCloud(PlyFile &file, const Path &fileName, const VerticesDescription &verticesFormat) { // update parent links if necessary updateMaxCamerasPerSample(verticesFormat); // access vertex structure const ElementsSyntax &types = verticesFormat.getTypeStructure(); const ElementsSemantics &semantics = verticesFormat.getSemantics(); const uint32 propertyCount = verticesFormat.getPropertyCount(); const uint32 fileSampleCount = verticesFormat.getElementCount(); // reserve memory for the samples to be loaded const uint32 oldSampleCount = getCount(); const uint32 maxSampleCount = ((uint32) -1) - 1; const uint32 maxNewTotalCount = min(fileSampleCount + oldSampleCount, maxSampleCount); reserve(maxNewTotalCount); // read each sample / vertex uint32 totalCount = oldSampleCount; for (uint32 fileSampleIdx = 0; fileSampleIdx < fileSampleCount && totalCount < maxNewTotalCount; ++fileSampleIdx) { if (!file.hasLeftData()) throw FileCorruptionException("Could not read all vertices which were defined by the ply header.", fileName); // create sample addSample(); // load data for current sample for (uint32 propertyIdx = 0; propertyIdx < propertyCount; ++propertyIdx) readSampleProperty(file, totalCount, types[propertyIdx], (VerticesDescription::SEMANTICS) semantics[propertyIdx]); // ignore zero confidence samples or samples with invalid scale if (Math::EPSILON >= mConfidences.back() || Math::EPSILON >= mScales.back()) popBackSample(); else ++totalCount; } // return loaded sample count return (totalCount - oldSampleCount); } void Samples::readSampleProperty(PlyFile &file, const uint32 sampleIdx, const ElementsDescription::TYPES type, const VerticesDescription::SEMANTICS semantic) { // get sample data destinations Vector3 *color = mColors.data() + sampleIdx; Vector3 *normal = mNormals.data() + sampleIdx; Vector3 &position = mPositions[sampleIdx]; Real *confidence = mConfidences.data() + sampleIdx; Real *scale = mScales.data() + sampleIdx; uint32 *camIDs = mParentCameras.data() + mMaxCamsPerSample * sampleIdx; file.readVertexProperty(color, normal, position, NULL, confidence, scale, camIDs, type, semantic); } void Samples::addSamplesViaMeshes(const vector<FlexibleMesh *> &meshes, const vector<vector<uint32> *> &cameraIndices, const vector<uint32> &camerasPerSamples) { // only reference cameras (one camera for each sample) or larger camera set via cameraIndices? assert(meshes.size() == cameraIndices.size() && meshes.size() == camerasPerSamples.size()); const uint32 meshCount = (uint32) meshes.size(); for (uint32 meshIdx = 0; meshIdx < meshCount; ++meshIdx) updateMaxCamerasPerSample(camerasPerSamples[meshIdx]); // compute number of new samples uint64 additionalSampleCount = 0; for (uint32 meshIdx = 0; meshIdx < meshCount; ++meshIdx) if (meshes[meshIdx]) additionalSampleCount += meshes[meshIdx]->getVertexCount(); // check sample & link count & reserve memory const uint64 newSampleCount = additionalSampleCount + getCount(); checkSampleCount(newSampleCount); checkLinkCount(newSampleCount, mMaxCamsPerSample); reserve(newSampleCount); // create and add samples for each mesh for (uint32 meshIdx = 0; meshIdx < meshCount; ++meshIdx) { const vector<uint32> *const meshCameraIndices = cameraIndices[meshIdx]; if (!meshCameraIndices || !meshes[meshIdx]) { cerr << "Could not add samples for a mesh, index: " << meshIdx << "\n." << flush; continue; } addSamplesViaMesh(*meshes[meshIdx], *meshCameraIndices, camerasPerSamples[meshIdx]); } check(); computeValidParentCameraCount(); computeAABB(); } void Samples::addSamplesViaMesh(const FlexibleMesh &mesh, const std::vector<uint32> &cameraIndices, const uint32 &camerasPerSample) { const uint32 *sampleParents = cameraIndices.data(); const Real confidence = 1.0f; // todo: how to get reasonable confidence values? // add a sample for each mesh vertex const uint32 vertexCount = mesh.getVertexCount(); for (uint32 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx, sampleParents += camerasPerSample) addSample(mesh.getColor(vertexIdx), mesh.getNormal(vertexIdx), mesh.getPosition(vertexIdx), confidence, mesh.getScale(vertexIdx), sampleParents, camerasPerSample); } void Samples::check() const { const int64 sampleCount = getCount(); // check sample scale / samples' 3D footprint sizes #pragma omp parallel for for (int64 sampleIdx = 0; sampleIdx < sampleCount; ++sampleIdx) { const Real &scale = getScale((uint32) sampleIdx); assert(scale > 0.0f); if (scale <= 0.0f) throw Exception("Invalid (non-positive) sample scale detected."); } } void Samples::computeAABB() { mAABBWS[0].set(REAL_MAX, REAL_MAX, REAL_MAX); mAABBWS[1].set(-REAL_MAX, -REAL_MAX, -REAL_MAX); const uint32 sampleCount = (uint32) mNormals.size(); for (uint32 sampleIdx = 0; sampleIdx < sampleCount; ++sampleIdx) addToAABB(mAABBWS, sampleIdx); } void Samples::compact(const uint32 *sampleOffsets) { // counts for filling const uint32 oldSampleCount = getCount(); const uint32 doomedSampleCount = sampleOffsets[oldSampleCount]; const uint32 newSampleCount = oldSampleCount - doomedSampleCount; cout << "Deleting " << doomedSampleCount << " of " << oldSampleCount << " samples, remaining: " << newSampleCount << " samples." << endl; Array<Vector3>::compaction(mColors, sampleOffsets); Array<Vector3>::compaction(mNormals, sampleOffsets); Array<Vector3>::compaction(mPositions, sampleOffsets); Array<Real>::compaction(mConfidences, sampleOffsets); Array<Real>::compaction(mScales, sampleOffsets); Array<uint32>::compaction(mParentCameras, sampleOffsets, mMaxCamsPerSample); computeValidParentCameraCount(); computeAABB(); cout << "Finished deletion of samples. " << endl; } bool Samples::computeMeans(Vector3 &meanColor, Vector3 &meanNormal, Vector3 &meanPosition, Real &meanScale, const vector<uint32> &sampleSet, bool weightedByConfidences) const { // weighted mean data of sample set const Real MIN_LENGTH_NORMALS = 0.5f; // todo magic number // initial mean values meanColor.set(0.0f, 0.0f, 0.0f); meanPosition.set(0.0f, 0.0f, 0.0f); meanNormal.set(0.0f, 0.0f, 0.0f); meanScale = 0.0f; const uint32 count = (uint32) sampleSet.size(); Real sum = 0.0f; for (uint32 i = 0; i < count; ++i) { const uint32 index = sampleSet[i]; const Vector3 &color = mColors[index]; const Vector3 &normal = mNormals[index]; const Vector3 &position = mPositions[index]; const Real confidence = mConfidences[index]; const Real scale = mScales[index]; const Real weight = (weightedByConfidences ? mConfidences[index] : 1.0f); meanColor += color * weight; meanNormal += normal * weight; meanPosition += position * weight; meanScale += scale * weight; sum += weight; } // normalized results const Real normFactor = 1.0f / sum; meanColor *= normFactor; meanNormal *= normFactor; meanPosition *= normFactor; meanScale *= normFactor; const Real lengthSq = meanNormal.getLengthSquared(); meanNormal /= sqrtr(lengthSq); // small distribution of sample normals? // it does not make sense to compute a model if sample oriantations are too chaotic return (lengthSq >= MIN_LENGTH_NORMALS * MIN_LENGTH_NORMALS); // todo magic number } bool Samples::computeViewAngles(Real &azimuthAngle, Real &polarAngle, const uint32 parentCameraIdx, const uint32 sampleIdx) const { // bad default values if something goes wrong azimuthAngle = -REAL_MAX; polarAngle = -REAL_MAX; Vector3 viewDirection; if (!computeViewDirection(viewDirection, parentCameraIdx, sampleIdx)) return false; Math::transformCartesianToSpherical(azimuthAngle, polarAngle, viewDirection); return true; } bool Samples::computeViewDirection(Vector3 &viewDirection, const uint32 parentCameraIdx, const uint32 sampleIdx) const { // bad default values if something goes wrong viewDirection.set(-REAL_MAX, -REAL_MAX, REAL_MAX); // check parent view index assert(parentCameraIdx < mMaxCamsPerSample); if (parentCameraIdx >= mMaxCamsPerSample) throw Exception("Invalid parentCameraIdx for a sample."); // valid parent view? const Scene &scene = Scene::getSingleton(); const Cameras &cameras = scene.getCameras(); const uint32 cameraIdx = getCameraIdx(parentCameraIdx, sampleIdx); if (!cameras.isValid(cameraIdx)) return false; // compute view direction const Vector3 &camWS = cameras.getPositionWS(cameraIdx); viewDirection = mPositions[sampleIdx] - Vector3(camWS.x, camWS.y, camWS.z); viewDirection.normalize(); return true; } void Samples::erase(const vector<uint32> theDoomed, const uint32 doomedCount) { // todo improve this - in place compaction does not make sense as resize is called later anyway // replace this with compact? const uint32 parentCameraBytes = sizeof(uint32) * mMaxCamsPerSample; const uint32 temp = (uint32) theDoomed.size(); uint32 numRemovedSamples = 0; for (uint32 i = 0; i < temp - 1; i += 2) { const uint32 targetIdx = theDoomed[i] - numRemovedSamples; const uint32 doomedCount = theDoomed[i + 1]; const uint32 sourceIdx = theDoomed[i] + doomedCount; const uint32 next = theDoomed[i + 2]; const uint32 moveCount = next - sourceIdx; if (0 == moveCount && next == getCount()) continue; memcpy(&mColors[targetIdx], &mColors[sourceIdx], sizeof(Vector3) * moveCount); memcpy(&mNormals[targetIdx], &mNormals[sourceIdx], sizeof(Vector3) * moveCount); memcpy(&mPositions[targetIdx], &mPositions[sourceIdx], sizeof(Vector3) * moveCount); memcpy(&mConfidences[targetIdx], &mConfidences[sourceIdx], sizeof(Real) * moveCount); memcpy(&mScales[targetIdx], &mScales[sourceIdx], sizeof(Real) * moveCount); memcpy(&mParentCameras[targetIdx * mMaxCamsPerSample], &mParentCameras[sourceIdx * mMaxCamsPerSample], parentCameraBytes * moveCount); numRemovedSamples += doomedCount; } resize(getCount() - doomedCount); computeValidParentCameraCount(); computeAABB(); } void Samples::getAABBWS(Vector3 &minWS, Vector3 &maxWS, const uint32 sampleIdx) const { const Vector3 &p = mPositions[sampleIdx]; const Real r = getMaxSamplingDistance(sampleIdx) + EPSILON; minWS.set(p.x - r, p.y - r, p.z - r); maxWS.set(p.x + r, p.y + r, p.z + r); } Real Samples::getDistanceToPlane(const Vector3 &pWS, const uint32 sampleIdx) const { CollisionDetection::Plane plane(mPositions[sampleIdx], mNormals[sampleIdx], true); return plane.getDistanceToPlane(pWS); } Real Samples::getFSSRWeight(const Math::Vector3 &pWS, const uint32 sampleIdx) const { const Vector3 vSS = toSampleSpace(pWS, sampleIdx); const Real s = mScales[sampleIdx]; // FSSR weighting function: weightX along x axis * weightY along y axis const Real range = 3.0f * s; const Real scaleSq = s * s; const Real scaleCu = scaleSq * s; const Real xSq = vSS.x * vSS.x; Real weight = 0.0f; // weight along normal if (vSS.x > -range && vSS.x < 0.0f) weight = xSq / (9.0f * scaleSq) + 2.0f * vSS.x / range + 1.0f; else if (vSS.x >= 0.0f && vSS.x < range) weight = 2.0f * xSq * vSS.x / (27.0f * scaleCu) - xSq / (3.0f * scaleSq) + 1.0f; else return 0.0f; // weight along tangent const Real tSq = vSS.y * vSS.y + vSS.z * vSS.z; const Real t = sqrtr(tSq); if (t < range) weight *= 2.0f * tSq * t / (27.0f * scaleCu) - tSq / (3.0f * scaleSq) + 1.0f; else return 0.0f; return weight; } Real Samples::getMeasureDistanceSquared(const uint32 sampleIdx, const uint32 parentCameraIdx) const { // get parent camera position const uint32 globalCameraIdx = getCameraIdx(parentCameraIdx, sampleIdx); const Cameras &cameras = Scene::getSingleton().getCameras(); const Vector3 &camPosWS = cameras.getPositionWS(globalCameraIdx); // measurement distance / sample depth const Vector3 camToSample = getPositionWS(sampleIdx) - camPosWS; const Real distanceSq = camToSample.getLengthSquared(); return distanceSq; } uint32 Samples::getCameraIdx(const uint32 parentCameraIdx, const uint32 sampleIdx) const { // sanity checks const uint32 sampleCount = getCount(); assert(parentCameraIdx < mMaxCamsPerSample); assert(sampleIdx < sampleCount); if (parentCameraIdx >= mMaxCamsPerSample || sampleIdx >= sampleCount) return Cameras::INVALID_ID; else return mParentCameras[sampleIdx * mMaxCamsPerSample + parentCameraIdx]; } void Samples::setSample(const uint32 targetIdx, const Vector3 &color, const Vector3 &normal, const Vector3 &positionWS, const Real &confidence, const Real &scale, const uint32 *parentCameraIDs, const uint32 &parentCameraCount) { // update simple sample attributes mColors[targetIdx] = color; mNormals[targetIdx] = normal; mPositions[targetIdx] = positionWS; mConfidences[targetIdx] = confidence; mScales[targetIdx] = scale; // update parent cameras and valid parent camera count uint32 *parentCameras = mParentCameras.data() + targetIdx * mMaxCamsPerSample; // copy cameras for (uint32 i = 0; i < mMaxCamsPerSample && i < parentCameraCount; ++i) { // is a parent camera added or erased? if (Cameras::INVALID_ID == parentCameras[i] && Cameras::INVALID_ID != parentCameraIDs[i]) ++mValidParentLinkCount; else if (Cameras::INVALID_ID != parentCameras[i] && Cameras::INVALID_ID == parentCameraIDs[i]) --mValidParentLinkCount; parentCameras[i] = parentCameraIDs[i]; } // fill remaining links with invalid indices for (uint32 i = parentCameraCount; i < mMaxCamsPerSample; ++i) parentCameras[i] = INVALID_INDEX; } void Samples::makeNoisy(normal_distribution<Real> noise[3], const uint32 sampleIdx) { // get necessary variables RandomManager &random = RandomManager::getSingleton(); Vector3 &normal = mNormals[sampleIdx]; Vector3 &position = mPositions[sampleIdx]; Real &scale = mScales[sampleIdx]; // get view direction Vector3 viewDirection; if (!computeViewDirection(viewDirection, 0, sampleIdx)) { // todo log this viewDirection.set(random.getNormal(noise[2]), random.getNormal(noise[2]), random.getNormal(noise[2])); viewDirection.normalize(); } // add noise to position const Real positionNoise = scale * random.getNormal(noise[0]); position += viewDirection * positionNoise; // add noise to scale const Real f = 1.0f + random.getNormal(noise[1]); scale = scale * Math::clamp<Real>(f, 1.75f, 0.25f); // add noise to normal Real azimuth; Real polar; Math::transformCartesianToSpherical(azimuth, polar, normal, 1.0f); azimuth += random.getNormal(noise[2]); polar += random.getNormal(noise[2]); Math::transformSphericalToCartesian(normal, azimuth, polar, 1.0f); } uint32 Samples::addSample() { // compute & check new sample count const uint32 sampleIdx = (uint32) mNormals.size(); const uint64 count = sampleIdx + 1; checkSampleCount(count); checkLinkCount(count, mMaxCamsPerSample); // resize containers mColors.resize(count); mNormals.resize(count); mPositions.resize(count); mConfidences.resize(count, 1.0f); mScales.resize(count); mParentCameras.resize(count * mMaxCamsPerSample, INVALID_INDEX); return sampleIdx; } void Samples::invalidateParentCameras(const uint32 sampleIdx) { const uint32 offset = sampleIdx * mMaxCamsPerSample; for (uint32 i = 0; i < mMaxCamsPerSample; ++i) mParentCameras[offset + i] = Cameras::INVALID_ID; } void Samples::deleteSample(const uint32 sampleIdx) { // swap last sample with replacedIdx and erase the last (replacedIdx) const uint32 lastSampleIdx = (uint32) mNormals.size() - 1; swap(sampleIdx, lastSampleIdx); popBackSample(); } void Samples::popBackSample() { // erase last sample from all containers mColors.pop_back(); mNormals.pop_back(); mPositions.pop_back(); mConfidences.pop_back(); mScales.pop_back(); // erase parent cameras & reduce the number of parent cameras accordingly const uint32 vectorSize = (uint32) mParentCameras.size(); uint32 erasedParentViewsCount = 0; for (uint32 parentCameraIdx = vectorSize - mMaxCamsPerSample; parentCameraIdx < vectorSize; ++parentCameraIdx) if (Cameras::INVALID_ID != mParentCameras[parentCameraIdx]) ++erasedParentViewsCount; mParentCameras.resize(mParentCameras.size() - mMaxCamsPerSample); mValidParentLinkCount -= erasedParentViewsCount; } void Samples::reserve(const uint64 sampleCount) { // check new counts checkSampleCount(sampleCount); checkLinkCount(sampleCount, mMaxCamsPerSample); // reserve memory mColors.reserve(sampleCount); mNormals.reserve(sampleCount); mPositions.reserve(sampleCount); mConfidences.reserve(sampleCount); mScales.reserve(sampleCount); mParentCameras.reserve(sampleCount * mMaxCamsPerSample); } void Samples::swap(const uint32 i, const uint32 j) { // same sample? if (i == j) return; // swap everything belonging to the two samples i and j // swap color, normal, position & scale Utilities::swap(mColors[i], mColors[j]); Utilities::swap(mNormals[i], mNormals[j]); Utilities::swap(mPositions[i], mPositions[j]); Utilities::swap(mConfidences[i], mConfidences[j]); Utilities::swap(mScales[i], mScales[j]); // update camera indices const uint32 offsetI = i * mMaxCamsPerSample; const uint32 offsetJ = j * mMaxCamsPerSample; uint32 *cameraI = mParentCameras.data() + (i * mMaxCamsPerSample); uint32 *cameraJ = mParentCameras.data() + (j * mMaxCamsPerSample); for (uint32 cameraIdx = 0; cameraIdx < mMaxCamsPerSample; ++cameraIdx, ++cameraI, ++cameraJ) Utilities::swap(*cameraI, *cameraJ); } Vector3 Samples::toSampleSpace(const Vector3 &pWS, const uint32 sampleIdx) const { // transform to sample space "SS" which depends on sample position and orientation Matrix3x3 offsetWSToSS = Matrix3x3::createBasisFromVector(mNormals[sampleIdx]); offsetWSToSS.transpose(); // convert pWS into coordinate system(mPosition, mNormal, tangent0, tangent1) const Vector3 offsetWS = pWS - mPositions[sampleIdx]; const Vector3 pSS = offsetWS * offsetWSToSS; return pSS; } void Samples::transform(const uint32 sampleIdx, const Matrix3x3 &transformation, const Vector3 &translation) { mNormals[sampleIdx] = mNormals[sampleIdx] * transformation; mPositions[sampleIdx] = (mPositions[sampleIdx] * transformation + translation); } void Samples::loadFromFile(const Path &fileName) { clear(); cout << "Loading samples from file " << fileName << "." << endl; // open file & check version File file(fileName, File::OPEN_READING, true, FILE_VERSION); // get #samples & #cameras per sample & request memory uint32 sampleCount; file.read(&sampleCount, sizeof(uint32), sizeof(uint32), 1); file.read(&mMaxCamsPerSample, sizeof(uint32), sizeof(uint32), 1); file.read(mAABBWS, sizeof(Vector3) * 2, sizeof(Vector3), 2); if (sampleCount != mNormals.capacity()) { shrinkToFit(); resize(sampleCount); } // load samples uint32 parentCount = sampleCount * mMaxCamsPerSample; file.read(mColors.data(), sizeof(Vector3) * sampleCount, sizeof(Vector3), sampleCount); file.read(mNormals.data(), sizeof(Vector3) * sampleCount, sizeof(Vector3), sampleCount); file.read(mPositions.data(), sizeof(Vector3) * sampleCount, sizeof(Vector3), sampleCount); file.read(mConfidences.data(), sizeof(Real) * sampleCount, sizeof(Real), sampleCount); file.read(mScales.data(), sizeof(Real) * sampleCount, sizeof(Real), sampleCount); file.read(mParentCameras.data(), sizeof(uint32) * parentCount, sizeof(uint32), parentCount); computeValidParentCameraCount(); cout << "Loaded " << getCount() << " samples." << endl; } void Samples::saveToFile(const Path &beginning, const bool saveAsPly, const bool saveAsSamples) const { // is there anything to save? if (mNormals.empty()) return; // as Stanford ply mesh? if (saveAsPly) { const Path fileName = Path::extendLeafName(beginning, FileNaming::ENDING_PLY); PlyFile file(fileName, File::CREATE_WRITING, true); file.saveTriangleMesh(ENCODING_BINARY_LITTLE_ENDIAN, true, getCount(), 0, mColors.data(), mNormals.data(), mPositions.data(), mConfidences.data(), mScales.data(), mParentCameras.data(), mMaxCamsPerSample, NULL); } // internal mesh format? if (saveAsSamples) { // create file & write version const Path fileName = Path::extendLeafName(beginning, FileNaming::ENDING_SAMPLES); File file(fileName, File::CREATE_WRITING, true, FILE_VERSION); // save sample count, cameras per sample & AABB const uint32 sampleCount = (uint32) mNormals.size(); file.write(&sampleCount, sizeof(uint32), 1); file.write(&mMaxCamsPerSample, sizeof(uint32), 1); file.write(mAABBWS, sizeof(Vector3), 2); // save all samples file.write(mColors.data(), sizeof(Vector3), sampleCount); file.write(mNormals.data(), sizeof(Vector3), sampleCount); file.write(mPositions.data(), sizeof(Vector3), sampleCount); file.write(mConfidences.data(), sizeof(Real), sampleCount); file.write(mScales.data(), sizeof(Real), sampleCount); file.write(mParentCameras.data(), sizeof(uint32), sampleCount * mMaxCamsPerSample); } } void Samples::resize(const uint32 sampleCount) { // still valid indices? checkSampleCount(sampleCount); checkLinkCount(sampleCount, mMaxCamsPerSample); // resize memory const uint32 oldCount = (uint32) mColors.size(); mColors.resize(sampleCount); mNormals.resize(sampleCount); mPositions.resize(sampleCount); mConfidences.resize(sampleCount, 1.0f); mScales.resize(sampleCount, 0.0f); mParentCameras.resize(sampleCount * mMaxCamsPerSample); // invalid cameras for all new samples if (sampleCount <= oldCount) return; // set invalid camera indices const uint32 newSamples = sampleCount - oldCount; const size_t byteCount = newSamples * mMaxCamsPerSample * sizeof(uint32); memset(mParentCameras.data() + oldCount * mMaxCamsPerSample, Cameras::INVALID_ID, byteCount); } void Samples::transformViewToParentCameraLinks(const vector<uint32> &viewToCameraIndices) { // update each link const int64 linkCount = getCount() * mMaxCamsPerSample; #pragma omp parallel for for (int64 linkIdx = 0; linkIdx < linkCount; ++linkIdx) { const uint32 viewID = mParentCameras[linkIdx]; if (Cameras::INVALID_ID != viewID) mParentCameras[linkIdx] = viewToCameraIndices[viewID]; } } void Samples::computeValidParentCameraCount() { // get & check parent link count uint64 linkCount = mMaxCamsPerSample * getCount(); if (linkCount >= (uint32) -1) throw Exception("Number of sample to parent camera links exceeds supported maximum = 2^32 - 2."); const uint32 parentCount = (uint32) linkCount; // count number of valid parent links uint32 invalidCount = 0; for (uint32 parentIdx = 0; parentIdx < parentCount; ++parentIdx) if (Cameras::INVALID_ID == mParentCameras[parentIdx]) ++invalidCount; mValidParentLinkCount = parentCount - invalidCount; cout << "Computed number of valid parent cameras for all samples.\n"; cout << "Parent camera count: " << mValidParentLinkCount << "; invalid view link count: " << invalidCount << "; parent view link count: " << getCount() * mMaxCamsPerSample << endl; } void Samples::reorder(const uint32 *targetIndices) { const uint32 sampleCount = getCount(); Array<Vector3>::reorder(mColors, targetIndices); Array<Vector3>::reorder(mNormals, targetIndices); Array<Vector3>::reorder(mPositions, targetIndices); Array<Real>::reorder(mConfidences, targetIndices); Array<Real>::reorder(mScales, targetIndices); Array<uint32>::reorder(mParentCameras, targetIndices, mMaxCamsPerSample); } void Samples::updateMaxCamerasPerSample(const VerticesDescription &verticesFormat) { const ElementsSemantics &semantics = verticesFormat.getSemantics(); const uint32 propertyCount = verticesFormat.getPropertyCount(); uint32 camerasPerSample = 0; for (uint32 propertyIdx = 0; propertyIdx < propertyCount; ++propertyIdx) if (semantics[propertyIdx] >= VerticesDescription::SEMANTIC_VIEWID0) ++camerasPerSample; updateMaxCamerasPerSample(camerasPerSample); } bool Samples::updateMaxCamerasPerSample(const uint32 camerasPerSample) { // no increase? if (camerasPerSample <= mMaxCamsPerSample) return false; // more links const uint32 oldMaxCamsPerSample = mMaxCamsPerSample; checkLinkCount(getCount(), camerasPerSample); mMaxCamsPerSample = camerasPerSample; // no update of links buffer necesary? if (empty()) return true; // new links buffer const uint32 sampleCount = getCount(); const int64 newParentsCount = sampleCount * mMaxCamsPerSample; vector<uint32> newParentCameras(newParentsCount); // copy old parent links and fill new gaps with invalid IDs const uint32 oldBytesPerParentsBlock = sizeof(uint32) * oldMaxCamsPerSample; const uint32 gapBytesForNewLinks = sizeof(uint32) * (mMaxCamsPerSample - oldMaxCamsPerSample); #pragma omp parallel for for (int64 sampleIdx = 0; sampleIdx < sampleCount; ++sampleIdx) { uint32 *targetStart = newParentCameras.data() + sampleIdx * mMaxCamsPerSample; const uint32 *sourceStart = mParentCameras.data() + sampleIdx * oldMaxCamsPerSample; // copy old links & fill gaps for new links with INVALID_INDEX memcpy(targetStart, sourceStart, oldBytesPerParentsBlock); memset(targetStart + oldMaxCamsPerSample, INVALID_INDEX, gapBytesForNewLinks); } mParentCameras.swap(newParentCameras); return true; } void Samples::checkLinkCount(const uint64 &newSampleCount, const uint32 &newMaxCamerasPerSample) const { const uint64 newLinkCount = (uint64) newSampleCount * (uint64) newMaxCamerasPerSample; if (newLinkCount < INVALID_INDEX) return; assert(false); throw Exception("Link count (sample to camera links) is larger than 2^32 - 1 which is not supported."); } void Samples::checkSampleCount(const uint64 &newSampleCount) const { if (newSampleCount < INVALID_INDEX) return; assert(false); throw Exception("Sample count is larger than 2^32 - 1 which is not supported."); }
namibj/TSR
<|start_filename|>examples/text-classification/ltp_configs/threshold.json<|end_filename|> { "_num_labels": 3, "architectures": [ "LTPForSequenceClassification" ], "attention_probs_dropout_prob": 0.1, "bos_token_id": 0, "eos_token_id": 2, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 1024, "id2label": { "0": "CONTRADICTION", "1": "NEUTRAL", "2": "ENTAILMENT" }, "initializer_range": 0.02, "intermediate_size": 4096, "label2id": { "CONTRADICTION": 0, "NEUTRAL": 1, "ENTAILMENT": 2 }, "layer_norm_eps": 1e-05, "max_position_embeddings": 514, "model_type": "ltp", "num_attention_heads": 16, "num_hidden_layers": 24, "pad_token_id": 1, "tokenizer_class": "RobertaTokenizer", "type_vocab_size": 1, "vocab_size": 50265, "quant_mode": false, "prune_mode": "threshold", "token_threshold": 0.008 }
kssteven418/LTP
<|start_filename|>lib/scrollbar_behavior_enum.dart<|end_filename|> // Scrollbar behavior values enum scrollbarBehavior { HIDE, SHOW, SHOW_ALWAYS }
shareef-dweikat/flutter-intro-slider
<|start_filename|>config.h<|end_filename|> #define HAVE_DECL_BE64ENC 0 #define HAVE_INTTYPES_H 1 #define HAVE_POSIX_MEMALIGN 1 #define HAVE_STDINT_H 1 #define HAVE_STDLIB_H 1 #define HAVE_STRING_H 1 #define HAVE_SYS_STAT_H 1 #define HAVE_SYS_TYPES_H 1 #define HAVE_UNISTD_H 1 #define PACKAGE "scrypt" #define PACKAGE_BUGREPORT "" #define PACKAGE_NAME "scrypt" #define PACKAGE_STRING "scrypt 1.1.6" #define PACKAGE_TARNAME "scrypt" #define PACKAGE_VERSION "1.1.6" #define STDC_HEADERS 1 #define VERSION "1.1.6"
iamjstates/js-scrypt
<|start_filename|>src/test/java/uk/gov/nationalarchives/utf8/validator/Utf8ValidatorTest.java<|end_filename|> /* * Copyright © 2011, The National Archives <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.gov.nationalarchives.utf8.validator; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * @author <NAME> <<EMAIL>> */ @RunWith(Parameterized.class) public class Utf8ValidatorTest { @Parameterized.Parameters(name = "{0}") public static java.util.Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"classic", false}, {"memory-mapped", true} }); } @Parameterized.Parameter(value = 0) public String name; @Parameterized.Parameter(value = 1) public boolean memoryMappedIo; @Test public void validOneByteChar() throws IOException, ValidationException, URISyntaxException { //character 'x' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("valid-one-byte-char.bin")); } @Test(expected = ValidationException.class) public void invalidOneByteChar() throws IOException, ValidationException, URISyntaxException { //first byte from 'e accute' two byte character new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-one-byte-char.bin")); } @Test public void validTwoByteChar() throws IOException, ValidationException, URISyntaxException { //character 'copyright symbol' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("valid-two-byte-char.bin")); } @Test(expected = ValidationException.class) public void invalidTwoByteChar() throws IOException, ValidationException, URISyntaxException { //first byte from 'copyright symbol' and then byte from 'x' character new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-two-byte-char.bin")); } @Test(expected = ValidationException.class) public void invalidTwoByteChar2() throws IOException, ValidationException, URISyntaxException { //first byte from 'x' character and then first byte from 'copyright symbol' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-two-byte-char-2.bin")); } @Test public void validThreeByteChar() throws IOException, ValidationException, URISyntaxException { //character 'euro symbol' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("valid-three-byte-char.bin")); } @Test(expected = ValidationException.class) public void invalidThreeByteChar() throws IOException, ValidationException, URISyntaxException { //first two bytes from 'euro symbol' and then byte from 'x' character new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-three-byte-char.bin")); } @Test(expected = ValidationException.class) public void invalidThreeByteChar2() throws IOException, ValidationException, URISyntaxException { //first byte from 'euro symbol', then byte from 'x' character, then second byte from 'euro symbol' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-three-byte-char-2.bin")); } @Test(expected = ValidationException.class) public void invalidThreeByteChar3() throws IOException, ValidationException, URISyntaxException { //byte from character 'x' and the first two bytes from 'euro symbol' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-three-byte-char-3.bin")); } @Test public void validFourByteChar() throws IOException, ValidationException, URISyntaxException { //character 'domino tile horizontal black' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("valid-four-byte-char.bin")); } @Test(expected = ValidationException.class) public void invalidFourByteChar() throws IOException, ValidationException, URISyntaxException { //first three bytes from character 'domino tile horizontal black', then the byte from character(x) new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-four-byte-char.bin")); } @Test(expected = ValidationException.class) public void oneInvalidOneByteChar_followedByTwoValidOneByteChars() throws IOException, ValidationException, URISyntaxException { //characters: invalid char, 'comma', 'c' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-mixed-1.bin")); } @Test(expected = ValidationException.class) public void oneValidOneByteChar_oneInvalidOneByteChar_followedByOneValidOneByteChar() throws IOException, ValidationException, URISyntaxException { //characters: 'comma', invalid char, 'c' new Utf8Validator(memoryMappedIo, new PrintingValidationHandler(true, System.out)) .validate(testResource("invalid-mixed-2.bin")); } private File testResource(final String filename) throws URISyntaxException { final URL resource = getClass().getResource(filename); return new File(resource.toURI()); } } <|start_filename|>src/main/java/uk/gov/nationalarchives/utf8/validator/PrintingValidationHandler.java<|end_filename|> /* * Copyright © 2011, The National Archives <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.gov.nationalarchives.utf8.validator; import java.io.PrintStream; /** * Example ValidationHandler which prints its errors to an output PrintStream * It also has the ability to fail-fast by aborting processing * upon the first error. * It is used by the Utf8ValidateCmd. * * @author <NAME> <<EMAIL>> */ public class PrintingValidationHandler implements ValidationHandler { private final boolean failFast; private final PrintStream output; private boolean errored = false; public PrintingValidationHandler(final boolean failFast, final PrintStream output) { this.failFast = failFast; this.output = output; } @Override public void error(final String message, final long byteOffset) throws ValidationException { errored = true; if(failFast) { throw new ValidationException(message, byteOffset); } else { output.println("[ERROR] " + message + " @ byte position: " + byteOffset); } } public boolean isErrored() { return errored; } } <|start_filename|>src/main/java/uk/gov/nationalarchives/utf8/validator/Utf8ValidateCmd.java<|end_filename|> /* * Copyright © 2011, The National Archives <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.gov.nationalarchives.utf8.validator; import java.io.File; import java.io.IOException; /** * UTF-8 Validator Command Line * * @author <NAME> <<EMAIL>> * @version 1.2 */ public class Utf8ValidateCmd { final static String VERSION = "1.2"; /** * @param args the command line arguments */ public static void main(final String[] args) { //check useage if(args.length < 1) { System.out.println("UTF-8 Validator version: " + VERSION); System.out.println("Usage: utf8validate [options] <file>"); System.out.println(""); System.out.println("\t-f | --fail-fast"); System.out.println("\t\tStops on the first validation error rather than reporting all errors. Default false"); System.out.println("\t-b | --buffer-size"); System.out.println("\t\tSize of the in-memory buffer for file data (in bytes). Default 8192"); System.out.println("\t-m | --mem-mapped"); System.out.println("\t\tUse memory mapped Disk I/O. Default false"); System.out.println(""); System.exit(ExitCode.INVALID_ARGS.getCode()); } //parse args boolean failFast = false; int bufferSize = -1; boolean memMapped = false; final File fileToValidate; // parse args for (int i = 0; i < args.length - 1; i++) { if(args[i].equals("-f") || args[i].equals("--fail-fast")) { failFast = true; } if(args[i].equals("-b") || args[i].equals("--buffer-size")) { bufferSize = Integer.parseInt(args[++i]); } if(args[i].equals("-m") || args[i].equals("--mem-mapped")) { memMapped = true; } } fileToValidate = new File(args[args.length - 1]); if(!fileToValidate.exists()) { System.out.println("File: " + fileToValidate.getPath() + " does not exist!"); System.exit(ExitCode.INVALID_ARGS.getCode()); } final PrintingValidationHandler handler = new PrintingValidationHandler(failFast, System.out); ExitCode result = ExitCode.OK; final long start = System.currentTimeMillis(); System.out.println("Validating: " + fileToValidate.getPath()); try { new Utf8Validator(memMapped, bufferSize, handler).validate(fileToValidate); if(!failFast && handler.isErrored()) { result = ExitCode.VALIDATION_ERROR; } else { System.out.println("Valid OK (took " + (System.currentTimeMillis() - start) + "ms)"); result = ExitCode.OK; } } catch(final ValidationException ve) { System.out.println(ve.getMessage()); result = ExitCode.VALIDATION_ERROR; } catch(final IOException ioe) { System.err.println("[ERROR]" + ioe.getMessage()); result = ExitCode.IO_ERROR; } System.exit(result.getCode()); } }
digital-preservation/utf8-validator
<|start_filename|>test/ownable-contract.js<|end_filename|> const { shouldBehaveLikeOwnable } = require('./ownable.behavior.js'); const Ownable = artifacts.require('./mintable_token.vyper'); contract('Ownable', function (accounts) { beforeEach(async function () { this.ownable = await Ownable.new(web3.fromAscii("Name"), web3.fromAscii("SYMBOL"), 10000, 10000, 18); }); shouldBehaveLikeOwnable(accounts); }); <|start_filename|>test/token-time-lock.js<|end_filename|> const { latestTime } = require('./helpers/latestTime'); const { increaseTimeTo, duration } = require('./helpers/increaseTime'); const { expectThrow } = require('./helpers/expectThrow'); const BigNumber = web3.BigNumber; require('chai') .use(require('chai-bignumber')(BigNumber)) .should(); const MintableToken = artifacts.require('mintable_token.vyper'); const TokenTimelock = artifacts.require('token_timelock.vyper'); contract('TokenTimelock', function ([_, owner, beneficiary]) { const amount = new BigNumber(100); beforeEach(async function () { this.token = await MintableToken.new(web3.fromAscii("Name"), web3.fromAscii("SYMBOL"), 0, 10000000, 18, { from: owner }); this.releaseTime = (await latestTime()) + duration.years(1); this.timelock = await TokenTimelock.new(this.token.address, beneficiary, this.releaseTime); await this.token.mint(this.timelock.address, amount, { from: owner }); }); it('initializes with correct balance', async function () { const balance = await this.token.balanceOf(this.timelock.address); balance.should.be.bignumber.equal(amount); }); it('cannot be released before time limit', async function () { await expectThrow(this.timelock.release({from: beneficiary})); }); it('cannot be released just before time limit', async function () { await increaseTimeTo(this.releaseTime - duration.seconds(3)); await expectThrow(this.timelock.release({from: beneficiary})); }); it('can be released just after limit', async function () { await increaseTimeTo(this.releaseTime + duration.seconds(1)); await this.timelock.release({from: beneficiary}); const balance = await this.token.balanceOf(beneficiary); balance.should.be.bignumber.equal(amount); }); it('can be released after time limit', async function () { await increaseTimeTo(this.releaseTime + duration.years(1)); await this.timelock.release({from: beneficiary}); const balance = await this.token.balanceOf(beneficiary); balance.should.be.bignumber.equal(amount); }); it('cannot be released twice', async function () { await increaseTimeTo(this.releaseTime + duration.years(1)); await this.timelock.release({from: beneficiary}); await expectThrow(this.timelock.release({from: beneficiary})); const balance = await this.token.balanceOf(beneficiary); balance.should.be.bignumber.equal(amount); }); }); <|start_filename|>test/burnable-token.js<|end_filename|> const BurnableToken = artifacts.require('./burnable_token.vyper'); const { assertRevert } = require('./helpers/assertRevert'); const { inLogs } = require('./helpers/expectEvent'); const BigNumber = web3.BigNumber; const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; require('chai') .use(require('chai-bignumber')(BigNumber)) .should(); contract('burnable_token', function ([owner]) { const initialBalance = 1000; beforeEach(async function () { this.token = await BurnableToken.new(web3.fromAscii("Name"), web3.fromAscii("SYMBOL"), initialBalance, 18); }); describe('as a basic burnable token', function () { const from = owner; describe('when the given amount is not greater than balance of the sender', function () { const amount = 100; beforeEach(async function () { ({ logs: this.logs } = await this.token.burn(amount, { from })); }); it('burns the requested amount', async function () { const balance = await this.token.balanceOf(from); balance.should.be.bignumber.equal(initialBalance - amount); }); it('emits a burn event', async function () { const event = await inLogs(this.logs, 'Burn'); event.args._burner.should.eq(owner); event.args._value.should.be.bignumber.equal(amount); }); it('emits a transfer event', async function () { const event = await inLogs(this.logs, 'Transfer'); event.args._from.should.eq(owner); event.args._to.should.eq(ZERO_ADDRESS); event.args._value.should.be.bignumber.equal(amount); }); }); describe('when the given amount is greater than the balance of the sender', function () { const amount = initialBalance + 1; it('reverts', async function () { await assertRevert(this.token.burn(amount, { from })); }); }); }); }); <|start_filename|>test/erc20.to.delete.js<|end_filename|> const Token = artifacts.require('./erc20_standard_token.vyper'); const BigNumber = require('bignumber.js'); const EVMRevert = require('./helpers/EVMRevert').EVMRevert; const ether = require('./helpers/ether').ether; require('chai') .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); contract('erc20_standard_token', function (accounts) { describe('Token Creation Ruleset', () => { it('must correctly deploy with correct parameters and state variables.', async () => { const name = "<NAME>"; const symbol = "EXA"; const totalSupply = ether(1000000000); const decimals = 18; let token = await Token.new(web3.fromAscii(name), web3.fromAscii(symbol), totalSupply, decimals); assert.equal(web3.toUtf8(await token.name()), name); assert.equal(web3.toUtf8(await token.symbol()), symbol); assert.equal((await token.decimals()).toNumber(), 18); (await token.totalSupply()).should.bignumber.equal(totalSupply); (await token.balanceOf(accounts[0])).should.bignumber.equal(totalSupply); }); }); }); <|start_filename|>test/mintable-token.js<|end_filename|> const { ether } = require('./helpers/ether'); const MintableToken = artifacts.require('./mintable_token.vyper'); const { assertRevert } = require('./helpers/assertRevert'); const BigNumber = web3.BigNumber; const { shouldBehaveLikeOwnable } = require('./ownable.behavior.js'); contract('MintableToken', function ([owner, anotherAccount, a, b]) { const minter = owner; const cap = ether(1000); const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; beforeEach(async function () { this.token = await MintableToken.new(web3.fromAscii("Name"), web3.fromAscii("SYMBOL"), 0, cap, 18, { from: owner }); this.ownable = this.token; }); shouldBehaveLikeOwnable([owner, anotherAccount, a, b]); describe('as a basic mintable token', function () { describe('after token creation', function () { it('sender should be token owner', async function () { const tokenOwner = await this.token.owner({ from: owner }); tokenOwner.should.equal(owner); }); }); describe('minting finished', function () { describe('when the token minting is not finished', function () { it('returns false', async function () { const mintingFinished = await this.token.mintingFinished(); assert.equal(mintingFinished, false); }); }); describe('when the token is minting finished', function () { beforeEach(async function () { await this.token.finishMinting({ from: owner }); }); it('returns true', async function () { const mintingFinished = await this.token.mintingFinished(); assert.equal(mintingFinished, true); }); }); }); describe('finish minting', function () { describe('when the sender is the token owner', function () { const from = owner; describe('when the token minting was not finished', function () { it('finishes token minting', async function () { await this.token.finishMinting({ from }); const mintingFinished = await this.token.mintingFinished(); assert.equal(mintingFinished, true); }); it('emits a mint finished event', async function () { const { logs } = await this.token.finishMinting({ from }); assert.equal(logs.length, 1); assert.equal(logs[0].event, 'MintFinished'); }); }); describe('when the token minting was already finished', function () { beforeEach(async function () { await this.token.finishMinting({ from }); }); it('reverts', async function () { await assertRevert(this.token.finishMinting({ from })); }); }); }); describe('when the sender is not the token owner', function () { const from = anotherAccount; describe('when the token minting was not finished', function () { it('reverts', async function () { await assertRevert(this.token.finishMinting({ from })); }); }); describe('when the token minting was already finished', function () { beforeEach(async function () { await this.token.finishMinting({ from: owner }); }); it('reverts', async function () { await assertRevert(this.token.finishMinting({ from })); }); }); }); }); describe('mint', function () { const amount = 100; describe('when the sender has the minting permission', function () { const from = minter; describe('when the token minting is not finished', function () { it('mints the requested amount', async function () { await this.token.mint(owner, amount, { from }); const balance = await this.token.balanceOf(owner); assert.equal(balance, amount); }); it('emits a mint and a transfer event', async function () { const { logs } = await this.token.mint(owner, amount, { from }); assert.equal(logs.length, 2); assert.equal(logs[0].event, 'Mint'); assert.equal(logs[0].args._to, owner); assert.equal(logs[0].args._amount, amount); assert.equal(logs[1].event, 'Transfer'); assert.equal(logs[1].args._from, ZERO_ADDRESS); assert.equal(logs[1].args._to, owner); assert.equal(logs[1].args._value, amount); }); }); describe('when the token minting is finished', function () { beforeEach(async function () { await this.token.finishMinting({ from: owner }); }); it('reverts', async function () { await assertRevert(this.token.mint(owner, amount, { from })); }); }); }); describe('when the sender has not the minting permission', function () { const from = anotherAccount; describe('when the token minting is not finished', function () { it('reverts', async function () { await assertRevert(this.token.mint(owner, amount, { from })); }); }); describe('when the token minting is already finished', function () { beforeEach(async function () { await this.token.finishMinting({ from: owner }); }); it('reverts', async function () { await assertRevert(this.token.mint(owner, amount, { from })); }); }); }); }); }); }); <|start_filename|>test/capped-token.js<|end_filename|> const { ether } = require('./helpers/ether'); const { expectThrow } = require('./helpers/expectThrow'); const CappedToken = artifacts.require('./mintable_token.vyper'); contract('Capped', function ([owner, anotherAccount]) { const cap = ether(1000); beforeEach(async function () { this.token = await CappedToken.new(web3.fromAscii("Name"), web3.fromAscii("SYMBOL"), 0, cap, 18, { from: owner }); }); describe('capped token', function () { const from = owner; it('should start with the correct cap', async function () { const _cap = await this.token.cap(); assert(cap.eq(_cap)); }); it('should mint when amount is less than cap', async function () { const result = await this.token.mint(owner, cap.sub(1), { from }); assert.equal(result.logs[0].event, 'Mint'); }); it('should fail to mint if the amount exceeds the cap', async function () { await this.token.mint(owner, cap.sub(1), { from }); await expectThrow(this.token.mint(owner, 100, { from })); }); it('should fail to mint after cap is reached', async function () { await this.token.mint(owner, cap, { from }); await expectThrow(this.token.mint(owner, 1, { from })); }); }); });
binodnp/vyper-erc20
<|start_filename|>modules/tibc/core/26-routing/proposal_handler.go<|end_filename|> package routing import ( "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/client/cli" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/keeper" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) var ( SetRoutingRulesProposalHandler = govclient.NewProposalHandler(cli.NewSetRoutingRulesProposalCmd, EmptyRESTHandler) ) func EmptyRESTHandler(clientCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "tibc", Handler: nil, } } // NewSetRoutingProposalHandler defines the routing manager proposal handler func NewSetRoutingProposalHandler(k keeper.Keeper) govtypes.Handler { return func(ctx sdk.Context, content govtypes.Content) error { switch c := content.(type) { case *types.SetRoutingRulesProposal: return k.HandleSetRoutingRulesProposal(ctx, c) default: return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized tibc proposal content type: %T", c) } } } <|start_filename|>modules/tibc/light-clients/08-bsc/types/update_test.go<|end_filename|> package types_test import ( "encoding/json" "io/ioutil" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" bsctypes "github.com/bianjieai/tibc-go/modules/tibc/light-clients/08-bsc/types" ) var ( chainName = "bsc" epoch = uint64(200) ) func (suite *BSCTestSuite) TestCheckHeaderAndUpdateState() { var genesisState GenesisState genesisStateBz, _ := ioutil.ReadFile("testdata/genesis_state.json") err := json.Unmarshal(genesisStateBz, &genesisState) suite.NoError(err) header := genesisState.GenesisHeader genesisValidatorHeader := genesisState.GenesisValidatorHeader validators, err := bsctypes.ParseValidators(header.Extra) suite.NoError(err) genesisValidators, err := bsctypes.ParseValidators(genesisValidatorHeader.Extra) suite.NoError(err) number := clienttypes.NewHeight(0, header.Number.Uint64()) clientState := exported.ClientState(&bsctypes.ClientState{ Header: header.ToHeader(), ChainId: 56, Epoch: epoch, BlockInteval: 3, Validators: genesisValidators, ContractAddress: []byte("0x00"), TrustingPeriod: 200, }) consensusState := exported.ConsensusState(&bsctypes.ConsensusState{ Timestamp: header.Time, Number: number, Root: header.Root[:], }) suite.app.TIBCKeeper.ClientKeeper.SetClientConsensusState(suite.ctx, chainName, number, consensusState) bsctypes.SetPendingValidators(suite.app.TIBCKeeper.ClientKeeper.ClientStore(suite.ctx, chainName), suite.app.AppCodec(), validators) var updateHeaders []*bsctypes.BscHeader updateHeadersBz, _ := ioutil.ReadFile("testdata/update_headers.json") err = json.Unmarshal(updateHeadersBz, &updateHeaders) suite.NoError(err) suite.Equal(int(1.5*float64(epoch)), len(updateHeaders)) for i, updateHeader := range updateHeaders { updateHeaders = append(updateHeaders, updateHeader) protoHeader := updateHeader.ToHeader() suite.NoError(err) clientState, consensusState, err = clientState.CheckHeaderAndUpdateState( suite.ctx, suite.app.AppCodec(), suite.app.TIBCKeeper.ClientKeeper.ClientStore(suite.ctx, chainName), // pass in chainName prefixed clientStore &protoHeader, ) suite.NoError(err) number.RevisionHeight = protoHeader.Height.RevisionHeight suite.app.TIBCKeeper.ClientKeeper.SetClientConsensusState(suite.ctx, chainName, number, consensusState) recentSigners, err := bsctypes.GetRecentSigners(suite.app.TIBCKeeper.ClientKeeper.ClientStore(suite.ctx, chainName)) suite.NoError(err) validatorCount := len(clientState.(*bsctypes.ClientState).Validators) if i+1 <= validatorCount/2+1 { suite.Equal(i+1, len(recentSigners)) } else { suite.Equal(validatorCount/2+1, len(recentSigners)) } suite.Equal(updateHeader.Number.Uint64(), clientState.GetLatestHeight().GetRevisionHeight()) } } type GenesisState struct { GenesisHeader *bsctypes.BscHeader `json:"genesis_header"` GenesisValidatorHeader *bsctypes.BscHeader `json:"genesis_validator_header"` } <|start_filename|>modules/tibc/core/04-packet/types/codec.go<|end_filename|> package types import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" ) // RegisterInterfaces register the tibc packet submodule interfaces to protobuf // Any. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterInterface( "tibc.core.packet.v1.PacketI", (*exported.PacketI)(nil), ) registry.RegisterInterface( "tibc.core.packet.v1.CleanPacketI", (*exported.CleanPacketI)(nil), ) registry.RegisterImplementations( (*exported.PacketI)(nil), &Packet{}, ) registry.RegisterImplementations( (*exported.CleanPacketI)(nil), &CleanPacket{}, ) registry.RegisterImplementations( (*sdk.Msg)(nil), &MsgRecvPacket{}, &MsgAcknowledgement{}, &MsgCleanPacket{}, &MsgRecvCleanPacket{}, ) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } // SubModuleCdc references the global x/ibc/core/04-channel module codec. Note, the codec should // ONLY be used in certain instances of tests and for JSON encoding. // // The actual codec used for serialization should be provided to x/ibc/core/04-channel and // defined at the application level. var SubModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) <|start_filename|>modules/tibc/core/26-routing/client/cli/query.go<|end_filename|> package cli import ( "context" "fmt" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // GetCmdQueryRoutingRulesCommitment defines the command to query routing rules func GetCmdQueryRoutingRulesCommitment() *cobra.Command { cmd := &cobra.Command{ Use: "routing-rules", Short: "Query routing rules commitment", Long: "Query routing rules commitment", Example: fmt.Sprintf( "%s query %s %s routing-rules", version.AppName, host.ModuleName, types.SubModuleName, ), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientQueryContext(cmd) if err != nil { return err } queryClient := types.NewQueryClient(clientCtx) if err != nil { return err } req := &types.QueryRoutingRulesRequest{} res, err := queryClient.RoutingRules(context.Background(), req) if err != nil { return err } return clientCtx.PrintProto(res) }, } flags.AddQueryFlagsToCmd(cmd) return cmd } <|start_filename|>modules/tibc/core/26-routing/genesis.go<|end_filename|> package routing import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/keeper" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // InitGenesis initializes the tibc routing submodule's state from a provided genesis // state. func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs types.GenesisState) { err := k.SetRoutingRules(ctx, gs.Rules) if err != nil { panic(err) } } // ExportGenesis returns the tibc routing submodule's exported genesis. func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { rules, _ := k.GetRoutingRules(ctx) return types.GenesisState{ Rules: rules, } } <|start_filename|>modules/tibc/core/04-packet/genesis.go<|end_filename|> package packet import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/keeper" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" ) // InitGenesis initializes the tibc packet submodule's state from a provided genesis // state. func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs types.GenesisState) { for _, ack := range gs.Acknowledgements { k.SetPacketAcknowledgement(ctx, ack.SourceChain, ack.DestinationChain, ack.Sequence, ack.Data) } for _, commitment := range gs.Commitments { k.SetPacketCommitment(ctx, commitment.SourceChain, commitment.DestinationChain, commitment.Sequence, commitment.Data) } for _, receipt := range gs.Receipts { k.SetPacketReceipt(ctx, receipt.SourceChain, receipt.DestinationChain, receipt.Sequence) } for _, ss := range gs.SendSequences { k.SetNextSequenceSend(ctx, ss.SourceChain, ss.DestinationChain, ss.Sequence) } } // ExportGenesis returns the tibc packet submodule's exported genesis. func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { return types.GenesisState{ Acknowledgements: k.GetAllPacketAcks(ctx), Commitments: k.GetAllPacketCommitments(ctx), Receipts: k.GetAllPacketReceipts(ctx), SendSequences: k.GetAllPacketSendSeqs(ctx), RecvSequences: k.GetAllPacketRecvSeqs(ctx), AckSequences: k.GetAllPacketAckSeqs(ctx), } } <|start_filename|>modules/tibc/core/types/query.go<|end_filename|> package types import ( "github.com/gogo/protobuf/grpc" client "github.com/bianjieai/tibc-go/modules/tibc/core/02-client" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" packet "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" routing "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing" routingtypes "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // QueryServer defines the TIBC interfaces that the gRPC query server must implement type QueryServer interface { clienttypes.QueryServer packettypes.QueryServer routingtypes.QueryServer } // RegisterQueryService registers each individual TIBC submodule query service func RegisterQueryService(server grpc.Server, queryService QueryServer) { client.RegisterQueryService(server, queryService) packet.RegisterQueryService(server, queryService) routing.RegisterQueryService(server, queryService) } <|start_filename|>modules/tibc/core/02-client/proposal_handler.go<|end_filename|> package client import ( "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/client/cli" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/keeper" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" ) // TODO: move to cli var ( CreateClientProposalHandler = govclient.NewProposalHandler(cli.NewCreateClientProposalCmd, EmptyRESTHandler) UpgradeClientProposalHandler = govclient.NewProposalHandler(cli.NewUpgradeClientProposalCmd, EmptyRESTHandler) RegisterRelayerProposalHandler = govclient.NewProposalHandler(cli.NewRegisterRelayerProposalCmd, EmptyRESTHandler) ) func EmptyRESTHandler(clientCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "tibc", Handler: nil, } } // NewClientProposalHandler defines the client manager proposal handler func NewClientProposalHandler(k keeper.Keeper) govtypes.Handler { return func(ctx sdk.Context, content govtypes.Content) error { switch c := content.(type) { case *types.CreateClientProposal: return k.HandleCreateClientProposal(ctx, c) case *types.UpgradeClientProposal: return k.HandleUpgradeClientProposal(ctx, c) case *types.RegisterRelayerProposal: return k.HandleRegisterRelayerProposal(ctx, c) default: return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized tibc proposal content type: %T", c) } } } <|start_filename|>modules/tibc/core/04-packet/types/errors.go<|end_filename|> package types import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) const moduleName = host.ModuleName + "-" + SubModuleName // TIBC packet sentinel errors var ( ErrSequenceSendNotFound = sdkerrors.Register(moduleName, 2, "sequence send not found") ErrSequenceReceiveNotFound = sdkerrors.Register(moduleName, 3, "sequence receive not found") ErrSequenceAckNotFound = sdkerrors.Register(moduleName, 4, "sequence acknowledgement not found") ErrInvalidPacket = sdkerrors.Register(moduleName, 5, "invalid packet") ErrInvalidAcknowledgement = sdkerrors.Register(moduleName, 6, "invalid acknowledgement") ErrPacketCommitmentNotFound = sdkerrors.Register(moduleName, 7, "packet commitment not found") ErrPacketReceived = sdkerrors.Register(moduleName, 8, "packet already received") ErrAcknowledgementExists = sdkerrors.Register(moduleName, 9, "acknowledgement for packet already exists") ErrInvalidCleanPacket = sdkerrors.Register(moduleName, 10, "invalid clean packet") ) <|start_filename|>modules/tibc/light-clients/08-bsc/types/genesis_test.go<|end_filename|> package types_test func (suite *BSCTestSuite) TestExportMetadata() { // TODO } <|start_filename|>modules/tibc/core/26-routing/types/proposal_test.go<|end_filename|> package types_test import ( "testing" "github.com/stretchr/testify/suite" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" tibctesting "github.com/bianjieai/tibc-go/modules/tibc/testing" ) type TypesTestSuite struct { suite.Suite coordinator *tibctesting.Coordinator chain *tibctesting.TestChain } func (suite *TypesTestSuite) SetupTest() { suite.coordinator = tibctesting.NewCoordinator(suite.T(), 1) suite.chain = suite.coordinator.GetChain(tibctesting.GetChainID(0)) } func TestTypesTestSuite(t *testing.T) { suite.Run(t, new(TypesTestSuite)) } func (suite *TypesTestSuite) TestNewSetRoutingRulesProposal() { p, err := types.NewSetRoutingRulesProposal(tibctesting.Title, tibctesting.Description, []string{"source.dest.dgsbl"}) suite.Require().NoError(err) suite.Require().NotNil(p) } <|start_filename|>modules/tibc/core/02-client/types/query.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/client/v1/query.proto package types import ( context "context" fmt "fmt" types "github.com/cosmos/cosmos-sdk/codec/types" query "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // QueryClientStateRequest is the request type for the Query/ClientState RPC // method type QueryClientStateRequest struct { // client state unique identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` } func (m *QueryClientStateRequest) Reset() { *m = QueryClientStateRequest{} } func (m *QueryClientStateRequest) String() string { return proto.CompactTextString(m) } func (*QueryClientStateRequest) ProtoMessage() {} func (*QueryClientStateRequest) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{0} } func (m *QueryClientStateRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryClientStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryClientStateRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryClientStateRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryClientStateRequest.Merge(m, src) } func (m *QueryClientStateRequest) XXX_Size() int { return m.Size() } func (m *QueryClientStateRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryClientStateRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryClientStateRequest proto.InternalMessageInfo func (m *QueryClientStateRequest) GetChainName() string { if m != nil { return m.ChainName } return "" } // QueryClientStateResponse is the response type for the Query/ClientState RPC // method. Besides the client state, it includes a proof and the height from // which the proof was retrieved. type QueryClientStateResponse struct { // client state associated with the request identifier ClientState *types.Any `protobuf:"bytes,1,opt,name=client_state,json=clientState,proto3" json:"client_state,omitempty"` // merkle proof of existence Proof []byte `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` // height at which the proof was retrieved ProofHeight Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height"` } func (m *QueryClientStateResponse) Reset() { *m = QueryClientStateResponse{} } func (m *QueryClientStateResponse) String() string { return proto.CompactTextString(m) } func (*QueryClientStateResponse) ProtoMessage() {} func (*QueryClientStateResponse) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{1} } func (m *QueryClientStateResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryClientStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryClientStateResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryClientStateResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryClientStateResponse.Merge(m, src) } func (m *QueryClientStateResponse) XXX_Size() int { return m.Size() } func (m *QueryClientStateResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryClientStateResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryClientStateResponse proto.InternalMessageInfo func (m *QueryClientStateResponse) GetClientState() *types.Any { if m != nil { return m.ClientState } return nil } func (m *QueryClientStateResponse) GetProof() []byte { if m != nil { return m.Proof } return nil } func (m *QueryClientStateResponse) GetProofHeight() Height { if m != nil { return m.ProofHeight } return Height{} } // QueryClientStatesRequest is the request type for the Query/ClientStates RPC // method type QueryClientStatesRequest struct { // pagination request Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *QueryClientStatesRequest) Reset() { *m = QueryClientStatesRequest{} } func (m *QueryClientStatesRequest) String() string { return proto.CompactTextString(m) } func (*QueryClientStatesRequest) ProtoMessage() {} func (*QueryClientStatesRequest) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{2} } func (m *QueryClientStatesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryClientStatesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryClientStatesRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryClientStatesRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryClientStatesRequest.Merge(m, src) } func (m *QueryClientStatesRequest) XXX_Size() int { return m.Size() } func (m *QueryClientStatesRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryClientStatesRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryClientStatesRequest proto.InternalMessageInfo func (m *QueryClientStatesRequest) GetPagination() *query.PageRequest { if m != nil { return m.Pagination } return nil } // QueryClientStatesResponse is the response type for the Query/ClientStates RPC // method. type QueryClientStatesResponse struct { // list of stored ClientStates of the chain. ClientStates IdentifiedClientStates `protobuf:"bytes,1,rep,name=client_states,json=clientStates,proto3,castrepeated=IdentifiedClientStates" json:"client_states"` // pagination response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *QueryClientStatesResponse) Reset() { *m = QueryClientStatesResponse{} } func (m *QueryClientStatesResponse) String() string { return proto.CompactTextString(m) } func (*QueryClientStatesResponse) ProtoMessage() {} func (*QueryClientStatesResponse) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{3} } func (m *QueryClientStatesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryClientStatesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryClientStatesResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryClientStatesResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryClientStatesResponse.Merge(m, src) } func (m *QueryClientStatesResponse) XXX_Size() int { return m.Size() } func (m *QueryClientStatesResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryClientStatesResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryClientStatesResponse proto.InternalMessageInfo func (m *QueryClientStatesResponse) GetClientStates() IdentifiedClientStates { if m != nil { return m.ClientStates } return nil } func (m *QueryClientStatesResponse) GetPagination() *query.PageResponse { if m != nil { return m.Pagination } return nil } // QueryConsensusStateRequest is the request type for the Query/ConsensusState // RPC method. Besides the consensus state, it includes a proof and the height // from which the proof was retrieved. type QueryConsensusStateRequest struct { // client identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // consensus state revision number RevisionNumber uint64 `protobuf:"varint,2,opt,name=revision_number,json=revisionNumber,proto3" json:"revision_number,omitempty"` // consensus state revision height RevisionHeight uint64 `protobuf:"varint,3,opt,name=revision_height,json=revisionHeight,proto3" json:"revision_height,omitempty"` // latest_height overrrides the height field and queries the latest stored // ConsensusState LatestHeight bool `protobuf:"varint,4,opt,name=latest_height,json=latestHeight,proto3" json:"latest_height,omitempty"` } func (m *QueryConsensusStateRequest) Reset() { *m = QueryConsensusStateRequest{} } func (m *QueryConsensusStateRequest) String() string { return proto.CompactTextString(m) } func (*QueryConsensusStateRequest) ProtoMessage() {} func (*QueryConsensusStateRequest) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{4} } func (m *QueryConsensusStateRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryConsensusStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryConsensusStateRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryConsensusStateRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryConsensusStateRequest.Merge(m, src) } func (m *QueryConsensusStateRequest) XXX_Size() int { return m.Size() } func (m *QueryConsensusStateRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryConsensusStateRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryConsensusStateRequest proto.InternalMessageInfo func (m *QueryConsensusStateRequest) GetChainName() string { if m != nil { return m.ChainName } return "" } func (m *QueryConsensusStateRequest) GetRevisionNumber() uint64 { if m != nil { return m.RevisionNumber } return 0 } func (m *QueryConsensusStateRequest) GetRevisionHeight() uint64 { if m != nil { return m.RevisionHeight } return 0 } func (m *QueryConsensusStateRequest) GetLatestHeight() bool { if m != nil { return m.LatestHeight } return false } // QueryConsensusStateResponse is the response type for the Query/ConsensusState // RPC method type QueryConsensusStateResponse struct { // consensus state associated with the client identifier at the given height ConsensusState *types.Any `protobuf:"bytes,1,opt,name=consensus_state,json=consensusState,proto3" json:"consensus_state,omitempty"` // merkle proof of existence Proof []byte `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` // height at which the proof was retrieved ProofHeight Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height"` } func (m *QueryConsensusStateResponse) Reset() { *m = QueryConsensusStateResponse{} } func (m *QueryConsensusStateResponse) String() string { return proto.CompactTextString(m) } func (*QueryConsensusStateResponse) ProtoMessage() {} func (*QueryConsensusStateResponse) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{5} } func (m *QueryConsensusStateResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryConsensusStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryConsensusStateResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryConsensusStateResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryConsensusStateResponse.Merge(m, src) } func (m *QueryConsensusStateResponse) XXX_Size() int { return m.Size() } func (m *QueryConsensusStateResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryConsensusStateResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryConsensusStateResponse proto.InternalMessageInfo func (m *QueryConsensusStateResponse) GetConsensusState() *types.Any { if m != nil { return m.ConsensusState } return nil } func (m *QueryConsensusStateResponse) GetProof() []byte { if m != nil { return m.Proof } return nil } func (m *QueryConsensusStateResponse) GetProofHeight() Height { if m != nil { return m.ProofHeight } return Height{} } // QueryConsensusStatesRequest is the request type for the Query/ConsensusStates // RPC method. type QueryConsensusStatesRequest struct { // client identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // pagination request Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *QueryConsensusStatesRequest) Reset() { *m = QueryConsensusStatesRequest{} } func (m *QueryConsensusStatesRequest) String() string { return proto.CompactTextString(m) } func (*QueryConsensusStatesRequest) ProtoMessage() {} func (*QueryConsensusStatesRequest) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{6} } func (m *QueryConsensusStatesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryConsensusStatesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryConsensusStatesRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryConsensusStatesRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryConsensusStatesRequest.Merge(m, src) } func (m *QueryConsensusStatesRequest) XXX_Size() int { return m.Size() } func (m *QueryConsensusStatesRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryConsensusStatesRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryConsensusStatesRequest proto.InternalMessageInfo func (m *QueryConsensusStatesRequest) GetChainName() string { if m != nil { return m.ChainName } return "" } func (m *QueryConsensusStatesRequest) GetPagination() *query.PageRequest { if m != nil { return m.Pagination } return nil } // QueryConsensusStatesResponse is the response type for the // Query/ConsensusStates RPC method type QueryConsensusStatesResponse struct { // consensus states associated with the identifier ConsensusStates []ConsensusStateWithHeight `protobuf:"bytes,1,rep,name=consensus_states,json=consensusStates,proto3" json:"consensus_states"` // pagination response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *QueryConsensusStatesResponse) Reset() { *m = QueryConsensusStatesResponse{} } func (m *QueryConsensusStatesResponse) String() string { return proto.CompactTextString(m) } func (*QueryConsensusStatesResponse) ProtoMessage() {} func (*QueryConsensusStatesResponse) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{7} } func (m *QueryConsensusStatesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryConsensusStatesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryConsensusStatesResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryConsensusStatesResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryConsensusStatesResponse.Merge(m, src) } func (m *QueryConsensusStatesResponse) XXX_Size() int { return m.Size() } func (m *QueryConsensusStatesResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryConsensusStatesResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryConsensusStatesResponse proto.InternalMessageInfo func (m *QueryConsensusStatesResponse) GetConsensusStates() []ConsensusStateWithHeight { if m != nil { return m.ConsensusStates } return nil } func (m *QueryConsensusStatesResponse) GetPagination() *query.PageResponse { if m != nil { return m.Pagination } return nil } // QueryRelayersRequest is the request type for the Query/Relayers // RPC method. type QueryRelayersRequest struct { // client identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` } func (m *QueryRelayersRequest) Reset() { *m = QueryRelayersRequest{} } func (m *QueryRelayersRequest) String() string { return proto.CompactTextString(m) } func (*QueryRelayersRequest) ProtoMessage() {} func (*QueryRelayersRequest) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{8} } func (m *QueryRelayersRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryRelayersRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryRelayersRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryRelayersRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryRelayersRequest.Merge(m, src) } func (m *QueryRelayersRequest) XXX_Size() int { return m.Size() } func (m *QueryRelayersRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryRelayersRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryRelayersRequest proto.InternalMessageInfo func (m *QueryRelayersRequest) GetChainName() string { if m != nil { return m.ChainName } return "" } // QueryConsensusStatesResponse is the response type for the // Query/Relayers RPC method type QueryRelayersResponse struct { // relayers address associated with the client Relayers []string `protobuf:"bytes,1,rep,name=relayers,proto3" json:"relayers,omitempty"` } func (m *QueryRelayersResponse) Reset() { *m = QueryRelayersResponse{} } func (m *QueryRelayersResponse) String() string { return proto.CompactTextString(m) } func (*QueryRelayersResponse) ProtoMessage() {} func (*QueryRelayersResponse) Descriptor() ([]byte, []int) { return fileDescriptor_62c85a887dc5e161, []int{9} } func (m *QueryRelayersResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryRelayersResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryRelayersResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryRelayersResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryRelayersResponse.Merge(m, src) } func (m *QueryRelayersResponse) XXX_Size() int { return m.Size() } func (m *QueryRelayersResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryRelayersResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryRelayersResponse proto.InternalMessageInfo func (m *QueryRelayersResponse) GetRelayers() []string { if m != nil { return m.Relayers } return nil } func init() { proto.RegisterType((*QueryClientStateRequest)(nil), "tibc.core.client.v1.QueryClientStateRequest") proto.RegisterType((*QueryClientStateResponse)(nil), "tibc.core.client.v1.QueryClientStateResponse") proto.RegisterType((*QueryClientStatesRequest)(nil), "tibc.core.client.v1.QueryClientStatesRequest") proto.RegisterType((*QueryClientStatesResponse)(nil), "tibc.core.client.v1.QueryClientStatesResponse") proto.RegisterType((*QueryConsensusStateRequest)(nil), "tibc.core.client.v1.QueryConsensusStateRequest") proto.RegisterType((*QueryConsensusStateResponse)(nil), "tibc.core.client.v1.QueryConsensusStateResponse") proto.RegisterType((*QueryConsensusStatesRequest)(nil), "tibc.core.client.v1.QueryConsensusStatesRequest") proto.RegisterType((*QueryConsensusStatesResponse)(nil), "tibc.core.client.v1.QueryConsensusStatesResponse") proto.RegisterType((*QueryRelayersRequest)(nil), "tibc.core.client.v1.QueryRelayersRequest") proto.RegisterType((*QueryRelayersResponse)(nil), "tibc.core.client.v1.QueryRelayersResponse") } func init() { proto.RegisterFile("tibc/core/client/v1/query.proto", fileDescriptor_62c85a887dc5e161) } var fileDescriptor_62c85a887dc5e161 = []byte{ // 842 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0x4f, 0x6b, 0x03, 0x45, 0x14, 0xcf, 0xf4, 0x8f, 0xb6, 0x93, 0xb4, 0x91, 0x31, 0x6a, 0xba, 0xad, 0x69, 0x88, 0xd0, 0xc6, 0x62, 0x66, 0x9a, 0x94, 0xd6, 0x82, 0x58, 0xb0, 0x4a, 0xd5, 0x4b, 0xd1, 0xf5, 0xa0, 0x78, 0x30, 0xec, 0x6e, 0xa7, 0x9b, 0x29, 0xc9, 0x4e, 0xba, 0xb3, 0x09, 0x84, 0xd2, 0x8b, 0xf8, 0x01, 0x0a, 0x9e, 0x3c, 0x78, 0x16, 0xbc, 0x08, 0x1e, 0xc4, 0x6f, 0x60, 0x8f, 0x05, 0x11, 0x3c, 0xa9, 0xb4, 0x82, 0x5f, 0x43, 0x76, 0x66, 0xb6, 0xd9, 0x4d, 0x37, 0xba, 0x2d, 0x7a, 0xdb, 0x7d, 0xf3, 0xfe, 0xfc, 0x7e, 0xbf, 0xf7, 0xe6, 0xed, 0xc2, 0xf5, 0x80, 0xd9, 0x0e, 0x71, 0xb8, 0x4f, 0x89, 0xd3, 0x65, 0xd4, 0x0b, 0xc8, 0xb0, 0x49, 0xce, 0x07, 0xd4, 0x1f, 0xe1, 0xbe, 0xcf, 0x03, 0x8e, 0x9e, 0x0f, 0x1d, 0x70, 0xe8, 0x80, 0x95, 0x03, 0x1e, 0x36, 0x8d, 0x2d, 0x87, 0x8b, 0x1e, 0x17, 0xc4, 0xb6, 0x04, 0x55, 0xde, 0x64, 0xd8, 0xb4, 0x69, 0x60, 0x35, 0x49, 0xdf, 0x72, 0x99, 0x67, 0x05, 0x8c, 0x7b, 0x2a, 0x81, 0x51, 0x4d, 0xab, 0xa0, 0x53, 0x29, 0x8f, 0x15, 0x97, 0x73, 0xb7, 0x4b, 0x89, 0x7c, 0xb3, 0x07, 0xa7, 0xc4, 0xf2, 0x74, 0x75, 0x63, 0x4d, 0x1f, 0x59, 0x7d, 0x46, 0x2c, 0xcf, 0xe3, 0x81, 0xcc, 0x2c, 0xf4, 0x69, 0xc9, 0xe5, 0x2e, 0x97, 0x8f, 0x24, 0x7c, 0x52, 0xd6, 0xda, 0x3e, 0x7c, 0xe9, 0xc3, 0x10, 0xd2, 0xdb, 0xb2, 0xc6, 0x47, 0x81, 0x15, 0x50, 0x93, 0x9e, 0x0f, 0xa8, 0x08, 0xd0, 0xcb, 0x10, 0x3a, 0x1d, 0x8b, 0x79, 0x6d, 0xcf, 0xea, 0xd1, 0x32, 0xa8, 0x82, 0xfa, 0xa2, 0xb9, 0x28, 0x2d, 0xc7, 0x56, 0x8f, 0xd6, 0xbe, 0x03, 0xb0, 0xfc, 0x30, 0x54, 0xf4, 0xb9, 0x27, 0x28, 0x7a, 0x1d, 0x16, 0x14, 0xea, 0xb6, 0x08, 0xed, 0x32, 0x3a, 0xdf, 0x2a, 0x61, 0x85, 0x10, 0x47, 0xe0, 0xf1, 0x5b, 0xde, 0xc8, 0xcc, 0x3b, 0xe3, 0x04, 0xa8, 0x04, 0xe7, 0xfb, 0x3e, 0xe7, 0xa7, 0xe5, 0x99, 0x2a, 0xa8, 0x17, 0x4c, 0xf5, 0x82, 0xde, 0x81, 0x05, 0xf9, 0xd0, 0xee, 0x50, 0xe6, 0x76, 0x82, 0xf2, 0xac, 0x4c, 0xb7, 0x8a, 0x53, 0xe4, 0xc6, 0xef, 0x49, 0x97, 0xc3, 0xb9, 0xeb, 0xdf, 0xd6, 0x73, 0x66, 0x5e, 0x86, 0x29, 0x53, 0xcd, 0x7e, 0x08, 0x58, 0x44, 0x64, 0x8f, 0x20, 0x1c, 0x37, 0x43, 0xc3, 0xdd, 0xc0, 0xaa, 0x73, 0x38, 0xec, 0x1c, 0x56, 0x7d, 0xd6, 0x9d, 0xc3, 0x1f, 0x58, 0x6e, 0x24, 0x94, 0x19, 0x8b, 0xac, 0xfd, 0x02, 0xe0, 0x4a, 0x4a, 0x11, 0x2d, 0x0b, 0x87, 0x4b, 0x71, 0x59, 0x44, 0x19, 0x54, 0x67, 0xeb, 0xf9, 0xd6, 0x56, 0x2a, 0x91, 0xf7, 0x4f, 0xa8, 0x17, 0xb0, 0x53, 0x46, 0x4f, 0x62, 0xb9, 0x0e, 0x2b, 0x21, 0xaf, 0x6f, 0x7f, 0x5f, 0x7f, 0x31, 0xf5, 0x58, 0x98, 0x85, 0x98, 0x9a, 0x02, 0xbd, 0x9b, 0xa0, 0x35, 0x23, 0x69, 0x6d, 0xfe, 0x2b, 0x2d, 0x85, 0x36, 0xc1, 0xeb, 0x7b, 0x00, 0x0d, 0xc5, 0x2b, 0x3c, 0xf2, 0xc4, 0x40, 0x3c, 0x62, 0x56, 0xd0, 0x26, 0x2c, 0xfa, 0x74, 0xc8, 0x04, 0xe3, 0x5e, 0xdb, 0x1b, 0xf4, 0x6c, 0xea, 0x4b, 0x2c, 0x73, 0xe6, 0x72, 0x64, 0x3e, 0x96, 0xd6, 0x84, 0x63, 0xac, 0xd7, 0x31, 0x47, 0xd5, 0x4b, 0xf4, 0x0a, 0x5c, 0xea, 0x86, 0x0c, 0x83, 0xc8, 0x6d, 0xae, 0x0a, 0xea, 0x0b, 0x66, 0x41, 0x19, 0x75, 0xc3, 0x7f, 0x04, 0x70, 0x35, 0x15, 0xb4, 0x6e, 0xc7, 0x9b, 0xb0, 0xe8, 0x44, 0x27, 0x19, 0x06, 0x75, 0xd9, 0x49, 0xa4, 0xf9, 0x5f, 0x67, 0xf5, 0x8b, 0x74, 0xe8, 0x22, 0xa3, 0xe0, 0x47, 0x29, 0x7d, 0x7f, 0xca, 0x38, 0xff, 0x04, 0xe0, 0x5a, 0x3a, 0x0c, 0x2d, 0xe1, 0x67, 0xf0, 0xb9, 0x09, 0x09, 0xa3, 0xa1, 0x6e, 0xa4, 0x32, 0x4e, 0xe6, 0xf9, 0x98, 0x05, 0x9d, 0x84, 0x06, 0xc5, 0xa4, 0xc4, 0xff, 0xe1, 0x00, 0xef, 0xc2, 0x92, 0x24, 0x62, 0xd2, 0xae, 0x35, 0xa2, 0x7e, 0x46, 0x21, 0x6b, 0x3b, 0xf0, 0x85, 0x89, 0x30, 0x4d, 0xdc, 0x80, 0x0b, 0xbe, 0xb6, 0x49, 0xc2, 0x8b, 0xe6, 0xfd, 0x7b, 0xeb, 0xea, 0x59, 0x38, 0x2f, 0xa3, 0xd0, 0x37, 0x00, 0xe6, 0x63, 0xd7, 0x13, 0xbd, 0x96, 0x2a, 0xca, 0x94, 0x0d, 0x6c, 0x34, 0x32, 0x7a, 0x2b, 0x48, 0xb5, 0x37, 0x3e, 0xff, 0xf9, 0xcf, 0x2f, 0x67, 0x76, 0xd1, 0x0e, 0x79, 0xf8, 0x11, 0x51, 0xdf, 0x9b, 0xc4, 0xf2, 0x21, 0x17, 0x63, 0xe2, 0x97, 0xe8, 0x6b, 0x00, 0x0b, 0xf1, 0x45, 0x82, 0xb2, 0x15, 0x8f, 0x74, 0x34, 0x70, 0x56, 0x77, 0x0d, 0x16, 0x4b, 0xb0, 0x75, 0xb4, 0x91, 0x0d, 0x2c, 0xfa, 0x0b, 0xc0, 0xe5, 0xe4, 0xf0, 0x20, 0xf2, 0x0f, 0x25, 0xd3, 0xb6, 0x94, 0xb1, 0x9d, 0x3d, 0x40, 0xa3, 0xf4, 0x25, 0xca, 0x2e, 0x3a, 0x9b, 0x8e, 0x72, 0x62, 0xfa, 0x13, 0xaa, 0x92, 0x68, 0x6b, 0x91, 0x8b, 0x89, 0xfd, 0x77, 0x49, 0xd4, 0x7a, 0x88, 0x1d, 0x28, 0xc3, 0x25, 0xfa, 0x01, 0xc0, 0xe2, 0xc4, 0x75, 0x43, 0x99, 0x91, 0xdf, 0xf7, 0xa3, 0xf9, 0x88, 0x08, 0x4d, 0xf6, 0x40, 0x92, 0xdd, 0x47, 0x7b, 0x4f, 0x23, 0x8b, 0xbe, 0x02, 0x70, 0x21, 0xba, 0x27, 0xe8, 0xd5, 0xe9, 0xf5, 0x27, 0xae, 0xa0, 0xb1, 0x95, 0xc5, 0x55, 0x63, 0xdc, 0x93, 0x18, 0xb7, 0x11, 0x9e, 0x8a, 0x31, 0xba, 0x85, 0x09, 0x6c, 0x87, 0x9f, 0x5c, 0xdf, 0x56, 0xc0, 0xcd, 0x6d, 0x05, 0xfc, 0x71, 0x5b, 0x01, 0x57, 0x77, 0x95, 0xdc, 0xcd, 0x5d, 0x25, 0xf7, 0xeb, 0x5d, 0x25, 0xf7, 0xe9, 0x81, 0xcb, 0x82, 0xce, 0xc0, 0xc6, 0x0e, 0xef, 0x11, 0x9b, 0x59, 0xde, 0x19, 0xa3, 0x16, 0x23, 0x21, 0xa2, 0x86, 0xcb, 0x49, 0x8f, 0x9f, 0x0c, 0xba, 0x54, 0x90, 0xf1, 0x7f, 0xd9, 0x76, 0xab, 0xa1, 0x2b, 0x06, 0xa3, 0x3e, 0x15, 0xf6, 0x33, 0xf2, 0x1b, 0xb1, 0xf3, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdd, 0x28, 0x02, 0x6b, 0x1d, 0x0a, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // QueryClient is the client API for Query service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { // ClientState queries an TIBC light client. ClientState(ctx context.Context, in *QueryClientStateRequest, opts ...grpc.CallOption) (*QueryClientStateResponse, error) // ClientStates queries all the TIBC light clients of a chain. ClientStates(ctx context.Context, in *QueryClientStatesRequest, opts ...grpc.CallOption) (*QueryClientStatesResponse, error) // ConsensusState queries a consensus state associated with a client state at // a given height. ConsensusState(ctx context.Context, in *QueryConsensusStateRequest, opts ...grpc.CallOption) (*QueryConsensusStateResponse, error) // ConsensusStates queries all the consensus state associated with a given // client. ConsensusStates(ctx context.Context, in *QueryConsensusStatesRequest, opts ...grpc.CallOption) (*QueryConsensusStatesResponse, error) // Relayers queries all the relayers associated with a given // client. Relayers(ctx context.Context, in *QueryRelayersRequest, opts ...grpc.CallOption) (*QueryRelayersResponse, error) } type queryClient struct { cc grpc1.ClientConn } func NewQueryClient(cc grpc1.ClientConn) QueryClient { return &queryClient{cc} } func (c *queryClient) ClientState(ctx context.Context, in *QueryClientStateRequest, opts ...grpc.CallOption) (*QueryClientStateResponse, error) { out := new(QueryClientStateResponse) err := c.cc.Invoke(ctx, "/tibc.core.client.v1.Query/ClientState", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) ClientStates(ctx context.Context, in *QueryClientStatesRequest, opts ...grpc.CallOption) (*QueryClientStatesResponse, error) { out := new(QueryClientStatesResponse) err := c.cc.Invoke(ctx, "/tibc.core.client.v1.Query/ClientStates", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) ConsensusState(ctx context.Context, in *QueryConsensusStateRequest, opts ...grpc.CallOption) (*QueryConsensusStateResponse, error) { out := new(QueryConsensusStateResponse) err := c.cc.Invoke(ctx, "/tibc.core.client.v1.Query/ConsensusState", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) ConsensusStates(ctx context.Context, in *QueryConsensusStatesRequest, opts ...grpc.CallOption) (*QueryConsensusStatesResponse, error) { out := new(QueryConsensusStatesResponse) err := c.cc.Invoke(ctx, "/tibc.core.client.v1.Query/ConsensusStates", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) Relayers(ctx context.Context, in *QueryRelayersRequest, opts ...grpc.CallOption) (*QueryRelayersResponse, error) { out := new(QueryRelayersResponse) err := c.cc.Invoke(ctx, "/tibc.core.client.v1.Query/Relayers", in, out, opts...) if err != nil { return nil, err } return out, nil } // QueryServer is the server API for Query service. type QueryServer interface { // ClientState queries an TIBC light client. ClientState(context.Context, *QueryClientStateRequest) (*QueryClientStateResponse, error) // ClientStates queries all the TIBC light clients of a chain. ClientStates(context.Context, *QueryClientStatesRequest) (*QueryClientStatesResponse, error) // ConsensusState queries a consensus state associated with a client state at // a given height. ConsensusState(context.Context, *QueryConsensusStateRequest) (*QueryConsensusStateResponse, error) // ConsensusStates queries all the consensus state associated with a given // client. ConsensusStates(context.Context, *QueryConsensusStatesRequest) (*QueryConsensusStatesResponse, error) // Relayers queries all the relayers associated with a given // client. Relayers(context.Context, *QueryRelayersRequest) (*QueryRelayersResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. type UnimplementedQueryServer struct { } func (*UnimplementedQueryServer) ClientState(ctx context.Context, req *QueryClientStateRequest) (*QueryClientStateResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ClientState not implemented") } func (*UnimplementedQueryServer) ClientStates(ctx context.Context, req *QueryClientStatesRequest) (*QueryClientStatesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ClientStates not implemented") } func (*UnimplementedQueryServer) ConsensusState(ctx context.Context, req *QueryConsensusStateRequest) (*QueryConsensusStateResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ConsensusState not implemented") } func (*UnimplementedQueryServer) ConsensusStates(ctx context.Context, req *QueryConsensusStatesRequest) (*QueryConsensusStatesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ConsensusStates not implemented") } func (*UnimplementedQueryServer) Relayers(ctx context.Context, req *QueryRelayersRequest) (*QueryRelayersResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Relayers not implemented") } func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } func _Query_ClientState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryClientStateRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).ClientState(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.client.v1.Query/ClientState", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).ClientState(ctx, req.(*QueryClientStateRequest)) } return interceptor(ctx, in, info, handler) } func _Query_ClientStates_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryClientStatesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).ClientStates(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.client.v1.Query/ClientStates", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).ClientStates(ctx, req.(*QueryClientStatesRequest)) } return interceptor(ctx, in, info, handler) } func _Query_ConsensusState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryConsensusStateRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).ConsensusState(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.client.v1.Query/ConsensusState", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).ConsensusState(ctx, req.(*QueryConsensusStateRequest)) } return interceptor(ctx, in, info, handler) } func _Query_ConsensusStates_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryConsensusStatesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).ConsensusStates(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.client.v1.Query/ConsensusStates", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).ConsensusStates(ctx, req.(*QueryConsensusStatesRequest)) } return interceptor(ctx, in, info, handler) } func _Query_Relayers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryRelayersRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).Relayers(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.client.v1.Query/Relayers", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).Relayers(ctx, req.(*QueryRelayersRequest)) } return interceptor(ctx, in, info, handler) } var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "tibc.core.client.v1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "ClientState", Handler: _Query_ClientState_Handler, }, { MethodName: "ClientStates", Handler: _Query_ClientStates_Handler, }, { MethodName: "ConsensusState", Handler: _Query_ConsensusState_Handler, }, { MethodName: "ConsensusStates", Handler: _Query_ConsensusStates_Handler, }, { MethodName: "Relayers", Handler: _Query_Relayers_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "tibc/core/client/v1/query.proto", } func (m *QueryClientStateRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryClientStateRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryClientStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryClientStateResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryClientStateResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryClientStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.Proof) > 0 { i -= len(m.Proof) copy(dAtA[i:], m.Proof) i = encodeVarintQuery(dAtA, i, uint64(len(m.Proof))) i-- dAtA[i] = 0x12 } if m.ClientState != nil { { size, err := m.ClientState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryClientStatesRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryClientStatesRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryClientStatesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryClientStatesResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryClientStatesResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryClientStatesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.ClientStates) > 0 { for iNdEx := len(m.ClientStates) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.ClientStates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *QueryConsensusStateRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryConsensusStateRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryConsensusStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.LatestHeight { i-- if m.LatestHeight { dAtA[i] = 1 } else { dAtA[i] = 0 } i-- dAtA[i] = 0x20 } if m.RevisionHeight != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.RevisionHeight)) i-- dAtA[i] = 0x18 } if m.RevisionNumber != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.RevisionNumber)) i-- dAtA[i] = 0x10 } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryConsensusStateResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryConsensusStateResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryConsensusStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.Proof) > 0 { i -= len(m.Proof) copy(dAtA[i:], m.Proof) i = encodeVarintQuery(dAtA, i, uint64(len(m.Proof))) i-- dAtA[i] = 0x12 } if m.ConsensusState != nil { { size, err := m.ConsensusState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryConsensusStatesRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryConsensusStatesRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryConsensusStatesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryConsensusStatesResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryConsensusStatesResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryConsensusStatesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.ConsensusStates) > 0 { for iNdEx := len(m.ConsensusStates) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.ConsensusStates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *QueryRelayersRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryRelayersRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryRelayersRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintQuery(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryRelayersResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryRelayersResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryRelayersResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Relayers) > 0 { for iNdEx := len(m.Relayers) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Relayers[iNdEx]) copy(dAtA[i:], m.Relayers[iNdEx]) i = encodeVarintQuery(dAtA, i, uint64(len(m.Relayers[iNdEx]))) i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { offset -= sovQuery(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *QueryClientStateRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryClientStateResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.ClientState != nil { l = m.ClientState.Size() n += 1 + l + sovQuery(uint64(l)) } l = len(m.Proof) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryClientStatesRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryClientStatesResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.ClientStates) > 0 { for _, e := range m.ClientStates { l = e.Size() n += 1 + l + sovQuery(uint64(l)) } } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryConsensusStateRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.RevisionNumber != 0 { n += 1 + sovQuery(uint64(m.RevisionNumber)) } if m.RevisionHeight != 0 { n += 1 + sovQuery(uint64(m.RevisionHeight)) } if m.LatestHeight { n += 2 } return n } func (m *QueryConsensusStateResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.ConsensusState != nil { l = m.ConsensusState.Size() n += 1 + l + sovQuery(uint64(l)) } l = len(m.Proof) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryConsensusStatesRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryConsensusStatesResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.ConsensusStates) > 0 { for _, e := range m.ConsensusStates { l = e.Size() n += 1 + l + sovQuery(uint64(l)) } } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryRelayersRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryRelayersResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Relayers) > 0 { for _, s := range m.Relayers { l = len(s) n += 1 + l + sovQuery(uint64(l)) } } return n } func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozQuery(x uint64) (n int) { return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *QueryClientStateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryClientStateRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryClientStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryClientStateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryClientStateResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryClientStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.ClientState == nil { m.ClientState = &types.Any{} } if err := m.ClientState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof[:0], dAtA[iNdEx:postIndex]...) if m.Proof == nil { m.Proof = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryClientStatesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryClientStatesRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryClientStatesRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageRequest{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryClientStatesResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryClientStatesResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryClientStatesResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientStates", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.ClientStates = append(m.ClientStates, IdentifiedClientState{}) if err := m.ClientStates[len(m.ClientStates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageResponse{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryConsensusStateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryConsensusStateRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryConsensusStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field RevisionNumber", wireType) } m.RevisionNumber = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.RevisionNumber |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field RevisionHeight", wireType) } m.RevisionHeight = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.RevisionHeight |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field LatestHeight", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int(b&0x7F) << shift if b < 0x80 { break } } m.LatestHeight = bool(v != 0) default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryConsensusStateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryConsensusStateResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryConsensusStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsensusState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.ConsensusState == nil { m.ConsensusState = &types.Any{} } if err := m.ConsensusState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof[:0], dAtA[iNdEx:postIndex]...) if m.Proof == nil { m.Proof = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryConsensusStatesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryConsensusStatesRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryConsensusStatesRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageRequest{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryConsensusStatesResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryConsensusStatesResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryConsensusStatesResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsensusStates", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.ConsensusStates = append(m.ConsensusStates, ConsensusStateWithHeight{}) if err := m.ConsensusStates[len(m.ConsensusStates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageResponse{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryRelayersRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryRelayersRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryRelayersRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryRelayersResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryRelayersResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryRelayersResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Relayers", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Relayers = append(m.Relayers, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthQuery } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupQuery } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthQuery } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/light-clients/09-eth/types/codec.go<|end_filename|> package types import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" ) // RegisterInterfaces registers the tendermint concrete client-related // implementations and interfaces. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations( (*exported.ClientState)(nil), &ClientState{}, ) registry.RegisterImplementations( (*exported.ConsensusState)(nil), &ConsensusState{}, ) registry.RegisterImplementations( (*exported.Header)(nil), &Header{}, ) } <|start_filename|>modules/tibc/apps/nft_transfer/types/codec.go<|end_filename|> package types import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" ) var ( amino = codec.NewLegacyAmino() ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) // AminoCdc is a amino codec created to support amino json compatible msgs. AminoCdc = codec.NewAminoCodec(amino) ) func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgNftTransfer{}, "cosmos-sdk/MsgNftTransfer", nil) } // RegisterInterfaces register the tibc-transfer module interfaces to protobuf // Any. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgNftTransfer{}) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } func init() { RegisterLegacyAminoCodec(amino) amino.Seal() } <|start_filename|>modules/tibc/core/types/metrics.go<|end_filename|> package types // Prometheus metric labels. const ( LabelPort = "port" LabelSourceChain = "source_chain" LabelDestinationChain = "destination_chain" LabelRelayChain = "destination_chain" LabelDenom = "denom" LabelSource = "source" ) <|start_filename|>modules/tibc/core/types/genesis.go<|end_filename|> package types import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" routingtypes "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) var _ codectypes.UnpackInterfacesMessage = GenesisState{} // DefaultGenesisState returns the tibc module's default genesis state. func DefaultGenesisState() *GenesisState { return &GenesisState{ ClientGenesis: clienttypes.DefaultGenesisState(), PacketGenesis: packettypes.DefaultGenesisState(), RoutingGenesis: routingtypes.DefaultGenesisState(), } } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (gs GenesisState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { return gs.ClientGenesis.UnpackInterfaces(unpacker) } // Validate performs basic genesis state validation returning an error upon any // failure. func (gs *GenesisState) Validate() error { if err := gs.ClientGenesis.Validate(); err != nil { return err } return gs.PacketGenesis.Validate() } <|start_filename|>modules/tibc/core/02-client/genesis.go<|end_filename|> package client import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/keeper" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" ) // InitGenesis initializes the tibc client submodule's state from a provided genesis // state. func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs types.GenesisState) { // Set all client metadata first. This will allow client keeper to overwrite client and consensus state keys // if clients accidentally write to ClientKeeper reserved keys. if len(gs.ClientsMetadata) != 0 { k.SetAllClientMetadata(ctx, gs.ClientsMetadata) } for _, client := range gs.Clients { cs, ok := client.ClientState.GetCachedValue().(exported.ClientState) if !ok { panic("invalid client state") } k.SetClientState(ctx, client.ChainName, cs) } for _, cs := range gs.ClientsConsensus { for _, consState := range cs.ConsensusStates { consensusState, ok := consState.ConsensusState.GetCachedValue().(exported.ConsensusState) if !ok { panic(fmt.Sprintf("invalid consensus state with chain name %s at height %s", cs.ChainName, consState.Height)) } k.SetClientConsensusState(ctx, cs.ChainName, consState.Height, consensusState) } } for _, rs := range gs.Relayers { k.RegisterRelayers(ctx, rs.ChainName, rs.Relayers) } k.SetChainName(ctx, gs.NativeChainName) } // ExportGenesis returns the tibc client submodule's exported genesis. // NOTE: CreateLocalhost should always be false on export since a // created localhost will be included in the exported clients. func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { genClients := k.GetAllGenesisClients(ctx) clientsMetadata, err := k.GetAllClientMetadata(ctx, genClients) if err != nil { panic(err) } return types.GenesisState{ Clients: genClients, ClientsMetadata: clientsMetadata, ClientsConsensus: k.GetAllConsensusStates(ctx), NativeChainName: k.GetChainName(ctx), Relayers: k.GetAllRelayers(ctx), } } <|start_filename|>modules/tibc/core/26-routing/types/codec.go<|end_filename|> package types import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) // RegisterInterfaces registers the routing interfaces to protobuf Any. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations( (*govtypes.Content)(nil), &SetRoutingRulesProposal{}, ) } <|start_filename|>modules/tibc/core/04-packet/types/expected_keepers.go<|end_filename|> package types import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" ) // ClientKeeper expected account TIBC client keeper type ClientKeeper interface { GetClientState(ctx sdk.Context, chainName string) (exported.ClientState, bool) GetClientConsensusState(ctx sdk.Context, chainName string, height exported.Height) (exported.ConsensusState, bool) ClientStore(ctx sdk.Context, chainName string) sdk.KVStore GetChainName(ctx sdk.Context) string } // PortKeeper expected account TIBC port keeper type RoutingKeeper interface { Authenticate(ctx sdk.Context, sourceChain, destinationChain, port string) bool } <|start_filename|>modules/tibc/core/26-routing/keeper/proposal.go<|end_filename|> package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // HandleSetRoutingRulesProposal will try to set routing rules if and only if the proposal passes. func (k Keeper) HandleSetRoutingRulesProposal(ctx sdk.Context, p *types.SetRoutingRulesProposal) error { return k.SetRoutingRules(ctx, p.Rules) } <|start_filename|>modules/tibc/core/26-routing/types/module.go<|end_filename|> package types import ( sdk "github.com/cosmos/cosmos-sdk/types" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" ) // TIBCModule defines an interface that implements all the callbacks // that modules must define as specified in TICS-26 type TIBCModule interface { // OnRecvPacket must return the acknowledgement bytes // In the case of an asynchronous acknowledgement, nil should be returned. OnRecvPacket( ctx sdk.Context, packet packettypes.Packet, ) (*sdk.Result, []byte, error) OnAcknowledgementPacket( ctx sdk.Context, packet packettypes.Packet, acknowledgement []byte, ) (*sdk.Result, error) } <|start_filename|>modules/tibc/core/26-routing/types/proposal.go<|end_filename|> package types import ( govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) const ( ProposalTypeSetRoutingRules = "SetRoutingRules" ) var ( _ govtypes.Content = &SetRoutingRulesProposal{} ) func init() { govtypes.RegisterProposalType(ProposalTypeSetRoutingRules) } // NewSetRoutingRulesProposal creates a new setting rules proposal. func NewSetRoutingRulesProposal(title, description string, rules []string) (*SetRoutingRulesProposal, error) { return &SetRoutingRulesProposal{ Title: title, Description: description, Rules: rules, }, nil } // GetTitle returns the title of a setting rules proposal. func (cup *SetRoutingRulesProposal) GetTitle() string { return cup.Title } // GetDescription returns the description of a setting rules proposal. func (cup *SetRoutingRulesProposal) GetDescription() string { return cup.Description } // ProposalRoute returns the routing key of a setting rules proposal. func (cup *SetRoutingRulesProposal) ProposalRoute() string { return RouterKey } // ProposalType returns the type of a setting rules proposal. func (cup *SetRoutingRulesProposal) ProposalType() string { return ProposalTypeSetRoutingRules } // ValidateBasic runs basic stateless validity checks func (cup *SetRoutingRulesProposal) ValidateBasic() error { err := govtypes.ValidateAbstract(cup) if err != nil { return err } if err := host.RoutingRulesValidator(cup.Rules); err != nil { return err } return nil } <|start_filename|>modules/tibc/light-clients/09-eth/types/consensus_state.go<|end_filename|> package types import ( commitmenttypes "github.com/bianjieai/tibc-go/modules/tibc/core/23-commitment/types" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" ) var _ exported.ConsensusState = (*ConsensusState)(nil) func (m *ConsensusState) ClientType() string { return exported.BSC } func (m *ConsensusState) GetRoot() exported.Root { return commitmenttypes.MerkleRoot{ Hash: m.Root, } } func (m *ConsensusState) GetTimestamp() uint64 { return m.Timestamp } func (m *ConsensusState) ValidateBasic() error { return nil } <|start_filename|>modules/tibc/light-clients/07-tendermint/types/errors.go<|end_filename|> package types import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) const ( SubModuleName = "tendermint-client" moduleName = host.ModuleName + "-" + SubModuleName ) // TIBC tendermint client sentinel errors var ( ErrInvalidChainID = sdkerrors.Register(moduleName, 2, "invalid chain-id") ErrInvalidTrustingPeriod = sdkerrors.Register(moduleName, 3, "invalid trusting period") ErrInvalidUnbondingPeriod = sdkerrors.Register(moduleName, 4, "invalid unbonding period") ErrInvalidHeaderHeight = sdkerrors.Register(moduleName, 5, "invalid header height") ErrInvalidHeader = sdkerrors.Register(moduleName, 6, "invalid header") ErrInvalidMaxClockDrift = sdkerrors.Register(moduleName, 7, "invalid max clock drift") ErrProcessedTimeNotFound = sdkerrors.Register(moduleName, 8, "processed time not found") ErrDelayPeriodNotPassed = sdkerrors.Register(moduleName, 9, "packet-specified delay period has not been reached") ErrTrustingPeriodExpired = sdkerrors.Register(moduleName, 10, "time since latest trusted state has passed the trusting period") ErrUnbondingPeriodExpired = sdkerrors.Register(moduleName, 11, "time since latest trusted state has passed the unbonding period") ErrInvalidProofSpecs = sdkerrors.Register(moduleName, 12, "invalid proof specs") ErrInvalidValidatorSet = sdkerrors.Register(moduleName, 13, "invalid validator set") ) <|start_filename|>modules/tibc/core/04-packet/types/packet_test.go<|end_filename|> package types_test import ( "testing" "github.com/stretchr/testify/require" codectypes "github.com/cosmos/cosmos-sdk/codec/types" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" ) func TestCommitPacket(t *testing.T) { packet := types.NewPacket(validPacketData, 1, sourceChain, destChain, relayChain, port) registry := codectypes.NewInterfaceRegistry() clienttypes.RegisterInterfaces(registry) types.RegisterInterfaces(registry) commitment := types.CommitPacket(&packet) require.NotNil(t, commitment) } func TestPacketValidateBasic(t *testing.T) { testCases := []struct { packet types.Packet expPass bool errMsg string }{ {types.NewPacket(validPacketData, 1, sourceChain, destChain, relayChain, port), true, ""}, {types.NewPacket(validPacketData, 0, sourceChain, destChain, relayChain, port), false, "invalid sequence"}, // {types.NewPacket(validPacketData, 1, invalidPort, destChain, relayChain, port), false, "invalid source port"}, // {types.NewPacket(validPacketData, 1, sourceChain, destChain, relayChain, invalidPort), false, "invalid port"}, {types.NewPacket(unknownPacketData, 1, sourceChain, destChain, relayChain, port), true, ""}, } for i, tc := range testCases { err := tc.packet.ValidateBasic() if tc.expPass { require.NoError(t, err, "Case %d failed: %s", i, tc.errMsg) } else { require.Error(t, err, "Invalid Case %d passed: %s", i, tc.errMsg) } } } <|start_filename|>modules/tibc/core/04-packet/module.go<|end_filename|> package packet import ( "github.com/gogo/protobuf/grpc" "github.com/spf13/cobra" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/client/cli" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" ) // Name returns the TIBC packet TICS name. func Name() string { return types.SubModuleName } // GetTxCmd returns the root tx command for TIBC packet. func GetTxCmd() *cobra.Command { return cli.NewTxCmd() } // GetQueryCmd returns the root query command for TIBC packet. func GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } // RegisterQueryService registers the gRPC query service for TIBC packet. func RegisterQueryService(server grpc.Server, queryServer types.QueryServer) { types.RegisterQueryServer(server, queryServer) } <|start_filename|>modules/tibc/core/26-routing/types/genesis.go<|end_filename|> package types import ( "regexp" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) func DefaultGenesisState() GenesisState { return GenesisState{ Rules: []string{}, } } func NewGenesisState(rules []string) GenesisState { return GenesisState{ Rules: rules, } } func (gs GenesisState) Validate() error { for _, rule := range gs.Rules { valid, _ := regexp.MatchString(RulePattern, rule) if !valid { return sdkerrors.Wrap(ErrInvalidRule, "invalid rule") } } return nil } <|start_filename|>modules/tibc/core/client/cli/cli.go<|end_filename|> package cli import ( "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" ibcclient "github.com/bianjieai/tibc-go/modules/tibc/core/02-client" packet "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" routing "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing" ) // GetTxCmd returns the transaction commands for this module func GetTxCmd() *cobra.Command { ibcTxCmd := &cobra.Command{ Use: host.ModuleName, Short: "IBC transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } ibcTxCmd.AddCommand( ibcclient.GetTxCmd(), packet.GetTxCmd(), ) return ibcTxCmd } // GetQueryCmd returns the cli query commands for this module func GetQueryCmd() *cobra.Command { // Group tibc queries under a subcommand ibcQueryCmd := &cobra.Command{ Use: host.ModuleName, Short: "Querying commands for the TIBC module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } ibcQueryCmd.AddCommand( ibcclient.GetQueryCmd(), packet.GetQueryCmd(), routing.GetQueryCmd(), ) return ibcQueryCmd } <|start_filename|>modules/tibc/core/04-packet/keeper/grpc_query.go<|end_filename|> package keeper import ( "context" "strconv" "strings" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) var _ types.QueryServer = (*Keeper)(nil) //PacketCommitment implements the Query/PacketCommitment gRPC method func (q Keeper) PacketCommitment(c context.Context, req *types.QueryPacketCommitmentRequest) (*types.QueryPacketCommitmentResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } if req.Sequence == 0 { return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0") } ctx := sdk.UnwrapSDKContext(c) commitmentBz := q.GetPacketCommitment(ctx, req.SourceChain, req.DestChain, req.Sequence) if len(commitmentBz) == 0 { return nil, status.Error(codes.NotFound, "packet commitment hash not found") } selfHeight := clienttypes.GetSelfHeight(ctx) return types.NewQueryPacketCommitmentResponse(commitmentBz, nil, selfHeight), nil } // PacketCommitments implements the Query/PacketCommitments gRPC method func (q Keeper) PacketCommitments(c context.Context, req *types.QueryPacketCommitmentsRequest) (*types.QueryPacketCommitmentsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) commitments := []*types.PacketState{} store := prefix.NewStore(ctx.KVStore(q.storeKey), []byte(host.PacketCommitmentPrefixPath(req.SourceChain, req.DestChain))) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { keySplit := strings.Split(string(key), "/") sequence, err := strconv.ParseUint(keySplit[len(keySplit)-1], 10, 64) if err != nil { return err } commitment := types.NewPacketState(req.SourceChain, req.DestChain, sequence, value) commitments = append(commitments, &commitment) return nil }) if err != nil { return nil, err } selfHeight := clienttypes.GetSelfHeight(ctx) return &types.QueryPacketCommitmentsResponse{ Commitments: commitments, Pagination: pageRes, Height: selfHeight, }, nil } // PacketReceipt implements the Query/PacketReceipt gRPC method func (q Keeper) PacketReceipt(c context.Context, req *types.QueryPacketReceiptRequest) (*types.QueryPacketReceiptResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } if req.Sequence == 0 { return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0") } ctx := sdk.UnwrapSDKContext(c) _, recvd := q.GetPacketReceipt(ctx, req.SourceChain, req.DestChain, req.Sequence) selfHeight := clienttypes.GetSelfHeight(ctx) return types.NewQueryPacketReceiptResponse(recvd, nil, selfHeight), nil } // PacketAcknowledgement implements the Query/PacketAcknowledgement gRPC method func (q Keeper) PacketAcknowledgement(c context.Context, req *types.QueryPacketAcknowledgementRequest) (*types.QueryPacketAcknowledgementResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } if req.Sequence == 0 { return nil, status.Error(codes.InvalidArgument, "packet sequence cannot be 0") } ctx := sdk.UnwrapSDKContext(c) acknowledgementBz, found := q.GetPacketAcknowledgement(ctx, req.SourceChain, req.DestChain, req.Sequence) if !found || len(acknowledgementBz) == 0 { return nil, status.Error(codes.NotFound, "packet acknowledgement hash not found") } selfHeight := clienttypes.GetSelfHeight(ctx) return types.NewQueryPacketAcknowledgementResponse(acknowledgementBz, nil, selfHeight), nil } // PacketAcknowledgements implements the Query/PacketAcknowledgements gRPC method func (q Keeper) PacketAcknowledgements(c context.Context, req *types.QueryPacketAcknowledgementsRequest) (*types.QueryPacketAcknowledgementsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) acks := []*types.PacketState{} store := prefix.NewStore(ctx.KVStore(q.storeKey), []byte(host.PacketAcknowledgementPrefixPath(req.SourceChain, req.DestChain))) pageRes, err := query.Paginate(store, req.Pagination, func(key, value []byte) error { keySplit := strings.Split(string(key), "/") sequence, err := strconv.ParseUint(keySplit[len(keySplit)-1], 10, 64) if err != nil { return err } ack := types.NewPacketState(req.SourceChain, req.DestChain, sequence, value) acks = append(acks, &ack) return nil }) if err != nil { return nil, err } selfHeight := clienttypes.GetSelfHeight(ctx) return &types.QueryPacketAcknowledgementsResponse{ Acknowledgements: acks, Pagination: pageRes, Height: selfHeight, }, nil } // UnreceivedPackets implements the Query/UnreceivedPackets gRPC method. Given // a list of counterparty packet commitments, the querier checks if the packet // has already been received by checking if a receipt exists on this // chain for the packet sequence. All packets that haven't been received yet // are returned in the response // Usage: To use this method correctly, first query all packet commitments on // the sending chain using the Query/PacketCommitments gRPC method. // Then input the returned sequences into the QueryUnreceivedPacketsRequest // and send the request to this Query/UnreceivedPackets on the **receiving** // chain. This gRPC method will then return the list of packet sequences that // are yet to be received on the receiving chain. // // NOTE: The querier makes the assumption that the provided list of packet // commitments is correct and will not function properly if the list // is not up to date. Ideally the query height should equal the latest height // on the counterparty's client which represents this chain. func (q Keeper) UnreceivedPackets(c context.Context, req *types.QueryUnreceivedPacketsRequest) (*types.QueryUnreceivedPacketsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) var unreceivedSequences = []uint64{} for i, seq := range req.PacketCommitmentSequences { if seq == 0 { return nil, status.Errorf(codes.InvalidArgument, "packet sequence %d cannot be 0", i) } // if packet receipt exists on the receiving chain, then packet has already been received if _, found := q.GetPacketReceipt(ctx, req.SourceChain, req.DestChain, seq); !found { unreceivedSequences = append(unreceivedSequences, seq) } } selfHeight := clienttypes.GetSelfHeight(ctx) return &types.QueryUnreceivedPacketsResponse{ Sequences: unreceivedSequences, Height: selfHeight, }, nil } // UnreceivedAcks implements the Query/UnreceivedAcks gRPC method. Given // a list of counterparty packet acknowledgements, the querier checks if the packet // has already been received by checking if the packet commitment still exists on this // chain (original sender) for the packet sequence. // All acknowledgmeents that haven't been received yet are returned in the response. // Usage: To use this method correctly, first query all packet acknowledgements on // the original receiving chain (ie the chain that wrote the acks) using the Query/PacketAcknowledgements gRPC method. // Then input the returned sequences into the QueryUnreceivedAcksRequest // and send the request to this Query/UnreceivedAcks on the **original sending** // chain. This gRPC method will then return the list of packet sequences whose // acknowledgements are already written on the receiving chain but haven't yet // been received back to the sending chain. // // NOTE: The querier makes the assumption that the provided list of packet // acknowledgements is correct and will not function properly if the list // is not up to date. Ideally the query height should equal the latest height // on the counterparty's client which represents this chain. func (q Keeper) UnreceivedAcks(c context.Context, req *types.QueryUnreceivedAcksRequest) (*types.QueryUnreceivedAcksResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) var unreceivedSequences = []uint64{} for i, seq := range req.PacketAckSequences { if seq == 0 { return nil, status.Errorf(codes.InvalidArgument, "packet sequence %d cannot be 0", i) } // if packet commitment still exists on the original sending chain, then packet ack has not been received // since processing the ack will delete the packet commitment if commitment := q.GetPacketCommitment(ctx, req.SourceChain, req.DestChain, seq); len(commitment) != 0 { unreceivedSequences = append(unreceivedSequences, seq) } } selfHeight := clienttypes.GetSelfHeight(ctx) return &types.QueryUnreceivedAcksResponse{ Sequences: unreceivedSequences, Height: selfHeight, }, nil } //CleanPacketCommitment implements the Query/PacketCommitment gRPC method func (q Keeper) CleanPacketCommitment(c context.Context, req *types.QueryCleanPacketCommitmentRequest) (*types.QueryCleanPacketCommitmentResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } if err := validategRPCRequest(req.SourceChain, req.DestChain); err != nil { return nil, err } ctx := sdk.UnwrapSDKContext(c) commitmentBz := q.GetCleanPacketCommitment(ctx, req.SourceChain, req.DestChain) if len(commitmentBz) == 0 { return nil, status.Error(codes.NotFound, "packet commitment hash not found") } selfHeight := clienttypes.GetSelfHeight(ctx) return types.NewQueryCleanPacketCommitmentResponse(commitmentBz, nil, selfHeight), nil } func validategRPCRequest(sourceChain, destChain string) error { if err := host.SourceChainValidator(sourceChain); err != nil { return status.Error(codes.InvalidArgument, err.Error()) } if err := host.DestChainValidator(destChain); err != nil { return status.Error(codes.InvalidArgument, err.Error()) } return nil } <|start_filename|>modules/tibc/light-clients/07-tendermint/types/tendermint.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/lightclients/tendermint/v1/tendermint.proto package types import ( fmt "fmt" types "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" types1 "github.com/bianjieai/tibc-go/modules/tibc/core/23-commitment/types" _go "github.com/confio/ics23/go" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" _ "github.com/golang/protobuf/ptypes/duration" _ "github.com/golang/protobuf/ptypes/timestamp" github_com_tendermint_tendermint_libs_bytes "github.com/tendermint/tendermint/libs/bytes" types2 "github.com/tendermint/tendermint/proto/tendermint/types" io "io" math "math" math_bits "math/bits" time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // ClientState from Tendermint tracks the current validator set, latest height, // and a possible frozen height. type ClientState struct { ChainId string `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` TrustLevel Fraction `protobuf:"bytes,2,opt,name=trust_level,json=trustLevel,proto3" json:"trust_level"` // duration of the period since the LastestTimestamp during which the // submitted headers are valid for upgrade TrustingPeriod time.Duration `protobuf:"bytes,3,opt,name=trusting_period,json=trustingPeriod,proto3,stdduration" json:"trusting_period"` // duration of the staking unbonding period UnbondingPeriod time.Duration `protobuf:"bytes,4,opt,name=unbonding_period,json=unbondingPeriod,proto3,stdduration" json:"unbonding_period"` // defines how much new (untrusted) header's Time can drift into the future. MaxClockDrift time.Duration `protobuf:"bytes,5,opt,name=max_clock_drift,json=maxClockDrift,proto3,stdduration" json:"max_clock_drift"` // latest height the client was updated to LatestHeight types.Height `protobuf:"bytes,6,opt,name=latest_height,json=latestHeight,proto3" json:"latest_height"` // proof specifications used in verifying counterparty state ProofSpecs []*_go.ProofSpec `protobuf:"bytes,7,rep,name=proof_specs,json=proofSpecs,proto3" json:"proof_specs,omitempty"` // commitment merkle prefix of the counterparty chain. MerklePrefix types1.MerklePrefix `protobuf:"bytes,8,opt,name=MerklePrefix,proto3" json:"MerklePrefix"` // period of transaction confirmation delay TimeDelay uint64 `protobuf:"varint,9,opt,name=timeDelay,proto3" json:"timeDelay,omitempty"` } func (m *ClientState) Reset() { *m = ClientState{} } func (m *ClientState) String() string { return proto.CompactTextString(m) } func (*ClientState) ProtoMessage() {} func (*ClientState) Descriptor() ([]byte, []int) { return fileDescriptor_a157e822442c0495, []int{0} } func (m *ClientState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ClientState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ClientState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ClientState) XXX_Merge(src proto.Message) { xxx_messageInfo_ClientState.Merge(m, src) } func (m *ClientState) XXX_Size() int { return m.Size() } func (m *ClientState) XXX_DiscardUnknown() { xxx_messageInfo_ClientState.DiscardUnknown(m) } var xxx_messageInfo_ClientState proto.InternalMessageInfo // ConsensusState defines the consensus state from Tendermint. type ConsensusState struct { // timestamp that corresponds to the block height in which the ConsensusState // was stored. Timestamp time.Time `protobuf:"bytes,1,opt,name=timestamp,proto3,stdtime" json:"timestamp"` // commitment root (i.e app hash) Root types1.MerkleRoot `protobuf:"bytes,2,opt,name=root,proto3" json:"root"` NextValidatorsHash github_com_tendermint_tendermint_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=next_validators_hash,json=nextValidatorsHash,proto3,casttype=github.com/tendermint/tendermint/libs/bytes.HexBytes" json:"next_validators_hash,omitempty"` } func (m *ConsensusState) Reset() { *m = ConsensusState{} } func (m *ConsensusState) String() string { return proto.CompactTextString(m) } func (*ConsensusState) ProtoMessage() {} func (*ConsensusState) Descriptor() ([]byte, []int) { return fileDescriptor_a157e822442c0495, []int{1} } func (m *ConsensusState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ConsensusState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ConsensusState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ConsensusState) XXX_Merge(src proto.Message) { xxx_messageInfo_ConsensusState.Merge(m, src) } func (m *ConsensusState) XXX_Size() int { return m.Size() } func (m *ConsensusState) XXX_DiscardUnknown() { xxx_messageInfo_ConsensusState.DiscardUnknown(m) } var xxx_messageInfo_ConsensusState proto.InternalMessageInfo // Header defines the Tendermint client consensus Header. // It encapsulates all the information necessary to update from a trusted // Tendermint ConsensusState. The inclusion of TrustedHeight and // TrustedValidators allows this update to process correctly, so long as the // ConsensusState for the TrustedHeight exists, this removes race conditions // among relayers The SignedHeader and ValidatorSet are the new untrusted update // fields for the client. The TrustedHeight is the height of a stored // ConsensusState on the client that will be used to verify the new untrusted // header. The Trusted ConsensusState must be within the unbonding period of // current time in order to correctly verify, and the TrustedValidators must // hash to TrustedConsensusState.NextValidatorsHash since that is the last // trusted validator set at the TrustedHeight. type Header struct { *types2.SignedHeader `protobuf:"bytes,1,opt,name=signed_header,json=signedHeader,proto3,embedded=signed_header" json:"signed_header,omitempty"` ValidatorSet *types2.ValidatorSet `protobuf:"bytes,2,opt,name=validator_set,json=validatorSet,proto3" json:"validator_set,omitempty"` TrustedHeight types.Height `protobuf:"bytes,3,opt,name=trusted_height,json=trustedHeight,proto3" json:"trusted_height"` TrustedValidators *types2.ValidatorSet `protobuf:"bytes,4,opt,name=trusted_validators,json=trustedValidators,proto3" json:"trusted_validators,omitempty"` } func (m *Header) Reset() { *m = Header{} } func (m *Header) String() string { return proto.CompactTextString(m) } func (*Header) ProtoMessage() {} func (*Header) Descriptor() ([]byte, []int) { return fileDescriptor_a157e822442c0495, []int{2} } func (m *Header) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Header) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Header.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Header) XXX_Merge(src proto.Message) { xxx_messageInfo_Header.Merge(m, src) } func (m *Header) XXX_Size() int { return m.Size() } func (m *Header) XXX_DiscardUnknown() { xxx_messageInfo_Header.DiscardUnknown(m) } var xxx_messageInfo_Header proto.InternalMessageInfo func (m *Header) GetValidatorSet() *types2.ValidatorSet { if m != nil { return m.ValidatorSet } return nil } func (m *Header) GetTrustedHeight() types.Height { if m != nil { return m.TrustedHeight } return types.Height{} } func (m *Header) GetTrustedValidators() *types2.ValidatorSet { if m != nil { return m.TrustedValidators } return nil } // Fraction defines the protobuf message type for tmmath.Fraction that only // supports positive values. type Fraction struct { Numerator uint64 `protobuf:"varint,1,opt,name=numerator,proto3" json:"numerator,omitempty"` Denominator uint64 `protobuf:"varint,2,opt,name=denominator,proto3" json:"denominator,omitempty"` } func (m *Fraction) Reset() { *m = Fraction{} } func (m *Fraction) String() string { return proto.CompactTextString(m) } func (*Fraction) ProtoMessage() {} func (*Fraction) Descriptor() ([]byte, []int) { return fileDescriptor_a157e822442c0495, []int{3} } func (m *Fraction) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Fraction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Fraction.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Fraction) XXX_Merge(src proto.Message) { xxx_messageInfo_Fraction.Merge(m, src) } func (m *Fraction) XXX_Size() int { return m.Size() } func (m *Fraction) XXX_DiscardUnknown() { xxx_messageInfo_Fraction.DiscardUnknown(m) } var xxx_messageInfo_Fraction proto.InternalMessageInfo func (m *Fraction) GetNumerator() uint64 { if m != nil { return m.Numerator } return 0 } func (m *Fraction) GetDenominator() uint64 { if m != nil { return m.Denominator } return 0 } func init() { proto.RegisterType((*ClientState)(nil), "tibc.lightclients.tendermint.v1.ClientState") proto.RegisterType((*ConsensusState)(nil), "tibc.lightclients.tendermint.v1.ConsensusState") proto.RegisterType((*Header)(nil), "tibc.lightclients.tendermint.v1.Header") proto.RegisterType((*Fraction)(nil), "tibc.lightclients.tendermint.v1.Fraction") } func init() { proto.RegisterFile("tibc/lightclients/tendermint/v1/tendermint.proto", fileDescriptor_a157e822442c0495) } var fileDescriptor_a157e822442c0495 = []byte{ // 813 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0xcf, 0x6e, 0xdb, 0x36, 0x1c, 0xb6, 0x12, 0x2f, 0x4d, 0x68, 0xbb, 0xe9, 0xb8, 0x1e, 0xdc, 0xac, 0x90, 0x8d, 0x0c, 0x03, 0xbc, 0x43, 0xa4, 0x3a, 0x1d, 0xb0, 0x61, 0xc0, 0x2e, 0x4e, 0x50, 0xb8, 0x6b, 0xbb, 0x05, 0xca, 0xb0, 0xc3, 0x2e, 0x02, 0x25, 0xfd, 0x2c, 0xb1, 0x95, 0x48, 0x41, 0xa4, 0x0c, 0xe7, 0x01, 0x06, 0xec, 0xd8, 0xe3, 0x8e, 0x7b, 0x85, 0xbd, 0x45, 0x8f, 0xb9, 0x0c, 0xd8, 0x29, 0x1b, 0x92, 0xb7, 0xd8, 0x69, 0x20, 0x45, 0xd9, 0x44, 0x3b, 0x20, 0xb9, 0x18, 0xfc, 0xfd, 0xf9, 0x3e, 0xf3, 0xf7, 0xe9, 0x23, 0x89, 0x9e, 0x48, 0x1a, 0xc5, 0x7e, 0x4e, 0xd3, 0x4c, 0xc6, 0x39, 0x05, 0x26, 0x85, 0x2f, 0x81, 0x25, 0x50, 0x15, 0x94, 0x49, 0x7f, 0x39, 0xb5, 0x22, 0xaf, 0xac, 0xb8, 0xe4, 0x78, 0xa4, 0x10, 0x9e, 0x8d, 0xf0, 0xac, 0x9e, 0xe5, 0xf4, 0x60, 0x6c, 0x11, 0xc8, 0x8b, 0x12, 0x84, 0xbf, 0x24, 0x39, 0x4d, 0x88, 0xe4, 0x55, 0x43, 0x71, 0xf0, 0xf8, 0x83, 0x0e, 0xfd, 0x6b, 0xaa, 0x9f, 0xc4, 0x9c, 0x2d, 0x28, 0xf7, 0xcb, 0x8a, 0xf3, 0x45, 0x9b, 0x74, 0x53, 0xce, 0xd3, 0x1c, 0x7c, 0x1d, 0x45, 0xf5, 0xc2, 0x4f, 0xea, 0x8a, 0x48, 0xca, 0x99, 0xa9, 0x8f, 0xde, 0xaf, 0x4b, 0x5a, 0x80, 0x90, 0xa4, 0x28, 0x4d, 0xc3, 0x58, 0x0f, 0x1a, 0xf3, 0x0a, 0xfc, 0x66, 0xdb, 0x6a, 0xb8, 0x66, 0x65, 0x3a, 0x26, 0x56, 0x07, 0x2f, 0x0a, 0x2a, 0x8b, 0xb6, 0x6b, 0x1d, 0x99, 0xce, 0x87, 0x29, 0x4f, 0xb9, 0x5e, 0xfa, 0x6a, 0xd5, 0x64, 0x0f, 0xff, 0xec, 0xa2, 0xde, 0x89, 0x26, 0x3c, 0x97, 0x44, 0x02, 0x7e, 0x84, 0x76, 0xe3, 0x8c, 0x50, 0x16, 0xd2, 0x64, 0xe8, 0x8c, 0x9d, 0xc9, 0x5e, 0x70, 0x4f, 0xc7, 0xcf, 0x13, 0x7c, 0x86, 0x7a, 0xb2, 0xaa, 0x85, 0x0c, 0x73, 0x58, 0x42, 0x3e, 0xdc, 0x1a, 0x3b, 0x93, 0xde, 0xf1, 0x17, 0xde, 0x2d, 0xca, 0x7a, 0xcf, 0x2a, 0x12, 0xab, 0x99, 0x67, 0xdd, 0x77, 0x57, 0xa3, 0x4e, 0x80, 0x34, 0xc7, 0x4b, 0x45, 0x81, 0x5f, 0xa2, 0x7d, 0x1d, 0x51, 0x96, 0x86, 0x25, 0x54, 0x94, 0x27, 0xc3, 0x6d, 0xcd, 0xfa, 0xc8, 0x6b, 0x94, 0xf1, 0x5a, 0x65, 0xbc, 0x53, 0xa3, 0xdc, 0x6c, 0x57, 0xb1, 0xfc, 0xf6, 0xf7, 0xc8, 0x09, 0xee, 0xb7, 0xd8, 0x33, 0x0d, 0xc5, 0xdf, 0xa3, 0x07, 0x35, 0x8b, 0x38, 0x4b, 0x2c, 0xba, 0xee, 0xdd, 0xe9, 0xf6, 0xd7, 0x60, 0xc3, 0xf7, 0x02, 0xed, 0x17, 0x64, 0x15, 0xc6, 0x39, 0x8f, 0xdf, 0x84, 0x49, 0x45, 0x17, 0x72, 0xf8, 0xd1, 0xdd, 0xe9, 0x06, 0x05, 0x59, 0x9d, 0x28, 0xe8, 0xa9, 0x42, 0xe2, 0x67, 0x68, 0x90, 0x13, 0x09, 0x42, 0x86, 0x19, 0x28, 0xad, 0x86, 0x3b, 0x9a, 0xea, 0xd3, 0x46, 0x3e, 0xf5, 0xfd, 0x3c, 0xf3, 0x5d, 0x97, 0x53, 0x6f, 0xae, 0x5b, 0x8c, 0x60, 0xfd, 0x06, 0xd7, 0xe4, 0xf0, 0x14, 0xf5, 0xb4, 0xc5, 0x42, 0x51, 0x42, 0x2c, 0x86, 0xf7, 0xc6, 0xdb, 0x93, 0xde, 0xf1, 0x03, 0x8f, 0xc6, 0xe2, 0xf8, 0xa9, 0x77, 0xa6, 0x2a, 0xe7, 0x25, 0xc4, 0x01, 0x2a, 0xdb, 0xa5, 0xc0, 0x3f, 0xa0, 0xfe, 0x2b, 0xa8, 0xde, 0xe4, 0x70, 0x56, 0xc1, 0x82, 0xae, 0x86, 0xbb, 0xfa, 0x9f, 0x3f, 0xb7, 0xff, 0x79, 0xe3, 0x95, 0xe5, 0xd4, 0xb3, 0x9b, 0xdb, 0x3d, 0xd8, 0x39, 0xfc, 0x18, 0xed, 0x29, 0xa3, 0x9e, 0x42, 0x4e, 0x2e, 0x86, 0x7b, 0x63, 0x67, 0xd2, 0x0d, 0x36, 0x89, 0x6f, 0xba, 0xbf, 0xfe, 0x3e, 0xea, 0x1c, 0xfe, 0xb2, 0x85, 0xee, 0x9f, 0x70, 0x26, 0x80, 0x89, 0x5a, 0x34, 0xd6, 0x9a, 0x35, 0x30, 0xed, 0x6f, 0xed, 0xad, 0xde, 0xf1, 0xc1, 0x07, 0x4a, 0xfe, 0xd8, 0x76, 0x34, 0x52, 0xbe, 0x55, 0x52, 0x6e, 0x60, 0xf8, 0x5b, 0xd4, 0xad, 0x38, 0x97, 0xc6, 0x7c, 0x9f, 0xdd, 0x32, 0x43, 0xc0, 0x79, 0xab, 0xa2, 0x86, 0xe1, 0xd7, 0xe8, 0x21, 0x83, 0x95, 0x0c, 0xd7, 0x67, 0x5b, 0x84, 0x19, 0x11, 0x99, 0x76, 0x5d, 0x7f, 0xf6, 0xf5, 0xbf, 0x57, 0xa3, 0x2f, 0x53, 0x2a, 0xb3, 0x3a, 0x52, 0x74, 0xf6, 0x9d, 0x62, 0x2d, 0x73, 0x1a, 0x09, 0x3f, 0xba, 0x90, 0x20, 0xbc, 0x39, 0xac, 0x66, 0x6a, 0x11, 0x60, 0xc5, 0xfa, 0xd3, 0x9a, 0x74, 0x4e, 0x44, 0x66, 0x74, 0xf8, 0x63, 0x0b, 0xed, 0xcc, 0x81, 0x24, 0x50, 0xe1, 0xe7, 0x68, 0x20, 0x68, 0xca, 0x20, 0x09, 0x33, 0x9d, 0x30, 0x1a, 0xb8, 0xf6, 0x79, 0x69, 0xae, 0x94, 0x73, 0xdd, 0xd6, 0xc0, 0x66, 0xdd, 0xcb, 0xab, 0x91, 0x13, 0xf4, 0x85, 0x95, 0xc3, 0x27, 0x68, 0xb0, 0x1e, 0x21, 0x14, 0xd0, 0xea, 0xf1, 0x3f, 0x54, 0xeb, 0x4d, 0x9d, 0x83, 0x0c, 0xfa, 0x4b, 0x2b, 0xc2, 0x73, 0xd4, 0x9c, 0x20, 0xbd, 0x21, 0xed, 0xc9, 0xed, 0xbb, 0x7a, 0x72, 0x60, 0x80, 0xc6, 0x94, 0xaf, 0x10, 0x6e, 0x99, 0x36, 0xca, 0x9a, 0xb3, 0x77, 0xdb, 0x9e, 0x3e, 0x36, 0xc8, 0x8d, 0x7a, 0x87, 0xdf, 0xa1, 0xdd, 0xf6, 0xd2, 0x50, 0x5e, 0x63, 0x75, 0x01, 0x95, 0xaa, 0x68, 0xc1, 0xba, 0xc1, 0x26, 0x81, 0xc7, 0xa8, 0x97, 0x00, 0xe3, 0x05, 0x65, 0xba, 0xbe, 0xa5, 0xeb, 0x76, 0x6a, 0x06, 0xef, 0xae, 0x5d, 0xe7, 0xf2, 0xda, 0x75, 0xfe, 0xb9, 0x76, 0x9d, 0xb7, 0x37, 0x6e, 0xe7, 0xf2, 0xc6, 0xed, 0xfc, 0x75, 0xe3, 0x76, 0x7e, 0x7e, 0x61, 0x7d, 0xe9, 0x88, 0x12, 0xf6, 0x9a, 0x02, 0xa1, 0xbe, 0x1a, 0xfd, 0x28, 0xe5, 0x7e, 0xc1, 0x93, 0x3a, 0x57, 0x77, 0xfc, 0xfa, 0xa5, 0x39, 0x6a, 0x9f, 0x9a, 0x27, 0x5f, 0x1d, 0xbd, 0xff, 0x14, 0x44, 0x3b, 0xda, 0xc0, 0x4f, 0xff, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x84, 0x81, 0x67, 0x2b, 0x9a, 0x06, 0x00, 0x00, } func (m *ClientState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClientState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ClientState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.TimeDelay != 0 { i = encodeVarintTendermint(dAtA, i, uint64(m.TimeDelay)) i-- dAtA[i] = 0x48 } { size, err := m.MerklePrefix.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x42 if len(m.ProofSpecs) > 0 { for iNdEx := len(m.ProofSpecs) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.ProofSpecs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x3a } } { size, err := m.LatestHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x32 n3, err3 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.MaxClockDrift, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.MaxClockDrift):]) if err3 != nil { return 0, err3 } i -= n3 i = encodeVarintTendermint(dAtA, i, uint64(n3)) i-- dAtA[i] = 0x2a n4, err4 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.UnbondingPeriod, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.UnbondingPeriod):]) if err4 != nil { return 0, err4 } i -= n4 i = encodeVarintTendermint(dAtA, i, uint64(n4)) i-- dAtA[i] = 0x22 n5, err5 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.TrustingPeriod, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.TrustingPeriod):]) if err5 != nil { return 0, err5 } i -= n5 i = encodeVarintTendermint(dAtA, i, uint64(n5)) i-- dAtA[i] = 0x1a { size, err := m.TrustLevel.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 if len(m.ChainId) > 0 { i -= len(m.ChainId) copy(dAtA[i:], m.ChainId) i = encodeVarintTendermint(dAtA, i, uint64(len(m.ChainId))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *ConsensusState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ConsensusState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ConsensusState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.NextValidatorsHash) > 0 { i -= len(m.NextValidatorsHash) copy(dAtA[i:], m.NextValidatorsHash) i = encodeVarintTendermint(dAtA, i, uint64(len(m.NextValidatorsHash))) i-- dAtA[i] = 0x1a } { size, err := m.Root.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 n8, err8 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):]) if err8 != nil { return 0, err8 } i -= n8 i = encodeVarintTendermint(dAtA, i, uint64(n8)) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *Header) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Header) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Header) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.TrustedValidators != nil { { size, err := m.TrustedValidators.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 } { size, err := m.TrustedHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if m.ValidatorSet != nil { { size, err := m.ValidatorSet.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if m.SignedHeader != nil { { size, err := m.SignedHeader.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTendermint(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *Fraction) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Fraction) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Fraction) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Denominator != 0 { i = encodeVarintTendermint(dAtA, i, uint64(m.Denominator)) i-- dAtA[i] = 0x10 } if m.Numerator != 0 { i = encodeVarintTendermint(dAtA, i, uint64(m.Numerator)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } func encodeVarintTendermint(dAtA []byte, offset int, v uint64) int { offset -= sovTendermint(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *ClientState) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainId) if l > 0 { n += 1 + l + sovTendermint(uint64(l)) } l = m.TrustLevel.Size() n += 1 + l + sovTendermint(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.TrustingPeriod) n += 1 + l + sovTendermint(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.UnbondingPeriod) n += 1 + l + sovTendermint(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.MaxClockDrift) n += 1 + l + sovTendermint(uint64(l)) l = m.LatestHeight.Size() n += 1 + l + sovTendermint(uint64(l)) if len(m.ProofSpecs) > 0 { for _, e := range m.ProofSpecs { l = e.Size() n += 1 + l + sovTendermint(uint64(l)) } } l = m.MerklePrefix.Size() n += 1 + l + sovTendermint(uint64(l)) if m.TimeDelay != 0 { n += 1 + sovTendermint(uint64(m.TimeDelay)) } return n } func (m *ConsensusState) Size() (n int) { if m == nil { return 0 } var l int _ = l l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp) n += 1 + l + sovTendermint(uint64(l)) l = m.Root.Size() n += 1 + l + sovTendermint(uint64(l)) l = len(m.NextValidatorsHash) if l > 0 { n += 1 + l + sovTendermint(uint64(l)) } return n } func (m *Header) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.SignedHeader != nil { l = m.SignedHeader.Size() n += 1 + l + sovTendermint(uint64(l)) } if m.ValidatorSet != nil { l = m.ValidatorSet.Size() n += 1 + l + sovTendermint(uint64(l)) } l = m.TrustedHeight.Size() n += 1 + l + sovTendermint(uint64(l)) if m.TrustedValidators != nil { l = m.TrustedValidators.Size() n += 1 + l + sovTendermint(uint64(l)) } return n } func (m *Fraction) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Numerator != 0 { n += 1 + sovTendermint(uint64(m.Numerator)) } if m.Denominator != 0 { n += 1 + sovTendermint(uint64(m.Denominator)) } return n } func sovTendermint(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozTendermint(x uint64) (n int) { return sovTendermint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *ClientState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClientState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClientState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainId = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TrustLevel", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.TrustLevel.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TrustingPeriod", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.TrustingPeriod, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field UnbondingPeriod", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.UnbondingPeriod, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field MaxClockDrift", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.MaxClockDrift, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field LatestHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.LatestHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofSpecs", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } m.ProofSpecs = append(m.ProofSpecs, &_go.ProofSpec{}) if err := m.ProofSpecs[len(m.ProofSpecs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 8: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field MerklePrefix", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.MerklePrefix.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 9: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field TimeDelay", wireType) } m.TimeDelay = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.TimeDelay |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipTendermint(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTendermint } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ConsensusState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ConsensusState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ConsensusState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Root", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Root.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field NextValidatorsHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } m.NextValidatorsHash = append(m.NextValidatorsHash[:0], dAtA[iNdEx:postIndex]...) if m.NextValidatorsHash == nil { m.NextValidatorsHash = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTendermint(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTendermint } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Header) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Header: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Header: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SignedHeader", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if m.SignedHeader == nil { m.SignedHeader = &types2.SignedHeader{} } if err := m.SignedHeader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ValidatorSet", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if m.ValidatorSet == nil { m.ValidatorSet = &types2.ValidatorSet{} } if err := m.ValidatorSet.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TrustedHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.TrustedHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TrustedValidators", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTendermint } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTendermint } if postIndex > l { return io.ErrUnexpectedEOF } if m.TrustedValidators == nil { m.TrustedValidators = &types2.ValidatorSet{} } if err := m.TrustedValidators.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTendermint(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTendermint } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Fraction) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Fraction: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Fraction: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Numerator", wireType) } m.Numerator = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Numerator |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Denominator", wireType) } m.Denominator = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTendermint } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Denominator |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipTendermint(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTendermint } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipTendermint(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTendermint } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTendermint } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTendermint } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthTendermint } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupTendermint } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthTendermint } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthTendermint = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowTendermint = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupTendermint = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/04-packet/types/genesis.go<|end_filename|> package types import ( "errors" "fmt" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) // NewPacketState creates a new PacketState instance. func NewPacketState(sourceChain, destinationChain string, seq uint64, data []byte) PacketState { return PacketState{ SourceChain: sourceChain, DestinationChain: destinationChain, Sequence: seq, Data: data, } } // Validate performs basic validation of fields returning an error upon any // failure. func (pa PacketState) Validate() error { if pa.Data == nil { return errors.New("data bytes cannot be nil") } return validateGenFields(pa.SourceChain, pa.DestinationChain, pa.Sequence) } // NewPacketSequence creates a new PacketSequences instance. func NewPacketSequence(sourceChain, destinationChain string, seq uint64) PacketSequence { return PacketSequence{ SourceChain: sourceChain, DestinationChain: destinationChain, Sequence: seq, } } // Validate performs basic validation of fields returning an error upon any // failure. func (ps PacketSequence) Validate() error { return validateGenFields(ps.SourceChain, ps.DestinationChain, ps.Sequence) } // NewGenesisState creates a GenesisState instance. func NewGenesisState( acks, commitments, receipts []PacketState, sendSeqs, recvSeqs, ackSeqs []PacketSequence, ) GenesisState { return GenesisState{ Acknowledgements: acks, Commitments: commitments, Receipts: receipts, SendSequences: sendSeqs, RecvSequences: recvSeqs, AckSequences: ackSeqs, } } // DefaultGenesisState returns the tibc packet submodule's default genesis state. func DefaultGenesisState() GenesisState { return GenesisState{ Acknowledgements: []PacketState{}, Receipts: []PacketState{}, Commitments: []PacketState{}, SendSequences: []PacketSequence{}, RecvSequences: []PacketSequence{}, AckSequences: []PacketSequence{}, } } // Validate performs basic genesis state validation returning an error upon any // failure. func (gs GenesisState) Validate() error { for i, ack := range gs.Acknowledgements { if err := ack.Validate(); err != nil { return fmt.Errorf("invalid acknowledgement %v ack index %d: %w", ack, i, err) } if len(ack.Data) == 0 { return fmt.Errorf("invalid acknowledgement %v ack index %d: data bytes cannot be empty", ack, i) } } for i, receipt := range gs.Receipts { if err := receipt.Validate(); err != nil { return fmt.Errorf("invalid acknowledgement %v ack index %d: %w", receipt, i, err) } } for i, commitment := range gs.Commitments { if err := commitment.Validate(); err != nil { return fmt.Errorf("invalid commitment %v index %d: %w", commitment, i, err) } if len(commitment.Data) == 0 { return fmt.Errorf("invalid acknowledgement %v ack index %d: data bytes cannot be empty", commitment, i) } } for i, ss := range gs.SendSequences { if err := ss.Validate(); err != nil { return fmt.Errorf("invalid send sequence %v index %d: %w", ss, i, err) } } for i, rs := range gs.RecvSequences { if err := rs.Validate(); err != nil { return fmt.Errorf("invalid receive sequence %v index %d: %w", rs, i, err) } } for i, as := range gs.AckSequences { if err := as.Validate(); err != nil { return fmt.Errorf("invalid acknowledgement sequence %v index %d: %w", as, i, err) } } return nil } func validateGenFields(sourceChain, destChain string, sequence uint64) error { if err := host.SourceChainValidator(sourceChain); err != nil { return fmt.Errorf("invalid port Id: %w", err) } if err := host.DestChainValidator(destChain); err != nil { return fmt.Errorf("invalid channel Id: %w", err) } if sequence == 0 { return errors.New("sequence cannot be 0") } return nil } <|start_filename|>modules/tibc/core/02-client/types/tx.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/client/v1/tx.proto package types import ( context "context" fmt "fmt" types "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // MsgUpdateClient defines an sdk.Msg to update a TIBC client state using // the given header. type MsgUpdateClient struct { // client unique identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // header to update the light client Header *types.Any `protobuf:"bytes,2,opt,name=header,proto3" json:"header,omitempty"` // signer address Signer string `protobuf:"bytes,3,opt,name=signer,proto3" json:"signer,omitempty"` } func (m *MsgUpdateClient) Reset() { *m = MsgUpdateClient{} } func (m *MsgUpdateClient) String() string { return proto.CompactTextString(m) } func (*MsgUpdateClient) ProtoMessage() {} func (*MsgUpdateClient) Descriptor() ([]byte, []int) { return fileDescriptor_d101b27e3bfc60c8, []int{0} } func (m *MsgUpdateClient) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgUpdateClient) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgUpdateClient.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgUpdateClient) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgUpdateClient.Merge(m, src) } func (m *MsgUpdateClient) XXX_Size() int { return m.Size() } func (m *MsgUpdateClient) XXX_DiscardUnknown() { xxx_messageInfo_MsgUpdateClient.DiscardUnknown(m) } var xxx_messageInfo_MsgUpdateClient proto.InternalMessageInfo // MsgUpdateClientResponse defines the Msg/UpdateClient response type. type MsgUpdateClientResponse struct { } func (m *MsgUpdateClientResponse) Reset() { *m = MsgUpdateClientResponse{} } func (m *MsgUpdateClientResponse) String() string { return proto.CompactTextString(m) } func (*MsgUpdateClientResponse) ProtoMessage() {} func (*MsgUpdateClientResponse) Descriptor() ([]byte, []int) { return fileDescriptor_d101b27e3bfc60c8, []int{1} } func (m *MsgUpdateClientResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgUpdateClientResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgUpdateClientResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgUpdateClientResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgUpdateClientResponse.Merge(m, src) } func (m *MsgUpdateClientResponse) XXX_Size() int { return m.Size() } func (m *MsgUpdateClientResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgUpdateClientResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgUpdateClientResponse proto.InternalMessageInfo func init() { proto.RegisterType((*MsgUpdateClient)(nil), "tibc.core.client.v1.MsgUpdateClient") proto.RegisterType((*MsgUpdateClientResponse)(nil), "tibc.core.client.v1.MsgUpdateClientResponse") } func init() { proto.RegisterFile("tibc/core/client/v1/tx.proto", fileDescriptor_d101b27e3bfc60c8) } var fileDescriptor_d101b27e3bfc60c8 = []byte{ // 324 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x91, 0x31, 0x4f, 0x02, 0x31, 0x14, 0xc7, 0xaf, 0x92, 0x10, 0xa9, 0x26, 0x26, 0x27, 0x51, 0x20, 0x7a, 0x10, 0xe2, 0xc0, 0x00, 0xad, 0xe0, 0xe6, 0x60, 0xa2, 0xce, 0x38, 0x90, 0x98, 0x18, 0x17, 0xd3, 0x1e, 0xcf, 0x52, 0xc3, 0xb5, 0x97, 0x6b, 0x21, 0xb2, 0x39, 0x3a, 0xfa, 0x11, 0xf8, 0x38, 0x8e, 0x8c, 0x8e, 0x06, 0x16, 0x3f, 0x86, 0xb9, 0xde, 0x11, 0x23, 0x71, 0x70, 0xeb, 0xeb, 0xef, 0x9f, 0x5f, 0x5f, 0xdf, 0xc3, 0x47, 0x56, 0xf2, 0x90, 0x86, 0x3a, 0x01, 0x1a, 0x8e, 0x25, 0x28, 0x4b, 0xa7, 0x5d, 0x6a, 0x9f, 0x49, 0x9c, 0x68, 0xab, 0xfd, 0xfd, 0x94, 0x92, 0x94, 0x92, 0x8c, 0x92, 0x69, 0xb7, 0x56, 0x16, 0x5a, 0x68, 0xc7, 0x69, 0x7a, 0xca, 0xa2, 0xb5, 0xaa, 0xd0, 0x5a, 0x8c, 0x81, 0xba, 0x8a, 0x4f, 0x1e, 0x29, 0x53, 0xb3, 0x0c, 0x35, 0x5f, 0x10, 0xde, 0xeb, 0x1b, 0x71, 0x1b, 0x0f, 0x99, 0x85, 0x6b, 0xe7, 0xf1, 0x8f, 0x31, 0x0e, 0x47, 0x4c, 0xaa, 0x07, 0xc5, 0x22, 0xa8, 0xa0, 0x06, 0x6a, 0x95, 0x06, 0x25, 0x77, 0x73, 0xc3, 0x22, 0xf0, 0xdb, 0xb8, 0x38, 0x02, 0x36, 0x84, 0xa4, 0xb2, 0xd5, 0x40, 0xad, 0x9d, 0x5e, 0x99, 0x64, 0x7a, 0xb2, 0xd6, 0x93, 0x4b, 0x35, 0x1b, 0xe4, 0x19, 0xff, 0x00, 0x17, 0x8d, 0x14, 0x0a, 0x92, 0x4a, 0xc1, 0x89, 0xf2, 0xea, 0x7c, 0xfb, 0x75, 0x5e, 0xf7, 0xbe, 0xe6, 0x75, 0xaf, 0x59, 0xc5, 0x87, 0x1b, 0x1d, 0x0c, 0xc0, 0xc4, 0x5a, 0x19, 0xe8, 0x49, 0x5c, 0xe8, 0x1b, 0xe1, 0x73, 0xbc, 0xfb, 0xab, 0xc1, 0x13, 0xf2, 0xc7, 0xdf, 0xc9, 0x86, 0xa4, 0xd6, 0xfe, 0x4f, 0x6a, 0xfd, 0xd4, 0xd5, 0xdd, 0xfb, 0x32, 0x40, 0x8b, 0x65, 0x80, 0x3e, 0x97, 0x01, 0x7a, 0x5b, 0x05, 0xde, 0x62, 0x15, 0x78, 0x1f, 0xab, 0xc0, 0xbb, 0xbf, 0x10, 0xd2, 0x8e, 0x26, 0x9c, 0x84, 0x3a, 0xa2, 0x5c, 0x32, 0xf5, 0x24, 0x81, 0x49, 0x9a, 0xba, 0x3b, 0x42, 0xd3, 0x48, 0x0f, 0x27, 0x63, 0x30, 0xf4, 0x67, 0x57, 0xa7, 0xbd, 0x4e, 0xbe, 0x2e, 0x3b, 0x8b, 0xc1, 0xf0, 0xa2, 0x9b, 0xcb, 0xd9, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0x07, 0xc8, 0x35, 0x78, 0xcf, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // MsgClient is the client API for Msg service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type MsgClient interface { // UpdateClient defines a rpc handler method for MsgUpdateClient. UpdateClient(ctx context.Context, in *MsgUpdateClient, opts ...grpc.CallOption) (*MsgUpdateClientResponse, error) } type msgClient struct { cc grpc1.ClientConn } func NewMsgClient(cc grpc1.ClientConn) MsgClient { return &msgClient{cc} } func (c *msgClient) UpdateClient(ctx context.Context, in *MsgUpdateClient, opts ...grpc.CallOption) (*MsgUpdateClientResponse, error) { out := new(MsgUpdateClientResponse) err := c.cc.Invoke(ctx, "/tibc.core.client.v1.Msg/UpdateClient", in, out, opts...) if err != nil { return nil, err } return out, nil } // MsgServer is the server API for Msg service. type MsgServer interface { // UpdateClient defines a rpc handler method for MsgUpdateClient. UpdateClient(context.Context, *MsgUpdateClient) (*MsgUpdateClientResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. type UnimplementedMsgServer struct { } func (*UnimplementedMsgServer) UpdateClient(ctx context.Context, req *MsgUpdateClient) (*MsgUpdateClientResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateClient not implemented") } func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) } func _Msg_UpdateClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgUpdateClient) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).UpdateClient(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.client.v1.Msg/UpdateClient", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).UpdateClient(ctx, req.(*MsgUpdateClient)) } return interceptor(ctx, in, info, handler) } var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "tibc.core.client.v1.Msg", HandlerType: (*MsgServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "UpdateClient", Handler: _Msg_UpdateClient_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "tibc/core/client/v1/tx.proto", } func (m *MsgUpdateClient) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgUpdateClient) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgUpdateClient) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Signer) > 0 { i -= len(m.Signer) copy(dAtA[i:], m.Signer) i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) i-- dAtA[i] = 0x1a } if m.Header != nil { { size, err := m.Header.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintTx(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MsgUpdateClientResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgUpdateClientResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgUpdateClientResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func encodeVarintTx(dAtA []byte, offset int, v uint64) int { offset -= sovTx(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *MsgUpdateClient) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if m.Header != nil { l = m.Header.Size() n += 1 + l + sovTx(uint64(l)) } l = len(m.Signer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } return n } func (m *MsgUpdateClientResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func sovTx(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozTx(x uint64) (n int) { return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *MsgUpdateClient) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgUpdateClient: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgUpdateClient: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if m.Header == nil { m.Header = &types.Any{} } if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Signer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgUpdateClientResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgUpdateClientResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgUpdateClientResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipTx(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthTx } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupTx } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthTx } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/02-client/module.go<|end_filename|> package client import ( "github.com/gogo/protobuf/grpc" "github.com/spf13/cobra" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/client/cli" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" ) // Name returns the TIBC client name. func Name() string { return types.SubModuleName } // GetQueryCmd returns no root query command for the TIBC client. func GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } // GetTxCmd returns the root tx command for 02-client. func GetTxCmd() *cobra.Command { return cli.NewTxCmd() } // RegisterQueryService registers the gRPC query service for TIBC client. func RegisterQueryService(server grpc.Server, queryServer types.QueryServer) { types.RegisterQueryServer(server, queryServer) } <|start_filename|>modules/tibc/light-clients/08-bsc/types/bsc.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/lightclients/bsc/v1/bsc.proto package types import ( fmt "fmt" types "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Header defines the bsc client consensus Header. type Header struct { ParentHash []byte `protobuf:"bytes,1,opt,name=parent_hash,json=parentHash,proto3" json:"parent_hash,omitempty"` UncleHash []byte `protobuf:"bytes,2,opt,name=uncle_hash,json=uncleHash,proto3" json:"uncle_hash,omitempty"` Coinbase []byte `protobuf:"bytes,3,opt,name=coinbase,proto3" json:"coinbase,omitempty"` Root []byte `protobuf:"bytes,4,opt,name=root,proto3" json:"root,omitempty"` TxHash []byte `protobuf:"bytes,5,opt,name=tx_hash,json=txHash,proto3" json:"tx_hash,omitempty"` ReceiptHash []byte `protobuf:"bytes,6,opt,name=receipt_hash,json=receiptHash,proto3" json:"receipt_hash,omitempty"` Bloom []byte `protobuf:"bytes,7,opt,name=bloom,proto3" json:"bloom,omitempty"` Difficulty uint64 `protobuf:"varint,8,opt,name=difficulty,proto3" json:"difficulty,omitempty"` Height types.Height `protobuf:"bytes,9,opt,name=height,proto3" json:"height"` GasLimit uint64 `protobuf:"varint,10,opt,name=gas_limit,json=gasLimit,proto3" json:"gas_limit,omitempty"` GasUsed uint64 `protobuf:"varint,11,opt,name=gas_used,json=gasUsed,proto3" json:"gas_used,omitempty"` Time uint64 `protobuf:"varint,12,opt,name=time,proto3" json:"time,omitempty"` Extra []byte `protobuf:"bytes,13,opt,name=extra,proto3" json:"extra,omitempty"` MixDigest []byte `protobuf:"bytes,14,opt,name=mix_digest,json=mixDigest,proto3" json:"mix_digest,omitempty"` Nonce []byte `protobuf:"bytes,15,opt,name=nonce,proto3" json:"nonce,omitempty"` } func (m *Header) Reset() { *m = Header{} } func (m *Header) String() string { return proto.CompactTextString(m) } func (*Header) ProtoMessage() {} func (*Header) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{0} } func (m *Header) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Header) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Header.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Header) XXX_Merge(src proto.Message) { xxx_messageInfo_Header.Merge(m, src) } func (m *Header) XXX_Size() int { return m.Size() } func (m *Header) XXX_DiscardUnknown() { xxx_messageInfo_Header.DiscardUnknown(m) } var xxx_messageInfo_Header proto.InternalMessageInfo // ClientState from bsc tracks the current validator set, latest height, // and a possible frozen height. type ClientState struct { Header Header `protobuf:"bytes,1,opt,name=header,proto3" json:"header"` ChainId uint64 `protobuf:"varint,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` Epoch uint64 `protobuf:"varint,3,opt,name=epoch,proto3" json:"epoch,omitempty"` BlockInteval uint64 `protobuf:"varint,4,opt,name=block_inteval,json=blockInteval,proto3" json:"block_inteval,omitempty"` Validators [][]byte `protobuf:"bytes,5,rep,name=validators,proto3" json:"validators,omitempty"` RecentSigners []Signer `protobuf:"bytes,6,rep,name=recent_signers,json=recentSigners,proto3" json:"recent_signers"` ContractAddress []byte `protobuf:"bytes,7,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` TrustingPeriod uint64 `protobuf:"varint,8,opt,name=trusting_period,json=trustingPeriod,proto3" json:"trusting_period,omitempty"` } func (m *ClientState) Reset() { *m = ClientState{} } func (m *ClientState) String() string { return proto.CompactTextString(m) } func (*ClientState) ProtoMessage() {} func (*ClientState) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{1} } func (m *ClientState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ClientState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ClientState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ClientState) XXX_Merge(src proto.Message) { xxx_messageInfo_ClientState.Merge(m, src) } func (m *ClientState) XXX_Size() int { return m.Size() } func (m *ClientState) XXX_DiscardUnknown() { xxx_messageInfo_ClientState.DiscardUnknown(m) } var xxx_messageInfo_ClientState proto.InternalMessageInfo type Signer struct { Height types.Height `protobuf:"bytes,1,opt,name=height,proto3" json:"height"` Validator []byte `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` } func (m *Signer) Reset() { *m = Signer{} } func (m *Signer) String() string { return proto.CompactTextString(m) } func (*Signer) ProtoMessage() {} func (*Signer) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{2} } func (m *Signer) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Signer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Signer.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Signer) XXX_Merge(src proto.Message) { xxx_messageInfo_Signer.Merge(m, src) } func (m *Signer) XXX_Size() int { return m.Size() } func (m *Signer) XXX_DiscardUnknown() { xxx_messageInfo_Signer.DiscardUnknown(m) } var xxx_messageInfo_Signer proto.InternalMessageInfo func (m *Signer) GetHeight() types.Height { if m != nil { return m.Height } return types.Height{} } func (m *Signer) GetValidator() []byte { if m != nil { return m.Validator } return nil } type SignerSet struct { Signers []Signer `protobuf:"bytes,1,rep,name=signers,proto3" json:"signers"` } func (m *SignerSet) Reset() { *m = SignerSet{} } func (m *SignerSet) String() string { return proto.CompactTextString(m) } func (*SignerSet) ProtoMessage() {} func (*SignerSet) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{3} } func (m *SignerSet) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *SignerSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_SignerSet.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *SignerSet) XXX_Merge(src proto.Message) { xxx_messageInfo_SignerSet.Merge(m, src) } func (m *SignerSet) XXX_Size() int { return m.Size() } func (m *SignerSet) XXX_DiscardUnknown() { xxx_messageInfo_SignerSet.DiscardUnknown(m) } var xxx_messageInfo_SignerSet proto.InternalMessageInfo func (m *SignerSet) GetSigners() []Signer { if m != nil { return m.Signers } return nil } type ValidatorSet struct { Validators [][]byte `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators,omitempty"` } func (m *ValidatorSet) Reset() { *m = ValidatorSet{} } func (m *ValidatorSet) String() string { return proto.CompactTextString(m) } func (*ValidatorSet) ProtoMessage() {} func (*ValidatorSet) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{4} } func (m *ValidatorSet) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ValidatorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ValidatorSet.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ValidatorSet) XXX_Merge(src proto.Message) { xxx_messageInfo_ValidatorSet.Merge(m, src) } func (m *ValidatorSet) XXX_Size() int { return m.Size() } func (m *ValidatorSet) XXX_DiscardUnknown() { xxx_messageInfo_ValidatorSet.DiscardUnknown(m) } var xxx_messageInfo_ValidatorSet proto.InternalMessageInfo func (m *ValidatorSet) GetValidators() [][]byte { if m != nil { return m.Validators } return nil } // ConsensusState defines the consensus state from bsc. type ConsensusState struct { // timestamp that corresponds to the block height in which the ConsensusState // was stored. Timestamp uint64 `protobuf:"varint,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` Number types.Height `protobuf:"bytes,2,opt,name=number,proto3" json:"number"` Root []byte `protobuf:"bytes,3,opt,name=root,proto3" json:"root,omitempty"` } func (m *ConsensusState) Reset() { *m = ConsensusState{} } func (m *ConsensusState) String() string { return proto.CompactTextString(m) } func (*ConsensusState) ProtoMessage() {} func (*ConsensusState) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{5} } func (m *ConsensusState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ConsensusState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ConsensusState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ConsensusState) XXX_Merge(src proto.Message) { xxx_messageInfo_ConsensusState.Merge(m, src) } func (m *ConsensusState) XXX_Size() int { return m.Size() } func (m *ConsensusState) XXX_DiscardUnknown() { xxx_messageInfo_ConsensusState.DiscardUnknown(m) } var xxx_messageInfo_ConsensusState proto.InternalMessageInfo type StorageResult struct { Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` Proof []string `protobuf:"bytes,3,rep,name=proof,proto3" json:"proof,omitempty"` } func (m *StorageResult) Reset() { *m = StorageResult{} } func (m *StorageResult) String() string { return proto.CompactTextString(m) } func (*StorageResult) ProtoMessage() {} func (*StorageResult) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{6} } func (m *StorageResult) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *StorageResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_StorageResult.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *StorageResult) XXX_Merge(src proto.Message) { xxx_messageInfo_StorageResult.Merge(m, src) } func (m *StorageResult) XXX_Size() int { return m.Size() } func (m *StorageResult) XXX_DiscardUnknown() { xxx_messageInfo_StorageResult.DiscardUnknown(m) } var xxx_messageInfo_StorageResult proto.InternalMessageInfo type Proof struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Balance string `protobuf:"bytes,2,opt,name=balance,proto3" json:"balance,omitempty"` CodeHash string `protobuf:"bytes,3,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` Nonce string `protobuf:"bytes,4,opt,name=nonce,proto3" json:"nonce,omitempty"` StorageHash string `protobuf:"bytes,5,opt,name=storage_hash,json=storageHash,proto3" json:"storage_hash,omitempty"` AccountProof []string `protobuf:"bytes,6,rep,name=account_proof,json=accountProof,proto3" json:"account_proof,omitempty"` StorageProof []*StorageResult `protobuf:"bytes,7,rep,name=storage_proof,json=storageProof,proto3" json:"storage_proof,omitempty"` } func (m *Proof) Reset() { *m = Proof{} } func (m *Proof) String() string { return proto.CompactTextString(m) } func (*Proof) ProtoMessage() {} func (*Proof) Descriptor() ([]byte, []int) { return fileDescriptor_1304259fbeedea63, []int{7} } func (m *Proof) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Proof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Proof.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Proof) XXX_Merge(src proto.Message) { xxx_messageInfo_Proof.Merge(m, src) } func (m *Proof) XXX_Size() int { return m.Size() } func (m *Proof) XXX_DiscardUnknown() { xxx_messageInfo_Proof.DiscardUnknown(m) } var xxx_messageInfo_Proof proto.InternalMessageInfo func init() { proto.RegisterType((*Header)(nil), "tibc.lightclients.bsc.v1.Header") proto.RegisterType((*ClientState)(nil), "tibc.lightclients.bsc.v1.ClientState") proto.RegisterType((*Signer)(nil), "tibc.lightclients.bsc.v1.Signer") proto.RegisterType((*SignerSet)(nil), "tibc.lightclients.bsc.v1.SignerSet") proto.RegisterType((*ValidatorSet)(nil), "tibc.lightclients.bsc.v1.ValidatorSet") proto.RegisterType((*ConsensusState)(nil), "tibc.lightclients.bsc.v1.ConsensusState") proto.RegisterType((*StorageResult)(nil), "tibc.lightclients.bsc.v1.StorageResult") proto.RegisterType((*Proof)(nil), "tibc.lightclients.bsc.v1.Proof") } func init() { proto.RegisterFile("tibc/lightclients/bsc/v1/bsc.proto", fileDescriptor_1304259fbeedea63) } var fileDescriptor_1304259fbeedea63 = []byte{ // 885 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0x3f, 0x6f, 0xdb, 0x46, 0x14, 0x17, 0x4d, 0x5a, 0x12, 0x9f, 0x24, 0x3b, 0x38, 0x04, 0x28, 0xe3, 0xa4, 0xb2, 0xaa, 0x0c, 0x71, 0x07, 0x93, 0x75, 0xba, 0xb4, 0x1d, 0x8a, 0x36, 0xc9, 0xe0, 0x00, 0x09, 0x60, 0x50, 0x68, 0x87, 0x0e, 0x25, 0x8e, 0xc7, 0x33, 0x75, 0x0d, 0xc9, 0x13, 0x78, 0x47, 0x41, 0x9e, 0xbb, 0x14, 0x9d, 0xfa, 0x11, 0xfa, 0x59, 0x3a, 0x65, 0xcc, 0xd8, 0xa9, 0x28, 0xec, 0xb5, 0x1f, 0xa2, 0xb8, 0x77, 0xa4, 0xa5, 0x16, 0x68, 0x50, 0x4f, 0xbc, 0xf7, 0x7b, 0x7f, 0xee, 0xbd, 0xdf, 0x7b, 0x7c, 0x07, 0x73, 0x2d, 0x52, 0x16, 0x15, 0x22, 0x5f, 0x6a, 0x56, 0x08, 0x5e, 0x69, 0x15, 0xa5, 0x8a, 0x45, 0xeb, 0x33, 0xf3, 0x09, 0x57, 0xb5, 0xd4, 0x92, 0x04, 0xc6, 0x26, 0xdc, 0xb5, 0x09, 0x8d, 0x72, 0x7d, 0x76, 0x74, 0x3f, 0x97, 0xb9, 0x44, 0xa3, 0xc8, 0x9c, 0xac, 0xfd, 0xd1, 0x0c, 0x63, 0x32, 0x59, 0xf3, 0xc8, 0xda, 0x9b, 0x70, 0xf6, 0x64, 0x2d, 0xe6, 0xbf, 0xb9, 0xd0, 0x3f, 0xe7, 0x34, 0xe3, 0x35, 0x39, 0x86, 0xd1, 0x8a, 0xd6, 0xbc, 0xd2, 0xc9, 0x92, 0xaa, 0x65, 0xe0, 0xcc, 0x9c, 0x93, 0x71, 0x0c, 0x16, 0x3a, 0xa7, 0x6a, 0x49, 0x3e, 0x04, 0x68, 0x2a, 0x56, 0x70, 0xab, 0xdf, 0x43, 0xbd, 0x8f, 0x08, 0xaa, 0x8f, 0x60, 0xc8, 0xa4, 0xa8, 0x52, 0xaa, 0x78, 0xe0, 0xa2, 0xf2, 0x56, 0x26, 0x04, 0xbc, 0x5a, 0x4a, 0x1d, 0x78, 0x88, 0xe3, 0x99, 0x7c, 0x00, 0x03, 0xbd, 0xb1, 0xb1, 0xf6, 0x11, 0xee, 0xeb, 0x0d, 0x06, 0xfa, 0x08, 0xc6, 0x35, 0x67, 0x5c, 0xac, 0xda, 0x4c, 0xfa, 0xa8, 0x1d, 0xb5, 0x18, 0x9a, 0xdc, 0x87, 0xfd, 0xb4, 0x90, 0xb2, 0x0c, 0x06, 0xa8, 0xb3, 0x02, 0x99, 0x02, 0x64, 0xe2, 0xf2, 0x52, 0xb0, 0xa6, 0xd0, 0x57, 0xc1, 0x70, 0xe6, 0x9c, 0x78, 0xf1, 0x0e, 0x42, 0x3e, 0x87, 0xfe, 0x92, 0x1b, 0xf2, 0x02, 0x7f, 0xe6, 0x9c, 0x8c, 0x9e, 0x3e, 0x0c, 0x91, 0x4f, 0xc3, 0x4f, 0xd8, 0xb2, 0xb2, 0x3e, 0x0b, 0xcf, 0xd1, 0xe4, 0x99, 0xf7, 0xf6, 0x8f, 0xe3, 0x5e, 0xdc, 0x3a, 0x90, 0x87, 0xe0, 0xe7, 0x54, 0x25, 0x85, 0x28, 0x85, 0x0e, 0x00, 0x23, 0x0f, 0x73, 0xaa, 0x5e, 0x19, 0x99, 0x3c, 0x00, 0x73, 0x4e, 0x1a, 0xc5, 0xb3, 0x60, 0x84, 0xba, 0x41, 0x4e, 0xd5, 0x37, 0x8a, 0x67, 0xa6, 0x70, 0x2d, 0x4a, 0x1e, 0x8c, 0x11, 0xc6, 0xb3, 0x49, 0x9e, 0x6f, 0x74, 0x4d, 0x83, 0x89, 0x4d, 0x1e, 0x05, 0xc3, 0x6e, 0x29, 0x36, 0x49, 0x26, 0x72, 0xae, 0x74, 0x70, 0x60, 0xd9, 0x2d, 0xc5, 0xe6, 0x05, 0x02, 0xc6, 0xa9, 0x92, 0x15, 0xe3, 0xc1, 0xa1, 0x75, 0x42, 0xe1, 0x0b, 0xef, 0xa7, 0x5f, 0x8f, 0x7b, 0xf3, 0xbf, 0xf6, 0x60, 0xf4, 0x1c, 0xf3, 0x5f, 0x68, 0xaa, 0x39, 0xf9, 0xd2, 0xd4, 0x69, 0x7a, 0x8a, 0x4d, 0x1c, 0x3d, 0x9d, 0x85, 0xff, 0x35, 0x37, 0xa1, 0xed, 0xfd, 0xb6, 0x58, 0x9c, 0x84, 0x07, 0x30, 0x64, 0x4b, 0x2a, 0xaa, 0x44, 0x64, 0xd8, 0x66, 0x2f, 0x1e, 0xa0, 0xfc, 0x32, 0xc3, 0xdc, 0x57, 0x92, 0x2d, 0xb1, 0xc3, 0x5e, 0x6c, 0x05, 0xf2, 0x18, 0x26, 0x69, 0x21, 0xd9, 0x9b, 0x44, 0x54, 0x9a, 0xaf, 0x69, 0x81, 0x7d, 0xf6, 0xe2, 0x31, 0x82, 0x2f, 0x2d, 0x66, 0xba, 0xb3, 0xa6, 0x85, 0xc8, 0xa8, 0x96, 0xb5, 0x0a, 0xf6, 0x67, 0xae, 0x19, 0xaf, 0x2d, 0x42, 0x5e, 0xc3, 0x81, 0x69, 0x71, 0xa5, 0x13, 0x25, 0xf2, 0x8a, 0xd7, 0x2a, 0xe8, 0xcf, 0xdc, 0xf7, 0x67, 0xbf, 0x40, 0xc3, 0x36, 0xfb, 0x89, 0xf5, 0xb6, 0x98, 0x22, 0x1f, 0xc3, 0x3d, 0x26, 0x2b, 0x5d, 0x53, 0xa6, 0x13, 0x9a, 0x65, 0x35, 0x57, 0xaa, 0x9d, 0x96, 0xc3, 0x0e, 0xff, 0xda, 0xc2, 0xe4, 0x09, 0x1c, 0xea, 0xba, 0x51, 0x5a, 0x54, 0x79, 0xb2, 0xe2, 0xb5, 0x90, 0x59, 0x3b, 0x3c, 0x07, 0x1d, 0x7c, 0x81, 0x68, 0x4b, 0x37, 0x85, 0xbe, 0xbd, 0x64, 0x67, 0xa0, 0x9c, 0xbb, 0x0e, 0xd4, 0x23, 0xf0, 0x6f, 0x6b, 0xef, 0xfe, 0xa5, 0x5b, 0x60, 0xfe, 0x1a, 0x7c, 0x7b, 0xc5, 0x82, 0x6b, 0xf2, 0x15, 0x0c, 0x3a, 0x46, 0x9c, 0x3b, 0x31, 0xd2, 0xb9, 0xcd, 0x43, 0x18, 0x7f, 0xdb, 0xc5, 0x36, 0x11, 0xff, 0xd9, 0x0a, 0xe7, 0xdf, 0xad, 0x98, 0xff, 0xe8, 0xc0, 0xc1, 0x73, 0x59, 0x29, 0x5e, 0xa9, 0x46, 0xd9, 0x99, 0x7a, 0x04, 0xbe, 0x19, 0x5e, 0xa5, 0x69, 0xb9, 0xc2, 0x6a, 0xbd, 0x78, 0x0b, 0x18, 0x22, 0xaa, 0xa6, 0x4c, 0xb9, 0x2d, 0xe5, 0xff, 0x11, 0x61, 0x1d, 0x6e, 0x57, 0x83, 0xbb, 0x5d, 0x0d, 0x2d, 0xcf, 0x0b, 0x98, 0x2c, 0xb4, 0xac, 0x69, 0xce, 0x63, 0xae, 0x9a, 0x42, 0x93, 0x7b, 0xe0, 0xbe, 0xe1, 0x57, 0x78, 0xbb, 0x1f, 0x9b, 0xa3, 0x19, 0xc7, 0x35, 0x2d, 0x1a, 0x8e, 0xd7, 0xfa, 0xb1, 0x15, 0x0c, 0xba, 0xaa, 0xa5, 0xbc, 0x0c, 0xdc, 0x99, 0x6b, 0x50, 0x14, 0xda, 0xa0, 0x3f, 0xef, 0xc1, 0xfe, 0x85, 0x91, 0x49, 0x00, 0x83, 0x6e, 0x2e, 0x6c, 0xc4, 0x4e, 0x34, 0x9a, 0x94, 0x16, 0xd4, 0xfc, 0x6d, 0x36, 0x6e, 0x27, 0x9a, 0x35, 0xc0, 0x64, 0xd6, 0x6e, 0x40, 0x17, 0x75, 0x43, 0x03, 0x74, 0x4b, 0xc9, 0xfe, 0xa2, 0x9e, 0x4d, 0x06, 0x05, 0xb3, 0xcd, 0x94, 0xad, 0x62, 0xbb, 0xeb, 0xfc, 0x78, 0xd4, 0x62, 0xe8, 0xf8, 0x18, 0x26, 0x94, 0x31, 0xd9, 0x54, 0x3a, 0xb1, 0x79, 0xf7, 0x31, 0xef, 0x71, 0x0b, 0xda, 0x74, 0x5f, 0xc1, 0xa4, 0x8b, 0x63, 0x8d, 0x06, 0x38, 0x0b, 0x4f, 0xde, 0x33, 0x0b, 0xbb, 0xe4, 0xc5, 0x5d, 0x16, 0x17, 0x5b, 0x32, 0x9e, 0x7d, 0xff, 0xf6, 0x7a, 0xea, 0xbc, 0xbb, 0x9e, 0x3a, 0x7f, 0x5e, 0x4f, 0x9d, 0x5f, 0x6e, 0xa6, 0xbd, 0x77, 0x37, 0xd3, 0xde, 0xef, 0x37, 0xd3, 0xde, 0x77, 0x2f, 0x72, 0xa1, 0x97, 0x4d, 0x1a, 0x32, 0x59, 0x46, 0xa9, 0xa0, 0xd5, 0x0f, 0x82, 0x53, 0x11, 0x99, 0xab, 0x4e, 0x73, 0x19, 0x95, 0x32, 0x6b, 0x0a, 0xae, 0xa2, 0xed, 0x93, 0x75, 0xda, 0xbd, 0x59, 0x9f, 0x7c, 0x76, 0x6a, 0x9e, 0x2d, 0x7d, 0xb5, 0xe2, 0x2a, 0xed, 0xe3, 0x23, 0xf3, 0xe9, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x45, 0x68, 0x2d, 0x3d, 0xdc, 0x06, 0x00, 0x00, } func (m *Header) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Header) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Header) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Nonce) > 0 { i -= len(m.Nonce) copy(dAtA[i:], m.Nonce) i = encodeVarintBsc(dAtA, i, uint64(len(m.Nonce))) i-- dAtA[i] = 0x7a } if len(m.MixDigest) > 0 { i -= len(m.MixDigest) copy(dAtA[i:], m.MixDigest) i = encodeVarintBsc(dAtA, i, uint64(len(m.MixDigest))) i-- dAtA[i] = 0x72 } if len(m.Extra) > 0 { i -= len(m.Extra) copy(dAtA[i:], m.Extra) i = encodeVarintBsc(dAtA, i, uint64(len(m.Extra))) i-- dAtA[i] = 0x6a } if m.Time != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.Time)) i-- dAtA[i] = 0x60 } if m.GasUsed != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.GasUsed)) i-- dAtA[i] = 0x58 } if m.GasLimit != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.GasLimit)) i-- dAtA[i] = 0x50 } { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x4a if m.Difficulty != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.Difficulty)) i-- dAtA[i] = 0x40 } if len(m.Bloom) > 0 { i -= len(m.Bloom) copy(dAtA[i:], m.Bloom) i = encodeVarintBsc(dAtA, i, uint64(len(m.Bloom))) i-- dAtA[i] = 0x3a } if len(m.ReceiptHash) > 0 { i -= len(m.ReceiptHash) copy(dAtA[i:], m.ReceiptHash) i = encodeVarintBsc(dAtA, i, uint64(len(m.ReceiptHash))) i-- dAtA[i] = 0x32 } if len(m.TxHash) > 0 { i -= len(m.TxHash) copy(dAtA[i:], m.TxHash) i = encodeVarintBsc(dAtA, i, uint64(len(m.TxHash))) i-- dAtA[i] = 0x2a } if len(m.Root) > 0 { i -= len(m.Root) copy(dAtA[i:], m.Root) i = encodeVarintBsc(dAtA, i, uint64(len(m.Root))) i-- dAtA[i] = 0x22 } if len(m.Coinbase) > 0 { i -= len(m.Coinbase) copy(dAtA[i:], m.Coinbase) i = encodeVarintBsc(dAtA, i, uint64(len(m.Coinbase))) i-- dAtA[i] = 0x1a } if len(m.UncleHash) > 0 { i -= len(m.UncleHash) copy(dAtA[i:], m.UncleHash) i = encodeVarintBsc(dAtA, i, uint64(len(m.UncleHash))) i-- dAtA[i] = 0x12 } if len(m.ParentHash) > 0 { i -= len(m.ParentHash) copy(dAtA[i:], m.ParentHash) i = encodeVarintBsc(dAtA, i, uint64(len(m.ParentHash))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *ClientState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClientState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ClientState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.TrustingPeriod != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.TrustingPeriod)) i-- dAtA[i] = 0x40 } if len(m.ContractAddress) > 0 { i -= len(m.ContractAddress) copy(dAtA[i:], m.ContractAddress) i = encodeVarintBsc(dAtA, i, uint64(len(m.ContractAddress))) i-- dAtA[i] = 0x3a } if len(m.RecentSigners) > 0 { for iNdEx := len(m.RecentSigners) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.RecentSigners[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x32 } } if len(m.Validators) > 0 { for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Validators[iNdEx]) copy(dAtA[i:], m.Validators[iNdEx]) i = encodeVarintBsc(dAtA, i, uint64(len(m.Validators[iNdEx]))) i-- dAtA[i] = 0x2a } } if m.BlockInteval != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.BlockInteval)) i-- dAtA[i] = 0x20 } if m.Epoch != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.Epoch)) i-- dAtA[i] = 0x18 } if m.ChainId != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.ChainId)) i-- dAtA[i] = 0x10 } { size, err := m.Header.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *Signer) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Signer) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Signer) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Validator) > 0 { i -= len(m.Validator) copy(dAtA[i:], m.Validator) i = encodeVarintBsc(dAtA, i, uint64(len(m.Validator))) i-- dAtA[i] = 0x12 } { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *SignerSet) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *SignerSet) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *SignerSet) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Signers) > 0 { for iNdEx := len(m.Signers) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Signers[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *ValidatorSet) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ValidatorSet) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ValidatorSet) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Validators) > 0 { for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Validators[iNdEx]) copy(dAtA[i:], m.Validators[iNdEx]) i = encodeVarintBsc(dAtA, i, uint64(len(m.Validators[iNdEx]))) i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *ConsensusState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ConsensusState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ConsensusState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Root) > 0 { i -= len(m.Root) copy(dAtA[i:], m.Root) i = encodeVarintBsc(dAtA, i, uint64(len(m.Root))) i-- dAtA[i] = 0x1a } { size, err := m.Number.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 if m.Timestamp != 0 { i = encodeVarintBsc(dAtA, i, uint64(m.Timestamp)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } func (m *StorageResult) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *StorageResult) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *StorageResult) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Proof) > 0 { for iNdEx := len(m.Proof) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Proof[iNdEx]) copy(dAtA[i:], m.Proof[iNdEx]) i = encodeVarintBsc(dAtA, i, uint64(len(m.Proof[iNdEx]))) i-- dAtA[i] = 0x1a } } if len(m.Value) > 0 { i -= len(m.Value) copy(dAtA[i:], m.Value) i = encodeVarintBsc(dAtA, i, uint64(len(m.Value))) i-- dAtA[i] = 0x12 } if len(m.Key) > 0 { i -= len(m.Key) copy(dAtA[i:], m.Key) i = encodeVarintBsc(dAtA, i, uint64(len(m.Key))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *Proof) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Proof) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Proof) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.StorageProof) > 0 { for iNdEx := len(m.StorageProof) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.StorageProof[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintBsc(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x3a } } if len(m.AccountProof) > 0 { for iNdEx := len(m.AccountProof) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.AccountProof[iNdEx]) copy(dAtA[i:], m.AccountProof[iNdEx]) i = encodeVarintBsc(dAtA, i, uint64(len(m.AccountProof[iNdEx]))) i-- dAtA[i] = 0x32 } } if len(m.StorageHash) > 0 { i -= len(m.StorageHash) copy(dAtA[i:], m.StorageHash) i = encodeVarintBsc(dAtA, i, uint64(len(m.StorageHash))) i-- dAtA[i] = 0x2a } if len(m.Nonce) > 0 { i -= len(m.Nonce) copy(dAtA[i:], m.Nonce) i = encodeVarintBsc(dAtA, i, uint64(len(m.Nonce))) i-- dAtA[i] = 0x22 } if len(m.CodeHash) > 0 { i -= len(m.CodeHash) copy(dAtA[i:], m.CodeHash) i = encodeVarintBsc(dAtA, i, uint64(len(m.CodeHash))) i-- dAtA[i] = 0x1a } if len(m.Balance) > 0 { i -= len(m.Balance) copy(dAtA[i:], m.Balance) i = encodeVarintBsc(dAtA, i, uint64(len(m.Balance))) i-- dAtA[i] = 0x12 } if len(m.Address) > 0 { i -= len(m.Address) copy(dAtA[i:], m.Address) i = encodeVarintBsc(dAtA, i, uint64(len(m.Address))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func encodeVarintBsc(dAtA []byte, offset int, v uint64) int { offset -= sovBsc(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *Header) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ParentHash) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.UncleHash) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Coinbase) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Root) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.TxHash) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.ReceiptHash) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Bloom) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } if m.Difficulty != 0 { n += 1 + sovBsc(uint64(m.Difficulty)) } l = m.Height.Size() n += 1 + l + sovBsc(uint64(l)) if m.GasLimit != 0 { n += 1 + sovBsc(uint64(m.GasLimit)) } if m.GasUsed != 0 { n += 1 + sovBsc(uint64(m.GasUsed)) } if m.Time != 0 { n += 1 + sovBsc(uint64(m.Time)) } l = len(m.Extra) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.MixDigest) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Nonce) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } return n } func (m *ClientState) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.Header.Size() n += 1 + l + sovBsc(uint64(l)) if m.ChainId != 0 { n += 1 + sovBsc(uint64(m.ChainId)) } if m.Epoch != 0 { n += 1 + sovBsc(uint64(m.Epoch)) } if m.BlockInteval != 0 { n += 1 + sovBsc(uint64(m.BlockInteval)) } if len(m.Validators) > 0 { for _, b := range m.Validators { l = len(b) n += 1 + l + sovBsc(uint64(l)) } } if len(m.RecentSigners) > 0 { for _, e := range m.RecentSigners { l = e.Size() n += 1 + l + sovBsc(uint64(l)) } } l = len(m.ContractAddress) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } if m.TrustingPeriod != 0 { n += 1 + sovBsc(uint64(m.TrustingPeriod)) } return n } func (m *Signer) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.Height.Size() n += 1 + l + sovBsc(uint64(l)) l = len(m.Validator) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } return n } func (m *SignerSet) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Signers) > 0 { for _, e := range m.Signers { l = e.Size() n += 1 + l + sovBsc(uint64(l)) } } return n } func (m *ValidatorSet) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Validators) > 0 { for _, b := range m.Validators { l = len(b) n += 1 + l + sovBsc(uint64(l)) } } return n } func (m *ConsensusState) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Timestamp != 0 { n += 1 + sovBsc(uint64(m.Timestamp)) } l = m.Number.Size() n += 1 + l + sovBsc(uint64(l)) l = len(m.Root) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } return n } func (m *StorageResult) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Key) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Value) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } if len(m.Proof) > 0 { for _, s := range m.Proof { l = len(s) n += 1 + l + sovBsc(uint64(l)) } } return n } func (m *Proof) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Address) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Balance) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.CodeHash) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.Nonce) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } l = len(m.StorageHash) if l > 0 { n += 1 + l + sovBsc(uint64(l)) } if len(m.AccountProof) > 0 { for _, s := range m.AccountProof { l = len(s) n += 1 + l + sovBsc(uint64(l)) } } if len(m.StorageProof) > 0 { for _, e := range m.StorageProof { l = e.Size() n += 1 + l + sovBsc(uint64(l)) } } return n } func sovBsc(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozBsc(x uint64) (n int) { return sovBsc(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *Header) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Header: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Header: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ParentHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.ParentHash = append(m.ParentHash[:0], dAtA[iNdEx:postIndex]...) if m.ParentHash == nil { m.ParentHash = []byte{} } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field UncleHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.UncleHash = append(m.UncleHash[:0], dAtA[iNdEx:postIndex]...) if m.UncleHash == nil { m.UncleHash = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Coinbase", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Coinbase = append(m.Coinbase[:0], dAtA[iNdEx:postIndex]...) if m.Coinbase == nil { m.Coinbase = []byte{} } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Root", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Root = append(m.Root[:0], dAtA[iNdEx:postIndex]...) if m.Root == nil { m.Root = []byte{} } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.TxHash = append(m.TxHash[:0], dAtA[iNdEx:postIndex]...) if m.TxHash == nil { m.TxHash = []byte{} } iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ReceiptHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.ReceiptHash = append(m.ReceiptHash[:0], dAtA[iNdEx:postIndex]...) if m.ReceiptHash == nil { m.ReceiptHash = []byte{} } iNdEx = postIndex case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Bloom", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Bloom = append(m.Bloom[:0], dAtA[iNdEx:postIndex]...) if m.Bloom == nil { m.Bloom = []byte{} } iNdEx = postIndex case 8: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Difficulty", wireType) } m.Difficulty = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Difficulty |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 9: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 10: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field GasLimit", wireType) } m.GasLimit = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.GasLimit |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 11: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) } m.GasUsed = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.GasUsed |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 12: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Time", wireType) } m.Time = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Time |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 13: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Extra", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Extra = append(m.Extra[:0], dAtA[iNdEx:postIndex]...) if m.Extra == nil { m.Extra = []byte{} } iNdEx = postIndex case 14: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field MixDigest", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.MixDigest = append(m.MixDigest[:0], dAtA[iNdEx:postIndex]...) if m.MixDigest == nil { m.MixDigest = []byte{} } iNdEx = postIndex case 15: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Nonce", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Nonce = append(m.Nonce[:0], dAtA[iNdEx:postIndex]...) if m.Nonce == nil { m.Nonce = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ClientState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClientState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClientState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Header", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Header.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) } m.ChainId = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.ChainId |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Epoch", wireType) } m.Epoch = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Epoch |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field BlockInteval", wireType) } m.BlockInteval = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.BlockInteval |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Validators = append(m.Validators, make([]byte, postIndex-iNdEx)) copy(m.Validators[len(m.Validators)-1], dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RecentSigners", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.RecentSigners = append(m.RecentSigners, Signer{}) if err := m.RecentSigners[len(m.RecentSigners)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.ContractAddress = append(m.ContractAddress[:0], dAtA[iNdEx:postIndex]...) if m.ContractAddress == nil { m.ContractAddress = []byte{} } iNdEx = postIndex case 8: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field TrustingPeriod", wireType) } m.TrustingPeriod = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.TrustingPeriod |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Signer) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Signer: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Signer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Validator = append(m.Validator[:0], dAtA[iNdEx:postIndex]...) if m.Validator == nil { m.Validator = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *SignerSet) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: SignerSet: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: SignerSet: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Signers", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Signers = append(m.Signers, Signer{}) if err := m.Signers[len(m.Signers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ValidatorSet) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ValidatorSet: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ValidatorSet: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Validators = append(m.Validators, make([]byte, postIndex-iNdEx)) copy(m.Validators[len(m.Validators)-1], dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ConsensusState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ConsensusState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ConsensusState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) } m.Timestamp = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Timestamp |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Number", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Number.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Root", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Root = append(m.Root[:0], dAtA[iNdEx:postIndex]...) if m.Root == nil { m.Root = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *StorageResult) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: StorageResult: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: StorageResult: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Key = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Value = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Proof) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Proof: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Proof: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Address = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Balance", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Balance = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.CodeHash = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Nonce", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.Nonce = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StorageHash", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.StorageHash = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field AccountProof", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.AccountProof = append(m.AccountProof, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StorageProof", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowBsc } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthBsc } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthBsc } if postIndex > l { return io.ErrUnexpectedEOF } m.StorageProof = append(m.StorageProof, &StorageResult{}) if err := m.StorageProof[len(m.StorageProof)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipBsc(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthBsc } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipBsc(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowBsc } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowBsc } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowBsc } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthBsc } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupBsc } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthBsc } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthBsc = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowBsc = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupBsc = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/26-routing/module.go<|end_filename|> package routing import ( "github.com/gogo/protobuf/grpc" "github.com/spf13/cobra" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/client/cli" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // Name returns the TIBC routing TICS name. func Name() string { return types.SubModuleName } // GetTxCmd returns the root tx command for TIBC routing. func GetTxCmd() *cobra.Command { return nil } // GetQueryCmd returns the root query command for TIBC routing. func GetQueryCmd() *cobra.Command { return cli.GetQueryCmd() } // RegisterQueryService registers the gRPC query service for TIBC routing. func RegisterQueryService(server grpc.Server, queryServer types.QueryServer) { types.RegisterQueryServer(server, queryServer) } <|start_filename|>modules/tibc/core/04-packet/types/packet.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/packet/v1/packet.proto package types import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Packet defines a type that carries data across different chains through TIBC type Packet struct { // number corresponds to the order of sends and receives, where a Packet // with an earlier sequence number must be sent and received before a Packet // with a later sequence number. Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` // identifies the port on the sending chain and destination chain. Port string `protobuf:"bytes,2,opt,name=port,proto3" json:"port,omitempty"` // identifies the chain id of the sending chain. SourceChain string `protobuf:"bytes,3,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty" yaml:"source_chain"` // identifies the chain id of the receiving chain. DestinationChain string `protobuf:"bytes,4,opt,name=destination_chain,json=destinationChain,proto3" json:"destination_chain,omitempty" yaml:"destination_port"` // identifies the chain id of the relay chain. RelayChain string `protobuf:"bytes,5,opt,name=relay_chain,json=relayChain,proto3" json:"relay_chain,omitempty" yaml:"relay_chain"` // actual opaque bytes transferred directly to the application module Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` } func (m *Packet) Reset() { *m = Packet{} } func (m *Packet) String() string { return proto.CompactTextString(m) } func (*Packet) ProtoMessage() {} func (*Packet) Descriptor() ([]byte, []int) { return fileDescriptor_59da8d378a3b7468, []int{0} } func (m *Packet) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Packet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Packet.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Packet) XXX_Merge(src proto.Message) { xxx_messageInfo_Packet.Merge(m, src) } func (m *Packet) XXX_Size() int { return m.Size() } func (m *Packet) XXX_DiscardUnknown() { xxx_messageInfo_Packet.DiscardUnknown(m) } var xxx_messageInfo_Packet proto.InternalMessageInfo // CleanPacket defines a type that carries data across different chains through TIBC type CleanPacket struct { // number corresponds to the order of sends and receives, where a Packet // with an earlier sequence number must be sent and received before a Packet // with a later sequence number. Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` // identifies the chain id of the sending chain. SourceChain string `protobuf:"bytes,3,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty" yaml:"source_chain"` // identifies the chain id of the receiving chain. DestinationChain string `protobuf:"bytes,4,opt,name=destination_chain,json=destinationChain,proto3" json:"destination_chain,omitempty" yaml:"destination_port"` // identifies the chain id of the relay chain. RelayChain string `protobuf:"bytes,5,opt,name=relay_chain,json=relayChain,proto3" json:"relay_chain,omitempty" yaml:"relay_chain"` } func (m *CleanPacket) Reset() { *m = CleanPacket{} } func (m *CleanPacket) String() string { return proto.CompactTextString(m) } func (*CleanPacket) ProtoMessage() {} func (*CleanPacket) Descriptor() ([]byte, []int) { return fileDescriptor_59da8d378a3b7468, []int{1} } func (m *CleanPacket) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *CleanPacket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_CleanPacket.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *CleanPacket) XXX_Merge(src proto.Message) { xxx_messageInfo_CleanPacket.Merge(m, src) } func (m *CleanPacket) XXX_Size() int { return m.Size() } func (m *CleanPacket) XXX_DiscardUnknown() { xxx_messageInfo_CleanPacket.DiscardUnknown(m) } var xxx_messageInfo_CleanPacket proto.InternalMessageInfo // PacketState defines the generic type necessary to retrieve and store // packet commitments, acknowledgements, and receipts. // Caller is responsible for knowing the context necessary to interpret this // state as a commitment, acknowledgement, or a receipt. type PacketState struct { // the sending chain identifier. SourceChain string `protobuf:"bytes,1,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty" yaml:"source_chain"` // the receiving chain identifier. DestinationChain string `protobuf:"bytes,2,opt,name=destination_chain,json=destinationChain,proto3" json:"destination_chain,omitempty" yaml:"source_chain"` // packet sequence. Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` // embedded data that represents packet state. Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` } func (m *PacketState) Reset() { *m = PacketState{} } func (m *PacketState) String() string { return proto.CompactTextString(m) } func (*PacketState) ProtoMessage() {} func (*PacketState) Descriptor() ([]byte, []int) { return fileDescriptor_59da8d378a3b7468, []int{2} } func (m *PacketState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *PacketState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_PacketState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *PacketState) XXX_Merge(src proto.Message) { xxx_messageInfo_PacketState.Merge(m, src) } func (m *PacketState) XXX_Size() int { return m.Size() } func (m *PacketState) XXX_DiscardUnknown() { xxx_messageInfo_PacketState.DiscardUnknown(m) } var xxx_messageInfo_PacketState proto.InternalMessageInfo // Acknowledgement is the recommended acknowledgement format to be used by // app-specific protocols. // NOTE: The field numbers 21 and 22 were explicitly chosen to avoid accidental // conflicts with other protobuf message formats used for acknowledgements. // The first byte of any message with this format will be the non-ASCII values // `0xaa` (result) or `0xb2` (error). Implemented as defined by TICS: // https://github.com/bianjieai/tics/tree/master/spec/tics-004-channel-and-packet-semantics#acknowledgement-envelope type Acknowledgement struct { // response contains either a result or an error and must be non-empty // // Types that are valid to be assigned to Response: // *Acknowledgement_Result // *Acknowledgement_Error Response isAcknowledgement_Response `protobuf_oneof:"response"` } func (m *Acknowledgement) Reset() { *m = Acknowledgement{} } func (m *Acknowledgement) String() string { return proto.CompactTextString(m) } func (*Acknowledgement) ProtoMessage() {} func (*Acknowledgement) Descriptor() ([]byte, []int) { return fileDescriptor_59da8d378a3b7468, []int{3} } func (m *Acknowledgement) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Acknowledgement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Acknowledgement.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Acknowledgement) XXX_Merge(src proto.Message) { xxx_messageInfo_Acknowledgement.Merge(m, src) } func (m *Acknowledgement) XXX_Size() int { return m.Size() } func (m *Acknowledgement) XXX_DiscardUnknown() { xxx_messageInfo_Acknowledgement.DiscardUnknown(m) } var xxx_messageInfo_Acknowledgement proto.InternalMessageInfo type isAcknowledgement_Response interface { isAcknowledgement_Response() MarshalTo([]byte) (int, error) Size() int } type Acknowledgement_Result struct { Result []byte `protobuf:"bytes,21,opt,name=result,proto3,oneof" json:"result,omitempty"` } type Acknowledgement_Error struct { Error string `protobuf:"bytes,22,opt,name=error,proto3,oneof" json:"error,omitempty"` } func (*Acknowledgement_Result) isAcknowledgement_Response() {} func (*Acknowledgement_Error) isAcknowledgement_Response() {} func (m *Acknowledgement) GetResponse() isAcknowledgement_Response { if m != nil { return m.Response } return nil } func (m *Acknowledgement) GetResult() []byte { if x, ok := m.GetResponse().(*Acknowledgement_Result); ok { return x.Result } return nil } func (m *Acknowledgement) GetError() string { if x, ok := m.GetResponse().(*Acknowledgement_Error); ok { return x.Error } return "" } // XXX_OneofWrappers is for the internal use of the proto package. func (*Acknowledgement) XXX_OneofWrappers() []interface{} { return []interface{}{ (*Acknowledgement_Result)(nil), (*Acknowledgement_Error)(nil), } } func init() { proto.RegisterType((*Packet)(nil), "tibc.core.packet.v1.Packet") proto.RegisterType((*CleanPacket)(nil), "tibc.core.packet.v1.CleanPacket") proto.RegisterType((*PacketState)(nil), "tibc.core.packet.v1.PacketState") proto.RegisterType((*Acknowledgement)(nil), "tibc.core.packet.v1.Acknowledgement") } func init() { proto.RegisterFile("tibc/core/packet/v1/packet.proto", fileDescriptor_59da8d378a3b7468) } var fileDescriptor_59da8d378a3b7468 = []byte{ // 448 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x93, 0x41, 0x8b, 0xd3, 0x40, 0x14, 0xc7, 0x33, 0xdd, 0x6c, 0x59, 0x5f, 0x17, 0xd4, 0x59, 0xed, 0x86, 0x15, 0xd2, 0x92, 0x53, 0x2f, 0xdb, 0xb8, 0x28, 0x08, 0x3d, 0x08, 0x76, 0x3d, 0xf4, 0xa6, 0xc4, 0x8b, 0x78, 0x91, 0x69, 0xfa, 0xc8, 0xc6, 0x4d, 0x67, 0xe2, 0xcc, 0x64, 0xa5, 0xdf, 0xc0, 0xa3, 0x7e, 0x03, 0xbf, 0x8c, 0xe0, 0x71, 0x8f, 0x9e, 0x8a, 0xb4, 0x77, 0x0f, 0xfd, 0x04, 0x32, 0x33, 0x41, 0x03, 0x11, 0xd1, 0xa3, 0xb7, 0xf7, 0x9f, 0xf7, 0xcf, 0x2f, 0xf9, 0xbf, 0xc9, 0x83, 0xa1, 0xce, 0xe7, 0x69, 0x9c, 0x0a, 0x89, 0x71, 0xc9, 0xd2, 0x4b, 0xd4, 0xf1, 0xd5, 0x59, 0x5d, 0x8d, 0x4b, 0x29, 0xb4, 0xa0, 0x47, 0xc6, 0x31, 0x36, 0x8e, 0x71, 0x7d, 0x7e, 0x75, 0x76, 0x72, 0x27, 0x13, 0x99, 0xb0, 0xfd, 0xd8, 0x54, 0xce, 0x1a, 0x7d, 0xec, 0x40, 0xf7, 0xb9, 0xf5, 0xd0, 0x13, 0x38, 0x50, 0xf8, 0xb6, 0x42, 0x9e, 0x62, 0x40, 0x86, 0x64, 0xe4, 0x27, 0x3f, 0x35, 0xa5, 0xe0, 0x97, 0x42, 0xea, 0xa0, 0x33, 0x24, 0xa3, 0x1b, 0x89, 0xad, 0xe9, 0x04, 0x0e, 0x95, 0xa8, 0x64, 0x8a, 0xaf, 0xd3, 0x0b, 0x96, 0xf3, 0x60, 0xcf, 0xf4, 0xa6, 0xc7, 0xbb, 0xf5, 0xe0, 0x68, 0xc5, 0x96, 0xc5, 0x24, 0x6a, 0x76, 0xa3, 0xa4, 0xe7, 0xe4, 0xb9, 0x51, 0x74, 0x06, 0xb7, 0x17, 0xa8, 0x74, 0xce, 0x99, 0xce, 0x05, 0xaf, 0x01, 0xbe, 0x05, 0xdc, 0xdb, 0xad, 0x07, 0xc7, 0x0e, 0xd0, 0xb4, 0x98, 0x57, 0x46, 0xc9, 0xad, 0xc6, 0x91, 0x23, 0x3d, 0x82, 0x9e, 0xc4, 0x82, 0xad, 0x6a, 0xc6, 0xbe, 0x65, 0xf4, 0x77, 0xeb, 0x01, 0x75, 0x8c, 0x46, 0x33, 0x4a, 0xc0, 0x2a, 0xf7, 0x20, 0x05, 0x7f, 0xc1, 0x34, 0x0b, 0xba, 0x43, 0x32, 0x3a, 0x4c, 0x6c, 0x3d, 0xf1, 0xdf, 0x7f, 0x1a, 0x78, 0xd1, 0x77, 0x02, 0xbd, 0xf3, 0x02, 0x19, 0xff, 0x8b, 0xc1, 0xfc, 0xdf, 0x43, 0xa8, 0x03, 0x7f, 0x26, 0xd0, 0x73, 0x59, 0x5f, 0x68, 0xa6, 0xdb, 0xa1, 0xc8, 0x3f, 0x84, 0x7a, 0xfa, 0xbb, 0x50, 0x9d, 0x3f, 0x03, 0xda, 0x81, 0x9a, 0x23, 0xdf, 0x6b, 0xff, 0x8b, 0xf6, 0xe2, 0xfc, 0xd6, 0xc5, 0x3d, 0x83, 0x9b, 0x4f, 0xd2, 0x4b, 0x2e, 0xde, 0x15, 0xb8, 0xc8, 0x70, 0x89, 0x5c, 0xd3, 0x00, 0xba, 0x12, 0x55, 0x55, 0xe8, 0xe0, 0xae, 0xb1, 0xcf, 0xbc, 0xa4, 0xd6, 0xb4, 0x0f, 0xfb, 0x28, 0xa5, 0x90, 0x41, 0xdf, 0x7c, 0xdc, 0xcc, 0x4b, 0x9c, 0x9c, 0x02, 0x1c, 0x48, 0x54, 0xa5, 0xe0, 0x0a, 0xa7, 0x2f, 0xbf, 0x6c, 0x42, 0x72, 0xbd, 0x09, 0xc9, 0xb7, 0x4d, 0x48, 0x3e, 0x6c, 0x43, 0xef, 0x7a, 0x1b, 0x7a, 0x5f, 0xb7, 0xa1, 0xf7, 0xea, 0x71, 0x96, 0xeb, 0x8b, 0x6a, 0x3e, 0x4e, 0xc5, 0x32, 0x9e, 0xe7, 0x8c, 0xbf, 0xc9, 0x91, 0xe5, 0xb1, 0xd9, 0xbb, 0xd3, 0x4c, 0xc4, 0x4b, 0xb1, 0xa8, 0x0a, 0x54, 0xf1, 0xaf, 0x4d, 0xbd, 0xff, 0xf0, 0xb4, 0x5e, 0x56, 0xbd, 0x2a, 0x51, 0xcd, 0xbb, 0x76, 0xfd, 0x1e, 0xfc, 0x08, 0x00, 0x00, 0xff, 0xff, 0x98, 0x07, 0x13, 0xe4, 0xcd, 0x03, 0x00, 0x00, } func (m *Packet) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Packet) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Packet) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Data) > 0 { i -= len(m.Data) copy(dAtA[i:], m.Data) i = encodeVarintPacket(dAtA, i, uint64(len(m.Data))) i-- dAtA[i] = 0x32 } if len(m.RelayChain) > 0 { i -= len(m.RelayChain) copy(dAtA[i:], m.RelayChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.RelayChain))) i-- dAtA[i] = 0x2a } if len(m.DestinationChain) > 0 { i -= len(m.DestinationChain) copy(dAtA[i:], m.DestinationChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.DestinationChain))) i-- dAtA[i] = 0x22 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x1a } if len(m.Port) > 0 { i -= len(m.Port) copy(dAtA[i:], m.Port) i = encodeVarintPacket(dAtA, i, uint64(len(m.Port))) i-- dAtA[i] = 0x12 } if m.Sequence != 0 { i = encodeVarintPacket(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } func (m *CleanPacket) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *CleanPacket) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *CleanPacket) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.RelayChain) > 0 { i -= len(m.RelayChain) copy(dAtA[i:], m.RelayChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.RelayChain))) i-- dAtA[i] = 0x2a } if len(m.DestinationChain) > 0 { i -= len(m.DestinationChain) copy(dAtA[i:], m.DestinationChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.DestinationChain))) i-- dAtA[i] = 0x22 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x1a } if m.Sequence != 0 { i = encodeVarintPacket(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } func (m *PacketState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *PacketState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *PacketState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Data) > 0 { i -= len(m.Data) copy(dAtA[i:], m.Data) i = encodeVarintPacket(dAtA, i, uint64(len(m.Data))) i-- dAtA[i] = 0x22 } if m.Sequence != 0 { i = encodeVarintPacket(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x18 } if len(m.DestinationChain) > 0 { i -= len(m.DestinationChain) copy(dAtA[i:], m.DestinationChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.DestinationChain))) i-- dAtA[i] = 0x12 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintPacket(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *Acknowledgement) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Acknowledgement) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Acknowledgement) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Response != nil { { size := m.Response.Size() i -= size if _, err := m.Response.MarshalTo(dAtA[i:]); err != nil { return 0, err } } } return len(dAtA) - i, nil } func (m *Acknowledgement_Result) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Acknowledgement_Result) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) if m.Result != nil { i -= len(m.Result) copy(dAtA[i:], m.Result) i = encodeVarintPacket(dAtA, i, uint64(len(m.Result))) i-- dAtA[i] = 0x1 i-- dAtA[i] = 0xaa } return len(dAtA) - i, nil } func (m *Acknowledgement_Error) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Acknowledgement_Error) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) i -= len(m.Error) copy(dAtA[i:], m.Error) i = encodeVarintPacket(dAtA, i, uint64(len(m.Error))) i-- dAtA[i] = 0x1 i-- dAtA[i] = 0xb2 return len(dAtA) - i, nil } func encodeVarintPacket(dAtA []byte, offset int, v uint64) int { offset -= sovPacket(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *Packet) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Sequence != 0 { n += 1 + sovPacket(uint64(m.Sequence)) } l = len(m.Port) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.DestinationChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.RelayChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.Data) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } return n } func (m *CleanPacket) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Sequence != 0 { n += 1 + sovPacket(uint64(m.Sequence)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.DestinationChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.RelayChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } return n } func (m *PacketState) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.SourceChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } l = len(m.DestinationChain) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } if m.Sequence != 0 { n += 1 + sovPacket(uint64(m.Sequence)) } l = len(m.Data) if l > 0 { n += 1 + l + sovPacket(uint64(l)) } return n } func (m *Acknowledgement) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Response != nil { n += m.Response.Size() } return n } func (m *Acknowledgement_Result) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Result != nil { l = len(m.Result) n += 2 + l + sovPacket(uint64(l)) } return n } func (m *Acknowledgement_Error) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Error) n += 2 + l + sovPacket(uint64(l)) return n } func sovPacket(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozPacket(x uint64) (n int) { return sovPacket(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *Packet) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Packet: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Packet: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Port", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.Port = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestinationChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.DestinationChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RelayChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.RelayChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) if m.Data == nil { m.Data = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipPacket(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthPacket } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *CleanPacket) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: CleanPacket: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CleanPacket: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestinationChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.DestinationChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RelayChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.RelayChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipPacket(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthPacket } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *PacketState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PacketState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PacketState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestinationChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.DestinationChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) if m.Data == nil { m.Data = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipPacket(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthPacket } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Acknowledgement) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Acknowledgement: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Acknowledgement: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 21: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } v := make([]byte, postIndex-iNdEx) copy(v, dAtA[iNdEx:postIndex]) m.Response = &Acknowledgement_Result{v} iNdEx = postIndex case 22: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowPacket } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthPacket } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthPacket } if postIndex > l { return io.ErrUnexpectedEOF } m.Response = &Acknowledgement_Error{string(dAtA[iNdEx:postIndex])} iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipPacket(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthPacket } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipPacket(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowPacket } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowPacket } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowPacket } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthPacket } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupPacket } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthPacket } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthPacket = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowPacket = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupPacket = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/02-client/types/client.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/client/v1/client.proto package types import ( fmt "fmt" types "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // IdentifiedClientState defines a client state with an additional client // identifier field. type IdentifiedClientState struct { // client identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // client state ClientState *types.Any `protobuf:"bytes,2,opt,name=client_state,json=clientState,proto3" json:"client_state,omitempty"` } func (m *IdentifiedClientState) Reset() { *m = IdentifiedClientState{} } func (m *IdentifiedClientState) String() string { return proto.CompactTextString(m) } func (*IdentifiedClientState) ProtoMessage() {} func (*IdentifiedClientState) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{0} } func (m *IdentifiedClientState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *IdentifiedClientState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_IdentifiedClientState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *IdentifiedClientState) XXX_Merge(src proto.Message) { xxx_messageInfo_IdentifiedClientState.Merge(m, src) } func (m *IdentifiedClientState) XXX_Size() int { return m.Size() } func (m *IdentifiedClientState) XXX_DiscardUnknown() { xxx_messageInfo_IdentifiedClientState.DiscardUnknown(m) } var xxx_messageInfo_IdentifiedClientState proto.InternalMessageInfo func (m *IdentifiedClientState) GetChainName() string { if m != nil { return m.ChainName } return "" } func (m *IdentifiedClientState) GetClientState() *types.Any { if m != nil { return m.ClientState } return nil } // IdentifiedRelayer defines a list of authorized relayers for the specified // client. type IdentifiedRelayers struct { // client identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // authorized relayer list Relayers []string `protobuf:"bytes,2,rep,name=relayers,proto3" json:"relayers,omitempty"` } func (m *IdentifiedRelayers) Reset() { *m = IdentifiedRelayers{} } func (m *IdentifiedRelayers) String() string { return proto.CompactTextString(m) } func (*IdentifiedRelayers) ProtoMessage() {} func (*IdentifiedRelayers) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{1} } func (m *IdentifiedRelayers) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *IdentifiedRelayers) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_IdentifiedRelayers.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *IdentifiedRelayers) XXX_Merge(src proto.Message) { xxx_messageInfo_IdentifiedRelayers.Merge(m, src) } func (m *IdentifiedRelayers) XXX_Size() int { return m.Size() } func (m *IdentifiedRelayers) XXX_DiscardUnknown() { xxx_messageInfo_IdentifiedRelayers.DiscardUnknown(m) } var xxx_messageInfo_IdentifiedRelayers proto.InternalMessageInfo func (m *IdentifiedRelayers) GetChainName() string { if m != nil { return m.ChainName } return "" } func (m *IdentifiedRelayers) GetRelayers() []string { if m != nil { return m.Relayers } return nil } // ConsensusStateWithHeight defines a consensus state with an additional height // field. type ConsensusStateWithHeight struct { // consensus state height Height Height `protobuf:"bytes,1,opt,name=height,proto3" json:"height"` // consensus state ConsensusState *types.Any `protobuf:"bytes,2,opt,name=consensus_state,json=consensusState,proto3" json:"consensus_state,omitempty"` } func (m *ConsensusStateWithHeight) Reset() { *m = ConsensusStateWithHeight{} } func (m *ConsensusStateWithHeight) String() string { return proto.CompactTextString(m) } func (*ConsensusStateWithHeight) ProtoMessage() {} func (*ConsensusStateWithHeight) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{2} } func (m *ConsensusStateWithHeight) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ConsensusStateWithHeight) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ConsensusStateWithHeight.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ConsensusStateWithHeight) XXX_Merge(src proto.Message) { xxx_messageInfo_ConsensusStateWithHeight.Merge(m, src) } func (m *ConsensusStateWithHeight) XXX_Size() int { return m.Size() } func (m *ConsensusStateWithHeight) XXX_DiscardUnknown() { xxx_messageInfo_ConsensusStateWithHeight.DiscardUnknown(m) } var xxx_messageInfo_ConsensusStateWithHeight proto.InternalMessageInfo func (m *ConsensusStateWithHeight) GetHeight() Height { if m != nil { return m.Height } return Height{} } func (m *ConsensusStateWithHeight) GetConsensusState() *types.Any { if m != nil { return m.ConsensusState } return nil } // ClientConsensusStates defines all the stored consensus states for a given // client. type ClientConsensusStates struct { // client identifier ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // consensus states and their heights associated with the client ConsensusStates []ConsensusStateWithHeight `protobuf:"bytes,2,rep,name=consensus_states,json=consensusStates,proto3" json:"consensus_states"` } func (m *ClientConsensusStates) Reset() { *m = ClientConsensusStates{} } func (m *ClientConsensusStates) String() string { return proto.CompactTextString(m) } func (*ClientConsensusStates) ProtoMessage() {} func (*ClientConsensusStates) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{3} } func (m *ClientConsensusStates) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *ClientConsensusStates) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_ClientConsensusStates.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *ClientConsensusStates) XXX_Merge(src proto.Message) { xxx_messageInfo_ClientConsensusStates.Merge(m, src) } func (m *ClientConsensusStates) XXX_Size() int { return m.Size() } func (m *ClientConsensusStates) XXX_DiscardUnknown() { xxx_messageInfo_ClientConsensusStates.DiscardUnknown(m) } var xxx_messageInfo_ClientConsensusStates proto.InternalMessageInfo func (m *ClientConsensusStates) GetChainName() string { if m != nil { return m.ChainName } return "" } func (m *ClientConsensusStates) GetConsensusStates() []ConsensusStateWithHeight { if m != nil { return m.ConsensusStates } return nil } // CreateClientProposal defines a overnance proposal to create an TIBC client type CreateClientProposal struct { // the title of the update proposal Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` // the description of the proposal Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` // the client identifier for the client to be updated if the proposal passes ChainName string `protobuf:"bytes,3,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // light client state ClientState *types.Any `protobuf:"bytes,4,opt,name=client_state,json=clientState,proto3" json:"client_state,omitempty"` // consensus state associated with the client that corresponds to a given // height. ConsensusState *types.Any `protobuf:"bytes,5,opt,name=consensus_state,json=consensusState,proto3" json:"consensus_state,omitempty"` } func (m *CreateClientProposal) Reset() { *m = CreateClientProposal{} } func (m *CreateClientProposal) String() string { return proto.CompactTextString(m) } func (*CreateClientProposal) ProtoMessage() {} func (*CreateClientProposal) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{4} } func (m *CreateClientProposal) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *CreateClientProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_CreateClientProposal.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *CreateClientProposal) XXX_Merge(src proto.Message) { xxx_messageInfo_CreateClientProposal.Merge(m, src) } func (m *CreateClientProposal) XXX_Size() int { return m.Size() } func (m *CreateClientProposal) XXX_DiscardUnknown() { xxx_messageInfo_CreateClientProposal.DiscardUnknown(m) } var xxx_messageInfo_CreateClientProposal proto.InternalMessageInfo // UpgradeClientProposal defines a overnance proposal to overide an TIBC client // state type UpgradeClientProposal struct { // the title of the update proposal Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` // the description of the proposal Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` // the client identifier for the client to be updated if the proposal passes ChainName string `protobuf:"bytes,3,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // client state ClientState *types.Any `protobuf:"bytes,4,opt,name=client_state,json=clientState,proto3" json:"client_state,omitempty"` // consensus state ConsensusState *types.Any `protobuf:"bytes,5,opt,name=consensus_state,json=consensusState,proto3" json:"consensus_state,omitempty"` } func (m *UpgradeClientProposal) Reset() { *m = UpgradeClientProposal{} } func (m *UpgradeClientProposal) String() string { return proto.CompactTextString(m) } func (*UpgradeClientProposal) ProtoMessage() {} func (*UpgradeClientProposal) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{5} } func (m *UpgradeClientProposal) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *UpgradeClientProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_UpgradeClientProposal.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *UpgradeClientProposal) XXX_Merge(src proto.Message) { xxx_messageInfo_UpgradeClientProposal.Merge(m, src) } func (m *UpgradeClientProposal) XXX_Size() int { return m.Size() } func (m *UpgradeClientProposal) XXX_DiscardUnknown() { xxx_messageInfo_UpgradeClientProposal.DiscardUnknown(m) } var xxx_messageInfo_UpgradeClientProposal proto.InternalMessageInfo // RegisterRelayerProposal defines a overnance proposal to register some // relayers for updating a client state. type RegisterRelayerProposal struct { // the title of the update proposal Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` // the description of the proposal Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` // the client identifier for the client to be updated if the proposal passes ChainName string `protobuf:"bytes,3,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` // relayer address list Relayers []string `protobuf:"bytes,4,rep,name=relayers,proto3" json:"relayers,omitempty"` } func (m *RegisterRelayerProposal) Reset() { *m = RegisterRelayerProposal{} } func (m *RegisterRelayerProposal) String() string { return proto.CompactTextString(m) } func (*RegisterRelayerProposal) ProtoMessage() {} func (*RegisterRelayerProposal) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{6} } func (m *RegisterRelayerProposal) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *RegisterRelayerProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_RegisterRelayerProposal.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *RegisterRelayerProposal) XXX_Merge(src proto.Message) { xxx_messageInfo_RegisterRelayerProposal.Merge(m, src) } func (m *RegisterRelayerProposal) XXX_Size() int { return m.Size() } func (m *RegisterRelayerProposal) XXX_DiscardUnknown() { xxx_messageInfo_RegisterRelayerProposal.DiscardUnknown(m) } var xxx_messageInfo_RegisterRelayerProposal proto.InternalMessageInfo // Height is a monotonically increasing data type // that can be compared against another Height for the purposes of updating and // freezing clients // // Normally the RevisionHeight is incremented at each height while keeping // RevisionNumber the same. However some consensus algorithms may choose to // reset the height in certain conditions e.g. hard forks, state-machine // breaking changes In these cases, the RevisionNumber is incremented so that // height continues to be monitonically increasing even as the RevisionHeight // gets reset type Height struct { // the revision that the client is currently on RevisionNumber uint64 `protobuf:"varint,1,opt,name=revision_number,json=revisionNumber,proto3" json:"revision_number,omitempty" yaml:"revision_number"` // the height within the given revision RevisionHeight uint64 `protobuf:"varint,2,opt,name=revision_height,json=revisionHeight,proto3" json:"revision_height,omitempty" yaml:"revision_height"` } func (m *Height) Reset() { *m = Height{} } func (*Height) ProtoMessage() {} func (*Height) Descriptor() ([]byte, []int) { return fileDescriptor_9e35181a4b95fed0, []int{7} } func (m *Height) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *Height) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_Height.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *Height) XXX_Merge(src proto.Message) { xxx_messageInfo_Height.Merge(m, src) } func (m *Height) XXX_Size() int { return m.Size() } func (m *Height) XXX_DiscardUnknown() { xxx_messageInfo_Height.DiscardUnknown(m) } var xxx_messageInfo_Height proto.InternalMessageInfo func init() { proto.RegisterType((*IdentifiedClientState)(nil), "tibc.core.client.v1.IdentifiedClientState") proto.RegisterType((*IdentifiedRelayers)(nil), "tibc.core.client.v1.IdentifiedRelayers") proto.RegisterType((*ConsensusStateWithHeight)(nil), "tibc.core.client.v1.ConsensusStateWithHeight") proto.RegisterType((*ClientConsensusStates)(nil), "tibc.core.client.v1.ClientConsensusStates") proto.RegisterType((*CreateClientProposal)(nil), "tibc.core.client.v1.CreateClientProposal") proto.RegisterType((*UpgradeClientProposal)(nil), "tibc.core.client.v1.UpgradeClientProposal") proto.RegisterType((*RegisterRelayerProposal)(nil), "tibc.core.client.v1.RegisterRelayerProposal") proto.RegisterType((*Height)(nil), "tibc.core.client.v1.Height") } func init() { proto.RegisterFile("tibc/core/client/v1/client.proto", fileDescriptor_9e35181a4b95fed0) } var fileDescriptor_9e35181a4b95fed0 = []byte{ // 563 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x54, 0x3f, 0x6f, 0xd3, 0x40, 0x14, 0xf7, 0xb5, 0x69, 0xd5, 0x5c, 0x50, 0x8b, 0x4c, 0x02, 0x21, 0x08, 0x27, 0xf2, 0x94, 0x25, 0x36, 0x0d, 0x03, 0x22, 0x12, 0x48, 0x24, 0x0b, 0x2c, 0x05, 0x19, 0x21, 0x10, 0x03, 0xd1, 0xd9, 0x79, 0x75, 0x0e, 0xd9, 0x77, 0x91, 0xef, 0x12, 0x29, 0xdf, 0x80, 0x11, 0x21, 0x84, 0x18, 0x18, 0xfa, 0x71, 0x3a, 0x76, 0x64, 0xaa, 0x50, 0x32, 0xc2, 0xc4, 0x27, 0x40, 0xbe, 0x73, 0xc8, 0x1f, 0xa5, 0x4a, 0x16, 0x26, 0xb6, 0xbb, 0xe7, 0x9f, 0x7f, 0x7f, 0xee, 0xdd, 0x3b, 0x5c, 0x93, 0xd4, 0x0f, 0xdc, 0x80, 0x27, 0xe0, 0x06, 0x11, 0x05, 0x26, 0xdd, 0xd1, 0x71, 0xb6, 0x72, 0x06, 0x09, 0x97, 0xdc, 0xbc, 0x91, 0x22, 0x9c, 0x14, 0xe1, 0x64, 0xf5, 0xd1, 0x71, 0xa5, 0x18, 0xf2, 0x90, 0xab, 0xef, 0x6e, 0xba, 0xd2, 0xd0, 0xca, 0xed, 0x90, 0xf3, 0x30, 0x02, 0x57, 0xed, 0xfc, 0xe1, 0xa9, 0x4b, 0xd8, 0x58, 0x7f, 0xb2, 0x39, 0x2e, 0x3d, 0xeb, 0x01, 0x93, 0xf4, 0x94, 0x42, 0xaf, 0xa3, 0x78, 0x5e, 0x4a, 0x22, 0xc1, 0xbc, 0x8b, 0x71, 0xd0, 0x27, 0x94, 0x75, 0x19, 0x89, 0xa1, 0x8c, 0x6a, 0xa8, 0x9e, 0xf7, 0xf2, 0xaa, 0x72, 0x42, 0x62, 0x30, 0x1f, 0xe0, 0x6b, 0x5a, 0xb5, 0x2b, 0x52, 0x78, 0x79, 0xa7, 0x86, 0xea, 0x85, 0x66, 0xd1, 0xd1, 0x4a, 0xce, 0x4c, 0xc9, 0x79, 0xc2, 0xc6, 0x5e, 0x21, 0x98, 0xf3, 0xda, 0xcf, 0xb1, 0x39, 0x17, 0xf4, 0x20, 0x22, 0x63, 0x48, 0xc4, 0x26, 0xb5, 0x0a, 0x3e, 0x48, 0x32, 0x68, 0x79, 0xa7, 0xb6, 0x5b, 0xcf, 0x7b, 0x7f, 0xf7, 0xf6, 0x67, 0x84, 0xcb, 0x1d, 0xce, 0x04, 0x30, 0x31, 0x14, 0x4a, 0xe3, 0x35, 0x95, 0xfd, 0xa7, 0x40, 0xc3, 0xbe, 0x34, 0x1f, 0xe2, 0xfd, 0xbe, 0x5a, 0x29, 0xce, 0x42, 0xf3, 0x8e, 0xb3, 0xe6, 0xd4, 0x1c, 0x0d, 0x6e, 0xe7, 0xce, 0x2f, 0xab, 0x86, 0x97, 0xfd, 0x60, 0x3e, 0xc2, 0x47, 0xc1, 0x8c, 0x76, 0x8b, 0x90, 0x87, 0xc1, 0x92, 0x07, 0xfb, 0x0b, 0xc2, 0x25, 0x7d, 0x9e, 0xcb, 0xe6, 0x36, 0x66, 0x7d, 0x87, 0xaf, 0xaf, 0xe8, 0xea, 0xcc, 0x85, 0x66, 0x63, 0xad, 0xf9, 0xab, 0xb2, 0x67, 0x71, 0x8e, 0x96, 0x7d, 0x09, 0xfb, 0x27, 0xc2, 0xc5, 0x4e, 0x02, 0x44, 0x82, 0xb6, 0xf7, 0x22, 0xe1, 0x03, 0x2e, 0x48, 0x64, 0x16, 0xf1, 0x9e, 0xa4, 0x32, 0x9a, 0x59, 0xd2, 0x1b, 0xb3, 0x86, 0x0b, 0x3d, 0x10, 0x41, 0x42, 0x07, 0x92, 0x72, 0xa6, 0x8e, 0x20, 0xef, 0x2d, 0x96, 0x56, 0xf2, 0xec, 0x6e, 0xba, 0x29, 0xb9, 0x2d, 0x6f, 0xca, 0xba, 0x06, 0xec, 0x6d, 0xdf, 0x80, 0x56, 0xee, 0xc3, 0x59, 0xd5, 0xb0, 0x7f, 0x21, 0x5c, 0x7a, 0x35, 0x08, 0x13, 0xd2, 0xfb, 0x2f, 0xe2, 0x7e, 0x42, 0xf8, 0x96, 0x07, 0x21, 0x15, 0x12, 0x92, 0x6c, 0xb8, 0xfe, 0x75, 0xe0, 0xc5, 0xd9, 0xcc, 0x2d, 0xcf, 0x66, 0x66, 0xea, 0x1b, 0xc2, 0xfb, 0xd9, 0x3c, 0x76, 0xf0, 0x51, 0x02, 0x23, 0x2a, 0x28, 0x67, 0x5d, 0x36, 0x8c, 0x7d, 0x48, 0x94, 0x9b, 0x5c, 0xbb, 0xf2, 0xfb, 0xb2, 0x7a, 0x73, 0x4c, 0xe2, 0xa8, 0x65, 0xaf, 0x00, 0x6c, 0xef, 0x70, 0x56, 0x39, 0x51, 0x85, 0x25, 0x92, 0x6c, 0xba, 0x77, 0xae, 0x24, 0xd1, 0x80, 0x05, 0x12, 0xed, 0xa4, 0x75, 0x90, 0x5a, 0xfb, 0x7a, 0x56, 0x35, 0xda, 0x6f, 0xce, 0x27, 0x16, 0xba, 0x98, 0x58, 0xe8, 0xc7, 0xc4, 0x42, 0x1f, 0xa7, 0x96, 0x71, 0x31, 0xb5, 0x8c, 0xef, 0x53, 0xcb, 0x78, 0xfb, 0x38, 0xa4, 0xb2, 0x3f, 0xf4, 0x9d, 0x80, 0xc7, 0xae, 0x4f, 0x09, 0x7b, 0x4f, 0x81, 0x50, 0x37, 0x1d, 0xc2, 0x46, 0xc8, 0xdd, 0x98, 0xf7, 0x86, 0x11, 0x08, 0x77, 0xfe, 0x52, 0xdf, 0x6b, 0x36, 0xb2, 0xc7, 0x5a, 0x8e, 0x07, 0x20, 0xfc, 0x7d, 0xd5, 0xb1, 0xfb, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0x34, 0x36, 0xe4, 0x42, 0xcd, 0x05, 0x00, 0x00, } func (m *IdentifiedClientState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *IdentifiedClientState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *IdentifiedClientState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.ClientState != nil { { size, err := m.ClientState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintClient(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *IdentifiedRelayers) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *IdentifiedRelayers) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *IdentifiedRelayers) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Relayers) > 0 { for iNdEx := len(m.Relayers) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Relayers[iNdEx]) copy(dAtA[i:], m.Relayers[iNdEx]) i = encodeVarintClient(dAtA, i, uint64(len(m.Relayers[iNdEx]))) i-- dAtA[i] = 0x12 } } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintClient(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *ConsensusStateWithHeight) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ConsensusStateWithHeight) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ConsensusStateWithHeight) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.ConsensusState != nil { { size, err := m.ConsensusState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *ClientConsensusStates) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClientConsensusStates) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *ClientConsensusStates) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.ConsensusStates) > 0 { for iNdEx := len(m.ConsensusStates) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.ConsensusStates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintClient(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *CreateClientProposal) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *CreateClientProposal) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *CreateClientProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.ConsensusState != nil { { size, err := m.ConsensusState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x2a } if m.ClientState != nil { { size, err := m.ClientState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintClient(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0x1a } if len(m.Description) > 0 { i -= len(m.Description) copy(dAtA[i:], m.Description) i = encodeVarintClient(dAtA, i, uint64(len(m.Description))) i-- dAtA[i] = 0x12 } if len(m.Title) > 0 { i -= len(m.Title) copy(dAtA[i:], m.Title) i = encodeVarintClient(dAtA, i, uint64(len(m.Title))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *UpgradeClientProposal) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *UpgradeClientProposal) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *UpgradeClientProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.ConsensusState != nil { { size, err := m.ConsensusState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x2a } if m.ClientState != nil { { size, err := m.ClientState.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintClient(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintClient(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0x1a } if len(m.Description) > 0 { i -= len(m.Description) copy(dAtA[i:], m.Description) i = encodeVarintClient(dAtA, i, uint64(len(m.Description))) i-- dAtA[i] = 0x12 } if len(m.Title) > 0 { i -= len(m.Title) copy(dAtA[i:], m.Title) i = encodeVarintClient(dAtA, i, uint64(len(m.Title))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *RegisterRelayerProposal) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *RegisterRelayerProposal) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *RegisterRelayerProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Relayers) > 0 { for iNdEx := len(m.Relayers) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Relayers[iNdEx]) copy(dAtA[i:], m.Relayers[iNdEx]) i = encodeVarintClient(dAtA, i, uint64(len(m.Relayers[iNdEx]))) i-- dAtA[i] = 0x22 } } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintClient(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0x1a } if len(m.Description) > 0 { i -= len(m.Description) copy(dAtA[i:], m.Description) i = encodeVarintClient(dAtA, i, uint64(len(m.Description))) i-- dAtA[i] = 0x12 } if len(m.Title) > 0 { i -= len(m.Title) copy(dAtA[i:], m.Title) i = encodeVarintClient(dAtA, i, uint64(len(m.Title))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *Height) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Height) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *Height) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.RevisionHeight != 0 { i = encodeVarintClient(dAtA, i, uint64(m.RevisionHeight)) i-- dAtA[i] = 0x10 } if m.RevisionNumber != 0 { i = encodeVarintClient(dAtA, i, uint64(m.RevisionNumber)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } func encodeVarintClient(dAtA []byte, offset int, v uint64) int { offset -= sovClient(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *IdentifiedClientState) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovClient(uint64(l)) } if m.ClientState != nil { l = m.ClientState.Size() n += 1 + l + sovClient(uint64(l)) } return n } func (m *IdentifiedRelayers) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovClient(uint64(l)) } if len(m.Relayers) > 0 { for _, s := range m.Relayers { l = len(s) n += 1 + l + sovClient(uint64(l)) } } return n } func (m *ConsensusStateWithHeight) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.Height.Size() n += 1 + l + sovClient(uint64(l)) if m.ConsensusState != nil { l = m.ConsensusState.Size() n += 1 + l + sovClient(uint64(l)) } return n } func (m *ClientConsensusStates) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovClient(uint64(l)) } if len(m.ConsensusStates) > 0 { for _, e := range m.ConsensusStates { l = e.Size() n += 1 + l + sovClient(uint64(l)) } } return n } func (m *CreateClientProposal) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Title) if l > 0 { n += 1 + l + sovClient(uint64(l)) } l = len(m.Description) if l > 0 { n += 1 + l + sovClient(uint64(l)) } l = len(m.ChainName) if l > 0 { n += 1 + l + sovClient(uint64(l)) } if m.ClientState != nil { l = m.ClientState.Size() n += 1 + l + sovClient(uint64(l)) } if m.ConsensusState != nil { l = m.ConsensusState.Size() n += 1 + l + sovClient(uint64(l)) } return n } func (m *UpgradeClientProposal) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Title) if l > 0 { n += 1 + l + sovClient(uint64(l)) } l = len(m.Description) if l > 0 { n += 1 + l + sovClient(uint64(l)) } l = len(m.ChainName) if l > 0 { n += 1 + l + sovClient(uint64(l)) } if m.ClientState != nil { l = m.ClientState.Size() n += 1 + l + sovClient(uint64(l)) } if m.ConsensusState != nil { l = m.ConsensusState.Size() n += 1 + l + sovClient(uint64(l)) } return n } func (m *RegisterRelayerProposal) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Title) if l > 0 { n += 1 + l + sovClient(uint64(l)) } l = len(m.Description) if l > 0 { n += 1 + l + sovClient(uint64(l)) } l = len(m.ChainName) if l > 0 { n += 1 + l + sovClient(uint64(l)) } if len(m.Relayers) > 0 { for _, s := range m.Relayers { l = len(s) n += 1 + l + sovClient(uint64(l)) } } return n } func (m *Height) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.RevisionNumber != 0 { n += 1 + sovClient(uint64(m.RevisionNumber)) } if m.RevisionHeight != 0 { n += 1 + sovClient(uint64(m.RevisionHeight)) } return n } func sovClient(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozClient(x uint64) (n int) { return sovClient(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *IdentifiedClientState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: IdentifiedClientState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: IdentifiedClientState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if m.ClientState == nil { m.ClientState = &types.Any{} } if err := m.ClientState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *IdentifiedRelayers) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: IdentifiedRelayers: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: IdentifiedRelayers: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Relayers", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Relayers = append(m.Relayers, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ConsensusStateWithHeight) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ConsensusStateWithHeight: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ConsensusStateWithHeight: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsensusState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if m.ConsensusState == nil { m.ConsensusState = &types.Any{} } if err := m.ConsensusState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ClientConsensusStates) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClientConsensusStates: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClientConsensusStates: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsensusStates", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ConsensusStates = append(m.ConsensusStates, ConsensusStateWithHeight{}) if err := m.ConsensusStates[len(m.ConsensusStates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *CreateClientProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: CreateClientProposal: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CreateClientProposal: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Title = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Description = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if m.ClientState == nil { m.ClientState = &types.Any{} } if err := m.ClientState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsensusState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if m.ConsensusState == nil { m.ConsensusState = &types.Any{} } if err := m.ConsensusState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *UpgradeClientProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: UpgradeClientProposal: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: UpgradeClientProposal: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Title = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Description = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if m.ClientState == nil { m.ClientState = &types.Any{} } if err := m.ClientState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsensusState", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } if m.ConsensusState == nil { m.ConsensusState = &types.Any{} } if err := m.ConsensusState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *RegisterRelayerProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: RegisterRelayerProposal: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: RegisterRelayerProposal: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Title = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Description = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Relayers", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthClient } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthClient } if postIndex > l { return io.ErrUnexpectedEOF } m.Relayers = append(m.Relayers, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Height) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Height: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Height: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field RevisionNumber", wireType) } m.RevisionNumber = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.RevisionNumber |= uint64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field RevisionHeight", wireType) } m.RevisionHeight = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowClient } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.RevisionHeight |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipClient(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthClient } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipClient(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowClient } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowClient } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowClient } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthClient } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupClient } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthClient } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthClient = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowClient = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupClient = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/light-clients/09-eth/types/hashing.go<|end_filename|> // Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum 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. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package types import ( "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rlp" "golang.org/x/crypto/sha3" ) // hasherPool holds LegacyKeccak256 hashers for rlpHash. var hasherPool = sync.Pool{ New: func() interface{} { return sha3.NewLegacyKeccak256() }, } // rlpHash encodes x and hashes the encoded bytes. func rlpHash(x interface{}) (h common.Hash) { sha := hasherPool.Get().(crypto.KeccakState) defer hasherPool.Put(sha) sha.Reset() _ = rlp.Encode(sha, x) _, _ = sha.Read(h[:]) return h } <|start_filename|>modules/tibc/core/24-host/errors.go<|end_filename|> package host import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // SubModuleName defines the TICS 24 host const SubModuleName = "host" const moduleName = ModuleName + "-" + SubModuleName // TIBC client sentinel errors var ( ErrInvalidID = sdkerrors.Register(moduleName, 2, "invalid identifier") ErrInvalidPath = sdkerrors.Register(moduleName, 3, "invalid path") ErrInvalidPacket = sdkerrors.Register(moduleName, 4, "invalid packet") ErrInvalidRule = sdkerrors.Register(moduleName, 5, "invalid routing rule") ) <|start_filename|>modules/tibc/testing/mock/doc.go<|end_filename|> /* This package is only intended to be used for testing core TIBC. In order to maintain secure testing, we need to do message passing and execution which requires connecting an TIBC application module that fulfills all the callbacks. We cannot connect to tibc-transfer which does not support all channel types so instead we create a mock application module which does nothing. It simply return nil in all cases so no error ever occurs. It is intended to be as minimal and lightweight as possible and should never import simapp. */ package mock <|start_filename|>modules/tibc/core/04-packet/types/tx.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/packet/v1/tx.proto package types import ( context "context" fmt "fmt" types "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // MsgRecvPacket receives incoming TIBC packet type MsgRecvPacket struct { Packet Packet `protobuf:"bytes,1,opt,name=packet,proto3" json:"packet"` ProofCommitment []byte `protobuf:"bytes,2,opt,name=proof_commitment,json=proofCommitment,proto3" json:"proof_commitment,omitempty" yaml:"proof_commitment"` ProofHeight types.Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height" yaml:"proof_height"` Signer string `protobuf:"bytes,4,opt,name=signer,proto3" json:"signer,omitempty"` } func (m *MsgRecvPacket) Reset() { *m = MsgRecvPacket{} } func (m *MsgRecvPacket) String() string { return proto.CompactTextString(m) } func (*MsgRecvPacket) ProtoMessage() {} func (*MsgRecvPacket) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{0} } func (m *MsgRecvPacket) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgRecvPacket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgRecvPacket.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgRecvPacket) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgRecvPacket.Merge(m, src) } func (m *MsgRecvPacket) XXX_Size() int { return m.Size() } func (m *MsgRecvPacket) XXX_DiscardUnknown() { xxx_messageInfo_MsgRecvPacket.DiscardUnknown(m) } var xxx_messageInfo_MsgRecvPacket proto.InternalMessageInfo // MsgRecvPacketResponse defines the Msg/RecvPacket response type. type MsgRecvPacketResponse struct { } func (m *MsgRecvPacketResponse) Reset() { *m = MsgRecvPacketResponse{} } func (m *MsgRecvPacketResponse) String() string { return proto.CompactTextString(m) } func (*MsgRecvPacketResponse) ProtoMessage() {} func (*MsgRecvPacketResponse) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{1} } func (m *MsgRecvPacketResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgRecvPacketResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgRecvPacketResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgRecvPacketResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgRecvPacketResponse.Merge(m, src) } func (m *MsgRecvPacketResponse) XXX_Size() int { return m.Size() } func (m *MsgRecvPacketResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgRecvPacketResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgRecvPacketResponse proto.InternalMessageInfo // MsgAcknowledgement receives incoming TIBC acknowledgement type MsgAcknowledgement struct { Packet Packet `protobuf:"bytes,1,opt,name=packet,proto3" json:"packet"` Acknowledgement []byte `protobuf:"bytes,2,opt,name=acknowledgement,proto3" json:"acknowledgement,omitempty"` ProofAcked []byte `protobuf:"bytes,3,opt,name=proof_acked,json=proofAcked,proto3" json:"proof_acked,omitempty" yaml:"proof_acked"` ProofHeight types.Height `protobuf:"bytes,4,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height" yaml:"proof_height"` Signer string `protobuf:"bytes,5,opt,name=signer,proto3" json:"signer,omitempty"` } func (m *MsgAcknowledgement) Reset() { *m = MsgAcknowledgement{} } func (m *MsgAcknowledgement) String() string { return proto.CompactTextString(m) } func (*MsgAcknowledgement) ProtoMessage() {} func (*MsgAcknowledgement) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{2} } func (m *MsgAcknowledgement) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgAcknowledgement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgAcknowledgement.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgAcknowledgement) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgAcknowledgement.Merge(m, src) } func (m *MsgAcknowledgement) XXX_Size() int { return m.Size() } func (m *MsgAcknowledgement) XXX_DiscardUnknown() { xxx_messageInfo_MsgAcknowledgement.DiscardUnknown(m) } var xxx_messageInfo_MsgAcknowledgement proto.InternalMessageInfo // MsgAcknowledgementResponse defines the Msg/Acknowledgement response type. type MsgAcknowledgementResponse struct { } func (m *MsgAcknowledgementResponse) Reset() { *m = MsgAcknowledgementResponse{} } func (m *MsgAcknowledgementResponse) String() string { return proto.CompactTextString(m) } func (*MsgAcknowledgementResponse) ProtoMessage() {} func (*MsgAcknowledgementResponse) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{3} } func (m *MsgAcknowledgementResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgAcknowledgementResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgAcknowledgementResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgAcknowledgementResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgAcknowledgementResponse.Merge(m, src) } func (m *MsgAcknowledgementResponse) XXX_Size() int { return m.Size() } func (m *MsgAcknowledgementResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgAcknowledgementResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgAcknowledgementResponse proto.InternalMessageInfo // MsgRecvPacket receives incoming TIBC packet type MsgCleanPacket struct { CleanPacket CleanPacket `protobuf:"bytes,1,opt,name=clean_packet,json=cleanPacket,proto3" json:"clean_packet"` Signer string `protobuf:"bytes,2,opt,name=signer,proto3" json:"signer,omitempty"` } func (m *MsgCleanPacket) Reset() { *m = MsgCleanPacket{} } func (m *MsgCleanPacket) String() string { return proto.CompactTextString(m) } func (*MsgCleanPacket) ProtoMessage() {} func (*MsgCleanPacket) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{4} } func (m *MsgCleanPacket) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgCleanPacket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCleanPacket.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgCleanPacket) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCleanPacket.Merge(m, src) } func (m *MsgCleanPacket) XXX_Size() int { return m.Size() } func (m *MsgCleanPacket) XXX_DiscardUnknown() { xxx_messageInfo_MsgCleanPacket.DiscardUnknown(m) } var xxx_messageInfo_MsgCleanPacket proto.InternalMessageInfo // MsgRecvPacketResponse defines the Msg/RecvPacket response type. type MsgCleanPacketResponse struct { } func (m *MsgCleanPacketResponse) Reset() { *m = MsgCleanPacketResponse{} } func (m *MsgCleanPacketResponse) String() string { return proto.CompactTextString(m) } func (*MsgCleanPacketResponse) ProtoMessage() {} func (*MsgCleanPacketResponse) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{5} } func (m *MsgCleanPacketResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgCleanPacketResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCleanPacketResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgCleanPacketResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCleanPacketResponse.Merge(m, src) } func (m *MsgCleanPacketResponse) XXX_Size() int { return m.Size() } func (m *MsgCleanPacketResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgCleanPacketResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgCleanPacketResponse proto.InternalMessageInfo // MsgRecvPacket receives incoming TIBC packet type MsgRecvCleanPacket struct { CleanPacket CleanPacket `protobuf:"bytes,1,opt,name=clean_packet,json=cleanPacket,proto3" json:"clean_packet"` ProofCommitment []byte `protobuf:"bytes,2,opt,name=proof_commitment,json=proofCommitment,proto3" json:"proof_commitment,omitempty" yaml:"proof_commitment"` ProofHeight types.Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height" yaml:"proof_height"` Signer string `protobuf:"bytes,4,opt,name=signer,proto3" json:"signer,omitempty"` } func (m *MsgRecvCleanPacket) Reset() { *m = MsgRecvCleanPacket{} } func (m *MsgRecvCleanPacket) String() string { return proto.CompactTextString(m) } func (*MsgRecvCleanPacket) ProtoMessage() {} func (*MsgRecvCleanPacket) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{6} } func (m *MsgRecvCleanPacket) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgRecvCleanPacket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgRecvCleanPacket.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgRecvCleanPacket) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgRecvCleanPacket.Merge(m, src) } func (m *MsgRecvCleanPacket) XXX_Size() int { return m.Size() } func (m *MsgRecvCleanPacket) XXX_DiscardUnknown() { xxx_messageInfo_MsgRecvCleanPacket.DiscardUnknown(m) } var xxx_messageInfo_MsgRecvCleanPacket proto.InternalMessageInfo // MsgRecvPacketResponse defines the Msg/RecvPacket response type. type MsgRecvCleanPacketResponse struct { } func (m *MsgRecvCleanPacketResponse) Reset() { *m = MsgRecvCleanPacketResponse{} } func (m *MsgRecvCleanPacketResponse) String() string { return proto.CompactTextString(m) } func (*MsgRecvCleanPacketResponse) ProtoMessage() {} func (*MsgRecvCleanPacketResponse) Descriptor() ([]byte, []int) { return fileDescriptor_1fd46e9a6c4c150c, []int{7} } func (m *MsgRecvCleanPacketResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MsgRecvCleanPacketResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgRecvCleanPacketResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MsgRecvCleanPacketResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgRecvCleanPacketResponse.Merge(m, src) } func (m *MsgRecvCleanPacketResponse) XXX_Size() int { return m.Size() } func (m *MsgRecvCleanPacketResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgRecvCleanPacketResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgRecvCleanPacketResponse proto.InternalMessageInfo func init() { proto.RegisterType((*MsgRecvPacket)(nil), "tibc.core.packet.v1.MsgRecvPacket") proto.RegisterType((*MsgRecvPacketResponse)(nil), "tibc.core.packet.v1.MsgRecvPacketResponse") proto.RegisterType((*MsgAcknowledgement)(nil), "tibc.core.packet.v1.MsgAcknowledgement") proto.RegisterType((*MsgAcknowledgementResponse)(nil), "tibc.core.packet.v1.MsgAcknowledgementResponse") proto.RegisterType((*MsgCleanPacket)(nil), "tibc.core.packet.v1.MsgCleanPacket") proto.RegisterType((*MsgCleanPacketResponse)(nil), "tibc.core.packet.v1.MsgCleanPacketResponse") proto.RegisterType((*MsgRecvCleanPacket)(nil), "tibc.core.packet.v1.MsgRecvCleanPacket") proto.RegisterType((*MsgRecvCleanPacketResponse)(nil), "tibc.core.packet.v1.MsgRecvCleanPacketResponse") } func init() { proto.RegisterFile("tibc/core/packet/v1/tx.proto", fileDescriptor_1fd46e9a6c4c150c) } var fileDescriptor_1fd46e9a6c4c150c = []byte{ // 586 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x95, 0xcf, 0x8f, 0xd2, 0x40, 0x14, 0xc7, 0x5b, 0x16, 0x89, 0x3e, 0x50, 0x4c, 0x57, 0x59, 0x52, 0x36, 0x2d, 0xa9, 0x87, 0x25, 0x9a, 0xed, 0xc8, 0x6a, 0x62, 0xdc, 0x83, 0xc9, 0xb2, 0x89, 0xd1, 0x03, 0x89, 0xe9, 0xc9, 0xa8, 0x09, 0x29, 0xc3, 0x38, 0x54, 0x68, 0x87, 0xd0, 0x2e, 0xba, 0x07, 0xef, 0x1e, 0xf5, 0x1f, 0x30, 0x7b, 0xf2, 0xee, 0x7f, 0xb1, 0xc7, 0x3d, 0x7a, 0x22, 0x06, 0x2e, 0x9e, 0xf9, 0x0b, 0x4c, 0x67, 0x0a, 0x94, 0x02, 0x4a, 0x62, 0xf6, 0xe2, 0xad, 0x6f, 0xde, 0xf7, 0xfd, 0x98, 0xcf, 0xbc, 0xe9, 0xc0, 0x6e, 0xe0, 0x34, 0x31, 0xc2, 0xac, 0x4f, 0x50, 0xcf, 0xc6, 0x1d, 0x12, 0xa0, 0x41, 0x15, 0x05, 0x1f, 0xcc, 0x5e, 0x9f, 0x05, 0x4c, 0xd9, 0x0e, 0xbd, 0x66, 0xe8, 0x35, 0x85, 0xd7, 0x1c, 0x54, 0xd5, 0x5b, 0x94, 0x51, 0xc6, 0xfd, 0x28, 0xfc, 0x12, 0x52, 0xb5, 0x3c, 0x4f, 0x84, 0xbb, 0x0e, 0xf1, 0x78, 0x22, 0xf1, 0xb5, 0xac, 0x98, 0x97, 0x8a, 0xd2, 0x72, 0x85, 0xf1, 0x25, 0x05, 0xd7, 0xeb, 0x3e, 0xb5, 0x08, 0x1e, 0xbc, 0xe0, 0xeb, 0xca, 0x63, 0xc8, 0x08, 0x45, 0x51, 0x2e, 0xcb, 0x95, 0xec, 0x41, 0xc9, 0x5c, 0xd1, 0x91, 0x29, 0xc4, 0xb5, 0xf4, 0xf9, 0x50, 0x97, 0xac, 0x28, 0x40, 0x79, 0x0a, 0x37, 0x7b, 0x7d, 0xc6, 0xde, 0x36, 0x30, 0x73, 0x5d, 0x27, 0x70, 0x89, 0x17, 0x14, 0x53, 0x65, 0xb9, 0x92, 0xab, 0x95, 0x26, 0x43, 0x7d, 0xe7, 0xd4, 0x76, 0xbb, 0x87, 0x46, 0x52, 0x61, 0x58, 0x79, 0xbe, 0x74, 0x3c, 0x5b, 0x51, 0x5e, 0x43, 0x4e, 0xa8, 0xda, 0xc4, 0xa1, 0xed, 0xa0, 0xb8, 0xb5, 0xd4, 0x48, 0xb4, 0xcb, 0x41, 0xd5, 0x7c, 0xc6, 0x25, 0xb5, 0x52, 0xd8, 0xc8, 0x64, 0xa8, 0x6f, 0xc7, 0x8b, 0x88, 0x70, 0xc3, 0xca, 0x72, 0x53, 0x28, 0x95, 0x02, 0x64, 0x7c, 0x87, 0x7a, 0xa4, 0x5f, 0x4c, 0x97, 0xe5, 0xca, 0x35, 0x2b, 0xb2, 0x0e, 0xaf, 0x7e, 0x3a, 0xd3, 0xa5, 0x5f, 0x67, 0xba, 0x64, 0xec, 0xc0, 0xed, 0x05, 0x24, 0x16, 0xf1, 0x7b, 0xcc, 0xf3, 0x89, 0xf1, 0x3d, 0x05, 0x4a, 0xdd, 0xa7, 0x47, 0xb8, 0xe3, 0xb1, 0xf7, 0x5d, 0xd2, 0xa2, 0x84, 0xb7, 0xfb, 0x0f, 0xc4, 0x2a, 0x90, 0xb7, 0x17, 0xb3, 0x09, 0x60, 0x56, 0x72, 0x59, 0x79, 0x04, 0x62, 0x17, 0x8d, 0x30, 0xb0, 0xc5, 0x91, 0xe4, 0x6a, 0x85, 0xc9, 0x50, 0x57, 0xe2, 0x3b, 0xe6, 0x4e, 0xc3, 0x02, 0x6e, 0x1d, 0x85, 0xc6, 0x12, 0xcc, 0xf4, 0xe5, 0xc0, 0xbc, 0xb2, 0x06, 0xe6, 0x2e, 0xa8, 0xcb, 0xc8, 0x66, 0x44, 0x3f, 0xc2, 0x8d, 0xba, 0x4f, 0x8f, 0xbb, 0xc4, 0xf6, 0xa2, 0xf1, 0x7b, 0x0e, 0x39, 0x1c, 0x9a, 0x8d, 0x05, 0xa4, 0xe5, 0x95, 0x48, 0x63, 0x71, 0x11, 0xd7, 0x2c, 0x8e, 0xa5, 0x9a, 0x37, 0x97, 0x5a, 0xd3, 0x5c, 0x11, 0x0a, 0x8b, 0xe5, 0x67, 0x8d, 0x7d, 0x13, 0x47, 0x1d, 0x0e, 0xc1, 0x25, 0x75, 0xf7, 0x9f, 0x5c, 0x16, 0x71, 0xbe, 0x09, 0x4e, 0x53, 0x8c, 0x07, 0x5f, 0xb7, 0x60, 0xab, 0xee, 0x53, 0xe5, 0x0d, 0x40, 0xec, 0x17, 0x63, 0xac, 0xe4, 0xb5, 0x70, 0xe7, 0xd4, 0xbb, 0x7f, 0xd7, 0x4c, 0xab, 0x28, 0x1d, 0xc8, 0x27, 0xef, 0xe4, 0xde, 0xba, 0xf0, 0x84, 0x50, 0x45, 0x1b, 0x0a, 0x67, 0xc5, 0x1a, 0x90, 0x8d, 0x4f, 0xc4, 0x9d, 0x75, 0xf1, 0x31, 0x91, 0x7a, 0x6f, 0x03, 0x51, 0x7c, 0x37, 0xc9, 0xb1, 0xdb, 0xfb, 0x13, 0x8c, 0x78, 0x21, 0xb4, 0xa1, 0x70, 0x5a, 0xac, 0xf6, 0xf2, 0x7c, 0xa4, 0xc9, 0x17, 0x23, 0x4d, 0xfe, 0x39, 0xd2, 0xe4, 0xcf, 0x63, 0x4d, 0xba, 0x18, 0x6b, 0xd2, 0x8f, 0xb1, 0x26, 0xbd, 0x7a, 0x42, 0x9d, 0xa0, 0x7d, 0xd2, 0x34, 0x31, 0x73, 0x51, 0xd3, 0xb1, 0xbd, 0x77, 0x0e, 0xb1, 0x1d, 0x14, 0xa6, 0xdf, 0xa7, 0x0c, 0xb9, 0xac, 0x75, 0xd2, 0x25, 0x3e, 0x9a, 0x3f, 0x30, 0xf7, 0x1f, 0xee, 0x47, 0x6f, 0x4c, 0x70, 0xda, 0x23, 0x7e, 0x33, 0xc3, 0x1f, 0x98, 0x07, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x4a, 0x8b, 0xa6, 0x9b, 0xef, 0x06, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // MsgClient is the client API for Msg service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type MsgClient interface { // RecvPacket defines a rpc handler method for MsgRecvPacket. RecvPacket(ctx context.Context, in *MsgRecvPacket, opts ...grpc.CallOption) (*MsgRecvPacketResponse, error) // Acknowledgement defines a rpc handler method for MsgAcknowledgement. Acknowledgement(ctx context.Context, in *MsgAcknowledgement, opts ...grpc.CallOption) (*MsgAcknowledgementResponse, error) // CleanPacket defines a rpc handler method for MsgCleanPacket. CleanPacket(ctx context.Context, in *MsgCleanPacket, opts ...grpc.CallOption) (*MsgCleanPacketResponse, error) // RecvCleanPacket defines a rpc handler method for MsgRecvCleanPacket. RecvCleanPacket(ctx context.Context, in *MsgRecvCleanPacket, opts ...grpc.CallOption) (*MsgRecvCleanPacketResponse, error) } type msgClient struct { cc grpc1.ClientConn } func NewMsgClient(cc grpc1.ClientConn) MsgClient { return &msgClient{cc} } func (c *msgClient) RecvPacket(ctx context.Context, in *MsgRecvPacket, opts ...grpc.CallOption) (*MsgRecvPacketResponse, error) { out := new(MsgRecvPacketResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Msg/RecvPacket", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) Acknowledgement(ctx context.Context, in *MsgAcknowledgement, opts ...grpc.CallOption) (*MsgAcknowledgementResponse, error) { out := new(MsgAcknowledgementResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Msg/Acknowledgement", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) CleanPacket(ctx context.Context, in *MsgCleanPacket, opts ...grpc.CallOption) (*MsgCleanPacketResponse, error) { out := new(MsgCleanPacketResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Msg/CleanPacket", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *msgClient) RecvCleanPacket(ctx context.Context, in *MsgRecvCleanPacket, opts ...grpc.CallOption) (*MsgRecvCleanPacketResponse, error) { out := new(MsgRecvCleanPacketResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Msg/RecvCleanPacket", in, out, opts...) if err != nil { return nil, err } return out, nil } // MsgServer is the server API for Msg service. type MsgServer interface { // RecvPacket defines a rpc handler method for MsgRecvPacket. RecvPacket(context.Context, *MsgRecvPacket) (*MsgRecvPacketResponse, error) // Acknowledgement defines a rpc handler method for MsgAcknowledgement. Acknowledgement(context.Context, *MsgAcknowledgement) (*MsgAcknowledgementResponse, error) // CleanPacket defines a rpc handler method for MsgCleanPacket. CleanPacket(context.Context, *MsgCleanPacket) (*MsgCleanPacketResponse, error) // RecvCleanPacket defines a rpc handler method for MsgRecvCleanPacket. RecvCleanPacket(context.Context, *MsgRecvCleanPacket) (*MsgRecvCleanPacketResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. type UnimplementedMsgServer struct { } func (*UnimplementedMsgServer) RecvPacket(ctx context.Context, req *MsgRecvPacket) (*MsgRecvPacketResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RecvPacket not implemented") } func (*UnimplementedMsgServer) Acknowledgement(ctx context.Context, req *MsgAcknowledgement) (*MsgAcknowledgementResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Acknowledgement not implemented") } func (*UnimplementedMsgServer) CleanPacket(ctx context.Context, req *MsgCleanPacket) (*MsgCleanPacketResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CleanPacket not implemented") } func (*UnimplementedMsgServer) RecvCleanPacket(ctx context.Context, req *MsgRecvCleanPacket) (*MsgRecvCleanPacketResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RecvCleanPacket not implemented") } func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) } func _Msg_RecvPacket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgRecvPacket) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).RecvPacket(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Msg/RecvPacket", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).RecvPacket(ctx, req.(*MsgRecvPacket)) } return interceptor(ctx, in, info, handler) } func _Msg_Acknowledgement_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgAcknowledgement) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).Acknowledgement(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Msg/Acknowledgement", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).Acknowledgement(ctx, req.(*MsgAcknowledgement)) } return interceptor(ctx, in, info, handler) } func _Msg_CleanPacket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgCleanPacket) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).CleanPacket(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Msg/CleanPacket", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).CleanPacket(ctx, req.(*MsgCleanPacket)) } return interceptor(ctx, in, info, handler) } func _Msg_RecvCleanPacket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgRecvCleanPacket) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MsgServer).RecvCleanPacket(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Msg/RecvCleanPacket", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MsgServer).RecvCleanPacket(ctx, req.(*MsgRecvCleanPacket)) } return interceptor(ctx, in, info, handler) } var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "tibc.core.packet.v1.Msg", HandlerType: (*MsgServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "RecvPacket", Handler: _Msg_RecvPacket_Handler, }, { MethodName: "Acknowledgement", Handler: _Msg_Acknowledgement_Handler, }, { MethodName: "CleanPacket", Handler: _Msg_CleanPacket_Handler, }, { MethodName: "RecvCleanPacket", Handler: _Msg_RecvCleanPacket_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "tibc/core/packet/v1/tx.proto", } func (m *MsgRecvPacket) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgRecvPacket) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgRecvPacket) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Signer) > 0 { i -= len(m.Signer) copy(dAtA[i:], m.Signer) i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) i-- dAtA[i] = 0x22 } { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.ProofCommitment) > 0 { i -= len(m.ProofCommitment) copy(dAtA[i:], m.ProofCommitment) i = encodeVarintTx(dAtA, i, uint64(len(m.ProofCommitment))) i-- dAtA[i] = 0x12 } { size, err := m.Packet.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *MsgRecvPacketResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgRecvPacketResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgRecvPacketResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgAcknowledgement) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgAcknowledgement) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgAcknowledgement) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Signer) > 0 { i -= len(m.Signer) copy(dAtA[i:], m.Signer) i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) i-- dAtA[i] = 0x2a } { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 if len(m.ProofAcked) > 0 { i -= len(m.ProofAcked) copy(dAtA[i:], m.ProofAcked) i = encodeVarintTx(dAtA, i, uint64(len(m.ProofAcked))) i-- dAtA[i] = 0x1a } if len(m.Acknowledgement) > 0 { i -= len(m.Acknowledgement) copy(dAtA[i:], m.Acknowledgement) i = encodeVarintTx(dAtA, i, uint64(len(m.Acknowledgement))) i-- dAtA[i] = 0x12 } { size, err := m.Packet.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *MsgAcknowledgementResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgAcknowledgementResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgAcknowledgementResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgCleanPacket) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgCleanPacket) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgCleanPacket) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Signer) > 0 { i -= len(m.Signer) copy(dAtA[i:], m.Signer) i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) i-- dAtA[i] = 0x12 } { size, err := m.CleanPacket.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *MsgCleanPacketResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgCleanPacketResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgCleanPacketResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *MsgRecvCleanPacket) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgRecvCleanPacket) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgRecvCleanPacket) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Signer) > 0 { i -= len(m.Signer) copy(dAtA[i:], m.Signer) i = encodeVarintTx(dAtA, i, uint64(len(m.Signer))) i-- dAtA[i] = 0x22 } { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.ProofCommitment) > 0 { i -= len(m.ProofCommitment) copy(dAtA[i:], m.ProofCommitment) i = encodeVarintTx(dAtA, i, uint64(len(m.ProofCommitment))) i-- dAtA[i] = 0x12 } { size, err := m.CleanPacket.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func (m *MsgRecvCleanPacketResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MsgRecvCleanPacketResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MsgRecvCleanPacketResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func encodeVarintTx(dAtA []byte, offset int, v uint64) int { offset -= sovTx(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *MsgRecvPacket) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.Packet.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.ProofCommitment) if l > 0 { n += 1 + l + sovTx(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.Signer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } return n } func (m *MsgRecvPacketResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgAcknowledgement) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.Packet.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.Acknowledgement) if l > 0 { n += 1 + l + sovTx(uint64(l)) } l = len(m.ProofAcked) if l > 0 { n += 1 + l + sovTx(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.Signer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } return n } func (m *MsgAcknowledgementResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgCleanPacket) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.CleanPacket.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.Signer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } return n } func (m *MsgCleanPacketResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *MsgRecvCleanPacket) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.CleanPacket.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.ProofCommitment) if l > 0 { n += 1 + l + sovTx(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovTx(uint64(l)) l = len(m.Signer) if l > 0 { n += 1 + l + sovTx(uint64(l)) } return n } func (m *MsgRecvCleanPacketResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func sovTx(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozTx(x uint64) (n int) { return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *MsgRecvPacket) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgRecvPacket: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgRecvPacket: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Packet", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Packet.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofCommitment", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.ProofCommitment = append(m.ProofCommitment[:0], dAtA[iNdEx:postIndex]...) if m.ProofCommitment == nil { m.ProofCommitment = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Signer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgRecvPacketResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgRecvPacketResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgRecvPacketResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgAcknowledgement) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgAcknowledgement: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgAcknowledgement: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Packet", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Packet.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Acknowledgement", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Acknowledgement = append(m.Acknowledgement[:0], dAtA[iNdEx:postIndex]...) if m.Acknowledgement == nil { m.Acknowledgement = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofAcked", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.ProofAcked = append(m.ProofAcked[:0], dAtA[iNdEx:postIndex]...) if m.ProofAcked == nil { m.ProofAcked = []byte{} } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Signer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgAcknowledgementResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgAcknowledgementResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgAcknowledgementResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgCleanPacket) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgCleanPacket: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgCleanPacket: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CleanPacket", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.CleanPacket.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Signer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgCleanPacketResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgCleanPacketResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgCleanPacketResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgRecvCleanPacket) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgRecvCleanPacket: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgRecvCleanPacket: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CleanPacket", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.CleanPacket.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofCommitment", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.ProofCommitment = append(m.ProofCommitment[:0], dAtA[iNdEx:postIndex]...) if m.ProofCommitment == nil { m.ProofCommitment = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Signer", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTx } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } m.Signer = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MsgRecvCleanPacketResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MsgRecvCleanPacketResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MsgRecvCleanPacketResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipTx(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTx } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthTx } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupTx } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthTx } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/types/codec.go<|end_filename|> package types import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" commitmenttypes "github.com/bianjieai/tibc-go/modules/tibc/core/23-commitment/types" routingtypes "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ibctmtypes "github.com/bianjieai/tibc-go/modules/tibc/light-clients/07-tendermint/types" bsctypes "github.com/bianjieai/tibc-go/modules/tibc/light-clients/08-bsc/types" ethtypes "github.com/bianjieai/tibc-go/modules/tibc/light-clients/09-eth/types" ) // RegisterInterfaces registers x/ibc interfaces into protobuf Any. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { clienttypes.RegisterInterfaces(registry) packettypes.RegisterInterfaces(registry) routingtypes.RegisterInterfaces(registry) ibctmtypes.RegisterInterfaces(registry) bsctypes.RegisterInterfaces(registry) ethtypes.RegisterInterfaces(registry) commitmenttypes.RegisterInterfaces(registry) } <|start_filename|>modules/tibc/light-clients/08-bsc/module.go<|end_filename|> package bsc import ( "github.com/bianjieai/tibc-go/modules/tibc/light-clients/08-bsc/types" ) // Name returns the TIBC bsc client name func Name() string { return types.SubModuleName } <|start_filename|>modules/tibc/core/04-packet/types/query.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/packet/v1/query.proto package types import ( context "context" fmt "fmt" types "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" query "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // QueryPacketCommitmentRequest is the request type for the // QueryPacketCommitment RPC method type QueryPacketCommitmentRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // packet sequence Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` } func (m *QueryPacketCommitmentRequest) Reset() { *m = QueryPacketCommitmentRequest{} } func (m *QueryPacketCommitmentRequest) String() string { return proto.CompactTextString(m) } func (*QueryPacketCommitmentRequest) ProtoMessage() {} func (*QueryPacketCommitmentRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{0} } func (m *QueryPacketCommitmentRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketCommitmentRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketCommitmentRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketCommitmentRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketCommitmentRequest.Merge(m, src) } func (m *QueryPacketCommitmentRequest) XXX_Size() int { return m.Size() } func (m *QueryPacketCommitmentRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketCommitmentRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketCommitmentRequest proto.InternalMessageInfo func (m *QueryPacketCommitmentRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryPacketCommitmentRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryPacketCommitmentRequest) GetSequence() uint64 { if m != nil { return m.Sequence } return 0 } // QueryPacketCommitmentResponse defines the client query response for a packet // which also includes a proof and the height from which the proof was // retrieved type QueryPacketCommitmentResponse struct { // packet associated with the request fields Commitment []byte `protobuf:"bytes,1,opt,name=commitment,proto3" json:"commitment,omitempty"` // merkle proof of existence Proof []byte `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` // height at which the proof was retrieved ProofHeight types.Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height"` } func (m *QueryPacketCommitmentResponse) Reset() { *m = QueryPacketCommitmentResponse{} } func (m *QueryPacketCommitmentResponse) String() string { return proto.CompactTextString(m) } func (*QueryPacketCommitmentResponse) ProtoMessage() {} func (*QueryPacketCommitmentResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{1} } func (m *QueryPacketCommitmentResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketCommitmentResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketCommitmentResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketCommitmentResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketCommitmentResponse.Merge(m, src) } func (m *QueryPacketCommitmentResponse) XXX_Size() int { return m.Size() } func (m *QueryPacketCommitmentResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketCommitmentResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketCommitmentResponse proto.InternalMessageInfo func (m *QueryPacketCommitmentResponse) GetCommitment() []byte { if m != nil { return m.Commitment } return nil } func (m *QueryPacketCommitmentResponse) GetProof() []byte { if m != nil { return m.Proof } return nil } func (m *QueryPacketCommitmentResponse) GetProofHeight() types.Height { if m != nil { return m.ProofHeight } return types.Height{} } // QueryPacketCommitmentsRequest is the request type for the // Query/QueryPacketCommitments RPC method type QueryPacketCommitmentsRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // pagination request Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *QueryPacketCommitmentsRequest) Reset() { *m = QueryPacketCommitmentsRequest{} } func (m *QueryPacketCommitmentsRequest) String() string { return proto.CompactTextString(m) } func (*QueryPacketCommitmentsRequest) ProtoMessage() {} func (*QueryPacketCommitmentsRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{2} } func (m *QueryPacketCommitmentsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketCommitmentsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketCommitmentsRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketCommitmentsRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketCommitmentsRequest.Merge(m, src) } func (m *QueryPacketCommitmentsRequest) XXX_Size() int { return m.Size() } func (m *QueryPacketCommitmentsRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketCommitmentsRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketCommitmentsRequest proto.InternalMessageInfo func (m *QueryPacketCommitmentsRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryPacketCommitmentsRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryPacketCommitmentsRequest) GetPagination() *query.PageRequest { if m != nil { return m.Pagination } return nil } // QueryPacketCommitmentsResponse is the request type for the // Query/QueryPacketCommitments RPC method type QueryPacketCommitmentsResponse struct { Commitments []*PacketState `protobuf:"bytes,1,rep,name=commitments,proto3" json:"commitments,omitempty"` // pagination response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` // query block height Height types.Height `protobuf:"bytes,3,opt,name=height,proto3" json:"height"` } func (m *QueryPacketCommitmentsResponse) Reset() { *m = QueryPacketCommitmentsResponse{} } func (m *QueryPacketCommitmentsResponse) String() string { return proto.CompactTextString(m) } func (*QueryPacketCommitmentsResponse) ProtoMessage() {} func (*QueryPacketCommitmentsResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{3} } func (m *QueryPacketCommitmentsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketCommitmentsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketCommitmentsResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketCommitmentsResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketCommitmentsResponse.Merge(m, src) } func (m *QueryPacketCommitmentsResponse) XXX_Size() int { return m.Size() } func (m *QueryPacketCommitmentsResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketCommitmentsResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketCommitmentsResponse proto.InternalMessageInfo func (m *QueryPacketCommitmentsResponse) GetCommitments() []*PacketState { if m != nil { return m.Commitments } return nil } func (m *QueryPacketCommitmentsResponse) GetPagination() *query.PageResponse { if m != nil { return m.Pagination } return nil } func (m *QueryPacketCommitmentsResponse) GetHeight() types.Height { if m != nil { return m.Height } return types.Height{} } // QueryPacketReceiptRequest is the request type for the // Query/PacketReceipt RPC method type QueryPacketReceiptRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // packet sequence Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` } func (m *QueryPacketReceiptRequest) Reset() { *m = QueryPacketReceiptRequest{} } func (m *QueryPacketReceiptRequest) String() string { return proto.CompactTextString(m) } func (*QueryPacketReceiptRequest) ProtoMessage() {} func (*QueryPacketReceiptRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{4} } func (m *QueryPacketReceiptRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketReceiptRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketReceiptRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketReceiptRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketReceiptRequest.Merge(m, src) } func (m *QueryPacketReceiptRequest) XXX_Size() int { return m.Size() } func (m *QueryPacketReceiptRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketReceiptRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketReceiptRequest proto.InternalMessageInfo func (m *QueryPacketReceiptRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryPacketReceiptRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryPacketReceiptRequest) GetSequence() uint64 { if m != nil { return m.Sequence } return 0 } // QueryPacketReceiptResponse defines the client query response for a packet receipt // which also includes a proof, and the height from which the proof was // retrieved type QueryPacketReceiptResponse struct { // success flag for if receipt exists Received bool `protobuf:"varint,2,opt,name=received,proto3" json:"received,omitempty"` // merkle proof of existence Proof []byte `protobuf:"bytes,3,opt,name=proof,proto3" json:"proof,omitempty"` // height at which the proof was retrieved ProofHeight types.Height `protobuf:"bytes,4,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height"` } func (m *QueryPacketReceiptResponse) Reset() { *m = QueryPacketReceiptResponse{} } func (m *QueryPacketReceiptResponse) String() string { return proto.CompactTextString(m) } func (*QueryPacketReceiptResponse) ProtoMessage() {} func (*QueryPacketReceiptResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{5} } func (m *QueryPacketReceiptResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketReceiptResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketReceiptResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketReceiptResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketReceiptResponse.Merge(m, src) } func (m *QueryPacketReceiptResponse) XXX_Size() int { return m.Size() } func (m *QueryPacketReceiptResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketReceiptResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketReceiptResponse proto.InternalMessageInfo func (m *QueryPacketReceiptResponse) GetReceived() bool { if m != nil { return m.Received } return false } func (m *QueryPacketReceiptResponse) GetProof() []byte { if m != nil { return m.Proof } return nil } func (m *QueryPacketReceiptResponse) GetProofHeight() types.Height { if m != nil { return m.ProofHeight } return types.Height{} } // QueryPacketAcknowledgementRequest is the request type for the // Query/PacketAcknowledgement RPC method type QueryPacketAcknowledgementRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // packet sequence Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` } func (m *QueryPacketAcknowledgementRequest) Reset() { *m = QueryPacketAcknowledgementRequest{} } func (m *QueryPacketAcknowledgementRequest) String() string { return proto.CompactTextString(m) } func (*QueryPacketAcknowledgementRequest) ProtoMessage() {} func (*QueryPacketAcknowledgementRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{6} } func (m *QueryPacketAcknowledgementRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketAcknowledgementRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketAcknowledgementRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketAcknowledgementRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketAcknowledgementRequest.Merge(m, src) } func (m *QueryPacketAcknowledgementRequest) XXX_Size() int { return m.Size() } func (m *QueryPacketAcknowledgementRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketAcknowledgementRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketAcknowledgementRequest proto.InternalMessageInfo func (m *QueryPacketAcknowledgementRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryPacketAcknowledgementRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryPacketAcknowledgementRequest) GetSequence() uint64 { if m != nil { return m.Sequence } return 0 } // QueryPacketAcknowledgementResponse defines the client query response for a // packet which also includes a proof and the height from which the // proof was retrieved type QueryPacketAcknowledgementResponse struct { // packet associated with the request fields Acknowledgement []byte `protobuf:"bytes,1,opt,name=acknowledgement,proto3" json:"acknowledgement,omitempty"` // merkle proof of existence Proof []byte `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` // height at which the proof was retrieved ProofHeight types.Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height"` } func (m *QueryPacketAcknowledgementResponse) Reset() { *m = QueryPacketAcknowledgementResponse{} } func (m *QueryPacketAcknowledgementResponse) String() string { return proto.CompactTextString(m) } func (*QueryPacketAcknowledgementResponse) ProtoMessage() {} func (*QueryPacketAcknowledgementResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{7} } func (m *QueryPacketAcknowledgementResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketAcknowledgementResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketAcknowledgementResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketAcknowledgementResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketAcknowledgementResponse.Merge(m, src) } func (m *QueryPacketAcknowledgementResponse) XXX_Size() int { return m.Size() } func (m *QueryPacketAcknowledgementResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketAcknowledgementResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketAcknowledgementResponse proto.InternalMessageInfo func (m *QueryPacketAcknowledgementResponse) GetAcknowledgement() []byte { if m != nil { return m.Acknowledgement } return nil } func (m *QueryPacketAcknowledgementResponse) GetProof() []byte { if m != nil { return m.Proof } return nil } func (m *QueryPacketAcknowledgementResponse) GetProofHeight() types.Height { if m != nil { return m.ProofHeight } return types.Height{} } // QueryPacketAcknowledgementsRequest is the request type for the // Query/QueryPacketCommitments RPC method type QueryPacketAcknowledgementsRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // pagination request Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` } func (m *QueryPacketAcknowledgementsRequest) Reset() { *m = QueryPacketAcknowledgementsRequest{} } func (m *QueryPacketAcknowledgementsRequest) String() string { return proto.CompactTextString(m) } func (*QueryPacketAcknowledgementsRequest) ProtoMessage() {} func (*QueryPacketAcknowledgementsRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{8} } func (m *QueryPacketAcknowledgementsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketAcknowledgementsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketAcknowledgementsRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketAcknowledgementsRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketAcknowledgementsRequest.Merge(m, src) } func (m *QueryPacketAcknowledgementsRequest) XXX_Size() int { return m.Size() } func (m *QueryPacketAcknowledgementsRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketAcknowledgementsRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketAcknowledgementsRequest proto.InternalMessageInfo func (m *QueryPacketAcknowledgementsRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryPacketAcknowledgementsRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryPacketAcknowledgementsRequest) GetPagination() *query.PageRequest { if m != nil { return m.Pagination } return nil } // QueryPacketAcknowledgemetsResponse is the request type for the // Query/QueryPacketAcknowledgements RPC method type QueryPacketAcknowledgementsResponse struct { Acknowledgements []*PacketState `protobuf:"bytes,1,rep,name=acknowledgements,proto3" json:"acknowledgements,omitempty"` // pagination response Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` // query block height Height types.Height `protobuf:"bytes,3,opt,name=height,proto3" json:"height"` } func (m *QueryPacketAcknowledgementsResponse) Reset() { *m = QueryPacketAcknowledgementsResponse{} } func (m *QueryPacketAcknowledgementsResponse) String() string { return proto.CompactTextString(m) } func (*QueryPacketAcknowledgementsResponse) ProtoMessage() {} func (*QueryPacketAcknowledgementsResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{9} } func (m *QueryPacketAcknowledgementsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryPacketAcknowledgementsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryPacketAcknowledgementsResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryPacketAcknowledgementsResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryPacketAcknowledgementsResponse.Merge(m, src) } func (m *QueryPacketAcknowledgementsResponse) XXX_Size() int { return m.Size() } func (m *QueryPacketAcknowledgementsResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryPacketAcknowledgementsResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryPacketAcknowledgementsResponse proto.InternalMessageInfo func (m *QueryPacketAcknowledgementsResponse) GetAcknowledgements() []*PacketState { if m != nil { return m.Acknowledgements } return nil } func (m *QueryPacketAcknowledgementsResponse) GetPagination() *query.PageResponse { if m != nil { return m.Pagination } return nil } func (m *QueryPacketAcknowledgementsResponse) GetHeight() types.Height { if m != nil { return m.Height } return types.Height{} } // QueryUnreceivedPacketsRequest is the request type for the // Query/UnreceivedPackets RPC method type QueryUnreceivedPacketsRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // list of packet sequences PacketCommitmentSequences []uint64 `protobuf:"varint,3,rep,packed,name=packet_commitment_sequences,json=packetCommitmentSequences,proto3" json:"packet_commitment_sequences,omitempty"` } func (m *QueryUnreceivedPacketsRequest) Reset() { *m = QueryUnreceivedPacketsRequest{} } func (m *QueryUnreceivedPacketsRequest) String() string { return proto.CompactTextString(m) } func (*QueryUnreceivedPacketsRequest) ProtoMessage() {} func (*QueryUnreceivedPacketsRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{10} } func (m *QueryUnreceivedPacketsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryUnreceivedPacketsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryUnreceivedPacketsRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryUnreceivedPacketsRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryUnreceivedPacketsRequest.Merge(m, src) } func (m *QueryUnreceivedPacketsRequest) XXX_Size() int { return m.Size() } func (m *QueryUnreceivedPacketsRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryUnreceivedPacketsRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryUnreceivedPacketsRequest proto.InternalMessageInfo func (m *QueryUnreceivedPacketsRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryUnreceivedPacketsRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryUnreceivedPacketsRequest) GetPacketCommitmentSequences() []uint64 { if m != nil { return m.PacketCommitmentSequences } return nil } // QueryUnreceivedPacketsResponse is the response type for the // Query/UnreceivedPacketCommitments RPC method type QueryUnreceivedPacketsResponse struct { // list of unreceived packet sequences Sequences []uint64 `protobuf:"varint,1,rep,packed,name=sequences,proto3" json:"sequences,omitempty"` // query block height Height types.Height `protobuf:"bytes,2,opt,name=height,proto3" json:"height"` } func (m *QueryUnreceivedPacketsResponse) Reset() { *m = QueryUnreceivedPacketsResponse{} } func (m *QueryUnreceivedPacketsResponse) String() string { return proto.CompactTextString(m) } func (*QueryUnreceivedPacketsResponse) ProtoMessage() {} func (*QueryUnreceivedPacketsResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{11} } func (m *QueryUnreceivedPacketsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryUnreceivedPacketsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryUnreceivedPacketsResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryUnreceivedPacketsResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryUnreceivedPacketsResponse.Merge(m, src) } func (m *QueryUnreceivedPacketsResponse) XXX_Size() int { return m.Size() } func (m *QueryUnreceivedPacketsResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryUnreceivedPacketsResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryUnreceivedPacketsResponse proto.InternalMessageInfo func (m *QueryUnreceivedPacketsResponse) GetSequences() []uint64 { if m != nil { return m.Sequences } return nil } func (m *QueryUnreceivedPacketsResponse) GetHeight() types.Height { if m != nil { return m.Height } return types.Height{} } // QueryUnreceivedAcks is the request type for the // Query/UnreceivedAcks RPC method type QueryUnreceivedAcksRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` // list of acknowledgement sequences PacketAckSequences []uint64 `protobuf:"varint,3,rep,packed,name=packet_ack_sequences,json=packetAckSequences,proto3" json:"packet_ack_sequences,omitempty"` } func (m *QueryUnreceivedAcksRequest) Reset() { *m = QueryUnreceivedAcksRequest{} } func (m *QueryUnreceivedAcksRequest) String() string { return proto.CompactTextString(m) } func (*QueryUnreceivedAcksRequest) ProtoMessage() {} func (*QueryUnreceivedAcksRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{12} } func (m *QueryUnreceivedAcksRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryUnreceivedAcksRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryUnreceivedAcksRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryUnreceivedAcksRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryUnreceivedAcksRequest.Merge(m, src) } func (m *QueryUnreceivedAcksRequest) XXX_Size() int { return m.Size() } func (m *QueryUnreceivedAcksRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryUnreceivedAcksRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryUnreceivedAcksRequest proto.InternalMessageInfo func (m *QueryUnreceivedAcksRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryUnreceivedAcksRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *QueryUnreceivedAcksRequest) GetPacketAckSequences() []uint64 { if m != nil { return m.PacketAckSequences } return nil } // QueryUnreceivedAcksResponse is the response type for the // Query/UnreceivedAcks RPC method type QueryUnreceivedAcksResponse struct { // list of unreceived acknowledgement sequences Sequences []uint64 `protobuf:"varint,1,rep,packed,name=sequences,proto3" json:"sequences,omitempty"` // query block height Height types.Height `protobuf:"bytes,2,opt,name=height,proto3" json:"height"` } func (m *QueryUnreceivedAcksResponse) Reset() { *m = QueryUnreceivedAcksResponse{} } func (m *QueryUnreceivedAcksResponse) String() string { return proto.CompactTextString(m) } func (*QueryUnreceivedAcksResponse) ProtoMessage() {} func (*QueryUnreceivedAcksResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{13} } func (m *QueryUnreceivedAcksResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryUnreceivedAcksResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryUnreceivedAcksResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryUnreceivedAcksResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryUnreceivedAcksResponse.Merge(m, src) } func (m *QueryUnreceivedAcksResponse) XXX_Size() int { return m.Size() } func (m *QueryUnreceivedAcksResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryUnreceivedAcksResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryUnreceivedAcksResponse proto.InternalMessageInfo func (m *QueryUnreceivedAcksResponse) GetSequences() []uint64 { if m != nil { return m.Sequences } return nil } func (m *QueryUnreceivedAcksResponse) GetHeight() types.Height { if m != nil { return m.Height } return types.Height{} } // QueryCleanPacketCommitmentRequest is the request type for the // QueryCleanPacketCommitment RPC method type QueryCleanPacketCommitmentRequest struct { // dest chain name DestChain string `protobuf:"bytes,1,opt,name=dest_chain,json=destChain,proto3" json:"dest_chain,omitempty"` // source chain name SourceChain string `protobuf:"bytes,2,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty"` } func (m *QueryCleanPacketCommitmentRequest) Reset() { *m = QueryCleanPacketCommitmentRequest{} } func (m *QueryCleanPacketCommitmentRequest) String() string { return proto.CompactTextString(m) } func (*QueryCleanPacketCommitmentRequest) ProtoMessage() {} func (*QueryCleanPacketCommitmentRequest) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{14} } func (m *QueryCleanPacketCommitmentRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryCleanPacketCommitmentRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryCleanPacketCommitmentRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryCleanPacketCommitmentRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryCleanPacketCommitmentRequest.Merge(m, src) } func (m *QueryCleanPacketCommitmentRequest) XXX_Size() int { return m.Size() } func (m *QueryCleanPacketCommitmentRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryCleanPacketCommitmentRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryCleanPacketCommitmentRequest proto.InternalMessageInfo func (m *QueryCleanPacketCommitmentRequest) GetDestChain() string { if m != nil { return m.DestChain } return "" } func (m *QueryCleanPacketCommitmentRequest) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } // QueryCleanPacketCommitmentResponse defines the client query response for a packet // which also includes a proof and the height from which the proof was // retrieved type QueryCleanPacketCommitmentResponse struct { // packet associated with the request fields Commitment []byte `protobuf:"bytes,1,opt,name=commitment,proto3" json:"commitment,omitempty"` // merkle proof of existence Proof []byte `protobuf:"bytes,2,opt,name=proof,proto3" json:"proof,omitempty"` // height at which the proof was retrieved ProofHeight types.Height `protobuf:"bytes,3,opt,name=proof_height,json=proofHeight,proto3" json:"proof_height"` } func (m *QueryCleanPacketCommitmentResponse) Reset() { *m = QueryCleanPacketCommitmentResponse{} } func (m *QueryCleanPacketCommitmentResponse) String() string { return proto.CompactTextString(m) } func (*QueryCleanPacketCommitmentResponse) ProtoMessage() {} func (*QueryCleanPacketCommitmentResponse) Descriptor() ([]byte, []int) { return fileDescriptor_281cd631706975e3, []int{15} } func (m *QueryCleanPacketCommitmentResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryCleanPacketCommitmentResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryCleanPacketCommitmentResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryCleanPacketCommitmentResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryCleanPacketCommitmentResponse.Merge(m, src) } func (m *QueryCleanPacketCommitmentResponse) XXX_Size() int { return m.Size() } func (m *QueryCleanPacketCommitmentResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryCleanPacketCommitmentResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryCleanPacketCommitmentResponse proto.InternalMessageInfo func (m *QueryCleanPacketCommitmentResponse) GetCommitment() []byte { if m != nil { return m.Commitment } return nil } func (m *QueryCleanPacketCommitmentResponse) GetProof() []byte { if m != nil { return m.Proof } return nil } func (m *QueryCleanPacketCommitmentResponse) GetProofHeight() types.Height { if m != nil { return m.ProofHeight } return types.Height{} } func init() { proto.RegisterType((*QueryPacketCommitmentRequest)(nil), "tibc.core.packet.v1.QueryPacketCommitmentRequest") proto.RegisterType((*QueryPacketCommitmentResponse)(nil), "tibc.core.packet.v1.QueryPacketCommitmentResponse") proto.RegisterType((*QueryPacketCommitmentsRequest)(nil), "tibc.core.packet.v1.QueryPacketCommitmentsRequest") proto.RegisterType((*QueryPacketCommitmentsResponse)(nil), "tibc.core.packet.v1.QueryPacketCommitmentsResponse") proto.RegisterType((*QueryPacketReceiptRequest)(nil), "tibc.core.packet.v1.QueryPacketReceiptRequest") proto.RegisterType((*QueryPacketReceiptResponse)(nil), "tibc.core.packet.v1.QueryPacketReceiptResponse") proto.RegisterType((*QueryPacketAcknowledgementRequest)(nil), "tibc.core.packet.v1.QueryPacketAcknowledgementRequest") proto.RegisterType((*QueryPacketAcknowledgementResponse)(nil), "tibc.core.packet.v1.QueryPacketAcknowledgementResponse") proto.RegisterType((*QueryPacketAcknowledgementsRequest)(nil), "tibc.core.packet.v1.QueryPacketAcknowledgementsRequest") proto.RegisterType((*QueryPacketAcknowledgementsResponse)(nil), "tibc.core.packet.v1.QueryPacketAcknowledgementsResponse") proto.RegisterType((*QueryUnreceivedPacketsRequest)(nil), "tibc.core.packet.v1.QueryUnreceivedPacketsRequest") proto.RegisterType((*QueryUnreceivedPacketsResponse)(nil), "tibc.core.packet.v1.QueryUnreceivedPacketsResponse") proto.RegisterType((*QueryUnreceivedAcksRequest)(nil), "tibc.core.packet.v1.QueryUnreceivedAcksRequest") proto.RegisterType((*QueryUnreceivedAcksResponse)(nil), "tibc.core.packet.v1.QueryUnreceivedAcksResponse") proto.RegisterType((*QueryCleanPacketCommitmentRequest)(nil), "tibc.core.packet.v1.QueryCleanPacketCommitmentRequest") proto.RegisterType((*QueryCleanPacketCommitmentResponse)(nil), "tibc.core.packet.v1.QueryCleanPacketCommitmentResponse") } func init() { proto.RegisterFile("tibc/core/packet/v1/query.proto", fileDescriptor_281cd631706975e3) } var fileDescriptor_281cd631706975e3 = []byte{ // 1042 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x58, 0xcf, 0x6f, 0x1b, 0x45, 0x14, 0xce, 0xd8, 0x69, 0x95, 0x3c, 0x07, 0xda, 0x0e, 0x29, 0x4a, 0x37, 0xa9, 0xeb, 0x2e, 0x12, 0x58, 0x48, 0xdd, 0x89, 0x53, 0xc4, 0x8f, 0x4b, 0xa5, 0x26, 0x08, 0x38, 0x70, 0x28, 0x5b, 0x21, 0x21, 0x2e, 0xd6, 0x7a, 0x3c, 0x5d, 0x6f, 0x6c, 0xef, 0x6c, 0x3d, 0x6b, 0xa3, 0xa8, 0xe4, 0x00, 0xb7, 0x4a, 0x1c, 0x2a, 0x05, 0x71, 0x01, 0x24, 0x38, 0xc2, 0x81, 0xbf, 0xa3, 0xc7, 0x4a, 0x5c, 0x38, 0x21, 0x94, 0xf4, 0xd0, 0x13, 0xe2, 0x06, 0x42, 0x1c, 0xd0, 0xce, 0x8c, 0xbd, 0xbb, 0xf1, 0x7a, 0x13, 0xa3, 0x38, 0xe4, 0xb6, 0x33, 0x7e, 0x6f, 0xde, 0xf7, 0x7d, 0xf3, 0xde, 0x9b, 0x27, 0xc3, 0xb5, 0xd0, 0x6b, 0x50, 0x42, 0x79, 0x8f, 0x91, 0xc0, 0xa1, 0x6d, 0x16, 0x92, 0x41, 0x8d, 0xdc, 0xef, 0xb3, 0xde, 0x8e, 0x15, 0xf4, 0x78, 0xc8, 0xf1, 0x0b, 0x91, 0x81, 0x15, 0x19, 0x58, 0xca, 0xc0, 0x1a, 0xd4, 0x8c, 0x4a, 0xec, 0x45, 0x3b, 0x1e, 0xf3, 0xa5, 0x97, 0xfa, 0x52, 0x6e, 0xc6, 0xab, 0x94, 0x8b, 0x2e, 0x17, 0xa4, 0xe1, 0x08, 0xa6, 0xce, 0x23, 0x83, 0x5a, 0x83, 0x85, 0x4e, 0x8d, 0x04, 0x8e, 0xeb, 0xf9, 0x4e, 0xe8, 0x71, 0x5f, 0xdb, 0x56, 0xb2, 0x30, 0xe8, 0x60, 0xca, 0x62, 0xcd, 0xe5, 0xdc, 0xed, 0x30, 0xe2, 0x04, 0x1e, 0x71, 0x7c, 0x9f, 0x87, 0xd2, 0x5d, 0xe8, 0x5f, 0x97, 0x5d, 0xee, 0x72, 0xf9, 0x49, 0xa2, 0x2f, 0xb5, 0x6b, 0x7e, 0x0a, 0x6b, 0x1f, 0x44, 0x71, 0xef, 0xc8, 0x83, 0xb6, 0x78, 0xb7, 0xeb, 0x85, 0x5d, 0xe6, 0x87, 0x36, 0xbb, 0xdf, 0x67, 0x22, 0xc4, 0x57, 0x01, 0x9a, 0x4c, 0x84, 0x75, 0xda, 0x72, 0x3c, 0x7f, 0x05, 0x55, 0x50, 0x75, 0xd1, 0x5e, 0x8c, 0x76, 0xb6, 0xa2, 0x0d, 0x7c, 0x1d, 0x96, 0x04, 0xef, 0xf7, 0x28, 0xd3, 0x06, 0x05, 0x69, 0x50, 0x52, 0x7b, 0xca, 0xc4, 0x80, 0x05, 0x11, 0x1d, 0xe6, 0x53, 0xb6, 0x52, 0xac, 0xa0, 0xea, 0xbc, 0x3d, 0x5a, 0x9b, 0x5f, 0x23, 0xb8, 0x3a, 0x21, 0xbc, 0x08, 0xb8, 0x2f, 0x18, 0x2e, 0x03, 0xd0, 0xd1, 0xae, 0x8c, 0xbf, 0x64, 0x27, 0x76, 0xf0, 0x32, 0x9c, 0x0b, 0x7a, 0x9c, 0xdf, 0x93, 0x91, 0x97, 0x6c, 0xb5, 0xc0, 0x6f, 0xc3, 0x92, 0xfc, 0xa8, 0xb7, 0x98, 0xe7, 0xb6, 0x42, 0x19, 0xb7, 0xb4, 0xb1, 0x6a, 0xc5, 0xb7, 0xa4, 0xaf, 0x61, 0x50, 0xb3, 0xde, 0x93, 0x26, 0x9b, 0xf3, 0x8f, 0x7f, 0xbd, 0x36, 0x67, 0x97, 0xa4, 0x9b, 0xda, 0x32, 0x7f, 0x98, 0x84, 0x4e, 0x9c, 0x9c, 0x3a, 0xef, 0x00, 0xc4, 0x37, 0xad, 0x71, 0xbe, 0x6c, 0xa9, 0xb4, 0xb0, 0xa2, 0xb4, 0xb0, 0x54, 0x9a, 0xe9, 0xb4, 0xb0, 0xee, 0x38, 0x2e, 0xd3, 0xd1, 0xed, 0x84, 0xa7, 0xf9, 0x0c, 0x41, 0x79, 0x12, 0x56, 0x2d, 0xe5, 0x26, 0x94, 0x62, 0xe1, 0xc4, 0x0a, 0xaa, 0x14, 0xab, 0xa5, 0x8d, 0x8a, 0x95, 0x91, 0xb9, 0x96, 0x3a, 0xe4, 0x6e, 0xe8, 0x84, 0xcc, 0x4e, 0x3a, 0xe1, 0x77, 0x53, 0x70, 0x0b, 0x12, 0xee, 0x2b, 0x47, 0xc2, 0x55, 0x00, 0x92, 0x78, 0xf1, 0x5b, 0x70, 0x7e, 0xda, 0xbb, 0xd1, 0x0e, 0xe6, 0x0e, 0x5c, 0x49, 0x30, 0xb5, 0x19, 0x65, 0x5e, 0x70, 0x4a, 0xf9, 0xfa, 0x25, 0x02, 0x23, 0x2b, 0xb6, 0x56, 0xd8, 0x80, 0x85, 0x5e, 0xb4, 0x35, 0x60, 0x4d, 0x79, 0xf2, 0x82, 0x3d, 0x5a, 0xc7, 0x89, 0x5a, 0xcc, 0x4b, 0xd4, 0xf9, 0xff, 0x94, 0xa8, 0x9f, 0x21, 0xb8, 0x9e, 0x80, 0x75, 0x9b, 0xb6, 0x7d, 0xfe, 0x49, 0x87, 0x35, 0x5d, 0x76, 0x7a, 0xa5, 0xfc, 0x23, 0x02, 0x33, 0x0f, 0x83, 0x96, 0xa8, 0x0a, 0x17, 0x9c, 0xf4, 0x4f, 0xba, 0xa8, 0x0f, 0x6f, 0xcf, 0xb4, 0xb2, 0x7f, 0xca, 0x05, 0x7b, 0x06, 0xcb, 0xfb, 0x4f, 0x04, 0x2f, 0xe5, 0x02, 0xd6, 0xf2, 0xbe, 0x0f, 0x17, 0x0f, 0xe9, 0x78, 0xfc, 0x42, 0x1f, 0xf3, 0x3c, 0x13, 0xd5, 0xfe, 0xfd, 0xb0, 0x09, 0x7f, 0xe8, 0x0f, 0x6b, 0x49, 0x81, 0x3e, 0xc1, 0x5b, 0xba, 0x05, 0xab, 0x4a, 0x92, 0x7a, 0xdc, 0xeb, 0xea, 0xc3, 0xcc, 0x16, 0x2b, 0xc5, 0x4a, 0xb1, 0x3a, 0x6f, 0x5f, 0x09, 0x0e, 0x75, 0xd6, 0xbb, 0x43, 0x03, 0x73, 0x47, 0xf7, 0xde, 0x0c, 0x88, 0xfa, 0x5e, 0xd6, 0x60, 0x31, 0x3e, 0x0f, 0xc9, 0xf3, 0xe2, 0x8d, 0x84, 0x3c, 0x85, 0x69, 0xe5, 0x79, 0x34, 0xec, 0x48, 0x71, 0xec, 0xdb, 0xb4, 0x7d, 0x82, 0xda, 0xac, 0xc3, 0xb2, 0xd6, 0xc6, 0xa1, 0xed, 0x31, 0x51, 0x70, 0x30, 0xcc, 0xc7, 0x58, 0x8d, 0x01, 0xac, 0x66, 0x22, 0x9a, 0xb5, 0x14, 0x4c, 0x37, 0xc1, 0xad, 0x0e, 0x73, 0xfc, 0x99, 0xcd, 0x33, 0xe6, 0x77, 0xc3, 0xde, 0x31, 0x21, 0xce, 0xff, 0x3f, 0xb8, 0x6c, 0xfc, 0x7e, 0x01, 0xce, 0x49, 0x88, 0xf8, 0x0f, 0x04, 0x17, 0x0f, 0x43, 0xc4, 0xb5, 0xcc, 0x56, 0x90, 0x37, 0x06, 0x1a, 0x1b, 0xd3, 0xb8, 0x28, 0x05, 0xcc, 0xfe, 0xe7, 0x3f, 0x3f, 0xdd, 0x2b, 0x70, 0xdc, 0x25, 0x19, 0x93, 0xab, 0x1a, 0x72, 0x93, 0x5a, 0x0b, 0xf2, 0x20, 0xb9, 0xdc, 0x25, 0xf1, 0x3d, 0x09, 0xf2, 0x20, 0x5e, 0xec, 0x92, 0xb1, 0x5a, 0x8d, 0x5c, 0x75, 0x06, 0xed, 0xe2, 0x67, 0x08, 0x2e, 0x8d, 0x0d, 0x41, 0x78, 0x0a, 0x02, 0xc3, 0xe2, 0x31, 0x6e, 0x4e, 0xe5, 0xa3, 0x59, 0x6f, 0x4b, 0xd6, 0x4d, 0xdc, 0x98, 0x3d, 0x6b, 0xfc, 0x14, 0xc1, 0x73, 0xa9, 0x49, 0x04, 0x5b, 0x47, 0x41, 0x4e, 0x8f, 0x4b, 0x06, 0x39, 0xb6, 0xbd, 0xa6, 0xd7, 0x93, 0xf4, 0x3a, 0x78, 0x7b, 0x46, 0xf4, 0x7a, 0x2a, 0x5e, 0xea, 0x46, 0xff, 0x42, 0x70, 0x39, 0xf3, 0xdd, 0xc3, 0xaf, 0x1f, 0x05, 0x3f, 0x7b, 0x14, 0x32, 0xde, 0x98, 0xda, 0x4f, 0xd3, 0xf7, 0x25, 0xfd, 0x16, 0xbe, 0x37, 0x23, 0xfa, 0x0e, 0x6d, 0xa7, 0xa8, 0xff, 0x83, 0xe0, 0xc5, 0xec, 0x27, 0x1f, 0x4f, 0xcb, 0x61, 0x94, 0xd6, 0x6f, 0x4e, 0xef, 0xa8, 0xd9, 0x73, 0xc9, 0xde, 0xc3, 0xee, 0xec, 0xd8, 0xa7, 0x39, 0x7e, 0x53, 0x80, 0x4b, 0x63, 0x8f, 0x6a, 0x5e, 0x2d, 0x4f, 0x1a, 0x12, 0xf2, 0x6a, 0x79, 0xe2, 0xab, 0x6d, 0x7e, 0x8b, 0x24, 0xe1, 0xaf, 0x10, 0xde, 0x43, 0xa7, 0xd1, 0xc4, 0x72, 0x86, 0x90, 0x5d, 0xd2, 0x1f, 0xc1, 0xac, 0x07, 0x5a, 0x88, 0x87, 0x05, 0x78, 0x3e, 0xfd, 0xca, 0x62, 0x72, 0x1c, 0x9e, 0x89, 0x09, 0xc1, 0x58, 0x3f, 0xbe, 0x83, 0x56, 0x65, 0x4f, 0xa9, 0xf2, 0x05, 0xc2, 0x0f, 0x4f, 0x53, 0x95, 0xd4, 0xf8, 0x91, 0x92, 0x23, 0x2a, 0x1a, 0xfc, 0x37, 0x82, 0xcb, 0x99, 0x2f, 0x72, 0x5e, 0x93, 0xc8, 0x1b, 0x15, 0xf2, 0x9a, 0x44, 0xee, 0xd3, 0x6f, 0x06, 0x52, 0x9f, 0x6d, 0xdc, 0x3a, 0x69, 0x75, 0x68, 0x14, 0xb6, 0x3e, 0xae, 0xd1, 0xe6, 0x47, 0x8f, 0xf7, 0xcb, 0xe8, 0xc9, 0x7e, 0x19, 0xfd, 0xb6, 0x5f, 0x46, 0x8f, 0x0e, 0xca, 0x73, 0x4f, 0x0e, 0xca, 0x73, 0xbf, 0x1c, 0x94, 0xe7, 0x3e, 0xbe, 0xe5, 0x7a, 0x61, 0xab, 0xdf, 0xb0, 0x28, 0xef, 0x92, 0x86, 0xe7, 0xf8, 0xdb, 0x1e, 0x73, 0x3c, 0x89, 0xeb, 0x86, 0xcb, 0x49, 0x97, 0x37, 0xfb, 0x1d, 0x26, 0x12, 0x38, 0xd7, 0x5f, 0xbb, 0xa1, 0xa1, 0x86, 0x3b, 0x01, 0x13, 0x8d, 0xf3, 0xf2, 0x6f, 0xa2, 0x9b, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0xa4, 0x98, 0xfa, 0x69, 0x02, 0x13, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // QueryClient is the client API for Query service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { // PacketCommitment queries a stored packet commitment hash. PacketCommitment(ctx context.Context, in *QueryPacketCommitmentRequest, opts ...grpc.CallOption) (*QueryPacketCommitmentResponse, error) // PacketCommitments returns all the packet commitments hashes associated PacketCommitments(ctx context.Context, in *QueryPacketCommitmentsRequest, opts ...grpc.CallOption) (*QueryPacketCommitmentsResponse, error) // PacketReceipt queries if a given packet sequence has been received on the queried chain PacketReceipt(ctx context.Context, in *QueryPacketReceiptRequest, opts ...grpc.CallOption) (*QueryPacketReceiptResponse, error) // PacketAcknowledgement queries a stored packet acknowledgement hash. PacketAcknowledgement(ctx context.Context, in *QueryPacketAcknowledgementRequest, opts ...grpc.CallOption) (*QueryPacketAcknowledgementResponse, error) // PacketAcknowledgements returns all the packet acknowledgements associated PacketAcknowledgements(ctx context.Context, in *QueryPacketAcknowledgementsRequest, opts ...grpc.CallOption) (*QueryPacketAcknowledgementsResponse, error) // UnreceivedPackets returns all the unreceived TIBC packets associated with sequences. UnreceivedPackets(ctx context.Context, in *QueryUnreceivedPacketsRequest, opts ...grpc.CallOption) (*QueryUnreceivedPacketsResponse, error) // UnreceivedAcks returns all the unreceived TIBC acknowledgements associated with sequences. UnreceivedAcks(ctx context.Context, in *QueryUnreceivedAcksRequest, opts ...grpc.CallOption) (*QueryUnreceivedAcksResponse, error) // CleanPacketCommitment queries a stored packet commitment hash. CleanPacketCommitment(ctx context.Context, in *QueryCleanPacketCommitmentRequest, opts ...grpc.CallOption) (*QueryCleanPacketCommitmentResponse, error) } type queryClient struct { cc grpc1.ClientConn } func NewQueryClient(cc grpc1.ClientConn) QueryClient { return &queryClient{cc} } func (c *queryClient) PacketCommitment(ctx context.Context, in *QueryPacketCommitmentRequest, opts ...grpc.CallOption) (*QueryPacketCommitmentResponse, error) { out := new(QueryPacketCommitmentResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/PacketCommitment", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) PacketCommitments(ctx context.Context, in *QueryPacketCommitmentsRequest, opts ...grpc.CallOption) (*QueryPacketCommitmentsResponse, error) { out := new(QueryPacketCommitmentsResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/PacketCommitments", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) PacketReceipt(ctx context.Context, in *QueryPacketReceiptRequest, opts ...grpc.CallOption) (*QueryPacketReceiptResponse, error) { out := new(QueryPacketReceiptResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/PacketReceipt", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) PacketAcknowledgement(ctx context.Context, in *QueryPacketAcknowledgementRequest, opts ...grpc.CallOption) (*QueryPacketAcknowledgementResponse, error) { out := new(QueryPacketAcknowledgementResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/PacketAcknowledgement", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) PacketAcknowledgements(ctx context.Context, in *QueryPacketAcknowledgementsRequest, opts ...grpc.CallOption) (*QueryPacketAcknowledgementsResponse, error) { out := new(QueryPacketAcknowledgementsResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/PacketAcknowledgements", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) UnreceivedPackets(ctx context.Context, in *QueryUnreceivedPacketsRequest, opts ...grpc.CallOption) (*QueryUnreceivedPacketsResponse, error) { out := new(QueryUnreceivedPacketsResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/UnreceivedPackets", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) UnreceivedAcks(ctx context.Context, in *QueryUnreceivedAcksRequest, opts ...grpc.CallOption) (*QueryUnreceivedAcksResponse, error) { out := new(QueryUnreceivedAcksResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/UnreceivedAcks", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *queryClient) CleanPacketCommitment(ctx context.Context, in *QueryCleanPacketCommitmentRequest, opts ...grpc.CallOption) (*QueryCleanPacketCommitmentResponse, error) { out := new(QueryCleanPacketCommitmentResponse) err := c.cc.Invoke(ctx, "/tibc.core.packet.v1.Query/CleanPacketCommitment", in, out, opts...) if err != nil { return nil, err } return out, nil } // QueryServer is the server API for Query service. type QueryServer interface { // PacketCommitment queries a stored packet commitment hash. PacketCommitment(context.Context, *QueryPacketCommitmentRequest) (*QueryPacketCommitmentResponse, error) // PacketCommitments returns all the packet commitments hashes associated PacketCommitments(context.Context, *QueryPacketCommitmentsRequest) (*QueryPacketCommitmentsResponse, error) // PacketReceipt queries if a given packet sequence has been received on the queried chain PacketReceipt(context.Context, *QueryPacketReceiptRequest) (*QueryPacketReceiptResponse, error) // PacketAcknowledgement queries a stored packet acknowledgement hash. PacketAcknowledgement(context.Context, *QueryPacketAcknowledgementRequest) (*QueryPacketAcknowledgementResponse, error) // PacketAcknowledgements returns all the packet acknowledgements associated PacketAcknowledgements(context.Context, *QueryPacketAcknowledgementsRequest) (*QueryPacketAcknowledgementsResponse, error) // UnreceivedPackets returns all the unreceived TIBC packets associated with sequences. UnreceivedPackets(context.Context, *QueryUnreceivedPacketsRequest) (*QueryUnreceivedPacketsResponse, error) // UnreceivedAcks returns all the unreceived TIBC acknowledgements associated with sequences. UnreceivedAcks(context.Context, *QueryUnreceivedAcksRequest) (*QueryUnreceivedAcksResponse, error) // CleanPacketCommitment queries a stored packet commitment hash. CleanPacketCommitment(context.Context, *QueryCleanPacketCommitmentRequest) (*QueryCleanPacketCommitmentResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. type UnimplementedQueryServer struct { } func (*UnimplementedQueryServer) PacketCommitment(ctx context.Context, req *QueryPacketCommitmentRequest) (*QueryPacketCommitmentResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PacketCommitment not implemented") } func (*UnimplementedQueryServer) PacketCommitments(ctx context.Context, req *QueryPacketCommitmentsRequest) (*QueryPacketCommitmentsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PacketCommitments not implemented") } func (*UnimplementedQueryServer) PacketReceipt(ctx context.Context, req *QueryPacketReceiptRequest) (*QueryPacketReceiptResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PacketReceipt not implemented") } func (*UnimplementedQueryServer) PacketAcknowledgement(ctx context.Context, req *QueryPacketAcknowledgementRequest) (*QueryPacketAcknowledgementResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PacketAcknowledgement not implemented") } func (*UnimplementedQueryServer) PacketAcknowledgements(ctx context.Context, req *QueryPacketAcknowledgementsRequest) (*QueryPacketAcknowledgementsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PacketAcknowledgements not implemented") } func (*UnimplementedQueryServer) UnreceivedPackets(ctx context.Context, req *QueryUnreceivedPacketsRequest) (*QueryUnreceivedPacketsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UnreceivedPackets not implemented") } func (*UnimplementedQueryServer) UnreceivedAcks(ctx context.Context, req *QueryUnreceivedAcksRequest) (*QueryUnreceivedAcksResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UnreceivedAcks not implemented") } func (*UnimplementedQueryServer) CleanPacketCommitment(ctx context.Context, req *QueryCleanPacketCommitmentRequest) (*QueryCleanPacketCommitmentResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CleanPacketCommitment not implemented") } func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } func _Query_PacketCommitment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryPacketCommitmentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).PacketCommitment(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/PacketCommitment", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).PacketCommitment(ctx, req.(*QueryPacketCommitmentRequest)) } return interceptor(ctx, in, info, handler) } func _Query_PacketCommitments_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryPacketCommitmentsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).PacketCommitments(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/PacketCommitments", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).PacketCommitments(ctx, req.(*QueryPacketCommitmentsRequest)) } return interceptor(ctx, in, info, handler) } func _Query_PacketReceipt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryPacketReceiptRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).PacketReceipt(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/PacketReceipt", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).PacketReceipt(ctx, req.(*QueryPacketReceiptRequest)) } return interceptor(ctx, in, info, handler) } func _Query_PacketAcknowledgement_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryPacketAcknowledgementRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).PacketAcknowledgement(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/PacketAcknowledgement", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).PacketAcknowledgement(ctx, req.(*QueryPacketAcknowledgementRequest)) } return interceptor(ctx, in, info, handler) } func _Query_PacketAcknowledgements_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryPacketAcknowledgementsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).PacketAcknowledgements(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/PacketAcknowledgements", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).PacketAcknowledgements(ctx, req.(*QueryPacketAcknowledgementsRequest)) } return interceptor(ctx, in, info, handler) } func _Query_UnreceivedPackets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryUnreceivedPacketsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).UnreceivedPackets(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/UnreceivedPackets", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).UnreceivedPackets(ctx, req.(*QueryUnreceivedPacketsRequest)) } return interceptor(ctx, in, info, handler) } func _Query_UnreceivedAcks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryUnreceivedAcksRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).UnreceivedAcks(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/UnreceivedAcks", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).UnreceivedAcks(ctx, req.(*QueryUnreceivedAcksRequest)) } return interceptor(ctx, in, info, handler) } func _Query_CleanPacketCommitment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryCleanPacketCommitmentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).CleanPacketCommitment(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.packet.v1.Query/CleanPacketCommitment", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).CleanPacketCommitment(ctx, req.(*QueryCleanPacketCommitmentRequest)) } return interceptor(ctx, in, info, handler) } var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "tibc.core.packet.v1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "PacketCommitment", Handler: _Query_PacketCommitment_Handler, }, { MethodName: "PacketCommitments", Handler: _Query_PacketCommitments_Handler, }, { MethodName: "PacketReceipt", Handler: _Query_PacketReceipt_Handler, }, { MethodName: "PacketAcknowledgement", Handler: _Query_PacketAcknowledgement_Handler, }, { MethodName: "PacketAcknowledgements", Handler: _Query_PacketAcknowledgements_Handler, }, { MethodName: "UnreceivedPackets", Handler: _Query_UnreceivedPackets_Handler, }, { MethodName: "UnreceivedAcks", Handler: _Query_UnreceivedAcks_Handler, }, { MethodName: "CleanPacketCommitment", Handler: _Query_CleanPacketCommitment_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "tibc/core/packet/v1/query.proto", } func (m *QueryPacketCommitmentRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketCommitmentRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketCommitmentRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Sequence != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x18 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketCommitmentResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketCommitmentResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketCommitmentResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.Proof) > 0 { i -= len(m.Proof) copy(dAtA[i:], m.Proof) i = encodeVarintQuery(dAtA, i, uint64(len(m.Proof))) i-- dAtA[i] = 0x12 } if len(m.Commitment) > 0 { i -= len(m.Commitment) copy(dAtA[i:], m.Commitment) i = encodeVarintQuery(dAtA, i, uint64(len(m.Commitment))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketCommitmentsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketCommitmentsRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketCommitmentsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketCommitmentsResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketCommitmentsResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketCommitmentsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.Commitments) > 0 { for iNdEx := len(m.Commitments) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Commitments[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *QueryPacketReceiptRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketReceiptRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketReceiptRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Sequence != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x18 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketReceiptResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketReceiptResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketReceiptResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 if len(m.Proof) > 0 { i -= len(m.Proof) copy(dAtA[i:], m.Proof) i = encodeVarintQuery(dAtA, i, uint64(len(m.Proof))) i-- dAtA[i] = 0x1a } if m.Received { i-- if m.Received { dAtA[i] = 1 } else { dAtA[i] = 0 } i-- dAtA[i] = 0x10 } return len(dAtA) - i, nil } func (m *QueryPacketAcknowledgementRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketAcknowledgementRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketAcknowledgementRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Sequence != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x18 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketAcknowledgementResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketAcknowledgementResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketAcknowledgementResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.Proof) > 0 { i -= len(m.Proof) copy(dAtA[i:], m.Proof) i = encodeVarintQuery(dAtA, i, uint64(len(m.Proof))) i-- dAtA[i] = 0x12 } if len(m.Acknowledgement) > 0 { i -= len(m.Acknowledgement) copy(dAtA[i:], m.Acknowledgement) i = encodeVarintQuery(dAtA, i, uint64(len(m.Acknowledgement))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketAcknowledgementsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketAcknowledgementsRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketAcknowledgementsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryPacketAcknowledgementsResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryPacketAcknowledgementsResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryPacketAcknowledgementsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if m.Pagination != nil { { size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } if len(m.Acknowledgements) > 0 { for iNdEx := len(m.Acknowledgements) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Acknowledgements[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *QueryUnreceivedPacketsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryUnreceivedPacketsRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryUnreceivedPacketsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.PacketCommitmentSequences) > 0 { dAtA11 := make([]byte, len(m.PacketCommitmentSequences)*10) var j10 int for _, num := range m.PacketCommitmentSequences { for num >= 1<<7 { dAtA11[j10] = uint8(uint64(num)&0x7f | 0x80) num >>= 7 j10++ } dAtA11[j10] = uint8(num) j10++ } i -= j10 copy(dAtA[i:], dAtA11[:j10]) i = encodeVarintQuery(dAtA, i, uint64(j10)) i-- dAtA[i] = 0x1a } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryUnreceivedPacketsResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryUnreceivedPacketsResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryUnreceivedPacketsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 if len(m.Sequences) > 0 { dAtA14 := make([]byte, len(m.Sequences)*10) var j13 int for _, num := range m.Sequences { for num >= 1<<7 { dAtA14[j13] = uint8(uint64(num)&0x7f | 0x80) num >>= 7 j13++ } dAtA14[j13] = uint8(num) j13++ } i -= j13 copy(dAtA[i:], dAtA14[:j13]) i = encodeVarintQuery(dAtA, i, uint64(j13)) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryUnreceivedAcksRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryUnreceivedAcksRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryUnreceivedAcksRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.PacketAckSequences) > 0 { dAtA16 := make([]byte, len(m.PacketAckSequences)*10) var j15 int for _, num := range m.PacketAckSequences { for num >= 1<<7 { dAtA16[j15] = uint8(uint64(num)&0x7f | 0x80) num >>= 7 j15++ } dAtA16[j15] = uint8(num) j15++ } i -= j15 copy(dAtA[i:], dAtA16[:j15]) i = encodeVarintQuery(dAtA, i, uint64(j15)) i-- dAtA[i] = 0x1a } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryUnreceivedAcksResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryUnreceivedAcksResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryUnreceivedAcksResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.Height.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 if len(m.Sequences) > 0 { dAtA19 := make([]byte, len(m.Sequences)*10) var j18 int for _, num := range m.Sequences { for num >= 1<<7 { dAtA19[j18] = uint8(uint64(num)&0x7f | 0x80) num >>= 7 j18++ } dAtA19[j18] = uint8(num) j18++ } i -= j18 copy(dAtA[i:], dAtA19[:j18]) i = encodeVarintQuery(dAtA, i, uint64(j18)) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryCleanPacketCommitmentRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryCleanPacketCommitmentRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryCleanPacketCommitmentRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0x12 } if len(m.DestChain) > 0 { i -= len(m.DestChain) copy(dAtA[i:], m.DestChain) i = encodeVarintQuery(dAtA, i, uint64(len(m.DestChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *QueryCleanPacketCommitmentResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryCleanPacketCommitmentResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryCleanPacketCommitmentResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.ProofHeight.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuery(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a if len(m.Proof) > 0 { i -= len(m.Proof) copy(dAtA[i:], m.Proof) i = encodeVarintQuery(dAtA, i, uint64(len(m.Proof))) i-- dAtA[i] = 0x12 } if len(m.Commitment) > 0 { i -= len(m.Commitment) copy(dAtA[i:], m.Commitment) i = encodeVarintQuery(dAtA, i, uint64(len(m.Commitment))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { offset -= sovQuery(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *QueryPacketCommitmentRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.Sequence != 0 { n += 1 + sovQuery(uint64(m.Sequence)) } return n } func (m *QueryPacketCommitmentResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Commitment) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.Proof) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryPacketCommitmentsRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryPacketCommitmentsResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Commitments) > 0 { for _, e := range m.Commitments { l = e.Size() n += 1 + l + sovQuery(uint64(l)) } } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } l = m.Height.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryPacketReceiptRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.Sequence != 0 { n += 1 + sovQuery(uint64(m.Sequence)) } return n } func (m *QueryPacketReceiptResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Received { n += 2 } l = len(m.Proof) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryPacketAcknowledgementRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.Sequence != 0 { n += 1 + sovQuery(uint64(m.Sequence)) } return n } func (m *QueryPacketAcknowledgementResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Acknowledgement) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.Proof) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryPacketAcknowledgementsRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryPacketAcknowledgementsResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Acknowledgements) > 0 { for _, e := range m.Acknowledgements { l = e.Size() n += 1 + l + sovQuery(uint64(l)) } } if m.Pagination != nil { l = m.Pagination.Size() n += 1 + l + sovQuery(uint64(l)) } l = m.Height.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryUnreceivedPacketsRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if len(m.PacketCommitmentSequences) > 0 { l = 0 for _, e := range m.PacketCommitmentSequences { l += sovQuery(uint64(e)) } n += 1 + sovQuery(uint64(l)) + l } return n } func (m *QueryUnreceivedPacketsResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Sequences) > 0 { l = 0 for _, e := range m.Sequences { l += sovQuery(uint64(e)) } n += 1 + sovQuery(uint64(l)) + l } l = m.Height.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryUnreceivedAcksRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } if len(m.PacketAckSequences) > 0 { l = 0 for _, e := range m.PacketAckSequences { l += sovQuery(uint64(e)) } n += 1 + sovQuery(uint64(l)) + l } return n } func (m *QueryUnreceivedAcksResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Sequences) > 0 { l = 0 for _, e := range m.Sequences { l += sovQuery(uint64(e)) } n += 1 + sovQuery(uint64(l)) + l } l = m.Height.Size() n += 1 + l + sovQuery(uint64(l)) return n } func (m *QueryCleanPacketCommitmentRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.DestChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.SourceChain) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } return n } func (m *QueryCleanPacketCommitmentResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Commitment) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = len(m.Proof) if l > 0 { n += 1 + l + sovQuery(uint64(l)) } l = m.ProofHeight.Size() n += 1 + l + sovQuery(uint64(l)) return n } func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozQuery(x uint64) (n int) { return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *QueryPacketCommitmentRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketCommitmentRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketCommitmentRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketCommitmentResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketCommitmentResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketCommitmentResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Commitment", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Commitment = append(m.Commitment[:0], dAtA[iNdEx:postIndex]...) if m.Commitment == nil { m.Commitment = []byte{} } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof[:0], dAtA[iNdEx:postIndex]...) if m.Proof == nil { m.Proof = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketCommitmentsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketCommitmentsRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketCommitmentsRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageRequest{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketCommitmentsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketCommitmentsResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketCommitmentsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Commitments", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Commitments = append(m.Commitments, &PacketState{}) if err := m.Commitments[len(m.Commitments)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageResponse{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketReceiptRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketReceiptRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketReceiptRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketReceiptResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketReceiptResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketReceiptResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Received", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int(b&0x7F) << shift if b < 0x80 { break } } m.Received = bool(v != 0) case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof[:0], dAtA[iNdEx:postIndex]...) if m.Proof == nil { m.Proof = []byte{} } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketAcknowledgementRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketAcknowledgementRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketAcknowledgementRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketAcknowledgementResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketAcknowledgementResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketAcknowledgementResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Acknowledgement", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Acknowledgement = append(m.Acknowledgement[:0], dAtA[iNdEx:postIndex]...) if m.Acknowledgement == nil { m.Acknowledgement = []byte{} } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof[:0], dAtA[iNdEx:postIndex]...) if m.Proof == nil { m.Proof = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketAcknowledgementsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketAcknowledgementsRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketAcknowledgementsRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageRequest{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryPacketAcknowledgementsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryPacketAcknowledgementsResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryPacketAcknowledgementsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Acknowledgements", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Acknowledgements = append(m.Acknowledgements, &PacketState{}) if err := m.Acknowledgements[len(m.Acknowledgements)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if m.Pagination == nil { m.Pagination = &query.PageResponse{} } if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryUnreceivedPacketsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryUnreceivedPacketsRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryUnreceivedPacketsRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType == 0 { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.PacketCommitmentSequences = append(m.PacketCommitmentSequences, v) } else if wireType == 2 { var packedLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ packedLen |= int(b&0x7F) << shift if b < 0x80 { break } } if packedLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + packedLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } var elementCount int var count int for _, integer := range dAtA[iNdEx:postIndex] { if integer < 128 { count++ } } elementCount = count if elementCount != 0 && len(m.PacketCommitmentSequences) == 0 { m.PacketCommitmentSequences = make([]uint64, 0, elementCount) } for iNdEx < postIndex { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.PacketCommitmentSequences = append(m.PacketCommitmentSequences, v) } } else { return fmt.Errorf("proto: wrong wireType = %d for field PacketCommitmentSequences", wireType) } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryUnreceivedPacketsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryUnreceivedPacketsResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryUnreceivedPacketsResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType == 0 { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.Sequences = append(m.Sequences, v) } else if wireType == 2 { var packedLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ packedLen |= int(b&0x7F) << shift if b < 0x80 { break } } if packedLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + packedLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } var elementCount int var count int for _, integer := range dAtA[iNdEx:postIndex] { if integer < 128 { count++ } } elementCount = count if elementCount != 0 && len(m.Sequences) == 0 { m.Sequences = make([]uint64, 0, elementCount) } for iNdEx < postIndex { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.Sequences = append(m.Sequences, v) } } else { return fmt.Errorf("proto: wrong wireType = %d for field Sequences", wireType) } case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryUnreceivedAcksRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryUnreceivedAcksRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryUnreceivedAcksRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType == 0 { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.PacketAckSequences = append(m.PacketAckSequences, v) } else if wireType == 2 { var packedLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ packedLen |= int(b&0x7F) << shift if b < 0x80 { break } } if packedLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + packedLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } var elementCount int var count int for _, integer := range dAtA[iNdEx:postIndex] { if integer < 128 { count++ } } elementCount = count if elementCount != 0 && len(m.PacketAckSequences) == 0 { m.PacketAckSequences = make([]uint64, 0, elementCount) } for iNdEx < postIndex { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.PacketAckSequences = append(m.PacketAckSequences, v) } } else { return fmt.Errorf("proto: wrong wireType = %d for field PacketAckSequences", wireType) } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryUnreceivedAcksResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryUnreceivedAcksResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryUnreceivedAcksResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType == 0 { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.Sequences = append(m.Sequences, v) } else if wireType == 2 { var packedLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ packedLen |= int(b&0x7F) << shift if b < 0x80 { break } } if packedLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + packedLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } var elementCount int var count int for _, integer := range dAtA[iNdEx:postIndex] { if integer < 128 { count++ } } elementCount = count if elementCount != 0 && len(m.Sequences) == 0 { m.Sequences = make([]uint64, 0, elementCount) } for iNdEx < postIndex { var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint64(b&0x7F) << shift if b < 0x80 { break } } m.Sequences = append(m.Sequences, v) } } else { return fmt.Errorf("proto: wrong wireType = %d for field Sequences", wireType) } case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Height.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryCleanPacketCommitmentRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryCleanPacketCommitmentRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryCleanPacketCommitmentRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.DestChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryCleanPacketCommitmentResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryCleanPacketCommitmentResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryCleanPacketCommitmentResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Commitment", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Commitment = append(m.Commitment[:0], dAtA[iNdEx:postIndex]...) if m.Commitment == nil { m.Commitment = []byte{} } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proof", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Proof = append(m.Proof[:0], dAtA[iNdEx:postIndex]...) if m.Proof == nil { m.Proof = []byte{} } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ProofHeight", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ProofHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthQuery } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupQuery } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthQuery } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/26-routing/types/port.go<|end_filename|> package types type Port string const ( FT Port = "FT" NFT Port = "NFT" CONTRACT Port = "CONTRACT" SERVICE Port = "SERVICE" ) <|start_filename|>modules/tibc/core/exported/packet.go<|end_filename|> package exported // PacketI defines the standard interface for TIBC clean packets type PacketI interface { GetSequence() uint64 GetPort() string GetSourceChain() string GetDestChain() string GetRelayChain() string GetData() []byte ValidateBasic() error } // CleanPacketI defines the standard interface for TIBC clean packets type CleanPacketI interface { GetSequence() uint64 GetSourceChain() string GetDestChain() string GetRelayChain() string ValidateBasic() error } <|start_filename|>Makefile<|end_filename|> #!/usr/bin/make -f SIMAPP = ./simapp BINDIR ?= $(GOPATH)/bin BUILDDIR ?= $(CURDIR)/build SIMAPP = ./simapp PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') PACKAGES_UNITTEST=$(shell go list ./... | grep -v '/simulation' | grep -v '/cli_test') export GO111MODULE = on # process build tags build_tags = netgo ifeq ($(LEDGER_ENABLED),true) ifeq ($(OS),Windows_NT) GCCEXE = $(shell where gcc.exe 2> NUL) ifeq ($(GCCEXE),) $(error gcc.exe not installed for ledger support, please install or set LEDGER_ENABLED=false) else build_tags += ledger endif else UNAME_S = $(shell uname -s) ifeq ($(UNAME_S),OpenBSD) $(warning OpenBSD detected, disabling ledger support (https://github.com/cosmos/cosmos-sdk/issues/1988)) else GCC = $(shell command -v gcc 2> /dev/null) ifeq ($(GCC),) $(error gcc not installed for ledger support, please install or set LEDGER_ENABLED=false) else build_tags += ledger endif endif endif endif ifeq (cleveldb,$(findstring cleveldb,$(COSMOS_BUILD_OPTIONS))) build_tags += gcc endif build_tags += $(BUILD_TAGS) build_tags := $(strip $(build_tags)) BUILD_FLAGS := -tags "$(build_tags)" -ldflags '$(ldflags)' # check for nostrip option ifeq (,$(findstring nostrip,$(COSMOS_BUILD_OPTIONS))) BUILD_FLAGS += -trimpath endif ############################################################################### ### Build ### ############################################################################### BUILD_TARGETS := build install build: BUILD_ARGS=-o $(BUILDDIR)/ build-linux: GOOS=linux GOARCH=amd64 LEDGER_ENABLED=false $(MAKE) build $(BUILD_TARGETS): go.sum $(BUILDDIR)/ go $@ -mod=readonly $(BUILD_FLAGS) $(BUILD_ARGS) ./... $(BUILDDIR)/: mkdir -p $(BUILDDIR)/ ######################################## ### Tools & dependencies go-mod-cache: go.sum @echo "--> Download go modules to local cache" @go mod download go.sum: go.mod @echo "--> Ensure dependencies have not been modified" @go mod verify clean: rm -rf snapcraft-local.yaml build/ distclean: clean rm -rf vendor/ proto-all: proto-tools proto-gen proto-gen: @./scripts/protocgen.sh ######################################## ### Testing test: test-unit test-unit: @VERSION=$(VERSION) go test -mod=readonly -tags='ledger test_ledger_mock' -ldflags '$(ldflags)' ${PACKAGES_UNITTEST} test-sim-nondeterminism: @echo "Running non-determinism test..." @go test -mod=readonly $(SIMAPP) -run TestAppStateDeterminism -Enabled=true \ -NumBlocks=100 -BlockSize=200 -Commit=true -Period=0 -v -timeout 24h test-sim-import-export: runsim @echo "Running application import/export simulation. This may take several minutes..." @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 5 TestAppImportExport test-sim-after-import: runsim @echo "Running application simulation-after-import. This may take several minutes..." @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 5 TestAppSimulationAfterImport test-sim-multi-seed-long: runsim @echo "Running long multi-seed application simulation. This may take awhile!" @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 500 50 TestFullAppSimulation test-sim-multi-seed-short: runsim @echo "Running short multi-seed application simulation. This may take awhile!" @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 10 TestFullAppSimulation test-sim-benchmark-invariants: @echo "Running simulation invariant benchmarks..." @go test -mod=readonly $(SIMAPP) -benchmem -bench=BenchmarkInvariants -run=^$ \ -Enabled=true -NumBlocks=1000 -BlockSize=200 \ -Period=1 -Commit=true -Seed=57 -v -timeout 24h lint: golangci-lint golangci-lint run find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./lite/*/statik.go" -not -path "*.pb.go" | xargs gofmt -d -s go mod verify format: find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./lite/*/statik.go" -not -path "*.pb.go" | xargs gofmt -w -s find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./lite/*/statik.go" -not -path "*.pb.go" | xargs misspell -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./lite/*/statik.go" -not -path "*.pb.go" | xargs goimports -w -local github.com/bianjieai/tibc-go benchmark: @go test -mod=readonly -bench=. ./... <|start_filename|>modules/tibc/core/simulation/genesis.go<|end_filename|> package simulation // DONTCOVER import ( "encoding/json" "fmt" "math/rand" "github.com/cosmos/cosmos-sdk/types/module" clientsims "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/simulation" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" packetsims "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/simulation" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" "github.com/bianjieai/tibc-go/modules/tibc/core/types" ) // Simulation parameter constants const ( clientGenesis = "client_genesis" packetGenesis = "packet_genesis" ) // RandomizedGenState generates a random GenesisState for evidence func RandomizedGenState(simState *module.SimulationState) { var ( clientGenesisState clienttypes.GenesisState packetGenesisState packettypes.GenesisState ) simState.AppParams.GetOrGenerate( simState.Cdc, clientGenesis, &clientGenesisState, simState.Rand, func(r *rand.Rand) { clientGenesisState = clientsims.GenClientGenesis(r, simState.Accounts) }, ) simState.AppParams.GetOrGenerate( simState.Cdc, packetGenesis, &packetGenesisState, simState.Rand, func(r *rand.Rand) { packetGenesisState = packetsims.GenpacketGenesis(r, simState.Accounts) }, ) ibcGenesis := types.GenesisState{ ClientGenesis: clientGenesisState, PacketGenesis: packetGenesisState, } bz, err := json.MarshalIndent(&ibcGenesis, "", " ") if err != nil { panic(err) } fmt.Printf("Selected randomly generated %s parameters:\n%s\n", host.ModuleName, bz) simState.GenState[host.ModuleName] = simState.Cdc.MustMarshalJSON(&ibcGenesis) } <|start_filename|>modules/tibc/core/handler.go<|end_filename|> package tibc import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" "github.com/bianjieai/tibc-go/modules/tibc/core/keeper" ) // NewHandler defines the TIBC handler func NewHandler(k keeper.Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { case *clienttypes.MsgUpdateClient: res, err := k.UpdateClient(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) // TIBC packet msgs get routed to the appropriate module callback case *packettypes.MsgRecvPacket: res, err := k.RecvPacket(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *packettypes.MsgAcknowledgement: res, err := k.Acknowledgement(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *packettypes.MsgCleanPacket: res, err := k.CleanPacket(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *packettypes.MsgRecvCleanPacket: res, err := k.RecvCleanPacket(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) default: return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized TIBC message type: %T", msg) } } } <|start_filename|>modules/tibc/core/02-client/types/genesis.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/client/v1/genesis.proto package types import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // GenesisState defines the tibc client submodule's genesis state. type GenesisState struct { // client states with their corresponding identifiers Clients IdentifiedClientStates `protobuf:"bytes,1,rep,name=clients,proto3,castrepeated=IdentifiedClientStates" json:"clients"` // consensus states from each client ClientsConsensus ClientsConsensusStates `protobuf:"bytes,2,rep,name=clients_consensus,json=clientsConsensus,proto3,castrepeated=ClientsConsensusStates" json:"clients_consensus"` // metadata from each client ClientsMetadata []IdentifiedGenesisMetadata `protobuf:"bytes,3,rep,name=clients_metadata,json=clientsMetadata,proto3" json:"clients_metadata"` // the chain name of the current chain NativeChainName string `protobuf:"bytes,5,opt,name=native_chain_name,json=nativeChainName,proto3" json:"native_chain_name,omitempty"` // IdentifiedRelayer defines a list of authorized relayers for the specified // client. Relayers []IdentifiedRelayers `protobuf:"bytes,6,rep,name=relayers,proto3" json:"relayers"` } func (m *GenesisState) Reset() { *m = GenesisState{} } func (m *GenesisState) String() string { return proto.CompactTextString(m) } func (*GenesisState) ProtoMessage() {} func (*GenesisState) Descriptor() ([]byte, []int) { return fileDescriptor_5b4ecc0f10c963d8, []int{0} } func (m *GenesisState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *GenesisState) XXX_Merge(src proto.Message) { xxx_messageInfo_GenesisState.Merge(m, src) } func (m *GenesisState) XXX_Size() int { return m.Size() } func (m *GenesisState) XXX_DiscardUnknown() { xxx_messageInfo_GenesisState.DiscardUnknown(m) } var xxx_messageInfo_GenesisState proto.InternalMessageInfo func (m *GenesisState) GetClients() IdentifiedClientStates { if m != nil { return m.Clients } return nil } func (m *GenesisState) GetClientsConsensus() ClientsConsensusStates { if m != nil { return m.ClientsConsensus } return nil } func (m *GenesisState) GetClientsMetadata() []IdentifiedGenesisMetadata { if m != nil { return m.ClientsMetadata } return nil } func (m *GenesisState) GetNativeChainName() string { if m != nil { return m.NativeChainName } return "" } func (m *GenesisState) GetRelayers() []IdentifiedRelayers { if m != nil { return m.Relayers } return nil } // GenesisMetadata defines the genesis type for metadata that clients may return // with ExportMetadata type GenesisMetadata struct { // store key of metadata without chainName-prefix Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // metadata value Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (m *GenesisMetadata) Reset() { *m = GenesisMetadata{} } func (m *GenesisMetadata) String() string { return proto.CompactTextString(m) } func (*GenesisMetadata) ProtoMessage() {} func (*GenesisMetadata) Descriptor() ([]byte, []int) { return fileDescriptor_5b4ecc0f10c963d8, []int{1} } func (m *GenesisMetadata) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *GenesisMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_GenesisMetadata.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *GenesisMetadata) XXX_Merge(src proto.Message) { xxx_messageInfo_GenesisMetadata.Merge(m, src) } func (m *GenesisMetadata) XXX_Size() int { return m.Size() } func (m *GenesisMetadata) XXX_DiscardUnknown() { xxx_messageInfo_GenesisMetadata.DiscardUnknown(m) } var xxx_messageInfo_GenesisMetadata proto.InternalMessageInfo // IdentifiedGenesisMetadata has the client metadata with the corresponding // chain name. type IdentifiedGenesisMetadata struct { ChainName string `protobuf:"bytes,1,opt,name=chain_name,json=chainName,proto3" json:"chain_name,omitempty"` Metadata []GenesisMetadata `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata"` } func (m *IdentifiedGenesisMetadata) Reset() { *m = IdentifiedGenesisMetadata{} } func (m *IdentifiedGenesisMetadata) String() string { return proto.CompactTextString(m) } func (*IdentifiedGenesisMetadata) ProtoMessage() {} func (*IdentifiedGenesisMetadata) Descriptor() ([]byte, []int) { return fileDescriptor_5b4ecc0f10c963d8, []int{2} } func (m *IdentifiedGenesisMetadata) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *IdentifiedGenesisMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_IdentifiedGenesisMetadata.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *IdentifiedGenesisMetadata) XXX_Merge(src proto.Message) { xxx_messageInfo_IdentifiedGenesisMetadata.Merge(m, src) } func (m *IdentifiedGenesisMetadata) XXX_Size() int { return m.Size() } func (m *IdentifiedGenesisMetadata) XXX_DiscardUnknown() { xxx_messageInfo_IdentifiedGenesisMetadata.DiscardUnknown(m) } var xxx_messageInfo_IdentifiedGenesisMetadata proto.InternalMessageInfo func (m *IdentifiedGenesisMetadata) GetChainName() string { if m != nil { return m.ChainName } return "" } func (m *IdentifiedGenesisMetadata) GetMetadata() []GenesisMetadata { if m != nil { return m.Metadata } return nil } func init() { proto.RegisterType((*GenesisState)(nil), "tibc.core.client.v1.GenesisState") proto.RegisterType((*GenesisMetadata)(nil), "tibc.core.client.v1.GenesisMetadata") proto.RegisterType((*IdentifiedGenesisMetadata)(nil), "tibc.core.client.v1.IdentifiedGenesisMetadata") } func init() { proto.RegisterFile("tibc/core/client/v1/genesis.proto", fileDescriptor_5b4ecc0f10c963d8) } var fileDescriptor_5b4ecc0f10c963d8 = []byte{ // 451 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x53, 0x31, 0x6f, 0x13, 0x31, 0x14, 0x3e, 0x37, 0x6d, 0x69, 0x4d, 0xa5, 0xb4, 0xa6, 0x42, 0x47, 0x25, 0x2e, 0x21, 0x42, 0x22, 0xaa, 0x54, 0x9b, 0x96, 0x8d, 0x01, 0xa4, 0x44, 0x02, 0x75, 0x80, 0xe1, 0x58, 0x10, 0xcb, 0xc9, 0xf1, 0x3d, 0xae, 0x86, 0x9c, 0x5d, 0xc5, 0x4e, 0x50, 0x56, 0x26, 0x46, 0x7e, 0x02, 0x33, 0xff, 0x03, 0xa9, 0x63, 0x47, 0x26, 0x40, 0xc9, 0x1f, 0x41, 0x67, 0x3b, 0x29, 0x8a, 0x8e, 0x76, 0x7b, 0xf9, 0xde, 0xfb, 0xbe, 0xef, 0x7d, 0x2f, 0x67, 0xfc, 0xc0, 0xca, 0x81, 0x60, 0x42, 0x8f, 0x80, 0x89, 0xa1, 0x04, 0x65, 0xd9, 0xe4, 0x98, 0x15, 0xa0, 0xc0, 0x48, 0x43, 0xcf, 0x47, 0xda, 0x6a, 0x72, 0xa7, 0x1a, 0xa1, 0xd5, 0x08, 0xf5, 0x23, 0x74, 0x72, 0x7c, 0xd0, 0xae, 0xe3, 0x85, 0xb6, 0xa3, 0x1d, 0xec, 0x17, 0xba, 0xd0, 0xae, 0x64, 0x55, 0xe5, 0xd1, 0xce, 0x8f, 0x06, 0xde, 0x79, 0xe9, 0xe5, 0xdf, 0x58, 0x6e, 0x81, 0xe4, 0xf8, 0x96, 0xa7, 0x99, 0x18, 0xb5, 0x1b, 0xdd, 0xdb, 0x27, 0x87, 0xb4, 0xc6, 0x8f, 0x9e, 0xe6, 0xa0, 0xac, 0x7c, 0x2f, 0x21, 0xef, 0x3b, 0xcc, 0x91, 0x7b, 0xc9, 0xc5, 0xaf, 0x56, 0xf4, 0xfd, 0x77, 0xeb, 0x6e, 0x6d, 0xdb, 0xa4, 0x0b, 0x69, 0xf2, 0x09, 0xef, 0x85, 0x32, 0x13, 0x5a, 0x19, 0x50, 0x66, 0x6c, 0xe2, 0xb5, 0x6b, 0xfc, 0xbc, 0x4c, 0x7f, 0x31, 0xeb, 0xf5, 0xae, 0xfc, 0x7c, 0xdb, 0xac, 0xf4, 0xd3, 0x5d, 0xb1, 0x82, 0x93, 0x0c, 0x2f, 0xb0, 0xac, 0x04, 0xcb, 0x73, 0x6e, 0x79, 0xdc, 0x70, 0xbe, 0xf4, 0x86, 0x9c, 0xe1, 0x4a, 0xaf, 0x02, 0xab, 0xb7, 0x5e, 0x79, 0xa7, 0xcd, 0xa0, 0xb6, 0x80, 0xc9, 0x21, 0xde, 0x53, 0xdc, 0xca, 0x09, 0x64, 0xe2, 0x8c, 0x4b, 0x95, 0x29, 0x5e, 0x42, 0xbc, 0xd1, 0x46, 0xdd, 0xed, 0xb4, 0xe9, 0x1b, 0xfd, 0x0a, 0x7f, 0xcd, 0x4b, 0x20, 0xa7, 0x78, 0x6b, 0x04, 0x43, 0x3e, 0x85, 0x91, 0x89, 0x37, 0xdd, 0x12, 0x8f, 0x6e, 0x58, 0x22, 0x0d, 0xe3, 0xc1, 0x7d, 0x49, 0xef, 0x3c, 0xc7, 0xcd, 0x95, 0x05, 0xc9, 0x2e, 0x6e, 0x7c, 0x84, 0x69, 0x8c, 0xda, 0xa8, 0xbb, 0x93, 0x56, 0x25, 0xd9, 0xc7, 0x1b, 0x13, 0x3e, 0x1c, 0x43, 0xbc, 0xe6, 0x30, 0xff, 0xe3, 0xe9, 0xfa, 0x97, 0x6f, 0xad, 0xa8, 0xf3, 0x19, 0xe1, 0x7b, 0xff, 0x0d, 0x4b, 0xee, 0x63, 0xfc, 0x4f, 0x1c, 0xe4, 0xe2, 0x6c, 0x8b, 0x65, 0x90, 0x17, 0x78, 0x6b, 0x79, 0x4d, 0xff, 0x2f, 0x3e, 0xac, 0x0d, 0x52, 0x7f, 0xc3, 0x25, 0xb7, 0xf7, 0xf6, 0x62, 0x96, 0xa0, 0xcb, 0x59, 0x82, 0xfe, 0xcc, 0x12, 0xf4, 0x75, 0x9e, 0x44, 0x97, 0xf3, 0x24, 0xfa, 0x39, 0x4f, 0xa2, 0x77, 0xcf, 0x0a, 0x69, 0xcf, 0xc6, 0x03, 0x2a, 0x74, 0xc9, 0x06, 0x92, 0xab, 0x0f, 0x12, 0xb8, 0x64, 0x95, 0xc7, 0x51, 0xa1, 0x59, 0xa9, 0xf3, 0xf1, 0x10, 0x0c, 0xbb, 0x7a, 0x04, 0x8f, 0x4f, 0x8e, 0xc2, 0x3b, 0xb0, 0xd3, 0x73, 0x30, 0x83, 0x4d, 0xf7, 0xb9, 0x3f, 0xf9, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x2f, 0x75, 0xdc, 0xde, 0x60, 0x03, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Relayers) > 0 { for iNdEx := len(m.Relayers) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Relayers[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x32 } } if len(m.NativeChainName) > 0 { i -= len(m.NativeChainName) copy(dAtA[i:], m.NativeChainName) i = encodeVarintGenesis(dAtA, i, uint64(len(m.NativeChainName))) i-- dAtA[i] = 0x2a } if len(m.ClientsMetadata) > 0 { for iNdEx := len(m.ClientsMetadata) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.ClientsMetadata[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } } if len(m.ClientsConsensus) > 0 { for iNdEx := len(m.ClientsConsensus) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.ClientsConsensus[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } if len(m.Clients) > 0 { for iNdEx := len(m.Clients) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Clients[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *GenesisMetadata) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *GenesisMetadata) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *GenesisMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Value) > 0 { i -= len(m.Value) copy(dAtA[i:], m.Value) i = encodeVarintGenesis(dAtA, i, uint64(len(m.Value))) i-- dAtA[i] = 0x12 } if len(m.Key) > 0 { i -= len(m.Key) copy(dAtA[i:], m.Key) i = encodeVarintGenesis(dAtA, i, uint64(len(m.Key))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *IdentifiedGenesisMetadata) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *IdentifiedGenesisMetadata) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *IdentifiedGenesisMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Metadata) > 0 { for iNdEx := len(m.Metadata) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Metadata[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } if len(m.ChainName) > 0 { i -= len(m.ChainName) copy(dAtA[i:], m.ChainName) i = encodeVarintGenesis(dAtA, i, uint64(len(m.ChainName))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { offset -= sovGenesis(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *GenesisState) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Clients) > 0 { for _, e := range m.Clients { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.ClientsConsensus) > 0 { for _, e := range m.ClientsConsensus { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.ClientsMetadata) > 0 { for _, e := range m.ClientsMetadata { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } l = len(m.NativeChainName) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } if len(m.Relayers) > 0 { for _, e := range m.Relayers { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } return n } func (m *GenesisMetadata) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Key) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } l = len(m.Value) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } return n } func (m *IdentifiedGenesisMetadata) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.ChainName) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } if len(m.Metadata) > 0 { for _, e := range m.Metadata { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } return n } func sovGenesis(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozGenesis(x uint64) (n int) { return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *GenesisState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Clients", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Clients = append(m.Clients, IdentifiedClientState{}) if err := m.Clients[len(m.Clients)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientsConsensus", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.ClientsConsensus = append(m.ClientsConsensus, ClientConsensusStates{}) if err := m.ClientsConsensus[len(m.ClientsConsensus)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientsMetadata", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.ClientsMetadata = append(m.ClientsMetadata, IdentifiedGenesisMetadata{}) if err := m.ClientsMetadata[len(m.ClientsMetadata)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field NativeChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.NativeChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Relayers", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Relayers = append(m.Relayers, IdentifiedRelayers{}) if err := m.Relayers[len(m.Relayers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenesis } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *GenesisMetadata) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: GenesisMetadata: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: GenesisMetadata: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) if m.Key == nil { m.Key = []byte{} } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) if m.Value == nil { m.Value = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenesis } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *IdentifiedGenesisMetadata) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: IdentifiedGenesisMetadata: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: IdentifiedGenesisMetadata: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ChainName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.ChainName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Metadata = append(m.Metadata, GenesisMetadata{}) if err := m.Metadata[len(m.Metadata)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenesis } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenesis(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthGenesis } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupGenesis } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthGenesis } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/23-commitment/types/errors.go<|end_filename|> package types import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) // SubModuleName is the error codespace const SubModuleName string = "commitment" const moduleName = host.ModuleName + "-" + SubModuleName // TIBC connection sentinel errors var ( ErrInvalidProof = sdkerrors.Register(moduleName, 2, "invalid proof") ErrInvalidPrefix = sdkerrors.Register(moduleName, 3, "invalid prefix") ErrInvalidMerkleProof = sdkerrors.Register(moduleName, 4, "invalid merkle proof") ) <|start_filename|>modules/tibc/core/02-client/types/metrics.go<|end_filename|> package types // Prometheus metric labels. const ( LabelClientType = "client_type" LabelChainName = "chain_name" LabelUpdateType = "update_type" LabelMsgType = "msg_type" ) <|start_filename|>modules/tibc/apps/nft_transfer/handler.go<|end_filename|> package nft_transfer import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/bianjieai/tibc-go/modules/tibc/apps/nft_transfer/keeper" nfttransfertypes "github.com/bianjieai/tibc-go/modules/tibc/apps/nft_transfer/types" ) // NewHandler defines the TIBC nft transfer handler func NewHandler(k keeper.Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { case *nfttransfertypes.MsgNftTransfer: res, err := k.NftTransfer(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) default: return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized TIBC message type: %T", msg) } } } <|start_filename|>modules/tibc/core/simulation/decoder.go<|end_filename|> package simulation import ( "fmt" "github.com/cosmos/cosmos-sdk/types/kv" clientsim "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/simulation" packetsim "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/simulation" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" "github.com/bianjieai/tibc-go/modules/tibc/core/keeper" ) // NewDecodeStore returns a decoder function closure that unmarshals the KVPair's // Value to the corresponding tibc type. func NewDecodeStore(k keeper.Keeper) func(kvA, kvB kv.Pair) string { return func(kvA, kvB kv.Pair) string { if res, found := clientsim.NewDecodeStore(k.ClientKeeper, kvA, kvB); found { return res } if res, found := packetsim.NewDecodeStore(k.Codec(), kvA, kvB); found { return res } panic(fmt.Sprintf("invalid %s key prefix: %s", host.ModuleName, string(kvA.Key))) } } <|start_filename|>modules/tibc/core/04-packet/types/events.go<|end_filename|> package types import ( "fmt" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) // TIBC packet events const ( EventTypeSendPacket = "send_packet" EventTypeRecvPacket = "recv_packet" EventTypeWriteAck = "write_acknowledgement" EventTypeAcknowledgePacket = "acknowledge_packet" EventTypeSendCleanPacket = "send_clean_packet" EventTypeRecvCleanPacket = "recv_clean_packet" AttributeKeyData = "packet_data" AttributeKeyAck = "packet_ack" AttributeKeySequence = "packet_sequence" AttributeKeyPort = "packet_port" AttributeKeySrcChain = "packet_src_chain" AttributeKeyDstChain = "packet_dst_port" AttributeKeyRelayChain = "packet_relay_channel" ) // tibc packet events vars var ( AttributeValueCategory = fmt.Sprintf("%s_%s", host.ModuleName, SubModuleName) ) <|start_filename|>modules/tibc/core/keeper/grpc_query.go<|end_filename|> package keeper import ( "context" clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" packettypes "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" routingtypes "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // ClientState implements the TIBC QueryServer interface func (q Keeper) ClientState(c context.Context, req *clienttypes.QueryClientStateRequest) (*clienttypes.QueryClientStateResponse, error) { return q.ClientKeeper.ClientState(c, req) } // ClientStates implements the TIBC QueryServer interface func (q Keeper) ClientStates(c context.Context, req *clienttypes.QueryClientStatesRequest) (*clienttypes.QueryClientStatesResponse, error) { return q.ClientKeeper.ClientStates(c, req) } // ConsensusState implements the TIBC QueryServer interface func (q Keeper) ConsensusState(c context.Context, req *clienttypes.QueryConsensusStateRequest) (*clienttypes.QueryConsensusStateResponse, error) { return q.ClientKeeper.ConsensusState(c, req) } // ConsensusStates implements the TIBC QueryServer interface func (q Keeper) ConsensusStates(c context.Context, req *clienttypes.QueryConsensusStatesRequest) (*clienttypes.QueryConsensusStatesResponse, error) { return q.ClientKeeper.ConsensusStates(c, req) } // PacketCommitment implements the TIBC QueryServer interface func (q Keeper) PacketCommitment(c context.Context, req *packettypes.QueryPacketCommitmentRequest) (*packettypes.QueryPacketCommitmentResponse, error) { return q.PacketKeeper.PacketCommitment(c, req) } // PacketCommitments implements the TIBC QueryServer interface func (q Keeper) PacketCommitments(c context.Context, req *packettypes.QueryPacketCommitmentsRequest) (*packettypes.QueryPacketCommitmentsResponse, error) { return q.PacketKeeper.PacketCommitments(c, req) } // PacketReceipt implements the TIBC QueryServer interface func (q Keeper) PacketReceipt(c context.Context, req *packettypes.QueryPacketReceiptRequest) (*packettypes.QueryPacketReceiptResponse, error) { return q.PacketKeeper.PacketReceipt(c, req) } // PacketAcknowledgement implements the TIBC QueryServer interface func (q Keeper) PacketAcknowledgement(c context.Context, req *packettypes.QueryPacketAcknowledgementRequest) (*packettypes.QueryPacketAcknowledgementResponse, error) { return q.PacketKeeper.PacketAcknowledgement(c, req) } // PacketAcknowledgements implements the TIBC QueryServer interface func (q Keeper) PacketAcknowledgements(c context.Context, req *packettypes.QueryPacketAcknowledgementsRequest) (*packettypes.QueryPacketAcknowledgementsResponse, error) { return q.PacketKeeper.PacketAcknowledgements(c, req) } // UnreceivedPackets implements the TIBC QueryServer interface func (q Keeper) UnreceivedPackets(c context.Context, req *packettypes.QueryUnreceivedPacketsRequest) (*packettypes.QueryUnreceivedPacketsResponse, error) { return q.PacketKeeper.UnreceivedPackets(c, req) } // UnreceivedAcks implements the TIBC QueryServer interface func (q Keeper) UnreceivedAcks(c context.Context, req *packettypes.QueryUnreceivedAcksRequest) (*packettypes.QueryUnreceivedAcksResponse, error) { return q.PacketKeeper.UnreceivedAcks(c, req) } // CleanPacketCommitment implements the TIBC QueryServer interface func (q Keeper) CleanPacketCommitment(c context.Context, req *packettypes.QueryCleanPacketCommitmentRequest) (*packettypes.QueryCleanPacketCommitmentResponse, error) { return q.PacketKeeper.CleanPacketCommitment(c, req) } // RoutingRules implements the TIBC QueryServer interface func (q Keeper) RoutingRules(c context.Context, req *routingtypes.QueryRoutingRulesRequest) (*routingtypes.QueryRoutingRulesResponse, error) { return q.RoutingKeeper.RoutingRules(c, req) } func (q Keeper) Relayers(c context.Context, req *clienttypes.QueryRelayersRequest) (*clienttypes.QueryRelayersResponse, error) { return q.ClientKeeper.Relayers(c, req) } <|start_filename|>modules/tibc/core/types/genesis.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/types/v1/genesis.proto package types import ( fmt "fmt" types "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" types1 "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" types2 "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // GenesisState defines the tibc module's genesis state. type GenesisState struct { // TICS002 - Clients genesis state ClientGenesis types.GenesisState `protobuf:"bytes,1,opt,name=client_genesis,json=clientGenesis,proto3" json:"client_genesis" yaml:"client_genesis"` // TICS004 - Packet genesis state PacketGenesis types1.GenesisState `protobuf:"bytes,3,opt,name=packet_genesis,json=packetGenesis,proto3" json:"packet_genesis" yaml:"packet_genesis"` // TICS026 - Routing genesis state RoutingGenesis types2.GenesisState `protobuf:"bytes,4,opt,name=routing_genesis,json=routingGenesis,proto3" json:"routing_genesis" yaml:"routing_genesis"` } func (m *GenesisState) Reset() { *m = GenesisState{} } func (m *GenesisState) String() string { return proto.CompactTextString(m) } func (*GenesisState) ProtoMessage() {} func (*GenesisState) Descriptor() ([]byte, []int) { return fileDescriptor_7379bcbeb8a4fd03, []int{0} } func (m *GenesisState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *GenesisState) XXX_Merge(src proto.Message) { xxx_messageInfo_GenesisState.Merge(m, src) } func (m *GenesisState) XXX_Size() int { return m.Size() } func (m *GenesisState) XXX_DiscardUnknown() { xxx_messageInfo_GenesisState.DiscardUnknown(m) } var xxx_messageInfo_GenesisState proto.InternalMessageInfo func (m *GenesisState) GetClientGenesis() types.GenesisState { if m != nil { return m.ClientGenesis } return types.GenesisState{} } func (m *GenesisState) GetPacketGenesis() types1.GenesisState { if m != nil { return m.PacketGenesis } return types1.GenesisState{} } func (m *GenesisState) GetRoutingGenesis() types2.GenesisState { if m != nil { return m.RoutingGenesis } return types2.GenesisState{} } func init() { proto.RegisterType((*GenesisState)(nil), "tibc.core.types.v1.GenesisState") } func init() { proto.RegisterFile("tibc/core/types/v1/genesis.proto", fileDescriptor_7379bcbeb8a4fd03) } var fileDescriptor_7379bcbeb8a4fd03 = []byte{ // 314 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x92, 0x31, 0x4e, 0xf3, 0x30, 0x18, 0x86, 0x93, 0xff, 0x47, 0x0c, 0x81, 0x16, 0x29, 0x02, 0x84, 0x2a, 0xe1, 0xb6, 0x9e, 0x58, 0xb0, 0x15, 0x60, 0x62, 0xec, 0xc2, 0xc6, 0x10, 0x36, 0x16, 0x94, 0x18, 0xcb, 0x98, 0x26, 0x71, 0x94, 0x38, 0x91, 0x7a, 0x0b, 0x8e, 0xd5, 0x05, 0xa9, 0x23, 0x53, 0x85, 0x92, 0x1b, 0x70, 0x02, 0xe4, 0xd8, 0x34, 0x69, 0x83, 0xc4, 0x16, 0xbd, 0x79, 0xbe, 0xf7, 0xf9, 0x2c, 0xdb, 0x99, 0x48, 0x1e, 0x12, 0x4c, 0x44, 0x46, 0xb1, 0x5c, 0xa4, 0x34, 0xc7, 0xa5, 0x87, 0x19, 0x4d, 0x68, 0xce, 0x73, 0x94, 0x66, 0x42, 0x0a, 0xd7, 0x55, 0x04, 0x52, 0x04, 0x6a, 0x08, 0x54, 0x7a, 0xa3, 0x63, 0x26, 0x98, 0x68, 0x7e, 0x63, 0xf5, 0xa5, 0xc9, 0xd1, 0xb4, 0xed, 0x22, 0x11, 0xa7, 0x89, 0xec, 0x95, 0x75, 0x91, 0x34, 0x20, 0x73, 0xfa, 0x0b, 0x02, 0x5b, 0x24, 0x13, 0x85, 0xe4, 0x09, 0xeb, 0x31, 0xf0, 0xfd, 0x9f, 0x73, 0x78, 0xa7, 0x93, 0x07, 0x19, 0x48, 0xea, 0x32, 0x67, 0xa8, 0x95, 0x4f, 0x06, 0x3c, 0xb3, 0x27, 0xf6, 0xc5, 0xc1, 0xd5, 0x14, 0xb5, 0xdb, 0x6b, 0x00, 0x95, 0x1e, 0xea, 0x8e, 0xce, 0xce, 0x97, 0xeb, 0xb1, 0xf5, 0xb5, 0x1e, 0x9f, 0x2c, 0x82, 0x38, 0xba, 0x85, 0xdb, 0x35, 0xd0, 0x1f, 0xe8, 0xc0, 0x8c, 0x28, 0x91, 0x5e, 0x7c, 0x23, 0xfa, 0xdf, 0x13, 0x69, 0xe0, 0x2f, 0xd1, 0x76, 0x0d, 0xf4, 0x07, 0x3a, 0xf8, 0x11, 0xcd, 0x9d, 0x23, 0x73, 0xfc, 0x8d, 0x69, 0xaf, 0x31, 0xc1, 0x8e, 0xc9, 0x10, 0x3d, 0x15, 0x30, 0xaa, 0x53, 0xad, 0xda, 0x29, 0x82, 0xfe, 0xd0, 0x24, 0x66, 0x68, 0x76, 0xbf, 0xac, 0x80, 0xbd, 0xaa, 0x80, 0xfd, 0x59, 0x01, 0xfb, 0xad, 0x06, 0xd6, 0xaa, 0x06, 0xd6, 0x47, 0x0d, 0xac, 0xc7, 0x1b, 0xc6, 0xe5, 0x4b, 0x11, 0x22, 0x22, 0x62, 0x1c, 0xf2, 0x20, 0x79, 0xe5, 0x34, 0xe0, 0x58, 0x6d, 0x70, 0xc9, 0x04, 0x8e, 0xc5, 0x73, 0x11, 0xd1, 0x1c, 0xef, 0x3c, 0xa2, 0x70, 0xbf, 0xb9, 0xa6, 0xeb, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x10, 0x14, 0xc4, 0x15, 0x5e, 0x02, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.RoutingGenesis.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 { size, err := m.PacketGenesis.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a { size, err := m.ClientGenesis.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { offset -= sovGenesis(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *GenesisState) Size() (n int) { if m == nil { return 0 } var l int _ = l l = m.ClientGenesis.Size() n += 1 + l + sovGenesis(uint64(l)) l = m.PacketGenesis.Size() n += 1 + l + sovGenesis(uint64(l)) l = m.RoutingGenesis.Size() n += 1 + l + sovGenesis(uint64(l)) return n } func sovGenesis(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozGenesis(x uint64) (n int) { return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *GenesisState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClientGenesis", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ClientGenesis.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field PacketGenesis", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.PacketGenesis.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RoutingGenesis", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.RoutingGenesis.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenesis } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenesis(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthGenesis } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupGenesis } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthGenesis } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/testing/config.go<|end_filename|> package tibctesting import ( "time" "github.com/bianjieai/tibc-go/modules/tibc/core/exported" ibctmtypes "github.com/bianjieai/tibc-go/modules/tibc/light-clients/07-tendermint/types" ) type ClientConfig interface { GetClientType() string } type TendermintConfig struct { TrustLevel ibctmtypes.Fraction TrustingPeriod time.Duration UnbondingPeriod time.Duration MaxClockDrift time.Duration AllowUpdateAfterExpiry bool AllowUpdateAfterMisbehaviour bool } func NewTendermintConfig() *TendermintConfig { return &TendermintConfig{ TrustLevel: DefaultTrustLevel, TrustingPeriod: TrustingPeriod, UnbondingPeriod: UnbondingPeriod, MaxClockDrift: MaxClockDrift, AllowUpdateAfterExpiry: false, AllowUpdateAfterMisbehaviour: false, } } func (tmcfg *TendermintConfig) GetClientType() string { return exported.Tendermint } <|start_filename|>modules/tibc/core/26-routing/client/cli/tx.go<|end_filename|> package cli import ( "encoding/json" "io/ioutil" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/bianjieai/tibc-go/modules/tibc/core/26-routing/types" ) // NewSetRoutingRulesProposalCmd implements a command handler for submitting a setting rules proposal transaction. func NewSetRoutingRulesProposalCmd() *cobra.Command { cmd := &cobra.Command{ Use: "set-rules [path/to/routing_rules.json] [flags]", Args: cobra.ExactArgs(1), Short: "Submit a rules set proposal", Long: "set routing rules", RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } routingRulesBz, err := ioutil.ReadFile(args[0]) if err != nil { return errors.Wrap(err, "neither JSON input nor path to .json file for routing rules were provided") } var rules []string if err := json.Unmarshal(routingRulesBz, &rules); err != nil { return errors.Wrap(err, "error unmarshalling rules file") } title, err := cmd.Flags().GetString(cli.FlagTitle) if err != nil { return err } description, err := cmd.Flags().GetString(cli.FlagDescription) if err != nil { return err } content, err := types.NewSetRoutingRulesProposal(title, description, rules) if err != nil { return err } depositStr, err := cmd.Flags().GetString(cli.FlagDeposit) if err != nil { return err } deposit, err := sdk.ParseCoinsNormalized(depositStr) if err != nil { return err } msg, err := govtypes.NewMsgSubmitProposal(content, deposit, clientCtx.GetFromAddress()) if err != nil { return err } if err = msg.ValidateBasic(); err != nil { return err } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } cmd.Flags().String(cli.FlagTitle, "", "title of proposal") cmd.Flags().String(cli.FlagDescription, "", "description of proposal") cmd.Flags().String(cli.FlagDeposit, "", "deposit of proposal") return cmd } <|start_filename|>modules/tibc/core/04-packet/simulation/genesis.go<|end_filename|> package simulation import ( "math/rand" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/bianjieai/tibc-go/modules/tibc/core/04-packet/types" ) // GenpacketGenesis returns the default packet genesis state. func GenpacketGenesis(_ *rand.Rand, _ []simtypes.Account) types.GenesisState { return types.DefaultGenesisState() } <|start_filename|>modules/tibc/core/04-packet/types/query.go<|end_filename|> package types import ( clienttypes "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" ) // NewQueryPacketCommitmentResponse creates a new QueryPacketCommitmentResponse instance func NewQueryPacketCommitmentResponse( commitment []byte, proof []byte, height clienttypes.Height, ) *QueryPacketCommitmentResponse { return &QueryPacketCommitmentResponse{ Commitment: commitment, Proof: proof, ProofHeight: height, } } // NewQueryPacketReceiptResponse creates a new QueryPacketReceiptResponse instance func NewQueryPacketReceiptResponse( recvd bool, proof []byte, height clienttypes.Height, ) *QueryPacketReceiptResponse { return &QueryPacketReceiptResponse{ Received: recvd, Proof: proof, ProofHeight: height, } } // NewQueryPacketAcknowledgementResponse creates a new QueryPacketAcknowledgementResponse instance func NewQueryPacketAcknowledgementResponse( acknowledgement []byte, proof []byte, height clienttypes.Height, ) *QueryPacketAcknowledgementResponse { return &QueryPacketAcknowledgementResponse{ Acknowledgement: acknowledgement, Proof: proof, ProofHeight: height, } } // NewQueryCleanPacketCommitmentResponse creates a new NewQueryCleanPacketCommitmentResponse instance func NewQueryCleanPacketCommitmentResponse( commitment []byte, proof []byte, height clienttypes.Height, ) *QueryCleanPacketCommitmentResponse { return &QueryCleanPacketCommitmentResponse{ Commitment: commitment, Proof: proof, ProofHeight: height, } } <|start_filename|>modules/tibc/light-clients/09-eth/module.go<|end_filename|> package eth import "github.com/bianjieai/tibc-go/modules/tibc/light-clients/09-eth/types" // Name returns the TIBC eth client name func Name() string { return types.SubModuleName } <|start_filename|>modules/tibc/core/26-routing/types/errors.go<|end_filename|> package types import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) const moduleName = host.ModuleName + "-" + SubModuleName // TIBC routing sentinel errors var ( ErrInvalidRoute = sdkerrors.Register(moduleName, 2, "route not found") ErrInvalidRule = sdkerrors.Register(moduleName, 3, "invalid rule") ErrFailMarshalRules = sdkerrors.Register(moduleName, 4, "failed to marshal rules") ErrFailUnmarshalRules = sdkerrors.Register(moduleName, 5, "failed to unmarshal rules") ErrRoutingRulesNotFound = sdkerrors.Register(moduleName, 6, "routing rules not found") ) <|start_filename|>modules/tibc/core/04-packet/types/genesis.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/packet/v1/genesis.proto package types import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // GenesisState defines the tibc channel submodule's genesis state. type GenesisState struct { Acknowledgements []PacketState `protobuf:"bytes,2,rep,name=acknowledgements,proto3" json:"acknowledgements"` Commitments []PacketState `protobuf:"bytes,3,rep,name=commitments,proto3" json:"commitments"` Receipts []PacketState `protobuf:"bytes,4,rep,name=receipts,proto3" json:"receipts"` SendSequences []PacketSequence `protobuf:"bytes,5,rep,name=send_sequences,json=sendSequences,proto3" json:"send_sequences" yaml:"send_sequences"` RecvSequences []PacketSequence `protobuf:"bytes,6,rep,name=recv_sequences,json=recvSequences,proto3" json:"recv_sequences" yaml:"recv_sequences"` AckSequences []PacketSequence `protobuf:"bytes,7,rep,name=ack_sequences,json=ackSequences,proto3" json:"ack_sequences" yaml:"ack_sequences"` } func (m *GenesisState) Reset() { *m = GenesisState{} } func (m *GenesisState) String() string { return proto.CompactTextString(m) } func (*GenesisState) ProtoMessage() {} func (*GenesisState) Descriptor() ([]byte, []int) { return fileDescriptor_0ac7d6194d8bf289, []int{0} } func (m *GenesisState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *GenesisState) XXX_Merge(src proto.Message) { xxx_messageInfo_GenesisState.Merge(m, src) } func (m *GenesisState) XXX_Size() int { return m.Size() } func (m *GenesisState) XXX_DiscardUnknown() { xxx_messageInfo_GenesisState.DiscardUnknown(m) } var xxx_messageInfo_GenesisState proto.InternalMessageInfo func (m *GenesisState) GetAcknowledgements() []PacketState { if m != nil { return m.Acknowledgements } return nil } func (m *GenesisState) GetCommitments() []PacketState { if m != nil { return m.Commitments } return nil } func (m *GenesisState) GetReceipts() []PacketState { if m != nil { return m.Receipts } return nil } func (m *GenesisState) GetSendSequences() []PacketSequence { if m != nil { return m.SendSequences } return nil } func (m *GenesisState) GetRecvSequences() []PacketSequence { if m != nil { return m.RecvSequences } return nil } func (m *GenesisState) GetAckSequences() []PacketSequence { if m != nil { return m.AckSequences } return nil } // PacketSequence defines the genesis type necessary to retrieve and store // next send and receive sequences. type PacketSequence struct { SourceChain string `protobuf:"bytes,1,opt,name=source_chain,json=sourceChain,proto3" json:"source_chain,omitempty" yaml:"source_chain"` DestinationChain string `protobuf:"bytes,2,opt,name=destination_chain,json=destinationChain,proto3" json:"destination_chain,omitempty" yaml:"destination_chain"` Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` } func (m *PacketSequence) Reset() { *m = PacketSequence{} } func (m *PacketSequence) String() string { return proto.CompactTextString(m) } func (*PacketSequence) ProtoMessage() {} func (*PacketSequence) Descriptor() ([]byte, []int) { return fileDescriptor_0ac7d6194d8bf289, []int{1} } func (m *PacketSequence) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *PacketSequence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_PacketSequence.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *PacketSequence) XXX_Merge(src proto.Message) { xxx_messageInfo_PacketSequence.Merge(m, src) } func (m *PacketSequence) XXX_Size() int { return m.Size() } func (m *PacketSequence) XXX_DiscardUnknown() { xxx_messageInfo_PacketSequence.DiscardUnknown(m) } var xxx_messageInfo_PacketSequence proto.InternalMessageInfo func (m *PacketSequence) GetSourceChain() string { if m != nil { return m.SourceChain } return "" } func (m *PacketSequence) GetDestinationChain() string { if m != nil { return m.DestinationChain } return "" } func (m *PacketSequence) GetSequence() uint64 { if m != nil { return m.Sequence } return 0 } func init() { proto.RegisterType((*GenesisState)(nil), "tibc.core.packet.v1.GenesisState") proto.RegisterType((*PacketSequence)(nil), "tibc.core.packet.v1.PacketSequence") } func init() { proto.RegisterFile("tibc/core/packet/v1/genesis.proto", fileDescriptor_0ac7d6194d8bf289) } var fileDescriptor_0ac7d6194d8bf289 = []byte{ // 454 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0xc1, 0x6e, 0xd3, 0x30, 0x18, 0xc7, 0x9b, 0xb5, 0x8c, 0xe1, 0xb6, 0xd3, 0xc8, 0x86, 0x88, 0xaa, 0x91, 0x86, 0x70, 0xe9, 0x65, 0x31, 0x03, 0x4e, 0x3b, 0x70, 0x08, 0x07, 0xe0, 0x86, 0xcc, 0x05, 0x71, 0x99, 0x5c, 0xf7, 0x23, 0x33, 0x6d, 0xec, 0x12, 0xbb, 0x45, 0x7b, 0x0b, 0x9e, 0x84, 0x0b, 0x2f, 0xb1, 0xe3, 0x8e, 0x9c, 0x2a, 0xd4, 0xbe, 0x41, 0x9f, 0x00, 0xd9, 0xce, 0xba, 0x54, 0x9b, 0x10, 0xdd, 0x2d, 0xfe, 0xfc, 0xff, 0xff, 0x7e, 0x91, 0xa5, 0x0f, 0x3d, 0xd5, 0xbc, 0xcf, 0x30, 0x93, 0x05, 0xe0, 0x31, 0x65, 0x43, 0xd0, 0x78, 0x7a, 0x8c, 0x33, 0x10, 0xa0, 0xb8, 0x4a, 0xc6, 0x85, 0xd4, 0xd2, 0xdf, 0x37, 0x91, 0xc4, 0x44, 0x12, 0x17, 0x49, 0xa6, 0xc7, 0x9d, 0x83, 0x4c, 0x66, 0xd2, 0xde, 0x63, 0xf3, 0xe5, 0xa2, 0x9d, 0xe8, 0x36, 0x5a, 0x59, 0xb2, 0x89, 0xf8, 0x67, 0x03, 0xb5, 0xde, 0x3a, 0xfc, 0x47, 0x4d, 0x35, 0xf8, 0x04, 0xed, 0x51, 0x36, 0x14, 0xf2, 0xfb, 0x08, 0x06, 0x19, 0xe4, 0x20, 0xb4, 0x0a, 0xb6, 0xa2, 0x7a, 0xaf, 0xf9, 0x22, 0x4a, 0x6e, 0x11, 0x27, 0x1f, 0xec, 0x97, 0xed, 0xa6, 0x8d, 0x8b, 0x59, 0xb7, 0x46, 0x6e, 0xf4, 0xfd, 0x77, 0xa8, 0xc9, 0x64, 0x9e, 0x73, 0xed, 0x70, 0xf5, 0x8d, 0x70, 0xd5, 0xaa, 0x9f, 0xa2, 0x9d, 0x02, 0x18, 0xf0, 0xb1, 0x56, 0x41, 0x63, 0x23, 0xcc, 0xaa, 0xe7, 0x73, 0xb4, 0xab, 0x40, 0x0c, 0x4e, 0x15, 0x7c, 0x9b, 0x80, 0x60, 0xa0, 0x82, 0x7b, 0x96, 0xf4, 0xec, 0x5f, 0xa4, 0x32, 0x9b, 0x3e, 0x31, 0xb0, 0xe5, 0xac, 0xfb, 0xe8, 0x9c, 0xe6, 0xa3, 0x93, 0x78, 0x1d, 0x14, 0x93, 0xb6, 0x19, 0x5c, 0x85, 0xad, 0xaa, 0x00, 0x36, 0xad, 0xa8, 0xb6, 0xef, 0xac, 0x5a, 0x07, 0xc5, 0xa4, 0x6d, 0x06, 0xd7, 0xaa, 0x2f, 0xa8, 0x4d, 0xd9, 0xb0, 0x62, 0xba, 0xff, 0xff, 0xa6, 0xc3, 0xd2, 0x74, 0xe0, 0x4c, 0x6b, 0x9c, 0x98, 0xb4, 0x28, 0x1b, 0xae, 0x3c, 0xf1, 0x2f, 0x0f, 0xed, 0xae, 0xd7, 0xfd, 0x13, 0xd4, 0x52, 0x72, 0x52, 0x30, 0x38, 0x65, 0x67, 0x94, 0x8b, 0xc0, 0x8b, 0xbc, 0xde, 0x83, 0xf4, 0xf1, 0x72, 0xd6, 0xdd, 0x2f, 0x5f, 0xa9, 0x72, 0x1b, 0x93, 0xa6, 0x3b, 0xbe, 0x31, 0x27, 0xff, 0x3d, 0x7a, 0x38, 0x00, 0xa5, 0xb9, 0xa0, 0x9a, 0x4b, 0x51, 0x02, 0xb6, 0x2c, 0xe0, 0x70, 0x39, 0xeb, 0x06, 0x0e, 0x70, 0x23, 0x12, 0x93, 0xbd, 0xca, 0xcc, 0xa1, 0x3a, 0x68, 0xe7, 0xea, 0xaf, 0x83, 0x7a, 0xe4, 0xf5, 0x1a, 0x64, 0x75, 0x4e, 0x3f, 0x5d, 0xcc, 0x43, 0xef, 0x72, 0x1e, 0x7a, 0x7f, 0xe6, 0xa1, 0xf7, 0x63, 0x11, 0xd6, 0x2e, 0x17, 0x61, 0xed, 0xf7, 0x22, 0xac, 0x7d, 0x7e, 0x9d, 0x71, 0x7d, 0x36, 0xe9, 0x27, 0x4c, 0xe6, 0xb8, 0xcf, 0xa9, 0xf8, 0xca, 0x81, 0x72, 0x6c, 0x1e, 0xed, 0x28, 0x93, 0x38, 0x97, 0x83, 0xc9, 0x08, 0x14, 0xbe, 0xde, 0xa3, 0xe7, 0xaf, 0x8e, 0xca, 0x55, 0xd2, 0xe7, 0x63, 0x50, 0xfd, 0x6d, 0xbb, 0x47, 0x2f, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x23, 0x33, 0x44, 0x2a, 0xb9, 0x03, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.AckSequences) > 0 { for iNdEx := len(m.AckSequences) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.AckSequences[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x3a } } if len(m.RecvSequences) > 0 { for iNdEx := len(m.RecvSequences) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.RecvSequences[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x32 } } if len(m.SendSequences) > 0 { for iNdEx := len(m.SendSequences) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.SendSequences[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x2a } } if len(m.Receipts) > 0 { for iNdEx := len(m.Receipts) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Receipts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 } } if len(m.Commitments) > 0 { for iNdEx := len(m.Commitments) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Commitments[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a } } if len(m.Acknowledgements) > 0 { for iNdEx := len(m.Acknowledgements) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Acknowledgements[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 } } return len(dAtA) - i, nil } func (m *PacketSequence) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *PacketSequence) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *PacketSequence) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.Sequence != 0 { i = encodeVarintGenesis(dAtA, i, uint64(m.Sequence)) i-- dAtA[i] = 0x18 } if len(m.DestinationChain) > 0 { i -= len(m.DestinationChain) copy(dAtA[i:], m.DestinationChain) i = encodeVarintGenesis(dAtA, i, uint64(len(m.DestinationChain))) i-- dAtA[i] = 0x12 } if len(m.SourceChain) > 0 { i -= len(m.SourceChain) copy(dAtA[i:], m.SourceChain) i = encodeVarintGenesis(dAtA, i, uint64(len(m.SourceChain))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { offset -= sovGenesis(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *GenesisState) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Acknowledgements) > 0 { for _, e := range m.Acknowledgements { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.Commitments) > 0 { for _, e := range m.Commitments { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.Receipts) > 0 { for _, e := range m.Receipts { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.SendSequences) > 0 { for _, e := range m.SendSequences { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.RecvSequences) > 0 { for _, e := range m.RecvSequences { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } if len(m.AckSequences) > 0 { for _, e := range m.AckSequences { l = e.Size() n += 1 + l + sovGenesis(uint64(l)) } } return n } func (m *PacketSequence) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.SourceChain) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } l = len(m.DestinationChain) if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } if m.Sequence != 0 { n += 1 + sovGenesis(uint64(m.Sequence)) } return n } func sovGenesis(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozGenesis(x uint64) (n int) { return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *GenesisState) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Acknowledgements", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Acknowledgements = append(m.Acknowledgements, PacketState{}) if err := m.Acknowledgements[len(m.Acknowledgements)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Commitments", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Commitments = append(m.Commitments, PacketState{}) if err := m.Commitments[len(m.Commitments)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Receipts", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.Receipts = append(m.Receipts, PacketState{}) if err := m.Receipts[len(m.Receipts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SendSequences", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.SendSequences = append(m.SendSequences, PacketSequence{}) if err := m.SendSequences[len(m.SendSequences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RecvSequences", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.RecvSequences = append(m.RecvSequences, PacketSequence{}) if err := m.RecvSequences[len(m.RecvSequences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field AckSequences", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.AckSequences = append(m.AckSequences, PacketSequence{}) if err := m.AckSequences[len(m.AckSequences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenesis } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *PacketSequence) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PacketSequence: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PacketSequence: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SourceChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.SourceChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DestinationChain", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenesis } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenesis } if postIndex > l { return io.ErrUnexpectedEOF } m.DestinationChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } m.Sequence = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenesis } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Sequence |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipGenesis(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenesis } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenesis(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenesis } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthGenesis } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupGenesis } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthGenesis } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/02-client/types/events.go<|end_filename|> package types import ( "fmt" host "github.com/bianjieai/tibc-go/modules/tibc/core/24-host" ) // TIBC client events const ( AttributeKeyChainName = "chain_name" AttributeKeyClientType = "client_type" AttributeKeyConsensusHeight = "consensus_height" AttributeKeyHeader = "header" ) // TIBC client events vars var ( EventTypeCreateClientProposal = "create_client_proposal" EventTypeUpdateClient = "update_client" EventTypeUpgradeClientProposal = "upgrade_client_proposal" EventTypeUpdateClientProposal = "update_client_proposal" AttributeValueCategory = fmt.Sprintf("%s_%s", host.ModuleName, SubModuleName) ) <|start_filename|>modules/tibc/core/04-packet/types/keys.go<|end_filename|> package types const ( // SubModuleName defines the TIBC packets name SubModuleName = "packet" // StoreKey is the store key string for TIBC packets StoreKey = SubModuleName // RouterKey is the message route for TIBC packets RouterKey = SubModuleName // QuerierRoute is the querier route for TIBC packets QuerierRoute = SubModuleName ) <|start_filename|>modules/tibc/core/23-commitment/types/commitment.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/commitment/v1/commitment.proto package types import ( fmt "fmt" _go "github.com/confio/ics23/go" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // MerkleRoot defines a merkle root hash. // In the Cosmos SDK, the AppHash of a block header becomes the root. type MerkleRoot struct { Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` } func (m *MerkleRoot) Reset() { *m = MerkleRoot{} } func (m *MerkleRoot) String() string { return proto.CompactTextString(m) } func (*MerkleRoot) ProtoMessage() {} func (*MerkleRoot) Descriptor() ([]byte, []int) { return fileDescriptor_e76044a26d8b9539, []int{0} } func (m *MerkleRoot) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MerkleRoot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MerkleRoot.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MerkleRoot) XXX_Merge(src proto.Message) { xxx_messageInfo_MerkleRoot.Merge(m, src) } func (m *MerkleRoot) XXX_Size() int { return m.Size() } func (m *MerkleRoot) XXX_DiscardUnknown() { xxx_messageInfo_MerkleRoot.DiscardUnknown(m) } var xxx_messageInfo_MerkleRoot proto.InternalMessageInfo // MerklePrefix is merkle path prefixed to the key. // The constructed key from the Path and the key will be append(Path.KeyPath, // append(Path.KeyPrefix, key...)) type MerklePrefix struct { KeyPrefix []byte `protobuf:"bytes,1,opt,name=key_prefix,json=keyPrefix,proto3" json:"key_prefix,omitempty" yaml:"key_prefix"` } func (m *MerklePrefix) Reset() { *m = MerklePrefix{} } func (m *MerklePrefix) String() string { return proto.CompactTextString(m) } func (*MerklePrefix) ProtoMessage() {} func (*MerklePrefix) Descriptor() ([]byte, []int) { return fileDescriptor_e76044a26d8b9539, []int{1} } func (m *MerklePrefix) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MerklePrefix) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MerklePrefix.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MerklePrefix) XXX_Merge(src proto.Message) { xxx_messageInfo_MerklePrefix.Merge(m, src) } func (m *MerklePrefix) XXX_Size() int { return m.Size() } func (m *MerklePrefix) XXX_DiscardUnknown() { xxx_messageInfo_MerklePrefix.DiscardUnknown(m) } var xxx_messageInfo_MerklePrefix proto.InternalMessageInfo func (m *MerklePrefix) GetKeyPrefix() []byte { if m != nil { return m.KeyPrefix } return nil } // MerklePath is the path used to verify commitment proofs, which can be an // arbitrary structured object (defined by a commitment type). // MerklePath is represented from root-to-leaf type MerklePath struct { KeyPath []string `protobuf:"bytes,1,rep,name=key_path,json=keyPath,proto3" json:"key_path,omitempty" yaml:"key_path"` } func (m *MerklePath) Reset() { *m = MerklePath{} } func (*MerklePath) ProtoMessage() {} func (*MerklePath) Descriptor() ([]byte, []int) { return fileDescriptor_e76044a26d8b9539, []int{2} } func (m *MerklePath) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MerklePath) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MerklePath.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MerklePath) XXX_Merge(src proto.Message) { xxx_messageInfo_MerklePath.Merge(m, src) } func (m *MerklePath) XXX_Size() int { return m.Size() } func (m *MerklePath) XXX_DiscardUnknown() { xxx_messageInfo_MerklePath.DiscardUnknown(m) } var xxx_messageInfo_MerklePath proto.InternalMessageInfo func (m *MerklePath) GetKeyPath() []string { if m != nil { return m.KeyPath } return nil } // MerkleProof is a wrapper type over a chain of CommitmentProofs. // It demonstrates membership or non-membership for an element or set of // elements, verifiable in conjunction with a known commitment root. Proofs // should be succinct. // MerkleProofs are ordered from leaf-to-root type MerkleProof struct { Proofs []*_go.CommitmentProof `protobuf:"bytes,1,rep,name=proofs,proto3" json:"proofs,omitempty"` } func (m *MerkleProof) Reset() { *m = MerkleProof{} } func (m *MerkleProof) String() string { return proto.CompactTextString(m) } func (*MerkleProof) ProtoMessage() {} func (*MerkleProof) Descriptor() ([]byte, []int) { return fileDescriptor_e76044a26d8b9539, []int{3} } func (m *MerkleProof) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *MerkleProof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MerkleProof.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *MerkleProof) XXX_Merge(src proto.Message) { xxx_messageInfo_MerkleProof.Merge(m, src) } func (m *MerkleProof) XXX_Size() int { return m.Size() } func (m *MerkleProof) XXX_DiscardUnknown() { xxx_messageInfo_MerkleProof.DiscardUnknown(m) } var xxx_messageInfo_MerkleProof proto.InternalMessageInfo func (m *MerkleProof) GetProofs() []*_go.CommitmentProof { if m != nil { return m.Proofs } return nil } func init() { proto.RegisterType((*MerkleRoot)(nil), "tibc.core.commitment.v1.MerkleRoot") proto.RegisterType((*MerklePrefix)(nil), "tibc.core.commitment.v1.MerklePrefix") proto.RegisterType((*MerklePath)(nil), "tibc.core.commitment.v1.MerklePath") proto.RegisterType((*MerkleProof)(nil), "tibc.core.commitment.v1.MerkleProof") } func init() { proto.RegisterFile("tibc/core/commitment/v1/commitment.proto", fileDescriptor_e76044a26d8b9539) } var fileDescriptor_e76044a26d8b9539 = []byte{ // 340 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xcd, 0x4e, 0xf2, 0x40, 0x14, 0x86, 0xdb, 0x7c, 0x84, 0x4f, 0x06, 0x12, 0x63, 0xf1, 0x2f, 0x2c, 0x8a, 0xe9, 0xc2, 0xb0, 0x61, 0x26, 0x80, 0x2b, 0x12, 0x37, 0xd5, 0xad, 0x09, 0xe9, 0xd2, 0x98, 0x98, 0x69, 0x9d, 0xb6, 0x23, 0x94, 0xd3, 0xb4, 0x03, 0xb1, 0x77, 0xe0, 0xd2, 0xa5, 0x4b, 0x2f, 0xc7, 0x25, 0x4b, 0x57, 0xc4, 0xd0, 0x3b, 0xe0, 0x0a, 0xcc, 0xcc, 0x88, 0x74, 0x77, 0xce, 0x9c, 0xe7, 0xfc, 0xcc, 0xfb, 0xa2, 0x9e, 0xe0, 0x7e, 0x40, 0x02, 0xc8, 0x18, 0x09, 0x20, 0x49, 0xb8, 0x48, 0xd8, 0x5c, 0x90, 0xe5, 0xa0, 0x92, 0xe1, 0x34, 0x03, 0x01, 0xd6, 0x99, 0x24, 0xb1, 0x24, 0x71, 0xa5, 0xb6, 0x1c, 0x74, 0x8e, 0x23, 0x88, 0x40, 0x31, 0x44, 0x46, 0x1a, 0xef, 0xb4, 0x03, 0x98, 0x87, 0x1c, 0x48, 0x9a, 0x01, 0x84, 0xb9, 0x7e, 0x74, 0x2e, 0x11, 0xba, 0x63, 0xd9, 0x74, 0xc6, 0x3c, 0x00, 0x61, 0x59, 0xa8, 0x16, 0xd3, 0x3c, 0x3e, 0x37, 0x2f, 0xcc, 0x5e, 0xcb, 0x53, 0xf1, 0xb8, 0xf6, 0xfa, 0xd1, 0x35, 0x9c, 0x5b, 0xd4, 0xd2, 0xdc, 0x24, 0x63, 0x21, 0x7f, 0xb1, 0xae, 0x10, 0x9a, 0xb2, 0xe2, 0x31, 0x55, 0x99, 0xe6, 0xdd, 0x93, 0xed, 0xba, 0x7b, 0x54, 0xd0, 0x64, 0x36, 0x76, 0xf6, 0x35, 0xc7, 0x6b, 0x4c, 0x59, 0xa1, 0xbb, 0x1c, 0x77, 0xb7, 0x6d, 0x42, 0x45, 0x6c, 0x61, 0x74, 0xa0, 0x38, 0x2a, 0xe4, 0xc6, 0x7f, 0xbd, 0x86, 0xdb, 0xde, 0xae, 0xbb, 0x87, 0x95, 0x09, 0x54, 0xc4, 0x8e, 0xf7, 0x5f, 0xf6, 0x53, 0x11, 0x8f, 0x6b, 0xef, 0xf2, 0x92, 0x6b, 0xd4, 0xdc, 0x5d, 0x02, 0x10, 0x5a, 0x18, 0xd5, 0xf5, 0x87, 0xd4, 0x88, 0xe6, 0xf0, 0x14, 0xf3, 0x20, 0x1f, 0x8e, 0xf0, 0xcd, 0x9f, 0x22, 0x8a, 0xf3, 0x7e, 0x29, 0xf7, 0xe1, 0x73, 0x63, 0x9b, 0xab, 0x8d, 0x6d, 0x7e, 0x6f, 0x6c, 0xf3, 0xad, 0xb4, 0x8d, 0x55, 0x69, 0x1b, 0x5f, 0xa5, 0x6d, 0xdc, 0xbb, 0x11, 0x17, 0xf1, 0xc2, 0x97, 0x5a, 0x12, 0x9f, 0xd3, 0xf9, 0x33, 0x67, 0x94, 0x13, 0xa9, 0x71, 0x3f, 0x02, 0x92, 0xc0, 0xd3, 0x62, 0xc6, 0x72, 0xb2, 0x77, 0x67, 0x38, 0xea, 0x57, 0x0c, 0x12, 0x45, 0xca, 0x72, 0xbf, 0xae, 0x54, 0x1d, 0xfd, 0x04, 0x00, 0x00, 0xff, 0xff, 0x9b, 0x08, 0xdc, 0xe8, 0xc5, 0x01, 0x00, 0x00, } func (m *MerkleRoot) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MerkleRoot) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MerkleRoot) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Hash) > 0 { i -= len(m.Hash) copy(dAtA[i:], m.Hash) i = encodeVarintCommitment(dAtA, i, uint64(len(m.Hash))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MerklePrefix) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MerklePrefix) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MerklePrefix) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.KeyPrefix) > 0 { i -= len(m.KeyPrefix) copy(dAtA[i:], m.KeyPrefix) i = encodeVarintCommitment(dAtA, i, uint64(len(m.KeyPrefix))) i-- dAtA[i] = 0xa } return len(dAtA) - i, nil } func (m *MerklePath) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MerklePath) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MerklePath) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.KeyPath) > 0 { for iNdEx := len(m.KeyPath) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.KeyPath[iNdEx]) copy(dAtA[i:], m.KeyPath[iNdEx]) i = encodeVarintCommitment(dAtA, i, uint64(len(m.KeyPath[iNdEx]))) i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *MerkleProof) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *MerkleProof) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *MerkleProof) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Proofs) > 0 { for iNdEx := len(m.Proofs) - 1; iNdEx >= 0; iNdEx-- { { size, err := m.Proofs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintCommitment(dAtA, i, uint64(size)) } i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func encodeVarintCommitment(dAtA []byte, offset int, v uint64) int { offset -= sovCommitment(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *MerkleRoot) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.Hash) if l > 0 { n += 1 + l + sovCommitment(uint64(l)) } return n } func (m *MerklePrefix) Size() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.KeyPrefix) if l > 0 { n += 1 + l + sovCommitment(uint64(l)) } return n } func (m *MerklePath) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.KeyPath) > 0 { for _, s := range m.KeyPath { l = len(s) n += 1 + l + sovCommitment(uint64(l)) } } return n } func (m *MerkleProof) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Proofs) > 0 { for _, e := range m.Proofs { l = e.Size() n += 1 + l + sovCommitment(uint64(l)) } } return n } func sovCommitment(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozCommitment(x uint64) (n int) { return sovCommitment(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *MerkleRoot) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MerkleRoot: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MerkleRoot: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthCommitment } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthCommitment } if postIndex > l { return io.ErrUnexpectedEOF } m.Hash = append(m.Hash[:0], dAtA[iNdEx:postIndex]...) if m.Hash == nil { m.Hash = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCommitment(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthCommitment } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MerklePrefix) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MerklePrefix: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MerklePrefix: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field KeyPrefix", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthCommitment } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthCommitment } if postIndex > l { return io.ErrUnexpectedEOF } m.KeyPrefix = append(m.KeyPrefix[:0], dAtA[iNdEx:postIndex]...) if m.KeyPrefix == nil { m.KeyPrefix = []byte{} } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCommitment(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthCommitment } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MerklePath) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MerklePath: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MerklePath: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field KeyPath", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthCommitment } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthCommitment } if postIndex > l { return io.ErrUnexpectedEOF } m.KeyPath = append(m.KeyPath, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCommitment(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthCommitment } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *MerkleProof) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MerkleProof: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MerkleProof: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Proofs", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCommitment } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthCommitment } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthCommitment } if postIndex > l { return io.ErrUnexpectedEOF } m.Proofs = append(m.Proofs, &_go.CommitmentProof{}) if err := m.Proofs[len(m.Proofs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCommitment(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthCommitment } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipCommitment(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowCommitment } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowCommitment } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowCommitment } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthCommitment } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupCommitment } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthCommitment } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthCommitment = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowCommitment = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupCommitment = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/core/02-client/types/proposal_test.go<|end_filename|> package types_test import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/bianjieai/tibc-go/modules/tibc/core/02-client/types" tibctmtypes "github.com/bianjieai/tibc-go/modules/tibc/light-clients/07-tendermint/types" tibctesting "github.com/bianjieai/tibc-go/modules/tibc/testing" ) func (suite *TypesTestSuite) TestNewCreateClientProposal() { p, err := types.NewCreateClientProposal(tibctesting.Title, tibctesting.Description, chainName, &tibctmtypes.ClientState{}, &tibctmtypes.ConsensusState{}) suite.Require().NoError(err) suite.Require().NotNil(p) p, err = types.NewCreateClientProposal(tibctesting.Title, tibctesting.Description, chainName, nil, nil) suite.Require().Error(err) suite.Require().Nil(p) } // tests a client update proposal can be marshaled and unmarshaled, and the // client state can be unpacked func (suite *TypesTestSuite) TestMarshalCreateClientProposalProposal() { path := tibctesting.NewPath(suite.chainA, suite.chainB) suite.coordinator.SetupClients(path) clientState := path.EndpointA.GetClientState() consensusState := path.EndpointA.GetConsensusState(clientState.GetLatestHeight()) // create proposal proposal, err := types.NewCreateClientProposal("update TIBC client", "description", "chain-name", clientState, consensusState) suite.Require().NoError(err) // create codec ir := codectypes.NewInterfaceRegistry() types.RegisterInterfaces(ir) govtypes.RegisterInterfaces(ir) tibctmtypes.RegisterInterfaces(ir) cdc := codec.NewProtoCodec(ir) // marshal message bz, err := cdc.MarshalJSON(proposal) suite.Require().NoError(err) // unmarshal proposal newProposal := &types.CreateClientProposal{} err = cdc.UnmarshalJSON(bz, newProposal) suite.Require().NoError(err) } <|start_filename|>modules/tibc/testing/coordinator.go<|end_filename|> package tibctesting import ( "fmt" "strconv" "testing" "time" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" ) const ChainIDPrefix = "testchain" var ( globalStartTime = time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC) TimeIncrement = time.Second * 5 ) // Coordinator is a testing struct which contains N TestChain's. It handles keeping all chains // in sync with regards to time. type Coordinator struct { t *testing.T CurrentTime time.Time Chains map[string]*TestChain } // NewCoordinator initializes Coordinator with N TestChain's func NewCoordinator(t *testing.T, n int) *Coordinator { chains := make(map[string]*TestChain) coord := &Coordinator{ t: t, CurrentTime: globalStartTime, } for i := 0; i < n; i++ { chainID := GetChainID(i) chains[chainID] = NewTestChain(t, coord, chainID) } coord.Chains = chains return coord } // IncrementTime iterates through all the TestChain's and increments their current header time // by 5 seconds. // // CONTRACT: this function must be called after every Commit on any TestChain. func (coord *Coordinator) IncrementTime() { coord.IncrementTimeBy(TimeIncrement) } // IncrementTimeBy iterates through all the TestChain's and increments their current header time // by specified time. func (coord *Coordinator) IncrementTimeBy(increment time.Duration) { coord.CurrentTime = coord.CurrentTime.Add(increment).UTC() coord.UpdateTime() } // UpdateTime updates all clocks for the TestChains to the current global time. func (coord *Coordinator) UpdateTime() { for _, chain := range coord.Chains { coord.UpdateTimeForChain(chain) } } // UpdateTimeForChain updates the clock for a specific chain. func (coord *Coordinator) UpdateTimeForChain(chain *TestChain) { chain.CurrentHeader.Time = coord.CurrentTime.UTC() chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) } // SetupClients is a helper function to create clients on both chains. It assumes the // caller does not anticipate any errors. func (coord *Coordinator) SetupClients(path *Path) { err := path.EndpointA.CreateClient() require.NoError(coord.t, err) err = path.EndpointB.CreateClient() require.NoError(coord.t, err) } // GetChain returns the TestChain using the given chainID and returns an error if it does // not exist. func (coord *Coordinator) GetChain(chainID string) *TestChain { chain, found := coord.Chains[chainID] require.True(coord.t, found, fmt.Sprintf("%s chain does not exist", chainID)) return chain } // GetChainID returns the chainID used for the provided index. func GetChainID(index int) string { return ChainIDPrefix + strconv.Itoa(index) } // CommitBlock commits a block on the provided indexes and then increments the global time. // // CONTRACT: the passed in list of indexes must not contain duplicates func (coord *Coordinator) CommitBlock(chains ...*TestChain) { for _, chain := range chains { chain.App.Commit() chain.NextBlock() } coord.IncrementTime() } // CommitNBlocks commits n blocks to state and updates the block height by 1 for each commit. func (coord *Coordinator) CommitNBlocks(chain *TestChain, n uint64) { for i := uint64(0); i < n; i++ { chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) chain.App.Commit() chain.NextBlock() coord.IncrementTime() } } <|start_filename|>modules/tibc/core/26-routing/types/query.pb.go<|end_filename|> // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: tibc/core/routing/v1/query.proto package types import ( context "context" fmt "fmt" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" io "io" math "math" math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // QueryRoutingRulesRequest is the request type for the // RoutingRules RPC method type QueryRoutingRulesRequest struct { } func (m *QueryRoutingRulesRequest) Reset() { *m = QueryRoutingRulesRequest{} } func (m *QueryRoutingRulesRequest) String() string { return proto.CompactTextString(m) } func (*QueryRoutingRulesRequest) ProtoMessage() {} func (*QueryRoutingRulesRequest) Descriptor() ([]byte, []int) { return fileDescriptor_7af620a084c71311, []int{0} } func (m *QueryRoutingRulesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryRoutingRulesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryRoutingRulesRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryRoutingRulesRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryRoutingRulesRequest.Merge(m, src) } func (m *QueryRoutingRulesRequest) XXX_Size() int { return m.Size() } func (m *QueryRoutingRulesRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryRoutingRulesRequest.DiscardUnknown(m) } var xxx_messageInfo_QueryRoutingRulesRequest proto.InternalMessageInfo // QueryRoutingRulesResponse defines the routing rules query response type QueryRoutingRulesResponse struct { // rule string array Rules []string `protobuf:"bytes,1,rep,name=rules,proto3" json:"rules,omitempty"` } func (m *QueryRoutingRulesResponse) Reset() { *m = QueryRoutingRulesResponse{} } func (m *QueryRoutingRulesResponse) String() string { return proto.CompactTextString(m) } func (*QueryRoutingRulesResponse) ProtoMessage() {} func (*QueryRoutingRulesResponse) Descriptor() ([]byte, []int) { return fileDescriptor_7af620a084c71311, []int{1} } func (m *QueryRoutingRulesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QueryRoutingRulesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryRoutingRulesResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QueryRoutingRulesResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryRoutingRulesResponse.Merge(m, src) } func (m *QueryRoutingRulesResponse) XXX_Size() int { return m.Size() } func (m *QueryRoutingRulesResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryRoutingRulesResponse.DiscardUnknown(m) } var xxx_messageInfo_QueryRoutingRulesResponse proto.InternalMessageInfo func (m *QueryRoutingRulesResponse) GetRules() []string { if m != nil { return m.Rules } return nil } func init() { proto.RegisterType((*QueryRoutingRulesRequest)(nil), "tibc.core.routing.v1.QueryRoutingRulesRequest") proto.RegisterType((*QueryRoutingRulesResponse)(nil), "tibc.core.routing.v1.QueryRoutingRulesResponse") } func init() { proto.RegisterFile("tibc/core/routing/v1/query.proto", fileDescriptor_7af620a084c71311) } var fileDescriptor_7af620a084c71311 = []byte{ // 279 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x28, 0xc9, 0x4c, 0x4a, 0xd6, 0x4f, 0xce, 0x2f, 0x4a, 0xd5, 0x2f, 0xca, 0x2f, 0x2d, 0xc9, 0xcc, 0x4b, 0xd7, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x01, 0xa9, 0xd0, 0x03, 0xa9, 0xd0, 0x83, 0xaa, 0xd0, 0x2b, 0x33, 0x94, 0x92, 0x49, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0x4f, 0xcc, 0xcb, 0xcb, 0x2f, 0x49, 0x2c, 0xc9, 0xcc, 0xcf, 0x2b, 0x86, 0xe8, 0x51, 0x92, 0xe2, 0x92, 0x08, 0x04, 0x19, 0x11, 0x04, 0xd1, 0x10, 0x54, 0x9a, 0x93, 0x5a, 0x1c, 0x94, 0x5a, 0x58, 0x9a, 0x5a, 0x5c, 0xa2, 0x64, 0xc8, 0x25, 0x89, 0x45, 0xae, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0x48, 0x84, 0x8b, 0xb5, 0x08, 0x24, 0x20, 0xc1, 0xa8, 0xc0, 0xac, 0xc1, 0x19, 0x04, 0xe1, 0x18, 0xad, 0x66, 0xe4, 0x62, 0x05, 0xeb, 0x11, 0x5a, 0xc8, 0xc8, 0xc5, 0x83, 0xac, 0x51, 0x48, 0x4f, 0x0f, 0x9b, 0xf3, 0xf4, 0x70, 0xd9, 0x2e, 0xa5, 0x4f, 0xb4, 0x7a, 0x88, 0x8b, 0x94, 0x0c, 0x9a, 0x2e, 0x3f, 0x99, 0xcc, 0xa4, 0x25, 0xa4, 0xa1, 0x8f, 0x2d, 0xa4, 0x92, 0x52, 0x4b, 0x12, 0x0d, 0x61, 0xfc, 0x78, 0xb0, 0x6b, 0x9d, 0x22, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x3e, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x3f, 0x29, 0x33, 0x31, 0x2f, 0x2b, 0x33, 0x35, 0x31, 0x13, 0x6c, 0xae, 0x6e, 0x7a, 0xbe, 0x7e, 0x6e, 0x7e, 0x0a, 0x48, 0x3f, 0x92, 0x3d, 0x46, 0x66, 0xba, 0x30, 0xab, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xc1, 0x6b, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x11, 0x35, 0x26, 0xf8, 0xb6, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // QueryClient is the client API for Query service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { // RoutingRules queries all routing rules. RoutingRules(ctx context.Context, in *QueryRoutingRulesRequest, opts ...grpc.CallOption) (*QueryRoutingRulesResponse, error) } type queryClient struct { cc grpc1.ClientConn } func NewQueryClient(cc grpc1.ClientConn) QueryClient { return &queryClient{cc} } func (c *queryClient) RoutingRules(ctx context.Context, in *QueryRoutingRulesRequest, opts ...grpc.CallOption) (*QueryRoutingRulesResponse, error) { out := new(QueryRoutingRulesResponse) err := c.cc.Invoke(ctx, "/tibc.core.routing.v1.Query/RoutingRules", in, out, opts...) if err != nil { return nil, err } return out, nil } // QueryServer is the server API for Query service. type QueryServer interface { // RoutingRules queries all routing rules. RoutingRules(context.Context, *QueryRoutingRulesRequest) (*QueryRoutingRulesResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. type UnimplementedQueryServer struct { } func (*UnimplementedQueryServer) RoutingRules(ctx context.Context, req *QueryRoutingRulesRequest) (*QueryRoutingRulesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RoutingRules not implemented") } func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } func _Query_RoutingRules_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryRoutingRulesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(QueryServer).RoutingRules(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tibc.core.routing.v1.Query/RoutingRules", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).RoutingRules(ctx, req.(*QueryRoutingRulesRequest)) } return interceptor(ctx, in, info, handler) } var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "tibc.core.routing.v1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "RoutingRules", Handler: _Query_RoutingRules_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "tibc/core/routing/v1/query.proto", } func (m *QueryRoutingRulesRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryRoutingRulesRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryRoutingRulesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l return len(dAtA) - i, nil } func (m *QueryRoutingRulesResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QueryRoutingRulesResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QueryRoutingRulesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Rules) > 0 { for iNdEx := len(m.Rules) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.Rules[iNdEx]) copy(dAtA[i:], m.Rules[iNdEx]) i = encodeVarintQuery(dAtA, i, uint64(len(m.Rules[iNdEx]))) i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { offset -= sovQuery(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *QueryRoutingRulesRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l return n } func (m *QueryRoutingRulesResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Rules) > 0 { for _, s := range m.Rules { l = len(s) n += 1 + l + sovQuery(uint64(l)) } } return n } func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozQuery(x uint64) (n int) { return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *QueryRoutingRulesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryRoutingRulesRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryRoutingRulesRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QueryRoutingRulesResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QueryRoutingRulesResponse: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QueryRoutingRulesResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Rules", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuery } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthQuery } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthQuery } if postIndex > l { return io.ErrUnexpectedEOF } m.Rules = append(m.Rules, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthQuery } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuery } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthQuery } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupQuery } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthQuery } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") ) <|start_filename|>modules/tibc/light-clients/07-tendermint/module.go<|end_filename|> package tendermint import ( "github.com/bianjieai/tibc-go/modules/tibc/light-clients/07-tendermint/types" ) // Name returns the TIBC tendermint client name func Name() string { return types.SubModuleName } <|start_filename|>modules/tibc/core/26-routing/types/router.go<|end_filename|> package types import ( "fmt" ) // The router is a map from module name to the TIBCModule // which contains all the module-defined callbacks required by TICS-26 type Router struct { routes map[string]TIBCModule sealed bool } func NewRouter() *Router { return &Router{ routes: make(map[string]TIBCModule), } } // Seal prevents the Router from any subsequent route handlers to be registered. // Seal will panic if called more than once. func (rtr *Router) Seal() { if rtr.sealed { panic("router already sealed") } rtr.sealed = true } // Sealed returns a boolean signifying if the Router is sealed or not. func (rtr Router) Sealed() bool { return rtr.sealed } // AddRoute adds TIBCModule for a given module name. It returns the Router // so AddRoute calls can be linked. It will panic if the Router is sealed. func (rtr *Router) AddRoute(port Port, cbs TIBCModule) *Router { if rtr.sealed { panic(fmt.Sprintf("router sealed; cannot register %s route callbacks", port)) } if rtr.HasRoute(port) { panic(fmt.Sprintf("route %s has already been registered", port)) } rtr.routes[string(port)] = cbs return rtr } // HasRoute returns true if the Router has a module registered or false otherwise. func (rtr *Router) HasRoute(port Port) bool { _, ok := rtr.routes[string(port)] return ok } // GetRoute returns a TIBCModule for a given module. func (rtr *Router) GetRoute(port Port) (TIBCModule, bool) { if !rtr.HasRoute(port) { return nil, false } return rtr.routes[string(port)], true }
gnehcein/tibc-go
<|start_filename|>lib/index.js<|end_filename|> (function() { 'use strict'; var sass = require('node-sass'), each = require('async/each'), path = require('path'), // from https://gist.github.com/stevenschobert/ca76531b46f2ac00cbd8 extend = function extend() { var args = [].slice.call(arguments); args[0] = (typeof args[0] === 'object') ? args[0] : {}; for (var i=1; i<args.length; i++) { if (typeof args[i] === 'object') { for (var key in args[i]) { if (args[i].hasOwnProperty(key)) { args[0][key] = args[i][key]; } } } } return args[0]; }, isAnySassFile = function isAnySassFile(filename) { return (/^[^_.].*\.s[ac]ss/).test(path.basename(filename)); }, isSassFile = function isSassFile(filename) { return (/^[^_.].*\.sass/).test(path.basename(filename)); }, isPartial = function isPartial(filename) { return (/^_.*\.s[ac]ss/).test(path.basename(filename)); }, compile = function(config, basePath, files, filename, done) { if (isPartial(filename)) { delete files[filename]; done(); return; } if (!isAnySassFile(filename)) { done(); return; } var file = files[filename], filePath = path.join(basePath, filename), opts = extend({ includePaths: [], outputStyle: 'compressed', imagePath: '/', outputDir: path.dirname(filename), indentedSyntax: isSassFile(filename) }, config, { // Use the file's content stream buffer rather than the file path. data: file.contents.toString(), file: filePath }), fileDir = path.dirname(filePath), computedOutputDir = (typeof opts.outputDir === 'function') ? opts.outputDir(path.dirname(filename)) : opts.outputDir, dest = path.join(computedOutputDir, path.basename(filename).replace(/\.s[ca]ss/, '.css')); if (opts.sourceMap) { opts.outFile = filePath.replace(/\.s[ca]ss/, '.css'); } // Append the file's base path to the available include paths. opts.includePaths.push(fileDir); // Compile the file using SASS. sass.render(opts, function (err, result) { var error = null; if (err && err instanceof Error) { error = new Error([ '[metalsmith-sass] Error: ', err.message, ' -> ', err.file, ':', err.line, ':', err.column ].join('')); } else if (err) { error = new Error(err); } if (error) { done(error); return; } // add soure map if (result.map) { files[dest+'.map'] = { contents: result.map, mode: file.mode }; } // replace contents file.contents = result.css; // rename file extension files[dest] = file; delete files[filename]; done(); }); }, compileSass = function compileSass(config, files, metalsmith, done) { /** * Looks up different key names on `metalsmith` to support * old versions (< v1) of Metalsmith. At some point, I will remove * support for < v1 and remove the key lookups */ var directory = metalsmith.dir || metalsmith._directory, source = metalsmith._src || metalsmith._source, basePath = path.isAbsolute(source) ? source : path.join(directory, source); each(Object.keys(files), compile.bind(null, config, basePath, files), done); }, plugin = function plugin(options) { var config = options || {}; return compileSass.bind(null, config); }; // exposing node-sass types for custom functions. see: // https://github.com/stevenschobert/metalsmith-sass/pull#21 plugin.types = sass.types; module.exports = plugin; }());
lfdebrux/metalsmith-sass
<|start_filename|>gulpfile.js<|end_filename|> 'use strict'; const gulp = require('gulp'); const gutil = require('gulp-util'); const babel = require('gulp-babel'); const sass = require('gulp-sass'); const cssnano = require('gulp-cssnano'); const postcss = require('gulp-postcss'); const rename = require('gulp-rename'); const uglify = require('gulp-uglify'); const browserSync = require('browser-sync'); gulp.task('demo', ['demo:build'], () => { browserSync.init({ server: { baseDir: './docs' } }); gulp.watch('./src/scss/**/*.scss', ['demo:build:css']); gulp.watch('./src/js/**/*.js', ['demo:build:js']); }); gulp.task('demo:build', [ 'demo:build:css', 'demo:build:js', ], (done) => { done(); }); gulp.task('demo:build:css', () => { return gulp.src('./src/scss/plyr-ads.scss') .pipe(sass()) .pipe(gulp.dest('./docs/css')) .pipe(browserSync.reload({stream: true})); }); gulp.task('demo:build:js', () => { return gulp.src('./src/js/plyr-ads.js') .pipe(gulp.dest('./docs/js')) .pipe(browserSync.reload({stream: true})); }); gulp.task('build', [ 'build:css', 'build:js' ], (done) => { done(); }); gulp.task('build:css', () => { return gulp.src('./src/scss/plyr-ads.scss') .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError)) .pipe(postcss([require('autoprefixer'), require('precss')])) .pipe(cssnano({ zindex: false })) .pipe(rename('plyr-ads.min.css')) .pipe(gulp.dest('./dist')) }); gulp.task('build:js', () => { return gulp.src('./src/js/plyr-ads.js') .pipe(babel({ presets: ['es2015'] })) .pipe(uglify({ preserveComments: false, mangle: true, sequences: true, dead_code: true, conditionals: true, booleans: true, unused: true, if_return: true, join_vars: true, drop_console: true, })).on('error', gutil.log) .pipe(rename('plyr-ads.min.js')) .pipe(gulp.dest('./dist')); }); <|start_filename|>docs/js/demo.js<|end_filename|> (function() { var player = plyr.setup(); plyrAds.setup(player, { adTagUrl: 'https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear&correlator=' }); })(); <|start_filename|>docs/css/plyr-ads.css<|end_filename|> .plyr--ready { position: relative; } .plyr-ads { font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol"; position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 10; cursor: pointer; } .plyr-ads video { left: 0; } .plyr-ads__skip-button { font-size: .8rem; position: absolute; color: #fff; bottom: 40px; right: 0; z-index: 11; background: rgba(0, 0, 0, 0.8); padding: 5px 10px; cursor: pointer; border: none; } .plyr-ads__skip-button.done { font-size: 1.5rem; } .plyr-ads__skip-button.done:after { content: ''; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAABGdBTUEAALGPC/xhBQAAAAJiS0dEAP+Hj8y/AAAAZElEQVQ4y+3SwQmDQBBGYRFy9mYLSRXWEyvRRtKBbdhDUoTH8HkVllX+u++48GD2zTTNTYiPrnhDXeBnyAT+Zo9EgNUrE9iMmQCLvhTas2jXWY8jvbNPP5OsU5L1my0uPY2bCjtXdo6mqRVtTgAAAABJRU5ErkJggg=="); background-repeat: no-repeat; display: inline-block; height: 24px; margin-left: 2px; vertical-align: middle; width: 24px; display: inline-block; } <|start_filename|>docs/js/plyr-ads.js<|end_filename|> /* global define,module */ // ========================================================================== // Plyr-Ads // plyr-ads.js v1.1.5 // https://github.com/ferdiemmen/plyr-ads // License: The MIT License (MIT) // ========================================================================== // Credits: Copyright 2013 Google Inc. All Rights Reserved. // You may study, modify, and use this example for any purpose. // Note that this example is provided "as is", WITHOUT WARRANTY // of any kind either expressed or implied. // ========================================================================== (function (root, factory) { 'use strict'; if (typeof module === 'object' && typeof module.exports === 'object') { // Node, CommonJS-like module.exports = factory(root, document); } else if (typeof define === 'function' && define.amd) { // AMD define([], function() { return factory(root, document); }); } else { // Browser globals (root is window) root.plyrAds = factory(root, document); } }(typeof window !== 'undefined' ? window : this, function (window, document) { 'use strict'; // Default config let defaults = { adTagUrl: '', skipButton: { enabled: true, text: 'Skip ad', delay: 10 } }; // Check variable types. let _is = { object: function (input) { return input !== null && typeof (input) === 'object'; }, array: function (input) { return input !== null && (typeof (input) === 'object' && input.constructor === Array); }, number: function (input) { return input !== null && (typeof (input) === 'number' && !isNaN(input - 0) || (typeof input === 'object' && input.constructor === Number)); }, string: function (input) { return input !== null && (typeof input === 'string' || (typeof input === 'object' && input.constructor === String)); }, boolean: function (input) { return input !== null && typeof input === 'boolean'; }, nodeList: function (input) { return input !== null && input instanceof NodeList; }, htmlElement: function (input) { return input !== null && input instanceof HTMLElement; }, function: function (input) { return input !== null && typeof input === 'function'; }, undefined: function (input) { return input !== null && typeof input === 'undefined'; } }; function PlyrAds(plyr, options) { this.adsManager; this.adsLoader; this.adDuration; this.intervalTimer; this.plyr = plyr; this.options = options; this.plyrContainer = plyr.getContainer(); this.adPaused = false; this.skipAdButton; this.adDisplayContainer; // Check if the Google IMA3 SDK is present. if (!window.google) { throw new Error('The Google IMA3 SDK is not loaded.'); } this.init = () => { if (!this.options.adTagUrl) { throw Error('No adTagUrl provided.'); } // Add ad container to DOM. this.createAdDisplayContainer(); // Setup IMA. this.setUpIMA(); }; this.playAds = () => { // Initialize the container. Must be done via a user action on mobile devices. this.adDisplayContainer.initialize(); // Initialize the ads manager. Ad rules playlist will start at this time. this.adsManager.init(this.plyrContainer.offsetWidth, this.plyrContainer.offsetHeight, window.google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will // start at this time; the call will be ignored for ad rules. this.adsManager.start(); }; this.playVideo = () => { if (this.skipAdButton) { this.skipAdButton.remove(); } this.plyrContainer.firstChild.remove(); if (this.plyr.getType() === 'youtube' && navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)) { // Due to this restriction, functions and parameters such as autoplay, // playVideo(), loadVideoById() won't work in all mobile environments. this.plyr.getEmbed().playVideoAt(0); } else { this.plyr.play(); } }; return { init: this.init }; } PlyrAds.prototype.setUpIMA = _setUpIMA; PlyrAds.prototype.createAdDisplayContainer = _createAdDisplayContainer; PlyrAds.prototype.createAdSkipButton = _createAdSkipButton; PlyrAds.prototype.onAdEvent = _onAdEvent; PlyrAds.prototype.onAdError = _onAdError; PlyrAds.prototype.onAdsManagerLoaded = _onAdsManagerLoaded; PlyrAds.prototype.onContentResumeRequested = _onContentResumeRequested; PlyrAds.prototype.onContentSkippable = _onContentSkippable; PlyrAds.prototype.toggleListener = _toggleListener; function _createAdDisplayContainer() { this.adDisplayContainer = new window.google.ima.AdDisplayContainer( this.plyrContainer); this.plyrContainer.firstChild.setAttribute('class', 'plyr-ads'); // Set listener on ad display container to play the ad. this.toggleListener(this.plyrContainer.firstChild, this.playAds); } function _createAdSkipButton() { let skipTimer = this.options.skipButton.delay; this.skipAdButton = _insertElement('button', this.plyrContainer, { class: 'plyr-ads__skip-button' }); if (this.options.skipButton.delay > 0) { this.skipAdButton.innerHTML = 'You can skip to video in ' + (skipTimer--); let skipButtonTimer = window.setInterval(function waitForAd() { if (!this.adPaused) { this.skipAdButton.innerHTML = 'You can skip to video in ' + skipTimer--; } if ((skipTimer + 1) === 0 || this.options.skipButton.delay === 0) { this.skipAdButton.className += ' done'; this.skipAdButton.innerHTML = this.options.skipButton.text; // Set listener on ad skip button to skip the ad. this.toggleListener(this.skipAdButton, this.playVideo); window.clearInterval(skipButtonTimer); } }.bind(this), 1000); } else { this.skipAdButton.className += ' done'; this.skipAdButton.innerHTML = this.options.skipButton.text; // Set listener on ad skip button to skip the ad. this.toggleListener(this.skipAdButton, this.playVideo); } } // Prepend child function _prependChild(parent, element) { return parent.insertBefore(element, parent.firstChild); } // Set attributes function _setAttributes(element, attributes) { for (let key in attributes) { if (Object.prototype.hasOwnProperty.call(attributes, key)) { element.setAttribute(key, (_is.boolean(attributes[key]) && attributes[key]) ? '' : attributes[key]); } } } // Insert a HTML element function _insertElement(type, parent, attributes) { // Create a new <element> let element = document.createElement(type); // Set all passed attributes _setAttributes(element, attributes); // Inject the new element return _prependChild(parent, element); } function _setUpIMA() { // Create ads loader. this.adsLoader = new window.google.ima.AdsLoader(this.adDisplayContainer); // Listen and respond to ads loaded and error events. this.adsLoader.addEventListener( window.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, function (e) { this.onAdsManagerLoaded(e); }.bind(this), false); this.adsLoader.addEventListener( window.google.ima.AdErrorEvent.Type.AD_ERROR, function(e) { this.plyrContainer.firstChild.remove(); }.bind(this), false); // Request video ads. let adsRequest = new window.google.ima.AdsRequest(); adsRequest.adTagUrl = this.options.adTagUrl; this.adsLoader.requestAds(adsRequest); } function _onAdsManagerLoaded(adsManagerLoadedEvent) { // Get the ads manager. let adsRenderingSettings = new window.google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; this.adsManager = adsManagerLoadedEvent.getAdsManager(adsRenderingSettings); // Add listeners to the required events. this.adsManager.addEventListener( window.google.ima.AdErrorEvent.Type.AD_ERROR, function (e) { this.onAdError(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, function (e) { this.onContentResumeRequested(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.SKIPPABLE_STATE_CHANGED, function (e) { this.onContentSkippable(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.ALL_ADS_COMPLETED, function (e) { this.onAdEvent(e); }.bind(this)); // Listen to any additional events, if necessary. this.adsManager.addEventListener( window.google.ima.AdEvent.Type.LOADED, function (e) { this.onAdEvent(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.STARTED, function (e) { this.onAdEvent(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.PAUSED, function (e) { this.onAdEvent(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.RESUMED, function (e) { this.onAdEvent(e); }.bind(this)); this.adsManager.addEventListener( window.google.ima.AdEvent.Type.COMPLETE, function (e) { this.onAdEvent(e); }.bind(this)); // Listen to the resizing of the window. And resize // ad accordingly. window.addEventListener( 'resize', function() { this.adsManager.resize( this.plyrContainer.offsetWidth, this.plyrContainer.offsetHeight, window.google.ima.ViewMode.NORMAL); }.bind(this)); } function _onAdEvent(adEvent) { // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED) // don't have ad object associated. let ad = adEvent.getAd(); switch (adEvent.type) { case window.google.ima.AdEvent.Type.LOADED: // This is the first event sent for an ad - it is possible to // determine whether the ad is a video ad or an overlay. if (!ad.isLinear()) { // Position AdDisplayContainer correctly for overlay. // Use ad.width and ad.height. this.playVideo(); } break; case window.google.ima.AdEvent.Type.STARTED: // This event indicates the ad has started - the video player // can adjust the UI, for example display a pause button and // remaining time. if (ad.isLinear()) { // For a linear ad, a timer can be started to poll for // the remaining time. // this.intervalTimer = setInterval( // function() { // let remainingTime = Math.round(this.adsManager.getRemainingTime()); // }.bind(this), // 300); // every 300ms if (ad.g.duration > 15 || this.options.skipButton.delay === 0) { // Add ad skip button to DOM. this.createAdSkipButton(); } } break; case window.google.ima.AdEvent.Type.PAUSED: // This event indicates the ad has started - the video player // can adjust the UI, for example display a pause button and // remaining time. if (ad.isLinear()) { // For a linear ad, a timer can be started to poll for // the remaining time. this.adPaused = true; } break; case window.google.ima.AdEvent.Type.RESUMED: // This event indicates the ad has started - the video player // can adjust the UI, for example display a pause button and // remaining time. if (ad.isLinear()) { // For a linear ad, a timer can be started to poll for // the remaining time. this.adPaused = false; } break; case window.google.ima.AdEvent.Type.COMPLETE: // This event indicates the ad has finished - the video player // can perform appropriate UI actions, such as removing the timer for // remaining time detection. // Start playing the video. this.playVideo(); if (ad.isLinear()) { clearInterval(this.intervalTimer); } break; default: break; } } function _onAdError(adErrorEvent) { // Handle the error logging. this.adsManager.destroy(); this.playVideo(); throw new Error(adErrorEvent.getError()); } function _onContentResumeRequested() { // Start playing the video. this.playVideo(); // This function is where you should ensure that your UI is ready // to play content. It is the responsibility of the Publisher to // implement this function when necessary. // setupUIForContent(); } function _onContentSkippable() { this.plyrAdSkipButton.style.display = 'block'; } // Deep extend/merge destination object with N more objects // http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/ // Removed call to arguments.callee (used explicit function name instead) function _extend() { // Get arguments let objects = arguments; // Bail if nothing to merge if (!objects.length) { return; } // Return first if specified but nothing to merge if (objects.length === 1) { return objects[0]; } // First object is the destination let destination = Array.prototype.shift.call(objects); let length = objects.length; // Loop through all objects to merge for (let i = 0; i < length; i++) { let source = objects[i]; for (let property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; _extend(destination[property], source[property]); } else { destination[property] = source[property]; } } } return destination; } function _toggleListener(element, cb) { let startEvent; var triggerCallback = function(event) { if (event.type === 'touchend' && startEvent === 'touchstart' || event.type === 'click') { cb(); } startEvent = event.type; element.removeEventListener(event.type, triggerCallback); } for (let touchEvent of _getEvents()) { element.addEventListener(touchEvent, triggerCallback, false); } } function _getEvents() { // Set the correct event based on userAgent. let startEvent = ['click']; if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)) { startEvent = ['touchstart', 'touchend', 'touchmove']; } return startEvent; } // Setup function function setup(plyr, config) { // Bail if plyr instances aren't found. if (!window.plyr || !plyr) return false; // Set options from defaults and config. let options = _extend({}, defaults, config); // Loop through plyr instances and add ads. plyr.forEach(function (instance) { // Only add ads to video instances. if (instance.getType() !== 'audio') { let newInstance = new PlyrAds(instance, options); newInstance.init(); } }); return false; } return { setup: setup }; }));
animaxdev/plyr-ads
<|start_filename|>docs/what-is-groovy.html<|end_filename|> <html> <head> <meta charset="UTF-8"> <title>2. Apache Groovyとは - Apache Groovyチュートリアル</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/highlight.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/my.css"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-84847594-1', 'auto'); ga('send', 'pageview'); </script> </head> <body> <div class="wrapper"> <div class="header"> <i class="fa fa-bars sidebar-toggle"></i> <span class="title"><a href="index.html">Apache Groovyチュートリアル</a></span> </div> <div class="sidebar"> <ul> <li class="numbered visible"> <a href="index.html" data-alt-hash="apache-groovy-"><span class="number">1.</span>Apache Groovy チュートリアル</a> <ul> <li class="numbered visible"><a href="index.html#id-42307f13d9d6d9fe7f15eb0536255b824fe0af1c"><span class="number">1.1.</span>さぁ始めよう!&hellip;の前に</a></li> </ul> </li> <li class="numbered visible"> <a href="what-is-groovy.html" data-alt-hash="apache-groovy"><span class="number">2.</span>Apache Groovyとは</a> <ul> <li class="numbered visible"><a href="what-is-groovy.html#id-fcad98b6bc96cf66e20f986f0973d2575fce430b"><span class="number">2.1.</span>シンプル&amp;パワフル</a></li> <li class="numbered visible"><a href="what-is-groovy.html#id-f9356a26c4c26110d0fb85dbe07c07c28751e391"><span class="number">2.2.</span>巨大なエコシステム</a></li> <li class="numbered visible"><a href="what-is-groovy.html#id-5f52ad0dbb814a0559eb8aa4b4a645c74bbedd8d"><span class="number">2.3.</span>気軽に実行</a></li> <li class="numbered visible"><a href="what-is-groovy.html#id-6f37a8477bcb751f15dedcbcc9ee8a9cc90ef061"><span class="number">2.4.</span>実験コードのお供に</a></li> <li class="numbered visible"><a href="what-is-groovy.html#id-ef4e0df42b47b23ce15bc3ccadd1d8d8e43f8385"><span class="number">2.5.</span>ビルドツール要らず</a></li> <li class="numbered visible"><a href="what-is-groovy.html#java"><span class="number">2.6.</span>Javaの友達</a></li> <li class="numbered visible"><a href="what-is-groovy.html#id-319e80ab91fa4b24ead46ec990e7890d8a62c899"><span class="number">2.7.</span>もちろんプロダクトとしても</a></li> <li class="numbered visible"><a href="what-is-groovy.html#ok"><span class="number">2.8.</span>どこからでもOK</a></li> </ul> </li> <li class="numbered visible"> <a href="startup/index.html" data-alt-hash="startup"><span class="number">3.</span>Startup</a> <ul> <li class="numbered visible"><a href="startup/install.html" data-alt-hash="install"><span class="number">3.1.</span>Install</a></li> <li class="numbered visible"><a href="startup/install.html#hello-world"><span class="number">3.2.</span>Hello World</a></li> <li class="numbered visible"> <a href="startup/execution.html" data-alt-hash="id-947e8b547a7ee2d2d16471408918f148e7008486"><span class="number">3.3.</span>色々な実行方法</a> <ul> <li class="numbered visible"><a href="startup/execution.html#groovyconsole"><span class="number">3.3.1.</span>GroovyConsole</a></li> <li class="numbered visible"><a href="startup/execution.html#groovysh"><span class="number">3.3.2.</span>Groovysh</a></li> <li class="numbered visible"><a href="startup/execution.html#id-da28f0cd33cb1f1e6ce383dde43065522845c2e8"><span class="number">3.3.3.</span>ファイルに保存してスクリプトとして実行</a></li> <li class="numbered visible"> <a href="startup/execution.html#id-fcbfd717080ef34d6aa5a6da494d789c4907d1a2"><span class="number">3.3.4.</span>ファイルに保存してコンパイル&amp;実行</a> <ul> <li class="numbered invisible"><a href="startup/execution.html#class"><span class="number">3.3.4.1.</span>ファイル名と生成されるclassファイル名の関係</a></li> </ul> </li> </ul> </li> </ul> </li> <li class="numbered visible"> <a href="variable/index.html" data-alt-hash="id-5221440a56644419d70a10bd0ccf693a2126dc64"><span class="number">4.</span>変数</a> <ul> <li class="numbered visible"><a href="variable/index.html#def"><span class="number">4.1.</span>defキーワード</a></li> <li class="numbered visible"><a href="variable/index.html#id-a6077d27e5f63be9d00575f8249b0ab98c2688cd"><span class="number">4.2.</span>型の変数名を同時に宣言</a></li> <li class="numbered visible"><a href="variable/index.html#id-bdb4879c8865cab8f31f2e02bedfab64275778af"><span class="number">4.3.</span>いきなり変数名</a></li> <li class="numbered visible"><a href="variable/index.html#id-94a94a68c07cac95e9dad0fb1b2cc0ac0080a74d"><span class="number">4.4.</span>まとめ</a></li> <li class="numbered visible"><a href="variable/index.html#other-memo"><span class="number">4.5.</span>Other memo</a></li> </ul> </li> <li class="numbered visible"> <a href="if/index.html" data-alt-hash="if"><span class="number">5.</span>if文</a> <ul> <li class="numbered visible"><a href="if/index.html#id-678b445de32757354dbd7b4d6d27a2679cb663a4"><span class="number">5.1.</span>普通のif</a></li> <li class="numbered visible"><a href="if/index.html#assert"><span class="number">5.2.</span>assert</a></li> <li class="numbered visible"><a href="if/index.html#id-b2368db87fc524b107821a7f97dc24e3c3fb7a3c"><span class="number">5.3.</span>三項演算子を使う</a></li> <li class="numbered visible"><a href="if/index.html#groovy-truth"><span class="number">5.4.</span>Groovy Truth</a></li> <li class="numbered visible"><a href="if/index.html#id-7f0ecf6d4f8badbce300a7cea1560cdc3eb80466"><span class="number">5.5.</span>エルビス演算子を使う</a></li> </ul> </li> <li class="numbered visible"> <a href="collection/list.html" data-alt-hash="id-b096d14061757613f9bb4fc3fdebeed1df3d7feb"><span class="number">6.</span>リスト</a> <ul> <li class="numbered visible"><a href="collection/list.html#collect"><span class="number">6.1.</span>collect</a></li> <li class="numbered visible"><a href="collection/list.html#inject"><span class="number">6.2.</span>inject</a></li> <li class="numbered visible"><a href="collection/list.html#find"><span class="number">6.3.</span>find</a></li> <li class="numbered visible"><a href="collection/list.html#findall"><span class="number">6.4.</span>findAll</a></li> <li class="numbered visible"><a href="collection/list.html#id-a3b0399fa150d0a6ed3d5fdb94debdbc965b43be"><span class="number">6.5.</span>まとめ</a></li> </ul> </li> <li class="numbered visible"> <a href="closure/index.html" data-alt-hash="id-bc9ded214e97abd0647bbea508cb878324996e3e"><span class="number">7.</span>クロージャ</a> <ul> <li class="numbered visible"><a href="closure/index.html#id-46071e2f627a54763ae382cb6ffc2b0b1e589013"><span class="number">7.1.</span>クロージャを使ってみる</a></li> <li class="numbered visible"><a href="closure/index.html#id-a6cf382c283896094fb20f51b389e9deec62dd3f"><span class="number">7.2.</span>さらに詳しく</a></li> <li class="numbered visible"><a href="closure/index.html#id-72c1711cd57bf25317237dd75f8c6d35545942dd"><span class="number">7.3.</span>関数合成</a></li> <li class="numbered visible"><a href="closure/index.html#thisownerdelegate"><span class="number">7.4.</span>特殊変数this、owner、delegate</a></li> <li class="numbered visible"><a href="closure/index.html#id-6578dcdcd86d65fc13e0e91b122bc41b2ba1ba08"><span class="number">7.5.</span>まとめ</a></li> </ul> </li> <li class="numbered visible"> <a href="collection/map.html" data-alt-hash="id-5408c1debd592f8b0779d2c9a302fbff89fb39ba"><span class="number">8.</span>マップ</a> <ul> <li class="numbered visible"><a href="collection/map.html#id-44e8571a56f022b3396fee07d6450bfd950e1a67"><span class="number">8.1.</span>繰り返し</a></li> <li class="numbered visible"><a href="collection/map.html#id-f8648999b740988e6ed27a5561760fe061ecb760"><span class="number">8.2.</span>リストとマップを組みあせる</a></li> </ul> </li> <li class="numbered visible"> <a href="null-safe/index.html" data-alt-hash="null"><span class="number">9.</span>Nullセーフ</a> <ul> <li class="numbered visible"><a href="null-safe/index.html#java8optional"><span class="number">9.1.</span>Java8のOptional</a></li> <li class="numbered visible"><a href="null-safe/index.html#groovy"><span class="number">9.2.</span>Groovyのセーフナビゲーション</a></li> <li class="numbered visible"><a href="null-safe/index.html#id-462a855457497e0f699b75d35950c57e31a0545b"><span class="number">9.3.</span>サンプルコード</a></li> <li class="numbered visible"><a href="null-safe/index.html#id-18aee802319ad5c16cd55c381c87b42226a4b149"><span class="number">9.4.</span>その他の方法</a></li> </ul> </li> <li class="numbered visible"> <a href="class/index.html" data-alt-hash="id-8b27332ee07f76ea4db44d6a7bdcdcf813427e3a"><span class="number">10.</span>クラス</a> <ul> <li class="numbered visible"><a href="class/index.html#2"><span class="number">10.1.</span>クラスは2つ以上定義しても良い</a></li> <li class="numbered visible"><a href="class/index.html#id-400faaa494727732c94af024c637e0d2129b72f9"><span class="number">10.2.</span>セッターとゲッター</a></li> </ul> </li> <li class="numbered visible"><a href="class/trait.html" data-alt-hash="trait"><span class="number">11.</span>Trait(トレイト)</a></li> <li class="numbered visible"> <a href="external-library/index.html" data-alt-hash="groovy"><span class="number">12.</span>Groovyで外部ライブラリを利用する</a> <ul> <li class="numbered visible"><a href="external-library/index.html#id-48131f790a0fdc19674de80e966b50d2d2954fa2"><span class="number">12.1.</span>実際に試してみよう</a></li> <li class="numbered visible"><a href="external-library/index.html#id-d3fd06b21472dc0e54bce2592d61eaa19369b573"><span class="number">12.2.</span>複数のライブラリを扱う</a></li> <li class="numbered visible"><a href="external-library/index.html#id-28df4375b1a38168d0fe528efd2d82fb65d313c0"><span class="number">12.3.</span>ちょっと補足</a></li> <li class="numbered visible"><a href="external-library/index.html#id-1ff68e378d712588bb7314663b7ec5f58e4ba62a"><span class="number">12.4.</span>まとめ</a></li> </ul> </li> <li class="numbered visible"> <a href="unit-test/index.html" data-alt-hash="id-24ac0411c687979683b211ecda6744d511f0ac85"><span class="number">13.</span>ユニットテスト</a> <ul> <li class="numbered visible"><a href="unit-test/index.html#spock"><span class="number">13.1.</span>初めてのSpock</a></li> <li class="numbered visible"> <a href="unit-test/index.html#id-be6ccbd026a73b061ec8e027551cad6733d3deb4"><span class="number">13.2.</span>フィーチャーメソッドとフィーチャーブロック</a> <ul> <li class="numbered visible"><a href="unit-test/index.html#whenthensetup"><span class="number">13.2.1.</span>whenとthen(そしてsetup)</a></li> <li class="numbered visible"><a href="unit-test/index.html#expect"><span class="number">13.2.2.</span>expect</a></li> <li class="numbered visible"><a href="unit-test/index.html#cleanup"><span class="number">13.2.3.</span>cleanup</a></li> <li class="numbered visible"> <a href="unit-test/index.html#where"><span class="number">13.2.4.</span>where</a> <ul> <li class="numbered invisible"><a href="unit-test/index.html#unroll"><span class="number">13.2.4.1.</span>@Unrollアノテーション</a></li> </ul> </li> </ul> </li> <li class="numbered visible"><a href="unit-test/index.html#id-bdd1a5a8c07a267571c3bd781ab9082669c5959f"><span class="number">13.3.</span>フィクスチャーメソッド</a></li> <li class="numbered visible"><a href="unit-test/index.html#id-b3c1ea2a3b540798f7cd793487a346fffeec9c09"><span class="number">13.4.</span>各フィーチャーメソッドで共通して利用する変数</a></li> <li class="numbered visible"><a href="unit-test/index.html#id-efba724c0eb52b004593236e37d0a25a1544ad6b"><span class="number">13.5.</span>実践</a></li> <li class="numbered visible"><a href="unit-test/index.html#bdd"><span class="number">13.6.</span>テストをより分かりやすくする(BDDスタイル)</a></li> <li class="numbered visible"><a href="unit-test/index.html#id-0a441a00637070d401d9e5a2653510c5967d9a05"><span class="number">13.7.</span>まとめ</a></li> </ul> </li> <li class="numbered visible"><a href="regular-expression/index.html" data-alt-hash="regular-expression"><span class="number">14.</span>Regular Expression</a></li> <li class="numbered visible"><a href="meta/index.html" data-alt-hash="meta-programming"><span class="number">15.</span>Meta programming</a></li> <li class="numbered visible"> <a href="static-groovy/index.html" data-alt-hash="groovy"><span class="number">16.</span>静的Groovy</a> <ul> <li class="numbered visible"><a href="static-groovy/index.html#id-b940591a92fde629fb71008c7b7e053237d7b8b4"><span class="number">16.1.</span>メソッド</a></li> <li class="numbered visible"> <a href="static-groovy/index.html#id-83dac9bdf0c71085ffa7a638a3bee37744fe1645"><span class="number">16.2.</span>ローカル変数</a> <ul> <li class="numbered visible"><a href="static-groovy/index.html#compilestatictypechecked"><span class="number">16.2.1.</span>CompileStaticとTypeChecked</a></li> </ul> </li> <li class="numbered visible"><a href="static-groovy/index.html#id-1ff68e378d712588bb7314663b7ec5f58e4ba62a"><span class="number">16.3.</span>まとめ</a></li> </ul> </li> <li class="numbered visible"> <a href="gpars/index.html" data-alt-hash="gpars"><span class="number">17.</span>GPars</a> <ul> <li class="numbered visible"><a href="gpars/actor.html" data-alt-hash="actor"><span class="number">17.1.</span>Actor</a></li> </ul> </li> <li class="numbered visible"> <a href="practice/index.html" data-alt-hash="id-0f8f1522a9609f45ebe45c4c425ad7a726b1bb7f"><span class="number">18.</span>実践/サンプル集</a> <ul> <li class="numbered visible"> <a href="practice/dataset-and-trait-orm.html" data-alt-hash="datasettraitorm"><span class="number">18.1.</span>DataSetとTraitを使って簡単なORM</a> <ul> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#id-76d4ffa3e7d72bf89f94b60af5f750d2d06dc1e8"><span class="number">18.1.1.</span>概要</a></li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#dataset"><span class="number">18.1.2.</span>DataSetのメモ</a></li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#id-7cb81475f86083b4ca6d8d3613d555118b576307"><span class="number">18.1.3.</span>本題</a></li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#trait"><span class="number">18.1.4.</span>traitと値を保持するクラスの作成</a></li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#id-72165400ede0a770ea8388c83d7b6583d826ac00"><span class="number">18.1.5.</span>実際に使ってみる</a></li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#id-3579f9fc20f87289e5d0d884038577d96b81aa67"><span class="number">18.1.6.</span>まとめ</a></li> </ul> </li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#id-a1880f698b418cb966ee0aa6196f852a004c403d"><span class="number">18.2.</span>参考</a></li> <li class="numbered visible"><a href="practice/dataset-and-trait-orm.html#id-595f48397a467a332eb14dcea74660ae4fdd653a"><span class="number">18.3.</span>全体ソース</a></li> <li class="numbered visible"><a href="practice/convert-decimal.html" data-alt-hash="102"><span class="number">18.4.</span>10進数を2進数に変換する</a></li> <li class="numbered visible"><a href="practice/samples-link.html" data-alt-hash="id-0d3bb1d122715fe5433159eb6ea50caa02c25184"><span class="number">18.5.</span>サンプルリンク集</a></li> <li class="numbered visible"><a href="practice/cli-tool.html" data-alt-hash="cli"><span class="number">18.6.</span>CLIツールの実装</a></li> </ul> </li> </ul> </div> <div class="content"> <div class="content-handle"></div> <div class="content-container"> <div class="content-nav content-nav-top"> <a class="prev-page" href="index.html"> <i class="fa fa-angle-left"></i> <span class="number">1.</span> index </a> <a class="next-page" href="startup/index.html"> <span class="number">3.</span> Startup <i class="fa fa-angle-right"></i> </a> </div> <div class="page-toc"> <ul> <li class="numbered visible"> <a href="#apache-groovy"><span class="number">2.</span>Apache Groovyとは</a> <ul> <li class="numbered visible"><a href="#id-fcad98b6bc96cf66e20f986f0973d2575fce430b"><span class="number">2.1.</span>シンプル&amp;パワフル</a></li> <li class="numbered visible"><a href="#id-f9356a26c4c26110d0fb85dbe07c07c28751e391"><span class="number">2.2.</span>巨大なエコシステム</a></li> <li class="numbered visible"><a href="#id-5f52ad0dbb814a0559eb8aa4b4a645c74bbedd8d"><span class="number">2.3.</span>気軽に実行</a></li> <li class="numbered visible"><a href="#id-6f37a8477bcb751f15dedcbcc9ee8a9cc90ef061"><span class="number">2.4.</span>実験コードのお供に</a></li> <li class="numbered visible"><a href="#id-ef4e0df42b47b23ce15bc3ccadd1d8d8e43f8385"><span class="number">2.5.</span>ビルドツール要らず</a></li> <li class="numbered visible"><a href="#java"><span class="number">2.6.</span>Javaの友達</a></li> <li class="numbered visible"><a href="#id-319e80ab91fa4b24ead46ec990e7890d8a62c899"><span class="number">2.7.</span>もちろんプロダクトとしても</a></li> <li class="numbered visible"><a href="#ok"><span class="number">2.8.</span>どこからでもOK</a></li> </ul> </li> </ul> </div> <div class="main-content"> <h1 id="apache-groovy"><span class="number">2.</span>Apache Groovyとは</h1> <p><a href="http://www.groovy-lang.org/">Apache Groovy</a>(以下Groovy)とは、現在 Apacheソフトウェアファウンデーション配下で開発が進められている <strong>動的型付け言語</strong> です。<br/>厳密な定義すると色々語弊があるかもしれませんが、 <strong>Groovyはいわゆるスクリプト言語です。</strong></p> <p>GroovyはJava Virtual Machine(以下JVM)上で動作します。<br/>なお、JVM上で動くJava以外のプログラミング言語には他にも色々なものが有ります。<br/>代表的なものとしては<a href="http://www.scala-lang.org/">Scala</a>や<a href="https://kotlinlang.org/">Kotlin</a>があります。<br/>この2つのプログラミング言語は、いわゆる <strong>静的型付け言語</strong> に属し、Groovyとは少し毛色が違います。<br/>そういう意味では、Groovyは同じJVM上で動くLISP方言の<a href="https://clojure.org/">Clojure</a>の方に近いかもしれません。 </p> <p>なお、Groovyの立ち位置としては、 <strong>Javaを置き換えるものではなく、Javaに寄り添うもの</strong> とよく表現されます。<br/>基本的にGroovyはJavaのコードをコピペすればそのままGroovyとして動作します。<br/><code>HelloWorld.java</code>をの拡張子を.groovyに変えて<code>HelloWorld.groovy</code>とするだけでOKなのです。<br/>このことから以下にGroovyがJavaとの親和性を大切にしているかが伺えます。 </p> <h2 id="id-fcad98b6bc96cf66e20f986f0973d2575fce430b"><span class="number">2.1.</span>シンプル&amp;パワフル</h2> <p>GroovyはJavaの良い点を踏襲しつつ、スクリプト言語らしく非常にシンプルにコーディングできるようになっています。<br/>さらに、関数型プログラミングのエッセンスも取り入れてコードをより簡潔に表現することも出来ます。 </p> <p>例えば、1から10の整数の入ったリストから偶数のみ抜き出して、それぞれを2倍して、全ての数をかけあわせる、という処理を実装してみます。</p> <pre><code class="groovy">(1..10).findAll { it % 2 == 0 }.collect { it * 2 }.inject {l, r -&gt; l * r } </code></pre> <p>非常に簡潔ですね!<br/>forの様なループやifによる条件分岐、さらに途中の計算結果を代入する一時変数すら登場しません。<br/>そしてGroovyはセミコロンと、明示的なreturnは不要です。<br/>また、型の指定も省略することが可能です。 </p> <p>Groovyではクロージャー(Closure)が簡単に利用できます。<br/>クロージャーを利用することで、Java8から導入されたStreamやLambdaと同じような事を、より簡潔に表現することが出来ます。<br/>例えば、クロージャーを利用して数学のシグマ(Σ)を実装してみます。</p> <pre><code class="groovy">def sigma = {Integer k, Integer to, Closure exp -&gt; (k..to).collect { exp(it) }.sum() } assert 25 == sigma(1, 5) {it + 2} </code></pre> <p>これまた簡潔ですね。<br/>すでにGroovyでは型を省略できると書きましたが、逆に型を明示することも当然可能です。</p> <h2 id="id-f9356a26c4c26110d0fb85dbe07c07c28751e391"><span class="number">2.2.</span>巨大なエコシステム</h2> <p>Groovyにはすでに10年以上の歴史が有り、Groovyの為の様々なツールが有ります。<br/>そして、JVMの上で動く様々なJava用ライブラリを利用することも可能です。<br/>あなたがJava用ライブラリを使ったことがあるのであれば、そのライブラリはGroovyからも利用できる上に、Groovyのシンプル&パワフルなシンタックスを利用することでよりお洒落に記述することができます。</p> <p>また、Groovyでよく利用されるある程度規模の大きなフレームワークなどには以下のようなものが有ります。</p> <ul> <li>フルスタックなWEBフレームワーク「<a href="https://grails.org/">Grails</a>」</li> <li>ノンブロッキングでシンプルなマイクロフレームワーク「<a href="https://ratpack.io/">Ratpack</a>」</li> <li>平行/並列処理を簡単に実現できる「<a href="http://www.gpars.org/">GPars</a>」</li> <li>BDDなユニットテストフレームワーク「<a href="https://github.com/spockframework/spock">Spock</a>」</li> <li>ブラウザからの機能テストをシンプルに実装できる「<a href="http://www.gebish.org/">Geb</a>」</li> <li>ビルドツール「<a href="http://gradle.org/">Gradle</a>」</li> </ul> <p><strong>GroovyはJavaのエコシステムに直接リーチするだけでなく、そのエコシステム自体の一員となり、さらにそのエコシステムを押し広げるものです。</strong><br/><a href="http://koji-k.github.io/ratpack-tutorial/">Ratpackの入門、チュトーリアルも公開しています!</a>コチラも順次内容を補填していきます。</p> <h2 id="id-5f52ad0dbb814a0559eb8aa4b4a645c74bbedd8d"><span class="number">2.3.</span>気軽に実行</h2> <p>さて、巨大なエコシステムとかライブラリとかっていう話を聞くと「何か難しそう。実行するの面倒くさそう」と思っちゃいますね。<br/>いえいえ。Groovyはそんなことありません! Groovyには、最近のモダンな言語にはよくある <strong>REPL</strong> も付属しています。<br/>Groovyをインストールしたらコンソールで<code>groovysh</code>と入力するだけでREPLが起動します。<br/>REPLを利用することで手軽に、即座にコードを確認することが出来ます。 </p> <pre><code class="terminal">[saba:~]$ groovysh Groovy Shell (2.3.11, JVM: 1.8.0_60) Type &#39;:help&#39; or &#39;:h&#39; for help. ------------------------------ groovy:000&gt; a = &quot;Hello&quot; ===&gt; Hello groovy:000&gt; println a Hello ===&gt; null groovy:000&gt; 2 * 4 ===&gt; 8 groovy:000&gt; (1..5).inject {a,b -&gt; a * b} ===&gt; 120 groovy:000&gt; </code></pre> <p>さて、この諸々のモダンな言語にも備わっている便利なREPLですが、Groovyに限らずScalaやClojureでも、REPLでちょっと長い関数などを書いて実行するとシンタックスエラーと言われてもう一回書く羽目になってイライラ。。。という経験は誰にだって有ります(よね?)<br/>そこでGroovyには <strong>GroovyConsole</strong> という、簡易的な統合開発環境まで備わっています。<br/>WindowsならGroovyのインストールディレクトリに、LinuxやMacはコンソールから <code>groovyConsole &amp;</code>と入力することで利用することが出来ます。<br/>あくまで簡易的な統合開発環境なので、コードの補完やデバッガなどは付属していません(が、クラスパスを追加したりなどの痒いところに手が届く機能搭載!)<br/><img src="images/groovyconsole1.png" alt="GroovyConsole" title="GroovyConsole"/><br/>しかし、この<code>GroovyConsole</code>の最大の特徴は、すでに起動したJVM上でコードが走るので、 <strong>プログラムの実行がJVM系言語とは思えないほど高速だということです。</strong><br/>さらに、同じ画面上にコードの実行結果が表示されるので、結果を確認しつつコードを修正して、即座に再実行することが出来るため、非常に効率よくコーディングできます。 </p> <p>このように、GroovyにはREPL(groovysh)とGroovyConsoleという強力な開発サポートツールが付属しています。<br/>この2つを利用することで、Groovy自体の勉強はもちろん、ロジックの確認、検証コードの作成、さらには業務をサポートするためのツールとしても利用することが出来ます。<br/><strong>なによりサクサクコーディグ&実行が出来るので、プログラミング自体がとても楽しくなります!</strong></p> <h2 id="id-6f37a8477bcb751f15dedcbcc9ee8a9cc90ef061"><span class="number">2.4.</span>実験コードのお供に</h2> <p>開発をしていて、ある機能が必要になり、あるアルゴリズム/ロジックをコードを書きながら試行錯誤したい、ということはよく有りますよね?<br/>Groovyは標準で様々な便利機能が用意されています。<br/>例えば、言語機能として<code>assert</code>(パワーアサート)が有ります。<br/>コレは、そのような実験コード(例えばどんなアルゴリズムにしようかを決める際に色々書くコード)に非常に便利です。 </p> <p>実際にサンプルを見てみましょう。</p> <pre><code class="groovy">class SomeClass { def someMethod() { &quot;Groovy&quot; } } def someClass = new SomeClass() assert &quot;groovy&quot; == someClass.someMethod() </code></pre> <p>最後の行がパワーアサートの部分です。<br/>この例だとsomeMethodの戻り値は先頭が大文字なのに、意図した結果は先頭小文字なので、当然エラーになります。<br/>エラーなお内容は非常に分かりやすく表示されます。 </p> <pre><code class="terminal">Assertion failed: assert &quot;groovy&quot; == someClass.someMethod() | | | | | Groovy | SomeClass@3e633f10 false at ConsoleScript6.run(ConsoleScript6:8) </code></pre> <p>こうすることで、メソッドの中身の実装を変えた際に、毎回目で実行結果に誤りが無いか、挙動が変わっていないかの確認が必要が無くなります。<br/>さらに、GroovyConsoleやGroovyshと言ったGroovyに備わっているツールを使えば、態々IDEやテキストエディタを開く事無くコードを試すことが出来ます。<br/>(GroovyConsoleはGUIツール、groovyshはCUIツール。いわゆるREPL)</p> <h2 id="id-ef4e0df42b47b23ce15bc3ccadd1d8d8e43f8385"><span class="number">2.5.</span>ビルドツール要らず</h2> <p>さて、では少し「実験コード」の範囲を広げましょう。<br/>例えばあなたが参加しているJavaプロジェクトであるJavaライブラリを導入することになったとします。<br/>そのライブラリの使い方をチェックするために態々山のようなクラスファイルを作る必要も、その外部ライブラリをクラスパスにと通す必要も、既存のプロジェクトコードを汚す必要もありません。<br/>さらにGradleやMavenといったビルドツールを導入したり、そもそもその対象ライブラリをダウンロードしてくる必要さえ無いのです。<br/>Groovyは言語機能として、 <strong>Grab</strong> という機能が有ります。このGrabに必要なライブラリの情報(Mavenに記述する様な情報)を渡してあげるだけで、ダウンロードからクラスパスの設定まで全てGroovyが自動で行ってくれます。<br/>例えば、ココではJsoupというJavaのWEBスクレイピングによく利用されるライブラリを導入してみましょう。</p> <pre><code class="groovy">@Grab(group=&#39;org.jsoup&#39;, module=&#39;jsoup&#39;, version=&#39;1.8.3&#39;) import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.select.Elements Document document = Jsoup.connect(&quot;http://koji-k.github.io/groovy-tutorial/index.html&quot;).get() document.select(&quot;a&quot;).collect {Element element -&gt; &quot;[${element.text()}](${element.attr(&quot;href&quot;)})&quot; }.each { println it } </code></pre> <p>これだけです。必要なのは上記のGroovyコードだけです。後は全てGroovyが面倒を見てくれます。<br/>当然ある程度規模の大きなアプリケーションになってくるとGradleやMavenを利用したほうが良いですが、Groovyではこのように日々のちょっとした業務をサポートしてくれる強力な機能が非常に多く備わっています。 </p> <p>(Grabの詳細は本チュートリアルの <a href="external-library/index.html">Groovyで外部ライブラリを利用する</a> を参照してください。)</p> <h2 id="java"><span class="number">2.6.</span>Javaの友達</h2> <p>すでに述べたとおり、Javaコードは基本的にそのままGroovyとして動作します。<br/>さらにGroovyの場合は1ファイルに1クラス、というルールがありません。つまり1ファイルにいくつもクラスを宣言することが出来ます。<br/>そしてクラスの宣言自体必要ありません。</p> <pre><code class="groovy">class A { def hoge() { println &quot;A&quot; } } class B { def hoge() { println &quot;B&quot; } } def a = new A() def b = new B() a.hoge() b.hoge() </code></pre> <p>このコードは1ファイルに詰め込んでもちゃんと動作します。<br/>このように、余計な事を考えずに必要なことに集中することができるのでこれからJavaを学習したい、というひともGroovyからJavaを効率よく勉強することが出来ます。<br/>そしてとても重要なことですが、JavaのAPIが利用できる知識があるのであれば、 <strong>あなたはすでにGroovyエンジニアです!</strong><br/>そこに少しだけ本チュートリアルの知識をプラスαするだけで、 <strong>最小の苦労で非常に多くのモダンな機能、そして知識を得ることが出来ます。</strong><br/><strong>Groovyはいつだって、あなたとJavaに寄り添う友達です。</strong></p> <h2 id="id-319e80ab91fa4b24ead46ec990e7890d8a62c899"><span class="number">2.7.</span>もちろんプロダクトとしても</h2> <p>Groovyは、2016年の時点で登場からすでに13年が経っています。<br/>Javaの知識をそのままGroovyで利用できるので、学習コストはほぼゼロです。<br/>スクリプト言語とは言え、実行時にはすでにclassファイルにコンパイルされているので、開発、デプロイ、運用というイテレーションもJavaの知識をそのまま流用できます。<br/>つまり、Groovyにはすでに実戦で利用できる十分な実績、ライブラリが備わっているということです!</p> <h2 id="ok"><span class="number">2.8.</span>どこからでもOK</h2> <p>JVMという実績のある環境の上で動作し、膨大なJavaのエコシステムを利用でき、シンプルで実用的な機能を抱負に揃えたGroovy。<br/>さらにコレクションを変換して、集約していき、可能な限り副作用を減らすという関数型プログラミングのエッセンスも含まれています。<br/>また、直ぐにプロダクトとして導入しなくても、ちょっとしたデータの作成用や、簡単なバッチファイルとしての利用などにも利用できます。<br/>JavaのコードがそのままGroovyとして動作するので、まずはJavaシンタックスで書いておいて、あとからGroovyのシンタックスに少しずつ変えていくということも可能です。<br/>Groovyは常に現実的な業務に寄り添ってくれます。あなたの必要だと思える場所、タイミングで、いつでも使いはじめることが出来る相棒です。 </p> <p><strong>さぁ、Groovyを初めましょう!</strong></p> </div> <div class="content-nav content-nav-bottom"> <a class="prev-page" href="index.html"> <i class="fa fa-angle-left"></i> <span class="number">1.</span> index </a> <a class="next-page" href="startup/index.html"> <span class="number">3.</span> Startup <i class="fa fa-angle-right"></i> </a> </div> <div class="footer"> <p class="credit text-muted">Powered by <a href="https://github.com/kobo/gaiden">Gaiden</a></p> </div> </div> </div> </div> <script src="js/jquery-2.1.1.min.js"></script> <script src="js/highlight.js"></script> <script src="js/application.js"></script> <script src="js/my.js"></script> </body> </html>
kojix2/groovy-tutorial
<|start_filename|>vendor/github.com/palantir/goastwriter/decl/var.go<|end_filename|> // Copyright 2017 <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package decl import ( "go/ast" "go/token" "github.com/palantir/goastwriter/astgen" "github.com/palantir/goastwriter/expression" "github.com/palantir/goastwriter/spec" ) type Var struct { Name string Type expression.Type Value astgen.ASTExpr } func NewVar(name string, typ expression.Type) *Var { return &Var{ Name: name, Type: typ, } } func (v *Var) ASTDecl() ast.Decl { valueSpec := &ast.ValueSpec{ Names: []*ast.Ident{ast.NewIdent(v.Name)}, } if v.Type != "" { valueSpec.Type = v.Type.ToIdent() } if v.Value != nil { valueSpec.Values = []ast.Expr{v.Value.ASTExpr()} } return &ast.GenDecl{ Tok: token.VAR, Specs: []ast.Spec{valueSpec}, } } type Vars struct { Values []*spec.Value } func (c *Vars) ASTDecl() ast.Decl { var specs []ast.Spec for _, val := range c.Values { specs = append(specs, val.ASTSpec()) } varDecl := &ast.GenDecl{ Tok: token.VAR, Specs: specs, } if len(specs) > 1 { // set Lparen to non-0 value to ensure that parenthesis are rendered varDecl.Lparen = token.Pos(1) } return varDecl }
smoorpal/godel-conjure-plugin
<|start_filename|>src/app/customizable-demo-form.component.css<|end_filename|> @import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500'); body { font-family: 'Roboto', sans-serif; } #jsonPanel { margin-top: 20px; } .colorPicker { display: inline-block; width: 40px; /* border: 1px solid; */ cursor: pointer; } .feedbackText { width: 400px; margin-right: 10px; } .divider { margin-top: 20px; margin-bottom: 20px; } .slider { width: 500px; } .sliderCaption { font-size: 14px; margin-bottom: 10px; } .customizeSwitch { display: inline-block; margin-top: 10px; margin-bottom: 10px; margin-left: 20px; } .customizeSwitch.sliderCustomizeSwitch { display: block; margin-left: 0; } mat-form-field { width: 400px; } .setting { display: block; margin-bottom: 20px; } .customizableSetting { background-color: #FAFAFA; padding: 20px; margin-left: 20px; margin-bottom: 30px; } .disabled { color: #BDBDBD; } <|start_filename|>config/server_config.template.json<|end_filename|> { "port": "8080", "staticPath": "build/static", "googleCloudApiKey": "enter your API key here", "toxicityAttribute": "TOXICITY", "cloudProjectId": "enter your cloud project id here" } <|start_filename|>src/styles.css<|end_filename|> /* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @import "~@angular/material/prebuilt-themes/indigo-pink.css"; body { background: #CCC; font-family: Roboto, sans-serif; } /** * Used for injected HTML img tags from the twemoji library. This style has to * be global because view encapsulation prevents this from working when defined * in component-specific CSS files. * * TODO(rachelrosen): Consider other options. */ .emoji { width: 16px; height: 16px; padding-left: 4px; padding-right: 4px; } .demoContainer { margin-left:auto; margin-right:auto; left:auto; background: #FFF; width: 100%; max-width: 800px; } .titleContainer { padding: 20px; } .demoTitle { color: rgba(0, 0, 0, .87); font-size: 20px; padding-bottom: 10px; } .demoSubtitle { color: rgba(0, 0, 0, .56); font-size: 14px; line-height: 24px; margin-bottom: 20px; } .divider { border-top: 2px solid #000000; height: 0px; margin: 0px; margin-left: 10px; margin-right: 20px; opacity: 0.1; } .checkerContainer { justify-content: center; margin-top: 10px; padding: 20px; } .checkerInputBox { margin-top: 10px; resize: none; border: none; width: 100%; font-size: 20px; color: rgba(0, 0, 0, .87); line-height: 36px; } .checkerInputBox:focus { outline: none; } .checkerInputTitle { font-size: 14px; color: rgba(0, 0, 0, .87); } <|start_filename|>ng-package.json<|end_filename|> { "$schema": "./node_modules/ng-packagr/ng-package.schema.json", "whitelistedNonPeerDependencies": ["."], "lib": { "entryFile": "public_api.ts", "umdModuleIds": { "lodash" : "_", "d3-interpolate": "d3", "toxiclibsjs": "toxicLibsJS", "twemoji": "twemoji", "gsap": "gsap", "rxjs" : "rxjs" } } }
heyawhite/perspectiveapi-authorship-demo
<|start_filename|>internal/kernel/version.generated.go<|end_filename|> package kernel const version = "1.41.0"
aws/jsii-runtime-go
<|start_filename|>photopicker/src/main/java/com/github/basshelal/unsplashpicker/presentation/OnPhotoSelectedListener.kt<|end_filename|> package com.github.basshelal.unsplashpicker.presentation import android.widget.ImageView import com.github.basshelal.unsplashpicker.data.UnsplashPhoto internal interface OnPhotoSelectedListener { fun onClickPhoto(photo: UnsplashPhoto, imageView: ImageView) fun onLongClickPhoto(photo: UnsplashPhoto, imageView: ImageView) }
codacy-badger/UnsplashPhotoPicker